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