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