In Windows/Gtk front-ends, consistently use the ellipsis convention for naming
[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 #include <stdio.h>
12 #include <assert.h>
13 #include <ctype.h>
14 #include <stdarg.h>
15 #include <stdlib.h>
16 #include <limits.h>
17 #include <time.h>
18
19 #include "puzzles.h"
20
21 #define IDM_NEW 0x0010
22 #define IDM_RESTART 0x0020
23 #define IDM_UNDO 0x0030
24 #define IDM_REDO 0x0040
25 #define IDM_COPY 0x0050
26 #define IDM_SOLVE 0x0060
27 #define IDM_QUIT 0x0070
28 #define IDM_CONFIG 0x0080
29 #define IDM_DESC 0x0090
30 #define IDM_SEED 0x00A0
31 #define IDM_HELPC 0x00B0
32 #define IDM_GAMEHELP 0x00C0
33 #define IDM_ABOUT 0x00D0
34 #define IDM_SAVE 0x00E0
35 #define IDM_LOAD 0x00F0
36 #define IDM_PRINT 0x0100
37 #define IDM_PRESETS 0x0110
38
39 #define HELP_FILE_NAME "puzzles.hlp"
40 #define HELP_CNT_NAME "puzzles.cnt"
41 #ifndef NO_HTMLHELP
42 #define CHM_FILE_NAME "puzzles.chm"
43 #endif /* NO_HTMLHELP */
44
45 #ifndef NO_HTMLHELP
46 typedef HWND (CALLBACK *htmlhelp_t)(HWND, LPCSTR, UINT, DWORD);
47 static DWORD html_help_cookie;
48 static htmlhelp_t htmlhelp;
49 static HINSTANCE hh_dll;
50 #endif /* NO_HTMLHELP */
51 enum { NONE, HLP, CHM } help_type;
52 char *help_path;
53 const char *help_topic;
54 int help_has_contents;
55
56 #ifdef DEBUGGING
57 static FILE *debug_fp = NULL;
58 static HANDLE debug_hdl = INVALID_HANDLE_VALUE;
59 static int debug_got_console = 0;
60
61 void dputs(char *buf)
62 {
63 DWORD dw;
64
65 if (!debug_got_console) {
66 if (AllocConsole()) {
67 debug_got_console = 1;
68 debug_hdl = GetStdHandle(STD_OUTPUT_HANDLE);
69 }
70 }
71 if (!debug_fp) {
72 debug_fp = fopen("debug.log", "w");
73 }
74
75 if (debug_hdl != INVALID_HANDLE_VALUE) {
76 WriteFile(debug_hdl, buf, strlen(buf), &dw, NULL);
77 }
78 fputs(buf, debug_fp);
79 fflush(debug_fp);
80 }
81
82 void debug_printf(char *fmt, ...)
83 {
84 char buf[4096];
85 va_list ap;
86
87 va_start(ap, fmt);
88 vsprintf(buf, fmt, ap);
89 dputs(buf);
90 va_end(ap);
91 }
92 #endif
93
94 #define WINFLAGS (WS_OVERLAPPEDWINDOW &~ \
95 (WS_THICKFRAME | WS_MAXIMIZEBOX | WS_OVERLAPPED))
96
97 static void new_game_size(frontend *fe);
98
99 struct font {
100 HFONT font;
101 int type;
102 int size;
103 };
104
105 struct cfg_aux {
106 int ctlid;
107 };
108
109 struct blitter {
110 HBITMAP bitmap;
111 frontend *fe;
112 int x, y, w, h;
113 };
114
115 enum { CFG_PRINT = CFG_FRONTEND_SPECIFIC };
116
117 struct frontend {
118 midend *me;
119 HWND hwnd, statusbar, cfgbox;
120 HINSTANCE inst;
121 HBITMAP bitmap, prevbm;
122 HDC hdc;
123 COLORREF *colours;
124 HBRUSH *brushes;
125 HPEN *pens;
126 HRGN clip;
127 UINT timer;
128 DWORD timer_last_tickcount;
129 int npresets;
130 game_params **presets;
131 struct font *fonts;
132 int nfonts, fontsize;
133 config_item *cfg;
134 struct cfg_aux *cfgaux;
135 int cfg_which, dlg_done;
136 HFONT cfgfont;
137 HBRUSH oldbr;
138 HPEN oldpen;
139 int help_running;
140 enum { DRAWING, PRINTING, NOTHING } drawstatus;
141 DOCINFO di;
142 int printcount, printw, printh, printsolns, printcurr, printcolour;
143 float printscale;
144 int printoffsetx, printoffsety;
145 float printpixelscale;
146 int fontstart;
147 int linewidth;
148 drawing *dr;
149 };
150
151 void fatal(char *fmt, ...)
152 {
153 char buf[2048];
154 va_list ap;
155
156 va_start(ap, fmt);
157 vsprintf(buf, fmt, ap);
158 va_end(ap);
159
160 MessageBox(NULL, buf, "Fatal error", MB_ICONEXCLAMATION | MB_OK);
161
162 exit(1);
163 }
164
165 char *geterrstr(void)
166 {
167 LPVOID lpMsgBuf;
168 DWORD dw = GetLastError();
169 char *ret;
170
171 FormatMessage(
172 FORMAT_MESSAGE_ALLOCATE_BUFFER |
173 FORMAT_MESSAGE_FROM_SYSTEM,
174 NULL,
175 dw,
176 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
177 (LPTSTR) &lpMsgBuf,
178 0, NULL );
179
180 ret = dupstr(lpMsgBuf);
181
182 LocalFree(lpMsgBuf);
183
184 return ret;
185 }
186
187 void get_random_seed(void **randseed, int *randseedsize)
188 {
189 time_t *tp = snew(time_t);
190 time(tp);
191 *randseed = (void *)tp;
192 *randseedsize = sizeof(time_t);
193 }
194
195 static void win_status_bar(void *handle, char *text)
196 {
197 frontend *fe = (frontend *)handle;
198
199 SetWindowText(fe->statusbar, text);
200 }
201
202 static blitter *win_blitter_new(void *handle, int w, int h)
203 {
204 blitter *bl = snew(blitter);
205
206 memset(bl, 0, sizeof(blitter));
207 bl->w = w;
208 bl->h = h;
209 bl->bitmap = 0;
210
211 return bl;
212 }
213
214 static void win_blitter_free(void *handle, blitter *bl)
215 {
216 if (bl->bitmap) DeleteObject(bl->bitmap);
217 sfree(bl);
218 }
219
220 static void blitter_mkbitmap(frontend *fe, blitter *bl)
221 {
222 HDC hdc = GetDC(fe->hwnd);
223 bl->bitmap = CreateCompatibleBitmap(hdc, bl->w, bl->h);
224 ReleaseDC(fe->hwnd, hdc);
225 }
226
227 /* BitBlt(dstDC, dstX, dstY, dstW, dstH, srcDC, srcX, srcY, dType) */
228
229 static void win_blitter_save(void *handle, blitter *bl, int x, int y)
230 {
231 frontend *fe = (frontend *)handle;
232 HDC hdc_win, hdc_blit;
233 HBITMAP prev_blit;
234
235 assert(fe->drawstatus == DRAWING);
236
237 if (!bl->bitmap) blitter_mkbitmap(fe, bl);
238
239 bl->x = x; bl->y = y;
240
241 hdc_win = GetDC(fe->hwnd);
242 hdc_blit = CreateCompatibleDC(hdc_win);
243 if (!hdc_blit) fatal("hdc_blit failed: 0x%x", GetLastError());
244
245 prev_blit = SelectObject(hdc_blit, bl->bitmap);
246 if (prev_blit == NULL || prev_blit == HGDI_ERROR)
247 fatal("SelectObject for hdc_main failed: 0x%x", GetLastError());
248
249 if (!BitBlt(hdc_blit, 0, 0, bl->w, bl->h,
250 fe->hdc, x, y, SRCCOPY))
251 fatal("BitBlt failed: 0x%x", GetLastError());
252
253 SelectObject(hdc_blit, prev_blit);
254 DeleteDC(hdc_blit);
255 ReleaseDC(fe->hwnd, hdc_win);
256 }
257
258 static void win_blitter_load(void *handle, blitter *bl, int x, int y)
259 {
260 frontend *fe = (frontend *)handle;
261 HDC hdc_win, hdc_blit;
262 HBITMAP prev_blit;
263
264 assert(fe->drawstatus == DRAWING);
265
266 assert(bl->bitmap); /* we should always have saved before loading */
267
268 if (x == BLITTER_FROMSAVED) x = bl->x;
269 if (y == BLITTER_FROMSAVED) y = bl->y;
270
271 hdc_win = GetDC(fe->hwnd);
272 hdc_blit = CreateCompatibleDC(hdc_win);
273
274 prev_blit = SelectObject(hdc_blit, bl->bitmap);
275
276 BitBlt(fe->hdc, x, y, bl->w, bl->h,
277 hdc_blit, 0, 0, SRCCOPY);
278
279 SelectObject(hdc_blit, prev_blit);
280 DeleteDC(hdc_blit);
281 ReleaseDC(fe->hwnd, hdc_win);
282 }
283
284 void frontend_default_colour(frontend *fe, float *output)
285 {
286 DWORD c = GetSysColor(COLOR_MENU); /* ick */
287
288 output[0] = (float)(GetRValue(c) / 255.0);
289 output[1] = (float)(GetGValue(c) / 255.0);
290 output[2] = (float)(GetBValue(c) / 255.0);
291 }
292
293 static POINT win_transform_point(frontend *fe, int x, int y)
294 {
295 POINT ret;
296
297 assert(fe->drawstatus != NOTHING);
298
299 if (fe->drawstatus == PRINTING) {
300 ret.x = (int)(fe->printoffsetx + fe->printpixelscale * x);
301 ret.y = (int)(fe->printoffsety + fe->printpixelscale * y);
302 } else {
303 ret.x = x;
304 ret.y = y;
305 }
306
307 return ret;
308 }
309
310 static void win_text_colour(frontend *fe, int colour)
311 {
312 assert(fe->drawstatus != NOTHING);
313
314 if (fe->drawstatus == PRINTING) {
315 int hatch;
316 float r, g, b;
317 print_get_colour(fe->dr, colour, &hatch, &r, &g, &b);
318 if (fe->printcolour)
319 SetTextColor(fe->hdc, RGB(r * 255, g * 255, b * 255));
320 else
321 SetTextColor(fe->hdc,
322 hatch == HATCH_CLEAR ? RGB(255,255,255) : RGB(0,0,0));
323 } else {
324 SetTextColor(fe->hdc, fe->colours[colour]);
325 }
326 }
327
328 static void win_set_brush(frontend *fe, int colour)
329 {
330 HBRUSH br;
331 assert(fe->drawstatus != NOTHING);
332
333 if (fe->drawstatus == PRINTING) {
334 int hatch;
335 float r, g, b;
336 print_get_colour(fe->dr, colour, &hatch, &r, &g, &b);
337
338 if (fe->printcolour)
339 br = CreateSolidBrush(RGB(r * 255, g * 255, b * 255));
340 else if (hatch == HATCH_SOLID)
341 br = CreateSolidBrush(RGB(0,0,0));
342 else if (hatch == HATCH_CLEAR)
343 br = CreateSolidBrush(RGB(255,255,255));
344 else
345 br = CreateHatchBrush(hatch == HATCH_BACKSLASH ? HS_FDIAGONAL :
346 hatch == HATCH_SLASH ? HS_BDIAGONAL :
347 hatch == HATCH_HORIZ ? HS_HORIZONTAL :
348 hatch == HATCH_VERT ? HS_VERTICAL :
349 hatch == HATCH_PLUS ? HS_CROSS :
350 /* hatch == HATCH_X ? */ HS_DIAGCROSS,
351 RGB(0,0,0));
352 } else {
353 br = fe->brushes[colour];
354 }
355 fe->oldbr = SelectObject(fe->hdc, br);
356 }
357
358 static void win_reset_brush(frontend *fe)
359 {
360 HBRUSH br;
361
362 assert(fe->drawstatus != NOTHING);
363
364 br = SelectObject(fe->hdc, fe->oldbr);
365 if (fe->drawstatus == PRINTING)
366 DeleteObject(br);
367 }
368
369 static void win_set_pen(frontend *fe, int colour, int thin)
370 {
371 HPEN pen;
372 assert(fe->drawstatus != NOTHING);
373
374 if (fe->drawstatus == PRINTING) {
375 int hatch;
376 float r, g, b;
377 int width = thin ? 0 : fe->linewidth;
378
379 print_get_colour(fe->dr, colour, &hatch, &r, &g, &b);
380 if (fe->printcolour)
381 pen = CreatePen(PS_SOLID, width,
382 RGB(r * 255, g * 255, b * 255));
383 else if (hatch == HATCH_SOLID)
384 pen = CreatePen(PS_SOLID, width, RGB(0, 0, 0));
385 else if (hatch == HATCH_CLEAR)
386 pen = CreatePen(PS_SOLID, width, RGB(255,255,255));
387 else {
388 assert(!"This shouldn't happen");
389 pen = CreatePen(PS_SOLID, 1, RGB(0, 0, 0));
390 }
391 } else {
392 pen = fe->pens[colour];
393 }
394 fe->oldpen = SelectObject(fe->hdc, pen);
395 }
396
397 static void win_reset_pen(frontend *fe)
398 {
399 HPEN pen;
400
401 assert(fe->drawstatus != NOTHING);
402
403 pen = SelectObject(fe->hdc, fe->oldpen);
404 if (fe->drawstatus == PRINTING)
405 DeleteObject(pen);
406 }
407
408 static void win_clip(void *handle, int x, int y, int w, int h)
409 {
410 frontend *fe = (frontend *)handle;
411 POINT p, q;
412
413 if (fe->drawstatus == NOTHING)
414 return;
415
416 p = win_transform_point(fe, x, y);
417 q = win_transform_point(fe, x+w, y+h);
418 IntersectClipRect(fe->hdc, p.x, p.y, q.x, q.y);
419 }
420
421 static void win_unclip(void *handle)
422 {
423 frontend *fe = (frontend *)handle;
424
425 if (fe->drawstatus == NOTHING)
426 return;
427
428 SelectClipRgn(fe->hdc, NULL);
429 }
430
431 static void win_draw_text(void *handle, int x, int y, int fonttype,
432 int fontsize, int align, int colour, char *text)
433 {
434 frontend *fe = (frontend *)handle;
435 POINT xy;
436 int i;
437
438 if (fe->drawstatus == NOTHING)
439 return;
440
441 if (fe->drawstatus == PRINTING)
442 fontsize = (int)(fontsize * fe->printpixelscale);
443
444 xy = win_transform_point(fe, x, y);
445
446 /*
447 * Find or create the font.
448 */
449 for (i = fe->fontstart; i < fe->nfonts; i++)
450 if (fe->fonts[i].type == fonttype && fe->fonts[i].size == fontsize)
451 break;
452
453 if (i == fe->nfonts) {
454 if (fe->fontsize <= fe->nfonts) {
455 fe->fontsize = fe->nfonts + 10;
456 fe->fonts = sresize(fe->fonts, fe->fontsize, struct font);
457 }
458
459 fe->nfonts++;
460
461 fe->fonts[i].type = fonttype;
462 fe->fonts[i].size = fontsize;
463
464 fe->fonts[i].font = CreateFont(-fontsize, 0, 0, 0,
465 fe->drawstatus == PRINTING ? 0 : FW_BOLD,
466 FALSE, FALSE, FALSE, DEFAULT_CHARSET,
467 OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS,
468 DEFAULT_QUALITY,
469 (fonttype == FONT_FIXED ?
470 FIXED_PITCH | FF_DONTCARE :
471 VARIABLE_PITCH | FF_SWISS),
472 NULL);
473 }
474
475 /*
476 * Position and draw the text.
477 */
478 {
479 HFONT oldfont;
480 TEXTMETRIC tm;
481 SIZE size;
482
483 oldfont = SelectObject(fe->hdc, fe->fonts[i].font);
484 if (GetTextMetrics(fe->hdc, &tm)) {
485 if (align & ALIGN_VCENTRE)
486 xy.y -= (tm.tmAscent+tm.tmDescent)/2;
487 else
488 xy.y -= tm.tmAscent;
489 }
490 if (GetTextExtentPoint32(fe->hdc, text, strlen(text), &size)) {
491 if (align & ALIGN_HCENTRE)
492 xy.x -= size.cx / 2;
493 else if (align & ALIGN_HRIGHT)
494 xy.x -= size.cx;
495 }
496 SetBkMode(fe->hdc, TRANSPARENT);
497 win_text_colour(fe, colour);
498 TextOut(fe->hdc, xy.x, xy.y, text, strlen(text));
499 SelectObject(fe->hdc, oldfont);
500 }
501 }
502
503 static void win_draw_rect(void *handle, int x, int y, int w, int h, int colour)
504 {
505 frontend *fe = (frontend *)handle;
506 POINT p, q;
507
508 if (fe->drawstatus == NOTHING)
509 return;
510
511 if (fe->drawstatus == DRAWING && w == 1 && h == 1) {
512 /*
513 * Rectangle() appears to get uppity if asked to draw a 1x1
514 * rectangle, presumably on the grounds that that's beneath
515 * its dignity and you ought to be using SetPixel instead.
516 * So I will.
517 */
518 SetPixel(fe->hdc, x, y, fe->colours[colour]);
519 } else {
520 win_set_brush(fe, colour);
521 win_set_pen(fe, colour, TRUE);
522 p = win_transform_point(fe, x, y);
523 q = win_transform_point(fe, x+w, y+h);
524 Rectangle(fe->hdc, p.x, p.y, q.x, q.y);
525 win_reset_brush(fe);
526 win_reset_pen(fe);
527 }
528 }
529
530 static void win_draw_line(void *handle, int x1, int y1, int x2, int y2, int colour)
531 {
532 frontend *fe = (frontend *)handle;
533 POINT p, q;
534
535 if (fe->drawstatus == NOTHING)
536 return;
537
538 win_set_pen(fe, colour, FALSE);
539 p = win_transform_point(fe, x1, y1);
540 q = win_transform_point(fe, x2, y2);
541 MoveToEx(fe->hdc, p.x, p.y, NULL);
542 LineTo(fe->hdc, q.x, q.y);
543 if (fe->drawstatus == DRAWING)
544 SetPixel(fe->hdc, q.x, q.y, fe->colours[colour]);
545 win_reset_pen(fe);
546 }
547
548 static void win_draw_circle(void *handle, int cx, int cy, int radius,
549 int fillcolour, int outlinecolour)
550 {
551 frontend *fe = (frontend *)handle;
552 POINT p, q, r;
553
554 assert(outlinecolour >= 0);
555
556 if (fe->drawstatus == NOTHING)
557 return;
558
559 if (fillcolour >= 0) {
560 win_set_brush(fe, fillcolour);
561 win_set_pen(fe, outlinecolour, FALSE);
562 p = win_transform_point(fe, cx - radius, cy - radius);
563 q = win_transform_point(fe, cx + radius, cy + radius);
564 Ellipse(fe->hdc, p.x, p.y, q.x+1, q.y+1);
565 win_reset_brush(fe);
566 win_reset_pen(fe);
567 } else {
568 win_set_pen(fe, outlinecolour, FALSE);
569 p = win_transform_point(fe, cx - radius, cy - radius);
570 q = win_transform_point(fe, cx + radius, cy + radius);
571 r = win_transform_point(fe, cx - radius, cy);
572 Arc(fe->hdc, p.x, p.y, q.x+1, q.y+1, r.x, r.y, r.x, r.y);
573 win_reset_pen(fe);
574 }
575 }
576
577 static void win_draw_polygon(void *handle, int *coords, int npoints,
578 int fillcolour, int outlinecolour)
579 {
580 frontend *fe = (frontend *)handle;
581 POINT *pts;
582 int i;
583
584 if (fe->drawstatus == NOTHING)
585 return;
586
587 pts = snewn(npoints+1, POINT);
588
589 for (i = 0; i <= npoints; i++) {
590 int j = (i < npoints ? i : 0);
591 pts[i] = win_transform_point(fe, coords[j*2], coords[j*2+1]);
592 }
593
594 assert(outlinecolour >= 0);
595
596 if (fillcolour >= 0) {
597 win_set_brush(fe, fillcolour);
598 win_set_pen(fe, outlinecolour, FALSE);
599 Polygon(fe->hdc, pts, npoints);
600 win_reset_brush(fe);
601 win_reset_pen(fe);
602 } else {
603 win_set_pen(fe, outlinecolour, FALSE);
604 Polyline(fe->hdc, pts, npoints+1);
605 win_reset_pen(fe);
606 }
607
608 sfree(pts);
609 }
610
611 static void win_start_draw(void *handle)
612 {
613 frontend *fe = (frontend *)handle;
614 HDC hdc_win;
615
616 assert(fe->drawstatus == NOTHING);
617
618 hdc_win = GetDC(fe->hwnd);
619 fe->hdc = CreateCompatibleDC(hdc_win);
620 fe->prevbm = SelectObject(fe->hdc, fe->bitmap);
621 ReleaseDC(fe->hwnd, hdc_win);
622 fe->clip = NULL;
623 SetMapMode(fe->hdc, MM_TEXT);
624 fe->drawstatus = DRAWING;
625 }
626
627 static void win_draw_update(void *handle, int x, int y, int w, int h)
628 {
629 frontend *fe = (frontend *)handle;
630 RECT r;
631
632 if (fe->drawstatus != DRAWING)
633 return;
634
635 r.left = x;
636 r.top = y;
637 r.right = x + w;
638 r.bottom = y + h;
639
640 InvalidateRect(fe->hwnd, &r, FALSE);
641 }
642
643 static void win_end_draw(void *handle)
644 {
645 frontend *fe = (frontend *)handle;
646 assert(fe->drawstatus == DRAWING);
647 SelectObject(fe->hdc, fe->prevbm);
648 DeleteDC(fe->hdc);
649 if (fe->clip) {
650 DeleteObject(fe->clip);
651 fe->clip = NULL;
652 }
653 fe->drawstatus = NOTHING;
654 }
655
656 static void win_line_width(void *handle, float width)
657 {
658 frontend *fe = (frontend *)handle;
659
660 assert(fe->drawstatus != DRAWING);
661 if (fe->drawstatus == NOTHING)
662 return;
663
664 fe->linewidth = (int)(width * fe->printpixelscale);
665 }
666
667 static void win_begin_doc(void *handle, int pages)
668 {
669 frontend *fe = (frontend *)handle;
670
671 assert(fe->drawstatus != DRAWING);
672 if (fe->drawstatus == NOTHING)
673 return;
674
675 if (StartDoc(fe->hdc, &fe->di) <= 0) {
676 char *e = geterrstr();
677 MessageBox(fe->hwnd, e, "Error starting to print",
678 MB_ICONERROR | MB_OK);
679 sfree(e);
680 fe->drawstatus = NOTHING;
681 }
682
683 /*
684 * Push a marker on the font stack so that we won't use the
685 * same fonts for printing and drawing. (This is because
686 * drawing seems to look generally better in bold, but printing
687 * is better not in bold.)
688 */
689 fe->fontstart = fe->nfonts;
690 }
691
692 static void win_begin_page(void *handle, int number)
693 {
694 frontend *fe = (frontend *)handle;
695
696 assert(fe->drawstatus != DRAWING);
697 if (fe->drawstatus == NOTHING)
698 return;
699
700 if (StartPage(fe->hdc) <= 0) {
701 char *e = geterrstr();
702 MessageBox(fe->hwnd, e, "Error starting a page",
703 MB_ICONERROR | MB_OK);
704 sfree(e);
705 fe->drawstatus = NOTHING;
706 }
707 }
708
709 static void win_begin_puzzle(void *handle, float xm, float xc,
710 float ym, float yc, int pw, int ph, float wmm)
711 {
712 frontend *fe = (frontend *)handle;
713 int ppw, pph, pox, poy;
714 float mmpw, mmph, mmox, mmoy;
715 float scale;
716
717 assert(fe->drawstatus != DRAWING);
718 if (fe->drawstatus == NOTHING)
719 return;
720
721 ppw = GetDeviceCaps(fe->hdc, HORZRES);
722 pph = GetDeviceCaps(fe->hdc, VERTRES);
723 mmpw = (float)GetDeviceCaps(fe->hdc, HORZSIZE);
724 mmph = (float)GetDeviceCaps(fe->hdc, VERTSIZE);
725
726 /*
727 * Compute the puzzle's position on the logical page.
728 */
729 mmox = xm * mmpw + xc;
730 mmoy = ym * mmph + yc;
731
732 /*
733 * Work out what that comes to in pixels.
734 */
735 pox = (int)(mmox * (float)ppw / mmpw);
736 poy = (int)(mmoy * (float)ppw / mmpw);
737
738 /*
739 * And determine the scale.
740 *
741 * I need a scale such that the maximum puzzle-coordinate
742 * extent of the rectangle (pw * scale) is equal to the pixel
743 * equivalent of the puzzle's millimetre width (wmm * ppw /
744 * mmpw).
745 */
746 scale = (wmm * ppw) / (mmpw * pw);
747
748 /*
749 * Now store pox, poy and scale for use in the main drawing
750 * functions.
751 */
752 fe->printoffsetx = pox;
753 fe->printoffsety = poy;
754 fe->printpixelscale = scale;
755
756 fe->linewidth = 1;
757 }
758
759 static void win_end_puzzle(void *handle)
760 {
761 /* Nothing needs to be done here. */
762 }
763
764 static void win_end_page(void *handle, int number)
765 {
766 frontend *fe = (frontend *)handle;
767
768 assert(fe->drawstatus != DRAWING);
769
770 if (fe->drawstatus == NOTHING)
771 return;
772
773 if (EndPage(fe->hdc) <= 0) {
774 char *e = geterrstr();
775 MessageBox(fe->hwnd, e, "Error finishing a page",
776 MB_ICONERROR | MB_OK);
777 sfree(e);
778 fe->drawstatus = NOTHING;
779 }
780 }
781
782 static void win_end_doc(void *handle)
783 {
784 frontend *fe = (frontend *)handle;
785
786 assert(fe->drawstatus != DRAWING);
787
788 /*
789 * Free all the fonts created since we began printing.
790 */
791 while (fe->nfonts > fe->fontstart) {
792 fe->nfonts--;
793 DeleteObject(fe->fonts[fe->nfonts].font);
794 }
795 fe->fontstart = 0;
796
797 /*
798 * The MSDN web site sample code doesn't bother to call EndDoc
799 * if an error occurs half way through printing. I expect doing
800 * so would cause the erroneous document to actually be
801 * printed, or something equally undesirable.
802 */
803 if (fe->drawstatus == NOTHING)
804 return;
805
806 if (EndDoc(fe->hdc) <= 0) {
807 char *e = geterrstr();
808 MessageBox(fe->hwnd, e, "Error finishing printing",
809 MB_ICONERROR | MB_OK);
810 sfree(e);
811 fe->drawstatus = NOTHING;
812 }
813 }
814
815 const struct drawing_api win_drawing = {
816 win_draw_text,
817 win_draw_rect,
818 win_draw_line,
819 win_draw_polygon,
820 win_draw_circle,
821 win_draw_update,
822 win_clip,
823 win_unclip,
824 win_start_draw,
825 win_end_draw,
826 win_status_bar,
827 win_blitter_new,
828 win_blitter_free,
829 win_blitter_save,
830 win_blitter_load,
831 win_begin_doc,
832 win_begin_page,
833 win_begin_puzzle,
834 win_end_puzzle,
835 win_end_page,
836 win_end_doc,
837 win_line_width,
838 };
839
840 void print(frontend *fe)
841 {
842 PRINTDLG pd;
843 char doctitle[256];
844 document *doc;
845 midend *nme = NULL; /* non-interactive midend for bulk puzzle generation */
846 int i;
847 char *err = NULL;
848
849 /*
850 * Create our document structure and fill it up with puzzles.
851 */
852 doc = document_new(fe->printw, fe->printh, fe->printscale / 100.0F);
853 for (i = 0; i < fe->printcount; i++) {
854 if (i == 0 && fe->printcurr) {
855 err = midend_print_puzzle(fe->me, doc, fe->printsolns);
856 } else {
857 if (!nme) {
858 game_params *params;
859
860 nme = midend_new(NULL, &thegame, NULL, NULL);
861
862 /*
863 * Set the non-interactive mid-end to have the same
864 * parameters as the standard one.
865 */
866 params = midend_get_params(fe->me);
867 midend_set_params(nme, params);
868 thegame.free_params(params);
869 }
870
871 midend_new_game(nme);
872 err = midend_print_puzzle(nme, doc, fe->printsolns);
873 }
874 if (err)
875 break;
876 }
877 if (nme)
878 midend_free(nme);
879
880 if (err) {
881 MessageBox(fe->hwnd, err, "Error preparing puzzles for printing",
882 MB_ICONERROR | MB_OK);
883 document_free(doc);
884 return;
885 }
886
887 memset(&pd, 0, sizeof(pd));
888 pd.lStructSize = sizeof(pd);
889 pd.hwndOwner = fe->hwnd;
890 pd.hDevMode = NULL;
891 pd.hDevNames = NULL;
892 pd.Flags = PD_USEDEVMODECOPIESANDCOLLATE | PD_RETURNDC |
893 PD_NOPAGENUMS | PD_NOSELECTION;
894 pd.nCopies = 1;
895 pd.nFromPage = pd.nToPage = 0xFFFF;
896 pd.nMinPage = pd.nMaxPage = 1;
897
898 if (!PrintDlg(&pd)) {
899 document_free(doc);
900 return;
901 }
902
903 /*
904 * Now pd.hDC is a device context for the printer.
905 */
906
907 /*
908 * FIXME: IWBNI we put up an Abort box here.
909 */
910
911 memset(&fe->di, 0, sizeof(fe->di));
912 fe->di.cbSize = sizeof(fe->di);
913 sprintf(doctitle, "Printed puzzles from %s (from Simon Tatham's"
914 " Portable Puzzle Collection)", thegame.name);
915 fe->di.lpszDocName = doctitle;
916 fe->di.lpszOutput = NULL;
917 fe->di.lpszDatatype = NULL;
918 fe->di.fwType = 0;
919
920 fe->drawstatus = PRINTING;
921 fe->hdc = pd.hDC;
922
923 fe->dr = drawing_new(&win_drawing, NULL, fe);
924 document_print(doc, fe->dr);
925 drawing_free(fe->dr);
926 fe->dr = NULL;
927
928 fe->drawstatus = NOTHING;
929
930 DeleteDC(pd.hDC);
931 document_free(doc);
932 }
933
934 void deactivate_timer(frontend *fe)
935 {
936 if (!fe)
937 return; /* for non-interactive midend */
938 if (fe->hwnd) KillTimer(fe->hwnd, fe->timer);
939 fe->timer = 0;
940 }
941
942 void activate_timer(frontend *fe)
943 {
944 if (!fe)
945 return; /* for non-interactive midend */
946 if (!fe->timer) {
947 fe->timer = SetTimer(fe->hwnd, fe->timer, 20, NULL);
948 fe->timer_last_tickcount = GetTickCount();
949 }
950 }
951
952 void write_clip(HWND hwnd, char *data)
953 {
954 HGLOBAL clipdata;
955 int len, i, j;
956 char *data2;
957 void *lock;
958
959 /*
960 * Windows expects CRLF in the clipboard, so we must convert
961 * any \n that has come out of the puzzle backend.
962 */
963 len = 0;
964 for (i = 0; data[i]; i++) {
965 if (data[i] == '\n')
966 len++;
967 len++;
968 }
969 data2 = snewn(len+1, char);
970 j = 0;
971 for (i = 0; data[i]; i++) {
972 if (data[i] == '\n')
973 data2[j++] = '\r';
974 data2[j++] = data[i];
975 }
976 assert(j == len);
977 data2[j] = '\0';
978
979 clipdata = GlobalAlloc(GMEM_DDESHARE | GMEM_MOVEABLE, len + 1);
980 if (!clipdata)
981 return;
982 lock = GlobalLock(clipdata);
983 if (!lock)
984 return;
985 memcpy(lock, data2, len);
986 ((unsigned char *) lock)[len] = 0;
987 GlobalUnlock(clipdata);
988
989 if (OpenClipboard(hwnd)) {
990 EmptyClipboard();
991 SetClipboardData(CF_TEXT, clipdata);
992 CloseClipboard();
993 } else
994 GlobalFree(clipdata);
995
996 sfree(data2);
997 }
998
999 /*
1000 * Set up Help and see if we can find a help file.
1001 */
1002 static void init_help(void)
1003 {
1004 char b[2048], *p, *q, *r;
1005 FILE *fp;
1006
1007 /*
1008 * Find the executable file path, so we can look alongside
1009 * it for help files. Trim the filename off the end.
1010 */
1011 GetModuleFileName(NULL, b, sizeof(b) - 1);
1012 r = b;
1013 p = strrchr(b, '\\');
1014 if (p && p >= r) r = p+1;
1015 q = strrchr(b, ':');
1016 if (q && q >= r) r = q+1;
1017
1018 #ifndef NO_HTMLHELP
1019 /*
1020 * Try HTML Help first.
1021 */
1022 strcpy(r, CHM_FILE_NAME);
1023 if ( (fp = fopen(b, "r")) != NULL) {
1024 fclose(fp);
1025
1026 /*
1027 * We have a .CHM. See if we can use it.
1028 */
1029 hh_dll = LoadLibrary("hhctrl.ocx");
1030 if (hh_dll) {
1031 htmlhelp = (htmlhelp_t)GetProcAddress(hh_dll, "HtmlHelpA");
1032 if (!htmlhelp)
1033 FreeLibrary(hh_dll);
1034 }
1035 if (htmlhelp) {
1036 htmlhelp(NULL, NULL, HH_INITIALIZE, (DWORD)&html_help_cookie);
1037 help_path = dupstr(b);
1038 help_type = CHM;
1039 help_topic = thegame.htmlhelp_topic;
1040 return;
1041 }
1042 }
1043 #endif /* NO_HTMLHELP */
1044
1045 /*
1046 * Now try old-style .HLP.
1047 */
1048 strcpy(r, HELP_FILE_NAME);
1049 if ( (fp = fopen(b, "r")) != NULL) {
1050 fclose(fp);
1051
1052 help_path = dupstr(b);
1053 help_type = HLP;
1054
1055 help_topic = thegame.winhelp_topic;
1056
1057 /*
1058 * See if there's a .CNT file alongside it.
1059 */
1060 strcpy(r, HELP_CNT_NAME);
1061 if ( (fp = fopen(b, "r")) != NULL) {
1062 fclose(fp);
1063 help_has_contents = TRUE;
1064 } else
1065 help_has_contents = FALSE;
1066
1067 return;
1068 }
1069
1070 help_type = NONE; /* didn't find any */
1071 }
1072
1073 /*
1074 * Start Help.
1075 */
1076 static void start_help(frontend *fe, const char *topic)
1077 {
1078 char *str = NULL;
1079 int cmd;
1080
1081 switch (help_type) {
1082 case HLP:
1083 assert(help_path);
1084 if (topic) {
1085 str = snewn(10+strlen(topic), char);
1086 sprintf(str, "JI(`',`%s')", topic);
1087 cmd = HELP_COMMAND;
1088 } else if (help_has_contents) {
1089 cmd = HELP_FINDER;
1090 } else {
1091 cmd = HELP_CONTENTS;
1092 }
1093 WinHelp(fe->hwnd, help_path, cmd, (DWORD)str);
1094 fe->help_running = TRUE;
1095 break;
1096 case CHM:
1097 #ifndef NO_HTMLHELP
1098 assert(help_path);
1099 assert(htmlhelp);
1100 if (topic) {
1101 str = snewn(20 + strlen(topic) + strlen(help_path), char);
1102 sprintf(str, "%s::/%s.html>main", help_path, topic);
1103 } else {
1104 str = dupstr(help_path);
1105 }
1106 htmlhelp(fe->hwnd, str, HH_DISPLAY_TOPIC, 0);
1107 fe->help_running = TRUE;
1108 break;
1109 #endif /* NO_HTMLHELP */
1110 case NONE:
1111 assert(!"This shouldn't happen");
1112 break;
1113 }
1114
1115 sfree(str);
1116 }
1117
1118 /*
1119 * Stop Help on window cleanup.
1120 */
1121 static void stop_help(frontend *fe)
1122 {
1123 if (fe->help_running) {
1124 switch (help_type) {
1125 case HLP:
1126 WinHelp(fe->hwnd, help_path, HELP_QUIT, 0);
1127 break;
1128 case CHM:
1129 #ifndef NO_HTMLHELP
1130 assert(htmlhelp);
1131 htmlhelp(NULL, NULL, HH_CLOSE_ALL, 0);
1132 break;
1133 #endif /* NO_HTMLHELP */
1134 case NONE:
1135 assert(!"This shouldn't happen");
1136 break;
1137 }
1138 fe->help_running = FALSE;
1139 }
1140 }
1141
1142 /*
1143 * Terminate Help on process exit.
1144 */
1145 static void cleanup_help(void)
1146 {
1147 #ifndef NO_HTMLHELP
1148 if (help_type == CHM) {
1149 assert(htmlhelp);
1150 htmlhelp(NULL, NULL, HH_UNINITIALIZE, html_help_cookie);
1151 }
1152 #endif /* NO_HTMLHELP */
1153 }
1154
1155 static void check_window_size(frontend *fe, int *px, int *py)
1156 {
1157 RECT r;
1158 int x, y, sy;
1159
1160 if (fe->statusbar) {
1161 RECT sr;
1162 GetWindowRect(fe->statusbar, &sr);
1163 sy = sr.bottom - sr.top;
1164 } else {
1165 sy = 0;
1166 }
1167
1168 /*
1169 * See if we actually got the window size we wanted, and adjust
1170 * the puzzle size if not.
1171 */
1172 GetClientRect(fe->hwnd, &r);
1173 x = r.right - r.left;
1174 y = r.bottom - r.top - sy;
1175 midend_size(fe->me, &x, &y, FALSE);
1176 if (x != r.right - r.left || y != r.bottom - r.top) {
1177 /*
1178 * Resize the window, now we know what size we _really_
1179 * want it to be.
1180 */
1181 r.left = r.top = 0;
1182 r.right = x;
1183 r.bottom = y + sy;
1184 AdjustWindowRectEx(&r, WINFLAGS, TRUE, 0);
1185 SetWindowPos(fe->hwnd, NULL, 0, 0, r.right - r.left, r.bottom - r.top,
1186 SWP_NOMOVE | SWP_NOZORDER);
1187 }
1188
1189 if (fe->statusbar) {
1190 GetClientRect(fe->hwnd, &r);
1191 SetWindowPos(fe->statusbar, NULL, 0, r.bottom-r.top-sy, r.right-r.left,
1192 sy, SWP_NOZORDER);
1193 }
1194
1195 *px = x;
1196 *py = y;
1197 }
1198
1199 static void get_max_puzzle_size(frontend *fe, int *x, int *y)
1200 {
1201 RECT r, sr;
1202
1203 if (SystemParametersInfo(SPI_GETWORKAREA, 0, &sr, FALSE)) {
1204 *x = sr.right - sr.left;
1205 *y = sr.bottom - sr.top;
1206 r.left = 100;
1207 r.right = 200;
1208 r.top = 100;
1209 r.bottom = 200;
1210 AdjustWindowRectEx(&r, WINFLAGS, TRUE, 0);
1211 *x -= r.right - r.left - 100;
1212 *y -= r.bottom - r.top - 100;
1213 } else {
1214 *x = *y = INT_MAX;
1215 }
1216
1217 if (fe->statusbar != NULL) {
1218 GetWindowRect(fe->statusbar, &sr);
1219 *y -= sr.bottom - sr.top;
1220 }
1221 }
1222
1223 static frontend *new_window(HINSTANCE inst, char *game_id, char **error)
1224 {
1225 frontend *fe;
1226 int x, y;
1227 RECT r;
1228
1229 fe = snew(frontend);
1230
1231 fe->me = midend_new(fe, &thegame, &win_drawing, fe);
1232
1233 if (game_id) {
1234 *error = midend_game_id(fe->me, game_id);
1235 if (*error) {
1236 midend_free(fe->me);
1237 sfree(fe);
1238 return NULL;
1239 }
1240 }
1241
1242 fe->inst = inst;
1243
1244 fe->timer = 0;
1245 fe->hwnd = NULL;
1246
1247 fe->help_running = FALSE;
1248
1249 fe->drawstatus = NOTHING;
1250 fe->dr = NULL;
1251 fe->fontstart = 0;
1252
1253 midend_new_game(fe->me);
1254
1255 fe->fonts = NULL;
1256 fe->nfonts = fe->fontsize = 0;
1257
1258 {
1259 int i, ncolours;
1260 float *colours;
1261
1262 colours = midend_colours(fe->me, &ncolours);
1263
1264 fe->colours = snewn(ncolours, COLORREF);
1265 fe->brushes = snewn(ncolours, HBRUSH);
1266 fe->pens = snewn(ncolours, HPEN);
1267
1268 for (i = 0; i < ncolours; i++) {
1269 fe->colours[i] = RGB(255 * colours[i*3+0],
1270 255 * colours[i*3+1],
1271 255 * colours[i*3+2]);
1272 fe->brushes[i] = CreateSolidBrush(fe->colours[i]);
1273 fe->pens[i] = CreatePen(PS_SOLID, 1, fe->colours[i]);
1274 }
1275 sfree(colours);
1276 }
1277
1278 if (midend_wants_statusbar(fe->me)) {
1279 fe->statusbar = CreateWindowEx(0, STATUSCLASSNAME, "ooh",
1280 WS_CHILD | WS_VISIBLE,
1281 0, 0, 0, 0, /* status bar does these */
1282 NULL, NULL, inst, NULL);
1283 } else
1284 fe->statusbar = NULL;
1285
1286 get_max_puzzle_size(fe, &x, &y);
1287 midend_size(fe->me, &x, &y, FALSE);
1288
1289 r.left = r.top = 0;
1290 r.right = x;
1291 r.bottom = y;
1292 AdjustWindowRectEx(&r, WINFLAGS, TRUE, 0);
1293
1294 fe->hwnd = CreateWindowEx(0, thegame.name, thegame.name,
1295 WS_OVERLAPPEDWINDOW &~
1296 (WS_THICKFRAME | WS_MAXIMIZEBOX),
1297 CW_USEDEFAULT, CW_USEDEFAULT,
1298 r.right - r.left, r.bottom - r.top,
1299 NULL, NULL, inst, NULL);
1300
1301 if (midend_wants_statusbar(fe->me)) {
1302 RECT sr;
1303 DestroyWindow(fe->statusbar);
1304 fe->statusbar = CreateWindowEx(0, STATUSCLASSNAME, "ooh",
1305 WS_CHILD | WS_VISIBLE,
1306 0, 0, 0, 0, /* status bar does these */
1307 fe->hwnd, NULL, inst, NULL);
1308 /*
1309 * Now resize the window to take account of the status bar.
1310 */
1311 GetWindowRect(fe->statusbar, &sr);
1312 GetWindowRect(fe->hwnd, &r);
1313 SetWindowPos(fe->hwnd, NULL, 0, 0, r.right - r.left,
1314 r.bottom - r.top + sr.bottom - sr.top,
1315 SWP_NOMOVE | SWP_NOZORDER);
1316 } else {
1317 fe->statusbar = NULL;
1318 }
1319
1320 {
1321 HMENU bar = CreateMenu();
1322 HMENU menu = CreateMenu();
1323
1324 AppendMenu(bar, MF_ENABLED|MF_POPUP, (UINT)menu, "Game");
1325 AppendMenu(menu, MF_ENABLED, IDM_NEW, "New");
1326 AppendMenu(menu, MF_ENABLED, IDM_RESTART, "Restart");
1327 AppendMenu(menu, MF_ENABLED, IDM_DESC, "Specific...");
1328 AppendMenu(menu, MF_ENABLED, IDM_SEED, "Random Seed...");
1329
1330 if ((fe->npresets = midend_num_presets(fe->me)) > 0 ||
1331 thegame.can_configure) {
1332 HMENU sub = CreateMenu();
1333 int i;
1334
1335 AppendMenu(bar, MF_ENABLED|MF_POPUP, (UINT)sub, "Type");
1336
1337 fe->presets = snewn(fe->npresets, game_params *);
1338
1339 for (i = 0; i < fe->npresets; i++) {
1340 char *name;
1341
1342 midend_fetch_preset(fe->me, i, &name, &fe->presets[i]);
1343
1344 /*
1345 * FIXME: we ought to go through and do something
1346 * with ampersands here.
1347 */
1348
1349 AppendMenu(sub, MF_ENABLED, IDM_PRESETS + 0x10 * i, name);
1350 }
1351
1352 if (thegame.can_configure) {
1353 AppendMenu(sub, MF_ENABLED, IDM_CONFIG, "Custom...");
1354 }
1355 }
1356
1357 AppendMenu(menu, MF_SEPARATOR, 0, 0);
1358 AppendMenu(menu, MF_ENABLED, IDM_LOAD, "Load...");
1359 AppendMenu(menu, MF_ENABLED, IDM_SAVE, "Save...");
1360 AppendMenu(menu, MF_SEPARATOR, 0, 0);
1361 if (thegame.can_print) {
1362 AppendMenu(menu, MF_ENABLED, IDM_PRINT, "Print...");
1363 AppendMenu(menu, MF_SEPARATOR, 0, 0);
1364 }
1365 AppendMenu(menu, MF_ENABLED, IDM_UNDO, "Undo");
1366 AppendMenu(menu, MF_ENABLED, IDM_REDO, "Redo");
1367 if (thegame.can_format_as_text) {
1368 AppendMenu(menu, MF_SEPARATOR, 0, 0);
1369 AppendMenu(menu, MF_ENABLED, IDM_COPY, "Copy");
1370 }
1371 if (thegame.can_solve) {
1372 AppendMenu(menu, MF_SEPARATOR, 0, 0);
1373 AppendMenu(menu, MF_ENABLED, IDM_SOLVE, "Solve");
1374 }
1375 AppendMenu(menu, MF_SEPARATOR, 0, 0);
1376 AppendMenu(menu, MF_ENABLED, IDM_QUIT, "Exit");
1377 menu = CreateMenu();
1378 AppendMenu(bar, MF_ENABLED|MF_POPUP, (UINT)menu, "Help");
1379 AppendMenu(menu, MF_ENABLED, IDM_ABOUT, "About");
1380 if (help_type != NONE) {
1381 AppendMenu(menu, MF_SEPARATOR, 0, 0);
1382 AppendMenu(menu, MF_ENABLED, IDM_HELPC, "Contents");
1383 if (help_topic) {
1384 char *item;
1385 assert(thegame.name);
1386 item = snewn(9+strlen(thegame.name), char); /*ick*/
1387 sprintf(item, "Help on %s", thegame.name);
1388 AppendMenu(menu, MF_ENABLED, IDM_GAMEHELP, item);
1389 sfree(item);
1390 }
1391 }
1392 SetMenu(fe->hwnd, bar);
1393 }
1394
1395 fe->bitmap = NULL;
1396 new_game_size(fe); /* initialises fe->bitmap */
1397 check_window_size(fe, &x, &y);
1398
1399 SetWindowLong(fe->hwnd, GWL_USERDATA, (LONG)fe);
1400
1401 ShowWindow(fe->hwnd, SW_NORMAL);
1402 SetForegroundWindow(fe->hwnd);
1403
1404 midend_redraw(fe->me);
1405
1406 return fe;
1407 }
1408
1409 static int CALLBACK AboutDlgProc(HWND hwnd, UINT msg,
1410 WPARAM wParam, LPARAM lParam)
1411 {
1412 frontend *fe = (frontend *)GetWindowLong(hwnd, GWL_USERDATA);
1413
1414 switch (msg) {
1415 case WM_INITDIALOG:
1416 return 0;
1417
1418 case WM_COMMAND:
1419 if ((HIWORD(wParam) == BN_CLICKED ||
1420 HIWORD(wParam) == BN_DOUBLECLICKED) &&
1421 LOWORD(wParam) == IDOK)
1422 fe->dlg_done = 1;
1423 return 0;
1424
1425 case WM_CLOSE:
1426 fe->dlg_done = 1;
1427 return 0;
1428 }
1429
1430 return 0;
1431 }
1432
1433 /*
1434 * Wrappers on midend_{get,set}_config, which extend the CFG_*
1435 * enumeration to add CFG_PRINT.
1436 */
1437 static config_item *frontend_get_config(frontend *fe, int which,
1438 char **wintitle)
1439 {
1440 if (which < CFG_FRONTEND_SPECIFIC) {
1441 return midend_get_config(fe->me, which, wintitle);
1442 } else if (which == CFG_PRINT) {
1443 config_item *ret;
1444 int i;
1445
1446 *wintitle = snewn(40 + strlen(thegame.name), char);
1447 sprintf(*wintitle, "%s print setup", thegame.name);
1448
1449 ret = snewn(8, config_item);
1450
1451 i = 0;
1452
1453 ret[i].name = "Number of puzzles to print";
1454 ret[i].type = C_STRING;
1455 ret[i].sval = dupstr("1");
1456 ret[i].ival = 0;
1457 i++;
1458
1459 ret[i].name = "Number of puzzles across the page";
1460 ret[i].type = C_STRING;
1461 ret[i].sval = dupstr("1");
1462 ret[i].ival = 0;
1463 i++;
1464
1465 ret[i].name = "Number of puzzles down the page";
1466 ret[i].type = C_STRING;
1467 ret[i].sval = dupstr("1");
1468 ret[i].ival = 0;
1469 i++;
1470
1471 ret[i].name = "Percentage of standard size";
1472 ret[i].type = C_STRING;
1473 ret[i].sval = dupstr("100.0");
1474 ret[i].ival = 0;
1475 i++;
1476
1477 ret[i].name = "Include currently shown puzzle";
1478 ret[i].type = C_BOOLEAN;
1479 ret[i].sval = NULL;
1480 ret[i].ival = TRUE;
1481 i++;
1482
1483 ret[i].name = "Print solutions";
1484 ret[i].type = C_BOOLEAN;
1485 ret[i].sval = NULL;
1486 ret[i].ival = FALSE;
1487 i++;
1488
1489 if (thegame.can_print_in_colour) {
1490 ret[i].name = "Print in colour";
1491 ret[i].type = C_BOOLEAN;
1492 ret[i].sval = NULL;
1493 ret[i].ival = FALSE;
1494 i++;
1495 }
1496
1497 ret[i].name = NULL;
1498 ret[i].type = C_END;
1499 ret[i].sval = NULL;
1500 ret[i].ival = 0;
1501 i++;
1502
1503 return ret;
1504 } else {
1505 assert(!"We should never get here");
1506 return NULL;
1507 }
1508 }
1509
1510 static char *frontend_set_config(frontend *fe, int which, config_item *cfg)
1511 {
1512 if (which < CFG_FRONTEND_SPECIFIC) {
1513 return midend_set_config(fe->me, which, cfg);
1514 } else if (which == CFG_PRINT) {
1515 if ((fe->printcount = atoi(cfg[0].sval)) <= 0)
1516 return "Number of puzzles to print should be at least one";
1517 if ((fe->printw = atoi(cfg[1].sval)) <= 0)
1518 return "Number of puzzles across the page should be at least one";
1519 if ((fe->printh = atoi(cfg[2].sval)) <= 0)
1520 return "Number of puzzles down the page should be at least one";
1521 if ((fe->printscale = (float)atof(cfg[3].sval)) <= 0)
1522 return "Print size should be positive";
1523 fe->printcurr = cfg[4].ival;
1524 fe->printsolns = cfg[5].ival;
1525 fe->printcolour = thegame.can_print_in_colour && cfg[6].ival;
1526 return NULL;
1527 } else {
1528 assert(!"We should never get here");
1529 return "Internal error";
1530 }
1531 }
1532
1533 static int CALLBACK ConfigDlgProc(HWND hwnd, UINT msg,
1534 WPARAM wParam, LPARAM lParam)
1535 {
1536 frontend *fe = (frontend *)GetWindowLong(hwnd, GWL_USERDATA);
1537 config_item *i;
1538 struct cfg_aux *j;
1539
1540 switch (msg) {
1541 case WM_INITDIALOG:
1542 return 0;
1543
1544 case WM_COMMAND:
1545 /*
1546 * OK and Cancel are special cases.
1547 */
1548 if ((HIWORD(wParam) == BN_CLICKED ||
1549 HIWORD(wParam) == BN_DOUBLECLICKED) &&
1550 (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL)) {
1551 if (LOWORD(wParam) == IDOK) {
1552 char *err = frontend_set_config(fe, fe->cfg_which, fe->cfg);
1553
1554 if (err) {
1555 MessageBox(hwnd, err, "Validation error",
1556 MB_ICONERROR | MB_OK);
1557 } else {
1558 fe->dlg_done = 2;
1559 }
1560 } else {
1561 fe->dlg_done = 1;
1562 }
1563 return 0;
1564 }
1565
1566 /*
1567 * First find the control whose id this is.
1568 */
1569 for (i = fe->cfg, j = fe->cfgaux; i->type != C_END; i++, j++) {
1570 if (j->ctlid == LOWORD(wParam))
1571 break;
1572 }
1573 if (i->type == C_END)
1574 return 0; /* not our problem */
1575
1576 if (i->type == C_STRING && HIWORD(wParam) == EN_CHANGE) {
1577 char buffer[4096];
1578 GetDlgItemText(fe->cfgbox, j->ctlid, buffer, lenof(buffer));
1579 buffer[lenof(buffer)-1] = '\0';
1580 sfree(i->sval);
1581 i->sval = dupstr(buffer);
1582 } else if (i->type == C_BOOLEAN &&
1583 (HIWORD(wParam) == BN_CLICKED ||
1584 HIWORD(wParam) == BN_DOUBLECLICKED)) {
1585 i->ival = IsDlgButtonChecked(fe->cfgbox, j->ctlid);
1586 } else if (i->type == C_CHOICES &&
1587 HIWORD(wParam) == CBN_SELCHANGE) {
1588 i->ival = SendDlgItemMessage(fe->cfgbox, j->ctlid,
1589 CB_GETCURSEL, 0, 0);
1590 }
1591
1592 return 0;
1593
1594 case WM_CLOSE:
1595 fe->dlg_done = 1;
1596 return 0;
1597 }
1598
1599 return 0;
1600 }
1601
1602 HWND mkctrl(frontend *fe, int x1, int x2, int y1, int y2,
1603 char *wclass, int wstyle,
1604 int exstyle, const char *wtext, int wid)
1605 {
1606 HWND ret;
1607 ret = CreateWindowEx(exstyle, wclass, wtext,
1608 wstyle | WS_CHILD | WS_VISIBLE, x1, y1, x2-x1, y2-y1,
1609 fe->cfgbox, (HMENU) wid, fe->inst, NULL);
1610 SendMessage(ret, WM_SETFONT, (WPARAM)fe->cfgfont, MAKELPARAM(TRUE, 0));
1611 return ret;
1612 }
1613
1614 static void about(frontend *fe)
1615 {
1616 int i;
1617 WNDCLASS wc;
1618 MSG msg;
1619 TEXTMETRIC tm;
1620 HDC hdc;
1621 HFONT oldfont;
1622 SIZE size;
1623 int gm, id;
1624 int winwidth, winheight, y;
1625 int height, width, maxwid;
1626 const char *strings[16];
1627 int lengths[16];
1628 int nstrings = 0;
1629 char titlebuf[512];
1630
1631 sprintf(titlebuf, "About %.250s", thegame.name);
1632
1633 strings[nstrings++] = thegame.name;
1634 strings[nstrings++] = "from Simon Tatham's Portable Puzzle Collection";
1635 strings[nstrings++] = ver;
1636
1637 wc.style = CS_DBLCLKS | CS_SAVEBITS | CS_BYTEALIGNWINDOW;
1638 wc.lpfnWndProc = DefDlgProc;
1639 wc.cbClsExtra = 0;
1640 wc.cbWndExtra = DLGWINDOWEXTRA + 8;
1641 wc.hInstance = fe->inst;
1642 wc.hIcon = NULL;
1643 wc.hCursor = LoadCursor(NULL, IDC_ARROW);
1644 wc.hbrBackground = (HBRUSH) (COLOR_BACKGROUND +1);
1645 wc.lpszMenuName = NULL;
1646 wc.lpszClassName = "GameAboutBox";
1647 RegisterClass(&wc);
1648
1649 hdc = GetDC(fe->hwnd);
1650 SetMapMode(hdc, MM_TEXT);
1651
1652 fe->dlg_done = FALSE;
1653
1654 fe->cfgfont = CreateFont(-MulDiv(8, GetDeviceCaps(hdc, LOGPIXELSY), 72),
1655 0, 0, 0, 0,
1656 FALSE, FALSE, FALSE, DEFAULT_CHARSET,
1657 OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS,
1658 DEFAULT_QUALITY,
1659 FF_SWISS,
1660 "MS Shell Dlg");
1661
1662 oldfont = SelectObject(hdc, fe->cfgfont);
1663 if (GetTextMetrics(hdc, &tm)) {
1664 height = tm.tmAscent + tm.tmDescent;
1665 width = tm.tmAveCharWidth;
1666 } else {
1667 height = width = 30;
1668 }
1669
1670 /*
1671 * Figure out the layout of the About box by measuring the
1672 * length of each piece of text.
1673 */
1674 maxwid = 0;
1675 winheight = height/2;
1676
1677 for (i = 0; i < nstrings; i++) {
1678 if (GetTextExtentPoint32(hdc, strings[i], strlen(strings[i]), &size))
1679 lengths[i] = size.cx;
1680 else
1681 lengths[i] = 0; /* *shrug* */
1682 if (maxwid < lengths[i])
1683 maxwid = lengths[i];
1684 winheight += height * 3 / 2 + (height / 2);
1685 }
1686
1687 winheight += height + height * 7 / 4; /* OK button */
1688 winwidth = maxwid + 4*width;
1689
1690 SelectObject(hdc, oldfont);
1691 ReleaseDC(fe->hwnd, hdc);
1692
1693 /*
1694 * Create the dialog, now that we know its size.
1695 */
1696 {
1697 RECT r, r2;
1698
1699 r.left = r.top = 0;
1700 r.right = winwidth;
1701 r.bottom = winheight;
1702
1703 AdjustWindowRectEx(&r, (WS_OVERLAPPEDWINDOW /*|
1704 DS_MODALFRAME | WS_POPUP | WS_VISIBLE |
1705 WS_CAPTION | WS_SYSMENU*/) &~
1706 (WS_MAXIMIZEBOX | WS_OVERLAPPED),
1707 FALSE, 0);
1708
1709 /*
1710 * Centre the dialog on its parent window.
1711 */
1712 r.right -= r.left;
1713 r.bottom -= r.top;
1714 GetWindowRect(fe->hwnd, &r2);
1715 r.left = (r2.left + r2.right - r.right) / 2;
1716 r.top = (r2.top + r2.bottom - r.bottom) / 2;
1717 r.right += r.left;
1718 r.bottom += r.top;
1719
1720 fe->cfgbox = CreateWindowEx(0, wc.lpszClassName, titlebuf,
1721 DS_MODALFRAME | WS_POPUP | WS_VISIBLE |
1722 WS_CAPTION | WS_SYSMENU,
1723 r.left, r.top,
1724 r.right-r.left, r.bottom-r.top,
1725 fe->hwnd, NULL, fe->inst, NULL);
1726 }
1727
1728 SendMessage(fe->cfgbox, WM_SETFONT, (WPARAM)fe->cfgfont, FALSE);
1729
1730 SetWindowLong(fe->cfgbox, GWL_USERDATA, (LONG)fe);
1731 SetWindowLong(fe->cfgbox, DWL_DLGPROC, (LONG)AboutDlgProc);
1732
1733 id = 1000;
1734 y = height/2;
1735 for (i = 0; i < nstrings; i++) {
1736 int border = width*2 + (maxwid - lengths[i]) / 2;
1737 mkctrl(fe, border, border+lengths[i], y+height*1/8, y+height*9/8,
1738 "Static", 0, 0, strings[i], id++);
1739 y += height*3/2;
1740
1741 assert(y < winheight);
1742 y += height/2;
1743 }
1744
1745 y += height/2; /* extra space before OK */
1746 mkctrl(fe, width*2, maxwid+width*2, y, y+height*7/4, "BUTTON",
1747 BS_PUSHBUTTON | BS_NOTIFY | WS_TABSTOP | BS_DEFPUSHBUTTON, 0,
1748 "OK", IDOK);
1749
1750 SendMessage(fe->cfgbox, WM_INITDIALOG, 0, 0);
1751
1752 EnableWindow(fe->hwnd, FALSE);
1753 ShowWindow(fe->cfgbox, SW_NORMAL);
1754 while ((gm=GetMessage(&msg, NULL, 0, 0)) > 0) {
1755 if (!IsDialogMessage(fe->cfgbox, &msg))
1756 DispatchMessage(&msg);
1757 if (fe->dlg_done)
1758 break;
1759 }
1760 EnableWindow(fe->hwnd, TRUE);
1761 SetForegroundWindow(fe->hwnd);
1762 DestroyWindow(fe->cfgbox);
1763 DeleteObject(fe->cfgfont);
1764 }
1765
1766 static int get_config(frontend *fe, int which)
1767 {
1768 config_item *i;
1769 struct cfg_aux *j;
1770 char *title;
1771 WNDCLASS wc;
1772 MSG msg;
1773 TEXTMETRIC tm;
1774 HDC hdc;
1775 HFONT oldfont;
1776 SIZE size;
1777 HWND ctl;
1778 int gm, id, nctrls;
1779 int winwidth, winheight, col1l, col1r, col2l, col2r, y;
1780 int height, width, maxlabel, maxcheckbox;
1781
1782 wc.style = CS_DBLCLKS | CS_SAVEBITS | CS_BYTEALIGNWINDOW;
1783 wc.lpfnWndProc = DefDlgProc;
1784 wc.cbClsExtra = 0;
1785 wc.cbWndExtra = DLGWINDOWEXTRA + 8;
1786 wc.hInstance = fe->inst;
1787 wc.hIcon = NULL;
1788 wc.hCursor = LoadCursor(NULL, IDC_ARROW);
1789 wc.hbrBackground = (HBRUSH) (COLOR_BACKGROUND +1);
1790 wc.lpszMenuName = NULL;
1791 wc.lpszClassName = "GameConfigBox";
1792 RegisterClass(&wc);
1793
1794 hdc = GetDC(fe->hwnd);
1795 SetMapMode(hdc, MM_TEXT);
1796
1797 fe->dlg_done = FALSE;
1798
1799 fe->cfgfont = CreateFont(-MulDiv(8, GetDeviceCaps(hdc, LOGPIXELSY), 72),
1800 0, 0, 0, 0,
1801 FALSE, FALSE, FALSE, DEFAULT_CHARSET,
1802 OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS,
1803 DEFAULT_QUALITY,
1804 FF_SWISS,
1805 "MS Shell Dlg");
1806
1807 oldfont = SelectObject(hdc, fe->cfgfont);
1808 if (GetTextMetrics(hdc, &tm)) {
1809 height = tm.tmAscent + tm.tmDescent;
1810 width = tm.tmAveCharWidth;
1811 } else {
1812 height = width = 30;
1813 }
1814
1815 fe->cfg = frontend_get_config(fe, which, &title);
1816 fe->cfg_which = which;
1817
1818 /*
1819 * Figure out the layout of the config box by measuring the
1820 * length of each piece of text.
1821 */
1822 maxlabel = maxcheckbox = 0;
1823 winheight = height/2;
1824
1825 for (i = fe->cfg; i->type != C_END; i++) {
1826 switch (i->type) {
1827 case C_STRING:
1828 case C_CHOICES:
1829 /*
1830 * Both these control types have a label filling only
1831 * the left-hand column of the box.
1832 */
1833 if (GetTextExtentPoint32(hdc, i->name, strlen(i->name), &size) &&
1834 maxlabel < size.cx)
1835 maxlabel = size.cx;
1836 winheight += height * 3 / 2 + (height / 2);
1837 break;
1838
1839 case C_BOOLEAN:
1840 /*
1841 * Checkboxes take up the whole of the box width.
1842 */
1843 if (GetTextExtentPoint32(hdc, i->name, strlen(i->name), &size) &&
1844 maxcheckbox < size.cx)
1845 maxcheckbox = size.cx;
1846 winheight += height + (height / 2);
1847 break;
1848 }
1849 }
1850
1851 winheight += height + height * 7 / 4; /* OK / Cancel buttons */
1852
1853 col1l = 2*width;
1854 col1r = col1l + maxlabel;
1855 col2l = col1r + 2*width;
1856 col2r = col2l + 30*width;
1857 if (col2r < col1l+2*height+maxcheckbox)
1858 col2r = col1l+2*height+maxcheckbox;
1859 winwidth = col2r + 2*width;
1860
1861 SelectObject(hdc, oldfont);
1862 ReleaseDC(fe->hwnd, hdc);
1863
1864 /*
1865 * Create the dialog, now that we know its size.
1866 */
1867 {
1868 RECT r, r2;
1869
1870 r.left = r.top = 0;
1871 r.right = winwidth;
1872 r.bottom = winheight;
1873
1874 AdjustWindowRectEx(&r, (WS_OVERLAPPEDWINDOW /*|
1875 DS_MODALFRAME | WS_POPUP | WS_VISIBLE |
1876 WS_CAPTION | WS_SYSMENU*/) &~
1877 (WS_MAXIMIZEBOX | WS_OVERLAPPED),
1878 FALSE, 0);
1879
1880 /*
1881 * Centre the dialog on its parent window.
1882 */
1883 r.right -= r.left;
1884 r.bottom -= r.top;
1885 GetWindowRect(fe->hwnd, &r2);
1886 r.left = (r2.left + r2.right - r.right) / 2;
1887 r.top = (r2.top + r2.bottom - r.bottom) / 2;
1888 r.right += r.left;
1889 r.bottom += r.top;
1890
1891 fe->cfgbox = CreateWindowEx(0, wc.lpszClassName, title,
1892 DS_MODALFRAME | WS_POPUP | WS_VISIBLE |
1893 WS_CAPTION | WS_SYSMENU,
1894 r.left, r.top,
1895 r.right-r.left, r.bottom-r.top,
1896 fe->hwnd, NULL, fe->inst, NULL);
1897 sfree(title);
1898 }
1899
1900 SendMessage(fe->cfgbox, WM_SETFONT, (WPARAM)fe->cfgfont, FALSE);
1901
1902 SetWindowLong(fe->cfgbox, GWL_USERDATA, (LONG)fe);
1903 SetWindowLong(fe->cfgbox, DWL_DLGPROC, (LONG)ConfigDlgProc);
1904
1905 /*
1906 * Count the controls so we can allocate cfgaux.
1907 */
1908 for (nctrls = 0, i = fe->cfg; i->type != C_END; i++)
1909 nctrls++;
1910 fe->cfgaux = snewn(nctrls, struct cfg_aux);
1911
1912 id = 1000;
1913 y = height/2;
1914 for (i = fe->cfg, j = fe->cfgaux; i->type != C_END; i++, j++) {
1915 switch (i->type) {
1916 case C_STRING:
1917 /*
1918 * Edit box with a label beside it.
1919 */
1920 mkctrl(fe, col1l, col1r, y+height*1/8, y+height*9/8,
1921 "Static", 0, 0, i->name, id++);
1922 ctl = mkctrl(fe, col2l, col2r, y, y+height*3/2,
1923 "EDIT", WS_TABSTOP | ES_AUTOHSCROLL,
1924 WS_EX_CLIENTEDGE, "", (j->ctlid = id++));
1925 SetWindowText(ctl, i->sval);
1926 y += height*3/2;
1927 break;
1928
1929 case C_BOOLEAN:
1930 /*
1931 * Simple checkbox.
1932 */
1933 mkctrl(fe, col1l, col2r, y, y+height, "BUTTON",
1934 BS_NOTIFY | BS_AUTOCHECKBOX | WS_TABSTOP,
1935 0, i->name, (j->ctlid = id++));
1936 CheckDlgButton(fe->cfgbox, j->ctlid, (i->ival != 0));
1937 y += height;
1938 break;
1939
1940 case C_CHOICES:
1941 /*
1942 * Drop-down list with a label beside it.
1943 */
1944 mkctrl(fe, col1l, col1r, y+height*1/8, y+height*9/8,
1945 "STATIC", 0, 0, i->name, id++);
1946 ctl = mkctrl(fe, col2l, col2r, y, y+height*41/2,
1947 "COMBOBOX", WS_TABSTOP |
1948 CBS_DROPDOWNLIST | CBS_HASSTRINGS,
1949 WS_EX_CLIENTEDGE, "", (j->ctlid = id++));
1950 {
1951 char c, *p, *q, *str;
1952
1953 SendMessage(ctl, CB_RESETCONTENT, 0, 0);
1954 p = i->sval;
1955 c = *p++;
1956 while (*p) {
1957 q = p;
1958 while (*q && *q != c) q++;
1959 str = snewn(q-p+1, char);
1960 strncpy(str, p, q-p);
1961 str[q-p] = '\0';
1962 SendMessage(ctl, CB_ADDSTRING, 0, (LPARAM)str);
1963 sfree(str);
1964 if (*q) q++;
1965 p = q;
1966 }
1967 }
1968
1969 SendMessage(ctl, CB_SETCURSEL, i->ival, 0);
1970
1971 y += height*3/2;
1972 break;
1973 }
1974
1975 assert(y < winheight);
1976 y += height/2;
1977 }
1978
1979 y += height/2; /* extra space before OK and Cancel */
1980 mkctrl(fe, col1l, (col1l+col2r)/2-width, y, y+height*7/4, "BUTTON",
1981 BS_PUSHBUTTON | BS_NOTIFY | WS_TABSTOP | BS_DEFPUSHBUTTON, 0,
1982 "OK", IDOK);
1983 mkctrl(fe, (col1l+col2r)/2+width, col2r, y, y+height*7/4, "BUTTON",
1984 BS_PUSHBUTTON | BS_NOTIFY | WS_TABSTOP, 0, "Cancel", IDCANCEL);
1985
1986 SendMessage(fe->cfgbox, WM_INITDIALOG, 0, 0);
1987
1988 EnableWindow(fe->hwnd, FALSE);
1989 ShowWindow(fe->cfgbox, SW_NORMAL);
1990 while ((gm=GetMessage(&msg, NULL, 0, 0)) > 0) {
1991 if (!IsDialogMessage(fe->cfgbox, &msg))
1992 DispatchMessage(&msg);
1993 if (fe->dlg_done)
1994 break;
1995 }
1996 EnableWindow(fe->hwnd, TRUE);
1997 SetForegroundWindow(fe->hwnd);
1998 DestroyWindow(fe->cfgbox);
1999 DeleteObject(fe->cfgfont);
2000
2001 free_cfg(fe->cfg);
2002 sfree(fe->cfgaux);
2003
2004 return (fe->dlg_done == 2);
2005 }
2006
2007 static void new_game_size(frontend *fe)
2008 {
2009 RECT r, sr;
2010 HDC hdc;
2011 int x, y;
2012
2013 get_max_puzzle_size(fe, &x, &y);
2014 midend_size(fe->me, &x, &y, FALSE);
2015
2016 r.left = r.top = 0;
2017 r.right = x;
2018 r.bottom = y;
2019 AdjustWindowRectEx(&r, WINFLAGS, TRUE, 0);
2020
2021 if (fe->statusbar != NULL) {
2022 GetWindowRect(fe->statusbar, &sr);
2023 } else {
2024 sr.left = sr.right = sr.top = sr.bottom = 0;
2025 }
2026 SetWindowPos(fe->hwnd, NULL, 0, 0,
2027 r.right - r.left,
2028 r.bottom - r.top + sr.bottom - sr.top,
2029 SWP_NOMOVE | SWP_NOZORDER);
2030
2031 check_window_size(fe, &x, &y);
2032
2033 if (fe->statusbar != NULL)
2034 SetWindowPos(fe->statusbar, NULL, 0, y, x,
2035 sr.bottom - sr.top, SWP_NOZORDER);
2036
2037 if (fe->bitmap) DeleteObject(fe->bitmap);
2038
2039 hdc = GetDC(fe->hwnd);
2040 fe->bitmap = CreateCompatibleBitmap(hdc, x, y);
2041 ReleaseDC(fe->hwnd, hdc);
2042
2043 midend_redraw(fe->me);
2044 }
2045
2046 static void new_game_type(frontend *fe)
2047 {
2048 midend_new_game(fe->me);
2049 new_game_size(fe);
2050 }
2051
2052 static int is_alt_pressed(void)
2053 {
2054 BYTE keystate[256];
2055 int r = GetKeyboardState(keystate);
2056 if (!r)
2057 return FALSE;
2058 if (keystate[VK_MENU] & 0x80)
2059 return TRUE;
2060 if (keystate[VK_RMENU] & 0x80)
2061 return TRUE;
2062 return FALSE;
2063 }
2064
2065 static void savefile_write(void *wctx, void *buf, int len)
2066 {
2067 FILE *fp = (FILE *)wctx;
2068 fwrite(buf, 1, len, fp);
2069 }
2070
2071 static int savefile_read(void *wctx, void *buf, int len)
2072 {
2073 FILE *fp = (FILE *)wctx;
2074 int ret;
2075
2076 ret = fread(buf, 1, len, fp);
2077 return (ret == len);
2078 }
2079
2080 static LRESULT CALLBACK WndProc(HWND hwnd, UINT message,
2081 WPARAM wParam, LPARAM lParam)
2082 {
2083 frontend *fe = (frontend *)GetWindowLong(hwnd, GWL_USERDATA);
2084 int cmd;
2085
2086 switch (message) {
2087 case WM_CLOSE:
2088 DestroyWindow(hwnd);
2089 return 0;
2090 case WM_COMMAND:
2091 cmd = wParam & ~0xF; /* low 4 bits reserved to Windows */
2092 switch (cmd) {
2093 case IDM_NEW:
2094 if (!midend_process_key(fe->me, 0, 0, 'n'))
2095 PostQuitMessage(0);
2096 break;
2097 case IDM_RESTART:
2098 midend_restart_game(fe->me);
2099 break;
2100 case IDM_UNDO:
2101 if (!midend_process_key(fe->me, 0, 0, 'u'))
2102 PostQuitMessage(0);
2103 break;
2104 case IDM_REDO:
2105 if (!midend_process_key(fe->me, 0, 0, '\x12'))
2106 PostQuitMessage(0);
2107 break;
2108 case IDM_COPY:
2109 {
2110 char *text = midend_text_format(fe->me);
2111 if (text)
2112 write_clip(hwnd, text);
2113 else
2114 MessageBeep(MB_ICONWARNING);
2115 sfree(text);
2116 }
2117 break;
2118 case IDM_SOLVE:
2119 {
2120 char *msg = midend_solve(fe->me);
2121 if (msg)
2122 MessageBox(hwnd, msg, "Unable to solve",
2123 MB_ICONERROR | MB_OK);
2124 }
2125 break;
2126 case IDM_QUIT:
2127 if (!midend_process_key(fe->me, 0, 0, 'q'))
2128 PostQuitMessage(0);
2129 break;
2130 case IDM_CONFIG:
2131 if (get_config(fe, CFG_SETTINGS))
2132 new_game_type(fe);
2133 break;
2134 case IDM_SEED:
2135 if (get_config(fe, CFG_SEED))
2136 new_game_type(fe);
2137 break;
2138 case IDM_DESC:
2139 if (get_config(fe, CFG_DESC))
2140 new_game_type(fe);
2141 break;
2142 case IDM_PRINT:
2143 if (get_config(fe, CFG_PRINT))
2144 print(fe);
2145 break;
2146 case IDM_ABOUT:
2147 about(fe);
2148 break;
2149 case IDM_LOAD:
2150 case IDM_SAVE:
2151 {
2152 OPENFILENAME of;
2153 char filename[FILENAME_MAX];
2154 int ret;
2155
2156 memset(&of, 0, sizeof(of));
2157 of.hwndOwner = hwnd;
2158 of.lpstrFilter = "All Files (*.*)\0*\0\0\0";
2159 of.lpstrCustomFilter = NULL;
2160 of.nFilterIndex = 1;
2161 of.lpstrFile = filename;
2162 filename[0] = '\0';
2163 of.nMaxFile = lenof(filename);
2164 of.lpstrFileTitle = NULL;
2165 of.lpstrTitle = (cmd == IDM_SAVE ?
2166 "Enter name of game file to save" :
2167 "Enter name of saved game file to load");
2168 of.Flags = 0;
2169 #ifdef OPENFILENAME_SIZE_VERSION_400
2170 of.lStructSize = OPENFILENAME_SIZE_VERSION_400;
2171 #else
2172 of.lStructSize = sizeof(of);
2173 #endif
2174 of.lpstrInitialDir = NULL;
2175
2176 if (cmd == IDM_SAVE)
2177 ret = GetSaveFileName(&of);
2178 else
2179 ret = GetOpenFileName(&of);
2180
2181 if (ret) {
2182 if (cmd == IDM_SAVE) {
2183 FILE *fp;
2184
2185 if ((fp = fopen(filename, "r")) != NULL) {
2186 char buf[256 + FILENAME_MAX];
2187 fclose(fp);
2188 /* file exists */
2189
2190 sprintf(buf, "Are you sure you want to overwrite"
2191 " the file \"%.*s\"?",
2192 FILENAME_MAX, filename);
2193 if (MessageBox(hwnd, buf, "Question",
2194 MB_YESNO | MB_ICONQUESTION)
2195 != IDYES)
2196 break;
2197 }
2198
2199 fp = fopen(filename, "w");
2200
2201 if (!fp) {
2202 MessageBox(hwnd, "Unable to open save file",
2203 "Error", MB_ICONERROR | MB_OK);
2204 break;
2205 }
2206
2207 midend_serialise(fe->me, savefile_write, fp);
2208
2209 fclose(fp);
2210 } else {
2211 FILE *fp = fopen(filename, "r");
2212 char *err;
2213
2214 if (!fp) {
2215 MessageBox(hwnd, "Unable to open saved game file",
2216 "Error", MB_ICONERROR | MB_OK);
2217 break;
2218 }
2219
2220 err = midend_deserialise(fe->me, savefile_read, fp);
2221
2222 fclose(fp);
2223
2224 if (err) {
2225 MessageBox(hwnd, err, "Error", MB_ICONERROR|MB_OK);
2226 break;
2227 }
2228
2229 new_game_size(fe);
2230 }
2231 }
2232 }
2233
2234 break;
2235 case IDM_HELPC:
2236 start_help(fe, NULL);
2237 break;
2238 case IDM_GAMEHELP:
2239 start_help(fe, help_topic);
2240 break;
2241 default:
2242 {
2243 int p = ((wParam &~ 0xF) - IDM_PRESETS) / 0x10;
2244
2245 if (p >= 0 && p < fe->npresets) {
2246 midend_set_params(fe->me, fe->presets[p]);
2247 new_game_type(fe);
2248 }
2249 }
2250 break;
2251 }
2252 break;
2253 case WM_DESTROY:
2254 stop_help(fe);
2255 PostQuitMessage(0);
2256 return 0;
2257 case WM_PAINT:
2258 {
2259 PAINTSTRUCT p;
2260 HDC hdc, hdc2;
2261 HBITMAP prevbm;
2262
2263 hdc = BeginPaint(hwnd, &p);
2264 hdc2 = CreateCompatibleDC(hdc);
2265 prevbm = SelectObject(hdc2, fe->bitmap);
2266 BitBlt(hdc,
2267 p.rcPaint.left, p.rcPaint.top,
2268 p.rcPaint.right - p.rcPaint.left,
2269 p.rcPaint.bottom - p.rcPaint.top,
2270 hdc2,
2271 p.rcPaint.left, p.rcPaint.top,
2272 SRCCOPY);
2273 SelectObject(hdc2, prevbm);
2274 DeleteDC(hdc2);
2275 EndPaint(hwnd, &p);
2276 }
2277 return 0;
2278 case WM_KEYDOWN:
2279 {
2280 int key = -1;
2281 BYTE keystate[256];
2282 int r = GetKeyboardState(keystate);
2283 int shift = (r && (keystate[VK_SHIFT] & 0x80)) ? MOD_SHFT : 0;
2284 int ctrl = (r && (keystate[VK_CONTROL] & 0x80)) ? MOD_CTRL : 0;
2285
2286 switch (wParam) {
2287 case VK_LEFT:
2288 if (!(lParam & 0x01000000))
2289 key = MOD_NUM_KEYPAD | '4';
2290 else
2291 key = shift | ctrl | CURSOR_LEFT;
2292 break;
2293 case VK_RIGHT:
2294 if (!(lParam & 0x01000000))
2295 key = MOD_NUM_KEYPAD | '6';
2296 else
2297 key = shift | ctrl | CURSOR_RIGHT;
2298 break;
2299 case VK_UP:
2300 if (!(lParam & 0x01000000))
2301 key = MOD_NUM_KEYPAD | '8';
2302 else
2303 key = shift | ctrl | CURSOR_UP;
2304 break;
2305 case VK_DOWN:
2306 if (!(lParam & 0x01000000))
2307 key = MOD_NUM_KEYPAD | '2';
2308 else
2309 key = shift | ctrl | CURSOR_DOWN;
2310 break;
2311 /*
2312 * Diagonal keys on the numeric keypad.
2313 */
2314 case VK_PRIOR:
2315 if (!(lParam & 0x01000000)) key = MOD_NUM_KEYPAD | '9';
2316 break;
2317 case VK_NEXT:
2318 if (!(lParam & 0x01000000)) key = MOD_NUM_KEYPAD | '3';
2319 break;
2320 case VK_HOME:
2321 if (!(lParam & 0x01000000)) key = MOD_NUM_KEYPAD | '7';
2322 break;
2323 case VK_END:
2324 if (!(lParam & 0x01000000)) key = MOD_NUM_KEYPAD | '1';
2325 break;
2326 case VK_INSERT:
2327 if (!(lParam & 0x01000000)) key = MOD_NUM_KEYPAD | '0';
2328 break;
2329 case VK_CLEAR:
2330 if (!(lParam & 0x01000000)) key = MOD_NUM_KEYPAD | '5';
2331 break;
2332 /*
2333 * Numeric keypad keys with Num Lock on.
2334 */
2335 case VK_NUMPAD4: key = MOD_NUM_KEYPAD | '4'; break;
2336 case VK_NUMPAD6: key = MOD_NUM_KEYPAD | '6'; break;
2337 case VK_NUMPAD8: key = MOD_NUM_KEYPAD | '8'; break;
2338 case VK_NUMPAD2: key = MOD_NUM_KEYPAD | '2'; break;
2339 case VK_NUMPAD5: key = MOD_NUM_KEYPAD | '5'; break;
2340 case VK_NUMPAD9: key = MOD_NUM_KEYPAD | '9'; break;
2341 case VK_NUMPAD3: key = MOD_NUM_KEYPAD | '3'; break;
2342 case VK_NUMPAD7: key = MOD_NUM_KEYPAD | '7'; break;
2343 case VK_NUMPAD1: key = MOD_NUM_KEYPAD | '1'; break;
2344 case VK_NUMPAD0: key = MOD_NUM_KEYPAD | '0'; break;
2345 }
2346
2347 if (key != -1) {
2348 if (!midend_process_key(fe->me, 0, 0, key))
2349 PostQuitMessage(0);
2350 } else {
2351 MSG m;
2352 m.hwnd = hwnd;
2353 m.message = WM_KEYDOWN;
2354 m.wParam = wParam;
2355 m.lParam = lParam & 0xdfff;
2356 TranslateMessage(&m);
2357 }
2358 }
2359 break;
2360 case WM_LBUTTONDOWN:
2361 case WM_RBUTTONDOWN:
2362 case WM_MBUTTONDOWN:
2363 {
2364 int button;
2365
2366 /*
2367 * Shift-clicks count as middle-clicks, since otherwise
2368 * two-button Windows users won't have any kind of
2369 * middle click to use.
2370 */
2371 if (message == WM_MBUTTONDOWN || (wParam & MK_SHIFT))
2372 button = MIDDLE_BUTTON;
2373 else if (message == WM_RBUTTONDOWN || is_alt_pressed())
2374 button = RIGHT_BUTTON;
2375 else
2376 button = LEFT_BUTTON;
2377
2378 if (!midend_process_key(fe->me, (signed short)LOWORD(lParam),
2379 (signed short)HIWORD(lParam), button))
2380 PostQuitMessage(0);
2381
2382 SetCapture(hwnd);
2383 }
2384 break;
2385 case WM_LBUTTONUP:
2386 case WM_RBUTTONUP:
2387 case WM_MBUTTONUP:
2388 {
2389 int button;
2390
2391 /*
2392 * Shift-clicks count as middle-clicks, since otherwise
2393 * two-button Windows users won't have any kind of
2394 * middle click to use.
2395 */
2396 if (message == WM_MBUTTONUP || (wParam & MK_SHIFT))
2397 button = MIDDLE_RELEASE;
2398 else if (message == WM_RBUTTONUP || is_alt_pressed())
2399 button = RIGHT_RELEASE;
2400 else
2401 button = LEFT_RELEASE;
2402
2403 if (!midend_process_key(fe->me, (signed short)LOWORD(lParam),
2404 (signed short)HIWORD(lParam), button))
2405 PostQuitMessage(0);
2406
2407 ReleaseCapture();
2408 }
2409 break;
2410 case WM_MOUSEMOVE:
2411 {
2412 int button;
2413
2414 if (wParam & (MK_MBUTTON | MK_SHIFT))
2415 button = MIDDLE_DRAG;
2416 else if (wParam & MK_RBUTTON || is_alt_pressed())
2417 button = RIGHT_DRAG;
2418 else
2419 button = LEFT_DRAG;
2420
2421 if (!midend_process_key(fe->me, (signed short)LOWORD(lParam),
2422 (signed short)HIWORD(lParam), button))
2423 PostQuitMessage(0);
2424 }
2425 break;
2426 case WM_CHAR:
2427 if (!midend_process_key(fe->me, 0, 0, (unsigned char)wParam))
2428 PostQuitMessage(0);
2429 return 0;
2430 case WM_TIMER:
2431 if (fe->timer) {
2432 DWORD now = GetTickCount();
2433 float elapsed = (float) (now - fe->timer_last_tickcount) * 0.001F;
2434 midend_timer(fe->me, elapsed);
2435 fe->timer_last_tickcount = now;
2436 }
2437 return 0;
2438 }
2439
2440 return DefWindowProc(hwnd, message, wParam, lParam);
2441 }
2442
2443 int WINAPI WinMain(HINSTANCE inst, HINSTANCE prev, LPSTR cmdline, int show)
2444 {
2445 MSG msg;
2446 char *error;
2447
2448 InitCommonControls();
2449
2450 if (!prev) {
2451 WNDCLASS wndclass;
2452
2453 wndclass.style = 0;
2454 wndclass.lpfnWndProc = WndProc;
2455 wndclass.cbClsExtra = 0;
2456 wndclass.cbWndExtra = 0;
2457 wndclass.hInstance = inst;
2458 wndclass.hIcon = LoadIcon(inst, MAKEINTRESOURCE(200));
2459 if (!wndclass.hIcon) /* in case resource file is absent */
2460 wndclass.hIcon = LoadIcon(inst, IDI_APPLICATION);
2461 wndclass.hCursor = LoadCursor(NULL, IDC_ARROW);
2462 wndclass.hbrBackground = NULL;
2463 wndclass.lpszMenuName = NULL;
2464 wndclass.lpszClassName = thegame.name;
2465
2466 RegisterClass(&wndclass);
2467 }
2468
2469 while (*cmdline && isspace((unsigned char)*cmdline))
2470 cmdline++;
2471
2472 init_help();
2473
2474 if (!new_window(inst, *cmdline ? cmdline : NULL, &error)) {
2475 char buf[128];
2476 sprintf(buf, "%.100s Error", thegame.name);
2477 MessageBox(NULL, error, buf, MB_OK|MB_ICONERROR);
2478 return 1;
2479 }
2480
2481 while (GetMessage(&msg, NULL, 0, 0)) {
2482 DispatchMessage(&msg);
2483 }
2484
2485 cleanup_help();
2486
2487 return msg.wParam;
2488 }