f412dd9411e57e4b04af2662c1156e7caadf468b
[elisp/semi.git] / mime-play.el
1 ;;; mime-play.el --- Playback processing module for mime-view.el
2
3 ;; Copyright (C) 1994,1995,1996,1997,1998,1999 Free Software Foundation, Inc.
4
5 ;; Author: MORIOKA Tomohiko <morioka@jaist.ac.jp>
6 ;; Created: 1995/9/26 (separated from tm-view.el)
7 ;;      Renamed: 1997/2/21 from tm-play.el
8 ;; Keywords: MIME, multimedia, mail, news
9
10 ;; This file is part of SEMI (Secretariat of Emacs MIME Interfaces).
11
12 ;; This program is free software; you can redistribute it and/or
13 ;; modify it under the terms of the GNU General Public License as
14 ;; published by the Free Software Foundation; either version 2, or (at
15 ;; your option) any later version.
16
17 ;; This program is distributed in the hope that it will be useful, but
18 ;; WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
20 ;; General Public License for more details.
21
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
24 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
25 ;; Boston, MA 02111-1307, USA.
26
27 ;;; Code:
28
29 (require 'mime-view)
30 (require 'alist)
31 (require 'filename)
32
33 (eval-when-compile
34   (condition-case nil
35       (require 'bbdb)
36     (error (defvar bbdb-buffer-name nil)))
37   )
38
39 (defvar mime-acting-situation-example-list nil)
40
41 (defvar mime-acting-situation-example-list-max-size 16)
42
43 (defun mime-save-acting-situation-examples ()
44   (let* ((file mime-acting-situation-examples-file)
45          (buffer (get-buffer-create " *mime-example*")))
46     (unwind-protect
47         (save-excursion
48           (set-buffer buffer)
49           (setq buffer-file-name file)
50           (erase-buffer)
51           (insert ";;; " (file-name-nondirectory file) "\n")
52           (insert "\n;; This file is generated automatically by "
53                   mime-view-version "\n\n")
54           (insert ";;; Code:\n\n")
55           (pp `(setq mime-acting-situation-example-list
56                      ',mime-acting-situation-example-list)
57               (current-buffer))
58           (insert "\n;;; "
59                   (file-name-nondirectory file)
60                   " ends here.\n")
61           (save-buffer))
62       (kill-buffer buffer))))
63
64 (add-hook 'kill-emacs-hook 'mime-save-acting-situation-examples)
65
66 (defun mime-reduce-acting-situation-examples ()
67   (let* ((rest mime-acting-situation-example-list)
68          (min-example (car rest))
69          (min-score (cdr min-example)))
70     (while rest
71       (let* ((example (car rest))
72              (score (cdr example)))
73         (cond ((< score min-score)
74                (setq min-score score
75                      min-example example)
76                )
77               ((= score min-score)
78                (if (<= (length (car example))(length (car min-example)))
79                    (setq min-example example)
80                  ))
81               ))
82       (setq rest (cdr rest)))
83     (setq mime-acting-situation-example-list
84           (delq min-example mime-acting-situation-example-list))
85     (setq min-example (car min-example))
86     (let ((examples mime-acting-situation-example-list)
87           (max-score 0)
88           max-examples)
89       (while examples
90         (let* ((ret (mime-compare-situation-with-example min-example
91                                                          (caar examples)))
92                (ret-score (car ret)))
93           (cond ((> ret-score max-score)
94                  (setq max-score ret-score
95                        max-examples (list (cdr ret)))
96                  )
97                 ((= ret-score max-score)
98                  (setq max-examples (cons (cdr ret) max-examples))
99                  )))
100         (setq examples (cdr examples)))
101       (while max-examples
102         (let* ((example (car max-examples))
103                (cell (assoc example mime-acting-situation-example-list)))
104           (if cell
105               (setcdr cell (1+ (cdr cell)))
106             (setq mime-acting-situation-example-list
107                   (cons (cons example 0)
108                         mime-acting-situation-example-list))
109             ))
110         (setq max-examples (cdr max-examples))
111         ))))
112
113
114 ;;; @ content decoder
115 ;;;
116
117 (defun mime-preview-play-current-entity (&optional ignore-examples mode)
118   "Play current entity.
119 It decodes current entity to call internal or external method.  The
120 method is selected from variable `mime-acting-condition'.
121 If IGNORE-EXAMPLES (C-u prefix) is specified, this function ignores
122 `mime-acting-situation-example-list'.
123 If MODE is specified, play as it.  Default MODE is \"play\"."
124   (interactive "P")
125   (let ((entity (get-text-property (point) 'mime-view-entity)))
126     (if entity
127         (mime-play-entity entity nil (or mode "play") ignore-examples)
128       )))
129
130 (defun mime-sort-situation (situation)
131   (sort situation
132         #'(lambda (a b)
133             (let ((a-t (car a))
134                   (b-t (car b))
135                   (order '((type . 1)
136                            (subtype . 2)
137                            (mode . 3)
138                            (method . 4)
139                            (major-mode . 5)
140                            (disposition-type . 6)
141                            ))
142                   a-order b-order)
143               (if (symbolp a-t)
144                   (let ((ret (assq a-t order)))
145                     (if ret
146                         (setq a-order (cdr ret))
147                       (setq a-order 7)
148                       ))
149                 (setq a-order 8)
150                 )
151               (if (symbolp b-t)
152                   (let ((ret (assq b-t order)))
153                     (if ret
154                         (setq b-order (cdr ret))
155                       (setq b-order 7)
156                       ))
157                 (setq b-order 8)
158                 )
159               (if (= a-order b-order)
160                   (string< (format "%s" a-t)(format "%s" b-t))
161                 (< a-order b-order))
162               )))
163   )
164
165 (defsubst mime-delq-null-situation (situations field
166                                                &optional ignored-value)
167   (let (dest)
168     (while situations
169       (let* ((situation (car situations))
170              (cell (assq field situation)))
171         (if cell
172             (or (eq (cdr cell) ignored-value)
173                 (setq dest (cons situation dest))
174                 )))
175       (setq situations (cdr situations)))
176     dest))
177
178 (defun mime-compare-situation-with-example (situation example)
179   (let ((example (copy-alist example))
180         (match 0))
181     (while situation
182       (let* ((cell (car situation))
183              (key (car cell))
184              (ecell (assoc key example)))
185         (when ecell
186           (if (equal cell ecell)
187               (setq match (1+ match))
188             (setq example (delq ecell example))
189             ))
190         )
191       (setq situation (cdr situation))
192       )
193     (cons match example)
194     ))
195
196 (defun mime-play-entity (entity &optional situation mode
197                                 ignore-examples ignored-method)
198   "Play entity specified by ENTITY.
199 It decodes the entity to call internal or external method.  The method
200 is selected from variable `mime-acting-condition'.  If MODE is
201 specified, play as it.  Default MODE is \"play\"."
202   (let (method ret)
203     (or situation
204         (setq situation (mime-entity-situation entity)))
205     (if mode
206         (setq situation (cons (cons 'mode mode) situation))
207       )
208     (if ignore-examples
209         (or (assq 'ignore-examples situation)
210             (setq situation
211                   (cons (cons 'ignore-examples ignore-examples) situation)))
212       )
213     (setq ret
214           (mime-delq-null-situation
215            (ctree-find-calist mime-acting-condition situation
216                               mime-view-find-every-acting-situation)
217            'method ignored-method))
218     (or ignore-examples
219         (if (cdr ret)
220             (let ((rest ret)
221                   (max-score 0)
222                   (max-escore 0)
223                   max-examples
224                   max-situations)
225               (while rest
226                 (let ((situation (car rest))
227                       (examples mime-acting-situation-example-list))
228                   (while examples
229                     (let* ((ret
230                             (mime-compare-situation-with-example
231                              situation (caar examples)))
232                            (ret-score (car ret)))
233                       (cond ((> ret-score max-score)
234                              (setq max-score ret-score
235                                    max-escore (cdar examples)
236                                    max-examples (list (cdr ret))
237                                    max-situations (list situation))
238                              )
239                             ((= ret-score max-score)
240                              (cond ((> (cdar examples) max-escore)
241                                     (setq max-escore (cdar examples)
242                                           max-examples (list (cdr ret))
243                                           max-situations (list situation))
244                                     )
245                                    ((= (cdar examples) max-escore)
246                                     (setq max-examples
247                                           (cons (cdr ret) max-examples))
248                                     (or (member situation max-situations)
249                                         (setq max-situations
250                                               (cons situation max-situations)))
251                                     )))))
252                     (setq examples (cdr examples))))
253                 (setq rest (cdr rest)))
254               (when max-situations
255                 (setq ret max-situations)
256                 (while max-examples
257                   (let* ((example (car max-examples))
258                          (cell
259                           (assoc example mime-acting-situation-example-list)))
260                     (if cell
261                         (setcdr cell (1+ (cdr cell)))
262                       (setq mime-acting-situation-example-list
263                             (cons (cons example 0)
264                                   mime-acting-situation-example-list))
265                       ))
266                   (setq max-examples (cdr max-examples))
267                   )))))
268     (cond ((cdr ret)
269            (setq ret (select-menu-alist
270                       "Methods"
271                       (mapcar (function
272                                (lambda (situation)
273                                  (cons
274                                   (format "%s"
275                                           (cdr (assq 'method situation)))
276                                   situation)))
277                               ret)))
278            (setq ret (mime-sort-situation ret))
279            (add-to-list 'mime-acting-situation-example-list (cons ret 0))
280            )
281           (t
282            (setq ret (car ret))
283            ))
284     (setq method (cdr (assq 'method ret)))
285     (cond ((and (symbolp method)
286                 (fboundp method))
287            (funcall method entity ret)
288            )
289           ((stringp method)
290            (mime-activate-mailcap-method entity ret)
291            )
292           ;; ((and (listp method)(stringp (car method)))
293           ;;  (mime-activate-external-method entity ret)
294           ;;  )
295           (t
296            (mime-show-echo-buffer "No method are specified for %s\n"
297                                   (mime-entity-type/subtype entity))
298            ))
299     ))
300
301
302 ;;; @ external decoder
303 ;;;
304
305 (defvar mime-mailcap-method-filename-alist nil)
306
307 (defun mime-activate-mailcap-method (entity situation)
308   (let ((method (cdr (assoc 'method situation)))
309         (name (mime-entity-safe-filename entity)))
310     (setq name
311           (if (and name (not (string= name "")))
312               (expand-file-name name temporary-file-directory)
313             (make-temp-name
314              (expand-file-name "EMI" temporary-file-directory))
315             ))
316     (mime-write-entity-content entity name)
317     (message "External method is starting...")
318     (let ((process
319            (let ((command
320                   (mailcap-format-command
321                    method
322                    (cons (cons 'filename name) situation))))
323              (start-process command mime-echo-buffer-name
324                             shell-file-name shell-command-switch command)
325              )))
326       (set-alist 'mime-mailcap-method-filename-alist process name)
327       (set-process-sentinel process 'mime-mailcap-method-sentinel)
328       )
329     ))
330
331 (defun mime-mailcap-method-sentinel (process event)
332   (let ((file (cdr (assq process mime-mailcap-method-filename-alist))))
333     (if (file-exists-p file)
334         (delete-file file)
335       ))
336   (remove-alist 'mime-mailcap-method-filename-alist process)
337   (message (format "%s %s" process event)))
338
339 (defvar mime-echo-window-is-shared-with-bbdb
340   (module-installed-p 'bbdb)
341   "*If non-nil, mime-echo window is shared with BBDB window.")
342
343 (defvar mime-echo-window-height
344   (function
345    (lambda ()
346      (/ (window-height) 5)
347      ))
348   "*Size of mime-echo window.
349 It allows function or integer.  If it is function,
350 `mime-show-echo-buffer' calls it to get height of mime-echo window.
351 Otherwise `mime-show-echo-buffer' uses it as height of mime-echo
352 window.")
353
354 (defun mime-show-echo-buffer (&rest forms)
355   "Show mime-echo buffer to display MIME-playing information."
356   (get-buffer-create mime-echo-buffer-name)
357   (let ((the-win (selected-window))
358         (win (get-buffer-window mime-echo-buffer-name)))
359     (unless win
360       (unless (and mime-echo-window-is-shared-with-bbdb
361                    (condition-case nil
362                        (setq win (get-buffer-window bbdb-buffer-name))
363                      (error nil)))
364         (select-window (get-buffer-window (or mime-preview-buffer
365                                               (current-buffer))))
366         (setq win (split-window-vertically
367                    (- (window-height)
368                       (if (functionp mime-echo-window-height)
369                           (funcall mime-echo-window-height)
370                         mime-echo-window-height)
371                       )))
372         )
373       (set-window-buffer win mime-echo-buffer-name)
374       )
375     (select-window win)
376     (goto-char (point-max))
377     (if forms
378         (insert (apply (function format) forms))
379       )
380     (select-window the-win)
381     ))
382
383
384 ;;; @ file name
385 ;;;
386
387 (defvar mime-view-file-name-char-regexp "[A-Za-z0-9+_-]")
388
389 (defvar mime-view-file-name-regexp-1
390   (concat mime-view-file-name-char-regexp "+\\."
391           mime-view-file-name-char-regexp "+"))
392
393 (defvar mime-view-file-name-regexp-2
394   (concat (regexp-* mime-view-file-name-char-regexp)
395           "\\(\\." mime-view-file-name-char-regexp "+\\)*"))
396
397 (defun mime-entity-safe-filename (entity)
398   (let ((filename
399          (or (mime-entity-filename entity)
400              (let ((subj
401                     (or (mime-read-field 'Content-Description entity)
402                         (mime-read-field 'Subject entity))))
403                (if (and subj
404                         (or (string-match mime-view-file-name-regexp-1 subj)
405                             (string-match mime-view-file-name-regexp-2 subj)))
406                    (substring subj (match-beginning 0)(match-end 0))
407                  )))))
408     (if filename
409         (replace-as-filename filename)
410       )))
411
412
413 ;;; @ file extraction
414 ;;;
415
416 (defun mime-save-content (entity situation)
417   (let* ((name (mime-entity-safe-filename entity))
418          (filename (if (and name (not (string-equal name "")))
419                        (expand-file-name name
420                                          (save-window-excursion
421                                            (call-interactively
422                                             (function
423                                              (lambda (dir)
424                                                (interactive "DDirectory: ")
425                                                dir)))))
426                      (save-window-excursion
427                        (call-interactively
428                         (function
429                          (lambda (file)
430                            (interactive "FFilename: ")
431                            (expand-file-name file)))))))
432          )
433     (if (file-exists-p filename)
434         (or (yes-or-no-p (format "File %s exists. Save anyway? " filename))
435             (error "")))
436     (mime-write-entity-content entity filename)
437     ))
438
439
440 ;;; @ file detection
441 ;;;
442
443 (defvar mime-magic-type-alist
444   '(("^\377\330\377[\340\356]..JFIF"    image jpeg)
445     ("^\211PNG"                         image png)
446     ("^GIF8[79]"                        image gif)
447     ("^II\\*\000"                       image tiff)
448     ("^MM\000\\*"                       image tiff)
449     ("^MThd"                            audio midi)
450     ("^\000\000\001\263"                video mpeg)
451     )
452   "*Alist of regexp about magic-number vs. corresponding media-types.
453 Each element looks like (REGEXP TYPE SUBTYPE).
454 REGEXP is a regular expression to match against the beginning of the
455 content of entity.
456 TYPE is symbol to indicate primary type of media-type.
457 SUBTYPE is symbol to indicate subtype of media-type.")
458
459 (defun mime-detect-content (entity situation)
460   (let (type subtype)
461     (let ((mdata (mime-entity-content entity))
462           (rest mime-magic-type-alist))
463       (while (not (let ((cell (car rest)))
464                     (if cell
465                         (if (string-match (car cell) mdata)
466                             (setq type (nth 1 cell)
467                                   subtype (nth 2 cell))
468                           )
469                       t)))
470         (setq rest (cdr rest))))
471     (if type
472         (mime-play-entity
473          entity
474          (put-alist 'type type
475                     (put-alist 'subtype subtype
476                                (del-alist 'method
477                                           (copy-alist situation))))
478          nil
479          (cdr (assq 'ignore-examples situation))
480          'mime-detect-content)
481       ))
482   )
483
484
485 ;;; @ mail/news message
486 ;;;
487
488 (defun mime-preview-quitting-method-for-mime-show-message-mode ()
489   "Quitting method for mime-view.
490 It is registered to variable `mime-preview-quitting-method-alist'."
491   (let ((mother mime-mother-buffer)
492         (win-conf mime-preview-original-window-configuration)
493         )
494     (kill-buffer mime-raw-buffer)
495     (mime-preview-kill-buffer)
496     (set-window-configuration win-conf)
497     (pop-to-buffer mother)
498     ))
499
500 (defun mime-view-message/rfc822 (entity situation)
501   (let* ((new-name
502           (format "%s-%s" (buffer-name) (mime-entity-number entity)))
503          (mother mime-preview-buffer)
504          (children (car (mime-entity-children entity))))
505     (set-buffer (get-buffer-create new-name))
506     (erase-buffer)
507     (insert-buffer-substring (mime-entity-buffer children)
508                              (mime-entity-point-min children)
509                              (mime-entity-point-max children))
510     (setq mime-message-structure children)
511     (setq major-mode 'mime-show-message-mode)
512     (mime-view-buffer (current-buffer) nil mother
513                       nil (if (mime-entity-cooked-p entity) 'cooked))
514     ))
515
516
517 ;;; @ message/partial
518 ;;;
519
520 (defun mime-store-message/partial-piece (entity cal)
521   (goto-char (mime-entity-point-min entity))
522   (let* ((root-dir
523           (expand-file-name
524            (concat "m-prts-" (user-login-name)) temporary-file-directory))
525          (id (cdr (assoc "id" cal)))
526          (number (cdr (assoc "number" cal)))
527          (total (cdr (assoc "total" cal)))
528          file
529          (mother mime-preview-buffer)
530          )
531     (or (file-exists-p root-dir)
532         (make-directory root-dir)
533         )
534     (setq id (replace-as-filename id))
535     (setq root-dir (concat root-dir "/" id))
536     (or (file-exists-p root-dir)
537         (make-directory root-dir)
538         )
539     (setq file (concat root-dir "/FULL"))
540     (if (file-exists-p file)
541         (let ((full-buf (get-buffer-create "FULL"))
542               (pwin (or (get-buffer-window mother)
543                         (get-largest-window)))
544               )
545           (save-window-excursion
546             (set-buffer full-buf)
547             (erase-buffer)
548             (as-binary-input-file (insert-file-contents file))
549             (setq major-mode 'mime-show-message-mode)
550             (mime-view-buffer (current-buffer) nil mother)
551             )
552           (set-window-buffer pwin
553                              (save-excursion
554                                (set-buffer full-buf)
555                                mime-preview-buffer))
556           (select-window pwin)
557           )
558       (setq file (concat root-dir "/" number))
559       (mime-write-entity-body entity file)
560       (let ((total-file (concat root-dir "/CT")))
561         (setq total
562               (if total
563                   (progn
564                     (or (file-exists-p total-file)
565                         (save-excursion
566                           (set-buffer
567                            (get-buffer-create mime-temp-buffer-name))
568                           (erase-buffer)
569                           (insert total)
570                           (write-region (point-min)(point-max) total-file)
571                           (kill-buffer (current-buffer))
572                           ))
573                     (string-to-number total)
574                     )
575                 (and (file-exists-p total-file)
576                      (save-excursion
577                        (set-buffer (find-file-noselect total-file))
578                        (prog1
579                            (and (re-search-forward "[0-9]+" nil t)
580                                 (string-to-number
581                                  (buffer-substring (match-beginning 0)
582                                                    (match-end 0)))
583                                 )
584                          (kill-buffer (current-buffer))
585                          )))
586                 )))
587       (if (and total (> total 0))
588           (catch 'tag
589             (save-excursion
590               (set-buffer (get-buffer-create mime-temp-buffer-name))
591               (let ((full-buf (current-buffer)))
592                 (erase-buffer)
593                 (let ((i 1))
594                   (while (<= i total)
595                     (setq file (concat root-dir "/" (int-to-string i)))
596                     (or (file-exists-p file)
597                         (throw 'tag nil)
598                         )
599                     (as-binary-input-file (insert-file-contents file))
600                     (goto-char (point-max))
601                     (setq i (1+ i))
602                     ))
603                 (as-binary-output-file
604                  (write-region (point-min)(point-max)
605                                (expand-file-name "FULL" root-dir)))
606                 (let ((i 1))
607                   (while (<= i total)
608                     (let ((file (format "%s/%d" root-dir i)))
609                       (and (file-exists-p file)
610                            (delete-file file)
611                            ))
612                     (setq i (1+ i))
613                     ))
614                 (let ((file (expand-file-name "CT" root-dir)))
615                   (and (file-exists-p file)
616                        (delete-file file)
617                        ))
618                 (save-window-excursion
619                   (setq major-mode 'mime-show-message-mode)
620                   (mime-view-buffer (current-buffer) nil mother)
621                   )
622                 (let ((pwin (or (get-buffer-window mother)
623                                 (get-largest-window)))
624                       (pbuf (save-excursion
625                               (set-buffer full-buf)
626                               mime-preview-buffer)))
627                   (set-window-buffer pwin pbuf)
628                   (select-window pwin)
629                   )))))
630       )))
631
632
633 ;;; @ message/external-body
634 ;;;
635
636 (defvar mime-raw-dired-function
637   (if (and (>= emacs-major-version 19) window-system)
638       (function dired-other-frame)
639     (function mime-raw-dired-function-for-one-frame)
640     ))
641
642 (defun mime-raw-dired-function-for-one-frame (dir)
643   (let ((win (or (get-buffer-window mime-preview-buffer)
644                  (get-largest-window))))
645     (select-window win)
646     (dired dir)
647     ))
648
649 (defun mime-view-message/external-anon-ftp (entity cal)
650   (let* ((site (cdr (assoc "site" cal)))
651          (directory (cdr (assoc "directory" cal)))
652          (name (cdr (assoc "name" cal)))
653          (pathname (concat "/anonymous@" site ":" directory)))
654     (message (concat "Accessing " (expand-file-name name pathname) " ..."))
655     (funcall mime-raw-dired-function pathname)
656     (goto-char (point-min))
657     (search-forward name)
658     ))
659
660 (defvar mime-raw-browse-url-function mime-browse-url-function)
661
662 (defun mime-view-message/external-url (entity cal)
663   (let ((url (cdr (assoc "url" cal))))
664     (message (concat "Accessing " url " ..."))
665     (funcall mime-raw-browse-url-function url)))
666
667
668 ;;; @ rot13-47
669 ;;;
670
671 (defun mime-view-caesar (entity situation)
672   "Internal method for mime-view to display ROT13-47-48 message."
673   (let* ((new-name (format "%s-%s" (buffer-name)
674                            (mime-entity-number entity)))
675          (mother mime-preview-buffer))
676     (let ((pwin (or (get-buffer-window mother)
677                     (get-largest-window)))
678           (buf (get-buffer-create new-name)))
679       (set-window-buffer pwin buf)
680       (set-buffer buf)
681       (select-window pwin)
682       )
683     (setq buffer-read-only nil)
684     (erase-buffer)
685     (mime-insert-text-content entity)
686     (mule-caesar-region (point-min) (point-max))
687     (set-buffer-modified-p nil)
688     (set-buffer mother)
689     (view-buffer new-name)
690     ))
691
692
693 ;;; @ end
694 ;;;
695
696 (provide 'mime-play)
697
698 (let* ((file mime-acting-situation-examples-file)
699        (buffer (get-buffer-create " *mime-example*")))
700   (if (file-readable-p file)
701       (unwind-protect
702           (save-excursion
703             (set-buffer buffer)
704             (erase-buffer)
705             (insert-file-contents file)
706             (eval-buffer)
707             ;; format check
708             (condition-case nil
709                 (let ((i 0))
710                   (while (and (> (length mime-acting-situation-example-list)
711                                  mime-acting-situation-example-list-max-size)
712                               (< i 16))
713                     (mime-reduce-acting-situation-examples)
714                     (setq i (1+ i))
715                     ))
716               (error (setq mime-acting-situation-example-list nil)))
717             )
718         (kill-buffer buffer))))
719
720 ;;; mime-play.el ends here