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