Quite a few instances of the Cardinal Error of Ctype were turned up
[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_PRESETS 0x0100
34
35 #define HELP_FILE_NAME "puzzles.hlp"
36 #define HELP_CNT_NAME "puzzles.cnt"
37
38 #ifdef DEBUGGING
39 static FILE *debug_fp = NULL;
40 static HANDLE debug_hdl = INVALID_HANDLE_VALUE;
41 static int debug_got_console = 0;
42
43 void dputs(char *buf)
44 {
45 DWORD dw;
46
47 if (!debug_got_console) {
48 if (AllocConsole()) {
49 debug_got_console = 1;
50 debug_hdl = GetStdHandle(STD_OUTPUT_HANDLE);
51 }
52 }
53 if (!debug_fp) {
54 debug_fp = fopen("debug.log", "w");
55 }
56
57 if (debug_hdl != INVALID_HANDLE_VALUE) {
58 WriteFile(debug_hdl, buf, strlen(buf), &dw, NULL);
59 }
60 fputs(buf, debug_fp);
61 fflush(debug_fp);
62 }
63
64 void debug_printf(char *fmt, ...)
65 {
66 char buf[4096];
67 va_list ap;
68
69 va_start(ap, fmt);
70 vsprintf(buf, fmt, ap);
71 dputs(buf);
72 va_end(ap);
73 }
74 #endif
75
76 struct font {
77 HFONT font;
78 int type;
79 int size;
80 };
81
82 struct cfg_aux {
83 int ctlid;
84 };
85
86 struct blitter {
87 HBITMAP bitmap;
88 frontend *fe;
89 int x, y, w, h;
90 };
91
92 struct frontend {
93 midend_data *me;
94 HWND hwnd, statusbar, cfgbox;
95 HINSTANCE inst;
96 HBITMAP bitmap, prevbm;
97 HDC hdc_bm;
98 COLORREF *colours;
99 HBRUSH *brushes;
100 HPEN *pens;
101 HRGN clip;
102 UINT timer;
103 DWORD timer_last_tickcount;
104 int npresets;
105 game_params **presets;
106 struct font *fonts;
107 int nfonts, fontsize;
108 config_item *cfg;
109 struct cfg_aux *cfgaux;
110 int cfg_which, dlg_done;
111 HFONT cfgfont;
112 char *help_path;
113 int help_has_contents;
114 char *laststatus;
115 };
116
117 void fatal(char *fmt, ...)
118 {
119 char buf[2048];
120 va_list ap;
121
122 va_start(ap, fmt);
123 vsprintf(buf, fmt, ap);
124 va_end(ap);
125
126 MessageBox(NULL, buf, "Fatal error", MB_ICONEXCLAMATION | MB_OK);
127
128 exit(1);
129 }
130
131 void get_random_seed(void **randseed, int *randseedsize)
132 {
133 time_t *tp = snew(time_t);
134 time(tp);
135 *randseed = (void *)tp;
136 *randseedsize = sizeof(time_t);
137 }
138
139 void status_bar(frontend *fe, char *text)
140 {
141 char *rewritten = midend_rewrite_statusbar(fe->me, text);
142 if (!fe->laststatus || strcmp(rewritten, fe->laststatus)) {
143 SetWindowText(fe->statusbar, rewritten);
144 sfree(fe->laststatus);
145 fe->laststatus = rewritten;
146 } else {
147 sfree(rewritten);
148 }
149 }
150
151 blitter *blitter_new(int w, int h)
152 {
153 blitter *bl = snew(blitter);
154
155 memset(bl, 0, sizeof(blitter));
156 bl->w = w;
157 bl->h = h;
158 bl->bitmap = 0;
159
160 return bl;
161 }
162
163 void blitter_free(blitter *bl)
164 {
165 if (bl->bitmap) DeleteObject(bl->bitmap);
166 sfree(bl);
167 }
168
169 static void blitter_mkbitmap(frontend *fe, blitter *bl)
170 {
171 HDC hdc = GetDC(fe->hwnd);
172 bl->bitmap = CreateCompatibleBitmap(hdc, bl->w, bl->h);
173 ReleaseDC(fe->hwnd, hdc);
174 }
175
176 /* BitBlt(dstDC, dstX, dstY, dstW, dstH, srcDC, srcX, srcY, dType) */
177
178 void blitter_save(frontend *fe, blitter *bl, int x, int y)
179 {
180 HDC hdc_win, hdc_blit;
181 HBITMAP prev_blit;
182
183 if (!bl->bitmap) blitter_mkbitmap(fe, bl);
184
185 bl->x = x; bl->y = y;
186
187 hdc_win = GetDC(fe->hwnd);
188 hdc_blit = CreateCompatibleDC(hdc_win);
189 if (!hdc_blit) fatal("hdc_blit failed: 0x%x", GetLastError());
190
191 prev_blit = SelectObject(hdc_blit, bl->bitmap);
192 if (prev_blit == NULL || prev_blit == HGDI_ERROR)
193 fatal("SelectObject for hdc_main failed: 0x%x", GetLastError());
194
195 if (!BitBlt(hdc_blit, 0, 0, bl->w, bl->h,
196 fe->hdc_bm, x, y, SRCCOPY))
197 fatal("BitBlt failed: 0x%x", GetLastError());
198
199 SelectObject(hdc_blit, prev_blit);
200 DeleteDC(hdc_blit);
201 ReleaseDC(fe->hwnd, hdc_win);
202 }
203
204 void blitter_load(frontend *fe, blitter *bl, int x, int y)
205 {
206 HDC hdc_win, hdc_blit;
207 HBITMAP prev_blit;
208
209 assert(bl->bitmap); /* we should always have saved before loading */
210
211 if (x == BLITTER_FROMSAVED) x = bl->x;
212 if (y == BLITTER_FROMSAVED) y = bl->y;
213
214 hdc_win = GetDC(fe->hwnd);
215 hdc_blit = CreateCompatibleDC(hdc_win);
216
217 prev_blit = SelectObject(hdc_blit, bl->bitmap);
218
219 BitBlt(fe->hdc_bm, x, y, bl->w, bl->h,
220 hdc_blit, 0, 0, SRCCOPY);
221
222 SelectObject(hdc_blit, prev_blit);
223 DeleteDC(hdc_blit);
224 ReleaseDC(fe->hwnd, hdc_win);
225 }
226
227 void frontend_default_colour(frontend *fe, float *output)
228 {
229 DWORD c = GetSysColor(COLOR_MENU); /* ick */
230
231 output[0] = (float)(GetRValue(c) / 255.0);
232 output[1] = (float)(GetGValue(c) / 255.0);
233 output[2] = (float)(GetBValue(c) / 255.0);
234 }
235
236 void clip(frontend *fe, int x, int y, int w, int h)
237 {
238 IntersectClipRect(fe->hdc_bm, x, y, x+w, y+h);
239 }
240
241 void unclip(frontend *fe)
242 {
243 SelectClipRgn(fe->hdc_bm, NULL);
244 }
245
246 void draw_text(frontend *fe, int x, int y, int fonttype, int fontsize,
247 int align, int colour, char *text)
248 {
249 int i;
250
251 /*
252 * Find or create the font.
253 */
254 for (i = 0; i < fe->nfonts; i++)
255 if (fe->fonts[i].type == fonttype && fe->fonts[i].size == fontsize)
256 break;
257
258 if (i == fe->nfonts) {
259 if (fe->fontsize <= fe->nfonts) {
260 fe->fontsize = fe->nfonts + 10;
261 fe->fonts = sresize(fe->fonts, fe->fontsize, struct font);
262 }
263
264 fe->nfonts++;
265
266 fe->fonts[i].type = fonttype;
267 fe->fonts[i].size = fontsize;
268
269 fe->fonts[i].font = CreateFont(-fontsize, 0, 0, 0, FW_BOLD,
270 FALSE, FALSE, FALSE, DEFAULT_CHARSET,
271 OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS,
272 DEFAULT_QUALITY,
273 (fonttype == FONT_FIXED ?
274 FIXED_PITCH | FF_DONTCARE :
275 VARIABLE_PITCH | FF_SWISS),
276 NULL);
277 }
278
279 /*
280 * Position and draw the text.
281 */
282 {
283 HFONT oldfont;
284 TEXTMETRIC tm;
285 SIZE size;
286
287 oldfont = SelectObject(fe->hdc_bm, fe->fonts[i].font);
288 if (GetTextMetrics(fe->hdc_bm, &tm)) {
289 if (align & ALIGN_VCENTRE)
290 y -= (tm.tmAscent+tm.tmDescent)/2;
291 else
292 y -= tm.tmAscent;
293 }
294 if (GetTextExtentPoint32(fe->hdc_bm, text, strlen(text), &size)) {
295 if (align & ALIGN_HCENTRE)
296 x -= size.cx / 2;
297 else if (align & ALIGN_HRIGHT)
298 x -= size.cx;
299 }
300 SetBkMode(fe->hdc_bm, TRANSPARENT);
301 SetTextColor(fe->hdc_bm, fe->colours[colour]);
302 TextOut(fe->hdc_bm, x, y, text, strlen(text));
303 SelectObject(fe->hdc_bm, oldfont);
304 }
305 }
306
307 void draw_rect(frontend *fe, int x, int y, int w, int h, int colour)
308 {
309 if (w == 1 && h == 1) {
310 /*
311 * Rectangle() appears to get uppity if asked to draw a 1x1
312 * rectangle, presumably on the grounds that that's beneath
313 * its dignity and you ought to be using SetPixel instead.
314 * So I will.
315 */
316 SetPixel(fe->hdc_bm, x, y, fe->colours[colour]);
317 } else {
318 HBRUSH oldbrush = SelectObject(fe->hdc_bm, fe->brushes[colour]);
319 HPEN oldpen = SelectObject(fe->hdc_bm, fe->pens[colour]);
320 Rectangle(fe->hdc_bm, x, y, x+w, y+h);
321 SelectObject(fe->hdc_bm, oldbrush);
322 SelectObject(fe->hdc_bm, oldpen);
323 }
324 }
325
326 void draw_line(frontend *fe, int x1, int y1, int x2, int y2, int colour)
327 {
328 HPEN oldpen = SelectObject(fe->hdc_bm, fe->pens[colour]);
329 MoveToEx(fe->hdc_bm, x1, y1, NULL);
330 LineTo(fe->hdc_bm, x2, y2);
331 SetPixel(fe->hdc_bm, x2, y2, fe->colours[colour]);
332 SelectObject(fe->hdc_bm, oldpen);
333 }
334
335 void draw_circle(frontend *fe, int cx, int cy, int radius,
336 int fillcolour, int outlinecolour)
337 {
338 assert(outlinecolour >= 0);
339
340 if (fillcolour >= 0) {
341 HBRUSH oldbrush = SelectObject(fe->hdc_bm, fe->brushes[fillcolour]);
342 HPEN oldpen = SelectObject(fe->hdc_bm, fe->pens[outlinecolour]);
343 Ellipse(fe->hdc_bm, cx - radius, cy - radius,
344 cx + radius + 1, cy + radius + 1);
345 SelectObject(fe->hdc_bm, oldbrush);
346 SelectObject(fe->hdc_bm, oldpen);
347 } else {
348 HPEN oldpen = SelectObject(fe->hdc_bm, fe->pens[outlinecolour]);
349 Arc(fe->hdc_bm, cx - radius, cy - radius,
350 cx + radius + 1, cy + radius + 1,
351 cx - radius, cy, cx - radius, cy);
352 SelectObject(fe->hdc_bm, oldpen);
353 }
354 }
355
356 void draw_polygon(frontend *fe, int *coords, int npoints,
357 int fillcolour, int outlinecolour)
358 {
359 POINT *pts = snewn(npoints+1, POINT);
360 int i;
361
362 for (i = 0; i <= npoints; i++) {
363 int j = (i < npoints ? i : 0);
364 pts[i].x = coords[j*2];
365 pts[i].y = coords[j*2+1];
366 }
367
368 assert(outlinecolour >= 0);
369
370 if (fillcolour >= 0) {
371 HBRUSH oldbrush = SelectObject(fe->hdc_bm, fe->brushes[fillcolour]);
372 HPEN oldpen = SelectObject(fe->hdc_bm, fe->pens[outlinecolour]);
373 Polygon(fe->hdc_bm, pts, npoints);
374 SelectObject(fe->hdc_bm, oldbrush);
375 SelectObject(fe->hdc_bm, oldpen);
376 } else {
377 HPEN oldpen = SelectObject(fe->hdc_bm, fe->pens[outlinecolour]);
378 Polyline(fe->hdc_bm, pts, npoints+1);
379 SelectObject(fe->hdc_bm, oldpen);
380 }
381
382 sfree(pts);
383 }
384
385 void start_draw(frontend *fe)
386 {
387 HDC hdc_win;
388 hdc_win = GetDC(fe->hwnd);
389 fe->hdc_bm = CreateCompatibleDC(hdc_win);
390 fe->prevbm = SelectObject(fe->hdc_bm, fe->bitmap);
391 ReleaseDC(fe->hwnd, hdc_win);
392 fe->clip = NULL;
393 SetMapMode(fe->hdc_bm, MM_TEXT);
394 }
395
396 void draw_update(frontend *fe, int x, int y, int w, int h)
397 {
398 RECT r;
399
400 r.left = x;
401 r.top = y;
402 r.right = x + w;
403 r.bottom = y + h;
404
405 InvalidateRect(fe->hwnd, &r, FALSE);
406 }
407
408 void end_draw(frontend *fe)
409 {
410 SelectObject(fe->hdc_bm, fe->prevbm);
411 DeleteDC(fe->hdc_bm);
412 if (fe->clip) {
413 DeleteObject(fe->clip);
414 fe->clip = NULL;
415 }
416 }
417
418 void deactivate_timer(frontend *fe)
419 {
420 KillTimer(fe->hwnd, fe->timer);
421 fe->timer = 0;
422 }
423
424 void activate_timer(frontend *fe)
425 {
426 if (!fe->timer) {
427 fe->timer = SetTimer(fe->hwnd, fe->timer, 20, NULL);
428 fe->timer_last_tickcount = GetTickCount();
429 }
430 }
431
432 void write_clip(HWND hwnd, char *data)
433 {
434 HGLOBAL clipdata;
435 int len, i, j;
436 char *data2;
437 void *lock;
438
439 /*
440 * Windows expects CRLF in the clipboard, so we must convert
441 * any \n that has come out of the puzzle backend.
442 */
443 len = 0;
444 for (i = 0; data[i]; i++) {
445 if (data[i] == '\n')
446 len++;
447 len++;
448 }
449 data2 = snewn(len+1, char);
450 j = 0;
451 for (i = 0; data[i]; i++) {
452 if (data[i] == '\n')
453 data2[j++] = '\r';
454 data2[j++] = data[i];
455 }
456 assert(j == len);
457 data2[j] = '\0';
458
459 clipdata = GlobalAlloc(GMEM_DDESHARE | GMEM_MOVEABLE, len + 1);
460 if (!clipdata)
461 return;
462 lock = GlobalLock(clipdata);
463 if (!lock)
464 return;
465 memcpy(lock, data2, len);
466 ((unsigned char *) lock)[len] = 0;
467 GlobalUnlock(clipdata);
468
469 if (OpenClipboard(hwnd)) {
470 EmptyClipboard();
471 SetClipboardData(CF_TEXT, clipdata);
472 CloseClipboard();
473 } else
474 GlobalFree(clipdata);
475
476 sfree(data2);
477 }
478
479 /*
480 * See if we can find a help file.
481 */
482 static void find_help_file(frontend *fe)
483 {
484 char b[2048], *p, *q, *r;
485 FILE *fp;
486 if (!fe->help_path) {
487 GetModuleFileName(NULL, b, sizeof(b) - 1);
488 r = b;
489 p = strrchr(b, '\\');
490 if (p && p >= r) r = p+1;
491 q = strrchr(b, ':');
492 if (q && q >= r) r = q+1;
493 strcpy(r, HELP_FILE_NAME);
494 if ( (fp = fopen(b, "r")) != NULL) {
495 fe->help_path = dupstr(b);
496 fclose(fp);
497 } else
498 fe->help_path = NULL;
499 strcpy(r, HELP_CNT_NAME);
500 if ( (fp = fopen(b, "r")) != NULL) {
501 fe->help_has_contents = TRUE;
502 fclose(fp);
503 } else
504 fe->help_has_contents = FALSE;
505 }
506 }
507
508 static void check_window_size(frontend *fe, int *px, int *py)
509 {
510 RECT r;
511 int x, y, sy;
512
513 if (fe->statusbar) {
514 RECT sr;
515 GetWindowRect(fe->statusbar, &sr);
516 sy = sr.bottom - sr.top;
517 } else {
518 sy = 0;
519 }
520
521 /*
522 * See if we actually got the window size we wanted, and adjust
523 * the puzzle size if not.
524 */
525 GetClientRect(fe->hwnd, &r);
526 x = r.right - r.left;
527 y = r.bottom - r.top - sy;
528 midend_size(fe->me, &x, &y, FALSE);
529 if (x != r.right - r.left || y != r.bottom - r.top) {
530 /*
531 * Resize the window, now we know what size we _really_
532 * want it to be.
533 */
534 r.left = r.top = 0;
535 r.right = x;
536 r.bottom = y + sy;
537 AdjustWindowRectEx(&r, WS_OVERLAPPEDWINDOW &~
538 (WS_THICKFRAME | WS_MAXIMIZEBOX | WS_OVERLAPPED),
539 TRUE, 0);
540 SetWindowPos(fe->hwnd, NULL, 0, 0, r.right - r.left, r.bottom - r.top,
541 SWP_NOMOVE | SWP_NOZORDER);
542 }
543
544 if (fe->statusbar) {
545 GetClientRect(fe->hwnd, &r);
546 SetWindowPos(fe->statusbar, NULL, 0, r.bottom-r.top-sy, r.right-r.left,
547 sy, SWP_NOZORDER);
548 }
549
550 *px = x;
551 *py = y;
552 }
553
554 static frontend *new_window(HINSTANCE inst, char *game_id, char **error)
555 {
556 frontend *fe;
557 int x, y;
558 RECT r;
559 HDC hdc;
560
561 fe = snew(frontend);
562
563 fe->me = midend_new(fe, &thegame);
564
565 if (game_id) {
566 *error = midend_game_id(fe->me, game_id);
567 if (*error) {
568 midend_free(fe->me);
569 sfree(fe);
570 return NULL;
571 }
572 }
573
574 fe->help_path = NULL;
575 find_help_file(fe);
576
577 fe->inst = inst;
578 midend_new_game(fe->me);
579
580 fe->timer = 0;
581
582 fe->fonts = NULL;
583 fe->nfonts = fe->fontsize = 0;
584
585 fe->laststatus = NULL;
586
587 {
588 int i, ncolours;
589 float *colours;
590
591 colours = midend_colours(fe->me, &ncolours);
592
593 fe->colours = snewn(ncolours, COLORREF);
594 fe->brushes = snewn(ncolours, HBRUSH);
595 fe->pens = snewn(ncolours, HPEN);
596
597 for (i = 0; i < ncolours; i++) {
598 fe->colours[i] = RGB(255 * colours[i*3+0],
599 255 * colours[i*3+1],
600 255 * colours[i*3+2]);
601 fe->brushes[i] = CreateSolidBrush(fe->colours[i]);
602 fe->pens[i] = CreatePen(PS_SOLID, 1, fe->colours[i]);
603 }
604 }
605
606 x = y = INT_MAX; /* find puzzle's preferred size */
607 midend_size(fe->me, &x, &y, FALSE);
608
609 r.left = r.top = 0;
610 r.right = x;
611 r.bottom = y;
612 AdjustWindowRectEx(&r, WS_OVERLAPPEDWINDOW &~
613 (WS_THICKFRAME | WS_MAXIMIZEBOX | WS_OVERLAPPED),
614 TRUE, 0);
615
616 fe->hwnd = CreateWindowEx(0, thegame.name, thegame.name,
617 WS_OVERLAPPEDWINDOW &~
618 (WS_THICKFRAME | WS_MAXIMIZEBOX),
619 CW_USEDEFAULT, CW_USEDEFAULT,
620 r.right - r.left, r.bottom - r.top,
621 NULL, NULL, inst, NULL);
622
623 if (midend_wants_statusbar(fe->me)) {
624 RECT sr;
625 fe->statusbar = CreateWindowEx(0, STATUSCLASSNAME, "ooh",
626 WS_CHILD | WS_VISIBLE,
627 0, 0, 0, 0, /* status bar does these */
628 fe->hwnd, NULL, inst, NULL);
629 /*
630 * Now resize the window to take account of the status bar.
631 */
632 GetWindowRect(fe->statusbar, &sr);
633 GetWindowRect(fe->hwnd, &r);
634 SetWindowPos(fe->hwnd, NULL, 0, 0, r.right - r.left,
635 r.bottom - r.top + sr.bottom - sr.top,
636 SWP_NOMOVE | SWP_NOZORDER);
637 } else {
638 fe->statusbar = NULL;
639 }
640
641 {
642 HMENU bar = CreateMenu();
643 HMENU menu = CreateMenu();
644
645 AppendMenu(bar, MF_ENABLED|MF_POPUP, (UINT)menu, "Game");
646 AppendMenu(menu, MF_ENABLED, IDM_NEW, "New");
647 AppendMenu(menu, MF_ENABLED, IDM_RESTART, "Restart");
648 AppendMenu(menu, MF_ENABLED, IDM_DESC, "Specific...");
649 AppendMenu(menu, MF_ENABLED, IDM_SEED, "Random Seed...");
650
651 if ((fe->npresets = midend_num_presets(fe->me)) > 0 ||
652 thegame.can_configure) {
653 HMENU sub = CreateMenu();
654 int i;
655
656 AppendMenu(bar, MF_ENABLED|MF_POPUP, (UINT)sub, "Type");
657
658 fe->presets = snewn(fe->npresets, game_params *);
659
660 for (i = 0; i < fe->npresets; i++) {
661 char *name;
662
663 midend_fetch_preset(fe->me, i, &name, &fe->presets[i]);
664
665 /*
666 * FIXME: we ought to go through and do something
667 * with ampersands here.
668 */
669
670 AppendMenu(sub, MF_ENABLED, IDM_PRESETS + 0x10 * i, name);
671 }
672
673 if (thegame.can_configure) {
674 AppendMenu(sub, MF_ENABLED, IDM_CONFIG, "Custom...");
675 }
676 }
677
678 AppendMenu(menu, MF_SEPARATOR, 0, 0);
679 AppendMenu(menu, MF_ENABLED, IDM_LOAD, "Load");
680 AppendMenu(menu, MF_ENABLED, IDM_SAVE, "Save");
681 AppendMenu(menu, MF_SEPARATOR, 0, 0);
682 AppendMenu(menu, MF_ENABLED, IDM_UNDO, "Undo");
683 AppendMenu(menu, MF_ENABLED, IDM_REDO, "Redo");
684 if (thegame.can_format_as_text) {
685 AppendMenu(menu, MF_SEPARATOR, 0, 0);
686 AppendMenu(menu, MF_ENABLED, IDM_COPY, "Copy");
687 }
688 if (thegame.can_solve) {
689 AppendMenu(menu, MF_SEPARATOR, 0, 0);
690 AppendMenu(menu, MF_ENABLED, IDM_SOLVE, "Solve");
691 }
692 AppendMenu(menu, MF_SEPARATOR, 0, 0);
693 AppendMenu(menu, MF_ENABLED, IDM_QUIT, "Exit");
694 menu = CreateMenu();
695 AppendMenu(bar, MF_ENABLED|MF_POPUP, (UINT)menu, "Help");
696 AppendMenu(menu, MF_ENABLED, IDM_ABOUT, "About");
697 if (fe->help_path) {
698 AppendMenu(menu, MF_SEPARATOR, 0, 0);
699 AppendMenu(menu, MF_ENABLED, IDM_HELPC, "Contents");
700 if (thegame.winhelp_topic) {
701 char *item;
702 assert(thegame.name);
703 item = snewn(9+strlen(thegame.name), char); /*ick*/
704 sprintf(item, "Help on %s", thegame.name);
705 AppendMenu(menu, MF_ENABLED, IDM_GAMEHELP, item);
706 sfree(item);
707 }
708 }
709 SetMenu(fe->hwnd, bar);
710 }
711
712 check_window_size(fe, &x, &y);
713
714 hdc = GetDC(fe->hwnd);
715 fe->bitmap = CreateCompatibleBitmap(hdc, x, y);
716 ReleaseDC(fe->hwnd, hdc);
717
718 SetWindowLong(fe->hwnd, GWL_USERDATA, (LONG)fe);
719
720 ShowWindow(fe->hwnd, SW_NORMAL);
721 SetForegroundWindow(fe->hwnd);
722
723 midend_redraw(fe->me);
724
725 return fe;
726 }
727
728 static int CALLBACK AboutDlgProc(HWND hwnd, UINT msg,
729 WPARAM wParam, LPARAM lParam)
730 {
731 frontend *fe = (frontend *)GetWindowLong(hwnd, GWL_USERDATA);
732
733 switch (msg) {
734 case WM_INITDIALOG:
735 return 0;
736
737 case WM_COMMAND:
738 if ((HIWORD(wParam) == BN_CLICKED ||
739 HIWORD(wParam) == BN_DOUBLECLICKED) &&
740 LOWORD(wParam) == IDOK)
741 fe->dlg_done = 1;
742 return 0;
743
744 case WM_CLOSE:
745 fe->dlg_done = 1;
746 return 0;
747 }
748
749 return 0;
750 }
751
752 static int CALLBACK ConfigDlgProc(HWND hwnd, UINT msg,
753 WPARAM wParam, LPARAM lParam)
754 {
755 frontend *fe = (frontend *)GetWindowLong(hwnd, GWL_USERDATA);
756 config_item *i;
757 struct cfg_aux *j;
758
759 switch (msg) {
760 case WM_INITDIALOG:
761 return 0;
762
763 case WM_COMMAND:
764 /*
765 * OK and Cancel are special cases.
766 */
767 if ((HIWORD(wParam) == BN_CLICKED ||
768 HIWORD(wParam) == BN_DOUBLECLICKED) &&
769 (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL)) {
770 if (LOWORD(wParam) == IDOK) {
771 char *err = midend_set_config(fe->me, fe->cfg_which, fe->cfg);
772
773 if (err) {
774 MessageBox(hwnd, err, "Validation error",
775 MB_ICONERROR | MB_OK);
776 } else {
777 fe->dlg_done = 2;
778 }
779 } else {
780 fe->dlg_done = 1;
781 }
782 return 0;
783 }
784
785 /*
786 * First find the control whose id this is.
787 */
788 for (i = fe->cfg, j = fe->cfgaux; i->type != C_END; i++, j++) {
789 if (j->ctlid == LOWORD(wParam))
790 break;
791 }
792 if (i->type == C_END)
793 return 0; /* not our problem */
794
795 if (i->type == C_STRING && HIWORD(wParam) == EN_CHANGE) {
796 char buffer[4096];
797 GetDlgItemText(fe->cfgbox, j->ctlid, buffer, lenof(buffer));
798 buffer[lenof(buffer)-1] = '\0';
799 sfree(i->sval);
800 i->sval = dupstr(buffer);
801 } else if (i->type == C_BOOLEAN &&
802 (HIWORD(wParam) == BN_CLICKED ||
803 HIWORD(wParam) == BN_DOUBLECLICKED)) {
804 i->ival = IsDlgButtonChecked(fe->cfgbox, j->ctlid);
805 } else if (i->type == C_CHOICES &&
806 HIWORD(wParam) == CBN_SELCHANGE) {
807 i->ival = SendDlgItemMessage(fe->cfgbox, j->ctlid,
808 CB_GETCURSEL, 0, 0);
809 }
810
811 return 0;
812
813 case WM_CLOSE:
814 fe->dlg_done = 1;
815 return 0;
816 }
817
818 return 0;
819 }
820
821 HWND mkctrl(frontend *fe, int x1, int x2, int y1, int y2,
822 char *wclass, int wstyle,
823 int exstyle, const char *wtext, int wid)
824 {
825 HWND ret;
826 ret = CreateWindowEx(exstyle, wclass, wtext,
827 wstyle | WS_CHILD | WS_VISIBLE, x1, y1, x2-x1, y2-y1,
828 fe->cfgbox, (HMENU) wid, fe->inst, NULL);
829 SendMessage(ret, WM_SETFONT, (WPARAM)fe->cfgfont, MAKELPARAM(TRUE, 0));
830 return ret;
831 }
832
833 static void about(frontend *fe)
834 {
835 int i;
836 WNDCLASS wc;
837 MSG msg;
838 TEXTMETRIC tm;
839 HDC hdc;
840 HFONT oldfont;
841 SIZE size;
842 int gm, id;
843 int winwidth, winheight, y;
844 int height, width, maxwid;
845 const char *strings[16];
846 int lengths[16];
847 int nstrings = 0;
848 char titlebuf[512];
849
850 sprintf(titlebuf, "About %.250s", thegame.name);
851
852 strings[nstrings++] = thegame.name;
853 strings[nstrings++] = "from Simon Tatham's Portable Puzzle Collection";
854 strings[nstrings++] = ver;
855
856 wc.style = CS_DBLCLKS | CS_SAVEBITS | CS_BYTEALIGNWINDOW;
857 wc.lpfnWndProc = DefDlgProc;
858 wc.cbClsExtra = 0;
859 wc.cbWndExtra = DLGWINDOWEXTRA + 8;
860 wc.hInstance = fe->inst;
861 wc.hIcon = NULL;
862 wc.hCursor = LoadCursor(NULL, IDC_ARROW);
863 wc.hbrBackground = (HBRUSH) (COLOR_BACKGROUND +1);
864 wc.lpszMenuName = NULL;
865 wc.lpszClassName = "GameAboutBox";
866 RegisterClass(&wc);
867
868 hdc = GetDC(fe->hwnd);
869 SetMapMode(hdc, MM_TEXT);
870
871 fe->dlg_done = FALSE;
872
873 fe->cfgfont = CreateFont(-MulDiv(8, GetDeviceCaps(hdc, LOGPIXELSY), 72),
874 0, 0, 0, 0,
875 FALSE, FALSE, FALSE, DEFAULT_CHARSET,
876 OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS,
877 DEFAULT_QUALITY,
878 FF_SWISS,
879 "MS Shell Dlg");
880
881 oldfont = SelectObject(hdc, fe->cfgfont);
882 if (GetTextMetrics(hdc, &tm)) {
883 height = tm.tmAscent + tm.tmDescent;
884 width = tm.tmAveCharWidth;
885 } else {
886 height = width = 30;
887 }
888
889 /*
890 * Figure out the layout of the About box by measuring the
891 * length of each piece of text.
892 */
893 maxwid = 0;
894 winheight = height/2;
895
896 for (i = 0; i < nstrings; i++) {
897 if (GetTextExtentPoint32(hdc, strings[i], strlen(strings[i]), &size))
898 lengths[i] = size.cx;
899 else
900 lengths[i] = 0; /* *shrug* */
901 if (maxwid < lengths[i])
902 maxwid = lengths[i];
903 winheight += height * 3 / 2 + (height / 2);
904 }
905
906 winheight += height + height * 7 / 4; /* OK button */
907 winwidth = maxwid + 4*width;
908
909 SelectObject(hdc, oldfont);
910 ReleaseDC(fe->hwnd, hdc);
911
912 /*
913 * Create the dialog, now that we know its size.
914 */
915 {
916 RECT r, r2;
917
918 r.left = r.top = 0;
919 r.right = winwidth;
920 r.bottom = winheight;
921
922 AdjustWindowRectEx(&r, (WS_OVERLAPPEDWINDOW /*|
923 DS_MODALFRAME | WS_POPUP | WS_VISIBLE |
924 WS_CAPTION | WS_SYSMENU*/) &~
925 (WS_MAXIMIZEBOX | WS_OVERLAPPED),
926 FALSE, 0);
927
928 /*
929 * Centre the dialog on its parent window.
930 */
931 r.right -= r.left;
932 r.bottom -= r.top;
933 GetWindowRect(fe->hwnd, &r2);
934 r.left = (r2.left + r2.right - r.right) / 2;
935 r.top = (r2.top + r2.bottom - r.bottom) / 2;
936 r.right += r.left;
937 r.bottom += r.top;
938
939 fe->cfgbox = CreateWindowEx(0, wc.lpszClassName, titlebuf,
940 DS_MODALFRAME | WS_POPUP | WS_VISIBLE |
941 WS_CAPTION | WS_SYSMENU,
942 r.left, r.top,
943 r.right-r.left, r.bottom-r.top,
944 fe->hwnd, NULL, fe->inst, NULL);
945 }
946
947 SendMessage(fe->cfgbox, WM_SETFONT, (WPARAM)fe->cfgfont, FALSE);
948
949 SetWindowLong(fe->cfgbox, GWL_USERDATA, (LONG)fe);
950 SetWindowLong(fe->cfgbox, DWL_DLGPROC, (LONG)AboutDlgProc);
951
952 id = 1000;
953 y = height/2;
954 for (i = 0; i < nstrings; i++) {
955 int border = width*2 + (maxwid - lengths[i]) / 2;
956 mkctrl(fe, border, border+lengths[i], y+height*1/8, y+height*9/8,
957 "Static", 0, 0, strings[i], id++);
958 y += height*3/2;
959
960 assert(y < winheight);
961 y += height/2;
962 }
963
964 y += height/2; /* extra space before OK */
965 mkctrl(fe, width*2, maxwid+width*2, y, y+height*7/4, "BUTTON",
966 BS_PUSHBUTTON | BS_NOTIFY | WS_TABSTOP | BS_DEFPUSHBUTTON, 0,
967 "OK", IDOK);
968
969 SendMessage(fe->cfgbox, WM_INITDIALOG, 0, 0);
970
971 EnableWindow(fe->hwnd, FALSE);
972 ShowWindow(fe->cfgbox, SW_NORMAL);
973 while ((gm=GetMessage(&msg, NULL, 0, 0)) > 0) {
974 if (!IsDialogMessage(fe->cfgbox, &msg))
975 DispatchMessage(&msg);
976 if (fe->dlg_done)
977 break;
978 }
979 EnableWindow(fe->hwnd, TRUE);
980 SetForegroundWindow(fe->hwnd);
981 DestroyWindow(fe->cfgbox);
982 DeleteObject(fe->cfgfont);
983 }
984
985 static int get_config(frontend *fe, int which)
986 {
987 config_item *i;
988 struct cfg_aux *j;
989 char *title;
990 WNDCLASS wc;
991 MSG msg;
992 TEXTMETRIC tm;
993 HDC hdc;
994 HFONT oldfont;
995 SIZE size;
996 HWND ctl;
997 int gm, id, nctrls;
998 int winwidth, winheight, col1l, col1r, col2l, col2r, y;
999 int height, width, maxlabel, maxcheckbox;
1000
1001 wc.style = CS_DBLCLKS | CS_SAVEBITS | CS_BYTEALIGNWINDOW;
1002 wc.lpfnWndProc = DefDlgProc;
1003 wc.cbClsExtra = 0;
1004 wc.cbWndExtra = DLGWINDOWEXTRA + 8;
1005 wc.hInstance = fe->inst;
1006 wc.hIcon = NULL;
1007 wc.hCursor = LoadCursor(NULL, IDC_ARROW);
1008 wc.hbrBackground = (HBRUSH) (COLOR_BACKGROUND +1);
1009 wc.lpszMenuName = NULL;
1010 wc.lpszClassName = "GameConfigBox";
1011 RegisterClass(&wc);
1012
1013 hdc = GetDC(fe->hwnd);
1014 SetMapMode(hdc, MM_TEXT);
1015
1016 fe->dlg_done = FALSE;
1017
1018 fe->cfgfont = CreateFont(-MulDiv(8, GetDeviceCaps(hdc, LOGPIXELSY), 72),
1019 0, 0, 0, 0,
1020 FALSE, FALSE, FALSE, DEFAULT_CHARSET,
1021 OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS,
1022 DEFAULT_QUALITY,
1023 FF_SWISS,
1024 "MS Shell Dlg");
1025
1026 oldfont = SelectObject(hdc, fe->cfgfont);
1027 if (GetTextMetrics(hdc, &tm)) {
1028 height = tm.tmAscent + tm.tmDescent;
1029 width = tm.tmAveCharWidth;
1030 } else {
1031 height = width = 30;
1032 }
1033
1034 fe->cfg = midend_get_config(fe->me, which, &title);
1035 fe->cfg_which = which;
1036
1037 /*
1038 * Figure out the layout of the config box by measuring the
1039 * length of each piece of text.
1040 */
1041 maxlabel = maxcheckbox = 0;
1042 winheight = height/2;
1043
1044 for (i = fe->cfg; i->type != C_END; i++) {
1045 switch (i->type) {
1046 case C_STRING:
1047 case C_CHOICES:
1048 /*
1049 * Both these control types have a label filling only
1050 * the left-hand column of the box.
1051 */
1052 if (GetTextExtentPoint32(hdc, i->name, strlen(i->name), &size) &&
1053 maxlabel < size.cx)
1054 maxlabel = size.cx;
1055 winheight += height * 3 / 2 + (height / 2);
1056 break;
1057
1058 case C_BOOLEAN:
1059 /*
1060 * Checkboxes take up the whole of the box width.
1061 */
1062 if (GetTextExtentPoint32(hdc, i->name, strlen(i->name), &size) &&
1063 maxcheckbox < size.cx)
1064 maxcheckbox = size.cx;
1065 winheight += height + (height / 2);
1066 break;
1067 }
1068 }
1069
1070 winheight += height + height * 7 / 4; /* OK / Cancel buttons */
1071
1072 col1l = 2*width;
1073 col1r = col1l + maxlabel;
1074 col2l = col1r + 2*width;
1075 col2r = col2l + 30*width;
1076 if (col2r < col1l+2*height+maxcheckbox)
1077 col2r = col1l+2*height+maxcheckbox;
1078 winwidth = col2r + 2*width;
1079
1080 SelectObject(hdc, oldfont);
1081 ReleaseDC(fe->hwnd, hdc);
1082
1083 /*
1084 * Create the dialog, now that we know its size.
1085 */
1086 {
1087 RECT r, r2;
1088
1089 r.left = r.top = 0;
1090 r.right = winwidth;
1091 r.bottom = winheight;
1092
1093 AdjustWindowRectEx(&r, (WS_OVERLAPPEDWINDOW /*|
1094 DS_MODALFRAME | WS_POPUP | WS_VISIBLE |
1095 WS_CAPTION | WS_SYSMENU*/) &~
1096 (WS_MAXIMIZEBOX | WS_OVERLAPPED),
1097 FALSE, 0);
1098
1099 /*
1100 * Centre the dialog on its parent window.
1101 */
1102 r.right -= r.left;
1103 r.bottom -= r.top;
1104 GetWindowRect(fe->hwnd, &r2);
1105 r.left = (r2.left + r2.right - r.right) / 2;
1106 r.top = (r2.top + r2.bottom - r.bottom) / 2;
1107 r.right += r.left;
1108 r.bottom += r.top;
1109
1110 fe->cfgbox = CreateWindowEx(0, wc.lpszClassName, title,
1111 DS_MODALFRAME | WS_POPUP | WS_VISIBLE |
1112 WS_CAPTION | WS_SYSMENU,
1113 r.left, r.top,
1114 r.right-r.left, r.bottom-r.top,
1115 fe->hwnd, NULL, fe->inst, NULL);
1116 sfree(title);
1117 }
1118
1119 SendMessage(fe->cfgbox, WM_SETFONT, (WPARAM)fe->cfgfont, FALSE);
1120
1121 SetWindowLong(fe->cfgbox, GWL_USERDATA, (LONG)fe);
1122 SetWindowLong(fe->cfgbox, DWL_DLGPROC, (LONG)ConfigDlgProc);
1123
1124 /*
1125 * Count the controls so we can allocate cfgaux.
1126 */
1127 for (nctrls = 0, i = fe->cfg; i->type != C_END; i++)
1128 nctrls++;
1129 fe->cfgaux = snewn(nctrls, struct cfg_aux);
1130
1131 id = 1000;
1132 y = height/2;
1133 for (i = fe->cfg, j = fe->cfgaux; i->type != C_END; i++, j++) {
1134 switch (i->type) {
1135 case C_STRING:
1136 /*
1137 * Edit box with a label beside it.
1138 */
1139 mkctrl(fe, col1l, col1r, y+height*1/8, y+height*9/8,
1140 "Static", 0, 0, i->name, id++);
1141 ctl = mkctrl(fe, col2l, col2r, y, y+height*3/2,
1142 "EDIT", WS_TABSTOP | ES_AUTOHSCROLL,
1143 WS_EX_CLIENTEDGE, "", (j->ctlid = id++));
1144 SetWindowText(ctl, i->sval);
1145 y += height*3/2;
1146 break;
1147
1148 case C_BOOLEAN:
1149 /*
1150 * Simple checkbox.
1151 */
1152 mkctrl(fe, col1l, col2r, y, y+height, "BUTTON",
1153 BS_NOTIFY | BS_AUTOCHECKBOX | WS_TABSTOP,
1154 0, i->name, (j->ctlid = id++));
1155 CheckDlgButton(fe->cfgbox, j->ctlid, (i->ival != 0));
1156 y += height;
1157 break;
1158
1159 case C_CHOICES:
1160 /*
1161 * Drop-down list with a label beside it.
1162 */
1163 mkctrl(fe, col1l, col1r, y+height*1/8, y+height*9/8,
1164 "STATIC", 0, 0, i->name, id++);
1165 ctl = mkctrl(fe, col2l, col2r, y, y+height*41/2,
1166 "COMBOBOX", WS_TABSTOP |
1167 CBS_DROPDOWNLIST | CBS_HASSTRINGS,
1168 WS_EX_CLIENTEDGE, "", (j->ctlid = id++));
1169 {
1170 char c, *p, *q, *str;
1171
1172 SendMessage(ctl, CB_RESETCONTENT, 0, 0);
1173 p = i->sval;
1174 c = *p++;
1175 while (*p) {
1176 q = p;
1177 while (*q && *q != c) q++;
1178 str = snewn(q-p+1, char);
1179 strncpy(str, p, q-p);
1180 str[q-p] = '\0';
1181 SendMessage(ctl, CB_ADDSTRING, 0, (LPARAM)str);
1182 sfree(str);
1183 if (*q) q++;
1184 p = q;
1185 }
1186 }
1187
1188 SendMessage(ctl, CB_SETCURSEL, i->ival, 0);
1189
1190 y += height*3/2;
1191 break;
1192 }
1193
1194 assert(y < winheight);
1195 y += height/2;
1196 }
1197
1198 y += height/2; /* extra space before OK and Cancel */
1199 mkctrl(fe, col1l, (col1l+col2r)/2-width, y, y+height*7/4, "BUTTON",
1200 BS_PUSHBUTTON | BS_NOTIFY | WS_TABSTOP | BS_DEFPUSHBUTTON, 0,
1201 "OK", IDOK);
1202 mkctrl(fe, (col1l+col2r)/2+width, col2r, y, y+height*7/4, "BUTTON",
1203 BS_PUSHBUTTON | BS_NOTIFY | WS_TABSTOP, 0, "Cancel", IDCANCEL);
1204
1205 SendMessage(fe->cfgbox, WM_INITDIALOG, 0, 0);
1206
1207 EnableWindow(fe->hwnd, FALSE);
1208 ShowWindow(fe->cfgbox, SW_NORMAL);
1209 while ((gm=GetMessage(&msg, NULL, 0, 0)) > 0) {
1210 if (!IsDialogMessage(fe->cfgbox, &msg))
1211 DispatchMessage(&msg);
1212 if (fe->dlg_done)
1213 break;
1214 }
1215 EnableWindow(fe->hwnd, TRUE);
1216 SetForegroundWindow(fe->hwnd);
1217 DestroyWindow(fe->cfgbox);
1218 DeleteObject(fe->cfgfont);
1219
1220 free_cfg(fe->cfg);
1221 sfree(fe->cfgaux);
1222
1223 return (fe->dlg_done == 2);
1224 }
1225
1226 static void new_game_size(frontend *fe)
1227 {
1228 RECT r, sr;
1229 HDC hdc;
1230 int x, y;
1231
1232 x = y = INT_MAX;
1233 midend_size(fe->me, &x, &y, FALSE);
1234
1235 r.left = r.top = 0;
1236 r.right = x;
1237 r.bottom = y;
1238 AdjustWindowRectEx(&r, WS_OVERLAPPEDWINDOW &~
1239 (WS_THICKFRAME | WS_MAXIMIZEBOX |
1240 WS_OVERLAPPED),
1241 TRUE, 0);
1242
1243 if (fe->statusbar != NULL) {
1244 GetWindowRect(fe->statusbar, &sr);
1245 } else {
1246 sr.left = sr.right = sr.top = sr.bottom = 0;
1247 }
1248 SetWindowPos(fe->hwnd, NULL, 0, 0,
1249 r.right - r.left,
1250 r.bottom - r.top + sr.bottom - sr.top,
1251 SWP_NOMOVE | SWP_NOZORDER);
1252
1253 check_window_size(fe, &x, &y);
1254
1255 if (fe->statusbar != NULL)
1256 SetWindowPos(fe->statusbar, NULL, 0, y, x,
1257 sr.bottom - sr.top, SWP_NOZORDER);
1258
1259 DeleteObject(fe->bitmap);
1260
1261 hdc = GetDC(fe->hwnd);
1262 fe->bitmap = CreateCompatibleBitmap(hdc, x, y);
1263 ReleaseDC(fe->hwnd, hdc);
1264
1265 midend_redraw(fe->me);
1266 }
1267
1268 static void new_game_type(frontend *fe)
1269 {
1270 midend_new_game(fe->me);
1271 new_game_size(fe);
1272 }
1273
1274 static int is_alt_pressed(void)
1275 {
1276 BYTE keystate[256];
1277 int r = GetKeyboardState(keystate);
1278 if (!r)
1279 return FALSE;
1280 if (keystate[VK_MENU] & 0x80)
1281 return TRUE;
1282 if (keystate[VK_RMENU] & 0x80)
1283 return TRUE;
1284 return FALSE;
1285 }
1286
1287 static void savefile_write(void *wctx, void *buf, int len)
1288 {
1289 FILE *fp = (FILE *)wctx;
1290 fwrite(buf, 1, len, fp);
1291 }
1292
1293 static int savefile_read(void *wctx, void *buf, int len)
1294 {
1295 FILE *fp = (FILE *)wctx;
1296 int ret;
1297
1298 ret = fread(buf, 1, len, fp);
1299 return (ret == len);
1300 }
1301
1302 static LRESULT CALLBACK WndProc(HWND hwnd, UINT message,
1303 WPARAM wParam, LPARAM lParam)
1304 {
1305 frontend *fe = (frontend *)GetWindowLong(hwnd, GWL_USERDATA);
1306 int cmd;
1307
1308 switch (message) {
1309 case WM_CLOSE:
1310 DestroyWindow(hwnd);
1311 return 0;
1312 case WM_COMMAND:
1313 cmd = wParam & ~0xF; /* low 4 bits reserved to Windows */
1314 switch (cmd) {
1315 case IDM_NEW:
1316 if (!midend_process_key(fe->me, 0, 0, 'n'))
1317 PostQuitMessage(0);
1318 break;
1319 case IDM_RESTART:
1320 midend_restart_game(fe->me);
1321 break;
1322 case IDM_UNDO:
1323 if (!midend_process_key(fe->me, 0, 0, 'u'))
1324 PostQuitMessage(0);
1325 break;
1326 case IDM_REDO:
1327 if (!midend_process_key(fe->me, 0, 0, '\x12'))
1328 PostQuitMessage(0);
1329 break;
1330 case IDM_COPY:
1331 {
1332 char *text = midend_text_format(fe->me);
1333 if (text)
1334 write_clip(hwnd, text);
1335 else
1336 MessageBeep(MB_ICONWARNING);
1337 sfree(text);
1338 }
1339 break;
1340 case IDM_SOLVE:
1341 {
1342 char *msg = midend_solve(fe->me);
1343 if (msg)
1344 MessageBox(hwnd, msg, "Unable to solve",
1345 MB_ICONERROR | MB_OK);
1346 }
1347 break;
1348 case IDM_QUIT:
1349 if (!midend_process_key(fe->me, 0, 0, 'q'))
1350 PostQuitMessage(0);
1351 break;
1352 case IDM_CONFIG:
1353 if (get_config(fe, CFG_SETTINGS))
1354 new_game_type(fe);
1355 break;
1356 case IDM_SEED:
1357 if (get_config(fe, CFG_SEED))
1358 new_game_type(fe);
1359 break;
1360 case IDM_DESC:
1361 if (get_config(fe, CFG_DESC))
1362 new_game_type(fe);
1363 break;
1364 case IDM_ABOUT:
1365 about(fe);
1366 break;
1367 case IDM_LOAD:
1368 case IDM_SAVE:
1369 {
1370 OPENFILENAME of;
1371 char filename[FILENAME_MAX];
1372 int ret;
1373
1374 memset(&of, 0, sizeof(of));
1375 of.hwndOwner = hwnd;
1376 of.lpstrFilter = "All Files (*.*)\0*\0\0\0";
1377 of.lpstrCustomFilter = NULL;
1378 of.nFilterIndex = 1;
1379 of.lpstrFile = filename;
1380 filename[0] = '\0';
1381 of.nMaxFile = lenof(filename);
1382 of.lpstrFileTitle = NULL;
1383 of.lpstrTitle = (cmd == IDM_SAVE ?
1384 "Enter name of game file to save" :
1385 "Enter name of saved game file to load");
1386 of.Flags = 0;
1387 #ifdef OPENFILENAME_SIZE_VERSION_400
1388 of.lStructSize = OPENFILENAME_SIZE_VERSION_400;
1389 #else
1390 of.lStructSize = sizeof(of);
1391 #endif
1392 of.lpstrInitialDir = NULL;
1393
1394 if (cmd == IDM_SAVE)
1395 ret = GetSaveFileName(&of);
1396 else
1397 ret = GetOpenFileName(&of);
1398
1399 if (ret) {
1400 if (cmd == IDM_SAVE) {
1401 FILE *fp;
1402
1403 if ((fp = fopen(filename, "r")) != NULL) {
1404 char buf[256 + FILENAME_MAX];
1405 fclose(fp);
1406 /* file exists */
1407
1408 sprintf(buf, "Are you sure you want to overwrite"
1409 " the file \"%.*s\"?",
1410 FILENAME_MAX, filename);
1411 if (MessageBox(hwnd, buf, "Question",
1412 MB_YESNO | MB_ICONQUESTION)
1413 != IDYES)
1414 break;
1415 }
1416
1417 fp = fopen(filename, "w");
1418
1419 if (!fp) {
1420 MessageBox(hwnd, "Unable to open save file",
1421 "Error", MB_ICONERROR | MB_OK);
1422 break;
1423 }
1424
1425 midend_serialise(fe->me, savefile_write, fp);
1426
1427 fclose(fp);
1428 } else {
1429 FILE *fp = fopen(filename, "r");
1430 char *err;
1431
1432 if (!fp) {
1433 MessageBox(hwnd, "Unable to open saved game file",
1434 "Error", MB_ICONERROR | MB_OK);
1435 break;
1436 }
1437
1438 err = midend_deserialise(fe->me, savefile_read, fp);
1439
1440 fclose(fp);
1441
1442 if (err) {
1443 MessageBox(hwnd, err, "Error", MB_ICONERROR|MB_OK);
1444 break;
1445 }
1446
1447 new_game_size(fe);
1448 }
1449 }
1450 }
1451
1452 break;
1453 case IDM_HELPC:
1454 assert(fe->help_path);
1455 WinHelp(hwnd, fe->help_path,
1456 fe->help_has_contents ? HELP_FINDER : HELP_CONTENTS, 0);
1457 break;
1458 case IDM_GAMEHELP:
1459 assert(fe->help_path);
1460 assert(thegame.winhelp_topic);
1461 {
1462 char *cmd = snewn(10+strlen(thegame.winhelp_topic), char);
1463 sprintf(cmd, "JI(`',`%s')", thegame.winhelp_topic);
1464 WinHelp(hwnd, fe->help_path, HELP_COMMAND, (DWORD)cmd);
1465 sfree(cmd);
1466 }
1467 break;
1468 default:
1469 {
1470 int p = ((wParam &~ 0xF) - IDM_PRESETS) / 0x10;
1471
1472 if (p >= 0 && p < fe->npresets) {
1473 midend_set_params(fe->me, fe->presets[p]);
1474 new_game_type(fe);
1475 }
1476 }
1477 break;
1478 }
1479 break;
1480 case WM_DESTROY:
1481 PostQuitMessage(0);
1482 return 0;
1483 case WM_PAINT:
1484 {
1485 PAINTSTRUCT p;
1486 HDC hdc, hdc2;
1487 HBITMAP prevbm;
1488
1489 hdc = BeginPaint(hwnd, &p);
1490 hdc2 = CreateCompatibleDC(hdc);
1491 prevbm = SelectObject(hdc2, fe->bitmap);
1492 BitBlt(hdc,
1493 p.rcPaint.left, p.rcPaint.top,
1494 p.rcPaint.right - p.rcPaint.left,
1495 p.rcPaint.bottom - p.rcPaint.top,
1496 hdc2,
1497 p.rcPaint.left, p.rcPaint.top,
1498 SRCCOPY);
1499 SelectObject(hdc2, prevbm);
1500 DeleteDC(hdc2);
1501 EndPaint(hwnd, &p);
1502 }
1503 return 0;
1504 case WM_KEYDOWN:
1505 {
1506 int key = -1;
1507 BYTE keystate[256];
1508 int r = GetKeyboardState(keystate);
1509 int shift = (r && (keystate[VK_SHIFT] & 0x80)) ? MOD_SHFT : 0;
1510 int ctrl = (r && (keystate[VK_CONTROL] & 0x80)) ? MOD_CTRL : 0;
1511
1512 switch (wParam) {
1513 case VK_LEFT:
1514 if (!(lParam & 0x01000000))
1515 key = MOD_NUM_KEYPAD | '4';
1516 else
1517 key = shift | ctrl | CURSOR_LEFT;
1518 break;
1519 case VK_RIGHT:
1520 if (!(lParam & 0x01000000))
1521 key = MOD_NUM_KEYPAD | '6';
1522 else
1523 key = shift | ctrl | CURSOR_RIGHT;
1524 break;
1525 case VK_UP:
1526 if (!(lParam & 0x01000000))
1527 key = MOD_NUM_KEYPAD | '8';
1528 else
1529 key = shift | ctrl | CURSOR_UP;
1530 break;
1531 case VK_DOWN:
1532 if (!(lParam & 0x01000000))
1533 key = MOD_NUM_KEYPAD | '2';
1534 else
1535 key = shift | ctrl | CURSOR_DOWN;
1536 break;
1537 /*
1538 * Diagonal keys on the numeric keypad.
1539 */
1540 case VK_PRIOR:
1541 if (!(lParam & 0x01000000)) key = MOD_NUM_KEYPAD | '9';
1542 break;
1543 case VK_NEXT:
1544 if (!(lParam & 0x01000000)) key = MOD_NUM_KEYPAD | '3';
1545 break;
1546 case VK_HOME:
1547 if (!(lParam & 0x01000000)) key = MOD_NUM_KEYPAD | '7';
1548 break;
1549 case VK_END:
1550 if (!(lParam & 0x01000000)) key = MOD_NUM_KEYPAD | '1';
1551 break;
1552 case VK_INSERT:
1553 if (!(lParam & 0x01000000)) key = MOD_NUM_KEYPAD | '0';
1554 break;
1555 case VK_CLEAR:
1556 if (!(lParam & 0x01000000)) key = MOD_NUM_KEYPAD | '5';
1557 break;
1558 /*
1559 * Numeric keypad keys with Num Lock on.
1560 */
1561 case VK_NUMPAD4: key = MOD_NUM_KEYPAD | '4'; break;
1562 case VK_NUMPAD6: key = MOD_NUM_KEYPAD | '6'; break;
1563 case VK_NUMPAD8: key = MOD_NUM_KEYPAD | '8'; break;
1564 case VK_NUMPAD2: key = MOD_NUM_KEYPAD | '2'; break;
1565 case VK_NUMPAD5: key = MOD_NUM_KEYPAD | '5'; break;
1566 case VK_NUMPAD9: key = MOD_NUM_KEYPAD | '9'; break;
1567 case VK_NUMPAD3: key = MOD_NUM_KEYPAD | '3'; break;
1568 case VK_NUMPAD7: key = MOD_NUM_KEYPAD | '7'; break;
1569 case VK_NUMPAD1: key = MOD_NUM_KEYPAD | '1'; break;
1570 case VK_NUMPAD0: key = MOD_NUM_KEYPAD | '0'; break;
1571 }
1572
1573 if (key != -1) {
1574 if (!midend_process_key(fe->me, 0, 0, key))
1575 PostQuitMessage(0);
1576 } else {
1577 MSG m;
1578 m.hwnd = hwnd;
1579 m.message = WM_KEYDOWN;
1580 m.wParam = wParam;
1581 m.lParam = lParam & 0xdfff;
1582 TranslateMessage(&m);
1583 }
1584 }
1585 break;
1586 case WM_LBUTTONDOWN:
1587 case WM_RBUTTONDOWN:
1588 case WM_MBUTTONDOWN:
1589 {
1590 int button;
1591
1592 /*
1593 * Shift-clicks count as middle-clicks, since otherwise
1594 * two-button Windows users won't have any kind of
1595 * middle click to use.
1596 */
1597 if (message == WM_MBUTTONDOWN || (wParam & MK_SHIFT))
1598 button = MIDDLE_BUTTON;
1599 else if (message == WM_RBUTTONDOWN || is_alt_pressed())
1600 button = RIGHT_BUTTON;
1601 else
1602 button = LEFT_BUTTON;
1603
1604 if (!midend_process_key(fe->me, (signed short)LOWORD(lParam),
1605 (signed short)HIWORD(lParam), button))
1606 PostQuitMessage(0);
1607
1608 SetCapture(hwnd);
1609 }
1610 break;
1611 case WM_LBUTTONUP:
1612 case WM_RBUTTONUP:
1613 case WM_MBUTTONUP:
1614 {
1615 int button;
1616
1617 /*
1618 * Shift-clicks count as middle-clicks, since otherwise
1619 * two-button Windows users won't have any kind of
1620 * middle click to use.
1621 */
1622 if (message == WM_MBUTTONUP || (wParam & MK_SHIFT))
1623 button = MIDDLE_RELEASE;
1624 else if (message == WM_RBUTTONUP || is_alt_pressed())
1625 button = RIGHT_RELEASE;
1626 else
1627 button = LEFT_RELEASE;
1628
1629 if (!midend_process_key(fe->me, (signed short)LOWORD(lParam),
1630 (signed short)HIWORD(lParam), button))
1631 PostQuitMessage(0);
1632
1633 ReleaseCapture();
1634 }
1635 break;
1636 case WM_MOUSEMOVE:
1637 {
1638 int button;
1639
1640 if (wParam & (MK_MBUTTON | MK_SHIFT))
1641 button = MIDDLE_DRAG;
1642 else if (wParam & MK_RBUTTON || is_alt_pressed())
1643 button = RIGHT_DRAG;
1644 else
1645 button = LEFT_DRAG;
1646
1647 if (!midend_process_key(fe->me, (signed short)LOWORD(lParam),
1648 (signed short)HIWORD(lParam), button))
1649 PostQuitMessage(0);
1650 }
1651 break;
1652 case WM_CHAR:
1653 if (!midend_process_key(fe->me, 0, 0, (unsigned char)wParam))
1654 PostQuitMessage(0);
1655 return 0;
1656 case WM_TIMER:
1657 if (fe->timer) {
1658 DWORD now = GetTickCount();
1659 float elapsed = (float) (now - fe->timer_last_tickcount) * 0.001F;
1660 midend_timer(fe->me, elapsed);
1661 fe->timer_last_tickcount = now;
1662 }
1663 return 0;
1664 }
1665
1666 return DefWindowProc(hwnd, message, wParam, lParam);
1667 }
1668
1669 int WINAPI WinMain(HINSTANCE inst, HINSTANCE prev, LPSTR cmdline, int show)
1670 {
1671 MSG msg;
1672 char *error;
1673
1674 InitCommonControls();
1675
1676 if (!prev) {
1677 WNDCLASS wndclass;
1678
1679 wndclass.style = 0;
1680 wndclass.lpfnWndProc = WndProc;
1681 wndclass.cbClsExtra = 0;
1682 wndclass.cbWndExtra = 0;
1683 wndclass.hInstance = inst;
1684 wndclass.hIcon = LoadIcon(inst, IDI_APPLICATION);
1685 wndclass.hCursor = LoadCursor(NULL, IDC_ARROW);
1686 wndclass.hbrBackground = NULL;
1687 wndclass.lpszMenuName = NULL;
1688 wndclass.lpszClassName = thegame.name;
1689
1690 RegisterClass(&wndclass);
1691 }
1692
1693 while (*cmdline && isspace((unsigned char)*cmdline))
1694 cmdline++;
1695
1696 if (!new_window(inst, *cmdline ? cmdline : NULL, &error)) {
1697 char buf[128];
1698 sprintf(buf, "%.100s Error", thegame.name);
1699 MessageBox(NULL, error, buf, MB_OK|MB_ICONERROR);
1700 return 1;
1701 }
1702
1703 while (GetMessage(&msg, NULL, 0, 0)) {
1704 DispatchMessage(&msg);
1705 }
1706
1707 return msg.wParam;
1708 }