http://www.jwz.org/xscreensaver/xscreensaver-5.09.tar.gz
[xscreensaver] / driver / timers.c
1 /* timers.c --- detecting when the user is idle, and other timer-related tasks.
2  * xscreensaver, Copyright (c) 1991-2008 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 #include <stdio.h>
18 #include <X11/Xlib.h>
19 #include <X11/Intrinsic.h>
20 #include <X11/Xos.h>
21 #include <time.h>
22 #include <sys/time.h>
23 #ifdef HAVE_XMU
24 # ifndef VMS
25 #  include <X11/Xmu/Error.h>
26 # else /* VMS */
27 #  include <Xmu/Error.h>
28 # endif /* VMS */
29 # else /* !HAVE_XMU */
30 # include "xmu.h"
31 #endif /* !HAVE_XMU */
32
33 #ifdef HAVE_XIDLE_EXTENSION
34 #include <X11/extensions/xidle.h>
35 #endif /* HAVE_XIDLE_EXTENSION */
36
37 #ifdef HAVE_MIT_SAVER_EXTENSION
38 #include <X11/extensions/scrnsaver.h>
39 #endif /* HAVE_MIT_SAVER_EXTENSION */
40
41 #ifdef HAVE_SGI_SAVER_EXTENSION
42 #include <X11/extensions/XScreenSaver.h>
43 #endif /* HAVE_SGI_SAVER_EXTENSION */
44
45 #ifdef HAVE_RANDR
46 #include <X11/extensions/Xrandr.h>
47 #endif /* HAVE_RANDR */
48
49 #include "xscreensaver.h"
50
51 #undef ABS
52 #define ABS(x)((x)<0?-(x):(x))
53
54 #undef MAX
55 #define MAX(x,y)((x)>(y)?(x):(y))
56
57
58 #ifdef HAVE_PROC_INTERRUPTS
59 static Bool proc_interrupts_activity_p (saver_info *si);
60 #endif /* HAVE_PROC_INTERRUPTS */
61
62 static void check_for_clock_skew (saver_info *si);
63
64
65 void
66 idle_timer (XtPointer closure, XtIntervalId *id)
67 {
68   saver_info *si = (saver_info *) closure;
69
70   /* What an amazingly shitty design.  Not only does Xt execute timeout
71      events from XtAppNextEvent() instead of from XtDispatchEvent(), but
72      there is no way to tell Xt to block until there is an X event OR a
73      timeout happens.  Once your timeout proc is called, XtAppNextEvent()
74      still won't return until a "real" X event comes in.
75
76      So this function pushes a stupid, gratuitous, unnecessary event back
77      on the event queue to force XtAppNextEvent to return Right Fucking Now.
78      When the code in sleep_until_idle() sees an event of type XAnyEvent,
79      which the server never generates, it knows that a timeout has occurred.
80    */
81   XEvent fake_event;
82   fake_event.type = 0;  /* XAnyEvent type, ignored. */
83   fake_event.xany.display = si->dpy;
84   fake_event.xany.window  = 0;
85   XPutBackEvent (si->dpy, &fake_event);
86
87   /* If we are the timer that just went off, clear the pointer to the id. */
88   if (id)
89     {
90       if (si->timer_id && *id != si->timer_id)
91         abort();  /* oops, scheduled timer twice?? */
92       si->timer_id = 0;
93     }
94 }
95
96
97 void
98 schedule_wakeup_event (saver_info *si, Time when, Bool verbose_p)
99 {
100   if (si->timer_id)
101     {
102       if (verbose_p)
103         fprintf (stderr, "%s: idle_timer already running\n", blurb());
104       return;
105     }
106
107   /* Wake up periodically to ask the server if we are idle. */
108   si->timer_id = XtAppAddTimeOut (si->app, when, idle_timer,
109                                   (XtPointer) si);
110
111   if (verbose_p)
112     fprintf (stderr, "%s: starting idle_timer (%ld, %ld)\n",
113              blurb(), when, si->timer_id);
114 }
115
116
117 static void
118 notice_events (saver_info *si, Window window, Bool top_p)
119 {
120   saver_preferences *p = &si->prefs;
121   XWindowAttributes attrs;
122   unsigned long events;
123   Window root, parent, *kids;
124   unsigned int nkids;
125   int screen_no;
126
127   if (XtWindowToWidget (si->dpy, window))
128     /* If it's one of ours, don't mess up its event mask. */
129     return;
130
131   if (!XQueryTree (si->dpy, window, &root, &parent, &kids, &nkids))
132     return;
133   if (window == root)
134     top_p = False;
135
136   /* Figure out which screen this window is on, for the diagnostics. */
137   for (screen_no = 0; screen_no < si->nscreens; screen_no++)
138     if (root == RootWindowOfScreen (si->screens[screen_no].screen))
139       break;
140
141   XGetWindowAttributes (si->dpy, window, &attrs);
142   events = ((attrs.all_event_masks | attrs.do_not_propagate_mask)
143             & KeyPressMask);
144
145   /* Select for SubstructureNotify on all windows.
146      Select for KeyPress on all windows that already have it selected.
147
148      Note that we can't select for ButtonPress, because of X braindamage:
149      only one client at a time may select for ButtonPress on a given
150      window, though any number can select for KeyPress.  Someone explain
151      *that* to me.
152
153      So, if the user spends a while clicking the mouse without ever moving
154      the mouse or touching the keyboard, we won't know that they've been
155      active, and the screensaver will come on.  That sucks, but I don't
156      know how to get around it.
157
158      Since X presents mouse wheels as clicks, this applies to those, too:
159      scrolling through a document using only the mouse wheel doesn't
160      count as activity...  Fortunately, /proc/interrupts helps, on
161      systems that have it.  Oh, if it's a PS/2 mouse, not serial or USB.
162      This sucks!
163    */
164   XSelectInput (si->dpy, window, SubstructureNotifyMask | events);
165
166   if (top_p && p->debug_p && (events & KeyPressMask))
167     {
168       /* Only mention one window per tree (hack hack). */
169       fprintf (stderr, "%s: %d: selected KeyPress on 0x%lX\n",
170                blurb(), screen_no, (unsigned long) window);
171       top_p = False;
172     }
173
174   if (kids)
175     {
176       while (nkids)
177         notice_events (si, kids [--nkids], top_p);
178       XFree ((char *) kids);
179     }
180 }
181
182
183 int
184 BadWindow_ehandler (Display *dpy, XErrorEvent *error)
185 {
186   /* When we notice a window being created, we spawn a timer that waits
187      30 seconds or so, and then selects events on that window.  This error
188      handler is used so that we can cope with the fact that the window
189      may have been destroyed <30 seconds after it was created.
190    */
191   if (error->error_code == BadWindow ||
192       error->error_code == BadMatch ||
193       error->error_code == BadDrawable)
194     return 0;
195   else
196     return saver_ehandler (dpy, error);
197 }
198
199
200 struct notice_events_timer_arg {
201   saver_info *si;
202   Window w;
203 };
204
205 static void
206 notice_events_timer (XtPointer closure, XtIntervalId *id)
207 {
208   struct notice_events_timer_arg *arg =
209     (struct notice_events_timer_arg *) closure;
210
211   XErrorHandler old_handler = XSetErrorHandler (BadWindow_ehandler);
212
213   saver_info *si = arg->si;
214   Window window = arg->w;
215
216   free(arg);
217   notice_events (si, window, True);
218   XSync (si->dpy, False);
219   XSetErrorHandler (old_handler);
220 }
221
222 void
223 start_notice_events_timer (saver_info *si, Window w, Bool verbose_p)
224 {
225   saver_preferences *p = &si->prefs;
226   struct notice_events_timer_arg *arg =
227     (struct notice_events_timer_arg *) malloc(sizeof(*arg));
228   arg->si = si;
229   arg->w = w;
230   XtAppAddTimeOut (si->app, p->notice_events_timeout, notice_events_timer,
231                    (XtPointer) arg);
232
233   if (verbose_p)
234     fprintf (stderr, "%s: starting notice_events_timer for 0x%X (%lu)\n",
235              blurb(), (unsigned int) w, p->notice_events_timeout);
236 }
237
238
239 /* When the screensaver is active, this timer will periodically change
240    the running program.
241  */
242 void
243 cycle_timer (XtPointer closure, XtIntervalId *id)
244 {
245   saver_info *si = (saver_info *) closure;
246   saver_preferences *p = &si->prefs;
247   Time how_long = p->cycle;
248
249   if (si->selection_mode > 0 &&
250       screenhack_running_p (si))
251     /* If we're in "SELECT n" mode, the cycle timer going off will just
252        restart this same hack again.  There's not much point in doing this
253        every 5 or 10 minutes, but on the other hand, leaving one hack running
254        for days is probably not a great idea, since they tend to leak and/or
255        crash.  So, restart the thing once an hour. */
256     how_long = 1000 * 60 * 60;
257
258   if (si->dbox_up_p)
259     {
260       if (p->verbose_p)
261         fprintf (stderr, "%s: dialog box up; delaying hack change.\n",
262                  blurb());
263       how_long = 30000; /* 30 secs */
264     }
265   else
266     {
267       int i;
268       maybe_reload_init_file (si);
269       for (i = 0; i < si->nscreens; i++)
270         kill_screenhack (&si->screens[i]);
271
272       raise_window (si, True, True, False);
273
274       if (!si->throttled_p)
275         for (i = 0; i < si->nscreens; i++)
276           spawn_screenhack (&si->screens[i]);
277       else
278         {
279           if (p->verbose_p)
280             fprintf (stderr, "%s: not launching new hack (throttled.)\n",
281                      blurb());
282         }
283     }
284
285   if (how_long > 0)
286     {
287       si->cycle_id = XtAppAddTimeOut (si->app, how_long, cycle_timer,
288                                       (XtPointer) si);
289
290       if (p->debug_p)
291         fprintf (stderr, "%s: starting cycle_timer (%ld, %ld)\n",
292                  blurb(), how_long, si->cycle_id);
293     }
294   else
295     {
296       if (p->debug_p)
297         fprintf (stderr, "%s: not starting cycle_timer: how_long == %ld\n",
298                  blurb(), (unsigned long) how_long);
299     }
300 }
301
302
303 void
304 activate_lock_timer (XtPointer closure, XtIntervalId *id)
305 {
306   saver_info *si = (saver_info *) closure;
307   saver_preferences *p = &si->prefs;
308
309   if (p->verbose_p)
310     fprintf (stderr, "%s: timed out; activating lock.\n", blurb());
311   set_locked_p (si, True);
312 }
313
314
315 /* Call this when user activity (or "simulated" activity) has been noticed.
316  */
317 void
318 reset_timers (saver_info *si)
319 {
320   saver_preferences *p = &si->prefs;
321   if (si->using_mit_saver_extension || si->using_sgi_saver_extension)
322     return;
323
324   if (si->timer_id)
325     {
326       if (p->debug_p)
327         fprintf (stderr, "%s: killing idle_timer  (%ld, %ld)\n",
328                  blurb(), p->timeout, si->timer_id);
329       XtRemoveTimeOut (si->timer_id);
330       si->timer_id = 0;
331     }
332
333   schedule_wakeup_event (si, p->timeout, p->debug_p); /* sets si->timer_id */
334
335   if (si->cycle_id) abort ();   /* no cycle timer when inactive */
336
337   si->last_activity_time = time ((time_t *) 0);
338
339   /* This will (hopefully, supposedly) tell the server to re-set its
340      DPMS timer.  Without this, the -deactivate clientmessage would
341      prevent xscreensaver from blanking, but would not prevent the
342      monitor from powering down. */
343 #if 0
344   /* #### With some servers, this causes the screen to flicker every
345      time a key is pressed!  Ok, I surrender.  I give up on ever
346      having DPMS work properly.
347    */
348   XForceScreenSaver (si->dpy, ScreenSaverReset);
349
350   /* And if the monitor is already powered off, turn it on.
351      You'd think the above would do that, but apparently not? */
352   monitor_power_on (si);
353 #endif
354
355 }
356
357
358 /* Returns true if the mouse has moved since the last time we checked.
359    Small motions (of less than "hysteresis" pixels/second) are ignored.
360  */
361 static Bool
362 pointer_moved_p (saver_screen_info *ssi, Bool mods_p)
363 {
364   saver_info *si = ssi->global;
365   saver_preferences *p = &si->prefs;
366
367   Window root, child;
368   int root_x, root_y, x, y;
369   unsigned int mask;
370   time_t now = time ((time_t *) 0);
371   unsigned int distance, dps;
372   unsigned long seconds = 0;
373   Bool moved_p = False;
374
375   /* don't check xinerama pseudo-screens. */
376   if (!ssi->real_screen_p) return False;
377
378   if (!XQueryPointer (si->dpy, ssi->screensaver_window, &root, &child,
379                       &root_x, &root_y, &x, &y, &mask))
380     {
381       /* If XQueryPointer() returns false, the mouse is not on this screen.
382        */
383       x = root_x = -1;
384       y = root_y = -1;
385       root = child = 0;
386       mask = 0;
387     }
388
389   distance = MAX (ABS (ssi->poll_mouse_last_root_x - root_x),
390                   ABS (ssi->poll_mouse_last_root_y - root_y));
391   seconds = (now - ssi->poll_mouse_last_time);
392
393
394   /* When the screen is blanked, we get MotionNotify events, but when not
395      blanked, we poll only every 5 seconds, and that's not enough resolution
396      to do hysteresis based on a 1 second interval.  So, assume that any
397      motion we've seen during the 5 seconds when our eyes were closed happened
398      in the last 1 second instead.
399    */
400   if (seconds > 1) seconds = 1;
401
402   dps = (seconds <= 0 ? distance : (distance / seconds));
403
404   /* Motion only counts if the rate is more than N pixels per second.
405    */
406   if (dps >= p->pointer_hysteresis &&
407       distance > 0)
408     moved_p = True;
409
410   /* If the mouse is not on this screen but used to be, that's motion.
411      If the mouse was not on this screen, but is now, that's motion.
412    */
413   {
414     Bool on_screen_p  = (root_x != -1 && root_y != -1);
415     Bool was_on_screen_p = (ssi->poll_mouse_last_root_x != -1 &&
416                             ssi->poll_mouse_last_root_y != -1);
417
418     if (on_screen_p != was_on_screen_p)
419       moved_p = True;
420   }
421
422   if (p->debug_p && (distance != 0 || moved_p))
423     {
424       fprintf (stderr, "%s: %d: pointer %s", blurb(), ssi->number,
425                (moved_p ? "moved:  " : "ignored:"));
426       if (ssi->poll_mouse_last_root_x == -1)
427         fprintf (stderr, "off screen");
428       else
429         fprintf (stderr, "%d,%d",
430                  ssi->poll_mouse_last_root_x,
431                  ssi->poll_mouse_last_root_y);
432       fprintf (stderr, " -> ");
433       if (root_x == -1)
434         fprintf (stderr, "off screen");
435       else
436         fprintf (stderr, "%d,%d", root_x, root_y);
437       if (ssi->poll_mouse_last_root_x != -1 && root_x != -1)
438         fprintf (stderr, " (%d,%d; %d/%lu=%d)",
439                  ABS(ssi->poll_mouse_last_root_x - root_x),
440                  ABS(ssi->poll_mouse_last_root_y - root_y),
441                  distance, seconds, dps);
442
443       fprintf (stderr, ".\n");
444     }
445
446   if (!moved_p &&
447       mods_p &&
448       mask != ssi->poll_mouse_last_mask)
449     {
450       moved_p = True;
451
452       if (p->debug_p)
453         fprintf (stderr, "%s: %d: modifiers changed: 0x%04x -> 0x%04x.\n",
454                  blurb(), ssi->number, ssi->poll_mouse_last_mask, mask);
455     }
456
457   si->last_activity_screen   = ssi;
458   ssi->poll_mouse_last_child = child;
459   ssi->poll_mouse_last_mask  = mask;
460
461   if (moved_p || seconds > 0)
462     {
463       ssi->poll_mouse_last_time   = now;
464       ssi->poll_mouse_last_root_x = root_x;
465       ssi->poll_mouse_last_root_y = root_y;
466     }
467
468   return moved_p;
469 }
470
471
472 /* When we aren't using a server extension, this timer is used to periodically
473    wake up and poll the mouse position, which is possibly more reliable than
474    selecting motion events on every window.
475  */
476 static void
477 check_pointer_timer (XtPointer closure, XtIntervalId *id)
478 {
479   int i;
480   saver_info *si = (saver_info *) closure;
481   saver_preferences *p = &si->prefs;
482   Bool active_p = False;
483
484   if (!si->using_proc_interrupts &&
485       (si->using_xidle_extension ||
486        si->using_mit_saver_extension ||
487        si->using_sgi_saver_extension))
488     /* If an extension is in use, we should not be polling the mouse.
489        Unless we're also checking /proc/interrupts, in which case, we should.
490      */
491     abort ();
492
493   if (id && *id == si->check_pointer_timer_id)  /* this is us - it's expired */
494     si->check_pointer_timer_id = 0;
495
496   if (si->check_pointer_timer_id)               /* only queue one at a time */
497     XtRemoveTimeOut (si->check_pointer_timer_id);
498
499   si->check_pointer_timer_id =                  /* now re-queue */
500     XtAppAddTimeOut (si->app, p->pointer_timeout, check_pointer_timer,
501                      (XtPointer) si);
502
503   for (i = 0; i < si->nscreens; i++)
504     {
505       saver_screen_info *ssi = &si->screens[i];
506       if (pointer_moved_p (ssi, True))
507         active_p = True;
508     }
509
510 #ifdef HAVE_PROC_INTERRUPTS
511   if (!active_p &&
512       si->using_proc_interrupts &&
513       proc_interrupts_activity_p (si))
514     {
515       active_p = True;
516     }
517 #endif /* HAVE_PROC_INTERRUPTS */
518
519   if (active_p)
520     reset_timers (si);
521
522   check_for_clock_skew (si);
523 }
524
525
526 /* An unfortunate situation is this: the saver is not active, because the
527    user has been typing.  The machine is a laptop.  The user closes the lid
528    and suspends it.  The CPU halts.  Some hours later, the user opens the
529    lid.  At this point, Xt's timers will fire, and xscreensaver will blank
530    the screen.
531
532    So far so good -- well, not really, but it's the best that we can do,
533    since the OS doesn't send us a signal *before* shutdown -- but if the
534    user had delayed locking (lockTimeout > 0) then we should start off
535    in the locked state, rather than only locking N minutes from when the
536    lid was opened.  Also, eschewing fading is probably a good idea, to
537    clamp down as soon as possible.
538
539    We only do this when we'd be polling the mouse position anyway.
540    This amounts to an assumption that machines with APM support also
541    have /proc/interrupts.
542  */
543 static void
544 check_for_clock_skew (saver_info *si)
545 {
546   saver_preferences *p = &si->prefs;
547   time_t now = time ((time_t *) 0);
548   long shift = now - si->last_wall_clock_time;
549
550   if (p->debug_p)
551     {
552       int i = (si->last_wall_clock_time == 0 ? 0 : shift);
553       fprintf (stderr,
554                "%s: checking wall clock for hibernation (%d:%02d:%02d).\n",
555                blurb(),
556                (i / (60 * 60)), ((i / 60) % 60), (i % 60));
557     }
558
559   if (si->last_wall_clock_time != 0 &&
560       shift > (p->timeout / 1000))
561     {
562       if (p->verbose_p)
563         fprintf (stderr, "%s: wall clock has jumped by %ld:%02ld:%02ld!\n",
564                  blurb(),
565                  (shift / (60 * 60)), ((shift / 60) % 60), (shift % 60));
566
567       si->emergency_lock_p = True;
568       idle_timer ((XtPointer) si, 0);
569     }
570
571   si->last_wall_clock_time = now;
572 }
573
574
575
576 static void
577 dispatch_event (saver_info *si, XEvent *event)
578 {
579   /* If this is for the splash dialog, pass it along.
580      Note that the password dialog is handled with its own event loop,
581      so events for that window will never come through here.
582    */
583   if (si->splash_dialog && event->xany.window == si->splash_dialog)
584     handle_splash_event (si, event);
585
586   XtDispatchEvent (event);
587 }
588
589
590 static void
591 swallow_unlock_typeahead_events (saver_info *si, XEvent *e)
592 {
593   XEvent event;
594   char buf [100];
595   int i = 0;
596
597   memset (buf, 0, sizeof(buf));
598
599   event = *e;
600
601   do
602     {
603       if (event.xany.type == KeyPress)
604         {
605           char s[2];
606           int size = XLookupString ((XKeyEvent *) &event, s, 1, 0, 0);
607           if (size != 1) continue;
608           switch (*s)
609             {
610             case '\010': case '\177':                   /* Backspace */
611               if (i > 0) i--;
612               break;
613             case '\025': case '\030':                   /* Erase line */
614             case '\012': case '\015':                   /* Enter */
615             case '\033':                                /* ESC */
616               i = 0;
617               break;
618             case '\040':                                /* Space */
619               if (i == 0)
620                 break;  /* ignore space at beginning of line */
621               /* else, fall through */
622             default:
623               buf [i++] = *s;
624               break;
625             }
626         }
627
628     } while (i < sizeof(buf)-1 &&
629              XCheckMaskEvent (si->dpy, KeyPressMask, &event));
630
631   buf[i] = 0;
632
633   if (si->unlock_typeahead)
634     {
635       memset (si->unlock_typeahead, 0, strlen(si->unlock_typeahead));
636       free (si->unlock_typeahead);
637     }
638
639   if (i > 0)
640     si->unlock_typeahead = strdup (buf);
641   else
642     si->unlock_typeahead = 0;
643
644   memset (buf, 0, sizeof(buf));
645 }
646
647
648 /* methods of detecting idleness:
649
650       explicitly informed by SGI SCREEN_SAVER server event;
651       explicitly informed by MIT-SCREEN-SAVER server event;
652       poll server idle time with XIDLE extension;
653       select events on all windows, and note absence of recent events;
654       note that /proc/interrupts has not changed in a while;
655       activated by clientmessage.
656
657    methods of detecting non-idleness:
658
659       read events on the xscreensaver window;
660       explicitly informed by SGI SCREEN_SAVER server event;
661       explicitly informed by MIT-SCREEN-SAVER server event;
662       select events on all windows, and note events on any of them;
663       note that /proc/interrupts has changed;
664       deactivated by clientmessage.
665
666    I trust that explains why this function is a big hairy mess.
667  */
668 void
669 sleep_until_idle (saver_info *si, Bool until_idle_p)
670 {
671   saver_preferences *p = &si->prefs;
672
673   /* We have to go through this union bullshit because gcc-4.4.0 has
674      stricter struct-aliasing rules.  Without this, the optimizer
675      can fuck things up.
676    */
677   union {
678     XEvent x_event;
679 # ifdef HAVE_RANDR
680     XRRScreenChangeNotifyEvent xrr_event;
681 # endif /* HAVE_RANDR */
682 # ifdef HAVE_MIT_SAVER_EXTENSION
683     XScreenSaverNotifyEvent sevent;
684 # endif /* HAVE_MIT_SAVER_EXTENSION */
685   } event;
686
687   /* We need to select events on all windows if we're not using any extensions.
688      Otherwise, we don't need to. */
689   Bool scanning_all_windows = !(si->using_xidle_extension ||
690                                 si->using_mit_saver_extension ||
691                                 si->using_sgi_saver_extension);
692
693   /* We need to periodically wake up and check for idleness if we're not using
694      any extensions, or if we're using the XIDLE extension.  The other two
695      extensions explicitly deliver events when we go idle/non-idle, so we
696      don't need to poll. */
697   Bool polling_for_idleness = !(si->using_mit_saver_extension ||
698                                 si->using_sgi_saver_extension);
699
700   /* Whether we need to periodically wake up and check to see if the mouse has
701      moved.  We only need to do this when not using any extensions.  The reason
702      this isn't the same as `polling_for_idleness' is that the "idleness" poll
703      can happen (for example) 5 minutes from now, whereas the mouse-position
704      poll should happen with low periodicity.  We don't need to poll the mouse
705      position with the XIDLE extension, but we do need to periodically wake up
706      and query the server with that extension.  For our purposes, polling
707      /proc/interrupts is just like polling the mouse position.  It has to
708      happen on the same kind of schedule. */
709   Bool polling_mouse_position = (si->using_proc_interrupts ||
710                                  !(si->using_xidle_extension ||
711                                    si->using_mit_saver_extension ||
712                                    si->using_sgi_saver_extension));
713
714   if (until_idle_p)
715     {
716       if (polling_for_idleness)
717         /* This causes a no-op event to be delivered to us in a while, so that
718            we come back around through the event loop again.  */
719         schedule_wakeup_event (si, p->timeout, p->debug_p);
720
721       if (polling_mouse_position)
722         /* Check to see if the mouse has moved, and set up a repeating timer
723            to do so periodically (typically, every 5 seconds.) */
724         check_pointer_timer ((XtPointer) si, 0);
725     }
726
727   while (1)
728     {
729       XtAppNextEvent (si->app, &event.x_event);
730
731       switch (event.x_event.xany.type) {
732       case 0:           /* our synthetic "timeout" event has been signalled */
733         if (until_idle_p)
734           {
735             Time idle;
736
737             /* We may be idle; check one last time to see if the mouse has
738                moved, just in case the idle-timer went off within the 5 second
739                window between mouse polling.  If the mouse has moved, then
740                check_pointer_timer() will reset last_activity_time.
741              */
742             if (polling_mouse_position)
743               check_pointer_timer ((XtPointer) si, 0);
744
745 #ifdef HAVE_XIDLE_EXTENSION
746             if (si->using_xidle_extension)
747               {
748                 /* The XIDLE extension uses the synthetic event to prod us into
749                    re-asking the server how long the user has been idle. */
750                 if (! XGetIdleTime (si->dpy, &idle))
751                   {
752                     fprintf (stderr, "%s: XGetIdleTime() failed.\n", blurb());
753                     saver_exit (si, 1, 0);
754                   }
755               }
756             else
757 #endif /* HAVE_XIDLE_EXTENSION */
758 #ifdef HAVE_MIT_SAVER_EXTENSION
759               if (si->using_mit_saver_extension)
760                 {
761                   /* We don't need to do anything in this case - the synthetic
762                      event isn't necessary, as we get sent specific events
763                      to wake us up.  In fact, this event generally shouldn't
764                      be being delivered when the MIT extension is in use. */
765                   idle = 0;
766                 }
767             else
768 #endif /* HAVE_MIT_SAVER_EXTENSION */
769 #ifdef HAVE_SGI_SAVER_EXTENSION
770               if (si->using_sgi_saver_extension)
771                 {
772                   /* We don't need to do anything in this case - the synthetic
773                      event isn't necessary, as we get sent specific events
774                      to wake us up.  In fact, this event generally shouldn't
775                      be being delivered when the SGI extension is in use. */
776                   idle = 0;
777                 }
778             else
779 #endif /* HAVE_SGI_SAVER_EXTENSION */
780               {
781                 /* Otherwise, no server extension is in use.  The synthetic
782                    event was to tell us to wake up and see if the user is now
783                    idle.  Compute the amount of idle time by comparing the
784                    `last_activity_time' to the wall clock.  The l_a_t was set
785                    by calling `reset_timers()', which is called only in only
786                    two situations: when polling the mouse position has revealed
787                    the the mouse has moved (user activity) or when we have read
788                    an event (again, user activity.)
789                  */
790                 idle = 1000 * (si->last_activity_time - time ((time_t *) 0));
791               }
792
793             if (idle >= p->timeout)
794               {
795                 /* Look, we've been idle long enough.  We're done. */
796                 goto DONE;
797               }
798             else if (si->emergency_lock_p)
799               {
800                 /* Oops, the wall clock has jumped far into the future, so
801                    we need to lock down in a hurry! */
802                 goto DONE;
803               }
804             else
805               {
806                 /* The event went off, but it turns out that the user has not
807                    yet been idle for long enough.  So re-signal the event.
808                    Be economical: if we should blank after 5 minutes, and the
809                    user has been idle for 2 minutes, then set this timer to
810                    go off in 3 minutes.
811                  */
812                 if (polling_for_idleness)
813                   schedule_wakeup_event (si, p->timeout - idle, p->debug_p);
814               }
815           }
816         break;
817
818       case ClientMessage:
819         if (handle_clientmessage (si, &event.x_event, until_idle_p))
820           goto DONE;
821         break;
822
823       case CreateNotify:
824         /* A window has been created on the screen somewhere.  If we're
825            supposed to scan all windows for events, prepare this window. */
826         if (scanning_all_windows)
827           {
828             Window w = event.x_event.xcreatewindow.window;
829             start_notice_events_timer (si, w, p->debug_p);
830           }
831         break;
832
833       case KeyPress:
834       case ButtonPress:
835       /* Ignore release events so that hitting ESC at the password dialog
836          doesn't result in the password dialog coming right back again when
837          the fucking release key is seen! */
838       /* case KeyRelease:*/
839       /* case ButtonRelease:*/
840       case MotionNotify:
841
842         if (p->debug_p)
843           {
844             Window root=0, window=0;
845             int x=-1, y=-1;
846             const char *type = 0;
847             if (event.x_event.xany.type == MotionNotify)
848               {
849                 /*type = "MotionNotify";*/
850                 root = event.x_event.xmotion.root;
851                 window = event.x_event.xmotion.window;
852                 x = event.x_event.xmotion.x_root;
853                 y = event.x_event.xmotion.y_root;
854               }
855             else if (event.x_event.xany.type == KeyPress)
856               {
857                 type = "KeyPress";
858                 root = event.x_event.xkey.root;
859                 window = event.x_event.xkey.window;
860                 x = y = -1;
861               }
862             else if (event.x_event.xany.type == ButtonPress)
863               {
864                 type = "ButtonPress";
865                 root = event.x_event.xkey.root;
866                 window = event.x_event.xkey.window;
867                 x = event.x_event.xmotion.x_root;
868                 y = event.x_event.xmotion.y_root;
869               }
870
871             if (type)
872               {
873                 int i;
874                 for (i = 0; i < si->nscreens; i++)
875                   if (root == RootWindowOfScreen (si->screens[i].screen))
876                     break;
877                 fprintf (stderr,"%s: %d: %s on 0x%lx",
878                          blurb(), i, type, (unsigned long) window);
879
880                 /* Be careful never to do this unless in -debug mode, as
881                    this could expose characters from the unlock password. */
882                 if (p->debug_p && event.x_event.xany.type == KeyPress)
883                   {
884                     KeySym keysym;
885                     char c = 0;
886                     XLookupString (&event.x_event.xkey, &c, 1, &keysym, 0);
887                     fprintf (stderr, " (%s%s)",
888                              (event.x_event.xkey.send_event ? "synthetic " : ""),
889                              XKeysymToString (keysym));
890                   }
891
892                 if (x == -1)
893                   fprintf (stderr, "\n");
894                 else
895                   fprintf (stderr, " at %d,%d.\n", x, y);
896               }
897           }
898
899         /* If any widgets want to handle this event, let them. */
900         dispatch_event (si, &event.x_event);
901
902         
903         /* If we got a MotionNotify event, figure out what screen it
904            was on and poll the mouse there: if the mouse hasn't moved
905            far enough to count as "real" motion, then ignore this
906            event.
907          */
908         if (event.x_event.xany.type == MotionNotify)
909           {
910             int i;
911             for (i = 0; i < si->nscreens; i++)
912               if (event.x_event.xmotion.root ==
913                   RootWindowOfScreen (si->screens[i].screen))
914                 break;
915             if (i < si->nscreens)
916               {
917                 if (!pointer_moved_p (&si->screens[i], False))
918                   continue;
919               }
920           }
921
922
923         /* We got a user event.
924            If we're waiting for the user to become active, this is it.
925            If we're waiting until the user becomes idle, reset the timers
926            (since now we have longer to wait.)
927          */
928         if (!until_idle_p)
929           {
930             if (si->demoing_p &&
931                 (event.x_event.xany.type == MotionNotify ||
932                  event.x_event.xany.type == KeyRelease))
933               /* When we're demoing a single hack, mouse motion doesn't
934                  cause deactivation.  Only clicks and keypresses do. */
935               ;
936             else
937               /* If we're not demoing, then any activity causes deactivation.
938                */
939               goto DONE;
940           }
941         else
942           reset_timers (si);
943
944         break;
945
946       default:
947
948 #ifdef HAVE_MIT_SAVER_EXTENSION
949         if (event.x_event.type == si->mit_saver_ext_event_number)
950           {
951             /* This event's number is that of the MIT-SCREEN-SAVER server
952                extension.  This extension has one event number, and the event
953                itself contains sub-codes that say what kind of event it was
954                (an "idle" or "not-idle" event.)
955              */
956             if (event.sevent.state == ScreenSaverOn)
957               {
958                 int i = 0;
959                 if (p->verbose_p)
960                   fprintf (stderr, "%s: MIT ScreenSaverOn event received.\n",
961                            blurb());
962
963                 /* Get the "real" server window(s) out of the way as soon
964                    as possible. */
965                 for (i = 0; i < si->nscreens; i++)
966                   {
967                     saver_screen_info *ssi = &si->screens[i];
968                     if (ssi->server_mit_saver_window &&
969                         window_exists_p (si->dpy,
970                                          ssi->server_mit_saver_window))
971                       XUnmapWindow (si->dpy, ssi->server_mit_saver_window);
972                   }
973
974                 if (event.sevent.kind != ScreenSaverExternal)
975                   {
976                     fprintf (stderr,
977                          "%s: ScreenSaverOn event wasn't of type External!\n",
978                              blurb());
979                   }
980
981                 if (until_idle_p)
982                   goto DONE;
983               }
984             else if (event.sevent.state == ScreenSaverOff)
985               {
986                 if (p->verbose_p)
987                   fprintf (stderr, "%s: MIT ScreenSaverOff event received.\n",
988                            blurb());
989                 if (!until_idle_p)
990                   goto DONE;
991               }
992             else
993               fprintf (stderr,
994                        "%s: unknown MIT-SCREEN-SAVER event %d received!\n",
995                        blurb(), event.sevent.state);
996           }
997         else
998
999 #endif /* HAVE_MIT_SAVER_EXTENSION */
1000
1001
1002 #ifdef HAVE_SGI_SAVER_EXTENSION
1003         if (event.x_event.type == (si->sgi_saver_ext_event_number + ScreenSaverStart))
1004           {
1005             /* The SGI SCREEN_SAVER server extension has two event numbers,
1006                and this event matches the "idle" event. */
1007             if (p->verbose_p)
1008               fprintf (stderr, "%s: SGI ScreenSaverStart event received.\n",
1009                        blurb());
1010
1011             if (until_idle_p)
1012               goto DONE;
1013           }
1014         else if (event.x_event.type == (si->sgi_saver_ext_event_number +
1015                                 ScreenSaverEnd))
1016           {
1017             /* The SGI SCREEN_SAVER server extension has two event numbers,
1018                and this event matches the "idle" event. */
1019             if (p->verbose_p)
1020               fprintf (stderr, "%s: SGI ScreenSaverEnd event received.\n",
1021                        blurb());
1022             if (!until_idle_p)
1023               goto DONE;
1024           }
1025         else
1026 #endif /* HAVE_SGI_SAVER_EXTENSION */
1027
1028 #ifdef HAVE_RANDR
1029         if (event.x_event.type == (si->randr_event_number + RRScreenChangeNotify))
1030           {
1031             /* The Resize and Rotate extension sends an event when the
1032                size, rotation, or refresh rate of any screen has changed.
1033              */
1034             if (p->verbose_p)
1035               {
1036                 /* XRRRootToScreen is in Xrandr.h 1.4, 2001/06/07 */
1037                 int screen = XRRRootToScreen (si->dpy, event.xrr_event.window);
1038                 fprintf (stderr, "%s: %d: screen change event received\n",
1039                          blurb(), screen);
1040               }
1041
1042 # ifdef RRScreenChangeNotifyMask
1043             /* Inform Xlib that it's ok to update its data structures. */
1044             XRRUpdateConfiguration (&event.x_event); /* Xrandr.h 1.9, 2002/09/29 */
1045 # endif /* RRScreenChangeNotifyMask */
1046
1047             /* Resize the existing xscreensaver windows and cached ssi data. */
1048             if (update_screen_layout (si))
1049               {
1050                 if (p->verbose_p)
1051                   {
1052                     fprintf (stderr, "%s: new layout:\n", blurb());
1053                     describe_monitor_layout (si);
1054                   }
1055                 resize_screensaver_window (si);
1056               }
1057           }
1058         else
1059 #endif /* HAVE_RANDR */
1060
1061           /* Just some random event.  Let the Widgets handle it, if desired. */
1062           dispatch_event (si, &event.x_event);
1063       }
1064     }
1065  DONE:
1066
1067
1068   /* If there's a user event on the queue, swallow it.
1069      If we're using a server extension, and the user becomes active, we
1070      get the extension event before the user event -- so the keypress or
1071      motion or whatever is still on the queue.  This makes "unfade" not
1072      work, because it sees that event, and bugs out.  (This problem
1073      doesn't exhibit itself without an extension, because in that case,
1074      there's only one event generated by user activity, not two.)
1075    */
1076   if (!until_idle_p && si->locked_p)
1077     swallow_unlock_typeahead_events (si, &event.x_event);
1078   else
1079     while (XCheckMaskEvent (si->dpy,
1080                             (KeyPressMask|ButtonPressMask|PointerMotionMask),
1081                      &event.x_event))
1082       ;
1083
1084
1085   if (si->check_pointer_timer_id)
1086     {
1087       XtRemoveTimeOut (si->check_pointer_timer_id);
1088       si->check_pointer_timer_id = 0;
1089     }
1090   if (si->timer_id)
1091     {
1092       XtRemoveTimeOut (si->timer_id);
1093       si->timer_id = 0;
1094     }
1095
1096   if (until_idle_p && si->cycle_id)     /* no cycle timer when inactive */
1097     abort ();
1098 }
1099
1100
1101 \f
1102 /* Some crap for dealing with /proc/interrupts.
1103
1104    On Linux systems, it's possible to see the hardware interrupt count
1105    associated with the keyboard.  We can therefore use that as another method
1106    of detecting idleness.
1107
1108    Why is it a good idea to do this?  Because it lets us detect keyboard
1109    activity that is not associated with X events.  For example, if the user
1110    has switched to another virtual console, it's good for xscreensaver to not
1111    be running graphics hacks on the (non-visible) X display.  The common
1112    complaint that checking /proc/interrupts addresses is that the user is
1113    playing Quake on a non-X console, and the GL hacks are perceptibly slowing
1114    the game...
1115
1116    This is tricky for a number of reasons.
1117
1118      * First, we must be sure to only do this when running on an X server that
1119        is on the local machine (because otherwise, we'd be reacting to the
1120        wrong keyboard.)  The way we do this is by noting that the $DISPLAY is
1121        pointing to display 0 on the local machine.  It *could* be that display
1122        1 is also on the local machine (e.g., two X servers, each on a different
1123        virtual-terminal) but it's also possible that screen 1 is an X terminal,
1124        using this machine as the host.  So we can't take that chance.
1125
1126      * Second, one can only access these interrupt numbers in a completely
1127        and utterly brain-damaged way.  You would think that one would use an
1128        ioctl for this.  But no.  The ONLY way to get this information is to
1129        open the pseudo-file /proc/interrupts AS A FILE, and read the numbers
1130        out of it TEXTUALLY.  Because this is Unix, and all the world's a file,
1131        and the only real data type is the short-line sequence of ASCII bytes.
1132
1133        Now it's all well and good that the /proc/interrupts pseudo-file
1134        exists; that's a clever idea, and a useful API for things that are
1135        already textually oriented, like shell scripts, and users doing
1136        interactive debugging sessions.  But to make a *C PROGRAM* open a file
1137        and parse the textual representation of integers out of it is just
1138        insane.
1139
1140      * Third, you can't just hold the file open, and fseek() back to the
1141        beginning to get updated data!  If you do that, the data never changes.
1142        And I don't want to call open() every five seconds, because I don't want
1143        to risk going to disk for any inodes.  It turns out that if you dup()
1144        it early, then each copy gets fresh data, so we can get around that in
1145        this way (but for how many releases, one might wonder?)
1146
1147      * Fourth, the format of the output of the /proc/interrupts file is
1148        undocumented, and has changed several times already!  In Linux 2.0.33,
1149        even on a multiprocessor machine, it looks like this:
1150
1151           0:  309453991   timer
1152           1:    4771729   keyboard
1153    
1154        but in Linux 2.2 and 2.4 kernels with MP machines, it looks like this:
1155
1156                    CPU0       CPU1
1157           0:    1671450    1672618    IO-APIC-edge  timer
1158           1:      13037      13495    IO-APIC-edge  keyboard
1159
1160        and in Linux 2.6, it's gotten even goofier: now there are two lines
1161        labelled "i8042".  One of them is the keyboard, and one of them is
1162        the PS/2 mouse -- and of course, you can't tell them apart, except
1163        by wiggling the mouse and noting which one changes:
1164
1165                    CPU0       CPU1
1166           1:      32051      30864    IO-APIC-edge  i8042
1167          12:     476577     479913    IO-APIC-edge  i8042
1168
1169        Joy!  So how are we expected to parse that?  Well, this code doesn't
1170        parse it: it saves the first line with the string "keyboard" (or
1171        "i8042") in it, and does a string-comparison to note when it has
1172        changed.  If there are two "i8042" lines, we assume the first is
1173        the keyboard and the second is the mouse (doesn't matter which is
1174        which, really, as long as we don't compare them against each other.)
1175
1176    Thanks to Nat Friedman <nat@nat.org> for figuring out most of this crap.
1177
1178    Note that if you have a serial or USB mouse, or a USB keyboard, it won't
1179    detect it.  That's because there's no way to tell the difference between a
1180    serial mouse and a general serial port, and all USB devices look the same
1181    from here.  It would be somewhat unfortunate to have the screensaver turn
1182    off when the modem on COM1 burped, or when a USB disk was accessed.
1183  */
1184
1185
1186 #ifdef HAVE_PROC_INTERRUPTS
1187
1188 #define PROC_INTERRUPTS "/proc/interrupts"
1189
1190 Bool
1191 query_proc_interrupts_available (saver_info *si, const char **why)
1192 {
1193   /* We can use /proc/interrupts if $DISPLAY points to :0, and if the
1194      "/proc/interrupts" file exists and is readable.
1195    */
1196   FILE *f;
1197   if (why) *why = 0;
1198
1199   if (!display_is_on_console_p (si))
1200     {
1201       if (why) *why = "not on primary console";
1202       return False;
1203     }
1204
1205   f = fopen (PROC_INTERRUPTS, "r");
1206   if (!f)
1207     {
1208       if (why) *why = "does not exist";
1209       return False;
1210     }
1211
1212   fclose (f);
1213   return True;
1214 }
1215
1216
1217 static Bool
1218 proc_interrupts_activity_p (saver_info *si)
1219 {
1220   static FILE *f0 = 0;
1221   FILE *f1 = 0;
1222   int fd;
1223   static char last_kbd_line[255] = { 0, };
1224   static char last_ptr_line[255] = { 0, };
1225   char new_line[sizeof(last_kbd_line)];
1226   Bool checked_kbd = False, kbd_changed = False;
1227   Bool checked_ptr = False, ptr_changed = False;
1228   int i8042_count = 0;
1229
1230   if (!f0)
1231     {
1232       /* First time -- open the file. */
1233       f0 = fopen (PROC_INTERRUPTS, "r");
1234       if (!f0)
1235         {
1236           char buf[255];
1237           sprintf(buf, "%s: error opening %s", blurb(), PROC_INTERRUPTS);
1238           perror (buf);
1239           goto FAIL;
1240         }
1241     }
1242
1243   if (f0 == (FILE *) -1)            /* means we got an error initializing. */
1244     return False;
1245
1246   fd = dup (fileno (f0));
1247   if (fd < 0)
1248     {
1249       char buf[255];
1250       sprintf(buf, "%s: could not dup() the %s fd", blurb(), PROC_INTERRUPTS);
1251       perror (buf);
1252       goto FAIL;
1253     }
1254
1255   f1 = fdopen (fd, "r");
1256   if (!f1)
1257     {
1258       char buf[255];
1259       sprintf(buf, "%s: could not fdopen() the %s fd", blurb(),
1260               PROC_INTERRUPTS);
1261       perror (buf);
1262       goto FAIL;
1263     }
1264
1265   /* Actually, I'm unclear on why this fseek() is necessary, given the timing
1266      of the dup() above, but it is. */
1267   if (fseek (f1, 0, SEEK_SET) != 0)
1268     {
1269       char buf[255];
1270       sprintf(buf, "%s: error rewinding %s", blurb(), PROC_INTERRUPTS);
1271       perror (buf);
1272       goto FAIL;
1273     }
1274
1275   /* Now read through the pseudo-file until we find the "keyboard",
1276      "PS/2 mouse", or "i8042" lines. */
1277
1278   while (fgets (new_line, sizeof(new_line)-1, f1))
1279     {
1280       Bool i8042_p = !!strstr (new_line, "i8042");
1281       if (i8042_p) i8042_count++;
1282
1283       if (strchr (new_line, ','))
1284         {
1285           /* Ignore any line that has a comma on it: this is because
1286              a setup like this:
1287
1288                  12:     930935          XT-PIC  usb-uhci, PS/2 Mouse
1289
1290              is really bad news.  It *looks* like we can note mouse
1291              activity from that line, but really, that interrupt gets
1292              fired any time any USB device has activity!  So we have
1293              to ignore any shared IRQs.
1294            */
1295         }
1296       else if (!checked_kbd &&
1297                (strstr (new_line, "keyboard") ||
1298                 (i8042_p && i8042_count == 1)))
1299         {
1300           /* Assume the keyboard interrupt is the line that says "keyboard",
1301              or the *first* line that says "i8042".
1302            */
1303           kbd_changed = (*last_kbd_line && !!strcmp (new_line, last_kbd_line));
1304           strcpy (last_kbd_line, new_line);
1305           checked_kbd = True;
1306         }
1307       else if (!checked_ptr &&
1308                (strstr (new_line, "PS/2 Mouse") ||
1309                 (i8042_p && i8042_count == 2)))
1310         {
1311           /* Assume the mouse interrupt is the line that says "PS/2 mouse",
1312              or the *second* line that says "i8042".
1313            */
1314           ptr_changed = (*last_ptr_line && !!strcmp (new_line, last_ptr_line));
1315           strcpy (last_ptr_line, new_line);
1316           checked_ptr = True;
1317         }
1318
1319       if (checked_kbd && checked_ptr)
1320         break;
1321     }
1322
1323   if (checked_kbd || checked_ptr)
1324     {
1325       fclose (f1);
1326
1327       if (si->prefs.debug_p && (kbd_changed || ptr_changed))
1328         fprintf (stderr, "%s: /proc/interrupts activity: %s\n",
1329                  blurb(),
1330                  ((kbd_changed && ptr_changed) ? "mouse and kbd" :
1331                   kbd_changed ? "kbd" :
1332                   ptr_changed ? "mouse" : "ERR"));
1333
1334       return (kbd_changed || ptr_changed);
1335     }
1336
1337
1338   /* If we got here, we didn't find either a "keyboard" or a "PS/2 Mouse"
1339      line in the file at all. */
1340   fprintf (stderr, "%s: no keyboard or mouse data in %s?\n",
1341            blurb(), PROC_INTERRUPTS);
1342
1343  FAIL:
1344   if (f1)
1345     fclose (f1);
1346
1347   if (f0 && f0 != (FILE *) -1)
1348     fclose (f0);
1349
1350   f0 = (FILE *) -1;
1351   return False;
1352 }
1353
1354 #endif /* HAVE_PROC_INTERRUPTS */
1355
1356 \f
1357 /* This timer goes off every few minutes, whether the user is idle or not,
1358    to try and clean up anything that has gone wrong.
1359
1360    It calls disable_builtin_screensaver() so that if xset has been used,
1361    or some other program (like xlock) has messed with the XSetScreenSaver()
1362    settings, they will be set back to sensible values (if a server extension
1363    is in use, messing with xlock can cause xscreensaver to never get a wakeup
1364    event, and could cause monitor power-saving to occur, and all manner of
1365    heinousness.)
1366
1367    If the screen is currently blanked, it raises the window, in case some
1368    other window has been mapped on top of it.
1369
1370    If the screen is currently blanked, and there is no hack running, it
1371    clears the window, in case there is an error message printed on it (we
1372    don't want the error message to burn in.)
1373  */
1374
1375 static void
1376 watchdog_timer (XtPointer closure, XtIntervalId *id)
1377 {
1378   saver_info *si = (saver_info *) closure;
1379   saver_preferences *p = &si->prefs;
1380
1381   disable_builtin_screensaver (si, False);
1382
1383   /* If the DPMS settings on the server have changed, change them back to
1384      what ~/.xscreensaver says they should be. */
1385   sync_server_dpms_settings (si->dpy,
1386                              (p->dpms_enabled_p  &&
1387                               p->mode != DONT_BLANK),
1388                              p->dpms_standby / 1000,
1389                              p->dpms_suspend / 1000,
1390                              p->dpms_off / 1000,
1391                              False);
1392
1393   if (si->screen_blanked_p)
1394     {
1395       Bool running_p = screenhack_running_p (si);
1396
1397       if (si->dbox_up_p)
1398         {
1399           if (si->prefs.debug_p)
1400             fprintf (stderr, "%s: dialog box is up: not raising screen.\n",
1401                      blurb());
1402         }
1403       else
1404         {
1405           if (si->prefs.debug_p)
1406             fprintf (stderr, "%s: watchdog timer raising %sscreen.\n",
1407                      blurb(), (running_p ? "" : "and clearing "));
1408
1409           raise_window (si, True, True, running_p);
1410         }
1411
1412       if (screenhack_running_p (si) &&
1413           !monitor_powered_on_p (si))
1414         {
1415           int i;
1416           if (si->prefs.verbose_p)
1417             fprintf (stderr,
1418                      "%s: X says monitor has powered down; "
1419                      "killing running hacks.\n", blurb());
1420           for (i = 0; i < si->nscreens; i++)
1421             kill_screenhack (&si->screens[i]);
1422         }
1423
1424       /* Re-schedule this timer.  The watchdog timer defaults to a bit less
1425          than the hack cycle period, but is never longer than one hour.
1426        */
1427       si->watchdog_id = 0;
1428       reset_watchdog_timer (si, True);
1429     }
1430 }
1431
1432
1433 void
1434 reset_watchdog_timer (saver_info *si, Bool on_p)
1435 {
1436   saver_preferences *p = &si->prefs;
1437
1438   if (si->watchdog_id)
1439     {
1440       XtRemoveTimeOut (si->watchdog_id);
1441       si->watchdog_id = 0;
1442     }
1443
1444   if (on_p && p->watchdog_timeout)
1445     {
1446       si->watchdog_id = XtAppAddTimeOut (si->app, p->watchdog_timeout,
1447                                          watchdog_timer, (XtPointer) si);
1448
1449       if (p->debug_p)
1450         fprintf (stderr, "%s: restarting watchdog_timer (%ld, %ld)\n",
1451                  blurb(), p->watchdog_timeout, si->watchdog_id);
1452     }
1453 }
1454
1455
1456 /* It's possible that a race condition could have led to the saver
1457    window being unexpectedly still mapped.  This can happen like so:
1458
1459     - screen is blanked
1460     - hack is launched
1461     - that hack tries to grab a screen image (it does this by
1462       first unmapping the saver window, then remapping it.)
1463     - hack unmaps window
1464     - hack waits
1465     - user becomes active
1466     - hack re-maps window (*)
1467     - driver kills subprocess
1468     - driver unmaps window (**)
1469
1470    The race is that (*) might have been sent to the server before
1471    the client process was killed, but, due to scheduling randomness,
1472    might not have been received by the server until after (**).
1473    In other words, (*) and (**) might happen out of order, meaning
1474    the driver will unmap the window, and then after that, the
1475    recently-dead client will re-map it.  This leaves the user
1476    locked out (it looks like a desktop, but it's not!)
1477
1478    To avoid this: after un-blanking the screen, we launch a timer
1479    that wakes up once a second for ten seconds, and makes damned
1480    sure that the window is still unmapped.
1481  */
1482
1483 void
1484 de_race_timer (XtPointer closure, XtIntervalId *id)
1485 {
1486   saver_info *si = (saver_info *) closure;
1487   saver_preferences *p = &si->prefs;
1488   int secs = 1;
1489
1490   if (id == 0)  /* if id is 0, this is the initialization call. */
1491     {
1492       si->de_race_ticks = 10;
1493       if (p->verbose_p)
1494         fprintf (stderr, "%s: starting de-race timer (%d seconds.)\n",
1495                  blurb(), si->de_race_ticks);
1496     }
1497   else
1498     {
1499       int i;
1500       XSync (si->dpy, False);
1501       for (i = 0; i < si->nscreens; i++)
1502         {
1503           saver_screen_info *ssi = &si->screens[i];
1504           Window w = ssi->screensaver_window;
1505           XWindowAttributes xgwa;
1506           XGetWindowAttributes (si->dpy, w, &xgwa);
1507           if (xgwa.map_state != IsUnmapped)
1508             {
1509               if (p->verbose_p)
1510                 fprintf (stderr,
1511                          "%s: %d: client race! emergency unmap 0x%lx.\n",
1512                          blurb(), i, (unsigned long) w);
1513               XUnmapWindow (si->dpy, w);
1514             }
1515           else if (p->debug_p)
1516             fprintf (stderr, "%s: %d: (de-race of 0x%lx is cool.)\n",
1517                      blurb(), i, (unsigned long) w);
1518         }
1519       XSync (si->dpy, False);
1520
1521       si->de_race_ticks--;
1522     }
1523
1524   if (id && *id == si->de_race_id)
1525     si->de_race_id = 0;
1526
1527   if (si->de_race_id) abort();
1528
1529   if (si->de_race_ticks <= 0)
1530     {
1531       si->de_race_id = 0;
1532       if (p->verbose_p)
1533         fprintf (stderr, "%s: de-race completed.\n", blurb());
1534     }
1535   else
1536     {
1537       si->de_race_id = XtAppAddTimeOut (si->app, secs * 1000,
1538                                         de_race_timer, closure);
1539     }
1540 }