bf7e0520dc7d582d21c305c04a54681fc373f408
[xscreensaver] / driver / demo-Xm.c
1 /* demo-Xm.c --- implements the interactive demo-mode and options dialogs.
2  * xscreensaver, Copyright (c) 1993-2001 Jamie Zawinski <jwz@jwz.org>
3  *
4  * Permission to use, copy, modify, distribute, and sell this software and its
5  * documentation for any purpose is hereby granted without fee, provided that
6  * the above copyright notice appear in all copies and that both that
7  * copyright notice and this permission notice appear in supporting
8  * documentation.  No representations are made about the suitability of this
9  * software for any purpose.  It is provided "as is" without express or 
10  * implied warranty.
11  */
12
13 #ifdef HAVE_CONFIG_H
14 # include "config.h"
15 #endif
16
17 #ifdef HAVE_MOTIF /* whole file */
18
19 #include <stdlib.h>
20
21 #ifdef HAVE_UNISTD_H
22 # include <unistd.h>
23 #endif
24
25 #ifndef VMS
26 # include <pwd.h>               /* for getpwuid() */
27 #else /* VMS */
28 # include "vms-pwd.h"
29 #endif /* VMS */
30
31 #ifdef HAVE_UNAME
32 # include <sys/utsname.h>       /* for uname() */
33 #endif /* HAVE_UNAME */
34
35 #include <stdio.h>
36
37 #include <X11/Xproto.h>         /* for CARD32 */
38 #include <X11/Xatom.h>          /* for XA_INTEGER */
39 #include <X11/Intrinsic.h>
40 #include <X11/StringDefs.h>
41
42 /* We don't actually use any widget internals, but these are included
43    so that gdb will have debug info for the widgets... */
44 #include <X11/IntrinsicP.h>
45 #include <X11/ShellP.h>
46
47 #ifdef HAVE_XPM
48 # include <X11/xpm.h>
49 #endif /* HAVE_XPM */
50
51 #ifdef HAVE_XMU
52 # ifndef VMS
53 #  include <X11/Xmu/Error.h>
54 # else /* VMS */
55 #  include <Xmu/Error.h>
56 # endif
57 #else
58 # include "xmu.h"
59 #endif
60
61
62
63 #include <Xm/Xm.h>
64 #include <Xm/List.h>
65 #include <Xm/PushB.h>
66 #include <Xm/LabelG.h>
67 #include <Xm/RowColumn.h>
68 #include <Xm/MessageB.h>
69
70 #ifdef HAVE_XMCOMBOBOX          /* a Motif 2.0 widget */
71 # include <Xm/ComboBox.h>
72 # ifndef XmNtextField           /* Lesstif 0.89.4 bug */
73 #  undef HAVE_XMCOMBOBOX
74 # endif
75 #endif /* HAVE_XMCOMBOBOX */
76
77 #include "version.h"
78 #include "prefs.h"
79 #include "resources.h"          /* for parse_time() */
80 #include "visual.h"             /* for has_writable_cells() */
81 #include "remote.h"             /* for xscreensaver_command() */
82 #include "usleep.h"
83
84 #include <stdio.h>
85 #include <string.h>
86 #include <ctype.h>
87
88 #undef countof
89 #define countof(x) (sizeof((x))/sizeof((*x)))
90
91
92 char *progname = 0;
93 char *progclass = "XScreenSaver";
94 XrmDatabase db;
95
96 typedef struct {
97   saver_preferences *a, *b;
98 } prefs_pair;
99
100 static void *global_prefs_pair;  /* I hate C so much... */
101
102 char *blurb (void) { return progname; }
103
104 extern Widget create_xscreensaver_demo (Widget parent);
105 extern const char *visual_menu[];
106
107
108 static char *short_version = 0;
109
110 Atom XA_VROOT;
111 Atom XA_SCREENSAVER, XA_SCREENSAVER_RESPONSE, XA_SCREENSAVER_VERSION;
112 Atom XA_SCREENSAVER_ID, XA_SCREENSAVER_STATUS, XA_SELECT, XA_DEMO;
113 Atom XA_ACTIVATE, XA_BLANK, XA_LOCK, XA_RESTART, XA_EXIT;
114
115
116 static void populate_demo_window (Widget toplevel,
117                                   int which, prefs_pair *pair);
118 static void populate_prefs_page (Widget top, prefs_pair *pair);
119 static int apply_changes_and_save (Widget widget);
120 static int maybe_reload_init_file (Widget widget, prefs_pair *pair);
121 static void await_xscreensaver (Widget widget);
122
123 \f
124 /* Some random utility functions
125  */
126
127 static Widget 
128 name_to_widget (Widget widget, const char *name)
129 {
130   Widget parent;
131   char name2[255];
132   name2[0] = '*';
133   strcpy (name2+1, name);
134   
135   while ((parent = XtParent (widget)))
136     widget = parent;
137   return XtNameToWidget (widget, name2);
138 }
139
140
141
142 /* Why this behavior isn't automatic in *either* toolkit, I'll never know.
143    Takes a scroller, viewport, or list as an argument.
144  */
145 static void
146 ensure_selected_item_visible (Widget list)
147 {
148   int *pos_list = 0;
149   int pos_count = 0;
150   if (XmListGetSelectedPos (list, &pos_list, &pos_count) && pos_count > 0)
151     {
152       int top = -2;
153       int visible = 0;
154       XtVaGetValues (list,
155                      XmNtopItemPosition, &top,
156                      XmNvisibleItemCount, &visible,
157                      0);
158       if (pos_list[0] >= top + visible)
159         {
160           int pos = pos_list[0] - visible + 1;
161           if (pos < 0) pos = 0;
162           XmListSetPos (list, pos);
163         }
164       else if (pos_list[0] < top)
165         {
166           XmListSetPos (list, pos_list[0]);
167         }
168     }
169   if (pos_list)
170     XtFree ((char *) pos_list);
171 }
172
173
174 static void
175 warning_dialog_dismiss_cb  (Widget button, XtPointer client_data,
176                             XtPointer user_data)
177 {
178   Widget shell = (Widget) client_data;
179   XtDestroyWidget (shell);
180 }
181
182
183 static void
184 warning_dialog (Widget parent, const char *message, int center)
185 {
186   char *msg = strdup (message);
187   char *head;
188
189   Widget dialog = 0;
190   Widget label = 0;
191   Widget ok = 0;
192   int i = 0;
193
194   Widget w;
195   Widget container;
196   XmString xmstr;
197   Arg av[10];
198   int ac = 0;
199
200   ac = 0;
201   dialog = XmCreateWarningDialog (parent, "warning", av, ac);
202
203   w = XmMessageBoxGetChild (dialog, XmDIALOG_MESSAGE_LABEL);
204   if (w) XtUnmanageChild (w);
205   w = XmMessageBoxGetChild (dialog, XmDIALOG_CANCEL_BUTTON);
206   if (w) XtUnmanageChild (w);
207   w = XmMessageBoxGetChild (dialog, XmDIALOG_HELP_BUTTON);
208   if (w) XtUnmanageChild (w);
209
210   ok = XmMessageBoxGetChild (dialog, XmDIALOG_OK_BUTTON);
211
212   ac = 0;
213   XtSetArg (av[ac], XmNnumColumns, 1); ac++;
214   XtSetArg (av[ac], XmNorientation, XmVERTICAL); ac++;
215   XtSetArg (av[ac], XmNpacking, XmPACK_COLUMN); ac++;
216   XtSetArg (av[ac], XmNrowColumnType, XmWORK_AREA); ac++;
217   XtSetArg (av[ac], XmNspacing, 0); ac++;
218   container = XmCreateRowColumn (dialog, "container", av, ac);
219
220   head = msg;
221   while (head)
222     {
223       char name[20];
224       char *s = strchr (head, '\n');
225       if (s) *s = 0;
226
227       sprintf (name, "label%d", i++);
228
229       xmstr = XmStringCreate (head, XmSTRING_DEFAULT_CHARSET);
230       ac = 0;
231       XtSetArg (av[ac], XmNlabelString, xmstr); ac++;
232       XtSetArg (av[ac], XmNmarginHeight, 0); ac++;
233       label = XmCreateLabelGadget (container, name, av, ac);
234       XtManageChild (label);
235       XmStringFree (xmstr);
236
237       if (s)
238         head = s+1;
239       else
240         head = 0;
241
242       center--;
243     }
244
245   XtManageChild (container);
246   XtRealizeWidget (dialog);
247   XtManageChild (dialog);
248
249   XtAddCallback (ok, XmNactivateCallback, warning_dialog_dismiss_cb, dialog);
250
251   free (msg);
252 }
253
254
255 static void
256 run_cmd (Widget widget, Atom command, int arg)
257 {
258   char *err = 0;
259   int status;
260
261   apply_changes_and_save (widget);
262   status = xscreensaver_command (XtDisplay (widget),
263                                  command, arg, False, &err);
264   if (status < 0)
265     {
266       char buf [255];
267       if (err)
268         sprintf (buf, "Error:\n\n%s", err);
269       else
270         strcpy (buf, "Unknown error!");
271       warning_dialog (widget, buf, 100);
272     }
273   if (err) free (err);
274 }
275
276
277 static void
278 run_hack (Widget widget, int which, Bool report_errors_p)
279 {
280   if (which < 0) return;
281   apply_changes_and_save (widget);
282   if (report_errors_p)
283     run_cmd (widget, XA_DEMO, which + 1);
284   else
285     {
286       char *s = 0;
287       xscreensaver_command (XtDisplay (widget), XA_DEMO, which + 1, False, &s);
288       if (s) free (s);
289     }
290 }
291
292
293 \f
294 /* Button callbacks
295  */
296
297 void
298 exit_menu_cb (Widget button, XtPointer client_data, XtPointer ignored)
299 {
300   apply_changes_and_save (XtParent (button));
301   exit (0);
302 }
303
304 #if 0
305 static void
306 wm_close_cb (Widget widget, GdkEvent *event, XtPointer data)
307 {
308   apply_changes_and_save (XtParent (button));
309   exit (0);
310 }
311 #endif
312
313 void
314 cut_menu_cb (Widget button, XtPointer client_data, XtPointer ignored)
315 {
316   /* #### */
317   warning_dialog (XtParent (button),
318                   "Error:\n\n"
319                   "cut unimplemented\n", 1);
320 }
321
322
323 void
324 copy_menu_cb (Widget button, XtPointer client_data, XtPointer ignored)
325 {
326   /* #### */
327   warning_dialog (XtParent (button),
328                   "Error:\n\n"
329                   "copy unimplemented\n", 1);
330 }
331
332
333 void
334 paste_menu_cb (Widget button, XtPointer client_data, XtPointer ignored)
335 {
336   /* #### */
337   warning_dialog (XtParent (button),
338                   "Error:\n\n"
339                   "paste unimplemented\n", 1);
340 }
341
342
343 void
344 about_menu_cb (Widget button, XtPointer client_data, XtPointer ignored)
345 {
346   char buf [2048];
347   char *s = strdup (screensaver_id + 4);
348   char *s2;
349
350   s2 = strchr (s, ',');
351   *s2 = 0;
352   s2 += 2;
353
354   sprintf (buf, "%s\n%s\n\n"
355            "For updates, check http://www.jwz.org/xscreensaver/",
356            s, s2);
357   free (s);
358
359   warning_dialog (XtParent (button), buf, 100);
360 }
361
362
363 void
364 doc_menu_cb (Widget button, XtPointer client_data, XtPointer ignored)
365 {
366   prefs_pair *pair = (prefs_pair *) client_data;
367
368   saver_preferences *p =  pair->a;
369   char *help_command;
370
371   if (!p->help_url || !*p->help_url)
372     {
373       warning_dialog (XtParent (button),
374                       "Error:\n\n"
375                       "No Help URL has been specified.\n", 100);
376       return;
377     }
378
379   help_command = (char *) malloc (strlen (p->load_url_command) +
380                                   (strlen (p->help_url) * 2) + 20);
381   strcpy (help_command, "( ");
382   sprintf (help_command + strlen(help_command),
383            p->load_url_command, p->help_url, p->help_url);
384   strcat (help_command, " ) &");
385   system (help_command);
386   free (help_command);
387 }
388
389
390 void
391 activate_menu_cb (Widget button, XtPointer client_data, XtPointer ignored)
392 {
393   run_cmd (XtParent (button), XA_ACTIVATE, 0);
394 }
395
396
397 void
398 lock_menu_cb (Widget button, XtPointer client_data, XtPointer ignored)
399 {
400   run_cmd (XtParent (button), XA_LOCK, 0);
401 }
402
403
404 void
405 kill_menu_cb (Widget button, XtPointer client_data, XtPointer ignored)
406 {
407   run_cmd (XtParent (button), XA_EXIT, 0);
408 }
409
410
411 void
412 restart_menu_cb (Widget button, XtPointer client_data, XtPointer ignored)
413 {
414 #if 0
415   run_cmd (XtParent (button), XA_RESTART, 0);
416 #else
417   button = XtParent (button);
418   apply_changes_and_save (button);
419   xscreensaver_command (XtDisplay (button), XA_EXIT, 0, False, NULL);
420   sleep (1);
421   system ("xscreensaver -nosplash &");
422 #endif
423
424   await_xscreensaver (button);
425 }
426
427 static void
428 await_xscreensaver (Widget widget)
429 {
430   int countdown = 5;
431
432   Display *dpy = XtDisplay (widget);
433   char *rversion = 0;
434
435   while (!rversion && (--countdown > 0))
436     {
437       /* Check for the version of the running xscreensaver... */
438       server_xscreensaver_version (dpy, &rversion, 0, 0);
439
440       /* If it's not there yet, wait a second... */
441       sleep (1);
442     }
443
444   if (rversion)
445     {
446       /* Got it. */
447       free (rversion);
448     }
449   else
450     {
451       /* Timed out, no screensaver running. */
452
453       char buf [1024];
454       Bool root_p = (geteuid () == 0);
455       
456       strcpy (buf, 
457               "Error:\n\n"
458               "The xscreensaver daemon did not start up properly.\n"
459               "\n");
460
461       if (root_p)
462         strcat (buf,
463             "You are running as root.  This usually means that xscreensaver\n"
464             "was unable to contact your X server because access control is\n"
465             "turned on.  Try running this command:\n"
466             "\n"
467             "                        xhost +localhost\n"
468             "\n"
469             "and then selecting `File / Restart Daemon'.\n"
470             "\n"
471             "Note that turning off access control will allow anyone logged\n"
472             "on to this machine to access your screen, which might be\n"
473             "considered a security problem.  Please read the xscreensaver\n"
474             "manual and FAQ for more information.\n"
475             "\n"
476             "You shouldn't run X as root. Instead, you should log in as a\n"
477             "normal user, and `su' as necessary.");
478       else
479         strcat (buf, "Please check your $PATH and permissions.");
480
481       warning_dialog (XtParent (widget), buf, 1);
482     }
483 }
484
485
486 static int _selected_hack_number = -1;
487
488 static int
489 selected_hack_number (Widget toplevel)
490 {
491   return _selected_hack_number;
492 }
493
494
495 static int
496 demo_write_init_file (Widget widget, saver_preferences *p)
497 {
498   if (!write_init_file (p, short_version, False))
499     return 0;
500   else
501     {
502       const char *f = init_file_name();
503       if (!f || !*f)
504         warning_dialog (widget,
505                         "Error:\n\nCouldn't determine init file name!\n",
506                         100);
507       else
508         {
509           char *b = (char *) malloc (strlen(f) + 1024);
510           sprintf (b, "Error:\n\nCouldn't write %s\n", f);
511           warning_dialog (widget, b, 100);
512           free (b);
513         }
514       return -1;
515     }
516 }
517
518
519 static int
520 apply_changes_and_save (Widget widget)
521 {
522   prefs_pair *pair = global_prefs_pair;
523   saver_preferences *p =  pair->a;
524   Widget list_widget = name_to_widget (widget, "list");
525   int which = selected_hack_number (widget);
526
527   Widget cmd = name_to_widget (widget, "cmdText");
528   Widget enabled = name_to_widget (widget, "enabled");
529
530   Widget vis = name_to_widget (widget, "combo");
531 # ifdef HAVE_XMCOMBOBOX
532   Widget text = 0;
533 # else /* !HAVE_XMCOMBOBOX */
534   Widget menu = 0, *kids = 0, selected_item = 0;
535   Cardinal nkids = 0;
536   int i = 0;
537 # endif /* !HAVE_XMCOMBOBOX */
538
539   Bool enabled_p = False;
540   const char *visual = 0;
541   const char *command = 0;
542   
543   char c;
544   unsigned long id;
545
546   if (which < 0) return -1;
547
548 # ifdef HAVE_XMCOMBOBOX
549   XtVaGetValues (vis, XmNtextField, &text, 0);
550   if (!text)
551     /* If we can't get at the text field of this combo box, we're screwed. */
552     abort();
553   XtVaGetValues (text, XmNvalue, &visual, 0);
554
555 # else /* !HAVE_XMCOMBOBOX */
556   XtVaGetValues (vis, XmNsubMenuId, &menu, 0);
557   XtVaGetValues (menu, XmNnumChildren, &nkids, XmNchildren, &kids, 0);
558   XtVaGetValues (menu, XmNmenuHistory, &selected_item, 0);
559   if (selected_item)
560     for (i = 0; i < nkids; i++)
561       if (kids[i] == selected_item)
562         break;
563
564   visual = visual_menu[i];
565 # endif /* !HAVE_XMCOMBOBOX */
566
567   XtVaGetValues (enabled, XmNset, &enabled_p, 0);
568   XtVaGetValues (cmd, XtNvalue, &command, 0);
569
570   if (maybe_reload_init_file (widget, pair) != 0)
571     return 1;
572
573   /* Sanity-check and canonicalize whatever the user typed into the combo box.
574    */
575   if      (!strcasecmp (visual, ""))                   visual = "";
576   else if (!strcasecmp (visual, "any"))                visual = "";
577   else if (!strcasecmp (visual, "default"))            visual = "Default";
578   else if (!strcasecmp (visual, "default-n"))          visual = "Default-N";
579   else if (!strcasecmp (visual, "default-i"))          visual = "Default-I";
580   else if (!strcasecmp (visual, "best"))               visual = "Best";
581   else if (!strcasecmp (visual, "mono"))               visual = "Mono";
582   else if (!strcasecmp (visual, "monochrome"))         visual = "Mono";
583   else if (!strcasecmp (visual, "gray"))               visual = "Gray";
584   else if (!strcasecmp (visual, "grey"))               visual = "Gray";
585   else if (!strcasecmp (visual, "color"))              visual = "Color";
586   else if (!strcasecmp (visual, "gl"))                 visual = "GL";
587   else if (!strcasecmp (visual, "staticgray"))         visual = "StaticGray";
588   else if (!strcasecmp (visual, "staticcolor"))        visual = "StaticColor";
589   else if (!strcasecmp (visual, "truecolor"))          visual = "TrueColor";
590   else if (!strcasecmp (visual, "grayscale"))          visual = "GrayScale";
591   else if (!strcasecmp (visual, "greyscale"))          visual = "GrayScale";
592   else if (!strcasecmp (visual, "pseudocolor"))        visual = "PseudoColor";
593   else if (!strcasecmp (visual, "directcolor"))        visual = "DirectColor";
594   else if (1 == sscanf (visual, " %ld %c", &id, &c))   ;
595   else if (1 == sscanf (visual, " 0x%lx %c", &id, &c)) ;
596   else
597     {
598       XBell (XtDisplay (widget), 0);                      /* unparsable */
599       visual = "";
600       /* #### gtk_entry_set_text (GTK_ENTRY (GTK_COMBO (vis)->entry), "Any");*/
601     }
602
603   ensure_selected_item_visible (list_widget);
604
605   if (!p->screenhacks[which]->visual)
606     p->screenhacks[which]->visual = strdup ("");
607   if (!p->screenhacks[which]->command)
608     p->screenhacks[which]->command = strdup ("");
609
610   if (p->screenhacks[which]->enabled_p != enabled_p ||
611       !!strcasecmp (p->screenhacks[which]->visual, visual) ||
612       !!strcasecmp (p->screenhacks[which]->command, command))
613     {
614       /* Something was changed -- store results into the struct,
615          and write the file.
616        */
617       free (p->screenhacks[which]->visual);
618       free (p->screenhacks[which]->command);
619       p->screenhacks[which]->visual = strdup (visual);
620       p->screenhacks[which]->command = strdup (command);
621       p->screenhacks[which]->enabled_p = enabled_p;
622
623       return demo_write_init_file (widget, p);
624     }
625
626   /* No changes made */
627   return 0;
628 }
629
630 void
631 run_this_cb (Widget button, XtPointer client_data, XtPointer ignored)
632 {
633   int which = selected_hack_number (XtParent (button));
634   if (which < 0) return;
635   if (0 == apply_changes_and_save (XtParent (button)))
636     run_hack (XtParent (button), which, True);
637 }
638
639
640 void
641 manual_cb (Widget button, XtPointer client_data, XtPointer ignored)
642 {
643   prefs_pair *pair = (prefs_pair *) client_data;
644   saver_preferences *p =  pair->a;
645   Widget list_widget = name_to_widget (button, "list");
646   int which = selected_hack_number (button);
647   char *name, *name2, *cmd, *s;
648   if (which < 0) return;
649   apply_changes_and_save (button);
650   ensure_selected_item_visible (list_widget);
651
652   name = strdup (p->screenhacks[which]->command);
653   name2 = name;
654   while (isspace (*name2)) name2++;
655   s = name2;
656   while (*s && !isspace (*s)) s++;
657   *s = 0;
658   s = strrchr (name2, '/');
659   if (s) name = s+1;
660
661   cmd = get_string_resource ("manualCommand", "ManualCommand");
662   if (cmd)
663     {
664       char *cmd2 = (char *) malloc (strlen (cmd) + strlen (name2) + 100);
665       strcpy (cmd2, "( ");
666       sprintf (cmd2 + strlen (cmd2),
667                cmd,
668                name2, name2, name2, name2);
669       strcat (cmd2, " ) &");
670       system (cmd2);
671       free (cmd2);
672     }
673   else
674     {
675       warning_dialog (XtParent (button),
676                       "Error:\n\nno `manualCommand' resource set.",
677                       100);
678     }
679
680   free (name);
681 }
682
683
684 void
685 run_next_cb (Widget button, XtPointer client_data, XtPointer ignored)
686 {
687   prefs_pair *pair = (prefs_pair *) client_data;
688   saver_preferences *p =  pair->a;
689
690   Widget list_widget = name_to_widget (button, "list");
691   int which = selected_hack_number (button);
692
693   button = XtParent (button);
694
695   if (which < 0)
696     which = 0;
697   else
698     which++;
699
700   if (which >= p->screenhacks_count)
701     which = 0;
702
703   apply_changes_and_save (button);
704
705   XmListDeselectAllItems (list_widget); /* LessTif lossage */
706   XmListSelectPos (list_widget, which+1, True);
707
708   ensure_selected_item_visible (list_widget);
709   populate_demo_window (button, which, pair);
710   run_hack (button, which, False);
711 }
712
713
714 void
715 run_prev_cb (Widget button, XtPointer client_data, XtPointer ignored)
716 {
717   prefs_pair *pair = (prefs_pair *) client_data;
718   saver_preferences *p =  pair->a;
719
720   Widget list_widget = name_to_widget (button, "list");
721   int which = selected_hack_number (button);
722
723   button = XtParent (button);
724
725   if (which < 0)
726     which = p->screenhacks_count - 1;
727   else
728     which--;
729
730   if (which < 0)
731     which = p->screenhacks_count - 1;
732
733   apply_changes_and_save (button);
734
735   XmListDeselectAllItems (list_widget); /* LessTif lossage */
736   XmListSelectPos (list_widget, which+1, True);
737
738   ensure_selected_item_visible (list_widget);
739   populate_demo_window (button, which, pair);
740   run_hack (button, which, False);
741 }
742
743
744 /* Helper for the text fields that contain time specifications:
745    this parses the text, and does error checking.
746  */
747 static void 
748 hack_time_text (Widget button, const char *line, Time *store, Bool sec_p)
749 {
750   if (*line)
751     {
752       int value;
753       value = parse_time ((char *) line, sec_p, True);
754       value *= 1000;    /* Time measures in microseconds */
755       if (value < 0)
756         {
757           char b[255];
758           sprintf (b,
759                    "Error:\n\n"
760                    "Unparsable time format: \"%s\"\n",
761                    line);
762           warning_dialog (XtParent (button), b, 100);
763         }
764       else
765         *store = value;
766     }
767 }
768
769
770 void
771 prefs_ok_cb (Widget button, XtPointer client_data, XtPointer ignored)
772 {
773   prefs_pair *pair = (prefs_pair *) client_data;
774
775   saver_preferences *p =  pair->a;
776   saver_preferences *p2 = pair->b;
777   Bool changed = False;
778   char *v = 0;
779
780   button = XtParent (button);
781
782 # define SECONDS(field, name) \
783   v = 0; \
784   XtVaGetValues (name_to_widget (button, (name)), XtNvalue, &v, 0); \
785   hack_time_text (button, v, (field), True)
786
787 # define MINUTES(field, name) \
788   v = 0; \
789   XtVaGetValues (name_to_widget (button, (name)), XtNvalue, &v, 0); \
790   hack_time_text (button, v, (field), False)
791
792 # define INTEGER(field, name) do { \
793     unsigned int value; \
794     char c; \
795     XtVaGetValues (name_to_widget (button, (name)), XtNvalue, &v, 0); \
796     if (! *v) \
797       ; \
798     else if (sscanf (v, "%u%c", &value, &c) != 1) \
799       { \
800         char b[255]; \
801         sprintf (b, "Error:\n\n" "Not an integer: \"%s\"\n", v); \
802         warning_dialog (XtParent (button), b, 100); \
803       } \
804    else \
805      *(field) = value; \
806   } while(0)
807
808 # define CHECKBOX(field, name) \
809   XtVaGetValues (name_to_widget (button, (name)), XmNset, &field, 0)
810
811   MINUTES (&p2->timeout,        "timeoutText");
812   MINUTES (&p2->cycle,          "cycleText");
813   SECONDS (&p2->fade_seconds,   "fadeSecondsText");
814   INTEGER (&p2->fade_ticks,     "fadeTicksText");
815   MINUTES (&p2->lock_timeout,   "lockText");
816   SECONDS (&p2->passwd_timeout, "passwdText");
817   CHECKBOX (p2->verbose_p,      "verboseToggle");
818   CHECKBOX (p2->install_cmap_p, "cmapToggle");
819   CHECKBOX (p2->fade_p,         "fadeToggle");
820   CHECKBOX (p2->unfade_p,       "unfadeToggle");
821   CHECKBOX (p2->lock_p,         "lockToggle");
822
823 # undef SECONDS
824 # undef MINUTES
825 # undef INTEGER
826 # undef CHECKBOX
827
828 # define COPY(field) \
829   if (p->field != p2->field) changed = True; \
830   p->field = p2->field
831
832   COPY(timeout);
833   COPY(cycle);
834   COPY(lock_timeout);
835   COPY(passwd_timeout);
836   COPY(fade_seconds);
837   COPY(fade_ticks);
838   COPY(verbose_p);
839   COPY(install_cmap_p);
840   COPY(fade_p);
841   COPY(unfade_p);
842   COPY(lock_p);
843 # undef COPY
844
845   populate_prefs_page (button, pair);
846
847   if (changed)
848     demo_write_init_file (button, p);
849 }
850
851
852 void
853 prefs_cancel_cb (Widget button, XtPointer client_data, XtPointer ignored)
854 {
855   prefs_pair *pair = (prefs_pair *) client_data;
856
857   *pair->b = *pair->a;
858   populate_prefs_page (XtParent (button), pair);
859 }
860
861
862 static void
863 list_select_cb (Widget list, XtPointer client_data, XtPointer call_data)
864 {
865   prefs_pair *pair = (prefs_pair *) client_data;
866
867   XmListCallbackStruct *lcb = (XmListCallbackStruct *) call_data;
868   int which = lcb->item_position - 1;
869
870   apply_changes_and_save (list);
871   populate_demo_window (list, which, pair);
872
873   if (lcb->reason == XmCR_DEFAULT_ACTION && which >= 0)
874     run_hack (list, which, True);
875 }
876
877 \f
878 /* Populating the various widgets
879  */
880
881
882 /* Formats a `Time' into "H:MM:SS".  (Time is microseconds.)
883  */
884 static void
885 format_time (char *buf, Time time)
886 {
887   int s = time / 1000;
888   unsigned int h = 0, m = 0;
889   if (s >= 60)
890     {
891       m += (s / 60);
892       s %= 60;
893     }
894   if (m >= 60)
895     {
896       h += (m / 60);
897       m %= 60;
898     }
899   sprintf (buf, "%u:%02u:%02u", h, m, s);
900 }
901
902
903 /* Finds the number of the last hack to run, and makes that item be
904    selected by default.
905  */
906 static void
907 scroll_to_current_hack (Widget toplevel, prefs_pair *pair)
908 {
909   Atom type;
910   int format;
911   unsigned long nitems, bytesafter;
912   CARD32 *data = 0;
913   Display *dpy = XtDisplay (toplevel);
914   int which = 0;
915   Widget list;
916
917   if (XGetWindowProperty (dpy, RootWindow (dpy, 0), /* always screen #0 */
918                           XA_SCREENSAVER_STATUS,
919                           0, 3, False, XA_INTEGER,
920                           &type, &format, &nitems, &bytesafter,
921                           (unsigned char **) &data)
922       == Success
923       && type == XA_INTEGER
924       && nitems >= 3
925       && data)
926     which = (int) data[2] - 1;
927
928   if (data) free (data);
929
930   if (which < 0)
931     return;
932
933   list = name_to_widget (toplevel, "list");
934   apply_changes_and_save (toplevel);
935
936   XmListDeselectAllItems (list);        /* LessTif lossage */
937   XmListSelectPos (list, which+1, True);
938
939   ensure_selected_item_visible (list);
940   populate_demo_window (toplevel, which, pair);
941 }
942
943
944
945 static void
946 populate_hack_list (Widget toplevel, prefs_pair *pair)
947 {
948   saver_preferences *p =  pair->a;
949   Widget list = name_to_widget (toplevel, "list");
950   screenhack **hacks = p->screenhacks;
951   screenhack **h;
952
953   for (h = hacks; *h; h++)
954     {
955       char *pretty_name = (h[0]->name
956                            ? strdup (h[0]->name)
957                            : make_hack_name (h[0]->command));
958
959       XmString xmstr = XmStringCreate (pretty_name, XmSTRING_DEFAULT_CHARSET);
960       XmListAddItem (list, xmstr, 0);
961       XmStringFree (xmstr);
962     }
963
964   XtAddCallback (list, XmNbrowseSelectionCallback, list_select_cb, pair);
965   XtAddCallback (list, XmNdefaultActionCallback,   list_select_cb, pair);
966 }
967
968
969 static void
970 populate_prefs_page (Widget top, prefs_pair *pair)
971 {
972   saver_preferences *p =  pair->a;
973   char s[100];
974
975   format_time (s, p->timeout);
976   XtVaSetValues (name_to_widget (top, "timeoutText"),     XmNvalue, s, 0);
977   format_time (s, p->cycle);
978   XtVaSetValues (name_to_widget (top, "cycleText"),       XmNvalue, s, 0);
979   format_time (s, p->lock_timeout);
980   XtVaSetValues (name_to_widget (top, "lockText"),        XmNvalue, s, 0);
981   format_time (s, p->passwd_timeout);
982   XtVaSetValues (name_to_widget (top, "passwdText"),      XmNvalue, s, 0);
983   format_time (s, p->fade_seconds);
984   XtVaSetValues (name_to_widget (top, "fadeSecondsText"), XmNvalue, s, 0);
985   sprintf (s, "%u", p->fade_ticks);
986   XtVaSetValues (name_to_widget (top, "fadeTicksText"),   XmNvalue, s, 0);
987
988   XtVaSetValues (name_to_widget (top, "verboseToggle"),
989                  XmNset, p->verbose_p, 0);
990   XtVaSetValues (name_to_widget (top, "cmapToggle"),
991                  XmNset, p->install_cmap_p, 0);
992   XtVaSetValues (name_to_widget (top, "fadeToggle"),
993                  XmNset, p->fade_p, 0);
994   XtVaSetValues (name_to_widget (top, "unfadeToggle"),
995                  XmNset, p->unfade_p, 0);
996   XtVaSetValues (name_to_widget (top, "lockToggle"),
997                  XmNset, p->lock_p, 0);
998
999
1000   {
1001     Bool found_any_writable_cells = False;
1002     Display *dpy = XtDisplay (top);
1003     int nscreens = ScreenCount(dpy);
1004     int i;
1005     for (i = 0; i < nscreens; i++)
1006       {
1007         Screen *s = ScreenOfDisplay (dpy, i);
1008         if (has_writable_cells (s, DefaultVisualOfScreen (s)))
1009           {
1010             found_any_writable_cells = True;
1011             break;
1012           }
1013       }
1014
1015     XtVaSetValues (name_to_widget (top, "fadeSecondsLabel"), XtNsensitive,
1016                            found_any_writable_cells, 0);
1017     XtVaSetValues (name_to_widget (top, "fadeTicksLabel"), XtNsensitive,
1018                            found_any_writable_cells, 0);
1019     XtVaSetValues (name_to_widget (top, "fadeSecondsText"), XtNsensitive,
1020                            found_any_writable_cells, 0);
1021     XtVaSetValues (name_to_widget (top, "fadeTicksText"), XtNsensitive,
1022                            found_any_writable_cells, 0);
1023     XtVaSetValues (name_to_widget (top, "cmapToggle"), XtNsensitive,
1024                            found_any_writable_cells, 0);
1025     XtVaSetValues (name_to_widget (top, "fadeToggle"), XtNsensitive,
1026                            found_any_writable_cells, 0);
1027     XtVaSetValues (name_to_widget (top, "unfadeToggle"), XtNsensitive,
1028                            found_any_writable_cells, 0);
1029   }
1030 }
1031
1032
1033 static void
1034 sensitize_demo_widgets (Widget toplevel, Bool sensitive_p)
1035 {
1036   const char *names[] = { "cmdLabel", "cmdText", "enabled",
1037                           "visLabel", "combo", "demo", "man" };
1038   int i;
1039   for (i = 0; i < sizeof(names)/countof(*names); i++)
1040     {
1041       Widget w = name_to_widget (toplevel, names[i]);
1042       XtVaSetValues (w, XtNsensitive, sensitive_p, 0);
1043     }
1044
1045   /* I don't know how to handle these yet... */
1046   {
1047     const char *names2[] = { "cut", "copy", "paste" };
1048     for (i = 0; i < sizeof(names2)/countof(*names2); i++)
1049       {
1050         Widget w = name_to_widget (toplevel, names2[i]);
1051         XtVaSetValues (w, XtNsensitive, FALSE, 0);
1052       }
1053   }
1054 }
1055
1056
1057 \f
1058 /* Pixmaps for the up and down arrow buttons (yeah, this is sleazy...)
1059  */
1060
1061 #ifdef HAVE_XPM
1062
1063 static char *up_arrow_xpm[] = {
1064   "15 15 4 1",
1065   "     c None s background",
1066   "-    c #FFFFFF",
1067   "+    c #D6D6D6",
1068   "@    c #000000",
1069
1070   "       @       ",
1071   "       @       ",
1072   "      -+@      ",
1073   "      -+@      ",
1074   "     -+++@     ",
1075   "     -+++@     ",
1076   "    -+++++@    ",
1077   "    -+++++@    ",
1078   "   -+++++++@   ",
1079   "   -+++++++@   ",
1080   "  -+++++++++@  ",
1081   "  -+++++++++@  ",
1082   " -+++++++++++@ ",
1083   " @@@@@@@@@@@@@ ",
1084   "               "
1085 };
1086
1087 static char *down_arrow_xpm[] = {
1088   "15 15 4 1",
1089   "     c None s background",
1090   "-    c #FFFFFF",
1091   "+    c #D6D6D6",
1092   "@    c #000000",
1093
1094   "               ",
1095   " ------------- ",
1096   " -+++++++++++@ ",
1097   "  -+++++++++@  ",
1098   "  -+++++++++@  ",
1099   "   -+++++++@   ",
1100   "   -+++++++@   ",
1101   "    -+++++@    ",
1102   "    -+++++@    ",
1103   "     -+++@     ",
1104   "     -+++@     ",
1105   "      -+@      ",
1106   "      -+@      ",
1107   "       @       ",
1108   "       @       "
1109 };
1110
1111 #endif /* HAVE_XPM */
1112
1113
1114 static void
1115 pixmapify_buttons (Widget toplevel)
1116 {
1117 #ifdef HAVE_XPM
1118
1119   Display *dpy = XtDisplay (toplevel);
1120   Window window = XtWindow (toplevel);
1121   XWindowAttributes xgwa;
1122   XpmAttributes xpmattrs;
1123   Pixmap up_pixmap = 0, down_pixmap = 0;
1124   int result;
1125   Widget up = name_to_widget (toplevel, "up");
1126   Widget dn = name_to_widget (toplevel, "down");
1127 # ifdef XpmColorSymbols
1128   XColor xc;
1129   XpmColorSymbol symbols[2];
1130   char color[20];
1131 # endif
1132
1133   XGetWindowAttributes (dpy, window, &xgwa);
1134
1135   xpmattrs.valuemask = 0;
1136
1137 # ifdef XpmColorSymbols
1138   symbols[0].name = "background";
1139   symbols[0].pixel = 0;
1140   symbols[1].name = 0;
1141   XtVaGetValues (up, XmNbackground, &xc, 0);
1142   XQueryColor (dpy, xgwa.colormap, &xc);
1143   sprintf (color, "#%04X%04X%04X", xc.red, xc.green, xc.blue);
1144   symbols[0].value = color;
1145   symbols[0].pixel = xc.pixel;
1146
1147   xpmattrs.valuemask |= XpmColorSymbols;
1148   xpmattrs.colorsymbols = symbols;
1149   xpmattrs.numsymbols = 1;
1150 # endif
1151
1152 # ifdef XpmCloseness
1153   xpmattrs.valuemask |= XpmCloseness;
1154   xpmattrs.closeness = 40000;
1155 # endif
1156 # ifdef XpmVisual
1157   xpmattrs.valuemask |= XpmVisual;
1158   xpmattrs.visual = xgwa.visual;
1159 # endif
1160 # ifdef XpmDepth
1161   xpmattrs.valuemask |= XpmDepth;
1162   xpmattrs.depth = xgwa.depth;
1163 # endif
1164 # ifdef XpmColormap
1165   xpmattrs.valuemask |= XpmColormap;
1166   xpmattrs.colormap = xgwa.colormap;
1167 # endif
1168
1169   result = XpmCreatePixmapFromData(dpy, window, up_arrow_xpm,
1170                                    &up_pixmap, 0 /* mask */, &xpmattrs);
1171   if (!up_pixmap || (result != XpmSuccess && result != XpmColorError))
1172     {
1173       fprintf (stderr, "%s: Can't load pixmaps\n", progname);
1174       return;
1175     }
1176
1177   result = XpmCreatePixmapFromData(dpy, window, down_arrow_xpm,
1178                                    &down_pixmap, 0 /* mask */, &xpmattrs);
1179   if (!down_pixmap || (result != XpmSuccess && result != XpmColorError))
1180     {
1181       fprintf (stderr, "%s: Can't load pixmaps\n", progname);
1182       return;
1183     }
1184
1185   XtVaSetValues (up, XmNlabelType, XmPIXMAP, XmNlabelPixmap, up_pixmap, 0);
1186   XtVaSetValues (dn, XmNlabelType, XmPIXMAP, XmNlabelPixmap, down_pixmap, 0);
1187
1188 #endif /* HAVE_XPM */
1189 }
1190
1191
1192
1193 char *
1194 get_hack_blurb (screenhack *hack)
1195 {
1196   char *doc_string;
1197   char *prog_name = strdup (hack->command);
1198   char *pretty_name = (hack->name
1199                        ? strdup (hack->name)
1200                        : make_hack_name (hack->command));
1201   char doc_name[255], doc_class[255];
1202   char *s, *s2;
1203
1204   for (s = prog_name; *s && !isspace(*s); s++)
1205     ;
1206   *s = 0;
1207   s = strrchr (prog_name, '/');
1208   if (s) strcpy (prog_name, s+1);
1209
1210   sprintf (doc_name,  "hacks.%s.documentation", pretty_name);
1211   sprintf (doc_class, "hacks.%s.documentation", prog_name);
1212   free (prog_name);
1213   free (pretty_name);
1214
1215   doc_string = get_string_resource (doc_name, doc_class);
1216   if (doc_string)
1217     {
1218       for (s = doc_string; *s; s++)
1219         {
1220           if (*s == '\n')
1221             {
1222               /* skip over whitespace at beginning of line */
1223               s++;
1224               while (*s && (*s == ' ' || *s == '\t'))
1225                 s++;
1226             }
1227           else if (*s == ' ' || *s == '\t')
1228             {
1229               /* compress all other horizontal whitespace. */
1230               *s = ' ';
1231               s++;
1232               for (s2 = s; *s2 && (*s2 == ' ' || *s2 == '\t'); s2++)
1233                 ;
1234               if (s2 > s) strcpy (s, s2);
1235               s--;
1236             }
1237         }
1238
1239       while (*s && isspace (*s))      /* Strip trailing whitespace */
1240         *(--s) = 0;
1241
1242       /* Delete whitespace at end of each line. */
1243       for (; s > doc_string; s--)
1244         if (*s == '\n' && (s[-1] == ' ' || s[-1] == '\t'))
1245           {
1246             for (s2 = s-1;
1247                  s2 > doc_string && (*s2 == ' ' || *s2 == '\t');
1248                  s2--)
1249               ;
1250             s2++;
1251             if (s2 < s) strcpy (s2, s);
1252             s = s2;
1253           }
1254       
1255       /* Delete leading blank lines. */
1256       for (s = doc_string; *s == '\n'; s++)
1257         ;
1258       if (s > doc_string) strcpy (doc_string, s);
1259     }
1260   else
1261     {
1262       static int doc_installed = 0;
1263       if (doc_installed == 0)
1264         {
1265           if (get_boolean_resource ("hacks.documentation.isInstalled",
1266                                     "hacks.documentation.isInstalled"))
1267             doc_installed = 1;
1268           else
1269             doc_installed = -1;
1270         }
1271
1272       if (doc_installed < 0)
1273         doc_string =
1274           strdup ("Error:\n\n"
1275                   "The documentation strings do not appear to be "
1276                   "installed.  This is probably because there is "
1277                   "an \"XScreenSaver\" app-defaults file installed "
1278                   "that is from an older version of the program. "
1279                   "To fix this problem, delete that file, or "
1280                   "install a current version (either will work.)");
1281       else
1282         doc_string = strdup ("");
1283     }
1284
1285   return doc_string;
1286 }
1287
1288
1289 static void
1290 populate_demo_window (Widget toplevel, int which, prefs_pair *pair)
1291 {
1292   saver_preferences *p = pair->a;
1293   screenhack *hack = (which >= 0 ? p->screenhacks[which] : 0);
1294   Widget frameL = name_to_widget (toplevel, "frameLabel");
1295   Widget doc = name_to_widget (toplevel, "doc");
1296   Widget cmd = name_to_widget (toplevel, "cmdText");
1297   Widget enabled = name_to_widget (toplevel, "enabled");
1298   Widget vis = name_to_widget (toplevel, "combo");
1299   int i = 0;
1300
1301   char *pretty_name = (hack
1302                        ? (hack->name
1303                           ? strdup (hack->name)
1304                           : make_hack_name (hack->command))
1305                        : 0);
1306   char *doc_string = hack ? get_hack_blurb (hack) : 0;
1307
1308   XmString xmstr;
1309
1310   xmstr = XmStringCreate (pretty_name, XmSTRING_DEFAULT_CHARSET);
1311   XtVaSetValues (frameL, XmNlabelString, xmstr, 0);
1312   XmStringFree (xmstr);
1313
1314   XtVaSetValues (doc, XmNvalue, doc_string, 0);
1315   XtVaSetValues (cmd, XmNvalue, (hack ? hack->command : ""), 0);
1316
1317   XtVaSetValues (enabled, XmNset, (hack ? hack->enabled_p : False), 0);
1318
1319   i = 0;
1320   if (hack && hack->visual && *hack->visual)
1321     for (i = 0; visual_menu[i]; i++)
1322       if (!strcasecmp (hack->visual, visual_menu[i]))
1323         break;
1324   if (!visual_menu[i]) i = -1;
1325
1326   {
1327 # ifdef HAVE_XMCOMBOBOX
1328     Widget text = 0;
1329     XtVaGetValues (vis, XmNtextField, &text, 0);
1330     XtVaSetValues (vis, XmNselectedPosition, i, 0);
1331     if (i < 0)
1332       XtVaSetValues (text, XmNvalue, hack->visual, 0);
1333 # else /* !HAVE_XMCOMBOBOX */
1334     Cardinal nkids;
1335     Widget *kids;
1336     Widget menu;
1337
1338     XtVaGetValues (vis, XmNsubMenuId, &menu, 0);
1339     if (!menu) abort ();
1340     XtVaGetValues (menu, XmNnumChildren, &nkids, XmNchildren, &kids, 0);
1341     if (!kids) abort();
1342     if (i < nkids)
1343       XtVaSetValues (vis, XmNmenuHistory, kids[i], 0);
1344 # endif /* !HAVE_XMCOMBOBOX */
1345   }
1346
1347   sensitize_demo_widgets (toplevel, (hack ? True : False));
1348
1349   if (pretty_name) free (pretty_name);
1350   if (doc_string) free (doc_string);
1351
1352   _selected_hack_number = which;
1353 }
1354
1355
1356
1357 static int
1358 maybe_reload_init_file (Widget widget, prefs_pair *pair)
1359 {
1360   int status = 0;
1361   saver_preferences *p =  pair->a;
1362
1363   static Bool reentrant_lock = False;
1364   if (reentrant_lock) return 0;
1365   reentrant_lock = True;
1366
1367   if (init_file_changed_p (p))
1368     {
1369       const char *f = init_file_name();
1370       char *b;
1371       int which;
1372       Widget list;
1373
1374       if (!f || !*f) return 0;
1375       b = (char *) malloc (strlen(f) + 1024);
1376       sprintf (b,
1377                "Warning:\n\n"
1378                "file \"%s\" has changed, reloading.\n",
1379                f);
1380       warning_dialog (widget, b, 100);
1381       free (b);
1382
1383       load_init_file (p);
1384
1385       which = selected_hack_number (widget);
1386       list = name_to_widget (widget, "list");
1387
1388       XtVaSetValues (list, XmNitemCount, 0, 0);
1389
1390       populate_hack_list (widget, pair);
1391
1392       XmListDeselectAllItems (list);    /* LessTif lossage */
1393       XmListSelectPos (list, which+1, True);
1394
1395       populate_prefs_page (widget, pair);
1396       populate_demo_window (widget, which, pair);
1397       ensure_selected_item_visible (list);
1398
1399       status = 1;
1400     }
1401
1402   reentrant_lock = False;
1403   return status;
1404 }
1405
1406
1407 \f
1408 /* Attach all callback functions to widgets
1409  */
1410
1411 static void
1412 add_callbacks (Widget toplevel, prefs_pair *pair)
1413 {
1414   Widget w;
1415
1416 # define CB(NAME,FN) \
1417   w = name_to_widget (toplevel, (NAME)); \
1418   XtAddCallback (w, XmNactivateCallback, (FN), pair)
1419
1420   CB ("blank",   activate_menu_cb);
1421   CB ("lock",    lock_menu_cb);
1422   CB ("kill",    kill_menu_cb);
1423   CB ("restart", restart_menu_cb);
1424   CB ("exit",    exit_menu_cb);
1425
1426   CB ("cut",     cut_menu_cb);
1427   CB ("copy",    copy_menu_cb);
1428   CB ("paste",   paste_menu_cb);
1429
1430   CB ("about",   about_menu_cb);
1431   CB ("docMenu", doc_menu_cb);
1432
1433   CB ("down",    run_next_cb);
1434   CB ("up",      run_prev_cb);
1435   CB ("demo",    run_this_cb);
1436   CB ("man",     manual_cb);
1437
1438   CB ("preferencesForm.Cancel",  prefs_cancel_cb);
1439   CB ("preferencesForm.OK",      prefs_ok_cb);
1440
1441 # undef CB
1442 }
1443
1444
1445 static void
1446 sanity_check_resources (Widget toplevel)
1447 {
1448   const char *names[] = { "demoTab", "optionsTab", "cmdLabel", "visLabel",
1449                           "enabled", "demo", "man", "timeoutLabel",
1450                           "cycleLabel", "fadeSecondsLabel", "fadeTicksLabel",
1451                           "lockLabel", "passwdLabel" };
1452   int i;
1453   for (i = 0; i < sizeof(names)/countof(*names); i++)
1454     {
1455       Widget w = name_to_widget (toplevel, names[i]);
1456       const char *name = XtName(w);
1457       XmString xm = 0;
1458       char *label = 0;
1459       XtVaGetValues (w, XmNlabelString, &xm, 0);
1460       if (xm) XmStringGetLtoR (xm, XmSTRING_DEFAULT_CHARSET, &label);
1461       if (w && (!label || !strcmp (name, label)))
1462         {
1463           xm = XmStringCreate ("ERROR", XmSTRING_DEFAULT_CHARSET);
1464           XtVaSetValues (w, XmNlabelString, xm, 0);
1465         }
1466     }
1467 }
1468
1469 /* Set certain buttons to be the same size (the max of the set.)
1470  */
1471 static void
1472 hack_button_sizes (Widget toplevel)
1473 {
1474   Widget demo = name_to_widget (toplevel, "demo");
1475   Widget man  = name_to_widget (toplevel, "man");
1476   Widget ok   = name_to_widget (toplevel, "OK");
1477   Widget can  = name_to_widget (toplevel, "Cancel");
1478   Widget up   = name_to_widget (toplevel, "up");
1479   Widget down = name_to_widget (toplevel, "down");
1480   Dimension w1, w2;
1481
1482   XtVaGetValues (demo, XmNwidth, &w1, 0);
1483   XtVaGetValues (man,  XmNwidth, &w2, 0);
1484   XtVaSetValues ((w1 > w2 ? man : demo), XmNwidth, (w1 > w2 ? w1 : w2), 0);
1485
1486   XtVaGetValues (ok,   XmNwidth, &w1, 0);
1487   XtVaGetValues (can,  XmNwidth, &w2, 0);
1488   XtVaSetValues ((w1 > w2 ? can : ok), XmNwidth, (w1 > w2 ? w1 : w2), 0);
1489
1490   XtVaGetValues (up,   XmNwidth, &w1, 0);
1491   XtVaGetValues (down, XmNwidth, &w2, 0);
1492   XtVaSetValues ((w1 > w2 ? down : up), XmNwidth, (w1 > w2 ? w1 : w2), 0);
1493 }
1494
1495
1496
1497 \f
1498 /* The main demo-mode command loop.
1499  */
1500
1501 #if 0
1502 static Bool
1503 mapper (XrmDatabase *db, XrmBindingList bindings, XrmQuarkList quarks,
1504         XrmRepresentation *type, XrmValue *value, XPointer closure)
1505 {
1506   int i;
1507   for (i = 0; quarks[i]; i++)
1508     {
1509       if (bindings[i] == XrmBindTightly)
1510         fprintf (stderr, (i == 0 ? "" : "."));
1511       else if (bindings[i] == XrmBindLoosely)
1512         fprintf (stderr, "*");
1513       else
1514         fprintf (stderr, " ??? ");
1515       fprintf(stderr, "%s", XrmQuarkToString (quarks[i]));
1516     }
1517
1518   fprintf (stderr, ": %s\n", (char *) value->addr);
1519
1520   return False;
1521 }
1522 #endif
1523
1524
1525 static void
1526 the_network_is_not_the_computer (Widget parent)
1527 {
1528   Display *dpy = XtDisplay (parent);
1529   char *rversion, *ruser, *rhost;
1530   char *luser, *lhost;
1531   char *msg = 0;
1532   struct passwd *p = getpwuid (getuid ());
1533   const char *d = DisplayString (dpy);
1534
1535 # if defined(HAVE_UNAME)
1536   struct utsname uts;
1537   if (uname (&uts) < 0)
1538     lhost = "<UNKNOWN>";
1539   else
1540     lhost = uts.nodename;
1541 # elif defined(VMS)
1542   strcpy (lhost, getenv("SYS$NODE"));
1543 # else  /* !HAVE_UNAME && !VMS */
1544   strcat (lhost, "<UNKNOWN>");
1545 # endif /* !HAVE_UNAME && !VMS */
1546
1547   if (p && p->pw_name)
1548     luser = p->pw_name;
1549   else
1550     luser = "???";
1551
1552   server_xscreensaver_version (dpy, &rversion, &ruser, &rhost);
1553
1554   /* Make a buffer that's big enough for a number of copies of all the
1555      strings, plus some. */
1556   msg = (char *) malloc (10 * ((rversion ? strlen(rversion) : 0) +
1557                                (ruser ? strlen(ruser) : 0) +
1558                                (rhost ? strlen(rhost) : 0) +
1559                                strlen(lhost) +
1560                                strlen(luser) +
1561                                strlen(d) +
1562                                1024));
1563   *msg = 0;
1564
1565   if (!rversion || !*rversion)
1566     {
1567       sprintf (msg,
1568                "Warning:\n\n"
1569                "The XScreenSaver daemon doesn't seem to be running\n"
1570                "on display \"%s\".  You can launch it by selecting\n"
1571                "`Restart Daemon' from the File menu, or by typing\n"
1572                "\"xscreensaver &\" in a shell.",
1573                d);
1574     }
1575   else if (p && ruser && *ruser && !!strcmp (ruser, p->pw_name))
1576     {
1577       /* Warn that the two processes are running as different users.
1578        */
1579       sprintf(msg,
1580                "Warning:\n\n"
1581               "%s is running as user \"%s\" on host \"%s\".\n"
1582               "But the xscreensaver managing display \"%s\"\n"
1583               "is running as user \"%s\" on host \"%s\".\n"
1584               "\n"
1585               "Since they are different users, they won't be reading/writing\n"
1586               "the same ~/.xscreensaver file, so %s isn't\n"
1587               "going to work right.\n"
1588               "\n"
1589               "Either re-run %s as \"%s\", or re-run\n"
1590               "xscreensaver as \"%s\" (which you can do by\n"
1591               "selecting `Restart Daemon' from the File menu.)\n",
1592               progname, luser, lhost,
1593               d,
1594               (ruser ? ruser : "???"), (rhost ? rhost : "???"),
1595               progname,
1596               progname, (ruser ? ruser : "???"),
1597               luser);
1598     }
1599   else if (rhost && *rhost && !!strcmp (rhost, lhost))
1600     {
1601       /* Warn that the two processes are running on different hosts.
1602        */
1603       sprintf (msg,
1604                "Warning:\n\n"
1605                "%s is running as user \"%s\" on host \"%s\".\n"
1606                "But the xscreensaver managing display \"%s\"\n"
1607                "is running as user \"%s\" on host \"%s\".\n"
1608                "\n"
1609                "If those two machines don't share a file system (that is,\n"
1610                "if they don't see the same ~%s/.xscreensaver file) then\n"
1611                "%s won't work right.\n"
1612                "\n"
1613                "You can restart the daemon on \"%s\" as \"%s\" by\n"
1614                "selecting `Restart Daemon' from the File menu.)",
1615                progname, luser, lhost,
1616                d,
1617                (ruser ? ruser : "???"), (rhost ? rhost : "???"),
1618                luser,
1619                progname,
1620                lhost, luser);
1621     }
1622   else if (!!strcmp (rversion, short_version))
1623     {
1624       /* Warn that the version numbers don't match.
1625        */
1626       sprintf (msg,
1627                "Warning:\n\n"
1628                "This is %s version %s.\n"
1629                "But the xscreensaver managing display \"%s\"\n"
1630                "is version %s.  This could cause problems.",
1631                progname, short_version,
1632                d,
1633                rversion);
1634     }
1635
1636
1637   if (*msg)
1638     warning_dialog (parent, msg, 1);
1639
1640   free (msg);
1641 }
1642
1643
1644 /* We use this error handler so that X errors are preceeded by the name
1645    of the program that generated them.
1646  */
1647 static int
1648 demo_ehandler (Display *dpy, XErrorEvent *error)
1649 {
1650   fprintf (stderr, "\nX error in %s:\n", progname);
1651   if (XmuPrintDefaultErrorMessage (dpy, error, stderr))
1652     exit (-1);
1653   else
1654     fprintf (stderr, " (nonfatal.)\n");
1655   return 0;
1656 }
1657
1658
1659
1660 static char *defaults[] = {
1661 #include "XScreenSaver_ad.h"
1662  0
1663 };
1664
1665
1666 int
1667 main (int argc, char **argv)
1668 {
1669   XtAppContext app;
1670   prefs_pair Pair, *pair;
1671   saver_preferences P, P2, *p, *p2;
1672   Bool prefs = False;
1673   int i;
1674   Display *dpy;
1675   Widget toplevel_shell, dialog;
1676   char *real_progname = argv[0];
1677   char *s;
1678
1679   s = strrchr (real_progname, '/');
1680   if (s) real_progname = s+1;
1681
1682   p = &P;
1683   p2 = &P2;
1684   pair = &Pair;
1685   pair->a = p;
1686   pair->b = p2;
1687   memset (p,  0, sizeof (*p));
1688   memset (p2, 0, sizeof (*p2));
1689
1690   global_prefs_pair = pair;
1691
1692   progname = real_progname;
1693
1694   /* We must read exactly the same resources as xscreensaver.
1695      That means we must have both the same progclass *and* progname,
1696      at least as far as the resource database is concerned.  So,
1697      put "xscreensaver" in argv[0] while initializing Xt.
1698    */
1699   argv[0] = "xscreensaver";
1700   progname = argv[0];
1701
1702
1703   toplevel_shell = XtAppInitialize (&app, progclass, 0, 0, &argc, argv,
1704                                     defaults, 0, 0);
1705
1706   dpy = XtDisplay (toplevel_shell);
1707   db = XtDatabase (dpy);
1708   XtGetApplicationNameAndClass (dpy, &progname, &progclass);
1709   XSetErrorHandler (demo_ehandler);
1710
1711   /* Complain about unrecognized command-line arguments.
1712    */
1713   for (i = 1; i < argc; i++)
1714     {
1715       char *s = argv[i];
1716       if (s[0] == '-' && s[1] == '-')
1717         s++;
1718       if (!strcmp (s, "-prefs"))
1719         prefs = True;
1720       else
1721         {
1722           fprintf (stderr, "usage: %s [ -display dpy-string ] [ -prefs ]\n",
1723                    real_progname);
1724           exit (1);
1725         }
1726     }
1727
1728   short_version = (char *) malloc (5);
1729   memcpy (short_version, screensaver_id + 17, 4);
1730   short_version [4] = 0;
1731
1732   /* Load the init file, which may end up consulting the X resource database
1733      and the site-wide app-defaults file.  Note that at this point, it's
1734      important that `progname' be "xscreensaver", rather than whatever
1735      was in argv[0].
1736    */
1737   p->db = db;
1738   load_init_file (p);
1739   *p2 = *p;
1740
1741   /* Now that Xt has been initialized, and the resources have been read,
1742      we can set our `progname' variable to something more in line with
1743      reality.
1744    */
1745   progname = real_progname;
1746
1747
1748 #if 0
1749   {
1750     XrmName name = { 0 };
1751     XrmClass class = { 0 };
1752     int count = 0;
1753     XrmEnumerateDatabase (db, &name, &class, XrmEnumAllLevels, mapper,
1754                           (POINTER) &count);
1755   }
1756 #endif
1757
1758
1759   /* Intern the atoms that xscreensaver_command() needs.
1760    */
1761   XA_VROOT = XInternAtom (dpy, "__SWM_VROOT", False);
1762   XA_SCREENSAVER = XInternAtom (dpy, "SCREENSAVER", False);
1763   XA_SCREENSAVER_VERSION = XInternAtom (dpy, "_SCREENSAVER_VERSION",False);
1764   XA_SCREENSAVER_STATUS = XInternAtom (dpy, "_SCREENSAVER_STATUS", False);
1765   XA_SCREENSAVER_ID = XInternAtom (dpy, "_SCREENSAVER_ID", False);
1766   XA_SCREENSAVER_RESPONSE = XInternAtom (dpy, "_SCREENSAVER_RESPONSE", False);
1767   XA_SELECT = XInternAtom (dpy, "SELECT", False);
1768   XA_DEMO = XInternAtom (dpy, "DEMO", False);
1769   XA_ACTIVATE = XInternAtom (dpy, "ACTIVATE", False);
1770   XA_BLANK = XInternAtom (dpy, "BLANK", False);
1771   XA_LOCK = XInternAtom (dpy, "LOCK", False);
1772   XA_EXIT = XInternAtom (dpy, "EXIT", False);
1773   XA_RESTART = XInternAtom (dpy, "RESTART", False);
1774
1775   /* Create the window and all its widgets.
1776    */
1777   dialog = create_xscreensaver_demo (toplevel_shell);
1778
1779   /* Set the window's title. */
1780   {
1781     char title[255];
1782     char *v = (char *) strdup(strchr(screensaver_id, ' '));
1783     char *s1, *s2, *s3, *s4;
1784     s1 = (char *) strchr(v,  ' '); s1++;
1785     s2 = (char *) strchr(s1, ' ');
1786     s3 = (char *) strchr(v,  '('); s3++;
1787     s4 = (char *) strchr(s3, ')');
1788     *s2 = 0;
1789     *s4 = 0;
1790     sprintf (title, "%.50s %.50s, %.50s", progclass, s1, s3);
1791     XtVaSetValues (toplevel_shell, XtNtitle, title, 0);
1792     free (v);
1793   }
1794
1795   sanity_check_resources (toplevel_shell);
1796   add_callbacks (toplevel_shell, pair);
1797   populate_hack_list (toplevel_shell, pair);
1798   populate_prefs_page (toplevel_shell, pair);
1799   sensitize_demo_widgets (toplevel_shell, False);
1800   scroll_to_current_hack (toplevel_shell, pair);
1801
1802   XtManageChild (dialog);
1803   XtRealizeWidget(toplevel_shell);
1804
1805   /* The next few calls must come after XtRealizeWidget(). */
1806   pixmapify_buttons (toplevel_shell);
1807   hack_button_sizes (toplevel_shell);
1808   ensure_selected_item_visible (name_to_widget (toplevel_shell, "list"));
1809
1810   XSync (dpy, False);
1811   XtVaSetValues (toplevel_shell, XmNallowShellResize, False, 0);
1812
1813
1814   /* Handle the -prefs command-line argument. */
1815   if (prefs)
1816     {
1817       Widget tabber = name_to_widget (toplevel_shell, "folder");
1818       Widget this_tab = name_to_widget (toplevel_shell, "optionsTab");
1819       Widget this_page = name_to_widget (toplevel_shell, "preferencesForm");
1820       Widget *kids = 0;
1821       Cardinal nkids = 0;
1822       if (!tabber) abort();
1823   
1824       XtVaGetValues (tabber, XmNnumChildren, &nkids, XmNchildren, &kids, 0);
1825       if (!kids) abort();
1826       if (nkids > 0)
1827         XtUnmanageChildren (kids, nkids);
1828
1829       XtManageChild (this_page);
1830
1831       XmProcessTraversal (this_tab, XmTRAVERSE_CURRENT);
1832     }
1833
1834   /* Issue any warnings about the running xscreensaver daemon. */
1835   the_network_is_not_the_computer (toplevel_shell);
1836
1837
1838   XtAppMainLoop (app);
1839   exit (0);
1840 }
1841
1842 #endif /* HAVE_MOTIF -- whole file */