Cleanups from James H: a few missing statics, a precautionary cast
[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 if (fe->hwnd) 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
579 fe->timer = 0;
580 fe->hwnd = NULL;
581
582 midend_new_game(fe->me);
583
584 fe->fonts = NULL;
585 fe->nfonts = fe->fontsize = 0;
586
587 fe->laststatus = NULL;
588
589 {
590 int i, ncolours;
591 float *colours;
592
593 colours = midend_colours(fe->me, &ncolours);
594
595 fe->colours = snewn(ncolours, COLORREF);
596 fe->brushes = snewn(ncolours, HBRUSH);
597 fe->pens = snewn(ncolours, HPEN);
598
599 for (i = 0; i < ncolours; i++) {
600 fe->colours[i] = RGB(255 * colours[i*3+0],
601 255 * colours[i*3+1],
602 255 * colours[i*3+2]);
603 fe->brushes[i] = CreateSolidBrush(fe->colours[i]);
604 fe->pens[i] = CreatePen(PS_SOLID, 1, fe->colours[i]);
605 }
606 }
607
608 x = y = INT_MAX; /* find puzzle's preferred size */
609 midend_size(fe->me, &x, &y, FALSE);
610
611 r.left = r.top = 0;
612 r.right = x;
613 r.bottom = y;
614 AdjustWindowRectEx(&r, WS_OVERLAPPEDWINDOW &~
615 (WS_THICKFRAME | WS_MAXIMIZEBOX | WS_OVERLAPPED),
616 TRUE, 0);
617
618 fe->hwnd = CreateWindowEx(0, thegame.name, thegame.name,
619 WS_OVERLAPPEDWINDOW &~
620 (WS_THICKFRAME | WS_MAXIMIZEBOX),
621 CW_USEDEFAULT, CW_USEDEFAULT,
622 r.right - r.left, r.bottom - r.top,
623 NULL, NULL, inst, NULL);
624
625 if (midend_wants_statusbar(fe->me)) {
626 RECT sr;
627 fe->statusbar = CreateWindowEx(0, STATUSCLASSNAME, "ooh",
628 WS_CHILD | WS_VISIBLE,
629 0, 0, 0, 0, /* status bar does these */
630 fe->hwnd, NULL, inst, NULL);
631 /*
632 * Now resize the window to take account of the status bar.
633 */
634 GetWindowRect(fe->statusbar, &sr);
635 GetWindowRect(fe->hwnd, &r);
636 SetWindowPos(fe->hwnd, NULL, 0, 0, r.right - r.left,
637 r.bottom - r.top + sr.bottom - sr.top,
638 SWP_NOMOVE | SWP_NOZORDER);
639 } else {
640 fe->statusbar = NULL;
641 }
642
643 {
644 HMENU bar = CreateMenu();
645 HMENU menu = CreateMenu();
646
647 AppendMenu(bar, MF_ENABLED|MF_POPUP, (UINT)menu, "Game");
648 AppendMenu(menu, MF_ENABLED, IDM_NEW, "New");
649 AppendMenu(menu, MF_ENABLED, IDM_RESTART, "Restart");
650 AppendMenu(menu, MF_ENABLED, IDM_DESC, "Specific...");
651 AppendMenu(menu, MF_ENABLED, IDM_SEED, "Random Seed...");
652
653 if ((fe->npresets = midend_num_presets(fe->me)) > 0 ||
654 thegame.can_configure) {
655 HMENU sub = CreateMenu();
656 int i;
657
658 AppendMenu(bar, MF_ENABLED|MF_POPUP, (UINT)sub, "Type");
659
660 fe->presets = snewn(fe->npresets, game_params *);
661
662 for (i = 0; i < fe->npresets; i++) {
663 char *name;
664
665 midend_fetch_preset(fe->me, i, &name, &fe->presets[i]);
666
667 /*
668 * FIXME: we ought to go through and do something
669 * with ampersands here.
670 */
671
672 AppendMenu(sub, MF_ENABLED, IDM_PRESETS + 0x10 * i, name);
673 }
674
675 if (thegame.can_configure) {
676 AppendMenu(sub, MF_ENABLED, IDM_CONFIG, "Custom...");
677 }
678 }
679
680 AppendMenu(menu, MF_SEPARATOR, 0, 0);
681 AppendMenu(menu, MF_ENABLED, IDM_LOAD, "Load");
682 AppendMenu(menu, MF_ENABLED, IDM_SAVE, "Save");
683 AppendMenu(menu, MF_SEPARATOR, 0, 0);
684 AppendMenu(menu, MF_ENABLED, IDM_UNDO, "Undo");
685 AppendMenu(menu, MF_ENABLED, IDM_REDO, "Redo");
686 if (thegame.can_format_as_text) {
687 AppendMenu(menu, MF_SEPARATOR, 0, 0);
688 AppendMenu(menu, MF_ENABLED, IDM_COPY, "Copy");
689 }
690 if (thegame.can_solve) {
691 AppendMenu(menu, MF_SEPARATOR, 0, 0);
692 AppendMenu(menu, MF_ENABLED, IDM_SOLVE, "Solve");
693 }
694 AppendMenu(menu, MF_SEPARATOR, 0, 0);
695 AppendMenu(menu, MF_ENABLED, IDM_QUIT, "Exit");
696 menu = CreateMenu();
697 AppendMenu(bar, MF_ENABLED|MF_POPUP, (UINT)menu, "Help");
698 AppendMenu(menu, MF_ENABLED, IDM_ABOUT, "About");
699 if (fe->help_path) {
700 AppendMenu(menu, MF_SEPARATOR, 0, 0);
701 AppendMenu(menu, MF_ENABLED, IDM_HELPC, "Contents");
702 if (thegame.winhelp_topic) {
703 char *item;
704 assert(thegame.name);
705 item = snewn(9+strlen(thegame.name), char); /*ick*/
706 sprintf(item, "Help on %s", thegame.name);
707 AppendMenu(menu, MF_ENABLED, IDM_GAMEHELP, item);
708 sfree(item);
709 }
710 }
711 SetMenu(fe->hwnd, bar);
712 }
713
714 check_window_size(fe, &x, &y);
715
716 hdc = GetDC(fe->hwnd);
717 fe->bitmap = CreateCompatibleBitmap(hdc, x, y);
718 ReleaseDC(fe->hwnd, hdc);
719
720 SetWindowLong(fe->hwnd, GWL_USERDATA, (LONG)fe);
721
722 ShowWindow(fe->hwnd, SW_NORMAL);
723 SetForegroundWindow(fe->hwnd);
724
725 midend_redraw(fe->me);
726
727 return fe;
728 }
729
730 static int CALLBACK AboutDlgProc(HWND hwnd, UINT msg,
731 WPARAM wParam, LPARAM lParam)
732 {
733 frontend *fe = (frontend *)GetWindowLong(hwnd, GWL_USERDATA);
734
735 switch (msg) {
736 case WM_INITDIALOG:
737 return 0;
738
739 case WM_COMMAND:
740 if ((HIWORD(wParam) == BN_CLICKED ||
741 HIWORD(wParam) == BN_DOUBLECLICKED) &&
742 LOWORD(wParam) == IDOK)
743 fe->dlg_done = 1;
744 return 0;
745
746 case WM_CLOSE:
747 fe->dlg_done = 1;
748 return 0;
749 }
750
751 return 0;
752 }
753
754 static int CALLBACK ConfigDlgProc(HWND hwnd, UINT msg,
755 WPARAM wParam, LPARAM lParam)
756 {
757 frontend *fe = (frontend *)GetWindowLong(hwnd, GWL_USERDATA);
758 config_item *i;
759 struct cfg_aux *j;
760
761 switch (msg) {
762 case WM_INITDIALOG:
763 return 0;
764
765 case WM_COMMAND:
766 /*
767 * OK and Cancel are special cases.
768 */
769 if ((HIWORD(wParam) == BN_CLICKED ||
770 HIWORD(wParam) == BN_DOUBLECLICKED) &&
771 (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL)) {
772 if (LOWORD(wParam) == IDOK) {
773 char *err = midend_set_config(fe->me, fe->cfg_which, fe->cfg);
774
775 if (err) {
776 MessageBox(hwnd, err, "Validation error",
777 MB_ICONERROR | MB_OK);
778 } else {
779 fe->dlg_done = 2;
780 }
781 } else {
782 fe->dlg_done = 1;
783 }
784 return 0;
785 }
786
787 /*
788 * First find the control whose id this is.
789 */
790 for (i = fe->cfg, j = fe->cfgaux; i->type != C_END; i++, j++) {
791 if (j->ctlid == LOWORD(wParam))
792 break;
793 }
794 if (i->type == C_END)
795 return 0; /* not our problem */
796
797 if (i->type == C_STRING && HIWORD(wParam) == EN_CHANGE) {
798 char buffer[4096];
799 GetDlgItemText(fe->cfgbox, j->ctlid, buffer, lenof(buffer));
800 buffer[lenof(buffer)-1] = '\0';
801 sfree(i->sval);
802 i->sval = dupstr(buffer);
803 } else if (i->type == C_BOOLEAN &&
804 (HIWORD(wParam) == BN_CLICKED ||
805 HIWORD(wParam) == BN_DOUBLECLICKED)) {
806 i->ival = IsDlgButtonChecked(fe->cfgbox, j->ctlid);
807 } else if (i->type == C_CHOICES &&
808 HIWORD(wParam) == CBN_SELCHANGE) {
809 i->ival = SendDlgItemMessage(fe->cfgbox, j->ctlid,
810 CB_GETCURSEL, 0, 0);
811 }
812
813 return 0;
814
815 case WM_CLOSE:
816 fe->dlg_done = 1;
817 return 0;
818 }
819
820 return 0;
821 }
822
823 HWND mkctrl(frontend *fe, int x1, int x2, int y1, int y2,
824 char *wclass, int wstyle,
825 int exstyle, const char *wtext, int wid)
826 {
827 HWND ret;
828 ret = CreateWindowEx(exstyle, wclass, wtext,
829 wstyle | WS_CHILD | WS_VISIBLE, x1, y1, x2-x1, y2-y1,
830 fe->cfgbox, (HMENU) wid, fe->inst, NULL);
831 SendMessage(ret, WM_SETFONT, (WPARAM)fe->cfgfont, MAKELPARAM(TRUE, 0));
832 return ret;
833 }
834
835 static void about(frontend *fe)
836 {
837 int i;
838 WNDCLASS wc;
839 MSG msg;
840 TEXTMETRIC tm;
841 HDC hdc;
842 HFONT oldfont;
843 SIZE size;
844 int gm, id;
845 int winwidth, winheight, y;
846 int height, width, maxwid;
847 const char *strings[16];
848 int lengths[16];
849 int nstrings = 0;
850 char titlebuf[512];
851
852 sprintf(titlebuf, "About %.250s", thegame.name);
853
854 strings[nstrings++] = thegame.name;
855 strings[nstrings++] = "from Simon Tatham's Portable Puzzle Collection";
856 strings[nstrings++] = ver;
857
858 wc.style = CS_DBLCLKS | CS_SAVEBITS | CS_BYTEALIGNWINDOW;
859 wc.lpfnWndProc = DefDlgProc;
860 wc.cbClsExtra = 0;
861 wc.cbWndExtra = DLGWINDOWEXTRA + 8;
862 wc.hInstance = fe->inst;
863 wc.hIcon = NULL;
864 wc.hCursor = LoadCursor(NULL, IDC_ARROW);
865 wc.hbrBackground = (HBRUSH) (COLOR_BACKGROUND +1);
866 wc.lpszMenuName = NULL;
867 wc.lpszClassName = "GameAboutBox";
868 RegisterClass(&wc);
869
870 hdc = GetDC(fe->hwnd);
871 SetMapMode(hdc, MM_TEXT);
872
873 fe->dlg_done = FALSE;
874
875 fe->cfgfont = CreateFont(-MulDiv(8, GetDeviceCaps(hdc, LOGPIXELSY), 72),
876 0, 0, 0, 0,
877 FALSE, FALSE, FALSE, DEFAULT_CHARSET,
878 OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS,
879 DEFAULT_QUALITY,
880 FF_SWISS,
881 "MS Shell Dlg");
882
883 oldfont = SelectObject(hdc, fe->cfgfont);
884 if (GetTextMetrics(hdc, &tm)) {
885 height = tm.tmAscent + tm.tmDescent;
886 width = tm.tmAveCharWidth;
887 } else {
888 height = width = 30;
889 }
890
891 /*
892 * Figure out the layout of the About box by measuring the
893 * length of each piece of text.
894 */
895 maxwid = 0;
896 winheight = height/2;
897
898 for (i = 0; i < nstrings; i++) {
899 if (GetTextExtentPoint32(hdc, strings[i], strlen(strings[i]), &size))
900 lengths[i] = size.cx;
901 else
902 lengths[i] = 0; /* *shrug* */
903 if (maxwid < lengths[i])
904 maxwid = lengths[i];
905 winheight += height * 3 / 2 + (height / 2);
906 }
907
908 winheight += height + height * 7 / 4; /* OK button */
909 winwidth = maxwid + 4*width;
910
911 SelectObject(hdc, oldfont);
912 ReleaseDC(fe->hwnd, hdc);
913
914 /*
915 * Create the dialog, now that we know its size.
916 */
917 {
918 RECT r, r2;
919
920 r.left = r.top = 0;
921 r.right = winwidth;
922 r.bottom = winheight;
923
924 AdjustWindowRectEx(&r, (WS_OVERLAPPEDWINDOW /*|
925 DS_MODALFRAME | WS_POPUP | WS_VISIBLE |
926 WS_CAPTION | WS_SYSMENU*/) &~
927 (WS_MAXIMIZEBOX | WS_OVERLAPPED),
928 FALSE, 0);
929
930 /*
931 * Centre the dialog on its parent window.
932 */
933 r.right -= r.left;
934 r.bottom -= r.top;
935 GetWindowRect(fe->hwnd, &r2);
936 r.left = (r2.left + r2.right - r.right) / 2;
937 r.top = (r2.top + r2.bottom - r.bottom) / 2;
938 r.right += r.left;
939 r.bottom += r.top;
940
941 fe->cfgbox = CreateWindowEx(0, wc.lpszClassName, titlebuf,
942 DS_MODALFRAME | WS_POPUP | WS_VISIBLE |
943 WS_CAPTION | WS_SYSMENU,
944 r.left, r.top,
945 r.right-r.left, r.bottom-r.top,
946 fe->hwnd, NULL, fe->inst, NULL);
947 }
948
949 SendMessage(fe->cfgbox, WM_SETFONT, (WPARAM)fe->cfgfont, FALSE);
950
951 SetWindowLong(fe->cfgbox, GWL_USERDATA, (LONG)fe);
952 SetWindowLong(fe->cfgbox, DWL_DLGPROC, (LONG)AboutDlgProc);
953
954 id = 1000;
955 y = height/2;
956 for (i = 0; i < nstrings; i++) {
957 int border = width*2 + (maxwid - lengths[i]) / 2;
958 mkctrl(fe, border, border+lengths[i], y+height*1/8, y+height*9/8,
959 "Static", 0, 0, strings[i], id++);
960 y += height*3/2;
961
962 assert(y < winheight);
963 y += height/2;
964 }
965
966 y += height/2; /* extra space before OK */
967 mkctrl(fe, width*2, maxwid+width*2, y, y+height*7/4, "BUTTON",
968 BS_PUSHBUTTON | BS_NOTIFY | WS_TABSTOP | BS_DEFPUSHBUTTON, 0,
969 "OK", IDOK);
970
971 SendMessage(fe->cfgbox, WM_INITDIALOG, 0, 0);
972
973 EnableWindow(fe->hwnd, FALSE);
974 ShowWindow(fe->cfgbox, SW_NORMAL);
975 while ((gm=GetMessage(&msg, NULL, 0, 0)) > 0) {
976 if (!IsDialogMessage(fe->cfgbox, &msg))
977 DispatchMessage(&msg);
978 if (fe->dlg_done)
979 break;
980 }
981 EnableWindow(fe->hwnd, TRUE);
982 SetForegroundWindow(fe->hwnd);
983 DestroyWindow(fe->cfgbox);
984 DeleteObject(fe->cfgfont);
985 }
986
987 static int get_config(frontend *fe, int which)
988 {
989 config_item *i;
990 struct cfg_aux *j;
991 char *title;
992 WNDCLASS wc;
993 MSG msg;
994 TEXTMETRIC tm;
995 HDC hdc;
996 HFONT oldfont;
997 SIZE size;
998 HWND ctl;
999 int gm, id, nctrls;
1000 int winwidth, winheight, col1l, col1r, col2l, col2r, y;
1001 int height, width, maxlabel, maxcheckbox;
1002
1003 wc.style = CS_DBLCLKS | CS_SAVEBITS | CS_BYTEALIGNWINDOW;
1004 wc.lpfnWndProc = DefDlgProc;
1005 wc.cbClsExtra = 0;
1006 wc.cbWndExtra = DLGWINDOWEXTRA + 8;
1007 wc.hInstance = fe->inst;
1008 wc.hIcon = NULL;
1009 wc.hCursor = LoadCursor(NULL, IDC_ARROW);
1010 wc.hbrBackground = (HBRUSH) (COLOR_BACKGROUND +1);
1011 wc.lpszMenuName = NULL;
1012 wc.lpszClassName = "GameConfigBox";
1013 RegisterClass(&wc);
1014
1015 hdc = GetDC(fe->hwnd);
1016 SetMapMode(hdc, MM_TEXT);
1017
1018 fe->dlg_done = FALSE;
1019
1020 fe->cfgfont = CreateFont(-MulDiv(8, GetDeviceCaps(hdc, LOGPIXELSY), 72),
1021 0, 0, 0, 0,
1022 FALSE, FALSE, FALSE, DEFAULT_CHARSET,
1023 OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS,
1024 DEFAULT_QUALITY,
1025 FF_SWISS,
1026 "MS Shell Dlg");
1027
1028 oldfont = SelectObject(hdc, fe->cfgfont);
1029 if (GetTextMetrics(hdc, &tm)) {
1030 height = tm.tmAscent + tm.tmDescent;
1031 width = tm.tmAveCharWidth;
1032 } else {
1033 height = width = 30;
1034 }
1035
1036 fe->cfg = midend_get_config(fe->me, which, &title);
1037 fe->cfg_which = which;
1038
1039 /*
1040 * Figure out the layout of the config box by measuring the
1041 * length of each piece of text.
1042 */
1043 maxlabel = maxcheckbox = 0;
1044 winheight = height/2;
1045
1046 for (i = fe->cfg; i->type != C_END; i++) {
1047 switch (i->type) {
1048 case C_STRING:
1049 case C_CHOICES:
1050 /*
1051 * Both these control types have a label filling only
1052 * the left-hand column of the box.
1053 */
1054 if (GetTextExtentPoint32(hdc, i->name, strlen(i->name), &size) &&
1055 maxlabel < size.cx)
1056 maxlabel = size.cx;
1057 winheight += height * 3 / 2 + (height / 2);
1058 break;
1059
1060 case C_BOOLEAN:
1061 /*
1062 * Checkboxes take up the whole of the box width.
1063 */
1064 if (GetTextExtentPoint32(hdc, i->name, strlen(i->name), &size) &&
1065 maxcheckbox < size.cx)
1066 maxcheckbox = size.cx;
1067 winheight += height + (height / 2);
1068 break;
1069 }
1070 }
1071
1072 winheight += height + height * 7 / 4; /* OK / Cancel buttons */
1073
1074 col1l = 2*width;
1075 col1r = col1l + maxlabel;
1076 col2l = col1r + 2*width;
1077 col2r = col2l + 30*width;
1078 if (col2r < col1l+2*height+maxcheckbox)
1079 col2r = col1l+2*height+maxcheckbox;
1080 winwidth = col2r + 2*width;
1081
1082 SelectObject(hdc, oldfont);
1083 ReleaseDC(fe->hwnd, hdc);
1084
1085 /*
1086 * Create the dialog, now that we know its size.
1087 */
1088 {
1089 RECT r, r2;
1090
1091 r.left = r.top = 0;
1092 r.right = winwidth;
1093 r.bottom = winheight;
1094
1095 AdjustWindowRectEx(&r, (WS_OVERLAPPEDWINDOW /*|
1096 DS_MODALFRAME | WS_POPUP | WS_VISIBLE |
1097 WS_CAPTION | WS_SYSMENU*/) &~
1098 (WS_MAXIMIZEBOX | WS_OVERLAPPED),
1099 FALSE, 0);
1100
1101 /*
1102 * Centre the dialog on its parent window.
1103 */
1104 r.right -= r.left;
1105 r.bottom -= r.top;
1106 GetWindowRect(fe->hwnd, &r2);
1107 r.left = (r2.left + r2.right - r.right) / 2;
1108 r.top = (r2.top + r2.bottom - r.bottom) / 2;
1109 r.right += r.left;
1110 r.bottom += r.top;
1111
1112 fe->cfgbox = CreateWindowEx(0, wc.lpszClassName, title,
1113 DS_MODALFRAME | WS_POPUP | WS_VISIBLE |
1114 WS_CAPTION | WS_SYSMENU,
1115 r.left, r.top,
1116 r.right-r.left, r.bottom-r.top,
1117 fe->hwnd, NULL, fe->inst, NULL);
1118 sfree(title);
1119 }
1120
1121 SendMessage(fe->cfgbox, WM_SETFONT, (WPARAM)fe->cfgfont, FALSE);
1122
1123 SetWindowLong(fe->cfgbox, GWL_USERDATA, (LONG)fe);
1124 SetWindowLong(fe->cfgbox, DWL_DLGPROC, (LONG)ConfigDlgProc);
1125
1126 /*
1127 * Count the controls so we can allocate cfgaux.
1128 */
1129 for (nctrls = 0, i = fe->cfg; i->type != C_END; i++)
1130 nctrls++;
1131 fe->cfgaux = snewn(nctrls, struct cfg_aux);
1132
1133 id = 1000;
1134 y = height/2;
1135 for (i = fe->cfg, j = fe->cfgaux; i->type != C_END; i++, j++) {
1136 switch (i->type) {
1137 case C_STRING:
1138 /*
1139 * Edit box with a label beside it.
1140 */
1141 mkctrl(fe, col1l, col1r, y+height*1/8, y+height*9/8,
1142 "Static", 0, 0, i->name, id++);
1143 ctl = mkctrl(fe, col2l, col2r, y, y+height*3/2,
1144 "EDIT", WS_TABSTOP | ES_AUTOHSCROLL,
1145 WS_EX_CLIENTEDGE, "", (j->ctlid = id++));
1146 SetWindowText(ctl, i->sval);
1147 y += height*3/2;
1148 break;
1149
1150 case C_BOOLEAN:
1151 /*
1152 * Simple checkbox.
1153 */
1154 mkctrl(fe, col1l, col2r, y, y+height, "BUTTON",
1155 BS_NOTIFY | BS_AUTOCHECKBOX | WS_TABSTOP,
1156 0, i->name, (j->ctlid = id++));
1157 CheckDlgButton(fe->cfgbox, j->ctlid, (i->ival != 0));
1158 y += height;
1159 break;
1160
1161 case C_CHOICES:
1162 /*
1163 * Drop-down list with a label beside it.
1164 */
1165 mkctrl(fe, col1l, col1r, y+height*1/8, y+height*9/8,
1166 "STATIC", 0, 0, i->name, id++);
1167 ctl = mkctrl(fe, col2l, col2r, y, y+height*41/2,
1168 "COMBOBOX", WS_TABSTOP |
1169 CBS_DROPDOWNLIST | CBS_HASSTRINGS,
1170 WS_EX_CLIENTEDGE, "", (j->ctlid = id++));
1171 {
1172 char c, *p, *q, *str;
1173
1174 SendMessage(ctl, CB_RESETCONTENT, 0, 0);
1175 p = i->sval;
1176 c = *p++;
1177 while (*p) {
1178 q = p;
1179 while (*q && *q != c) q++;
1180 str = snewn(q-p+1, char);
1181 strncpy(str, p, q-p);
1182 str[q-p] = '\0';
1183 SendMessage(ctl, CB_ADDSTRING, 0, (LPARAM)str);
1184 sfree(str);
1185 if (*q) q++;
1186 p = q;
1187 }
1188 }
1189
1190 SendMessage(ctl, CB_SETCURSEL, i->ival, 0);
1191
1192 y += height*3/2;
1193 break;
1194 }
1195
1196 assert(y < winheight);
1197 y += height/2;
1198 }
1199
1200 y += height/2; /* extra space before OK and Cancel */
1201 mkctrl(fe, col1l, (col1l+col2r)/2-width, y, y+height*7/4, "BUTTON",
1202 BS_PUSHBUTTON | BS_NOTIFY | WS_TABSTOP | BS_DEFPUSHBUTTON, 0,
1203 "OK", IDOK);
1204 mkctrl(fe, (col1l+col2r)/2+width, col2r, y, y+height*7/4, "BUTTON",
1205 BS_PUSHBUTTON | BS_NOTIFY | WS_TABSTOP, 0, "Cancel", IDCANCEL);
1206
1207 SendMessage(fe->cfgbox, WM_INITDIALOG, 0, 0);
1208
1209 EnableWindow(fe->hwnd, FALSE);
1210 ShowWindow(fe->cfgbox, SW_NORMAL);
1211 while ((gm=GetMessage(&msg, NULL, 0, 0)) > 0) {
1212 if (!IsDialogMessage(fe->cfgbox, &msg))
1213 DispatchMessage(&msg);
1214 if (fe->dlg_done)
1215 break;
1216 }
1217 EnableWindow(fe->hwnd, TRUE);
1218 SetForegroundWindow(fe->hwnd);
1219 DestroyWindow(fe->cfgbox);
1220 DeleteObject(fe->cfgfont);
1221
1222 free_cfg(fe->cfg);
1223 sfree(fe->cfgaux);
1224
1225 return (fe->dlg_done == 2);
1226 }
1227
1228 static void new_game_size(frontend *fe)
1229 {
1230 RECT r, sr;
1231 HDC hdc;
1232 int x, y;
1233
1234 x = y = INT_MAX;
1235 midend_size(fe->me, &x, &y, FALSE);
1236
1237 r.left = r.top = 0;
1238 r.right = x;
1239 r.bottom = y;
1240 AdjustWindowRectEx(&r, WS_OVERLAPPEDWINDOW &~
1241 (WS_THICKFRAME | WS_MAXIMIZEBOX |
1242 WS_OVERLAPPED),
1243 TRUE, 0);
1244
1245 if (fe->statusbar != NULL) {
1246 GetWindowRect(fe->statusbar, &sr);
1247 } else {
1248 sr.left = sr.right = sr.top = sr.bottom = 0;
1249 }
1250 SetWindowPos(fe->hwnd, NULL, 0, 0,
1251 r.right - r.left,
1252 r.bottom - r.top + sr.bottom - sr.top,
1253 SWP_NOMOVE | SWP_NOZORDER);
1254
1255 check_window_size(fe, &x, &y);
1256
1257 if (fe->statusbar != NULL)
1258 SetWindowPos(fe->statusbar, NULL, 0, y, x,
1259 sr.bottom - sr.top, SWP_NOZORDER);
1260
1261 DeleteObject(fe->bitmap);
1262
1263 hdc = GetDC(fe->hwnd);
1264 fe->bitmap = CreateCompatibleBitmap(hdc, x, y);
1265 ReleaseDC(fe->hwnd, hdc);
1266
1267 midend_redraw(fe->me);
1268 }
1269
1270 static void new_game_type(frontend *fe)
1271 {
1272 midend_new_game(fe->me);
1273 new_game_size(fe);
1274 }
1275
1276 static int is_alt_pressed(void)
1277 {
1278 BYTE keystate[256];
1279 int r = GetKeyboardState(keystate);
1280 if (!r)
1281 return FALSE;
1282 if (keystate[VK_MENU] & 0x80)
1283 return TRUE;
1284 if (keystate[VK_RMENU] & 0x80)
1285 return TRUE;
1286 return FALSE;
1287 }
1288
1289 static void savefile_write(void *wctx, void *buf, int len)
1290 {
1291 FILE *fp = (FILE *)wctx;
1292 fwrite(buf, 1, len, fp);
1293 }
1294
1295 static int savefile_read(void *wctx, void *buf, int len)
1296 {
1297 FILE *fp = (FILE *)wctx;
1298 int ret;
1299
1300 ret = fread(buf, 1, len, fp);
1301 return (ret == len);
1302 }
1303
1304 static LRESULT CALLBACK WndProc(HWND hwnd, UINT message,
1305 WPARAM wParam, LPARAM lParam)
1306 {
1307 frontend *fe = (frontend *)GetWindowLong(hwnd, GWL_USERDATA);
1308 int cmd;
1309
1310 switch (message) {
1311 case WM_CLOSE:
1312 DestroyWindow(hwnd);
1313 return 0;
1314 case WM_COMMAND:
1315 cmd = wParam & ~0xF; /* low 4 bits reserved to Windows */
1316 switch (cmd) {
1317 case IDM_NEW:
1318 if (!midend_process_key(fe->me, 0, 0, 'n'))
1319 PostQuitMessage(0);
1320 break;
1321 case IDM_RESTART:
1322 midend_restart_game(fe->me);
1323 break;
1324 case IDM_UNDO:
1325 if (!midend_process_key(fe->me, 0, 0, 'u'))
1326 PostQuitMessage(0);
1327 break;
1328 case IDM_REDO:
1329 if (!midend_process_key(fe->me, 0, 0, '\x12'))
1330 PostQuitMessage(0);
1331 break;
1332 case IDM_COPY:
1333 {
1334 char *text = midend_text_format(fe->me);
1335 if (text)
1336 write_clip(hwnd, text);
1337 else
1338 MessageBeep(MB_ICONWARNING);
1339 sfree(text);
1340 }
1341 break;
1342 case IDM_SOLVE:
1343 {
1344 char *msg = midend_solve(fe->me);
1345 if (msg)
1346 MessageBox(hwnd, msg, "Unable to solve",
1347 MB_ICONERROR | MB_OK);
1348 }
1349 break;
1350 case IDM_QUIT:
1351 if (!midend_process_key(fe->me, 0, 0, 'q'))
1352 PostQuitMessage(0);
1353 break;
1354 case IDM_CONFIG:
1355 if (get_config(fe, CFG_SETTINGS))
1356 new_game_type(fe);
1357 break;
1358 case IDM_SEED:
1359 if (get_config(fe, CFG_SEED))
1360 new_game_type(fe);
1361 break;
1362 case IDM_DESC:
1363 if (get_config(fe, CFG_DESC))
1364 new_game_type(fe);
1365 break;
1366 case IDM_ABOUT:
1367 about(fe);
1368 break;
1369 case IDM_LOAD:
1370 case IDM_SAVE:
1371 {
1372 OPENFILENAME of;
1373 char filename[FILENAME_MAX];
1374 int ret;
1375
1376 memset(&of, 0, sizeof(of));
1377 of.hwndOwner = hwnd;
1378 of.lpstrFilter = "All Files (*.*)\0*\0\0\0";
1379 of.lpstrCustomFilter = NULL;
1380 of.nFilterIndex = 1;
1381 of.lpstrFile = filename;
1382 filename[0] = '\0';
1383 of.nMaxFile = lenof(filename);
1384 of.lpstrFileTitle = NULL;
1385 of.lpstrTitle = (cmd == IDM_SAVE ?
1386 "Enter name of game file to save" :
1387 "Enter name of saved game file to load");
1388 of.Flags = 0;
1389 #ifdef OPENFILENAME_SIZE_VERSION_400
1390 of.lStructSize = OPENFILENAME_SIZE_VERSION_400;
1391 #else
1392 of.lStructSize = sizeof(of);
1393 #endif
1394 of.lpstrInitialDir = NULL;
1395
1396 if (cmd == IDM_SAVE)
1397 ret = GetSaveFileName(&of);
1398 else
1399 ret = GetOpenFileName(&of);
1400
1401 if (ret) {
1402 if (cmd == IDM_SAVE) {
1403 FILE *fp;
1404
1405 if ((fp = fopen(filename, "r")) != NULL) {
1406 char buf[256 + FILENAME_MAX];
1407 fclose(fp);
1408 /* file exists */
1409
1410 sprintf(buf, "Are you sure you want to overwrite"
1411 " the file \"%.*s\"?",
1412 FILENAME_MAX, filename);
1413 if (MessageBox(hwnd, buf, "Question",
1414 MB_YESNO | MB_ICONQUESTION)
1415 != IDYES)
1416 break;
1417 }
1418
1419 fp = fopen(filename, "w");
1420
1421 if (!fp) {
1422 MessageBox(hwnd, "Unable to open save file",
1423 "Error", MB_ICONERROR | MB_OK);
1424 break;
1425 }
1426
1427 midend_serialise(fe->me, savefile_write, fp);
1428
1429 fclose(fp);
1430 } else {
1431 FILE *fp = fopen(filename, "r");
1432 char *err;
1433
1434 if (!fp) {
1435 MessageBox(hwnd, "Unable to open saved game file",
1436 "Error", MB_ICONERROR | MB_OK);
1437 break;
1438 }
1439
1440 err = midend_deserialise(fe->me, savefile_read, fp);
1441
1442 fclose(fp);
1443
1444 if (err) {
1445 MessageBox(hwnd, err, "Error", MB_ICONERROR|MB_OK);
1446 break;
1447 }
1448
1449 new_game_size(fe);
1450 }
1451 }
1452 }
1453
1454 break;
1455 case IDM_HELPC:
1456 assert(fe->help_path);
1457 WinHelp(hwnd, fe->help_path,
1458 fe->help_has_contents ? HELP_FINDER : HELP_CONTENTS, 0);
1459 break;
1460 case IDM_GAMEHELP:
1461 assert(fe->help_path);
1462 assert(thegame.winhelp_topic);
1463 {
1464 char *cmd = snewn(10+strlen(thegame.winhelp_topic), char);
1465 sprintf(cmd, "JI(`',`%s')", thegame.winhelp_topic);
1466 WinHelp(hwnd, fe->help_path, HELP_COMMAND, (DWORD)cmd);
1467 sfree(cmd);
1468 }
1469 break;
1470 default:
1471 {
1472 int p = ((wParam &~ 0xF) - IDM_PRESETS) / 0x10;
1473
1474 if (p >= 0 && p < fe->npresets) {
1475 midend_set_params(fe->me, fe->presets[p]);
1476 new_game_type(fe);
1477 }
1478 }
1479 break;
1480 }
1481 break;
1482 case WM_DESTROY:
1483 PostQuitMessage(0);
1484 return 0;
1485 case WM_PAINT:
1486 {
1487 PAINTSTRUCT p;
1488 HDC hdc, hdc2;
1489 HBITMAP prevbm;
1490
1491 hdc = BeginPaint(hwnd, &p);
1492 hdc2 = CreateCompatibleDC(hdc);
1493 prevbm = SelectObject(hdc2, fe->bitmap);
1494 BitBlt(hdc,
1495 p.rcPaint.left, p.rcPaint.top,
1496 p.rcPaint.right - p.rcPaint.left,
1497 p.rcPaint.bottom - p.rcPaint.top,
1498 hdc2,
1499 p.rcPaint.left, p.rcPaint.top,
1500 SRCCOPY);
1501 SelectObject(hdc2, prevbm);
1502 DeleteDC(hdc2);
1503 EndPaint(hwnd, &p);
1504 }
1505 return 0;
1506 case WM_KEYDOWN:
1507 {
1508 int key = -1;
1509 BYTE keystate[256];
1510 int r = GetKeyboardState(keystate);
1511 int shift = (r && (keystate[VK_SHIFT] & 0x80)) ? MOD_SHFT : 0;
1512 int ctrl = (r && (keystate[VK_CONTROL] & 0x80)) ? MOD_CTRL : 0;
1513
1514 switch (wParam) {
1515 case VK_LEFT:
1516 if (!(lParam & 0x01000000))
1517 key = MOD_NUM_KEYPAD | '4';
1518 else
1519 key = shift | ctrl | CURSOR_LEFT;
1520 break;
1521 case VK_RIGHT:
1522 if (!(lParam & 0x01000000))
1523 key = MOD_NUM_KEYPAD | '6';
1524 else
1525 key = shift | ctrl | CURSOR_RIGHT;
1526 break;
1527 case VK_UP:
1528 if (!(lParam & 0x01000000))
1529 key = MOD_NUM_KEYPAD | '8';
1530 else
1531 key = shift | ctrl | CURSOR_UP;
1532 break;
1533 case VK_DOWN:
1534 if (!(lParam & 0x01000000))
1535 key = MOD_NUM_KEYPAD | '2';
1536 else
1537 key = shift | ctrl | CURSOR_DOWN;
1538 break;
1539 /*
1540 * Diagonal keys on the numeric keypad.
1541 */
1542 case VK_PRIOR:
1543 if (!(lParam & 0x01000000)) key = MOD_NUM_KEYPAD | '9';
1544 break;
1545 case VK_NEXT:
1546 if (!(lParam & 0x01000000)) key = MOD_NUM_KEYPAD | '3';
1547 break;
1548 case VK_HOME:
1549 if (!(lParam & 0x01000000)) key = MOD_NUM_KEYPAD | '7';
1550 break;
1551 case VK_END:
1552 if (!(lParam & 0x01000000)) key = MOD_NUM_KEYPAD | '1';
1553 break;
1554 case VK_INSERT:
1555 if (!(lParam & 0x01000000)) key = MOD_NUM_KEYPAD | '0';
1556 break;
1557 case VK_CLEAR:
1558 if (!(lParam & 0x01000000)) key = MOD_NUM_KEYPAD | '5';
1559 break;
1560 /*
1561 * Numeric keypad keys with Num Lock on.
1562 */
1563 case VK_NUMPAD4: key = MOD_NUM_KEYPAD | '4'; break;
1564 case VK_NUMPAD6: key = MOD_NUM_KEYPAD | '6'; break;
1565 case VK_NUMPAD8: key = MOD_NUM_KEYPAD | '8'; break;
1566 case VK_NUMPAD2: key = MOD_NUM_KEYPAD | '2'; break;
1567 case VK_NUMPAD5: key = MOD_NUM_KEYPAD | '5'; break;
1568 case VK_NUMPAD9: key = MOD_NUM_KEYPAD | '9'; break;
1569 case VK_NUMPAD3: key = MOD_NUM_KEYPAD | '3'; break;
1570 case VK_NUMPAD7: key = MOD_NUM_KEYPAD | '7'; break;
1571 case VK_NUMPAD1: key = MOD_NUM_KEYPAD | '1'; break;
1572 case VK_NUMPAD0: key = MOD_NUM_KEYPAD | '0'; break;
1573 }
1574
1575 if (key != -1) {
1576 if (!midend_process_key(fe->me, 0, 0, key))
1577 PostQuitMessage(0);
1578 } else {
1579 MSG m;
1580 m.hwnd = hwnd;
1581 m.message = WM_KEYDOWN;
1582 m.wParam = wParam;
1583 m.lParam = lParam & 0xdfff;
1584 TranslateMessage(&m);
1585 }
1586 }
1587 break;
1588 case WM_LBUTTONDOWN:
1589 case WM_RBUTTONDOWN:
1590 case WM_MBUTTONDOWN:
1591 {
1592 int button;
1593
1594 /*
1595 * Shift-clicks count as middle-clicks, since otherwise
1596 * two-button Windows users won't have any kind of
1597 * middle click to use.
1598 */
1599 if (message == WM_MBUTTONDOWN || (wParam & MK_SHIFT))
1600 button = MIDDLE_BUTTON;
1601 else if (message == WM_RBUTTONDOWN || is_alt_pressed())
1602 button = RIGHT_BUTTON;
1603 else
1604 button = LEFT_BUTTON;
1605
1606 if (!midend_process_key(fe->me, (signed short)LOWORD(lParam),
1607 (signed short)HIWORD(lParam), button))
1608 PostQuitMessage(0);
1609
1610 SetCapture(hwnd);
1611 }
1612 break;
1613 case WM_LBUTTONUP:
1614 case WM_RBUTTONUP:
1615 case WM_MBUTTONUP:
1616 {
1617 int button;
1618
1619 /*
1620 * Shift-clicks count as middle-clicks, since otherwise
1621 * two-button Windows users won't have any kind of
1622 * middle click to use.
1623 */
1624 if (message == WM_MBUTTONUP || (wParam & MK_SHIFT))
1625 button = MIDDLE_RELEASE;
1626 else if (message == WM_RBUTTONUP || is_alt_pressed())
1627 button = RIGHT_RELEASE;
1628 else
1629 button = LEFT_RELEASE;
1630
1631 if (!midend_process_key(fe->me, (signed short)LOWORD(lParam),
1632 (signed short)HIWORD(lParam), button))
1633 PostQuitMessage(0);
1634
1635 ReleaseCapture();
1636 }
1637 break;
1638 case WM_MOUSEMOVE:
1639 {
1640 int button;
1641
1642 if (wParam & (MK_MBUTTON | MK_SHIFT))
1643 button = MIDDLE_DRAG;
1644 else if (wParam & MK_RBUTTON || is_alt_pressed())
1645 button = RIGHT_DRAG;
1646 else
1647 button = LEFT_DRAG;
1648
1649 if (!midend_process_key(fe->me, (signed short)LOWORD(lParam),
1650 (signed short)HIWORD(lParam), button))
1651 PostQuitMessage(0);
1652 }
1653 break;
1654 case WM_CHAR:
1655 if (!midend_process_key(fe->me, 0, 0, (unsigned char)wParam))
1656 PostQuitMessage(0);
1657 return 0;
1658 case WM_TIMER:
1659 if (fe->timer) {
1660 DWORD now = GetTickCount();
1661 float elapsed = (float) (now - fe->timer_last_tickcount) * 0.001F;
1662 midend_timer(fe->me, elapsed);
1663 fe->timer_last_tickcount = now;
1664 }
1665 return 0;
1666 }
1667
1668 return DefWindowProc(hwnd, message, wParam, lParam);
1669 }
1670
1671 int WINAPI WinMain(HINSTANCE inst, HINSTANCE prev, LPSTR cmdline, int show)
1672 {
1673 MSG msg;
1674 char *error;
1675
1676 InitCommonControls();
1677
1678 if (!prev) {
1679 WNDCLASS wndclass;
1680
1681 wndclass.style = 0;
1682 wndclass.lpfnWndProc = WndProc;
1683 wndclass.cbClsExtra = 0;
1684 wndclass.cbWndExtra = 0;
1685 wndclass.hInstance = inst;
1686 wndclass.hIcon = LoadIcon(inst, IDI_APPLICATION);
1687 wndclass.hCursor = LoadCursor(NULL, IDC_ARROW);
1688 wndclass.hbrBackground = NULL;
1689 wndclass.lpszMenuName = NULL;
1690 wndclass.lpszClassName = thegame.name;
1691
1692 RegisterClass(&wndclass);
1693 }
1694
1695 while (*cmdline && isspace((unsigned char)*cmdline))
1696 cmdline++;
1697
1698 if (!new_window(inst, *cmdline ? cmdline : NULL, &error)) {
1699 char buf[128];
1700 sprintf(buf, "%.100s Error", thegame.name);
1701 MessageBox(NULL, error, buf, MB_OK|MB_ICONERROR);
1702 return 1;
1703 }
1704
1705 while (GetMessage(&msg, NULL, 0, 0)) {
1706 DispatchMessage(&msg);
1707 }
1708
1709 return msg.wParam;
1710 }