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