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