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