;;; xwem-launcher.el --- Program launcher for XWEM.

;; Copyright (C) 2003 by Free Software Foundation, Inc.

;; Author: Zajcev Evgeny <zevlg@yandex.ru>
;; Created: Thu Dec  4 16:32:11 MSK 2003
;; Keywords: xwem, xlib
;; X-CVS: $Id: xwem-launcher.el,v 1.5 2004/05/12 16:14:32 lg Exp $

;; This file is part of XWEM.

;; XWEM 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 (at your option)
;; any later version.

;; XWEM 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 XEmacs; see the file COPYING.  If not, write to the Free
;; Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
;; 02111-1307, USA.

;;; Synched up with: Not in FSF

;;; Commentary:

;; External programs launcher for XWEM.

;;; TODO:
;;    * Assume argument in quotas as single argument, i.e. do not make
;;      splitting inside quotas.

;;; Code:

(eval-and-compile
;  (require 'completer)
  (require 'comint))

(autoload 'executable-find "executable")

(defgroup xwem-launcher nil
  "Group to customize XWEM's programs launcher."
  :prefix "xwem-"
  :group 'xwem)

(defcustom xwem-launcher-beep-done nil
  "*Non-nil mean beep when execution of program done.
Beep performed using \(xwem-play-sound 'ready\)."
  :type 'boolean
  :group 'xwem-launcher)

;;;###autoload
(defcustom xwem-launcher-function 'xwem-execute-program
  "Function to be used to execute external program."
  :type 'function
  :group 'xwem-launcher)

(defcustom xwem-launcher-abbrev-table nil
  "Abbrev table used by `xwem-launcher-query'."
  :type 'list
  :group 'xwem-launcher)

(defcustom xwem-launcher-history nil
  "History of `xwem-launcher-query'ies."
  :type 'list
  :group 'xwem-launcher)

(defcustom xwem-launcher-split-type 'xwem-execute-program-other-win-vertical
  "Window split type, when launching program in other window."
  :type '(choice (const :tag "Horizontal" xwem-execute-program-other-win-horizontal)
		 (const :tag "Vertical" xwem-execute-program-other-win-vertical))
  :group 'xwem-launcher)

(defcustom xwem-launcher-frame-type 'xwem-execute-program-other-frame
  "Type of frame, when launching program in other frame."
  :type '(choice (const :tag "Normal frame" xwem-execute-program-other-frame)
		 (const :tag "Embedded frame" xwem-execute-program-embedded-frame))
  :group 'xwem-launcher)

(defcustom xwem-xterm-program "xterm"
  "Name of terminal emulator program."
  :type 'string
  :group 'xwem-launcher)

(defcustom xwem-xterm-font-argument "-fn"
  "Program key to specify in order to change font."
  :type 'string
  :group 'xwem-launcher)

(defcustom xwem-xterm-font1 ""
  "Default xterm font."
  :type 'string
  :group 'xwem-launcher)

(defcustom xwem-xterm-font2 "10x20"
  "Second xterm font."
  :type 'string
  :group 'xwem-launcher)

(defcustom xwem-xterm-font3 "9x15"
  "Third xterm font."
  :type 'string
  :group 'xwem-launcher)

(defcustom xwem-xterm-font4 "fixed"
  "Forth xterm font."
  :type 'string
  :group 'xwem-launcher)

(defcustom xwem-lupe-program "lupe"
  "Xmag like mignifier program."
  :type 'string
  :group 'xwem-launcher)

(defcustom xwem-lupe-arguments "-noshape -nohud"
  "Argument to pass to `xwem-lupe-program'."
  :type 'string
  :group 'xwem-launcher)

(defcustom xwem-xlock-program "xlock"
  "Program to run in order to lock X display."
  :type 'string
  :group 'xwem-launcher)

(defcustom xwem-xlock-arguments "-mode image"
  "Arguments to supply `xwem-xlock-program'."
  :type 'string
  :group 'xwem-launcher)

(defvar xwem-launcher-shell-completion-table nil
  "*Completion table in used by `xwem-completer'.")

;; Executing program
(defun xwem-launcher-build-shell-completion-table (&optional rehash)
  "Scan `exec-path' to build completion table of executables."
  (if (and xwem-launcher-shell-completion-table (not rehash))
      xwem-launcher-shell-completion-table

    (setq xwem-launcher-shell-completion-table
          (apply 'nconc (mapcar (lambda (dir)
                                  (mapcar 'list (directory-files dir nil nil t t)))
                                exec-path))))
  )

(defun xwem-launcher-shell-complete (&optional undo mode)
  "Complete the previous command or display possibilities if done
twice in a row.  If called with a prefix, undo the last completion."
  (interactive "P")
  (if undo
      (completer-undo)

    (setq completer-string nil)
    (if (string-match ".*[ \t].*" (buffer-substring (point-min) (point-max)))
        (comint-dynamic-complete-filename)

      ;; Complete application
      (completer-complete-goto "^ \t\n\"" completer-words
                               (xwem-launcher-build-shell-completion-table)
                               (lambda (w)
                                 (executable-find (car w)))))))

(defun xwem-launcher-read-command (prompt &optional initial-input)
  "Read command name prompting PROMPT.
Just linke `read-shell-command', but installs
`xwem-launcher-abbrev-table' as abbrev table, `xwem-launcher-history'
as history of commands and `xwem-launcher-shell-completion-table' as table
to performe completions.
INITIAL-INPUT is self-described."
  (let ((minibuffer-completion-table nil)
        (keymap (copy-keymap read-shell-command-map)))
    
    (unwind-protect
        (progn
          (define-key read-shell-command-map (kbd "TAB") 'xwem-launcher-shell-complete)
          (xwem-read-from-minibuffer prompt initial-input read-shell-command-map
                                      nil 'xwem-launcher-history xwem-launcher-abbrev-table))
      (setq read-shell-command-map keymap))
  ))

(defun xwem-launcher-split-cmd (cmd-with-args)
  "Split string CMD-WITH-ARGS into command and aguments strings.
Also aplly `executable-find' to find out full path to command.
Also remove explicit spaces in arguments string."
  (let* ((scmd (split-string cmd-with-args " "))
	 (cmd-str (car scmd))
	 (arg-str (mapconcat 'identity (cdr scmd) " ")))
    (cons (executable-find cmd-str) (replace-in-string arg-str " +" " "))))

(defun xwem-launcher-join-cmd (cmd-cell)
  "Construct final command from cons cell CMD-CELL.
`car' of CMD-CELL is cmd and `cdr' is arguments string."
  (when (car cmd-cell)
    (concat (car cmd-cell)
	    (if (and (stringp (cdr cmd-cell))
		     (> (length (cdr cmd-cell)) 0))
		(concat " " (cdr cmd-cell))
	      ""))))

(defun xwem-launcher-normalize-cmd (cmd)
  "Normalize command CMD, i.e. performe `xwem-launcher-split-cmd' and `xwem-launcher-join-cmd'.
If some errors encoureged, send signal"
  (let ((ncmd (xwem-launcher-split-cmd cmd)))
    (if (null (car ncmd))
	(error "Can't normalize command: %S" cmd)
      (xwem-launcher-join-cmd ncmd))))

;;;###autoload
(defun xwem-launcher-query (&optional prompt)
  "Query for command to launch using PROMPT."
  (let ((cmd (xwem-launcher-read-command
	      (if prompt (concat prompt "XWEM-Run: ") "XWEM-Run: "))))

    (xwem-launcher-normalize-cmd cmd)))

;;;###autoload(autoload 'xwem-run-program "xwem-launcher" "" t)
(define-xwem-command xwem-run-program (command)
  "Run COMMAND."
  (xwem-interactive "eRun command: ")

  (xwem-execute-program command))

;;;###autoload
(defun xwem-execute-program (command &optional buffer-name)
  "Execute COMMAND in buffer with BUFFER-NAME.
Unlike `background' do not use shell."
  (let* ((cmdargs (condition-case nil (split-string command " ") (t (list command)))) ; due to split-string args-out-of-range bug
	 (prg (car cmdargs))
	 (args (cdr cmdargs))
	 (job-number 1)
	 job-name)
    (while (get-process (setq job-name (format "xwem-run-%d" job-number)))
      (setq job-number (1+ job-number)))

    (or buffer-name
	(setq buffer-name (format " *%s*" job-name)))

    (with-current-buffer (get-buffer-create buffer-name)
      (erase-buffer)

      (insert "--- working directory: %S" default-directory
	      "\n% " command ?\n)

      (let ((proc (get-buffer-process
		   (comint-exec buffer-name job-name prg nil args))))
	(comint-mode)
	;; COND because the proc may have died before the G-B-P is called.
	(cond (proc (set-process-sentinel proc 'xwem-program-sentinel)
		    (message "[%d] %d" job-number (process-id proc))))
	(setq mode-name "XWEM-Run")
	proc))))

(defun xwem-program-sentinel (process msg)
  "Called when PROCESS changed state to MSG."
  (let ((ms (match-data))) ; barf
    (unwind-protect
	 (let ((msg (cond ((string= msg "finished\n") "Done")
			  ((string-match "^exited" msg)
			   (concat "Exit " (substring msg 28 -1)))
			  ((zerop (length msg)) "Continuing")
			  (t (concat (upcase (substring msg 0 1))
				     (substring msg 1 -1))))))
           (when xwem-launcher-beep-done
             (xwem-play-sound 'ready))
	   (xwem-message 'info "[%s] %s '%s'" (process-name process)
			 msg
			 (mapconcat 'identity (process-command process) " "))
	   (if (null (buffer-name (process-buffer process)))
	       (set-process-buffer process nil) ; WHY? Olin.

	     (if (memq (process-status process) '(signal exit))
		 (with-current-buffer (process-buffer process)
		   (let ((at-end (eobp)))
		     (save-excursion
		       (goto-char (point-max))
		       (insert ?\n msg ?\x20
			       (substring (current-time-string) 11 19) ?\n))
		     (if at-end (goto-char (point-max))))
		   (set-buffer-modified-p nil)))))
      (store-match-data ms))))

(defun xwem-execute-program-other-win (cmd type)
  "Execute CMD in other XWEM window, making TYPE split if needed.
TYPE is one of 'horizontal of 'vertical"
  (setq cmd (xwem-launcher-normalize-cmd cmd))

  (let ((own (xwem-window-other 1))
	(xwem-win-after-split-hook nil)) ; prevent hooks processing

    ;; Check is there split needed
    (when (eq own (xwem-win-selected))
      (if (eq type 'horizontal)
	  (xwem-frame-split-horiz 0)
	(xwem-frame-split-vert 0))
      (setq own (xwem-win-next (xwem-win-selected))))

    (when (xwem-win-p own)
      (xwem-win-expt-inc own cmd))	;install expectation
    (xwem-execute-program cmd)
    ))

(defun xwem-execute-program-other-win-horizontal (cmd)
  "Execute CMD in other XWEM window, making horizontal split if needed."
  (xwem-execute-program-other-win cmd 'horizontal))

(defun xwem-execute-program-other-win-vertical (cmd)
  "Execute CMD in other XWEM window, making vertical split if needed."
  (xwem-execute-program-other-win cmd 'vertical))

(defun xwem-execute-program-other-frame (cmd)
  "Execute CMD in other XWEM frame."
  (setq cmd (xwem-launcher-normalize-cmd cmd))

  (let ((oframe (or (xwem-frame-other (xwem-frame-selected))
		    (xwem-make-frame-1 nil nil nil t))))

    (xwem-win-expt-inc (xwem-frame-selwin oframe) cmd)
    (xwem-execute-program cmd)
    (xwem-frame-select oframe)
    ))

(defun xwem-execute-program-embedded-frame (cmd)
  "Execute CMD in linkaged frame or in embedded XWEM frame."
  (setq cmd (xwem-launcher-normalize-cmd cmd))

  (let ((oframe (or (xwem-frame-other (xwem-frame-selected) 'linkage)
		    (xwem-make-frame-1 t nil nil t))))

    (xwem-win-expt-inc (xwem-frame-selwin oframe) cmd)
    (xwem-execute-program cmd)
    (xwem-frame-select oframe)
    ))

;;;; XWEM commands.

;;;###autoload(autoload 'xwem-launcher-turn-on-horizontal-split-type "xwem-launcher" "" t)
(define-xwem-command xwem-launcher-turn-on-horizontal-split-type ()
  "Set `xwem-launcher-split-type' to `xwem-execute-program-other-win-horizontal'."
  (xwem-interactive)
  
  (setq xwem-launcher-split-type 'xwem-execute-program-other-win-horizontal)
  (xwem-message 'info "Launcher split type HORIZONTAL on."))

;;;###autoload(autoload 'xwem-launcher-turn-on-vertical-split-type "xwem-launcher" "" t)
(define-xwem-command xwem-launcher-turn-on-vertical-split-type ()
  "Set `xwem-launcher-split-type' to `xwem-execute-program-other-win-vertical'."
  (xwem-interactive)

  (setq xwem-launcher-split-type 'xwem-execute-program-other-win-vertical)
  (xwem-message 'info "Launcher split type VERTICAL on."))

;;;###autoload(autoload 'xwem-launcher-toggle-split-type "xwem-launcher" "" t)
(define-xwem-command xwem-launcher-toggle-split-type (arg)
  "Toggle `xwem-launcher-split-type'.
Without prefix ARG set it to vertical, with prefix ARG set it to horizontal."
  (xwem-interactive "P")
  
  (if arg
      (xwem-launcher-turn-on-horizontal-split-type)
    (xwem-launcher-turn-on-vertical-split-type)))

;;;###autoload(autoload 'xwem-launcher-turn-on-normal-frame-type "xwem-launcher" "" t)
(define-xwem-command xwem-launcher-turn-on-normal-frame-type ()
  "Set `xwem-launcher-frame-type' to `xwem-execute-program-other-frame', aka normal frame type."
  (xwem-interactive)
  
  (setq xwem-launcher-frame-type 'xwem-execute-program-other-frame)
  (xwem-message 'info "Other frame NORMAL type on."))

;;;###autoload(autoload 'xwem-launcher-turn-on-embedded-frame-type "xwem-launcher" "" t)
(define-xwem-command xwem-launcher-turn-on-embedded-frame-type ()
  "Set `xwem-launcher-frame-type' to `xwem-execute-program-embedded-frame' aka embedded frame type."
  (xwem-interactive)

  (setq xwem-launcher-frame-type 'xwem-execute-program-embedded-frame)
  (xwem-message 'info "Other frame EMBEDDED type on."))

;;;###autoload(autoload 'xwem-launcher-toggle-frame-type "xwem-launcher" "" t)
(define-xwem-command xwem-launcher-toggle-frame-type (arg)
  "Toggle `xwem-launcher-frame-type'.
Without prefix ARG set it to normal, with prefix ARG set it to embedded."
  (xwem-interactive "P")
  
  (if arg
      (xwem-launcher-turn-on-normal-frame-type)
    (xwem-launcher-turn-on-embedded-frame-type)))

;;;###autoload(autoload 'xwem-launch-program "xwem-launcher" "" t)
(define-xwem-command xwem-launch-program (cmd &optional arg)
  "Run CMD program in background.
If used with prefix ARG (\\<xwem-global-map>\\[xwem-universal-argument]), installs
expectance on selected window (i.e. when client window performe
MapWindow, it will be managed to window where expectance setuped
regardless selected window at map moment.  It is usefull to do so when
you start application with large start time, such as Mozilla or
AcrobatReader, and you want continue doing things not wainting untill
application window maps.
If used with numeric prefix ARG, then that number specifies how many
programs to run."
  (xwem-interactive "eLaunch program: \nP")

  (cond ((listp arg)
         (xwem-win-expt-inc (xwem-win-selected) cmd)
         (xwem-execute-program cmd))

	((numberp arg)
	 (while (> arg 0)
	   (xwem-execute-program cmd)
	   (setq arg (1- arg))))
	(t (error "Invalid arg: %s" arg)))
  )

;;;###autoload(autoload 'xwem-launch-program-other-win "xwem-launcher" "" t)
(define-xwem-command xwem-launch-program-other-win (cmd &optional arg)
  "Run program in other window.
If used with prefix ARG, then do horisontal split if needed."
  (xwem-interactive "eLaunch Other Win: \nP")

  (let ((own (xwem-window-other 1))
	(xwem-win-after-split-hook nil)) ; prevent hooks processing

    ;; Check is there split needed
    (when (eq own (xwem-win-selected))
      (if arg
	  (xwem-frame-split-horiz 0)
	(xwem-frame-split-vert 0))
      (setq own (xwem-win-next (xwem-win-selected))))

    (when (xwem-win-p own)
      (xwem-win-expt-inc own cmd))	;install expectation
    (xwem-execute-program cmd)
    ))

;;;###autoload(autoload 'xwem-launch-program-other-frame "xwem-launcher" "" t)
(define-xwem-command xwem-launch-program-other-frame (cmd &optional arg)
  "Run programm in other frame.
ARG passed as first argument to `xwem-make-frame-1'."
  (xwem-interactive "eLaunch Other Frame: \nP")
  
  (let ((oframe (or (xwem-frame-other (xwem-frame-selected))
		    (xwem-make-frame-1 arg nil nil t))))

    (xwem-win-expt-inc (xwem-frame-selwin oframe) cmd)
    (xwem-execute-program cmd)
    (xwem-frame-select oframe))
  )

;;;###autoload
(defsubst xwem-launch (cmd)
  "Execute CMD using `xwem-launcher'."
  (funcall xwem-launcher-function cmd))

;;;###autoload
(defun xwem-launch-generic-program (cmd sarg)
  "Run generic program CMD with arguments SARG."
  (xwem-launch (xwem-launcher-join-cmd (cons cmd sarg))))

;; Executing xterm
(defun xwem-xterm-construct-cmd (arg)
  "Construct xterm command according to ARG."
  (let ((fn (symbol-value (intern (concat "xwem-xterm-font" (int-to-string arg)))))
	(cmd xwem-xterm-program))

    (when (and (stringp fn) (> (length fn) 0))
      (setq cmd (concat cmd " " xwem-xterm-font-argument " " fn)))
    cmd))

;;;###autoload(autoload 'xwem-launch-xterm "xwem-launcher" "" t)
(define-xwem-command xwem-launch-xterm (arg)
  "Run xterm program `xwem-xterm-program' with ARG as font argument."
  (xwem-interactive "p")

  (let ((cmd (xwem-xterm-construct-cmd arg)))
    (xwem-launch cmd)))

;;;###autoload(autoload 'xwem-launch-xterm-other-win "xwem-launcher" "" t)
(define-xwem-command xwem-launch-xterm-other-win (arg)
  "Execute xterm in other window, ARG have same meaning as in `xwem-launch-xterm'."
  (xwem-interactive "p")

  (let ((xwem-launcher-function xwem-launcher-split-type))
    (xwem-launch-xterm arg)))

;;;###autoload(autoload 'xwem-launch-xterm-other-frame "xwem-launcher" "" t)
(define-xwem-command xwem-launch-xterm-other-frame (arg)
  "Execute xterm in other frame, ARG have same meaning as in `xwem-launch-xterm'."
  (xwem-interactive "p")

  (let ((xwem-launcher-function xwem-launcher-frame-type))
    (xwem-launch-xterm arg)))

;; Executing lupe
;;;###autoload(autoload 'xwem-launch-lupe "xwem-launcher" "" t)
(define-xwem-command xwem-launch-lupe (arg)
  "Run lupe `xwem-lupe-program' with `xwem-lupe-arguments'.
Prefix ARG is actually unused."
  (xwem-interactive "P")

  (xwem-launch-generic-program xwem-lupe-program xwem-lupe-arguments))

;;;###autoload(autoload 'xwem-launch-lupe-other-win "xwem-launcher" "" t)
(define-xwem-command xwem-launch-lupe-other-win (arg)
  "Run lupe in other window.
Prefix ARG is actually unused."
  (xwem-interactive "P")
  
  (let ((xwem-launcher-function xwem-launcher-split-type))
    (xwem-launch-lupe arg)))

;;;###autoload(autoload 'xwem-launch-lupe-other-frame "xwem-launcher" "" t)
(define-xwem-command xwem-launch-lupe-other-frame (arg)
  "Run lupe in other frame.
Prefix ARG is actually unused."
  (xwem-interactive "P")

  (let ((xwem-launcher-function xwem-launcher-frame-type))
    (xwem-launch-lupe arg)))

;;;###autoload(autoload 'xwem-launch-xlock "xwem-launcher" "" t)
(define-xwem-command xwem-launch-xlock ()
  "Launch `xwem-xlock-program' with `xwem-xlock-arguments'."
  (xwem-interactive)

  (xwem-launch-generic-program xwem-xlock-program xwem-xlock-arguments))


;;; Launcher dockapp button
(defcustom xwem-launch-dock-width 24
  "*Launcher dockapp width."
  :type 'number
  :group 'xwem-launch)

(defcustom xwem-launch-dock-height 24
  "*Launcher dockapp height."
  :type 'number
  :group 'xwem-launch)

(defcustom xwem-launch-dock-thick 2
  "*Launcher dockapp border thickness."
  :type 'number
  :group 'xwem-launch)

(defface xwem-launch-dock-face
  `((t (:foreground "gray70" :background "black")))
  "Default background face for launcher docks."
  :group 'xwem-launch)

(defvar xwem-launch-dock-keymap
  (let ((map (make-sparse-keymap)))
    (define-key map [button1] 'xwem-launch-dock-down)
    (define-key map [button1up] 'xwem-launch-dock-launch)
    (define-key map [button3] 'xwem-launch-dock-menu)
    map)
  "Keymap for launch docks.")

(define-xwem-command xwem-launch-dock-down ()
  "Default command when button is down."
  (xwem-interactive)

  (xwem-ladock-push (X-Event-win xwem-last-xevent))
  )

(define-xwem-command xwem-launch-dock-launch ()
  "Launch command for launch dock."
  (xwem-interactive)

  (let* ((xwin (X-Event-win xwem-last-xevent))
         (action (X-Win-get-prop xwin 'ladock-action))
         (atype (car action))
         (acmd (cdr action)))
    (xwem-ladock-pop xwin)
    (cond ((eq atype 'elisp)
           (eval (read acmd)))

          ((eq atype 'cmd)
           (xwem-execute-program acmd))

          (t (xwem-message 'warn "Unknown action type=`%s'" atype)))
  ))

(define-xwem-command xwem-launch-dock-menu (action)
  "Popup menu."
  (xwem-interactive (list (X-Win-get-prop (X-Event-win xwem-last-xevent) 'ladock-action)))

  (let (cls menu oldfrnum)
    (mapc (lambda (cl)
            (when (string-match (cdr action) (xwem-hints-wm-command (xwem-cl-hints cl)))
              (setq cls (cons cl cls))))
          xwem-clients)

    ;; Sort clients
    (setq cls (sort cls (lambda (cl1 cl2)
                          (and (xwem-frame-p (xwem-cl-frame cl1))
                               (xwem-frame-p (xwem-cl-frame cl2))
                               (> (xwem-frame-num (xwem-cl-frame cl1))
                                  (xwem-frame-num (xwem-cl-frame cl2)))))))
    
    (setq menu (list "Clients" :filter
                     (lambda (not-used)
                       (mapcar (lambda (cl)
                                 (let ((frame (xwem-cl-frame cl))
                                      (name (xwem-hints-wm-name (xwem-cl-hints cl))))
                                  (vector (if (xwem-frame-p frame)
                                              (format "[%d](%s): %s" (xwem-frame-num (xwem-cl-frame cl))
                                                      (xwem-frame-name (xwem-cl-frame cl))
                                                      name)
                                            name)
                                          `(xwem-cl-pop-to-client ,cl)
                                          :active (if (xwem-cl-exclude-p cl) nil t))))
                               cls))))
    (xwem-popup-menu menu))
  )

(defun xwem-ladock-push (xwin)
  "Emulate pushing button."
  (X-Win-put-prop xwin 'ladock-state 'down)
  (xwem-ladock-redraw xwin))

(defun xwem-ladock-pop (xwin)
  "Emulate poping button."
  (X-Win-put-prop xwin 'ladock-state 'up)
  (xwem-ladock-redraw xwin))
 
(defun xwem-ladock-puticon (xwin)
  "Draw icon on launcher dock XWIN."
  (let* ((xdpy (X-Win-dpy xwin))
         (xpix (X-Win-get-prop xwin 'ladock-xpix))
         (ximg (X-Pixmap-get-prop xpix 'ximg))
         (xgc (X-Win-get-prop xwin 'ladock-xgc)))
    (XCopyArea xdpy xpix xwin xgc 0 0
               (X-Image-width ximg) (X-Image-height ximg)
               (/ (- xwem-launch-dock-width (X-Image-width ximg)) 2)
               (/ (- xwem-launch-dock-height (X-Image-height ximg)) 2))
    ))
    
(defun xwem-ladock-redraw (xwin)
  "Redraw launcher button dock XWIN."
  (let ((state (X-Win-get-prop xwin 'ladock-state))
        (xdpy (X-Win-dpy xwin)))
    (X-Dpy-send-excursion xdpy
      (cond ((eq state 'down)
             (xwem-misc-draw-bar xdpy xwin
                                 (xwem-face-get-gc 'xwem-launch-dock-face)
                                 (xwem-face-get-gc 'xwem-face-black)
                                 (xwem-face-get-gc 'xwem-face-white)
                                 0 0 xwem-launch-dock-width xwem-launch-dock-height xwem-launch-dock-thick))

            ((eq state 'up)
             (xwem-misc-draw-bar xdpy xwin
                                 (xwem-face-get-gc 'xwem-launch-dock-face)
                                 (xwem-face-get-gc 'xwem-face-white)
                                 (xwem-face-get-gc 'xwem-face-black)
                                 0 0 xwem-launch-dock-width xwem-launch-dock-height xwem-launch-dock-thick))
            )
      (xwem-ladock-puticon xwin))
    ))

(defun xwem-ladock-evhandler (xdpy xwin xev)
  "On XDPY and launcher dock XWIN handle event XEV."
  (X-Event-CASE xev
    (:X-Expose
     (xwem-ladock-redraw xwin))

    ((:X-ButtonPress :X-ButtonRelease)
     (let ((xwem-override-global-map xwem-launch-dock-keymap))
       (xwem-kbd-handle-keybutton xev)))

    (:X-DestroyNotify
     (xwem-launch-button-stop xwin))
    ))

(defun xwem-launch-button-stop (xwin &optional force)
  "Destoy launch dockapp button XWIN.
If FORCE is non-nil also destroy XWIN."
  (let ((xdpy (X-Win-dpy xwin))
        (xpix (X-Win-get-prop xwin 'ladock-xpix))
        (xpix-mask (X-Win-get-prop xwin 'ladock-xpix-mask))
        (xgc (X-Win-get-prop xwin 'ladock-xgc)))
    (XFreeGC xdpy xgc)
    (XFreePixmap xdpy xpix)
    (XFreePixmap xdpy xpix-mask)

    (when force
      (XDestroyWindow xdpy xwin))))

;;;###autoload
(defun xwem-launch-button-start (xpm-file action &optional xdpy)
  "Create new dockapp button with XPM-FILE image and doing ACTION on click.
ACTION is cons cell wher car is one of 'elisp or 'cmd and cdr is string.
For 'elisp car, cdr is real elisp expression, to evaluate on click.
For 'cmd  car, cdr is cmd to run on click."
  (unless xdpy
    (setq xdpy (xwem-dpy)))

  (let (xwin xpix xpix-mask ximg xgc)
    (setq xwin (XCreateWindow xdpy nil 0 0 xwem-launch-dock-width xwem-launch-dock-height 0 nil nil nil
                              (make-X-Attr :override-redirect t
                                           :backing-store X-WhenMapped
                                           :background-pixel (XAllocNamedColor xdpy (XDefaultColormap xdpy) "gray50")
                                           :border-pixel (XAllocNamedColor xdpy (XDefaultColormap xdpy) "gray80"))
                              ))
    ;; Create pixmap
    (setq xpix (X:xpm-pixmap-from-file xdpy xwin xpm-file))
    (setq ximg (X-Pixmap-get-prop xpix 'ximg))
    (setq xpix-mask (X:xpm-pixmap-from-file xdpy xwin xpm-file t))

    (setq xgc (XCreateGC xdpy xpix
                         (make-X-Gc :dpy xdpy :id (X-Dpy-get-id xdpy)
                                    :clip-x-origin (/ (- xwem-launch-dock-width (X-Image-width ximg)) 2)
                                    :clip-y-origin (/ (- xwem-launch-dock-height (X-Image-height ximg)) 2)
                                    :clip-mask xpix-mask)))
    ;; Put some properties
    (X-Win-put-prop xwin 'ladock-state 'up)
    (X-Win-put-prop xwin 'ladock-action action)

    (X-Win-put-prop xwin 'ladock-xgc xgc)
    (X-Win-put-prop xwin 'ladock-xpix xpix)
    (X-Win-put-prop xwin 'ladock-xpix-mask xpix-mask)

    (XSelectInput xdpy xwin (Xmask-or XM-Exposure XM-StructureNotify XM-ButtonPress XM-ButtonRelease))
    (X-Win-EventHandler-add xwin 'xwem-ladock-evhandler nil
			    (list X-Expose X-ButtonPress X-ButtonRelease X-DestroyNotify))

    (XTrayInit xdpy xwin)

    xwin))
  

(provide 'xwem-launcher)

;;; xwem-launcher.el ends here
