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