;;; select-xface.el --- Select X-Faces graphically

; Created:    <97/08/22 12:49:31 teranisi>
; Time-stamp: <2002-02-17 23:46:09 teranisi>

;; Copyright (C) 1997-2002 Yuuichi Teranishi

;; Author: Yuuichi Teranishi <teranisi@gohome.org>
;; Maintainer: Yuuichi Teranishi <teranisi@gohome.org>
;; Version: 0.15
;; Target: Emacs, Mule, XEmacs

;; Select X-Face is free software; you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation; either version 2, or
;; any later version.

;; Select X-Face is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;; GNU General Public License for more details.

;; You should have received a copy of the GNU General Public License
;; along with GNU Emacs; see the file COPYING.  If not, write to the
;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
;; Boston, MA 02111-1307, USA.

;; Setup:
;;
;; (autoload 'select-xface "select-xface" "Select X-Face" t)
;;
;; For Mew:
;; (add-hook 'mew-draft-mode-hook
;;	  (lambda ()
;;	    (define-key (current-local-map) "\C-c\C-x"
;;	      'select-xface)))
;;
;; For Gnus:
;; (add-hook 'gnus-message-setup-hook
;;	  (lambda ()
;;	    (define-key (current-local-map) "\C-x4x"
;;	      'select-xface)))
;; For mh-e:
;; (add-hook 'mh-letter-mode-hook
;;	  (lambda ()
;;	    (define-key (current-local-map) "\C-x4x"
;;	      'select-xface)))
;; For MAIL, RMAIL, VM, cmail, Wanderlust:
;; (add-hook 'mail-mode-hook
;;	  (lambda ()
;;	    (define-key (current-local-map) "\C-x4x"
;;	      'select-xface)))

;;; Commentary:
;; 

;;; Code:

(defconst select-xface-appname "Select X-Face")
(defconst select-xface-version-number "v0.15")
(defconst select-xface-codename "Live And Let Die")

(defconst select-xface-version
  (concat select-xface-appname " "
	  select-xface-version-number " - \""
	  select-xface-codename "\""))

;;
;; Users may set these variables
;;
(defvar select-xface-directory "~/.xfaces"
  "*files or subdirectories in this directory become the candidates.")

(defvar select-xface-height 5
  "*height of the popup buffer.")

(defvar select-xface-field-insert-before "^X-Mailer:\\|^User-Agent:\\|^--"
  "*insert xface field before this regexp.")

(defvar select-xface-mode-hook nil
  "*hooks to be called after select-xface-mode starts.")

(defvar select-xface-insert-hook nil
  "*hooks to be called after xface is inserted.")

(defvar select-xface-candidate-regexp "^[^.].*"
  "*only file/directory names containing that regexp are adopted.")

(defvar select-xface-gzip-program "gzip"
  "*gzip executable.")

(defvar select-xface-add-x-face-version-header nil
  "*insert X-Face-Version header.")

(defvar select-xface-header-separator-regexp "\\(^--.*$\\)\\|\\(\n\n\\)"
  "*header separator. (regexp)")

(defvar select-xface-display-func
  (function
   (lambda (beg end)
     (cond
      ((featurep 'xemacs)
       (require 'highlight-headers)
       (let ((highlight-headers-hack-x-face-p t)
	     (x-face-xmas-like-highlight-headers nil))
	 (highlight-headers beg end nil)))
      ((fboundp 'x-face-decode-message-header)
       (x-face-decode-message-header beg end))
      (t nil))))
  "xface display function.")

;;
;; No setting is needed for these variables.
;;
(defvar select-xface-candidate-list nil)
(defvar select-xface-face-list nil)
(defvar select-xface-current-list-pos 0)
(defvar select-xface-mode-map nil)
(defvar select-xface-parent-buffer nil)
(defvar select-xface-orig-window-config nil)
(defvar select-xface-popup-menu nil)
(defconst select-xface-buffer select-xface-appname)

(defmacro select-xface-header-end ()
  (` (save-excursion
       (goto-char (point-min))
       (if (re-search-forward select-xface-header-separator-regexp nil t)
	   (point)))))

(if select-xface-mode-map
    nil
  (setq select-xface-mode-map (make-sparse-keymap))
  (define-key select-xface-mode-map "p"        'select-xface-prev-face)
  (define-key select-xface-mode-map "\C-p"     'select-xface-prev-face)
  (define-key select-xface-mode-map [up]       'select-xface-prev-face)
  (define-key select-xface-mode-map "n"        'select-xface-next-face)
  (define-key select-xface-mode-map "\C-n"     'select-xface-next-face)
  (define-key select-xface-mode-map [down]     'select-xface-next-face)
  (define-key select-xface-mode-map "\C-m"     'select-xface-out)
  (define-key select-xface-mode-map "o"        'select-xface-out)
  (define-key select-xface-mode-map "q"        'select-xface-exit)
  (define-key select-xface-mode-map "\C-g"     'select-xface-exit)
; (define-key select-xface-mode-map [?a up]    'select-xface-append-out-top)
  (define-key select-xface-mode-map [?a right] 'select-xface-append-out-last)
; (define-key select-xface-mode-map [?a down]  'select-xface-append-out-bottom)
  (define-key select-xface-mode-map [?a left]  'select-xface-append-out-first)
  (define-key select-xface-mode-map " "        'select-xface-append-out-last)
  (define-key select-xface-mode-map "r"        'select-xface-rebuild-face-list)
  )

(defun select-xface-make-popup-menu ()
  "define popup menu."
  (if (not select-xface-popup-menu)
      (easy-menu-define
       select-xface-popup-menu
       select-xface-mode-map "Menu for Select X-Face"
       '("Select X-Face"
	 ["Prev"   select-xface-prev-face       t]
	 ["Next"   select-xface-next-face       t]
	 ["Output" select-xface-out             t]
	 ["Append" select-xface-append-out-last t]
	 "----"
	 ["Quit"   select-xface-exit            t]
	 )
       )
    )
  (easy-menu-add select-xface-popup-menu))
  

(defun select-xface-mode ()
;;a up    select-xface-append-out-top    append the current as the top face
;;a down  select-xface-append-out-bottom append the current as the bottom face
"Major mode for select and insert X-Face: field in the current draft buffer.

RET     select-xface-out               output the current face
o       select-xface-out               output the current face
C-n     select-xface-next-face         display the next candidate
n       select-xface-next-face         display the next candidate
C-p     select-xface-prev-face         display the previous candidate
p       select-xface-prev-face         display the previous candidate
a right select-xface-append-out-last   append the current as the last face
a left  select-xface-append-out-first  append the current as the first face
r       select-xface-rebuild-face-list rebuild face list
SPC     select-xface-append-out-last   append the current as the last face
C-g     select-xface-exit              quit selecting face
q       select-xface-exit              quit selecting face
"
  (interactive)
  (setq major-mode 'select-xface-mode)
  (setq mode-name select-xface-appname)
  (use-local-map select-xface-mode-map)
  (make-local-variable 'tab-width)
  (setq tab-width 8)
  (select-xface-make-popup-menu)
  (if (featurep 'xemacs)
      (set-specifier text-cursor-visible-p (cons (current-buffer) nil)))
  (run-hooks 'select-xface-mode-hook))

(defun select-xface-delete-all-xface-related-fields ()
  "delete all xface related fields in the current buffer."
  (save-excursion
    (goto-char (point-min))
    (while (re-search-forward
	    "^\\(X-Face.*:\\) *\\(.*\\(\n[ \t].*\\)*\\)\n"
	    (select-xface-header-end) t)
      (delete-region (match-beginning 0) (match-end 0))
      (goto-char (point-min)))))


(defun select-xface-collect-xface-related-fields ()
  "collect the xface related fields in the current buffer."
  (let ((end (select-xface-header-end))
	ret)
    (save-excursion
      (goto-char (point-min))
      (while (re-search-forward
	      "\\(^\\(X-Face-Type:\\)[ \t]*\\(.*\\(\n[ \t].*\\)*\\)\n\\)\\|\\(^\\(X-Face[-0-9]*:\\)[ \t]*\\(.*\\(\n[ \t].*\\)*\\)\n\\)" end t)
	(setq ret (concat ret
			  (buffer-substring (match-beginning 0)
					    (match-end 0)))))
      (if ret
	  (let ((ret-len (length ret)))
	    (if (string= (substring ret (- ret-len 1) ret-len) "\n")
		(setq ret (substring ret 0 (- ret-len 1)))))))
    ret))

(defun select-xface-append-out-last ()
  "append the current face as the last face."
  (interactive)
  (setq this-command 'select-xface-out)
  (select-xface-insert (select-xface-make-out-xface)
		       'last)
  )

(defun select-xface-append-out-first ()
  "append the current face as the frst face."
  (interactive)
  (setq this-command 'select-xface-out)
  (select-xface-insert (select-xface-make-out-xface)
		       'first))

(defun select-xface-append-out-top ()
  "append the current face as the top face."
  (interactive)
  (select-xface-insert (select-xface-make-out-xface)
		       'top))

(defun select-xface-append-out-bottom ()
  "append the current face as the bottom face."
  (interactive)
  (select-xface-insert (select-xface-make-out-xface)
		       'bottom))

(defun select-xface-make-append-xface (current-xface
				       out-xface
				       direction)
  "append the current face in the specified direction."
  (interactive)
  (let (insert-str)
    (cond
     ((eq direction 'top)
      (setq insert-str
	    (concat "X-Face-Type: geometry=1x2\n"
		    out-xface
		    current-xface "\n")))
     ((eq direction 'first)
      (setq insert-str
	    (concat ;; "X-Face-Type: geometry=2x1\n"
		    out-xface "\n"
		    current-xface)))
     ((eq direction 'bottom)
      (setq insert-str
	    (concat "X-Face-Type: geometry=1x2\n"
		    (if current-xface (concat current-xface "\n"))
		    out-xface)))
     (t ;; last or other
      (setq insert-str
	    (concat ;; "X-Face-Type: geometry=2x1\n"
		    (if current-xface (concat current-xface "\n"))
		    out-xface))))
    insert-str
   ))

(defun select-xface-make-out-xface ()
  "make output xface string from select-xface buffer."
  (nth select-xface-current-list-pos select-xface-face-list))

(defun select-xface-out ()
  "output the current face."
  (interactive)
  (select-xface-insert (select-xface-make-out-xface)))

(defun select-xface-insert (out-xface &optional append-direction)
  "insert the xface into the draft buffer."
  (save-window-excursion
    (delete-window)
    (let ((inhibit-read-only t)
	  current-xface beg end
	  )
      (save-excursion
	(set-buffer select-xface-parent-buffer)
	(if append-direction
	    (setq current-xface
		  (select-xface-collect-xface-related-fields)))
	(select-xface-delete-all-xface-related-fields)
	(goto-char (point-min))
	(re-search-forward select-xface-field-insert-before end t)
	(beginning-of-line)
	(setq beg (point))
	(if append-direction
	    (insert (select-xface-make-append-xface current-xface
						    out-xface
						    append-direction))
	  (insert out-xface))
	(insert "\n")
	(put-text-property beg (point) 'invisible nil)
	(if (and (fboundp 'x-face-insert-version-header)
		 x-face-add-x-face-version-header)
	    (progn
	      (setq beg (point))
	      (x-face-insert-version-header)
	      (if (not (eq beg (point)))
		  (progn
		    (put-text-property beg (point) 'invisible nil)
		    (insert (concat "                with "
				    select-xface-version "\n")))))
	  (if select-xface-add-x-face-version-header
	      (insert (concat "X-Face-Version: " select-xface-version "\n"))))
	(run-hooks 'select-xface-insert-hook)
	)
      )
    )
  (select-xface-exit))

(defun select-xface-prev-face ()
  "display previous candidate."
  (interactive)
  (if (= 0 select-xface-current-list-pos)
      (select-xface-set-list-pos (1- (length select-xface-face-list)))
    (select-xface-set-list-pos (1- select-xface-current-list-pos))))

(defun select-xface-next-face ()
  "display next candidate."
  (interactive)
  (if (= select-xface-current-list-pos (1- (length select-xface-face-list)))
      (select-xface-set-list-pos 0)
    (select-xface-set-list-pos (1+ select-xface-current-list-pos))))

(defun select-xface-set-invisible (string)
  "set string invisible."
  (save-excursion
    (goto-char (point-min))
    (while (re-search-forward (concat "\\(" string "\\)") nil t)
      (put-text-property
       (match-beginning 1) (match-end 1) 'invisible t))))

(defun select-xface-set-list-pos (pos)
  "display nth candidate in the popup buffer."
  (setq select-xface-current-list-pos pos)
;  (message (format "%d th entry." pos))
  (let ((buffer-read-only nil)
	(entry (nth pos select-xface-face-list))
	(xface-name (nth pos select-xface-candidate-list))
	)
    (setq xface-name (if xface-name xface-name "No name"))
    (erase-buffer)
    (if (not entry)
	()
      (if (string-match "^X-Face-Type: .*\n" entry)
	  (progn
	    (insert "From: \n")
	    (insert entry)
	    (insert "\n")
	    (funcall select-xface-display-func (point-min) (point-max))
	    (goto-char (point-min))
	    (while (re-search-forward "^X-Face-Type: .*\n" nil t)
	      (delete-region (match-beginning 0) (match-end 0)))
	    (re-search-backward "From:" nil t)
	    (select-xface-set-invisible "X-Face:")
	    (select-xface-set-invisible "From:")
	    (select-xface-set-invisible "     ")
	    )
	(insert "From: \n")
	(insert entry)
	(insert "\n")
	(funcall select-xface-display-func (point-min) (point-max))
	(goto-char (point-min))
	(select-xface-set-invisible "From:")
	(select-xface-set-invisible "     "))
      (goto-char (point-max))
      (if (featurep 'xemacs)
	  (goto-char (point-min))
	(while (char-equal (char-before (point)) ?\n)
	  (backward-char 1)))
      (set-buffer-modified-p nil)
      (rename-buffer (concat select-xface-appname "(" xface-name ")"))
      (setq select-xface-buffer (concat
				 select-xface-appname "(" xface-name ")"))
      )))

(defun select-xface-check-rgb (list)
  "check if files in the path are rgb."
  (let ((tmplist list))
    (setq tmplist (delete "red" tmplist))
    (setq tmplist (delete "green" tmplist))
    (setq tmplist (delete "blue" tmplist))
    (not tmplist)))

(defun select-xface-make-candidate-list (path)
  "make file list in the path."
  (let (ret files attr)
    (setq ret
	  (directory-files path nil select-xface-candidate-regexp nil))
    (setq ret (delete "." ret))
    (setq ret (delete ".." ret))
    (setq files ret)
    (while files
      (setq attr (car files))
      (if (car (file-attributes (expand-file-name attr path)))
	  (setq ret (delete attr ret)))
      (setq files (cdr files)))
    ret)
  )

(defun select-xface-reduce-needless-character-in-buffer ()
  "reduce needless character for xface in the buffer."
  (if (= 0 (buffer-size))
      ()
    ;; reduce a space character in the beginning of the buffer.
    (while (char-equal (char-after (point-min)) ? )
      (progn
	(goto-char (point-min))
	(delete-char 1)))
    ;; reduce a newline character in the end of the buffer.
    (while (char-equal (char-before (point-max)) ?\n)
      (progn
	(goto-char (1- (point-max)))
	(delete-char 1)))))
  
(defun select-xface-reduce-needless-character-in-string (string)
  "reduce needless character for xface in the string."
  (let ((strlen (length string))
	(ret-string string))
    (if (= 0 strlen)
	()
      ;; reduce a newline character in the end of the string.
      (while (and (not (= strlen 0))
		  (string= (substring ret-string (- strlen 1) strlen) "\n"))
	(setq ret-string (substring ret-string 0 (- strlen 1)))
	(setq strlen (- strlen 1)))
      ;; reduce a space character in the beginning of the string.
      (while (and (not (= strlen 0))
		  (string= (substring ret-string 0 1) " "))
	(setq ret-string (substring ret-string 1 strlen))
	(setq strlen (- strlen 1))))
    ret-string
    ))

(defun select-xface-make-xface-string (candidate-name directory)
  "make xface string from face file."
  (save-excursion
    (let ((tmp-buffer (get-buffer-create (concat
					  "*Select-X-Face-"
					  (expand-file-name candidate-name
							    directory)
					  "-tmp*"
					  )))
	  (coding-system-for-read 'binary)
	  (coding-system-for-write 'binary)
	  format-alist jka-compr-compression-info-list
	  child-clist ret-string)
      (set-buffer tmp-buffer)
      (if (not (file-directory-p
		(expand-file-name candidate-name
				  directory)))
	  (progn
	    (if (string-match "\\.xbm\\(\\.gz\\)?$" candidate-name)
		;;
		;; use X-Face utility for xbm or gzipped xbm file.
		;;
		(if (fboundp 'x-face-insert)
		    (let (x-face-add-x-face-version-header)
		      (condition-case ()
			  (x-face-insert
			   (expand-file-name candidate-name
					     select-xface-directory))
			(error
			 (setq select-xface-candidate-list
			       (delete candidate-name
				       select-xface-candidate-list))
			 (message (format
				   "%s has illegal contents(ignored)."
				   candidate-name))))
		      (select-xface-reduce-needless-character-in-buffer)
		      )
		  (message "xbm file is not supported."))
	      ;;
	      ;; xface file.
	      ;;
	      (insert-file-contents
	       (expand-file-name candidate-name directory))
	      (if (looking-at "\x1f\x8b") ; gzipped?
		  (call-process-region
		   (point-min) (point-max)
		   select-xface-gzip-program t t nil "-cd"))
	      (select-xface-reduce-needless-character-in-buffer)
	      (goto-char (point-min))
	      (if (not (re-search-forward "X-Face:" nil t))
		  (insert "X-Face: ")))
	    (setq ret-string
		  (select-xface-reduce-needless-character-in-string
		   (concat
		    (buffer-substring (point-min)
				      (point-max))))))
	;;
	;; recursive subdirectory processing.
	;;
	(setq child-clist (select-xface-make-candidate-list
			   (expand-file-name candidate-name
					     directory)))
	(if (select-xface-check-rgb child-clist)
	    (progn
	      (insert )
	      (setq ret-string
		    (concat "X-Face-Type: RGB; geometry=1x1\n"
			    (select-xface-make-xface-string
			     "red"
			     (expand-file-name candidate-name directory))))
	      (setq ret-string
		    (concat ret-string "\n"
			    (select-xface-make-xface-string
			     "green"
			     (expand-file-name candidate-name directory))))
	      (setq ret-string
		    (concat ret-string "\n"
			    (select-xface-make-xface-string
			     "blue"
			     (expand-file-name candidate-name directory)))))
;;      (insert (format "X-Face-Type: geometry=%dx1\n"
;;		      (length child-flist)))
	  ;; insert subdirectory candidates recursively.
	  (let (cur-cname)
	    (while child-clist
	      (setq cur-cname (car child-clist))
	      (setq ret-string
		    (concat ret-string
			    (select-xface-make-xface-string
			     cur-cname
			     (expand-file-name candidate-name directory))
			    "\n"
			    ))
	      (setq child-clist (cdr child-clist)))
	    )
	  ))
      (setq ret-string (select-xface-reduce-needless-character-in-string
			ret-string))
      (if (string= ret-string "") (setq ret-string nil))
      (kill-buffer tmp-buffer)
      ret-string
      )))

(defun select-xface-add-face-to-face-list (face &optional name)
  "add face to select-xface-face-list. returns pos."
  (let ((flist select-xface-face-list)
	(found nil)
	(pos 0)
	)
    (catch 'loop
      (while flist
	(if (string= face (car flist))
	    (progn
	      (setq found t)
	      (throw 'loop nil))
	  (setq flist (cdr flist))
	  (setq pos (1+ pos))
	  )))
    (if (and face (not found))
	(setq select-xface-face-list (append select-xface-face-list
					     (list face)))
      (if name
	  (progn
	    (setq select-xface-candidate-list
		  (delete name
			  select-xface-candidate-list))
	    (message "Same candidate already exists!"))))
    (if (not face) (setq pos 0))
    pos))

(defun select-xface-rebuild-face-list ()
  "rebuild face list from directory."
  (interactive)
  (setq select-xface-candidate-list nil)
  (setq select-xface-face-list nil)
  (select-xface-make-face-list)
  (if select-xface-face-list
      (select-xface-set-list-pos 0)
    (message "No X-Face candidates.")
    (select-xface-exit)
    )
  )

(defun select-xface-make-face-list ()
  "make face list from directory."
  ;; if select-xface-candidate-list is nil, all files or directories
  ;; that contain select-xface-candidate-regexp
  ;; in the select-xface-directory became the candidates.
  (if (not select-xface-candidate-list)
      (setq select-xface-candidate-list
	    (select-xface-make-candidate-list select-xface-directory)))
  ;; make face list from candidate list.
  (if (not select-xface-face-list)
      (select-xface-make-face-list-from-candidate-list
       select-xface-candidate-list)))
  
(defun select-xface-make-face-list-from-candidate-list (candidate-list)
  "make list of faces."
  (save-excursion
    (let ((ret-list nil)
	  (clist candidate-list))
      (while clist
	(select-xface-add-face-to-face-list
	 (select-xface-make-xface-string
	  (car clist) select-xface-directory)
	 (car clist))
	(setq clist (cdr clist)))
      ret-list ;; return value
      )))
  
(defun select-xface-pop-to-buffer (buf)
  "split current window."
  (split-window-vertically)
  (other-window 1)
  (switch-to-buffer buf))

(defun select-xface ()
  "select xfaces graphically."
  (interactive)
  (if (not select-xface-display-func)
      (message "cannot display X-Face in your environment.")
    (setq select-xface-parent-buffer (buffer-name))
    (select-xface-make-face-list)
  ;; add current face to candidate list.
    (let (pos)
      (setq pos (select-xface-add-face-to-face-list
		 (select-xface-collect-xface-related-fields)))
      (if select-xface-face-list
	  (progn
	    (setq select-xface-orig-window-config
		  (current-window-configuration))
	    (if (get-buffer select-xface-buffer)
		(select-xface-pop-to-buffer select-xface-buffer)
	      (let* ()
		(select-xface-pop-to-buffer select-xface-buffer)
		(enlarge-window (- select-xface-height (window-height)))
		(select-xface-set-list-pos pos)
		(toggle-read-only)))
	    (select-xface-mode))
	(message "No X-Face candidates."))
      ))
  )

(defun select-xface-exit ()
  "quit selecting xface."
  (interactive)
  (pop-to-buffer select-xface-parent-buffer)
  (set-window-configuration select-xface-orig-window-config)
  (kill-buffer select-xface-buffer)
)

(provide 'select-xface)
;;; select-xface.el ends here
