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