]> asedeno.scripts.mit.edu Git - PuTTY.git/blob - windows/winctrls.c
Move a recently introduced utility function out of the file in which I
[PuTTY.git] / windows / winctrls.c
1 /*
2  * winctrls.c: routines to self-manage the controls in a dialog
3  * box.
4  */
5
6 /*
7  * Possible TODO in new cross-platform config box stuff:
8  *
9  *  - When lining up two controls alongside each other, I wonder if
10  *    we could conveniently arrange to centre them vertically?
11  *    Particularly ugly in the current setup is the `Add new
12  *    forwarded port:' static next to the rather taller `Remove'
13  *    button.
14  */
15
16 #include <assert.h>
17 #include <ctype.h>
18
19 #include "putty.h"
20 #include "misc.h"
21 #include "dialog.h"
22
23 #include <commctrl.h>
24
25 #define GAPBETWEEN 3
26 #define GAPWITHIN 1
27 #define GAPXBOX 7
28 #define GAPYBOX 4
29 #define DLGWIDTH 168
30 #define STATICHEIGHT 8
31 #define TITLEHEIGHT 12
32 #define CHECKBOXHEIGHT 8
33 #define RADIOHEIGHT 8
34 #define EDITHEIGHT 12
35 #define LISTHEIGHT 11
36 #define LISTINCREMENT 8
37 #define COMBOHEIGHT 12
38 #define PUSHBTNHEIGHT 14
39 #define PROGBARHEIGHT 14
40
41 void ctlposinit(struct ctlpos *cp, HWND hwnd,
42                 int leftborder, int rightborder, int topborder)
43 {
44     RECT r, r2;
45     cp->hwnd = hwnd;
46     cp->font = SendMessage(hwnd, WM_GETFONT, 0, 0);
47     cp->ypos = topborder;
48     GetClientRect(hwnd, &r);
49     r2.left = r2.top = 0;
50     r2.right = 4;
51     r2.bottom = 8;
52     MapDialogRect(hwnd, &r2);
53     cp->dlu4inpix = r2.right;
54     cp->width = (r.right * 4) / (r2.right) - 2 * GAPBETWEEN;
55     cp->xoff = leftborder;
56     cp->width -= leftborder + rightborder;
57 }
58
59 HWND doctl(struct ctlpos *cp, RECT r,
60            char *wclass, int wstyle, int exstyle, char *wtext, int wid)
61 {
62     HWND ctl;
63     /*
64      * Note nonstandard use of RECT. This is deliberate: by
65      * transforming the width and height directly we arrange to
66      * have all supposedly same-sized controls really same-sized.
67      */
68
69     r.left += cp->xoff;
70     MapDialogRect(cp->hwnd, &r);
71
72     /*
73      * We can pass in cp->hwnd == NULL, to indicate a dry run
74      * without creating any actual controls.
75      */
76     if (cp->hwnd) {
77         ctl = CreateWindowEx(exstyle, wclass, wtext, wstyle,
78                              r.left, r.top, r.right, r.bottom,
79                              cp->hwnd, (HMENU) wid, hinst, NULL);
80         SendMessage(ctl, WM_SETFONT, cp->font, MAKELPARAM(TRUE, 0));
81
82         if (!strcmp(wclass, "LISTBOX")) {
83             /*
84              * Bizarre Windows bug: the list box calculates its
85              * number of lines based on the font it has at creation
86              * time, but sending it WM_SETFONT doesn't cause it to
87              * recalculate. So now, _after_ we've sent it
88              * WM_SETFONT, we explicitly resize it (to the same
89              * size it was already!) to force it to reconsider.
90              */
91             SetWindowPos(ctl, NULL, 0, 0, r.right, r.bottom,
92                          SWP_NOACTIVATE | SWP_NOCOPYBITS |
93                          SWP_NOMOVE | SWP_NOZORDER);
94         }
95     } else
96         ctl = NULL;
97     return ctl;
98 }
99
100 /*
101  * A title bar across the top of a sub-dialog.
102  */
103 void bartitle(struct ctlpos *cp, char *name, int id)
104 {
105     RECT r;
106
107     r.left = GAPBETWEEN;
108     r.right = cp->width;
109     r.top = cp->ypos;
110     r.bottom = STATICHEIGHT;
111     cp->ypos += r.bottom + GAPBETWEEN;
112     doctl(cp, r, "STATIC", WS_CHILD | WS_VISIBLE, 0, name, id);
113 }
114
115 /*
116  * Begin a grouping box, with or without a group title.
117  */
118 void beginbox(struct ctlpos *cp, char *name, int idbox)
119 {
120     cp->boxystart = cp->ypos;
121     if (!name)
122         cp->boxystart -= STATICHEIGHT / 2;
123     if (name)
124         cp->ypos += STATICHEIGHT;
125     cp->ypos += GAPYBOX;
126     cp->width -= 2 * GAPXBOX;
127     cp->xoff += GAPXBOX;
128     cp->boxid = idbox;
129     cp->boxtext = name;
130 }
131
132 /*
133  * End a grouping box.
134  */
135 void endbox(struct ctlpos *cp)
136 {
137     RECT r;
138     cp->xoff -= GAPXBOX;
139     cp->width += 2 * GAPXBOX;
140     cp->ypos += GAPYBOX - GAPBETWEEN;
141     r.left = GAPBETWEEN;
142     r.right = cp->width;
143     r.top = cp->boxystart;
144     r.bottom = cp->ypos - cp->boxystart;
145     doctl(cp, r, "BUTTON", BS_GROUPBOX | WS_CHILD | WS_VISIBLE, 0,
146           cp->boxtext ? cp->boxtext : "", cp->boxid);
147     cp->ypos += GAPYBOX;
148 }
149
150 /*
151  * A static line, followed by a full-width edit box.
152  */
153 void editboxfw(struct ctlpos *cp, int password, char *text,
154                int staticid, int editid)
155 {
156     RECT r;
157
158     r.left = GAPBETWEEN;
159     r.right = cp->width;
160
161     if (text) {
162         r.top = cp->ypos;
163         r.bottom = STATICHEIGHT;
164         doctl(cp, r, "STATIC", WS_CHILD | WS_VISIBLE, 0, text, staticid);
165         cp->ypos += STATICHEIGHT + GAPWITHIN;
166     }
167     r.top = cp->ypos;
168     r.bottom = EDITHEIGHT;
169     doctl(cp, r, "EDIT",
170           WS_CHILD | WS_VISIBLE | WS_TABSTOP | ES_AUTOHSCROLL |
171           (password ? ES_PASSWORD : 0),
172           WS_EX_CLIENTEDGE, "", editid);
173     cp->ypos += EDITHEIGHT + GAPBETWEEN;
174 }
175
176 /*
177  * A static line, followed by a full-width combo box.
178  */
179 void combobox(struct ctlpos *cp, char *text, int staticid, int listid)
180 {
181     RECT r;
182
183     r.left = GAPBETWEEN;
184     r.right = cp->width;
185
186     if (text) {
187         r.top = cp->ypos;
188         r.bottom = STATICHEIGHT;
189         doctl(cp, r, "STATIC", WS_CHILD | WS_VISIBLE, 0, text, staticid);
190         cp->ypos += STATICHEIGHT + GAPWITHIN;
191     }
192     r.top = cp->ypos;
193     r.bottom = COMBOHEIGHT * 10;
194     doctl(cp, r, "COMBOBOX",
195           WS_CHILD | WS_VISIBLE | WS_TABSTOP | WS_VSCROLL |
196           CBS_DROPDOWN | CBS_HASSTRINGS, WS_EX_CLIENTEDGE, "", listid);
197     cp->ypos += COMBOHEIGHT + GAPBETWEEN;
198 }
199
200 struct radio { char *text; int id; };
201
202 static void radioline_common(struct ctlpos *cp, char *text, int id,
203                              int nacross, struct radio *buttons, int nbuttons)
204 {
205     RECT r;
206     int group;
207     int i;
208     int j;
209
210     if (text) {
211         r.left = GAPBETWEEN;
212         r.top = cp->ypos;
213         r.right = cp->width;
214         r.bottom = STATICHEIGHT;
215         cp->ypos += r.bottom + GAPWITHIN;
216         doctl(cp, r, "STATIC", WS_CHILD | WS_VISIBLE, 0, text, id);
217     }
218
219     group = WS_GROUP;
220     i = 0;
221     for (j = 0; j < nbuttons; j++) {
222         char *btext = buttons[j].text;
223         int bid = buttons[j].id;
224
225         if (i == nacross) {
226             cp->ypos += r.bottom + (nacross > 1 ? GAPBETWEEN : GAPWITHIN);
227             i = 0;
228         }
229         r.left = GAPBETWEEN + i * (cp->width + GAPBETWEEN) / nacross;
230         if (j < nbuttons-1)
231             r.right =
232                 (i + 1) * (cp->width + GAPBETWEEN) / nacross - r.left;
233         else
234             r.right = cp->width - r.left;
235         r.top = cp->ypos;
236         r.bottom = RADIOHEIGHT;
237         doctl(cp, r, "BUTTON",
238               BS_NOTIFY | BS_AUTORADIOBUTTON | WS_CHILD |
239               WS_VISIBLE | WS_TABSTOP | group, 0, btext, bid);
240         group = 0;
241         i++;
242     }
243     cp->ypos += r.bottom + GAPBETWEEN;
244 }
245
246 /*
247  * A set of radio buttons on the same line, with a static above
248  * them. `nacross' dictates how many parts the line is divided into
249  * (you might want this not to equal the number of buttons if you
250  * needed to line up some 2s and some 3s to look good in the same
251  * panel).
252  * 
253  * There's a bit of a hack in here to ensure that if nacross
254  * exceeds the actual number of buttons, the rightmost button
255  * really does get all the space right to the edge of the line, so
256  * you can do things like
257  * 
258  * (*) Button1  (*) Button2  (*) ButtonWithReallyLongTitle
259  */
260 void radioline(struct ctlpos *cp, char *text, int id, int nacross, ...)
261 {
262     va_list ap;
263     struct radio *buttons;
264     int i, nbuttons;
265
266     va_start(ap, nacross);
267     nbuttons = 0;
268     while (1) {
269         char *btext = va_arg(ap, char *);
270         int bid;
271         if (!btext)
272             break;
273         bid = va_arg(ap, int);
274         nbuttons++;
275     }
276     va_end(ap);
277     buttons = snewn(nbuttons, struct radio);
278     va_start(ap, nacross);
279     for (i = 0; i < nbuttons; i++) {
280         buttons[i].text = va_arg(ap, char *);
281         buttons[i].id = va_arg(ap, int);
282     }
283     va_end(ap);
284     radioline_common(cp, text, id, nacross, buttons, nbuttons);
285     sfree(buttons);
286 }
287
288 /*
289  * A set of radio buttons on the same line, without a static above
290  * them. Otherwise just like radioline.
291  */
292 void bareradioline(struct ctlpos *cp, int nacross, ...)
293 {
294     va_list ap;
295     struct radio *buttons;
296     int i, nbuttons;
297
298     va_start(ap, nacross);
299     nbuttons = 0;
300     while (1) {
301         char *btext = va_arg(ap, char *);
302         int bid;
303         if (!btext)
304             break;
305         bid = va_arg(ap, int);
306     }
307     va_end(ap);
308     buttons = snewn(nbuttons, struct radio);
309     va_start(ap, nacross);
310     for (i = 0; i < nbuttons; i++) {
311         buttons[i].text = va_arg(ap, char *);
312         buttons[i].id = va_arg(ap, int);
313     }
314     va_end(ap);
315     radioline_common(cp, NULL, 0, nacross, buttons, nbuttons);
316     sfree(buttons);
317 }
318
319 /*
320  * A set of radio buttons on multiple lines, with a static above
321  * them.
322  */
323 void radiobig(struct ctlpos *cp, char *text, int id, ...)
324 {
325     va_list ap;
326     struct radio *buttons;
327     int i, nbuttons;
328
329     va_start(ap, id);
330     nbuttons = 0;
331     while (1) {
332         char *btext = va_arg(ap, char *);
333         int bid;
334         if (!btext)
335             break;
336         bid = va_arg(ap, int);
337     }
338     va_end(ap);
339     buttons = snewn(nbuttons, struct radio);
340     va_start(ap, id);
341     for (i = 0; i < nbuttons; i++) {
342         buttons[i].text = va_arg(ap, char *);
343         buttons[i].id = va_arg(ap, int);
344     }
345     va_end(ap);
346     radioline_common(cp, text, id, 1, buttons, nbuttons);
347     sfree(buttons);
348 }
349
350 /*
351  * A single standalone checkbox.
352  */
353 void checkbox(struct ctlpos *cp, char *text, int id)
354 {
355     RECT r;
356
357     r.left = GAPBETWEEN;
358     r.top = cp->ypos;
359     r.right = cp->width;
360     r.bottom = CHECKBOXHEIGHT;
361     cp->ypos += r.bottom + GAPBETWEEN;
362     doctl(cp, r, "BUTTON",
363           BS_NOTIFY | BS_AUTOCHECKBOX | WS_CHILD | WS_VISIBLE | WS_TABSTOP, 0,
364           text, id);
365 }
366
367 /*
368  * Wrap a piece of text for a static text control. Returns the
369  * wrapped text (a malloc'ed string containing \ns), and also
370  * returns the number of lines required.
371  */
372 char *staticwrap(struct ctlpos *cp, HWND hwnd, char *text, int *lines)
373 {
374     HDC hdc = GetDC(hwnd);
375     int lpx = GetDeviceCaps(hdc, LOGPIXELSX);
376     int width, nlines, j;
377     INT *pwidths, nfit;
378     SIZE size;
379     char *ret, *p, *q;
380     RECT r;
381     HFONT oldfont, newfont;
382
383     ret = snewn(1+strlen(text), char);
384     p = text;
385     q = ret;
386     pwidths = snewn(1+strlen(text), INT);
387
388     /*
389      * Work out the width the text will need to fit in, by doing
390      * the same adjustment that the `statictext' function itself
391      * will perform.
392      */
393     SetMapMode(hdc, MM_TEXT);          /* ensure logical units == pixels */
394     r.left = r.top = r.bottom = 0;
395     r.right = cp->width;
396     MapDialogRect(hwnd, &r);
397     width = r.right;
398
399     nlines = 1;
400
401     /*
402      * We must select the correct font into the HDC before calling
403      * GetTextExtent*, or silly things will happen.
404      */
405     newfont = (HFONT)SendMessage(hwnd, WM_GETFONT, 0, 0);
406     oldfont = SelectObject(hdc, newfont);
407
408     while (*p) {
409         if (!GetTextExtentExPoint(hdc, p, strlen(p), width,
410                                   &nfit, pwidths, &size) ||
411             (size_t)nfit >= strlen(p)) {
412             /*
413              * Either GetTextExtentExPoint returned failure, or the
414              * whole of the rest of the text fits on this line.
415              * Either way, we stop wrapping, copy the remainder of
416              * the input string unchanged to the output, and leave.
417              */
418             strcpy(q, p);
419             break;
420         }
421
422         /*
423          * Now we search backwards along the string from `nfit',
424          * looking for a space at which to break the line. If we
425          * don't find one at all, that's fine - we'll just break
426          * the line at `nfit'.
427          */
428         for (j = nfit; j > 0; j--) {
429             if (isspace((unsigned char)p[j])) {
430                 nfit = j;
431                 break;
432             }
433         }
434
435         strncpy(q, p, nfit);
436         q[nfit] = '\n';
437         q += nfit+1;
438
439         p += nfit;
440         while (*p && isspace((unsigned char)*p))
441             p++;
442
443         nlines++;
444     }
445
446     SelectObject(hdc, oldfont);
447     ReleaseDC(cp->hwnd, hdc);
448
449     if (lines) *lines = nlines;
450
451     return ret;
452 }
453
454 /*
455  * A single standalone static text control.
456  */
457 void statictext(struct ctlpos *cp, char *text, int lines, int id)
458 {
459     RECT r;
460
461     r.left = GAPBETWEEN;
462     r.top = cp->ypos;
463     r.right = cp->width;
464     r.bottom = STATICHEIGHT * lines;
465     cp->ypos += r.bottom + GAPBETWEEN;
466     doctl(cp, r, "STATIC",
467           WS_CHILD | WS_VISIBLE | SS_LEFTNOWORDWRAP,
468           0, text, id);
469 }
470
471 /*
472  * An owner-drawn static text control for a panel title.
473  */
474 void paneltitle(struct ctlpos *cp, int id)
475 {
476     RECT r;
477
478     r.left = GAPBETWEEN;
479     r.top = cp->ypos;
480     r.right = cp->width;
481     r.bottom = TITLEHEIGHT;
482     cp->ypos += r.bottom + GAPBETWEEN;
483     doctl(cp, r, "STATIC", WS_CHILD | WS_VISIBLE | SS_OWNERDRAW,
484           0, NULL, id);
485 }
486
487 /*
488  * A button on the right hand side, with a static to its left.
489  */
490 void staticbtn(struct ctlpos *cp, char *stext, int sid,
491                char *btext, int bid)
492 {
493     const int height = (PUSHBTNHEIGHT > STATICHEIGHT ?
494                         PUSHBTNHEIGHT : STATICHEIGHT);
495     RECT r;
496     int lwid, rwid, rpos;
497
498     rpos = GAPBETWEEN + 3 * (cp->width + GAPBETWEEN) / 4;
499     lwid = rpos - 2 * GAPBETWEEN;
500     rwid = cp->width + GAPBETWEEN - rpos;
501
502     r.left = GAPBETWEEN;
503     r.top = cp->ypos + (height - STATICHEIGHT) / 2;
504     r.right = lwid;
505     r.bottom = STATICHEIGHT;
506     doctl(cp, r, "STATIC", WS_CHILD | WS_VISIBLE, 0, stext, sid);
507
508     r.left = rpos;
509     r.top = cp->ypos + (height - PUSHBTNHEIGHT) / 2;
510     r.right = rwid;
511     r.bottom = PUSHBTNHEIGHT;
512     doctl(cp, r, "BUTTON",
513           BS_NOTIFY | WS_CHILD | WS_VISIBLE | WS_TABSTOP | BS_PUSHBUTTON,
514           0, btext, bid);
515
516     cp->ypos += height + GAPBETWEEN;
517 }
518
519 /*
520  * A simple push button.
521  */
522 void button(struct ctlpos *cp, char *btext, int bid, int defbtn)
523 {
524     RECT r;
525
526     r.left = GAPBETWEEN;
527     r.top = cp->ypos;
528     r.right = cp->width;
529     r.bottom = PUSHBTNHEIGHT;
530
531     /* Q67655: the _dialog box_ must know which button is default
532      * as well as the button itself knowing */
533     if (defbtn && cp->hwnd)
534         SendMessage(cp->hwnd, DM_SETDEFID, bid, 0);
535
536     doctl(cp, r, "BUTTON",
537           BS_NOTIFY | WS_CHILD | WS_VISIBLE | WS_TABSTOP |
538           (defbtn ? BS_DEFPUSHBUTTON : 0) | BS_PUSHBUTTON,
539           0, btext, bid);
540
541     cp->ypos += PUSHBTNHEIGHT + GAPBETWEEN;
542 }
543
544 /*
545  * Like staticbtn, but two buttons.
546  */
547 void static2btn(struct ctlpos *cp, char *stext, int sid,
548                 char *btext1, int bid1, char *btext2, int bid2)
549 {
550     const int height = (PUSHBTNHEIGHT > STATICHEIGHT ?
551                         PUSHBTNHEIGHT : STATICHEIGHT);
552     RECT r;
553     int lwid, rwid1, rwid2, rpos1, rpos2;
554
555     rpos1 = GAPBETWEEN + (cp->width + GAPBETWEEN) / 2;
556     rpos2 = GAPBETWEEN + 3 * (cp->width + GAPBETWEEN) / 4;
557     lwid = rpos1 - 2 * GAPBETWEEN;
558     rwid1 = rpos2 - rpos1 - GAPBETWEEN;
559     rwid2 = cp->width + GAPBETWEEN - rpos2;
560
561     r.left = GAPBETWEEN;
562     r.top = cp->ypos + (height - STATICHEIGHT) / 2;
563     r.right = lwid;
564     r.bottom = STATICHEIGHT;
565     doctl(cp, r, "STATIC", WS_CHILD | WS_VISIBLE, 0, stext, sid);
566
567     r.left = rpos1;
568     r.top = cp->ypos + (height - PUSHBTNHEIGHT) / 2;
569     r.right = rwid1;
570     r.bottom = PUSHBTNHEIGHT;
571     doctl(cp, r, "BUTTON",
572           BS_NOTIFY | WS_CHILD | WS_VISIBLE | WS_TABSTOP | BS_PUSHBUTTON,
573           0, btext1, bid1);
574
575     r.left = rpos2;
576     r.top = cp->ypos + (height - PUSHBTNHEIGHT) / 2;
577     r.right = rwid2;
578     r.bottom = PUSHBTNHEIGHT;
579     doctl(cp, r, "BUTTON",
580           BS_NOTIFY | WS_CHILD | WS_VISIBLE | WS_TABSTOP | BS_PUSHBUTTON,
581           0, btext2, bid2);
582
583     cp->ypos += height + GAPBETWEEN;
584 }
585
586 /*
587  * An edit control on the right hand side, with a static to its left.
588  */
589 static void staticedit_internal(struct ctlpos *cp, char *stext,
590                                 int sid, int eid, int percentedit,
591                                 int style)
592 {
593     const int height = (EDITHEIGHT > STATICHEIGHT ?
594                         EDITHEIGHT : STATICHEIGHT);
595     RECT r;
596     int lwid, rwid, rpos;
597
598     rpos =
599         GAPBETWEEN + (100 - percentedit) * (cp->width + GAPBETWEEN) / 100;
600     lwid = rpos - 2 * GAPBETWEEN;
601     rwid = cp->width + GAPBETWEEN - rpos;
602
603     r.left = GAPBETWEEN;
604     r.top = cp->ypos + (height - STATICHEIGHT) / 2;
605     r.right = lwid;
606     r.bottom = STATICHEIGHT;
607     doctl(cp, r, "STATIC", WS_CHILD | WS_VISIBLE, 0, stext, sid);
608
609     r.left = rpos;
610     r.top = cp->ypos + (height - EDITHEIGHT) / 2;
611     r.right = rwid;
612     r.bottom = EDITHEIGHT;
613     doctl(cp, r, "EDIT",
614           WS_CHILD | WS_VISIBLE | WS_TABSTOP | ES_AUTOHSCROLL | style,
615           WS_EX_CLIENTEDGE, "", eid);
616
617     cp->ypos += height + GAPBETWEEN;
618 }
619
620 void staticedit(struct ctlpos *cp, char *stext,
621                 int sid, int eid, int percentedit)
622 {
623     staticedit_internal(cp, stext, sid, eid, percentedit, 0);
624 }
625
626 void staticpassedit(struct ctlpos *cp, char *stext,
627                     int sid, int eid, int percentedit)
628 {
629     staticedit_internal(cp, stext, sid, eid, percentedit, ES_PASSWORD);
630 }
631
632 /*
633  * A drop-down list box on the right hand side, with a static to
634  * its left.
635  */
636 void staticddl(struct ctlpos *cp, char *stext,
637                int sid, int lid, int percentlist)
638 {
639     const int height = (COMBOHEIGHT > STATICHEIGHT ?
640                         COMBOHEIGHT : STATICHEIGHT);
641     RECT r;
642     int lwid, rwid, rpos;
643
644     rpos =
645         GAPBETWEEN + (100 - percentlist) * (cp->width + GAPBETWEEN) / 100;
646     lwid = rpos - 2 * GAPBETWEEN;
647     rwid = cp->width + GAPBETWEEN - rpos;
648
649     r.left = GAPBETWEEN;
650     r.top = cp->ypos + (height - STATICHEIGHT) / 2;
651     r.right = lwid;
652     r.bottom = STATICHEIGHT;
653     doctl(cp, r, "STATIC", WS_CHILD | WS_VISIBLE, 0, stext, sid);
654
655     r.left = rpos;
656     r.top = cp->ypos + (height - EDITHEIGHT) / 2;
657     r.right = rwid;
658     r.bottom = COMBOHEIGHT*4;
659     doctl(cp, r, "COMBOBOX",
660           WS_CHILD | WS_VISIBLE | WS_TABSTOP | WS_VSCROLL |
661           CBS_DROPDOWNLIST | CBS_HASSTRINGS, WS_EX_CLIENTEDGE, "", lid);
662
663     cp->ypos += height + GAPBETWEEN;
664 }
665
666 /*
667  * A combo box on the right hand side, with a static to its left.
668  */
669 void staticcombo(struct ctlpos *cp, char *stext,
670                  int sid, int lid, int percentlist)
671 {
672     const int height = (COMBOHEIGHT > STATICHEIGHT ?
673                         COMBOHEIGHT : STATICHEIGHT);
674     RECT r;
675     int lwid, rwid, rpos;
676
677     rpos =
678         GAPBETWEEN + (100 - percentlist) * (cp->width + GAPBETWEEN) / 100;
679     lwid = rpos - 2 * GAPBETWEEN;
680     rwid = cp->width + GAPBETWEEN - rpos;
681
682     r.left = GAPBETWEEN;
683     r.top = cp->ypos + (height - STATICHEIGHT) / 2;
684     r.right = lwid;
685     r.bottom = STATICHEIGHT;
686     doctl(cp, r, "STATIC", WS_CHILD | WS_VISIBLE, 0, stext, sid);
687
688     r.left = rpos;
689     r.top = cp->ypos + (height - EDITHEIGHT) / 2;
690     r.right = rwid;
691     r.bottom = COMBOHEIGHT*10;
692     doctl(cp, r, "COMBOBOX",
693           WS_CHILD | WS_VISIBLE | WS_TABSTOP | WS_VSCROLL |
694           CBS_DROPDOWN | CBS_HASSTRINGS, WS_EX_CLIENTEDGE, "", lid);
695
696     cp->ypos += height + GAPBETWEEN;
697 }
698
699 /*
700  * A static, with a full-width drop-down list box below it.
701  */
702 void staticddlbig(struct ctlpos *cp, char *stext,
703                   int sid, int lid)
704 {
705     RECT r;
706
707     if (stext) {
708         r.left = GAPBETWEEN;
709         r.top = cp->ypos;
710         r.right = cp->width;
711         r.bottom = STATICHEIGHT;
712         doctl(cp, r, "STATIC", WS_CHILD | WS_VISIBLE, 0, stext, sid);
713         cp->ypos += STATICHEIGHT;
714     }
715
716     r.left = GAPBETWEEN;
717     r.top = cp->ypos;
718     r.right = cp->width;
719     r.bottom = COMBOHEIGHT*4;
720     doctl(cp, r, "COMBOBOX",
721           WS_CHILD | WS_VISIBLE | WS_TABSTOP | WS_VSCROLL |
722           CBS_DROPDOWNLIST | CBS_HASSTRINGS, WS_EX_CLIENTEDGE, "", lid);
723     cp->ypos += COMBOHEIGHT + GAPBETWEEN;
724 }
725
726 /*
727  * A big multiline edit control with a static labelling it.
728  */
729 void bigeditctrl(struct ctlpos *cp, char *stext,
730                  int sid, int eid, int lines)
731 {
732     RECT r;
733
734     if (stext) {
735         r.left = GAPBETWEEN;
736         r.top = cp->ypos;
737         r.right = cp->width;
738         r.bottom = STATICHEIGHT;
739         cp->ypos += r.bottom + GAPWITHIN;
740         doctl(cp, r, "STATIC", WS_CHILD | WS_VISIBLE, 0, stext, sid);
741     }
742
743     r.left = GAPBETWEEN;
744     r.top = cp->ypos;
745     r.right = cp->width;
746     r.bottom = EDITHEIGHT + (lines - 1) * STATICHEIGHT;
747     cp->ypos += r.bottom + GAPBETWEEN;
748     doctl(cp, r, "EDIT",
749           WS_CHILD | WS_VISIBLE | WS_TABSTOP | WS_VSCROLL | ES_MULTILINE,
750           WS_EX_CLIENTEDGE, "", eid);
751 }
752
753 /*
754  * A list box with a static labelling it.
755  */
756 void listbox(struct ctlpos *cp, char *stext,
757              int sid, int lid, int lines, int multi)
758 {
759     RECT r;
760
761     if (stext != NULL) {
762         r.left = GAPBETWEEN;
763         r.top = cp->ypos;
764         r.right = cp->width;
765         r.bottom = STATICHEIGHT;
766         cp->ypos += r.bottom + GAPWITHIN;
767         doctl(cp, r, "STATIC", WS_CHILD | WS_VISIBLE, 0, stext, sid);
768     }
769
770     r.left = GAPBETWEEN;
771     r.top = cp->ypos;
772     r.right = cp->width;
773     r.bottom = LISTHEIGHT + (lines - 1) * LISTINCREMENT;
774     cp->ypos += r.bottom + GAPBETWEEN;
775     doctl(cp, r, "LISTBOX",
776           WS_CHILD | WS_VISIBLE | WS_TABSTOP | WS_VSCROLL |
777           LBS_NOTIFY | LBS_HASSTRINGS | LBS_USETABSTOPS |
778           (multi ? LBS_MULTIPLESEL : 0),
779           WS_EX_CLIENTEDGE, "", lid);
780 }
781
782 /*
783  * A tab-control substitute when a real tab control is unavailable.
784  */
785 void ersatztab(struct ctlpos *cp, char *stext, int sid, int lid, int s2id)
786 {
787     const int height = (COMBOHEIGHT > STATICHEIGHT ?
788                         COMBOHEIGHT : STATICHEIGHT);
789     RECT r;
790     int bigwid, lwid, rwid, rpos;
791     static const int BIGGAP = 15;
792     static const int MEDGAP = 3;
793
794     bigwid = cp->width + 2 * GAPBETWEEN - 2 * BIGGAP;
795     cp->ypos += MEDGAP;
796     rpos = BIGGAP + (bigwid + BIGGAP) / 2;
797     lwid = rpos - 2 * BIGGAP;
798     rwid = bigwid + BIGGAP - rpos;
799
800     r.left = BIGGAP;
801     r.top = cp->ypos + (height - STATICHEIGHT) / 2;
802     r.right = lwid;
803     r.bottom = STATICHEIGHT;
804     doctl(cp, r, "STATIC", WS_CHILD | WS_VISIBLE, 0, stext, sid);
805
806     r.left = rpos;
807     r.top = cp->ypos + (height - COMBOHEIGHT) / 2;
808     r.right = rwid;
809     r.bottom = COMBOHEIGHT * 10;
810     doctl(cp, r, "COMBOBOX",
811           WS_CHILD | WS_VISIBLE | WS_TABSTOP |
812           CBS_DROPDOWNLIST | CBS_HASSTRINGS, WS_EX_CLIENTEDGE, "", lid);
813
814     cp->ypos += height + MEDGAP + GAPBETWEEN;
815
816     r.left = GAPBETWEEN;
817     r.top = cp->ypos;
818     r.right = cp->width;
819     r.bottom = 2;
820     doctl(cp, r, "STATIC", WS_CHILD | WS_VISIBLE | SS_ETCHEDHORZ,
821           0, "", s2id);
822 }
823
824 /*
825  * A static line, followed by an edit control on the left hand side
826  * and a button on the right.
827  */
828 void editbutton(struct ctlpos *cp, char *stext, int sid,
829                 int eid, char *btext, int bid)
830 {
831     const int height = (EDITHEIGHT > PUSHBTNHEIGHT ?
832                         EDITHEIGHT : PUSHBTNHEIGHT);
833     RECT r;
834     int lwid, rwid, rpos;
835
836     r.left = GAPBETWEEN;
837     r.top = cp->ypos;
838     r.right = cp->width;
839     r.bottom = STATICHEIGHT;
840     cp->ypos += r.bottom + GAPWITHIN;
841     doctl(cp, r, "STATIC", WS_CHILD | WS_VISIBLE, 0, stext, sid);
842
843     rpos = GAPBETWEEN + 3 * (cp->width + GAPBETWEEN) / 4;
844     lwid = rpos - 2 * GAPBETWEEN;
845     rwid = cp->width + GAPBETWEEN - rpos;
846
847     r.left = GAPBETWEEN;
848     r.top = cp->ypos + (height - EDITHEIGHT) / 2;
849     r.right = lwid;
850     r.bottom = EDITHEIGHT;
851     doctl(cp, r, "EDIT",
852           WS_CHILD | WS_VISIBLE | WS_TABSTOP | ES_AUTOHSCROLL,
853           WS_EX_CLIENTEDGE, "", eid);
854
855     r.left = rpos;
856     r.top = cp->ypos + (height - PUSHBTNHEIGHT) / 2;
857     r.right = rwid;
858     r.bottom = PUSHBTNHEIGHT;
859     doctl(cp, r, "BUTTON",
860           BS_NOTIFY | WS_CHILD | WS_VISIBLE | WS_TABSTOP | BS_PUSHBUTTON,
861           0, btext, bid);
862
863     cp->ypos += height + GAPBETWEEN;
864 }
865
866 /*
867  * A special control for manipulating an ordered preference list
868  * (eg. for cipher selection).
869  * XXX: this is a rough hack and could be improved.
870  */
871 void prefslist(struct prefslist *hdl, struct ctlpos *cp, int lines,
872                char *stext, int sid, int listid, int upbid, int dnbid)
873 {
874     const static int percents[] = { 5, 75, 20 };
875     RECT r;
876     int xpos, percent = 0, i;
877     int listheight = LISTHEIGHT + (lines - 1) * LISTINCREMENT;
878     const int BTNSHEIGHT = 2*PUSHBTNHEIGHT + GAPBETWEEN;
879     int totalheight, buttonpos;
880
881     /* Squirrel away IDs. */
882     hdl->listid = listid;
883     hdl->upbid  = upbid;
884     hdl->dnbid  = dnbid;
885
886     /* The static label. */
887     if (stext != NULL) {
888         r.left = GAPBETWEEN;
889         r.top = cp->ypos;
890         r.right = cp->width;
891         r.bottom = STATICHEIGHT;
892         cp->ypos += r.bottom + GAPWITHIN;
893         doctl(cp, r, "STATIC", WS_CHILD | WS_VISIBLE, 0, stext, sid);
894     }
895
896     if (listheight > BTNSHEIGHT) {
897         totalheight = listheight;
898         buttonpos = (listheight - BTNSHEIGHT) / 2;
899     } else {
900         totalheight = BTNSHEIGHT;
901         buttonpos = 0;
902     }
903
904     for (i=0; i<3; i++) {
905         int left, wid;
906         xpos = (cp->width + GAPBETWEEN) * percent / 100;
907         left = xpos + GAPBETWEEN;
908         percent += percents[i];
909         xpos = (cp->width + GAPBETWEEN) * percent / 100;
910         wid = xpos - left;
911
912         switch (i) {
913           case 1:
914             /* The drag list box. */
915             r.left = left; r.right = wid;
916             r.top = cp->ypos; r.bottom = listheight;
917             {
918                 HWND ctl;
919                 ctl = doctl(cp, r, "LISTBOX",
920                             WS_CHILD | WS_VISIBLE | WS_TABSTOP |
921                             WS_VSCROLL | LBS_HASSTRINGS | LBS_USETABSTOPS,
922                             WS_EX_CLIENTEDGE,
923                             "", listid);
924                 MakeDragList(ctl);
925             }
926             break;
927
928           case 2:
929             /* The "Up" and "Down" buttons. */
930             /* XXX worry about accelerators if we have more than one
931              * prefslist on a panel */
932             r.left = left; r.right = wid;
933             r.top = cp->ypos + buttonpos; r.bottom = PUSHBTNHEIGHT;
934             doctl(cp, r, "BUTTON",
935                   BS_NOTIFY | WS_CHILD | WS_VISIBLE |
936                   WS_TABSTOP | BS_PUSHBUTTON,
937                   0, "&Up", upbid);
938
939             r.left = left; r.right = wid;
940             r.top = cp->ypos + buttonpos + PUSHBTNHEIGHT + GAPBETWEEN;
941             r.bottom = PUSHBTNHEIGHT;
942             doctl(cp, r, "BUTTON",
943                   BS_NOTIFY | WS_CHILD | WS_VISIBLE |
944                   WS_TABSTOP | BS_PUSHBUTTON,
945                   0, "&Down", dnbid);
946
947             break;
948
949         }
950     }
951
952     cp->ypos += totalheight + GAPBETWEEN;
953
954 }
955
956 /*
957  * Helper function for prefslist: move item in list box.
958  */
959 static void pl_moveitem(HWND hwnd, int listid, int src, int dst)
960 {
961     int tlen, val;
962     char *txt;
963     /* Get the item's data. */
964     tlen = SendDlgItemMessage (hwnd, listid, LB_GETTEXTLEN, src, 0);
965     txt = snewn(tlen+1, char);
966     SendDlgItemMessage (hwnd, listid, LB_GETTEXT, src, (LPARAM) txt);
967     val = SendDlgItemMessage (hwnd, listid, LB_GETITEMDATA, src, 0);
968     /* Deselect old location. */
969     SendDlgItemMessage (hwnd, listid, LB_SETSEL, FALSE, src);
970     /* Delete it at the old location. */
971     SendDlgItemMessage (hwnd, listid, LB_DELETESTRING, src, 0);
972     /* Insert it at new location. */
973     SendDlgItemMessage (hwnd, listid, LB_INSERTSTRING, dst,
974                         (LPARAM) txt);
975     SendDlgItemMessage (hwnd, listid, LB_SETITEMDATA, dst,
976                         (LPARAM) val);
977     /* Set selection. */
978     SendDlgItemMessage (hwnd, listid, LB_SETCURSEL, dst, 0);
979     sfree (txt);
980 }
981
982 int pl_itemfrompt(HWND hwnd, POINT cursor, BOOL scroll)
983 {
984     int ret;
985     POINT uppoint, downpoint;
986     int updist, downdist, upitem, downitem, i;
987
988     /*
989      * Ghastly hackery to try to figure out not which
990      * _item_, but which _gap between items_, the user
991      * is pointing at. We do this by first working out
992      * which list item is under the cursor, and then
993      * working out how far the cursor would have to
994      * move up or down before the answer was different.
995      * Then we put the insertion point _above_ the
996      * current item if the upper edge is closer than
997      * the lower edge, or _below_ it if vice versa.
998      */
999     ret = LBItemFromPt(hwnd, cursor, scroll);
1000     if (ret == -1)
1001         return ret;
1002     ret = LBItemFromPt(hwnd, cursor, FALSE);
1003     updist = downdist = 0;
1004     for (i = 1; i < 4096 && (!updist || !downdist); i++) {
1005         uppoint = downpoint = cursor;
1006         uppoint.y -= i;
1007         downpoint.y += i;
1008         upitem = LBItemFromPt(hwnd, uppoint, FALSE);
1009         downitem = LBItemFromPt(hwnd, downpoint, FALSE);
1010         if (!updist && upitem != ret)
1011             updist = i;
1012         if (!downdist && downitem != ret)
1013             downdist = i;
1014     }
1015     if (downdist < updist)
1016         ret++;
1017     return ret;
1018 }
1019
1020 /*
1021  * Handler for prefslist above.
1022  * 
1023  * Return value has bit 0 set if the dialog box procedure needs to
1024  * return TRUE from handling this message; it has bit 1 set if a
1025  * change may have been made in the contents of the list.
1026  */
1027 int handle_prefslist(struct prefslist *hdl,
1028                      int *array, int maxmemb,
1029                      int is_dlmsg, HWND hwnd,
1030                      WPARAM wParam, LPARAM lParam)
1031 {
1032     int i;
1033     int ret = 0;
1034
1035     if (is_dlmsg) {
1036
1037         if ((int)wParam == hdl->listid) {
1038             DRAGLISTINFO *dlm = (DRAGLISTINFO *)lParam;
1039             int dest = 0;              /* initialise to placate gcc */
1040             switch (dlm->uNotification) {
1041               case DL_BEGINDRAG:
1042                 /* Add a dummy item to make pl_itemfrompt() work
1043                  * better.
1044                  * FIXME: this causes scrollbar glitches if the count of
1045                  *        listbox contains >= its height. */
1046                 hdl->dummyitem =
1047                     SendDlgItemMessage(hwnd, hdl->listid,
1048                                        LB_ADDSTRING, 0, (LPARAM) "");
1049
1050                 hdl->srcitem = LBItemFromPt(dlm->hWnd, dlm->ptCursor, TRUE);
1051                 hdl->dragging = 0;
1052                 /* XXX hack Q183115 */
1053                 SetWindowLongPtr(hwnd, DWLP_MSGRESULT, TRUE);
1054                 ret |= 1; break;
1055               case DL_CANCELDRAG:
1056                 DrawInsert(hwnd, dlm->hWnd, -1);     /* Clear arrow */
1057                 SendDlgItemMessage(hwnd, hdl->listid,
1058                                    LB_DELETESTRING, hdl->dummyitem, 0);
1059                 hdl->dragging = 0;
1060                 ret |= 1; break;
1061               case DL_DRAGGING:
1062                 hdl->dragging = 1;
1063                 dest = pl_itemfrompt(dlm->hWnd, dlm->ptCursor, TRUE);
1064                 if (dest > hdl->dummyitem) dest = hdl->dummyitem;
1065                 DrawInsert (hwnd, dlm->hWnd, dest);
1066                 if (dest >= 0)
1067                     SetWindowLongPtr(hwnd, DWLP_MSGRESULT, DL_MOVECURSOR);
1068                 else
1069                     SetWindowLongPtr(hwnd, DWLP_MSGRESULT, DL_STOPCURSOR);
1070                 ret |= 1; break;
1071               case DL_DROPPED:
1072                 if (hdl->dragging) {
1073                     dest = pl_itemfrompt(dlm->hWnd, dlm->ptCursor, TRUE);
1074                     if (dest > hdl->dummyitem) dest = hdl->dummyitem;
1075                     DrawInsert (hwnd, dlm->hWnd, -1);
1076                 }
1077                 SendDlgItemMessage(hwnd, hdl->listid,
1078                                    LB_DELETESTRING, hdl->dummyitem, 0);
1079                 if (hdl->dragging) {
1080                     hdl->dragging = 0;
1081                     if (dest >= 0) {
1082                         /* Correct for "missing" item. */
1083                         if (dest > hdl->srcitem) dest--;
1084                         pl_moveitem(hwnd, hdl->listid, hdl->srcitem, dest);
1085                     }
1086                     ret |= 2;
1087                 }
1088                 ret |= 1; break;
1089             }
1090         }
1091
1092     } else {
1093
1094         if (((LOWORD(wParam) == hdl->upbid) ||
1095              (LOWORD(wParam) == hdl->dnbid)) &&
1096             ((HIWORD(wParam) == BN_CLICKED) ||
1097              (HIWORD(wParam) == BN_DOUBLECLICKED))) {
1098             /* Move an item up or down the list. */
1099             /* Get the current selection, if any. */
1100             int selection = SendDlgItemMessage (hwnd, hdl->listid, LB_GETCURSEL, 0, 0);
1101             if (selection == LB_ERR) {
1102                 MessageBeep(0);
1103             } else {
1104                 int nitems;
1105                 /* Get the total number of items. */
1106                 nitems = SendDlgItemMessage (hwnd, hdl->listid, LB_GETCOUNT, 0, 0);
1107                 /* Should we do anything? */
1108                 if (LOWORD(wParam) == hdl->upbid && (selection > 0))
1109                     pl_moveitem(hwnd, hdl->listid, selection, selection - 1);
1110                 else if (LOWORD(wParam) == hdl->dnbid && (selection < nitems - 1))
1111                     pl_moveitem(hwnd, hdl->listid, selection, selection + 1);
1112                 ret |= 2;
1113             }
1114
1115         }
1116
1117     }
1118
1119     if (array) {
1120         /* Update array to match the list box. */
1121         for (i=0; i < maxmemb; i++)
1122             array[i] = SendDlgItemMessage (hwnd, hdl->listid, LB_GETITEMDATA,
1123                                            i, 0);
1124     }
1125
1126     return ret;
1127 }
1128
1129 /*
1130  * A progress bar (from Common Controls). We like our progress bars
1131  * to be smooth and unbroken, without those ugly divisions; some
1132  * older compilers may not support that, but that's life.
1133  */
1134 void progressbar(struct ctlpos *cp, int id)
1135 {
1136     RECT r;
1137
1138     r.left = GAPBETWEEN;
1139     r.top = cp->ypos;
1140     r.right = cp->width;
1141     r.bottom = PROGBARHEIGHT;
1142     cp->ypos += r.bottom + GAPBETWEEN;
1143
1144     doctl(cp, r, PROGRESS_CLASS, WS_CHILD | WS_VISIBLE
1145 #ifdef PBS_SMOOTH
1146           | PBS_SMOOTH
1147 #endif
1148           , WS_EX_CLIENTEDGE, "", id);
1149 }
1150
1151 /* ----------------------------------------------------------------------
1152  * Platform-specific side of portable dialog-box mechanism.
1153  */
1154
1155 /*
1156  * This function takes a string, escapes all the ampersands, and
1157  * places a single (unescaped) ampersand in front of the first
1158  * occurrence of the given shortcut character (which may be
1159  * NO_SHORTCUT).
1160  * 
1161  * Return value is a malloc'ed copy of the processed version of the
1162  * string.
1163  */
1164 static char *shortcut_escape(const char *text, char shortcut)
1165 {
1166     char *ret;
1167     char const *p;
1168     char *q;
1169
1170     if (!text)
1171         return NULL;                   /* sfree won't choke on this */
1172
1173     ret = snewn(2*strlen(text)+1, char);   /* size potentially doubles! */
1174     shortcut = tolower((unsigned char)shortcut);
1175
1176     p = text;
1177     q = ret;
1178     while (*p) {
1179         if (shortcut != NO_SHORTCUT &&
1180             tolower((unsigned char)*p) == shortcut) {
1181             *q++ = '&';
1182             shortcut = NO_SHORTCUT;    /* stop it happening twice */
1183         } else if (*p == '&') {
1184             *q++ = '&';
1185         }
1186         *q++ = *p++;
1187     }
1188     *q = '\0';
1189     return ret;
1190 }
1191
1192 void winctrl_add_shortcuts(struct dlgparam *dp, struct winctrl *c)
1193 {
1194     int i;
1195     for (i = 0; i < lenof(c->shortcuts); i++)
1196         if (c->shortcuts[i] != NO_SHORTCUT) {
1197             unsigned char s = tolower((unsigned char)c->shortcuts[i]);
1198             assert(!dp->shortcuts[s]);
1199             dp->shortcuts[s] = TRUE;
1200         }
1201 }
1202
1203 void winctrl_rem_shortcuts(struct dlgparam *dp, struct winctrl *c)
1204 {
1205     int i;
1206     for (i = 0; i < lenof(c->shortcuts); i++)
1207         if (c->shortcuts[i] != NO_SHORTCUT) {
1208             unsigned char s = tolower((unsigned char)c->shortcuts[i]);
1209             assert(dp->shortcuts[s]);
1210             dp->shortcuts[s] = FALSE;
1211         }
1212 }
1213
1214 static int winctrl_cmp_byctrl(void *av, void *bv)
1215 {
1216     struct winctrl *a = (struct winctrl *)av;
1217     struct winctrl *b = (struct winctrl *)bv;
1218     if (a->ctrl < b->ctrl)
1219         return -1;
1220     else if (a->ctrl > b->ctrl)
1221         return +1;
1222     else
1223         return 0;
1224 }
1225 static int winctrl_cmp_byid(void *av, void *bv)
1226 {
1227     struct winctrl *a = (struct winctrl *)av;
1228     struct winctrl *b = (struct winctrl *)bv;
1229     if (a->base_id < b->base_id)
1230         return -1;
1231     else if (a->base_id > b->base_id)
1232         return +1;
1233     else
1234         return 0;
1235 }
1236 static int winctrl_cmp_byctrl_find(void *av, void *bv)
1237 {
1238     union control *a = (union control *)av;
1239     struct winctrl *b = (struct winctrl *)bv;
1240     if (a < b->ctrl)
1241         return -1;
1242     else if (a > b->ctrl)
1243         return +1;
1244     else
1245         return 0;
1246 }
1247 static int winctrl_cmp_byid_find(void *av, void *bv)
1248 {
1249     int *a = (int *)av;
1250     struct winctrl *b = (struct winctrl *)bv;
1251     if (*a < b->base_id)
1252         return -1;
1253     else if (*a >= b->base_id + b->num_ids)
1254         return +1;
1255     else
1256         return 0;
1257 }
1258
1259 void winctrl_init(struct winctrls *wc)
1260 {
1261     wc->byctrl = newtree234(winctrl_cmp_byctrl);
1262     wc->byid = newtree234(winctrl_cmp_byid);
1263 }
1264 void winctrl_cleanup(struct winctrls *wc)
1265 {
1266     struct winctrl *c;
1267
1268     while ((c = index234(wc->byid, 0)) != NULL) {
1269         winctrl_remove(wc, c);
1270         sfree(c->data);
1271         sfree(c);
1272     }
1273
1274     freetree234(wc->byctrl);
1275     freetree234(wc->byid);
1276     wc->byctrl = wc->byid = NULL;
1277 }
1278
1279 void winctrl_add(struct winctrls *wc, struct winctrl *c)
1280 {
1281     struct winctrl *ret;
1282     if (c->ctrl) {
1283         ret = add234(wc->byctrl, c);
1284         assert(ret == c);
1285     }
1286     ret = add234(wc->byid, c);
1287     assert(ret == c);
1288 }
1289
1290 void winctrl_remove(struct winctrls *wc, struct winctrl *c)
1291 {
1292     struct winctrl *ret;
1293     ret = del234(wc->byctrl, c);
1294     ret = del234(wc->byid, c);
1295     assert(ret == c);
1296 }
1297
1298 struct winctrl *winctrl_findbyctrl(struct winctrls *wc, union control *ctrl)
1299 {
1300     return find234(wc->byctrl, ctrl, winctrl_cmp_byctrl_find);
1301 }
1302
1303 struct winctrl *winctrl_findbyid(struct winctrls *wc, int id)
1304 {
1305     return find234(wc->byid, &id, winctrl_cmp_byid_find);
1306 }
1307
1308 struct winctrl *winctrl_findbyindex(struct winctrls *wc, int index)
1309 {
1310     return index234(wc->byid, index);
1311 }
1312
1313 void winctrl_layout(struct dlgparam *dp, struct winctrls *wc,
1314                     struct ctlpos *cp, struct controlset *s, int *id)
1315 {
1316     struct ctlpos columns[16];
1317     int ncols, colstart, colspan;
1318
1319     struct ctlpos tabdelays[16];
1320     union control *tabdelayed[16];
1321     int ntabdelays;
1322
1323     struct ctlpos pos;
1324
1325     char shortcuts[MAX_SHORTCUTS_PER_CTRL];
1326     int nshortcuts;
1327     char *escaped;
1328     int i, actual_base_id, base_id, num_ids;
1329     void *data;
1330
1331     base_id = *id;
1332
1333     /* Start a containing box, if we have a boxname. */
1334     if (s->boxname && *s->boxname) {
1335         struct winctrl *c = snew(struct winctrl);
1336         c->ctrl = NULL;
1337         c->base_id = base_id;
1338         c->num_ids = 1;
1339         c->data = NULL;
1340         memset(c->shortcuts, NO_SHORTCUT, lenof(c->shortcuts));
1341         winctrl_add(wc, c);
1342         beginbox(cp, s->boxtitle, base_id);
1343         base_id++;
1344     }
1345
1346     /* Draw a title, if we have one. */
1347     if (!s->boxname && s->boxtitle) {
1348         struct winctrl *c = snew(struct winctrl);
1349         c->ctrl = NULL;
1350         c->base_id = base_id;
1351         c->num_ids = 1;
1352         c->data = dupstr(s->boxtitle);
1353         memset(c->shortcuts, NO_SHORTCUT, lenof(c->shortcuts));
1354         winctrl_add(wc, c);
1355         paneltitle(cp, base_id);
1356         base_id++;
1357     }
1358
1359     /* Initially we have just one column. */
1360     ncols = 1;
1361     columns[0] = *cp;                  /* structure copy */
1362
1363     /* And initially, there are no pending tab-delayed controls. */
1364     ntabdelays = 0;
1365
1366     /* Loop over each control in the controlset. */
1367     for (i = 0; i < s->ncontrols; i++) {
1368         union control *ctrl = s->ctrls[i];
1369
1370         /*
1371          * Generic processing that pertains to all control types.
1372          * At the end of this if statement, we'll have produced
1373          * `ctrl' (a pointer to the control we have to create, or
1374          * think about creating, in this iteration of the loop),
1375          * `pos' (a suitable ctlpos with which to position it), and
1376          * `c' (a winctrl structure to receive details of the
1377          * dialog IDs). Or we'll have done a `continue', if it was
1378          * CTRL_COLUMNS and doesn't require any control creation at
1379          * all.
1380          */
1381         if (ctrl->generic.type == CTRL_COLUMNS) {
1382             assert((ctrl->columns.ncols == 1) ^ (ncols == 1));
1383
1384             if (ncols == 1) {
1385                 /*
1386                  * We're splitting into multiple columns.
1387                  */
1388                 int lpercent, rpercent, lx, rx, i;
1389
1390                 ncols = ctrl->columns.ncols;
1391                 assert(ncols <= lenof(columns));
1392                 for (i = 1; i < ncols; i++)
1393                     columns[i] = columns[0];   /* structure copy */
1394
1395                 lpercent = 0;
1396                 for (i = 0; i < ncols; i++) {
1397                     rpercent = lpercent + ctrl->columns.percentages[i];
1398                     lx = columns[i].xoff + lpercent *
1399                         (columns[i].width + GAPBETWEEN) / 100;
1400                     rx = columns[i].xoff + rpercent *
1401                         (columns[i].width + GAPBETWEEN) / 100;
1402                     columns[i].xoff = lx;
1403                     columns[i].width = rx - lx - GAPBETWEEN;
1404                     lpercent = rpercent;
1405                 }
1406             } else {
1407                 /*
1408                  * We're recombining the various columns into one.
1409                  */
1410                 int maxy = columns[0].ypos;
1411                 int i;
1412                 for (i = 1; i < ncols; i++)
1413                     if (maxy < columns[i].ypos)
1414                         maxy = columns[i].ypos;
1415                 ncols = 1;
1416                 columns[0] = *cp;      /* structure copy */
1417                 columns[0].ypos = maxy;
1418             }
1419
1420             continue;
1421         } else if (ctrl->generic.type == CTRL_TABDELAY) {
1422             int i;
1423
1424             assert(!ctrl->generic.tabdelay);
1425             ctrl = ctrl->tabdelay.ctrl;
1426
1427             for (i = 0; i < ntabdelays; i++)
1428                 if (tabdelayed[i] == ctrl)
1429                     break;
1430             assert(i < ntabdelays);    /* we have to have found it */
1431
1432             pos = tabdelays[i];        /* structure copy */
1433
1434             colstart = colspan = -1;   /* indicate this was tab-delayed */
1435
1436         } else {
1437             /*
1438              * If it wasn't one of those, it's a genuine control;
1439              * so we'll have to compute a position for it now, by
1440              * checking its column span.
1441              */
1442             int col;
1443
1444             colstart = COLUMN_START(ctrl->generic.column);
1445             colspan = COLUMN_SPAN(ctrl->generic.column);
1446
1447             pos = columns[colstart];   /* structure copy */
1448             pos.width = columns[colstart+colspan-1].width +
1449                 (columns[colstart+colspan-1].xoff - columns[colstart].xoff);
1450
1451             for (col = colstart; col < colstart+colspan; col++)
1452                 if (pos.ypos < columns[col].ypos)
1453                     pos.ypos = columns[col].ypos;
1454
1455             /*
1456              * If this control is to be tabdelayed, add it to the
1457              * tabdelay list, and unset pos.hwnd to inhibit actual
1458              * control creation.
1459              */
1460             if (ctrl->generic.tabdelay) {
1461                 assert(ntabdelays < lenof(tabdelays));
1462                 tabdelays[ntabdelays] = pos;   /* structure copy */
1463                 tabdelayed[ntabdelays] = ctrl;
1464                 ntabdelays++;
1465                 pos.hwnd = NULL;
1466             }
1467         }
1468
1469         /* Most controls don't need anything in c->data. */
1470         data = NULL;
1471
1472         /* And they all start off with no shortcuts registered. */
1473         memset(shortcuts, NO_SHORTCUT, lenof(shortcuts));
1474         nshortcuts = 0;
1475
1476         /* Almost all controls start at base_id. */
1477         actual_base_id = base_id;
1478
1479         /*
1480          * Now we're ready to actually create the control, by
1481          * switching on its type.
1482          */
1483         switch (ctrl->generic.type) {
1484           case CTRL_TEXT:
1485             {
1486                 char *wrapped, *escaped;
1487                 int lines;
1488                 num_ids = 1;
1489                 wrapped = staticwrap(&pos, cp->hwnd,
1490                                      ctrl->generic.label, &lines);
1491                 escaped = shortcut_escape(wrapped, NO_SHORTCUT);
1492                 statictext(&pos, escaped, lines, base_id);
1493                 sfree(escaped);
1494                 sfree(wrapped);
1495             }
1496             break;
1497           case CTRL_EDITBOX:
1498             num_ids = 2;               /* static, edit */
1499             escaped = shortcut_escape(ctrl->editbox.label,
1500                                       ctrl->editbox.shortcut);
1501             shortcuts[nshortcuts++] = ctrl->editbox.shortcut;
1502             if (ctrl->editbox.percentwidth == 100) {
1503                 if (ctrl->editbox.has_list)
1504                     combobox(&pos, escaped,
1505                              base_id, base_id+1);
1506                 else
1507                     editboxfw(&pos, ctrl->editbox.password, escaped,
1508                               base_id, base_id+1);
1509             } else {
1510                 if (ctrl->editbox.has_list) {
1511                     staticcombo(&pos, escaped, base_id, base_id+1,
1512                                 ctrl->editbox.percentwidth);
1513                 } else {
1514                     (ctrl->editbox.password ? staticpassedit : staticedit)
1515                         (&pos, escaped, base_id, base_id+1,
1516                          ctrl->editbox.percentwidth);
1517                 }
1518             }
1519             sfree(escaped);
1520             break;
1521           case CTRL_RADIO:
1522             num_ids = ctrl->radio.nbuttons + 1;   /* label as well */
1523             {
1524                 struct radio *buttons;
1525                 int i;
1526
1527                 escaped = shortcut_escape(ctrl->radio.label,
1528                                           ctrl->radio.shortcut);
1529                 shortcuts[nshortcuts++] = ctrl->radio.shortcut;
1530
1531                 buttons = snewn(ctrl->radio.nbuttons, struct radio);
1532
1533                 for (i = 0; i < ctrl->radio.nbuttons; i++) {
1534                     buttons[i].text =
1535                         shortcut_escape(ctrl->radio.buttons[i],
1536                                         (char)(ctrl->radio.shortcuts ?
1537                                                ctrl->radio.shortcuts[i] :
1538                                                NO_SHORTCUT));
1539                     buttons[i].id = base_id + 1 + i;
1540                     if (ctrl->radio.shortcuts) {
1541                         assert(nshortcuts < MAX_SHORTCUTS_PER_CTRL);
1542                         shortcuts[nshortcuts++] = ctrl->radio.shortcuts[i];
1543                     }
1544                 }
1545
1546                 radioline_common(&pos, escaped, base_id,
1547                                  ctrl->radio.ncolumns,
1548                                  buttons, ctrl->radio.nbuttons);
1549
1550                 for (i = 0; i < ctrl->radio.nbuttons; i++) {
1551                     sfree(buttons[i].text);
1552                 }
1553                 sfree(buttons);
1554                 sfree(escaped);
1555             }
1556             break;
1557           case CTRL_CHECKBOX:
1558             num_ids = 1;
1559             escaped = shortcut_escape(ctrl->checkbox.label,
1560                                       ctrl->checkbox.shortcut);
1561             shortcuts[nshortcuts++] = ctrl->checkbox.shortcut;
1562             checkbox(&pos, escaped, base_id);
1563             sfree(escaped);
1564             break;
1565           case CTRL_BUTTON:
1566             escaped = shortcut_escape(ctrl->button.label,
1567                                       ctrl->button.shortcut);
1568             shortcuts[nshortcuts++] = ctrl->button.shortcut;
1569             if (ctrl->button.iscancel)
1570                 actual_base_id = IDCANCEL;
1571             num_ids = 1;
1572             button(&pos, escaped, actual_base_id, ctrl->button.isdefault);
1573             sfree(escaped);
1574             break;
1575           case CTRL_LISTBOX:
1576             num_ids = 2;
1577             escaped = shortcut_escape(ctrl->listbox.label,
1578                                       ctrl->listbox.shortcut);
1579             shortcuts[nshortcuts++] = ctrl->listbox.shortcut;
1580             if (ctrl->listbox.draglist) {
1581                 data = snew(struct prefslist);
1582                 num_ids = 4;
1583                 prefslist(data, &pos, ctrl->listbox.height, escaped,
1584                           base_id, base_id+1, base_id+2, base_id+3);
1585                 shortcuts[nshortcuts++] = 'u';   /* Up */
1586                 shortcuts[nshortcuts++] = 'd';   /* Down */
1587             } else if (ctrl->listbox.height == 0) {
1588                 /* Drop-down list. */
1589                 if (ctrl->listbox.percentwidth == 100) {
1590                     staticddlbig(&pos, escaped,
1591                                  base_id, base_id+1);
1592                 } else {
1593                     staticddl(&pos, escaped, base_id,
1594                               base_id+1, ctrl->listbox.percentwidth);
1595                 }
1596             } else {
1597                 /* Ordinary list. */
1598                 listbox(&pos, escaped, base_id, base_id+1,
1599                         ctrl->listbox.height, ctrl->listbox.multisel);
1600             }
1601             if (ctrl->listbox.ncols) {
1602                 /*
1603                  * This method of getting the box width is a bit of
1604                  * a hack; we'd do better to try to retrieve the
1605                  * actual width in dialog units from doctl() just
1606                  * before MapDialogRect. But that's going to be no
1607                  * fun, and this should be good enough accuracy.
1608                  */
1609                 int width = cp->width * ctrl->listbox.percentwidth;
1610                 int *tabarray;
1611                 int i, percent;
1612
1613                 tabarray = snewn(ctrl->listbox.ncols-1, int);
1614                 percent = 0;
1615                 for (i = 0; i < ctrl->listbox.ncols-1; i++) {
1616                     percent += ctrl->listbox.percentages[i];
1617                     tabarray[i] = width * percent / 10000;
1618                 }
1619                 SendDlgItemMessage(cp->hwnd, base_id+1, LB_SETTABSTOPS,
1620                                    ctrl->listbox.ncols-1, (LPARAM)tabarray);
1621                 sfree(tabarray);
1622             }
1623             sfree(escaped);
1624             break;
1625           case CTRL_FILESELECT:
1626             num_ids = 3;
1627             escaped = shortcut_escape(ctrl->fileselect.label,
1628                                       ctrl->fileselect.shortcut);
1629             shortcuts[nshortcuts++] = ctrl->fileselect.shortcut;
1630             editbutton(&pos, escaped, base_id, base_id+1,
1631                        "Bro&wse...", base_id+2);
1632             shortcuts[nshortcuts++] = 'w';
1633             sfree(escaped);
1634             break;
1635           case CTRL_FONTSELECT:
1636             num_ids = 3;
1637             escaped = shortcut_escape(ctrl->fontselect.label,
1638                                       ctrl->fontselect.shortcut);
1639             shortcuts[nshortcuts++] = ctrl->fontselect.shortcut;
1640             statictext(&pos, escaped, 1, base_id);
1641             staticbtn(&pos, "", base_id+1, "Change...", base_id+2);
1642             data = fontspec_new("", 0, 0, 0);
1643             sfree(escaped);
1644             break;
1645           default:
1646             assert(!"Can't happen");
1647             num_ids = 0;               /* placate gcc */
1648             break;
1649         }
1650
1651         /*
1652          * Create a `struct winctrl' for this control, and advance
1653          * the dialog ID counter, if it's actually been created
1654          * (and isn't tabdelayed).
1655          */
1656         if (pos.hwnd) {
1657             struct winctrl *c = snew(struct winctrl);
1658
1659             c->ctrl = ctrl;
1660             c->base_id = actual_base_id;
1661             c->num_ids = num_ids;
1662             c->data = data;
1663             memcpy(c->shortcuts, shortcuts, sizeof(shortcuts));
1664             winctrl_add(wc, c);
1665             winctrl_add_shortcuts(dp, c);
1666             if (actual_base_id == base_id)
1667                 base_id += num_ids;
1668         }
1669
1670         if (colstart >= 0) {
1671             /*
1672              * Update the ypos in all columns crossed by this
1673              * control.
1674              */
1675             int i;
1676             for (i = colstart; i < colstart+colspan; i++)
1677                 columns[i].ypos = pos.ypos;
1678         }
1679     }
1680
1681     /*
1682      * We've now finished laying out the controls; so now update
1683      * the ctlpos and control ID that were passed in, terminate
1684      * any containing box, and return.
1685      */
1686     for (i = 0; i < ncols; i++)
1687         if (cp->ypos < columns[i].ypos)
1688             cp->ypos = columns[i].ypos;
1689     *id = base_id;
1690
1691     if (s->boxname && *s->boxname)
1692         endbox(cp);
1693 }
1694
1695 static void winctrl_set_focus(union control *ctrl, struct dlgparam *dp,
1696                               int has_focus)
1697 {
1698     if (has_focus) {
1699         if (dp->focused)
1700             dp->lastfocused = dp->focused;
1701         dp->focused = ctrl;
1702     } else if (!has_focus && dp->focused == ctrl) {
1703         dp->lastfocused = dp->focused;
1704         dp->focused = NULL;
1705     }
1706 }
1707
1708 union control *dlg_last_focused(union control *ctrl, void *dlg)
1709 {
1710     struct dlgparam *dp = (struct dlgparam *)dlg;
1711     return dp->focused == ctrl ? dp->lastfocused : dp->focused;
1712 }
1713
1714 /*
1715  * The dialog-box procedure calls this function to handle Windows
1716  * messages on a control we manage.
1717  */
1718 int winctrl_handle_command(struct dlgparam *dp, UINT msg,
1719                            WPARAM wParam, LPARAM lParam)
1720 {
1721     struct winctrl *c;
1722     union control *ctrl;
1723     int i, id, ret;
1724     static UINT draglistmsg = WM_NULL;
1725
1726     /*
1727      * Filter out pointless window messages. Our interest is in
1728      * WM_COMMAND and the drag list message, and nothing else.
1729      */
1730     if (draglistmsg == WM_NULL)
1731         draglistmsg = RegisterWindowMessage (DRAGLISTMSGSTRING);
1732
1733     if (msg != draglistmsg && msg != WM_COMMAND && msg != WM_DRAWITEM)
1734         return 0;
1735
1736     /*
1737      * Look up the control ID in our data.
1738      */
1739     c = NULL;
1740     for (i = 0; i < dp->nctrltrees; i++) {
1741         c = winctrl_findbyid(dp->controltrees[i], LOWORD(wParam));
1742         if (c)
1743             break;
1744     }
1745     if (!c)
1746         return 0;                      /* we have nothing to do */
1747
1748     if (msg == WM_DRAWITEM) {
1749         /*
1750          * Owner-draw request for a panel title.
1751          */
1752         LPDRAWITEMSTRUCT di = (LPDRAWITEMSTRUCT) lParam;
1753         HDC hdc = di->hDC;
1754         RECT r = di->rcItem;
1755         SIZE s;
1756
1757         SetMapMode(hdc, MM_TEXT);      /* ensure logical units == pixels */
1758
1759         GetTextExtentPoint32(hdc, (char *)c->data,
1760                                  strlen((char *)c->data), &s);
1761         DrawEdge(hdc, &r, EDGE_ETCHED, BF_ADJUST | BF_RECT);
1762         TextOut(hdc,
1763                 r.left + (r.right-r.left-s.cx)/2,
1764                 r.top + (r.bottom-r.top-s.cy)/2,
1765                 (char *)c->data, strlen((char *)c->data));
1766
1767         return TRUE;
1768     }
1769
1770     ctrl = c->ctrl;
1771     id = LOWORD(wParam) - c->base_id;
1772
1773     if (!ctrl || !ctrl->generic.handler)
1774         return 0;                      /* nothing we can do here */
1775
1776     /*
1777      * From here on we do not issue `return' statements until the
1778      * very end of the dialog box: any event handler is entitled to
1779      * ask for a colour selector, so we _must_ always allow control
1780      * to reach the end of this switch statement so that the
1781      * subsequent code can test dp->coloursel_wanted().
1782      */
1783     ret = 0;
1784     dp->coloursel_wanted = FALSE;
1785
1786     /*
1787      * Now switch on the control type and the message.
1788      */
1789     switch (ctrl->generic.type) {
1790       case CTRL_EDITBOX:
1791         if (msg == WM_COMMAND && !ctrl->editbox.has_list &&
1792             (HIWORD(wParam) == EN_SETFOCUS || HIWORD(wParam) == EN_KILLFOCUS))
1793             winctrl_set_focus(ctrl, dp, HIWORD(wParam) == EN_SETFOCUS);
1794         if (msg == WM_COMMAND && ctrl->editbox.has_list &&
1795             (HIWORD(wParam)==CBN_SETFOCUS || HIWORD(wParam)==CBN_KILLFOCUS))
1796             winctrl_set_focus(ctrl, dp, HIWORD(wParam) == CBN_SETFOCUS);
1797
1798         if (msg == WM_COMMAND && !ctrl->editbox.has_list &&
1799             HIWORD(wParam) == EN_CHANGE)
1800             ctrl->generic.handler(ctrl, dp, dp->data, EVENT_VALCHANGE);
1801         if (msg == WM_COMMAND &&
1802             ctrl->editbox.has_list) {
1803             if (HIWORD(wParam) == CBN_SELCHANGE) {
1804                 int index, len;
1805                 char *text;
1806
1807                 index = SendDlgItemMessage(dp->hwnd, c->base_id+1,
1808                                            CB_GETCURSEL, 0, 0);
1809                 len = SendDlgItemMessage(dp->hwnd, c->base_id+1,
1810                                          CB_GETLBTEXTLEN, index, 0);
1811                 text = snewn(len+1, char);
1812                 SendDlgItemMessage(dp->hwnd, c->base_id+1, CB_GETLBTEXT,
1813                                    index, (LPARAM)text);
1814                 SetDlgItemText(dp->hwnd, c->base_id+1, text);
1815                 sfree(text);
1816                 ctrl->generic.handler(ctrl, dp, dp->data, EVENT_VALCHANGE);
1817             } else if (HIWORD(wParam) == CBN_EDITCHANGE) {
1818                 ctrl->generic.handler(ctrl, dp, dp->data, EVENT_VALCHANGE);
1819             } else if (HIWORD(wParam) == CBN_KILLFOCUS) {
1820                 ctrl->generic.handler(ctrl, dp, dp->data, EVENT_REFRESH);
1821             }
1822
1823         }
1824         break;
1825       case CTRL_RADIO:
1826         if (msg == WM_COMMAND &&
1827             (HIWORD(wParam) == BN_SETFOCUS || HIWORD(wParam) == BN_KILLFOCUS))
1828             winctrl_set_focus(ctrl, dp, HIWORD(wParam) == BN_SETFOCUS);
1829         /*
1830          * We sometimes get spurious BN_CLICKED messages for the
1831          * radio button that is just about to _lose_ selection, if
1832          * we're switching using the arrow keys. Therefore we
1833          * double-check that the button in wParam is actually
1834          * checked before generating an event.
1835          */
1836         if (msg == WM_COMMAND &&
1837             (HIWORD(wParam) == BN_CLICKED ||
1838              HIWORD(wParam) == BN_DOUBLECLICKED) &&
1839             IsDlgButtonChecked(dp->hwnd, LOWORD(wParam))) {
1840             ctrl->generic.handler(ctrl, dp, dp->data, EVENT_VALCHANGE);
1841         }
1842         break;
1843       case CTRL_CHECKBOX:
1844         if (msg == WM_COMMAND &&
1845             (HIWORD(wParam) == BN_SETFOCUS || HIWORD(wParam) == BN_KILLFOCUS))
1846             winctrl_set_focus(ctrl, dp, HIWORD(wParam) == BN_SETFOCUS);
1847         if (msg == WM_COMMAND &&
1848             (HIWORD(wParam) == BN_CLICKED ||
1849              HIWORD(wParam) == BN_DOUBLECLICKED)) {
1850             ctrl->generic.handler(ctrl, dp, dp->data, EVENT_VALCHANGE);
1851         }
1852         break;
1853       case CTRL_BUTTON:
1854         if (msg == WM_COMMAND &&
1855             (HIWORD(wParam) == BN_SETFOCUS || HIWORD(wParam) == BN_KILLFOCUS))
1856             winctrl_set_focus(ctrl, dp, HIWORD(wParam) == BN_SETFOCUS);
1857         if (msg == WM_COMMAND &&
1858             (HIWORD(wParam) == BN_CLICKED ||
1859              HIWORD(wParam) == BN_DOUBLECLICKED)) {
1860             ctrl->generic.handler(ctrl, dp, dp->data, EVENT_ACTION);
1861         }
1862         break;
1863       case CTRL_LISTBOX:
1864         if (msg == WM_COMMAND && ctrl->listbox.height != 0 &&
1865             (HIWORD(wParam)==LBN_SETFOCUS || HIWORD(wParam)==LBN_KILLFOCUS))
1866             winctrl_set_focus(ctrl, dp, HIWORD(wParam) == LBN_SETFOCUS);
1867         if (msg == WM_COMMAND && ctrl->listbox.height == 0 &&
1868             (HIWORD(wParam)==CBN_SETFOCUS || HIWORD(wParam)==CBN_KILLFOCUS))
1869             winctrl_set_focus(ctrl, dp, HIWORD(wParam) == CBN_SETFOCUS);
1870         if (msg == WM_COMMAND && id >= 2 &&
1871             (HIWORD(wParam) == BN_SETFOCUS || HIWORD(wParam) == BN_KILLFOCUS))
1872             winctrl_set_focus(ctrl, dp, HIWORD(wParam) == BN_SETFOCUS);
1873         if (ctrl->listbox.draglist) {
1874             int pret;
1875             pret = handle_prefslist(c->data, NULL, 0, (msg != WM_COMMAND),
1876                                     dp->hwnd, wParam, lParam);
1877             if (pret & 2)
1878                 ctrl->generic.handler(ctrl, dp, dp->data, EVENT_VALCHANGE);
1879             ret = pret & 1;
1880         } else {
1881             if (msg == WM_COMMAND && HIWORD(wParam) == LBN_DBLCLK) {
1882                 SetCapture(dp->hwnd);
1883                 ctrl->generic.handler(ctrl, dp, dp->data, EVENT_ACTION);
1884             } else if (msg == WM_COMMAND && HIWORD(wParam) == LBN_SELCHANGE) {
1885                 ctrl->generic.handler(ctrl, dp, dp->data, EVENT_SELCHANGE);
1886             }
1887         }
1888         break;
1889       case CTRL_FILESELECT:
1890         if (msg == WM_COMMAND && id == 1 &&
1891             (HIWORD(wParam) == EN_SETFOCUS || HIWORD(wParam) == EN_KILLFOCUS))
1892             winctrl_set_focus(ctrl, dp, HIWORD(wParam) == EN_SETFOCUS);
1893         if (msg == WM_COMMAND && id == 2 &&
1894             (HIWORD(wParam) == BN_SETFOCUS || HIWORD(wParam) == BN_KILLFOCUS))
1895             winctrl_set_focus(ctrl, dp, HIWORD(wParam) == BN_SETFOCUS);
1896         if (msg == WM_COMMAND && id == 1 && HIWORD(wParam) == EN_CHANGE)
1897             ctrl->generic.handler(ctrl, dp, dp->data, EVENT_VALCHANGE);
1898         if (id == 2 &&
1899             (msg == WM_COMMAND &&
1900              (HIWORD(wParam) == BN_CLICKED ||
1901               HIWORD(wParam) == BN_DOUBLECLICKED))) {
1902             OPENFILENAME of;
1903             char filename[FILENAME_MAX];
1904
1905             memset(&of, 0, sizeof(of));
1906             of.hwndOwner = dp->hwnd;
1907             if (ctrl->fileselect.filter)
1908                 of.lpstrFilter = ctrl->fileselect.filter;
1909             else
1910                 of.lpstrFilter = "All Files (*.*)\0*\0\0\0";
1911             of.lpstrCustomFilter = NULL;
1912             of.nFilterIndex = 1;
1913             of.lpstrFile = filename;
1914             GetDlgItemText(dp->hwnd, c->base_id+1, filename, lenof(filename));
1915             filename[lenof(filename)-1] = '\0';
1916             of.nMaxFile = lenof(filename);
1917             of.lpstrFileTitle = NULL;
1918             of.lpstrTitle = ctrl->fileselect.title;
1919             of.Flags = 0;
1920             if (request_file(NULL, &of, FALSE, ctrl->fileselect.for_writing)) {
1921                 SetDlgItemText(dp->hwnd, c->base_id + 1, filename);
1922                 ctrl->generic.handler(ctrl, dp, dp->data, EVENT_VALCHANGE);
1923             }
1924         }
1925         break;
1926       case CTRL_FONTSELECT:
1927         if (msg == WM_COMMAND && id == 2 &&
1928             (HIWORD(wParam) == BN_SETFOCUS || HIWORD(wParam) == BN_KILLFOCUS))
1929             winctrl_set_focus(ctrl, dp, HIWORD(wParam) == BN_SETFOCUS);
1930         if (id == 2 &&
1931             (msg == WM_COMMAND &&
1932              (HIWORD(wParam) == BN_CLICKED ||
1933               HIWORD(wParam) == BN_DOUBLECLICKED))) {
1934             CHOOSEFONT cf;
1935             LOGFONT lf;
1936             HDC hdc;
1937             FontSpec *fs = (FontSpec *)c->data;
1938
1939             hdc = GetDC(0);
1940             lf.lfHeight = -MulDiv(fs->height,
1941                                   GetDeviceCaps(hdc, LOGPIXELSY), 72);
1942             ReleaseDC(0, hdc);
1943             lf.lfWidth = lf.lfEscapement = lf.lfOrientation = 0;
1944             lf.lfItalic = lf.lfUnderline = lf.lfStrikeOut = 0;
1945             lf.lfWeight = (fs->isbold ? FW_BOLD : 0);
1946             lf.lfCharSet = fs->charset;
1947             lf.lfOutPrecision = OUT_DEFAULT_PRECIS;
1948             lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
1949             lf.lfQuality = DEFAULT_QUALITY;
1950             lf.lfPitchAndFamily = FIXED_PITCH | FF_DONTCARE;
1951             strncpy(lf.lfFaceName, fs->name,
1952                     sizeof(lf.lfFaceName) - 1);
1953             lf.lfFaceName[sizeof(lf.lfFaceName) - 1] = '\0';
1954
1955             cf.lStructSize = sizeof(cf);
1956             cf.hwndOwner = dp->hwnd;
1957             cf.lpLogFont = &lf;
1958             cf.Flags = (dp->fixed_pitch_fonts ? CF_FIXEDPITCHONLY : 0) |
1959                 CF_FORCEFONTEXIST | CF_INITTOLOGFONTSTRUCT | CF_SCREENFONTS;
1960
1961             if (ChooseFont(&cf)) {
1962                 fs = fontspec_new(lf.lfFaceName, (lf.lfWeight == FW_BOLD),
1963                                   cf.iPointSize / 10, lf.lfCharSet);
1964                 dlg_fontsel_set(ctrl, dp, fs);
1965                 fontspec_free(fs);
1966
1967                 ctrl->generic.handler(ctrl, dp, dp->data, EVENT_VALCHANGE);
1968             }
1969         }
1970         break;
1971     }
1972
1973     /*
1974      * If the above event handler has asked for a colour selector,
1975      * now is the time to generate one.
1976      */
1977     if (dp->coloursel_wanted) {
1978         static CHOOSECOLOR cc;
1979         static DWORD custom[16] = { 0 };    /* zero initialisers */
1980         cc.lStructSize = sizeof(cc);
1981         cc.hwndOwner = dp->hwnd;
1982         cc.hInstance = (HWND) hinst;
1983         cc.lpCustColors = custom;
1984         cc.rgbResult = RGB(dp->coloursel_result.r,
1985                            dp->coloursel_result.g,
1986                            dp->coloursel_result.b);
1987         cc.Flags = CC_FULLOPEN | CC_RGBINIT;
1988         if (ChooseColor(&cc)) {
1989             dp->coloursel_result.r =
1990                 (unsigned char) (cc.rgbResult & 0xFF);
1991             dp->coloursel_result.g =
1992                 (unsigned char) (cc.rgbResult >> 8) & 0xFF;
1993             dp->coloursel_result.b =
1994                 (unsigned char) (cc.rgbResult >> 16) & 0xFF;
1995             dp->coloursel_result.ok = TRUE;
1996         } else
1997             dp->coloursel_result.ok = FALSE;
1998         ctrl->generic.handler(ctrl, dp, dp->data, EVENT_CALLBACK);
1999     }
2000
2001     return ret;
2002 }
2003
2004 /*
2005  * This function can be called to produce context help on a
2006  * control. Returns TRUE if it has actually launched some help.
2007  */
2008 int winctrl_context_help(struct dlgparam *dp, HWND hwnd, int id)
2009 {
2010     int i;
2011     struct winctrl *c;
2012
2013     /*
2014      * Look up the control ID in our data.
2015      */
2016     c = NULL;
2017     for (i = 0; i < dp->nctrltrees; i++) {
2018         c = winctrl_findbyid(dp->controltrees[i], id);
2019         if (c)
2020             break;
2021     }
2022     if (!c)
2023         return 0;                      /* we have nothing to do */
2024
2025     /*
2026      * This is the Windows front end, so we're allowed to assume
2027      * `helpctx.p' is a context string.
2028      */
2029     if (!c->ctrl || !c->ctrl->generic.helpctx.p)
2030         return 0;                      /* no help available for this ctrl */
2031
2032     launch_help(hwnd, c->ctrl->generic.helpctx.p);
2033     return 1;
2034 }
2035
2036 /*
2037  * Now the various functions that the platform-independent
2038  * mechanism can call to access the dialog box entries.
2039  */
2040
2041 static struct winctrl *dlg_findbyctrl(struct dlgparam *dp, union control *ctrl)
2042 {
2043     int i;
2044
2045     for (i = 0; i < dp->nctrltrees; i++) {
2046         struct winctrl *c = winctrl_findbyctrl(dp->controltrees[i], ctrl);
2047         if (c)
2048             return c;
2049     }
2050     return NULL;
2051 }
2052
2053 void dlg_radiobutton_set(union control *ctrl, void *dlg, int whichbutton)
2054 {
2055     struct dlgparam *dp = (struct dlgparam *)dlg;
2056     struct winctrl *c = dlg_findbyctrl(dp, ctrl);
2057     assert(c && c->ctrl->generic.type == CTRL_RADIO);
2058     CheckRadioButton(dp->hwnd,
2059                      c->base_id + 1,
2060                      c->base_id + c->ctrl->radio.nbuttons,
2061                      c->base_id + 1 + whichbutton);
2062 }
2063
2064 int dlg_radiobutton_get(union control *ctrl, void *dlg)
2065 {
2066     struct dlgparam *dp = (struct dlgparam *)dlg;
2067     struct winctrl *c = dlg_findbyctrl(dp, ctrl);
2068     int i;
2069     assert(c && c->ctrl->generic.type == CTRL_RADIO);
2070     for (i = 0; i < c->ctrl->radio.nbuttons; i++)
2071         if (IsDlgButtonChecked(dp->hwnd, c->base_id + 1 + i))
2072             return i;
2073     assert(!"No radio button was checked?!");
2074     return 0;
2075 }
2076
2077 void dlg_checkbox_set(union control *ctrl, void *dlg, int checked)
2078 {
2079     struct dlgparam *dp = (struct dlgparam *)dlg;
2080     struct winctrl *c = dlg_findbyctrl(dp, ctrl);
2081     assert(c && c->ctrl->generic.type == CTRL_CHECKBOX);
2082     CheckDlgButton(dp->hwnd, c->base_id, (checked != 0));
2083 }
2084
2085 int dlg_checkbox_get(union control *ctrl, void *dlg)
2086 {
2087     struct dlgparam *dp = (struct dlgparam *)dlg;
2088     struct winctrl *c = dlg_findbyctrl(dp, ctrl);
2089     assert(c && c->ctrl->generic.type == CTRL_CHECKBOX);
2090     return 0 != IsDlgButtonChecked(dp->hwnd, c->base_id);
2091 }
2092
2093 void dlg_editbox_set(union control *ctrl, void *dlg, char const *text)
2094 {
2095     struct dlgparam *dp = (struct dlgparam *)dlg;
2096     struct winctrl *c = dlg_findbyctrl(dp, ctrl);
2097     assert(c && c->ctrl->generic.type == CTRL_EDITBOX);
2098     SetDlgItemText(dp->hwnd, c->base_id+1, text);
2099 }
2100
2101 char *dlg_editbox_get(union control *ctrl, void *dlg)
2102 {
2103     struct dlgparam *dp = (struct dlgparam *)dlg;
2104     struct winctrl *c = dlg_findbyctrl(dp, ctrl);
2105     assert(c && c->ctrl->generic.type == CTRL_EDITBOX);
2106     return GetDlgItemText_alloc(dp->hwnd, c->base_id+1);
2107 }
2108
2109 /* The `listbox' functions can also apply to combo boxes. */
2110 void dlg_listbox_clear(union control *ctrl, void *dlg)
2111 {
2112     struct dlgparam *dp = (struct dlgparam *)dlg;
2113     struct winctrl *c = dlg_findbyctrl(dp, ctrl);
2114     int msg;
2115     assert(c &&
2116            (c->ctrl->generic.type == CTRL_LISTBOX ||
2117             (c->ctrl->generic.type == CTRL_EDITBOX &&
2118              c->ctrl->editbox.has_list)));
2119     msg = (c->ctrl->generic.type==CTRL_LISTBOX && c->ctrl->listbox.height!=0 ?
2120            LB_RESETCONTENT : CB_RESETCONTENT);
2121     SendDlgItemMessage(dp->hwnd, c->base_id+1, msg, 0, 0);
2122 }
2123
2124 void dlg_listbox_del(union control *ctrl, void *dlg, int index)
2125 {
2126     struct dlgparam *dp = (struct dlgparam *)dlg;
2127     struct winctrl *c = dlg_findbyctrl(dp, ctrl);
2128     int msg;
2129     assert(c &&
2130            (c->ctrl->generic.type == CTRL_LISTBOX ||
2131             (c->ctrl->generic.type == CTRL_EDITBOX &&
2132              c->ctrl->editbox.has_list)));
2133     msg = (c->ctrl->generic.type==CTRL_LISTBOX && c->ctrl->listbox.height!=0 ?
2134            LB_DELETESTRING : CB_DELETESTRING);
2135     SendDlgItemMessage(dp->hwnd, c->base_id+1, msg, index, 0);
2136 }
2137
2138 void dlg_listbox_add(union control *ctrl, void *dlg, char const *text)
2139 {
2140     struct dlgparam *dp = (struct dlgparam *)dlg;
2141     struct winctrl *c = dlg_findbyctrl(dp, ctrl);
2142     int msg;
2143     assert(c &&
2144            (c->ctrl->generic.type == CTRL_LISTBOX ||
2145             (c->ctrl->generic.type == CTRL_EDITBOX &&
2146              c->ctrl->editbox.has_list)));
2147     msg = (c->ctrl->generic.type==CTRL_LISTBOX && c->ctrl->listbox.height!=0 ?
2148            LB_ADDSTRING : CB_ADDSTRING);
2149     SendDlgItemMessage(dp->hwnd, c->base_id+1, msg, 0, (LPARAM)text);
2150 }
2151
2152 /*
2153  * Each listbox entry may have a numeric id associated with it.
2154  * Note that some front ends only permit a string to be stored at
2155  * each position, which means that _if_ you put two identical
2156  * strings in any listbox then you MUST not assign them different
2157  * IDs and expect to get meaningful results back.
2158  */
2159 void dlg_listbox_addwithid(union control *ctrl, void *dlg,
2160                            char const *text, int id)
2161 {
2162     struct dlgparam *dp = (struct dlgparam *)dlg;
2163     struct winctrl *c = dlg_findbyctrl(dp, ctrl);
2164     int msg, msg2, index;
2165     assert(c &&
2166            (c->ctrl->generic.type == CTRL_LISTBOX ||
2167             (c->ctrl->generic.type == CTRL_EDITBOX &&
2168              c->ctrl->editbox.has_list)));
2169     msg = (c->ctrl->generic.type==CTRL_LISTBOX && c->ctrl->listbox.height!=0 ?
2170            LB_ADDSTRING : CB_ADDSTRING);
2171     msg2 = (c->ctrl->generic.type==CTRL_LISTBOX && c->ctrl->listbox.height!=0 ?
2172            LB_SETITEMDATA : CB_SETITEMDATA);
2173     index = SendDlgItemMessage(dp->hwnd, c->base_id+1, msg, 0, (LPARAM)text);
2174     SendDlgItemMessage(dp->hwnd, c->base_id+1, msg2, index, (LPARAM)id);
2175 }
2176
2177 int dlg_listbox_getid(union control *ctrl, void *dlg, int index)
2178 {
2179     struct dlgparam *dp = (struct dlgparam *)dlg;
2180     struct winctrl *c = dlg_findbyctrl(dp, ctrl);
2181     int msg;
2182     assert(c && c->ctrl->generic.type == CTRL_LISTBOX);
2183     msg = (c->ctrl->listbox.height != 0 ? LB_GETITEMDATA : CB_GETITEMDATA);
2184     return
2185         SendDlgItemMessage(dp->hwnd, c->base_id+1, msg, index, 0);
2186 }
2187
2188 /* dlg_listbox_index returns <0 if no single element is selected. */
2189 int dlg_listbox_index(union control *ctrl, void *dlg)
2190 {
2191     struct dlgparam *dp = (struct dlgparam *)dlg;
2192     struct winctrl *c = dlg_findbyctrl(dp, ctrl);
2193     int msg, ret;
2194     assert(c && c->ctrl->generic.type == CTRL_LISTBOX);
2195     if (c->ctrl->listbox.multisel) {
2196         assert(c->ctrl->listbox.height != 0); /* not combo box */
2197         ret = SendDlgItemMessage(dp->hwnd, c->base_id+1, LB_GETSELCOUNT, 0, 0);
2198         if (ret == LB_ERR || ret > 1)
2199             return -1;
2200     }
2201     msg = (c->ctrl->listbox.height != 0 ? LB_GETCURSEL : CB_GETCURSEL);
2202     ret = SendDlgItemMessage(dp->hwnd, c->base_id+1, msg, 0, 0);
2203     if (ret == LB_ERR)
2204         return -1;
2205     else
2206         return ret;
2207 }
2208
2209 int dlg_listbox_issel(union control *ctrl, void *dlg, int index)
2210 {
2211     struct dlgparam *dp = (struct dlgparam *)dlg;
2212     struct winctrl *c = dlg_findbyctrl(dp, ctrl);
2213     assert(c && c->ctrl->generic.type == CTRL_LISTBOX &&
2214            c->ctrl->listbox.multisel &&
2215            c->ctrl->listbox.height != 0);
2216     return
2217         SendDlgItemMessage(dp->hwnd, c->base_id+1, LB_GETSEL, index, 0);
2218 }
2219
2220 void dlg_listbox_select(union control *ctrl, void *dlg, int index)
2221 {
2222     struct dlgparam *dp = (struct dlgparam *)dlg;
2223     struct winctrl *c = dlg_findbyctrl(dp, ctrl);
2224     int msg;
2225     assert(c && c->ctrl->generic.type == CTRL_LISTBOX &&
2226            !c->ctrl->listbox.multisel);
2227     msg = (c->ctrl->listbox.height != 0 ? LB_SETCURSEL : CB_SETCURSEL);
2228     SendDlgItemMessage(dp->hwnd, c->base_id+1, msg, index, 0);
2229 }
2230
2231 void dlg_text_set(union control *ctrl, void *dlg, char const *text)
2232 {
2233     struct dlgparam *dp = (struct dlgparam *)dlg;
2234     struct winctrl *c = dlg_findbyctrl(dp, ctrl);
2235     assert(c && c->ctrl->generic.type == CTRL_TEXT);
2236     SetDlgItemText(dp->hwnd, c->base_id, text);
2237 }
2238
2239 void dlg_label_change(union control *ctrl, void *dlg, char const *text)
2240 {
2241     struct dlgparam *dp = (struct dlgparam *)dlg;
2242     struct winctrl *c = dlg_findbyctrl(dp, ctrl);
2243     char *escaped = NULL;
2244     int id = -1;
2245
2246     assert(c);
2247     switch (c->ctrl->generic.type) {
2248       case CTRL_EDITBOX:
2249         escaped = shortcut_escape(text, c->ctrl->editbox.shortcut);
2250         id = c->base_id;
2251         break;
2252       case CTRL_RADIO:
2253         escaped = shortcut_escape(text, c->ctrl->radio.shortcut);
2254         id = c->base_id;
2255         break;
2256       case CTRL_CHECKBOX:
2257         escaped = shortcut_escape(text, ctrl->checkbox.shortcut);
2258         id = c->base_id;
2259         break;
2260       case CTRL_BUTTON:
2261         escaped = shortcut_escape(text, ctrl->button.shortcut);
2262         id = c->base_id;
2263         break;
2264       case CTRL_LISTBOX:
2265         escaped = shortcut_escape(text, ctrl->listbox.shortcut);
2266         id = c->base_id;
2267         break;
2268       case CTRL_FILESELECT:
2269         escaped = shortcut_escape(text, ctrl->fileselect.shortcut);
2270         id = c->base_id;
2271         break;
2272       case CTRL_FONTSELECT:
2273         escaped = shortcut_escape(text, ctrl->fontselect.shortcut);
2274         id = c->base_id;
2275         break;
2276       default:
2277         assert(!"Can't happen");
2278         break;
2279     }
2280     if (escaped) {
2281         SetDlgItemText(dp->hwnd, id, escaped);
2282         sfree(escaped);
2283     }
2284 }
2285
2286 void dlg_filesel_set(union control *ctrl, void *dlg, Filename *fn)
2287 {
2288     struct dlgparam *dp = (struct dlgparam *)dlg;
2289     struct winctrl *c = dlg_findbyctrl(dp, ctrl);
2290     assert(c && c->ctrl->generic.type == CTRL_FILESELECT);
2291     SetDlgItemText(dp->hwnd, c->base_id+1, fn->path);
2292 }
2293
2294 Filename *dlg_filesel_get(union control *ctrl, void *dlg)
2295 {
2296     struct dlgparam *dp = (struct dlgparam *)dlg;
2297     struct winctrl *c = dlg_findbyctrl(dp, ctrl);
2298     char *tmp;
2299     Filename *ret;
2300     assert(c && c->ctrl->generic.type == CTRL_FILESELECT);
2301     tmp = GetDlgItemText_alloc(dp->hwnd, c->base_id+1);
2302     ret = filename_from_str(tmp);
2303     sfree(tmp);
2304     return ret;
2305 }
2306
2307 void dlg_fontsel_set(union control *ctrl, void *dlg, FontSpec *fs)
2308 {
2309     char *buf, *boldstr;
2310     struct dlgparam *dp = (struct dlgparam *)dlg;
2311     struct winctrl *c = dlg_findbyctrl(dp, ctrl);
2312     assert(c && c->ctrl->generic.type == CTRL_FONTSELECT);
2313
2314     fontspec_free((FontSpec *)c->data);
2315     c->data = fontspec_copy(fs);
2316
2317     boldstr = (fs->isbold ? "bold, " : "");
2318     if (fs->height == 0)
2319         buf = dupprintf("Font: %s, %sdefault height", fs->name, boldstr);
2320     else
2321         buf = dupprintf("Font: %s, %s%d-%s", fs->name, boldstr,
2322                         (fs->height < 0 ? -fs->height : fs->height),
2323                         (fs->height < 0 ? "pixel" : "point"));
2324     SetDlgItemText(dp->hwnd, c->base_id+1, buf);
2325     sfree(buf);
2326
2327     dlg_auto_set_fixed_pitch_flag(dp);
2328 }
2329
2330 FontSpec *dlg_fontsel_get(union control *ctrl, void *dlg)
2331 {
2332     struct dlgparam *dp = (struct dlgparam *)dlg;
2333     struct winctrl *c = dlg_findbyctrl(dp, ctrl);
2334     assert(c && c->ctrl->generic.type == CTRL_FONTSELECT);
2335     return fontspec_copy((FontSpec *)c->data);
2336 }
2337
2338 /*
2339  * Bracketing a large set of updates in these two functions will
2340  * cause the front end (if possible) to delay updating the screen
2341  * until it's all complete, thus avoiding flicker.
2342  */
2343 void dlg_update_start(union control *ctrl, void *dlg)
2344 {
2345     struct dlgparam *dp = (struct dlgparam *)dlg;
2346     struct winctrl *c = dlg_findbyctrl(dp, ctrl);
2347     if (c && c->ctrl->generic.type == CTRL_LISTBOX) {
2348         SendDlgItemMessage(dp->hwnd, c->base_id+1, WM_SETREDRAW, FALSE, 0);
2349     }
2350 }
2351
2352 void dlg_update_done(union control *ctrl, void *dlg)
2353 {
2354     struct dlgparam *dp = (struct dlgparam *)dlg;
2355     struct winctrl *c = dlg_findbyctrl(dp, ctrl);
2356     if (c && c->ctrl->generic.type == CTRL_LISTBOX) {
2357         HWND hw = GetDlgItem(dp->hwnd, c->base_id+1);
2358         SendMessage(hw, WM_SETREDRAW, TRUE, 0);
2359         InvalidateRect(hw, NULL, TRUE);
2360     }
2361 }
2362
2363 void dlg_set_focus(union control *ctrl, void *dlg)
2364 {
2365     struct dlgparam *dp = (struct dlgparam *)dlg;
2366     struct winctrl *c = dlg_findbyctrl(dp, ctrl);
2367     int id;
2368     HWND ctl;
2369     switch (ctrl->generic.type) {
2370       case CTRL_EDITBOX: id = c->base_id + 1; break;
2371       case CTRL_RADIO:
2372         for (id = c->base_id + ctrl->radio.nbuttons; id > 1; id--)
2373             if (IsDlgButtonChecked(dp->hwnd, id))
2374                 break;
2375         /*
2376          * In the theoretically-unlikely case that no button was
2377          * selected, id should come out of this as 1, which is a
2378          * reasonable enough choice.
2379          */
2380         break;
2381       case CTRL_CHECKBOX: id = c->base_id; break;
2382       case CTRL_BUTTON: id = c->base_id; break;
2383       case CTRL_LISTBOX: id = c->base_id + 1; break;
2384       case CTRL_FILESELECT: id = c->base_id + 1; break;
2385       case CTRL_FONTSELECT: id = c->base_id + 2; break;
2386       default: id = c->base_id; break;
2387     }
2388     ctl = GetDlgItem(dp->hwnd, id);
2389     SetFocus(ctl);
2390 }
2391
2392 /*
2393  * During event processing, you might well want to give an error
2394  * indication to the user. dlg_beep() is a quick and easy generic
2395  * error; dlg_error() puts up a message-box or equivalent.
2396  */
2397 void dlg_beep(void *dlg)
2398 {
2399     /* struct dlgparam *dp = (struct dlgparam *)dlg; */
2400     MessageBeep(0);
2401 }
2402
2403 void dlg_error_msg(void *dlg, char *msg)
2404 {
2405     struct dlgparam *dp = (struct dlgparam *)dlg;
2406     MessageBox(dp->hwnd, msg,
2407                dp->errtitle ? dp->errtitle : NULL,
2408                MB_OK | MB_ICONERROR);
2409 }
2410
2411 /*
2412  * This function signals to the front end that the dialog's
2413  * processing is completed, and passes an integer value (typically
2414  * a success status).
2415  */
2416 void dlg_end(void *dlg, int value)
2417 {
2418     struct dlgparam *dp = (struct dlgparam *)dlg;
2419     dp->ended = TRUE;
2420     dp->endresult = value;
2421 }
2422
2423 void dlg_refresh(union control *ctrl, void *dlg)
2424 {
2425     struct dlgparam *dp = (struct dlgparam *)dlg;
2426     int i, j;
2427     struct winctrl *c;
2428
2429     if (!ctrl) {
2430         /*
2431          * Send EVENT_REFRESH to absolutely everything.
2432          */
2433         for (j = 0; j < dp->nctrltrees; j++) {
2434             for (i = 0;
2435                  (c = winctrl_findbyindex(dp->controltrees[j], i)) != NULL;
2436                  i++) {
2437                 if (c->ctrl && c->ctrl->generic.handler != NULL)
2438                     c->ctrl->generic.handler(c->ctrl, dp,
2439                                              dp->data, EVENT_REFRESH);
2440             }
2441         }
2442     } else {
2443         /*
2444          * Send EVENT_REFRESH to a specific control.
2445          */
2446         if (ctrl->generic.handler != NULL)
2447             ctrl->generic.handler(ctrl, dp, dp->data, EVENT_REFRESH);
2448     }
2449 }
2450
2451 void dlg_coloursel_start(union control *ctrl, void *dlg, int r, int g, int b)
2452 {
2453     struct dlgparam *dp = (struct dlgparam *)dlg;
2454     dp->coloursel_wanted = TRUE;
2455     dp->coloursel_result.r = r;
2456     dp->coloursel_result.g = g;
2457     dp->coloursel_result.b = b;
2458 }
2459
2460 int dlg_coloursel_results(union control *ctrl, void *dlg,
2461                           int *r, int *g, int *b)
2462 {
2463     struct dlgparam *dp = (struct dlgparam *)dlg;
2464     if (dp->coloursel_result.ok) {
2465         *r = dp->coloursel_result.r;
2466         *g = dp->coloursel_result.g;
2467         *b = dp->coloursel_result.b;
2468         return 1;
2469     } else
2470         return 0;
2471 }
2472
2473 void dlg_auto_set_fixed_pitch_flag(void *dlg)
2474 {
2475     struct dlgparam *dp = (struct dlgparam *)dlg;
2476     Conf *conf = (Conf *)dp->data;
2477     FontSpec *fs;
2478     int quality;
2479     HFONT hfont;
2480     HDC hdc;
2481     TEXTMETRIC tm;
2482     int is_var;
2483
2484     /*
2485      * Attempt to load the current font, and see if it's
2486      * variable-pitch. If so, start off the fixed-pitch flag for the
2487      * dialog box as false.
2488      *
2489      * We assume here that any client of the dlg_* mechanism which is
2490      * using font selectors at all is also using a normal 'Conf *'
2491      * as dp->data.
2492      */
2493
2494     quality = conf_get_int(conf, CONF_font_quality);
2495     fs = conf_get_fontspec(conf, CONF_font);
2496
2497     hfont = CreateFont(0, 0, 0, 0, FW_DONTCARE, FALSE, FALSE, FALSE,
2498                        DEFAULT_CHARSET, OUT_DEFAULT_PRECIS,
2499                        CLIP_DEFAULT_PRECIS, FONT_QUALITY(quality),
2500                        FIXED_PITCH | FF_DONTCARE, fs->name);
2501     hdc = GetDC(NULL);
2502     if (hdc && SelectObject(hdc, hfont) && GetTextMetrics(hdc, &tm)) {
2503         /* Note that the TMPF_FIXED_PITCH bit is defined upside down :-( */
2504         is_var = (tm.tmPitchAndFamily & TMPF_FIXED_PITCH);
2505     } else {
2506         is_var = FALSE;                /* assume it's basically normal */
2507     }
2508     if (hdc)
2509         ReleaseDC(NULL, hdc);
2510     if (hfont)
2511         DeleteObject(hfont);
2512
2513     if (is_var)
2514         dp->fixed_pitch_fonts = FALSE;
2515 }
2516
2517 int dlg_get_fixed_pitch_flag(void *dlg)
2518 {
2519     struct dlgparam *dp = (struct dlgparam *)dlg;
2520     return dp->fixed_pitch_fonts;
2521 }
2522
2523 void dlg_set_fixed_pitch_flag(void *dlg, int flag)
2524 {
2525     struct dlgparam *dp = (struct dlgparam *)dlg;
2526     dp->fixed_pitch_fonts = flag;
2527 }
2528
2529 struct perctrl_privdata {
2530     union control *ctrl;
2531     void *data;
2532     int needs_free;
2533 };
2534
2535 static int perctrl_privdata_cmp(void *av, void *bv)
2536 {
2537     struct perctrl_privdata *a = (struct perctrl_privdata *)av;
2538     struct perctrl_privdata *b = (struct perctrl_privdata *)bv;
2539     if (a->ctrl < b->ctrl)
2540         return -1;
2541     else if (a->ctrl > b->ctrl)
2542         return +1;
2543     return 0;
2544 }
2545
2546 void dp_init(struct dlgparam *dp)
2547 {
2548     dp->nctrltrees = 0;
2549     dp->data = NULL;
2550     dp->ended = FALSE;
2551     dp->focused = dp->lastfocused = NULL;
2552     memset(dp->shortcuts, 0, sizeof(dp->shortcuts));
2553     dp->hwnd = NULL;
2554     dp->wintitle = dp->errtitle = NULL;
2555     dp->privdata = newtree234(perctrl_privdata_cmp);
2556     dp->fixed_pitch_fonts = TRUE;
2557 }
2558
2559 void dp_add_tree(struct dlgparam *dp, struct winctrls *wc)
2560 {
2561     assert(dp->nctrltrees < lenof(dp->controltrees));
2562     dp->controltrees[dp->nctrltrees++] = wc;
2563 }
2564
2565 void dp_cleanup(struct dlgparam *dp)
2566 {
2567     struct perctrl_privdata *p;
2568
2569     if (dp->privdata) {
2570         while ( (p = index234(dp->privdata, 0)) != NULL ) {
2571             del234(dp->privdata, p);
2572             if (p->needs_free)
2573                 sfree(p->data);
2574             sfree(p);
2575         }
2576         freetree234(dp->privdata);
2577         dp->privdata = NULL;
2578     }
2579     sfree(dp->wintitle);
2580     sfree(dp->errtitle);
2581 }
2582
2583 void *dlg_get_privdata(union control *ctrl, void *dlg)
2584 {
2585     struct dlgparam *dp = (struct dlgparam *)dlg;
2586     struct perctrl_privdata tmp, *p;
2587     tmp.ctrl = ctrl;
2588     p = find234(dp->privdata, &tmp, NULL);
2589     if (p)
2590         return p->data;
2591     else
2592         return NULL;
2593 }
2594
2595 void dlg_set_privdata(union control *ctrl, void *dlg, void *ptr)
2596 {
2597     struct dlgparam *dp = (struct dlgparam *)dlg;
2598     struct perctrl_privdata tmp, *p;
2599     tmp.ctrl = ctrl;
2600     p = find234(dp->privdata, &tmp, NULL);
2601     if (!p) {
2602         p = snew(struct perctrl_privdata);
2603         p->ctrl = ctrl;
2604         p->needs_free = FALSE;
2605         add234(dp->privdata, p);
2606     }
2607     p->data = ptr;
2608 }
2609
2610 void *dlg_alloc_privdata(union control *ctrl, void *dlg, size_t size)
2611 {
2612     struct dlgparam *dp = (struct dlgparam *)dlg;
2613     struct perctrl_privdata tmp, *p;
2614     tmp.ctrl = ctrl;
2615     p = find234(dp->privdata, &tmp, NULL);
2616     if (!p) {
2617         p = snew(struct perctrl_privdata);
2618         p->ctrl = ctrl;
2619         p->needs_free = FALSE;
2620         add234(dp->privdata, p);
2621     }
2622     assert(!p->needs_free);
2623     p->needs_free = TRUE;
2624     /*
2625      * This is an internal allocation routine, so it's allowed to
2626      * use smalloc directly.
2627      */
2628     p->data = smalloc(size);
2629     return p->data;
2630 }