8347e5584ce55b45bc0ef7364a8e190b456f8236
[gnus] / lisp / gnus-demon.el
1 ;;; gnus-demon.el --- daemonic Gnus behaviour
2 ;; Copyright (C) 1995,96,97 Free Software Foundation, Inc.
3
4 ;; Author: Lars Magne Ingebrigtsen <larsi@ifi.uio.no>
5 ;; Keywords: news
6
7 ;; This file is part of GNU Emacs.
8
9 ;; GNU Emacs is free software; you can redistribute it and/or modify
10 ;; it under the terms of the GNU General Public License as published by
11 ;; the Free Software Foundation; either version 2, or (at your option)
12 ;; any later version.
13
14 ;; GNU Emacs is distributed in the hope that it will be useful,
15 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
16 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17 ;; GNU General Public License for more details.
18
19 ;; You should have received a copy of the GNU General Public License
20 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
21 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
22 ;; Boston, MA 02111-1307, USA.
23
24 ;;; Commentary:
25
26 ;;; Code:
27
28 (eval-when-compile (require 'cl))
29
30 (require 'gnus)
31 (require 'gnus-int)
32 (require 'nnheader)
33 (require 'nntp)
34 (eval-and-compile
35   (if (string-match "XEmacs" (emacs-version))
36       (require 'itimer)
37     (require 'timer)))
38
39 (defgroup gnus-demon nil
40   "Demonic behaviour."
41   :group 'gnus)
42
43 (defcustom gnus-demon-handlers nil
44   "Alist of daemonic handlers to be run at intervals.
45 Each handler is a list on the form
46
47 \(FUNCTION TIME IDLE)
48
49 FUNCTION is the function to be called.
50 TIME is the number of `gnus-demon-timestep's between each call.
51 If nil, never call.  If t, call each `gnus-demon-timestep'.
52 If IDLE is t, only call if Emacs has been idle for a while.  If IDLE
53 is a number, only call when Emacs has been idle more than this number
54 of `gnus-demon-timestep's.  If IDLE is nil, don't care about
55 idleness.  If IDLE is a number and TIME is nil, then call once each
56 time Emacs has been idle for IDLE `gnus-demon-timestep's."
57   :group 'gnus-demon
58   :type '(repeat (list function
59                        (choice :tag "Time"
60                                (const :tag "never" nil)
61                                (const :tag "one" t)
62                                (integer :tag "steps" 1))
63                        (choice :tag "Idle"
64                                (const :tag "don't care" nil)
65                                (const :tag "for a while" t)
66                                (integer :tag "steps" 1)))))
67
68 (defcustom gnus-demon-timestep 60
69   "*Number of seconds in each demon timestep."
70   :group 'gnus-demon
71   :type 'integer)
72
73 ;;; Internal variables.
74
75 (defvar gnus-demon-timer nil)
76 (defvar gnus-demon-idle-has-been-called nil)
77 (defvar gnus-demon-idle-time 0)
78 (defvar gnus-demon-handler-state nil)
79 (defvar gnus-demon-last-keys nil)
80 (defvar gnus-inhibit-demon nil
81   "*If non-nil, no daemonic function will be run.")
82
83 (eval-and-compile
84   (autoload 'timezone-parse-date "timezone")
85   (autoload 'timezone-make-arpa-date "timezone"))
86
87 ;;; Functions.
88
89 (defun gnus-demon-add-handler (function time idle)
90   "Add the handler FUNCTION to be run at TIME and IDLE."
91   ;; First remove any old handlers that use this function.
92   (gnus-demon-remove-handler function)
93   ;; Then add the new one.
94   (push (list function time idle) gnus-demon-handlers)
95   (gnus-demon-init))
96
97 (defun gnus-demon-remove-handler (function &optional no-init)
98   "Remove the handler FUNCTION from the list of handlers."
99   (setq gnus-demon-handlers
100         (delq (assq function gnus-demon-handlers)
101               gnus-demon-handlers))
102   (unless no-init
103     (gnus-demon-init)))
104
105 (defun gnus-demon-init ()
106   "Initialize the Gnus daemon."
107   (interactive)
108   (gnus-demon-cancel)
109   (when gnus-demon-handlers
110     ;; Set up the timer.
111     (setq gnus-demon-timer
112           (nnheader-run-at-time
113            gnus-demon-timestep gnus-demon-timestep 'gnus-demon))
114     ;; Reset control variables.
115     (setq gnus-demon-handler-state
116           (mapcar
117            (lambda (handler)
118              (list (car handler) (gnus-demon-time-to-step (nth 1 handler))
119                    (nth 2 handler)))
120            gnus-demon-handlers))
121     (setq gnus-demon-idle-time 0)
122     (setq gnus-demon-idle-has-been-called nil)
123     (setq gnus-use-demon t)))
124
125 (gnus-add-shutdown 'gnus-demon-cancel 'gnus)
126
127 (defun gnus-demon-cancel ()
128   "Cancel any Gnus daemons."
129   (interactive)
130   (when gnus-demon-timer
131     (nnheader-cancel-timer gnus-demon-timer))
132   (setq gnus-demon-timer nil
133         gnus-use-demon nil
134         gnus-demon-idle-has-been-called nil)
135   (condition-case ()
136       (nnheader-cancel-function-timers 'gnus-demon)
137     (error t)))
138
139 (defun gnus-demon-is-idle-p ()
140   "Whether Emacs is idle or not."
141   ;; We do this simply by comparing the 100 most recent keystrokes
142   ;; with the ones we had last time.  If they are the same, one might
143   ;; guess that Emacs is indeed idle.  This only makes sense if one
144   ;; calls this function seldom -- like once a minute, which is what
145   ;; we do here.
146   (let ((keys (recent-keys)))
147     (or (equal keys gnus-demon-last-keys)
148         (progn
149           (setq gnus-demon-last-keys keys)
150           nil))))
151
152 (defun gnus-demon-time-to-step (time)
153   "Find out how many seconds to TIME, which is on the form \"17:43\"."
154   (if (not (stringp time))
155       time
156     (let* ((now (current-time))
157            ;; obtain NOW as discrete components -- make a vector for speed
158            (nowParts (apply 'vector (decode-time now)))
159            ;; obtain THEN as discrete components
160            (thenParts (timezone-parse-time time))
161            (thenHour (string-to-int (elt thenParts 0)))
162            (thenMin (string-to-int (elt thenParts 1)))
163            ;; convert time as elements into number of seconds since EPOCH.
164            (then (encode-time 0
165                               thenMin
166                               thenHour
167                               ;; If THEN is earlier than NOW, make it
168                               ;; same time tomorrow. Doc for encode-time
169                               ;; says that this is OK.
170                               (+ (elt nowParts 3)
171                                  (if (or (< thenHour (elt nowParts 2))
172                                          (and (= thenHour (elt nowParts 2))
173                                               (<= thenMin (elt nowParts 1))))
174                                      1 0))
175                               (elt nowParts 4)
176                               (elt nowParts 5)
177                               (elt nowParts 6)
178                               (elt nowParts 7)
179                               (elt nowParts 8)))
180            ;; calculate number of seconds between NOW and THEN
181            (diff (+ (* 65536 (- (car then) (car now)))
182                     (- (cadr then) (cadr now)))))
183       ;; return number of timesteps in the number of seconds
184       (round (/ diff gnus-demon-timestep)))))
185
186 (defun gnus-demon ()
187   "The Gnus daemon that takes care of running all Gnus handlers."
188   ;; Increase or reset the time Emacs has been idle.
189   (if (gnus-demon-is-idle-p)
190       (incf gnus-demon-idle-time)
191     (setq gnus-demon-idle-time 0)
192     (setq gnus-demon-idle-has-been-called nil))
193   ;; Disable all daemonic stuff if we're in the minibuffer
194   (when (and (not (window-minibuffer-p (selected-window)))
195              (not gnus-inhibit-demon))
196     ;; Then we go through all the handler and call those that are
197     ;; sufficiently ripe.
198     (let ((handlers gnus-demon-handler-state)
199           (gnus-inhibit-demon t)
200           handler time idle)
201       (while handlers
202         (setq handler (pop handlers))
203         (cond
204          ((numberp (setq time (nth 1 handler)))
205           ;; These handlers use a regular timeout mechanism.  We decrease
206           ;; the timer if it hasn't reached zero yet.
207           (unless (zerop time)
208             (setcar (nthcdr 1 handler) (decf time)))
209           (and (zerop time)             ; If the timer now is zero...
210                ;; Test for appropriate idleness
211                (progn
212                  (setq idle (nth 2 handler))
213                  (cond
214                   ((null idle) t)       ; Don't care about idle.
215                   ((numberp idle)       ; Numerical idle...
216                    (< idle gnus-demon-idle-time)) ; Idle timed out.
217                   (t (< 0 gnus-demon-idle-time)))) ; Or just need to be idle.
218                ;; So we call the handler.
219                (progn
220                  (ignore-errors (funcall (car handler)))
221                  ;; And reset the timer.
222                  (setcar (nthcdr 1 handler)
223                          (gnus-demon-time-to-step
224                           (nth 1 (assq (car handler) gnus-demon-handlers)))))))
225          ;; These are only supposed to be called when Emacs is idle.
226          ((null (setq idle (nth 2 handler)))
227           ;; We do nothing.
228           )
229          ((and (not (numberp idle))
230                (gnus-demon-is-idle-p))
231           ;; We want to call this handler each and every time that
232           ;; Emacs is idle.
233           (ignore-errors (funcall (car handler))))
234          (t
235           ;; We want to call this handler only if Emacs has been idle
236           ;; for a specified number of timesteps.
237           (and (not (memq (car handler) gnus-demon-idle-has-been-called))
238                (< idle gnus-demon-idle-time)
239                (gnus-demon-is-idle-p)
240                (progn
241                  (ignore-errors (funcall (car handler)))
242                  ;; Make sure the handler won't be called once more in
243                  ;; this idle-cycle.
244                  (push (car handler) gnus-demon-idle-has-been-called)))))))))
245
246 (defun gnus-demon-add-nocem ()
247   "Add daemonic NoCeM handling to Gnus."
248   (gnus-demon-add-handler 'gnus-demon-scan-nocem 60 30))
249
250 (defun gnus-demon-scan-nocem ()
251   "Scan NoCeM groups for NoCeM messages."
252   (save-window-excursion
253     (gnus-nocem-scan-groups)))
254
255 (defun gnus-demon-add-disconnection ()
256   "Add daemonic server disconnection to Gnus."
257   (gnus-demon-add-handler 'gnus-demon-close-connections nil 30))
258
259 (defun gnus-demon-close-connections ()
260   (save-window-excursion
261     (gnus-close-backends)))
262
263 (defun gnus-demon-add-nntp-close-connection ()
264   "Add daemonic nntp server disconnection to Gnus.
265 If no commands have gone out via nntp during the last five
266 minutes, the connection is closed."
267   (gnus-demon-add-handler 'gnus-demon-close-connections 5 nil))
268
269 (defun gnus-demon-nntp-close-connection ()
270   (save-window-excursion
271     (when (nnmail-time-less '(0 300)
272                             (nnmail-time-since nntp-last-command-time))
273       (nntp-close-server))))
274
275 (defun gnus-demon-add-scanmail ()
276   "Add daemonic scanning of mail from the mail backends."
277   (gnus-demon-add-handler 'gnus-demon-scan-mail 120 60))
278
279 (defun gnus-demon-scan-mail ()
280   (save-window-excursion
281     (let ((servers gnus-opened-servers)
282           server)
283       (gnus-clear-inboxes-moved)
284       (while (setq server (car (pop servers)))
285         (and (gnus-check-backend-function 'request-scan (car server))
286              (or (gnus-server-opened server)
287                  (gnus-open-server server))
288              (gnus-request-scan nil server))))))
289
290 (defun gnus-demon-add-rescan ()
291   "Add daemonic scanning of new articles from all backends."
292   (gnus-demon-add-handler 'gnus-demon-scan-news 120 60))
293
294 (defun gnus-demon-scan-news ()
295   (let ((win (current-window-configuration)))
296     (unwind-protect
297         (save-window-excursion
298           (save-excursion
299             (when (gnus-alive-p)
300               (save-excursion
301                 (set-buffer gnus-group-buffer)
302                 (gnus-group-get-new-news)))))
303       (set-window-configuration win))))
304
305 (defun gnus-demon-add-scan-timestamps ()
306   "Add daemonic updating of timestamps in empty newgroups."
307   (gnus-demon-add-handler 'gnus-demon-scan-timestamps nil 30))
308
309 (defun gnus-demon-scan-timestamps ()
310   "Set the timestamp on all newsgroups with no unread and no ticked articles."
311   (when (gnus-alive-p)
312     (let ((cur-time (current-time))
313           (newsrc (cdr gnus-newsrc-alist))
314           info group unread has-ticked)
315       (while (setq info (pop newsrc))
316         (setq group (gnus-info-group info)
317               unread (gnus-group-unread group)
318               has-ticked (cdr (assq 'tick (gnus-info-marks info))))
319         (when (and (numberp unread)
320                    (= unread 0)
321                    (not has-ticked))
322           (gnus-group-set-parameter group 'timestamp cur-time))))))
323
324 (provide 'gnus-demon)
325
326 ;;; gnus-demon.el ends here