Fix warnings XBoard file browser
[xboard.git] / filebrowser / selfile.c
1 /*
2  * Copyright 1989 Software Research Associates, Inc., Tokyo, Japan
3  *
4  * Permission to use, copy, modify, and distribute this software and its
5  * documentation for any purpose and without fee is hereby granted, provided
6  * that the above copyright notice appear in all copies and that both that
7  * copyright notice and this permission notice appear in supporting
8  * documentation, and that the name of Software Research Associates not be used
9  * in advertising or publicity pertaining to distribution of the software
10  * without specific, written prior permission.  Software Research Associates
11  * makes no representations about the suitability of this software for any
12  * purpose.  It is provided "as is" without express or implied warranty.
13  *
14  * SOFTWARE RESEARCH ASSOCIATES DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS
15  * SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS,
16  * IN NO EVENT SHALL SOFTWARE RESEARCH ASSOCIATES BE LIABLE FOR ANY SPECIAL,
17  * INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
18  * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
19  * OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
20  * PERFORMANCE OF THIS SOFTWARE.
21  *
22  * Author: Erik M. van der Poel
23  *         Software Research Associates, Inc., Tokyo, Japan
24  *         erik@sra.co.jp
25  */
26
27 /*
28  * Author's address:
29  *
30  *     erik@sra.co.jp
31  *                                            OR
32  *     erik%sra.co.jp@uunet.uu.net
33  *                                            OR
34  *     erik%sra.co.jp@mcvax.uucp
35  *                                            OR
36  *     try junet instead of co.jp
37  *                                            OR
38  *     Erik M. van der Poel
39  *     Software Research Associates, Inc.
40  *     1-1-1 Hirakawa-cho, Chiyoda-ku
41  *     Tokyo 102 Japan. TEL +81-3-234-2692
42  */
43
44 #include <stdio.h>
45 #include <errno.h>
46 /* BSD 4.3 errno.h does not declare errno */
47 extern int errno;
48 //extern int sys_nerr;
49 //extern char *sys_errlist[]; // [HGM] this produced a compile error in Ubuntu 8.04
50
51 #include <sys/param.h>
52 #include <X11/cursorfont.h>
53 #include <X11/Intrinsic.h>
54 #include <X11/StringDefs.h>
55 #include <X11/Composite.h>
56 #include <X11/Shell.h>
57 #include <X11/Xaw/Form.h>
58 #include <X11/Xaw/Command.h>
59 #include <X11/Xaw/Scrollbar.h>
60 #include <X11/Xaw/Label.h>
61 #include <X11/Xaw/Cardinals.h>
62
63 #include "xstat.h"
64 #include "selfile.h"
65
66 #ifndef MAXPATHLEN
67 #define MAXPATHLEN 1024
68 #endif /* ndef MAXPATHLEN */
69
70 #if !defined(SVR4) && !defined(SYSV) && !defined(USG)
71 extern char *getwd();
72 #endif /* !defined(SVR4) && !defined(SYSV) && !defined(USG) */
73
74 int SFstatus = SEL_FILE_NULL;
75
76 char
77         SFstartDir[MAXPATHLEN],
78         SFcurrentPath[MAXPATHLEN],
79         SFlastPath[MAXPATHLEN],
80         SFcurrentDir[MAXPATHLEN];
81
82 Widget
83         selFile,
84         selFileCancel,
85         selFileField,
86         selFileMess,
87         filterField,
88         selFileForm,
89         selFileHScroll,
90         selFileHScrolls[3],
91         selFileLists[3],
92         selFileOK,
93         selFilePrompt,
94         selFileVScrolls[3];
95
96 Display *SFdisplay;
97
98 Pixel SFfore, SFback;
99
100 Atom    SFwmDeleteWindow;
101
102 XSegment SFsegs[2], SFcompletionSegs[2];
103
104 XawTextPosition SFtextPos;
105
106 int SFupperX, SFlowerY, SFupperY;
107
108 int SFtextX, SFtextYoffset;
109
110 int SFentryWidth, SFentryHeight;
111
112 int SFlineToTextH = 3;
113
114 int SFlineToTextV = 3;
115
116 int SFbesideText = 3;
117
118 int SFaboveAndBelowText = 2;
119
120 int SFcharsPerEntry = 15;
121
122 int SFlistSize = 10;
123
124 int SFworkProcAdded = 0;
125
126 XtAppContext SFapp;
127
128 int SFpathScrollWidth, SFvScrollHeight, SFhScrollWidth;
129
130 char SFtextBuffer[MAXPATHLEN];
131
132 char SFfilterBuffer[MAXPATHLEN];
133
134 XtIntervalId SFdirModTimerId;
135
136 int (*SFfunc)();
137
138 Boolean SFpathFlag; // [HGM]
139
140 static char *oneLineTextEditTranslations = "\
141         <Key>Return:    redraw-display()\n\
142         Ctrl<Key>M:     redraw-display()\n\
143 ";
144
145 /* ARGSUSED */
146 static void
147 SFexposeList(w, n, event, cont)
148         Widget          w;
149         XtPointer       n;
150         XEvent          *event;
151         Boolean         *cont;
152 {
153         if ((event->type == NoExpose) || event->xexpose.count) {
154                 return;
155         }
156
157         SFdrawList((int)(intptr_t)n, SF_DO_NOT_SCROLL);
158 }
159
160 void
161 SFpurge()
162 {
163         if(SFdirs) XtFree((XtPointer) SFdirs);
164         SFdirs = NULL; // kludge to throw away all cached info
165 }
166
167 /* ARGSUSED */
168 static void
169 SFmodVerifyCallback(w, client_data, event, cont)
170         Widget                  w;
171         XtPointer               client_data;
172         XEvent                  *event;
173         Boolean                 *cont;
174 {
175         char    buf[2];
176
177         if (
178                 (XLookupString(&(event->xkey), buf, 2, NULL, NULL) == 1) &&
179                 ((*buf) == '\r' || *buf == 033)
180         ) {
181                 if(client_data) {
182                     Arg args[10]; char *p;
183                     if(*buf == 033) { // [HGM] esc in filter: restore and give focus to path
184                         XtSetArg(args[0], XtNstring, SFfilterBuffer);
185                         XtSetValues(filterField, args, 1);
186                         XtSetKeyboardFocus(selFileForm, selFileField);
187                         SFstatus = SEL_FILE_TEXT;
188                         return;
189                     } else
190                     if(!SFpathFlag) // [HGM] cr: fetch current extenson filter
191                     {   
192                         XtSetArg(args[0], XtNstring, &p);
193                         XtGetValues(filterField, args, 1);
194                         if(strcmp(SFfilterBuffer, p)) SFpurge();
195                         strncpy(SFfilterBuffer, p, 40);
196                         SFstatus = SEL_FILE_TEXT;
197                     }
198                     return;
199                 }
200                 SFstatus = (*buf == 033 ? SEL_FILE_CANCEL : SEL_FILE_OK);
201         } else {
202                 if(!client_data) SFstatus = SEL_FILE_TEXT;
203         }
204 }
205
206 /* ARGSUSED */
207 static void
208 SFokCallback(w, cl, cd)
209         Widget  w;
210         XtPointer cl, cd;
211 {
212         SFstatus = SEL_FILE_OK;
213 }
214
215 static XtCallbackRec SFokSelect[] = {
216         { SFokCallback, (XtPointer) NULL },
217         { NULL, (XtPointer) NULL },
218 };
219
220 /* ARGSUSED */
221 static void
222 SFcancelCallback(w, cl, cd)
223         Widget  w;
224         XtPointer cl, cd;
225 {
226         SFstatus = SEL_FILE_CANCEL;
227 }
228
229 static XtCallbackRec SFcancelSelect[] = {
230         { SFcancelCallback, (XtPointer) NULL },
231         { NULL, (XtPointer) NULL },
232 };
233
234 /* ARGSUSED */
235 static void
236 SFdismissAction(w, event, params, num_params)
237         Widget  w;
238         XEvent *event;
239         String *params;
240         Cardinal *num_params;
241 {
242         if (event->type == ClientMessage &&
243             event->xclient.data.l[0] != SFwmDeleteWindow) return;
244
245         SFstatus = SEL_FILE_CANCEL;
246 }
247
248 static char *wmDeleteWindowTranslation = "\
249         <Message>WM_PROTOCOLS:  SelFileDismiss()\n\
250 ";
251
252 static XtActionsRec actions[] = {
253         {"SelFileDismiss",      SFdismissAction},
254 };
255
256 void SFsetFocus(Widget w, XtPointer data, XEvent *event, Boolean *b)
257 {
258     XtSetKeyboardFocus((Widget) data, w);
259 }
260
261 void SFwheelProc(Widget w, XtPointer data, XEvent *event, Boolean *b)
262 {   // [HGM] mouse-wheel callback scrolls lists
263     int dir, n = (intptr_t) data;
264     if(event->xbutton.button == Button4) dir = -2; // kludge to indicate relative motion
265     if(event->xbutton.button == Button5) dir = -1;
266     SFvSliderMovedCallback(w, n, dir);
267 }
268
269 static void
270 SFcreateWidgets(toplevel, prompt, ok, cancel)
271         Widget  toplevel;
272         char    *prompt;
273         char    *ok;
274         char    *cancel;
275 {
276         Cardinal        i, n;
277         int             listWidth, listHeight;
278         int             listSpacing = 10;
279         int             scrollThickness = 15;
280         int             hScrollX, hScrollY;
281         int             vScrollX, vScrollY;
282         Cursor
283                         xtermCursor,
284                         sbRightArrowCursor,
285                         dotCursor;
286         Arg             arglist[20];
287
288         i = 0;
289         XtSetArg(arglist[i], XtNtransientFor, toplevel);                i++;
290
291         selFile = XtAppCreateShell("Browse", "SelFile",
292                 transientShellWidgetClass, SFdisplay, arglist, i);
293
294         /* Add WM_DELETE_WINDOW protocol */
295         XtAppAddActions(XtWidgetToApplicationContext(selFile),
296                 actions, XtNumber(actions));
297         XtOverrideTranslations(selFile,
298                 XtParseTranslationTable(wmDeleteWindowTranslation));
299
300         i = 0;
301         XtSetArg(arglist[i], XtNdefaultDistance, 30);                   i++;
302         selFileForm = XtCreateManagedWidget("selFileForm",
303                 formWidgetClass, selFile, arglist, i);
304
305         i = 0;
306         XtSetArg(arglist[i], XtNlabel, prompt);                         i++;
307         XtSetArg(arglist[i], XtNresizable, True);                       i++;
308         XtSetArg(arglist[i], XtNtop, XtChainTop);                       i++;
309         XtSetArg(arglist[i], XtNbottom, XtChainTop);                    i++;
310         XtSetArg(arglist[i], XtNleft, XtChainLeft);                     i++;
311         XtSetArg(arglist[i], XtNright, XtChainLeft);                    i++;
312         XtSetArg(arglist[i], XtNborderWidth, 0);                        i++;
313         selFilePrompt = XtCreateManagedWidget("selFilePrompt",
314                 labelWidgetClass, selFileForm, arglist, i);
315
316         i = 0;
317         XtSetArg(arglist[i], XtNforeground, &SFfore);                   i++;
318         XtSetArg(arglist[i], XtNbackground, &SFback);                   i++;
319         XtGetValues(selFilePrompt, arglist, i);
320
321         SFinitFont();
322
323         SFentryWidth = SFbesideText + SFcharsPerEntry * SFcharWidth +
324                         SFbesideText;
325         SFentryHeight = SFaboveAndBelowText + SFcharHeight +
326                         SFaboveAndBelowText;
327
328         listWidth = SFlineToTextH + SFentryWidth + SFlineToTextH + 1 +
329                         scrollThickness;
330         listHeight = SFlineToTextV + SFentryHeight + SFlineToTextV + 1 +
331                         SFlineToTextV + SFlistSize * SFentryHeight +
332                         SFlineToTextV + 1 + scrollThickness;
333
334         SFpathScrollWidth = NR * listWidth + (NR-1) * listSpacing + 4;
335
336         hScrollX = -1;
337         hScrollY = SFlineToTextV + SFentryHeight + SFlineToTextV + 1 +
338                         SFlineToTextV + SFlistSize * SFentryHeight +
339                         SFlineToTextV;
340         SFhScrollWidth = SFlineToTextH + SFentryWidth + SFlineToTextH;
341
342         vScrollX = SFlineToTextH + SFentryWidth + SFlineToTextH;
343         vScrollY = SFlineToTextV + SFentryHeight + SFlineToTextV;
344         SFvScrollHeight = SFlineToTextV + SFlistSize * SFentryHeight +
345                         SFlineToTextV;
346
347         SFupperX = SFlineToTextH + SFentryWidth + SFlineToTextH - 1;
348         SFlowerY = SFlineToTextV + SFentryHeight + SFlineToTextV + 1 +
349                         SFlineToTextV;
350         SFupperY = SFlineToTextV + SFentryHeight + SFlineToTextV + 1 +
351                         SFlineToTextV + SFlistSize * SFentryHeight - 1;
352
353         SFtextX = SFlineToTextH + SFbesideText;
354         SFtextYoffset = SFlowerY + SFaboveAndBelowText + SFcharAscent;
355
356         SFsegs[0].x1 = 0;
357         SFsegs[0].y1 = vScrollY;
358         SFsegs[0].x2 = vScrollX - 1;
359         SFsegs[0].y2 = vScrollY;
360         SFsegs[1].x1 = vScrollX;
361         SFsegs[1].y1 = 0;
362         SFsegs[1].x2 = vScrollX;
363         SFsegs[1].y2 = vScrollY - 1;
364
365         SFcompletionSegs[0].x1 = SFcompletionSegs[0].x2 = SFlineToTextH;
366         SFcompletionSegs[1].x1 = SFcompletionSegs[1].x2 =
367                 SFlineToTextH + SFentryWidth - 1;
368
369         i = 0;
370         XtSetArg(arglist[i], XtNwidth, NR * listWidth + (NR - 1) * listSpacing + 4);
371                                                                         i++;
372         XtSetArg(arglist[i], XtNborderColor, SFfore);                   i++;
373
374         XtSetArg(arglist[i], XtNfromVert, selFilePrompt);               i++;
375         XtSetArg(arglist[i], XtNvertDistance, 5);                       i++;
376         XtSetArg(arglist[i], XtNresizable, True);                       i++;
377         XtSetArg(arglist[i], XtNtop, XtChainTop);                       i++;
378         XtSetArg(arglist[i], XtNbottom, XtChainTop);                    i++;
379         XtSetArg(arglist[i], XtNleft, XtChainLeft);                     i++;
380         XtSetArg(arglist[i], XtNright, XtChainLeft);                    i++;
381         XtSetArg(arglist[i], XtNstring, SFtextBuffer);                  i++;
382         XtSetArg(arglist[i], XtNlength, MAXPATHLEN);                    i++;
383         XtSetArg(arglist[i], XtNeditType, XawtextEdit);                 i++;
384         XtSetArg(arglist[i], XtNwrap, XawtextWrapWord);                 i++;
385         XtSetArg(arglist[i], XtNresize, XawtextResizeHeight);           i++;
386         XtSetArg(arglist[i], XtNuseStringInPlace, True);                i++;
387         selFileField = XtCreateManagedWidget("selFileField",
388                 asciiTextWidgetClass, selFileForm, arglist, i);
389
390         XtOverrideTranslations(selFileField,
391                 XtParseTranslationTable(oneLineTextEditTranslations));
392         XtAddEventHandler(selFileField, ButtonPressMask, False, SFsetFocus, (XtPointer) selFileForm);
393
394         i = 0;
395         XtSetArg(arglist[i], XtNlabel, "Filter on extensions:");        i++;
396         XtSetArg(arglist[i], XtNvertDistance, 5);                       i++;
397         XtSetArg(arglist[i], XtNfromVert, selFileField);                i++;
398         XtSetArg(arglist[i], XtNresizable, True);                       i++;
399         XtSetArg(arglist[i], XtNtop, XtChainTop);                       i++;
400         XtSetArg(arglist[i], XtNbottom, XtChainTop);                    i++;
401         XtSetArg(arglist[i], XtNleft, XtChainLeft);                     i++;
402         XtSetArg(arglist[i], XtNright, XtChainLeft);                    i++;
403         XtSetArg(arglist[i], XtNborderWidth, 0);                        i++;
404         selFileMess = XtCreateManagedWidget("selFileMess",
405                 labelWidgetClass, selFileForm, arglist, i);
406
407         i = 0;
408         XtSetArg(arglist[i], XtNwidth, NR * listWidth + (NR - 1) * listSpacing + 4);
409                                                                         i++;
410         XtSetArg(arglist[i], XtNborderColor, SFfore);                   i++;
411         XtSetArg(arglist[i], XtNvertDistance, 5);                       i++;
412         XtSetArg(arglist[i], XtNfromVert, selFileMess);                 i++;
413         XtSetArg(arglist[i], XtNresizable, True);                       i++;
414         XtSetArg(arglist[i], XtNtop, XtChainTop);                       i++;
415         XtSetArg(arglist[i], XtNbottom, XtChainTop);                    i++;
416         XtSetArg(arglist[i], XtNleft, XtChainLeft);                     i++;
417         XtSetArg(arglist[i], XtNright, XtChainLeft);                    i++;
418         XtSetArg(arglist[i], XtNlength, MAXPATHLEN);                    i++;
419         XtSetArg(arglist[i], XtNeditType, XawtextEdit);                 i++;
420         XtSetArg(arglist[i], XtNwrap, XawtextWrapWord);                 i++;
421         XtSetArg(arglist[i], XtNresize, XawtextResizeHeight);           i++;
422         XtSetArg(arglist[i], XtNuseStringInPlace, False);               i++;
423         filterField = XtCreateManagedWidget("filterField",
424                 asciiTextWidgetClass, selFileForm, arglist, i);
425
426         XtOverrideTranslations(filterField,
427                 XtParseTranslationTable(oneLineTextEditTranslations));
428         XtAddEventHandler(filterField, ButtonPressMask, False, SFsetFocus, (XtPointer) selFileForm);
429
430         i = 0;
431         XtSetArg(arglist[i], XtNorientation, XtorientHorizontal);       i++;
432         XtSetArg(arglist[i], XtNwidth, SFpathScrollWidth);              i++;
433         XtSetArg(arglist[i], XtNheight, scrollThickness);               i++;
434         XtSetArg(arglist[i], XtNborderColor, SFfore);                   i++;
435         XtSetArg(arglist[i], XtNfromVert, filterField);                 i++;
436         XtSetArg(arglist[i], XtNvertDistance, 10);                      i++;
437         XtSetArg(arglist[i], XtNtop, XtChainTop);                       i++;
438         XtSetArg(arglist[i], XtNbottom, XtChainTop);                    i++;
439         XtSetArg(arglist[i], XtNleft, XtChainLeft);                     i++;
440         XtSetArg(arglist[i], XtNright, XtChainLeft);                    i++;
441         selFileHScroll = XtCreateManagedWidget("selFileHScroll",
442                 scrollbarWidgetClass, selFileForm, arglist, i);
443
444         XtAddCallback(selFileHScroll, XtNjumpProc,
445                 SFpathSliderMovedCallback, (XtPointer) NULL);
446         XtAddCallback(selFileHScroll, XtNscrollProc,
447                 SFpathAreaSelectedCallback, (XtPointer) NULL);
448
449         i = 0;
450         XtSetArg(arglist[i], XtNwidth, listWidth);                      i++;
451         XtSetArg(arglist[i], XtNheight, listHeight);                    i++;
452         XtSetArg(arglist[i], XtNborderColor, SFfore);                   i++;
453         XtSetArg(arglist[i], XtNfromVert, selFileHScroll);              i++;
454         XtSetArg(arglist[i], XtNvertDistance, 10);                      i++;
455         XtSetArg(arglist[i], XtNtop, XtChainTop);                       i++;
456         XtSetArg(arglist[i], XtNbottom, XtChainTop);                    i++;
457         XtSetArg(arglist[i], XtNleft, XtChainLeft);                     i++;
458         XtSetArg(arglist[i], XtNright, XtChainLeft);                    i++;
459         selFileLists[0] = XtCreateManagedWidget("selFileList1",
460                 compositeWidgetClass, selFileForm, arglist, i);
461 #if (NR == 3)
462         i = 0;
463         XtSetArg(arglist[i], XtNwidth, listWidth);                      i++;
464         XtSetArg(arglist[i], XtNheight, listHeight);                    i++;
465         XtSetArg(arglist[i], XtNborderColor, SFfore);                   i++;
466         XtSetArg(arglist[i], XtNfromHoriz, selFileLists[0]);            i++;
467         XtSetArg(arglist[i], XtNfromVert, selFileHScroll);              i++;
468         XtSetArg(arglist[i], XtNhorizDistance, listSpacing);            i++;
469         XtSetArg(arglist[i], XtNvertDistance, 10);                      i++;
470         XtSetArg(arglist[i], XtNtop, XtChainTop);                       i++;
471         XtSetArg(arglist[i], XtNbottom, XtChainTop);                    i++;
472         XtSetArg(arglist[i], XtNleft, XtChainLeft);                     i++;
473         XtSetArg(arglist[i], XtNright, XtChainLeft);                    i++;
474         selFileLists[1] = XtCreateManagedWidget("selFileList2",
475                 compositeWidgetClass, selFileForm, arglist, i);
476
477         i = 0;
478         XtSetArg(arglist[i], XtNwidth, listWidth);                      i++;
479         XtSetArg(arglist[i], XtNheight, listHeight);                    i++;
480         XtSetArg(arglist[i], XtNborderColor, SFfore);                   i++;
481         XtSetArg(arglist[i], XtNfromHoriz, selFileLists[1]);            i++;
482         XtSetArg(arglist[i], XtNfromVert, selFileHScroll);              i++;
483         XtSetArg(arglist[i], XtNhorizDistance, listSpacing);            i++;
484         XtSetArg(arglist[i], XtNvertDistance, 10);                      i++;
485         XtSetArg(arglist[i], XtNtop, XtChainTop);                       i++;
486         XtSetArg(arglist[i], XtNbottom, XtChainTop);                    i++;
487         XtSetArg(arglist[i], XtNleft, XtChainLeft);                     i++;
488         XtSetArg(arglist[i], XtNright, XtChainLeft);                    i++;
489         selFileLists[2] = XtCreateManagedWidget("selFileList3",
490                 compositeWidgetClass, selFileForm, arglist, i);
491 #endif
492         for (n = 0; n < NR; n++) {
493
494                 i = 0;
495                 XtSetArg(arglist[i], XtNx, vScrollX);                   i++;
496                 XtSetArg(arglist[i], XtNy, vScrollY);                   i++;
497                 XtSetArg(arglist[i], XtNwidth, scrollThickness);        i++;
498                 XtSetArg(arglist[i], XtNheight, SFvScrollHeight);       i++;
499                 XtSetArg(arglist[i], XtNborderColor, SFfore);           i++;
500                 selFileVScrolls[n] = XtCreateManagedWidget("selFileVScroll",
501                         scrollbarWidgetClass, selFileLists[n], arglist, i);
502
503                 XtAddCallback(selFileVScrolls[n], XtNjumpProc,
504                         SFvFloatSliderMovedCallback, (XtPointer)(intptr_t) n);
505                 XtAddCallback(selFileVScrolls[n], XtNscrollProc,
506                         SFvAreaSelectedCallback, (XtPointer)(intptr_t) n);
507
508                 i = 0;
509
510                 XtSetArg(arglist[i], XtNorientation, XtorientHorizontal);
511                                                                         i++;
512                 XtSetArg(arglist[i], XtNx, hScrollX);                   i++;
513                 XtSetArg(arglist[i], XtNy, hScrollY);                   i++;
514                 XtSetArg(arglist[i], XtNwidth, SFhScrollWidth);         i++;
515                 XtSetArg(arglist[i], XtNheight, scrollThickness);       i++;
516                 XtSetArg(arglist[i], XtNborderColor, SFfore);           i++;
517                 selFileHScrolls[n] = XtCreateManagedWidget("selFileHScroll",
518                         scrollbarWidgetClass, selFileLists[n], arglist, i);
519
520                 XtAddCallback(selFileHScrolls[n], XtNjumpProc,
521                         SFhSliderMovedCallback, (XtPointer)(intptr_t) n);
522                 XtAddCallback(selFileHScrolls[n], XtNscrollProc,
523                         SFhAreaSelectedCallback, (XtPointer)(intptr_t) n);
524
525                 XtAddEventHandler(selFileVScrolls[n], ButtonPressMask, False,
526                         SFwheelProc, (XtPointer)(intptr_t) n); // [HGM] couplemouse wheel to v-scroll
527         }
528
529         i = 0;
530         XtSetArg(arglist[i], XtNlabel, ok);                             i++;
531         XtSetArg(arglist[i], XtNresizable, True);                       i++;
532         XtSetArg(arglist[i], XtNcallback, SFokSelect);                  i++;
533         XtSetArg(arglist[i], XtNborderColor, SFfore);                   i++;
534         XtSetArg(arglist[i], XtNfromVert, selFileLists[0]);             i++;
535         XtSetArg(arglist[i], XtNvertDistance, 30);                      i++;
536         XtSetArg(arglist[i], XtNtop, XtChainTop);                       i++;
537         XtSetArg(arglist[i], XtNbottom, XtChainTop);                    i++;
538         XtSetArg(arglist[i], XtNleft, XtChainLeft);                     i++;
539         XtSetArg(arglist[i], XtNright, XtChainLeft);                    i++;
540         selFileOK = XtCreateManagedWidget("selFileOK", commandWidgetClass,
541                 selFileForm, arglist, i);
542
543         i = 0;
544         XtSetArg(arglist[i], XtNlabel, cancel);                         i++;
545         XtSetArg(arglist[i], XtNresizable, True);                       i++;
546         XtSetArg(arglist[i], XtNcallback, SFcancelSelect);              i++;
547         XtSetArg(arglist[i], XtNborderColor, SFfore);                   i++;
548         XtSetArg(arglist[i], XtNfromHoriz, selFileOK);                  i++;
549         XtSetArg(arglist[i], XtNfromVert, selFileLists[0]);             i++;
550         XtSetArg(arglist[i], XtNhorizDistance, 30);                     i++;
551         XtSetArg(arglist[i], XtNvertDistance, 30);                      i++;
552         XtSetArg(arglist[i], XtNtop, XtChainTop);                       i++;
553         XtSetArg(arglist[i], XtNbottom, XtChainTop);                    i++;
554         XtSetArg(arglist[i], XtNleft, XtChainLeft);                     i++;
555         XtSetArg(arglist[i], XtNright, XtChainLeft);                    i++;
556         selFileCancel = XtCreateManagedWidget("selFileCancel",
557                 commandWidgetClass, selFileForm, arglist, i);
558
559         XtSetMappedWhenManaged(selFile, False);
560         XtRealizeWidget(selFile);
561
562         /* Add WM_DELETE_WINDOW protocol */
563         SFwmDeleteWindow = XInternAtom(SFdisplay, "WM_DELETE_WINDOW", False);
564         XSetWMProtocols(SFdisplay, XtWindow(selFile), &SFwmDeleteWindow, 1);
565
566         SFcreateGC();
567
568         xtermCursor = XCreateFontCursor(SFdisplay, XC_xterm);
569
570         sbRightArrowCursor = XCreateFontCursor(SFdisplay, XC_sb_right_arrow);
571         dotCursor = XCreateFontCursor(SFdisplay, XC_dot);
572
573         XDefineCursor(SFdisplay, XtWindow(selFileForm), xtermCursor);
574         XDefineCursor(SFdisplay, XtWindow(selFileField), xtermCursor);
575         XDefineCursor(SFdisplay, XtWindow(filterField), xtermCursor);
576
577         for (n = 0; n < NR; n++) {
578                 XDefineCursor(SFdisplay, XtWindow(selFileLists[n]),
579                         sbRightArrowCursor);
580         }
581         XDefineCursor(SFdisplay, XtWindow(selFileOK), dotCursor);
582         XDefineCursor(SFdisplay, XtWindow(selFileCancel), dotCursor);
583
584         for (n = 0; n < NR; n++) {
585                 XtAddEventHandler(selFileLists[n], ExposureMask, True,
586                         SFexposeList, (XtPointer)(intptr_t) n);
587                 XtAddEventHandler(selFileLists[n], EnterWindowMask, False,
588                         SFenterList, (XtPointer)(intptr_t) n);
589                 XtAddEventHandler(selFileLists[n], LeaveWindowMask, False,
590                         SFleaveList, (XtPointer)(intptr_t) n);
591                 XtAddEventHandler(selFileLists[n], PointerMotionMask, False,
592                         (XtEventHandler) SFmotionList, (XtPointer)(intptr_t) n);
593                 XtAddEventHandler(selFileLists[n], ButtonPressMask, False,
594                         SFbuttonPressList, (XtPointer)(intptr_t) n);
595                 XtAddEventHandler(selFileLists[n], ButtonReleaseMask, False,
596                         SFbuttonReleaseList, (XtPointer)(intptr_t) n);
597         }
598
599         XtAddEventHandler(selFileField, KeyPressMask, False,
600                 SFmodVerifyCallback, (XtPointer) NULL);
601         XtAddEventHandler(filterField, KeyReleaseMask, False,
602                 SFmodVerifyCallback, (XtPointer) 1);
603         XtSetKeyboardFocus(selFileForm, selFileField);
604
605         SFapp = XtWidgetToApplicationContext(selFile);
606
607 }
608
609 /* position widget under the cursor */
610 void
611 SFpositionWidget(w)
612     Widget w;
613 {
614     Arg args[3];
615     Cardinal num_args;
616     Dimension width, height, b_width;
617     int x, y, max_x, max_y;
618     Window root, child;
619     int dummyx, dummyy;
620     unsigned int dummymask;
621     
622     XQueryPointer(XtDisplay(w), XtWindow(w), &root, &child, &x, &y,
623                   &dummyx, &dummyy, &dummymask);
624     num_args = 0;
625     XtSetArg(args[num_args], XtNwidth, &width); num_args++;
626     XtSetArg(args[num_args], XtNheight, &height); num_args++;
627     XtSetArg(args[num_args], XtNborderWidth, &b_width); num_args++;
628     XtGetValues(w, args, num_args);
629
630     width += 2 * b_width;
631     height += 2 * b_width;
632
633     x -= ( (Position) width/2 );
634     if (x < 0) x = 0;
635     if ( x > (max_x = (Position) (XtScreen(w)->width - width)) ) x = max_x;
636
637     y -= ( (Position) height/2 );
638     if (y < 0) y = 0;
639     if ( y > (max_y = (Position) (XtScreen(w)->height - height)) ) y = max_y;
640     
641     num_args = 0;
642     XtSetArg(args[num_args], XtNx, x); num_args++;
643     XtSetArg(args[num_args], XtNy, y); num_args++;
644     XtSetValues(w, args, num_args);
645 }
646
647 FILE *
648 SFopenFile(name, mode, prompt, failed)
649     char *name;
650     char *mode;
651     char *prompt;
652     char *failed;
653 {
654     Arg args[1];
655     FILE *fp;
656
657     SFchdir(SFstartDir);
658     if ((fp = fopen(name, mode)) == NULL) {
659         char *buf;
660         if (1) { // [HGM] always use strerror
661             buf = XtMalloc(strlen(failed) + strlen(strerror(errno)) + 
662                            strlen(prompt) + 2);
663             strcpy(buf, failed);
664             strcat(buf, strerror(errno));
665             strcat(buf, "\n");
666             strcat(buf, prompt);
667         } else {
668             buf = XtMalloc(strlen(failed) + strlen(prompt) + 2);
669             strcpy(buf, failed);
670             strcat(buf, "\n");
671             strcat(buf, prompt);
672         }
673         XtSetArg(args[0], XtNlabel, buf);
674         XtSetValues(selFilePrompt, args, ONE);
675         XtFree(buf);
676         return NULL;
677     }
678     return fp;
679 }
680
681 void
682 SFtextChanged()
683 {
684
685         if ((SFtextBuffer[0] == '/') || (SFtextBuffer[0] == '~')) {
686           (void) strncpy(SFcurrentPath, SFtextBuffer, MAXPATHLEN);
687
688                 SFtextPos = XawTextGetInsertionPoint(selFileField);
689         } else {
690           (void) strcat(strncpy(SFcurrentPath, SFstartDir, MAXPATHLEN), SFtextBuffer);
691
692                 SFtextPos = XawTextGetInsertionPoint(selFileField) +
693                         strlen(SFstartDir);
694         }
695
696         if (!SFworkProcAdded) {
697                 (void) XtAppAddWorkProc(SFapp, SFworkProc, NULL);
698                 SFworkProcAdded = 1;
699         }
700
701         SFupdatePath();
702         return;
703 }
704
705 static char *
706 SFgetText()
707 {
708         return strcpy(XtMalloc((unsigned) (strlen(SFtextBuffer) + 1)),
709                 SFtextBuffer);
710 }
711
712 static void
713 SFprepareToReturn()
714 {
715         SFstatus = SEL_FILE_NULL;
716         XtRemoveGrab(selFile);
717         XtUnmapWidget(selFile);
718         XtRemoveTimeOut(SFdirModTimerId);
719         if (SFchdir(SFstartDir)) {
720                 XtAppError(
721                         SFapp,
722                         "XsraSelFile: can't return to current directory"
723                 );
724         }
725         return;
726 }
727
728 FILE *
729 XsraSelFile(toplevel, prompt, ok, cancel, failed,
730             init_path, filter, mode, show_entry, name_return)
731         Widget          toplevel;
732         char            *prompt;
733         char            *ok;
734         char            *cancel;
735         char            *failed;
736         char            *init_path;
737         char            *filter;
738         char            *mode;
739         int             (*show_entry)();
740         char            **name_return;
741 {
742         static int      firstTime = 1;
743         Cardinal        i;
744         Arg             arglist[20];
745         XEvent          event;
746         FILE            *fp;
747
748         if (!prompt) {
749                 prompt = "Pathname:";
750         }
751
752         if (!ok) {
753                 ok = "OK";
754         }
755
756         if (!cancel) {
757                 cancel = "Cancel";
758         }
759
760         if(SFpathFlag != (mode && mode[0] == 'p') || strcmp(SFfilterBuffer, filter)) {
761                 SFpurge();
762                 SFpathFlag = (mode && mode[0] == 'p'); // [HGM] ignore everything that is not a directory
763         }
764
765         if (firstTime) {
766                 firstTime = 0;
767                 SFdisplay = XtDisplay(toplevel);
768                 SFcreateWidgets(toplevel, prompt, ok, cancel);
769         } else {
770                 i = 0;
771
772                 XtSetArg(arglist[i], XtNlabel, prompt);                 i++;
773                 XtSetValues(selFilePrompt, arglist, i);
774
775                 i = 0;
776                 XtSetArg(arglist[i], XtNlabel, ok);                     i++;
777                 XtSetValues(selFileOK, arglist, i);
778
779                 i = 0;
780                 XtSetArg(arglist[i], XtNlabel, cancel);                 i++;
781                 XtSetValues(selFileCancel, arglist, i);
782         }
783
784         i = 0;
785         XtSetArg(arglist[i], XtNstring, filter);                        i++;
786         XtSetValues(filterField, arglist, i);
787
788         safeStrCpy(SFfilterBuffer, filter, MAXPATHLEN);
789         safeStrCpy(SFlastPath, SFtextBuffer, MAXPATHLEN); // remember for cancel
790
791         SFpositionWidget(selFile);
792         XtMapWidget(selFile);
793
794 #if defined(SVR4) || defined(SYSV) || defined(USG) || 1
795         if (!getcwd(SFstartDir, MAXPATHLEN)) { // [HGM] always do this, as I do not know when exactly to do it
796 #else /* defined(SVR4) || defined(SYSV) || defined(USG) */
797         if (!getwd(SFstartDir)) {
798 #endif /* defined(SVR4) || defined(SYSV) || defined(USG) */
799
800                 XtAppError(SFapp, "XsraSelFile: can't get current directory");
801         }
802         (void) strcat(SFstartDir, "/");
803         (void) strncpy(SFcurrentDir, SFstartDir, MAXPATHLEN);
804
805         if (init_path) {
806                 if (init_path[0] == '/') {
807                   (void) strncpy(SFcurrentPath, init_path, MAXPATHLEN);
808                         if (strncmp(
809                                 SFcurrentPath,
810                                 SFstartDir,
811                                 strlen(SFstartDir)
812                         )) {
813                                 SFsetText(SFcurrentPath);
814                         } else {
815                                 SFsetText(&(SFcurrentPath[strlen(SFstartDir)]));
816                         }
817                 } else {
818                   (void) strcat(strncpy(SFcurrentPath, SFstartDir, MAXPATHLEN),
819                                 init_path);
820                         SFsetText(&(SFcurrentPath[strlen(SFstartDir)]));
821                 }
822         } else {
823           (void) strncpy(SFcurrentPath, SFstartDir, MAXPATHLEN);
824         }
825
826         SFfunc = show_entry;
827
828         SFtextChanged();
829
830         XtAddGrab(selFile, True, True);
831
832         SFdirModTimerId = XtAppAddTimeOut(SFapp, (unsigned long) 1000,
833                 SFdirModTimer, (XtPointer) NULL);
834
835         while (1) {
836                 XtAppNextEvent(SFapp, &event);
837                 XtDispatchEvent(&event);
838                 switch (SFstatus) {
839                 case SEL_FILE_TEXT:
840                         SFstatus = SEL_FILE_NULL;
841                         SFtextChanged();
842                         break;
843                 case SEL_FILE_OK:
844                         *name_return = SFgetText();
845                         if(mode && (mode[0] == 'p' || mode[0] == 'f')) { // [HGM] for use in file-option browse button
846                                 SFprepareToReturn();
847                                 return stderr;
848                         }
849                         if ((*name_return)[strlen(*name_return)-1] != '/' &&         // [HGM] refuse directories
850                             (fp = SFopenFile(*name_return, mode, prompt, failed))) {
851                                 SFprepareToReturn();
852                                 return fp;
853                         }
854                         SFstatus = SEL_FILE_NULL;
855                         break;
856                 case SEL_FILE_CANCEL:
857                         SFprepareToReturn();
858                         SFsetText(SFlastPath);
859                         return NULL;
860                 case SEL_FILE_NULL:
861                         break;
862                 }
863         }
864 }