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