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