;;; xwem-clients.el --- Clients manage.

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

;; Author: Zajcev Evgeny <zevlg@yandex.ru>
;; Created: 2 Mar 2003
;; Keywords: xlib, xwem
;; X-CVS: $Id: xwem-clients.el,v 1.4 2004/05/05 22:43:08 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:
;;
;; This file used for generic X clients management.
;;
;; Client state(`xwem-cl-state') is one of:
;; 
;;   'managed - Client has `xwem-cl-win' and in WIN's clients list, but
;;              not current in WIN.
;;   
;;   'managed-current - As 'managed, but CL aslo current in WIN.
;;   
;;   'demanaged - CL may have valid `xwem-cl-win', but not in WIN's
;;                clients list and not current in any window.
;;   
;;   'iconified - Same as 'demanaged
;;   
;;   'destroyed - CL's x window destroyed.
;;   
;;   'unknown   - Not any of above.

;; 
;; Hooks are:
;; 
;;   `xwem-cl-create-hook' - Called when new CL just created.
;;
;;   `xwem-cl-destroy-hook' - Called when CL destroyed.
;;
;;   `xwem-cl-state-change-hook' - Called when CL changes state to one
;;                                 described above.
;; 
;;   `xwem-cl-manage-hook' - Called when CL just managed in some
;;                           window.
;;
;;   `xwem-cl-demanage-hook' - Called when CL just demanaged from some
;;                             window.
;;
;;   `xwem-cl-mark-hook' - Called when CL marked or unmarked.

;;; Code:

(eval-when-compile
  ;; Shutup compiler
  (require 'xwem-macros)
  (defvar iswitchb-buflist nil)
  (autoload 'subtract-time "time-date")
  (autoload 'iswitchb-read-buffer "iswitchb")
  )

;;; Variables
(defgroup xwem-cl nil
  "Group to customize XWEM Clients handling."
  :prefix "xwem-cl-"
  :group 'xwem)

(defcustom xwem-cl-use-parent-xwin t
  "*Non-nil mean that CL will use some X window, where it(CL) lowered.
This is need to fullish some X applications, which accuire clients in such evil manner."
  :type 'boolean
  :group 'xwem-cl)

(defcustom xwem-cl-other-strategy 'samewin
  "*Strategy to be used to select other CL.
One of 'any 'samewin 'sameframe.
TODO: add more strategies."
  :type '(choice (const :tag "Same Window" samewin)
		 (const :tag "Same Frame" sameframe)
		 (const :tag "Any" any))
  :group 'xwem-cl)

(defcustom xwem-cl-other-on-split t
  "Non-nil mean manage other client when split occurs in new window.
Minor mode."
  :type 'boolean
  :group 'xwem-cl)

(defcustom xwem-cl-use-set-focus t
  "*Non-nil mean that managed clients takes focus.
NOTE: installs hook into `xwem-cl-manage-hook'."
  :type 'boolean
  :group 'xwem-cl)

(defcustom xwem-cl-use-recent-cl-on-top nil
  "*Non-nil mean that most recent client is on top in `xwem-clients' list."
  :type 'boolean
  :group 'xwem-cl)

(defcustom xwem-cl-mark-ring-max 16
  "*Maximum size of `xwem-cl-mark-ring'.
Start discarding off end if gets this big."
  :type 'number
  :group 'xwem-cl)

;;;###autoload
(defcustom xwem-cl-create-hook nil
  "Hook to call when creating new client."
  :type 'hook
  :group 'xwem-cl)

;;;###autoload
(defcustom xwem-cl-destroy-hook nil
  "Hooks called with one argument - cl, when cl destroyed.
NOT USED YET."
  :type 'hook
  :group 'xwem-hooks)

;;;###autoload
(defcustom xwem-cl-manage-hook nil
  "*Hooks to be called with just setuped CL as argument."
  :type 'hook
  :group 'xwem-hooks)

;;;###autoload
(defcustom xwem-cl-demanage-hook nil
  "*Hooks to be called with just desetuped CL as argument."
  :type 'hook
  :group 'xwem-hooks)

;;;###autoload
(defcustom xwem-cl-refit-hook nil
  "Hooks called when CL just refited."
  :type 'hook
  :group 'xwem-hooks)

;;;###autoload
(defcustom xwem-cl-iconify-hook nil
  "Hooks called when CL just iconified."
  :type 'hook
  :group 'xwem-hooks)

;;;###autoload
(defcustom xwem-cl-change-hook nil
  "Hooks called when something changed in CL."
  :type 'hook
  :group 'xwem-hooks)

;;;###autoload
(defcustom xwem-cl-state-change-hook nil
  "*Hooks to run when state of client changes.
Every hook called with three args - CL OLD-STATE NEW-STATE."
  :type 'hook
  :group 'xwem-hooks)

;;;###autoload
(defcustom xwem-cl-mark-hook nil
  "*Hooks to run when marking client.
Hooks called with two args - CL STATE.
Where STATE is one of 'mark or 'unmark."
  :type 'hook
  :group 'xwem-hooks)

;;; CL property change hooks
;;;###autoload
(defcustom xwem-cl-wmnh-change-hooks nil
  "Hooks to be called when WM_NORMAL_HINTS changes."
  :type 'hook
  :group 'xwem-hooks)

;;;###autoload
(defcustom xwem-cl-wmname-change-hooks nil
  "Hooks to be called when WM_NAME changes."
  :type 'hook
  :group 'xwem-hooks)

;;;###autoload
(defcustom xwem-cl-wmcommand-chage-hooks nil
  "Hooks to be called when WM_COMMAND changes."
  :type 'hook
  :group 'xwem-hooks)

;;;###autoload
(defcustom xwem-cl-wmclass-change-hooks nil
  "Hooks to be called when WM_CLASS changes."
  :type 'hook
  :group 'xwem-hooks)

;;;###autoload
(defcustom xwem-cl-wmh-change-hooks nil
  "Hooks to be called when WM_HINTS changes."
  :type 'hook
  :group 'xwem-hooks)

;;;###autoload
(defvar xwem-clients nil "Clients Windows list")

;;;###autoload
(defvar xwem-cl-mark-ring nil
  "The list of marked clients.")

;;;###autoload
(defstruct xwem-hints
  ;; TODO: add more
  wm-normal-hints
  wm-hints
  wm-class
  wm-command
  wm-name
  wm-transient-for
  wm-protocols)

;;;###autoload
(defconst xwem-client-ev-mask (Xmask-or XM-ColormapChange XM-PropertyChange
					XM-FocusChange XM-EnterWindow XM-LeaveWindow
					XM-StructureNotify XM-ResizeRedirect)
  "Event mask for xwem's client.")

;;;###autoload
(defstruct (xwem-cl (:predicate xwem-iscl-p))
  xwin					; X-Win
  saved-name				; saved WM_NAME
  xgeom					; X-Geom etry for cl
  xattrs				; X-Attr ibutes
  
  win					; xwem-win dow
  hints					; xwem-hints
  manda					; xwem-manda entry
  transient-for				; non-nil if client is transient for window
  (ev-mask xwem-client-ev-mask)		; event mask for certain client

  (state 'unknown)			; state of client, 'managed, 'iconified, 'unknown, etc
  start-time				; start-time
  recency				; last time when CL was active
  translist				; list of transient-for windows for this client

  plist					; user defined plist
  )


;;; Functions
;;;###autoload
(defun xwem-cl-p (cl &optional sig)
  "Returns t if CL is XWEM client window."
  (let ((iscl (xwem-iscl-p cl)))
    (if (and (not iscl) sig)
	(signal 'wrong-type-argument (list sig 'xwem-cl-p cl))
      iscl)))

;;;###autoload
(defun xwem-cl-marked-p (cl)
  "Return non-nil if client CL is marked, i.e. in `xwem-cl-mark-ring' list."
  (member cl xwem-cl-mark-ring))

;;;###autoload
(defun xwem-cl-destroyed-p (cl)
  "Return non-nil if CL has already destroyed xwin."
  (eq (xwem-cl-state cl) 'destroyed))

;;;###autoload
(defsubst xwem-cl-put-prop (cl prop val)
  "In CL's property list put property PROP with value VAL."
  (setf (xwem-cl-plist cl) (plist-put (xwem-cl-plist cl) prop val)))
(put 'xwem-cl-put-prop 'lisp-indent-function 2)

;;;###autoload
(defsubst xwem-cl-get-prop (cl prop)
  "From CL's property list get property PROP."
  (plist-get (xwem-cl-plist cl) prop))

;;;###autoload
(defsubst xwem-cl-rem-prop (cl prop)
  "From CL's property list remove property PROP."
  (setf (xwem-cl-plist cl) (plist-remprop (xwem-cl-plist cl) prop)))

;;;###autoload
(defun xwem-client-name (cl &optional clist)
  "Returns unique name for CL.
If CLIST is ommited, `xwem-clients' will be used.
If CL is string, return it."
  (if (stringp cl)
      cl
    (let ((cll (or clist xwem-clients))
	  (cln (xwem-hints-wm-name (xwem-cl-hints cl)))
	  (cnt 0))
      (while cll
	(cond ((string= (xwem-hints-wm-name (xwem-cl-hints (car cll))) cln)
	       (if (eq cl (car cll))
		   (setq cll nil)
		 (setq cnt (1+ cnt))))
	      (t nil))
	(setq cll (cdr cll)))
      (if (> cnt 0)
	  (format "%s<%d>" cln cnt)
	cln))))

;;;###autoload
(defun xwem-find-client (win-or-id)
  "Find WIN-OR-ID in client windows list.
WIN-OR-ID can be X-Win or id of window."
  (let ((winid (if (X-Win-p win-or-id) (X-Win-id win-or-id) win-or-id))
	(cl xwem-clients)
	(rc nil))
    (while cl
      (if (= (X-Win-id (xwem-cl-xwin (car cl))) winid)
	  (progn
	    (setq rc (car cl))
	    (setq cl nil))
	(setq cl (cdr cl))))
    rc))

;;;###autoload
(defun xwem-remove-client (cl)
  "Delete WIN from clients list."
  (setq xwem-clients (delete cl xwem-clients)))

(defun xwem-cl-do-gravity (cl step)
  "Change CL's gravity.
NOT USED"
  )

;;;###autoload
(defun xwem-cl-send-config (cl)
  "Send config info to window."
  (xwem-cl-p cl 'xwem-cl-send-config)

  (let ((clgeom (xwem-cl-xgeom cl))
	(win (xwem-cl-xwin cl)))

    (XSendEvent (xwem-dpy) win nil XM-StructureNotify
		(X-Create-message
		 (list [1 X-ConfigureNotify] ;type
		       [1 nil]		;detail
		       [2 2806]		;seq
		       [4 (X-Win-id win)] ;event
		       [4 (X-Win-id win)] ;window
		       [4 X-None]	;above sibling
		       (vector 2 (X-Geom-x clgeom)) ; shutup compiler
		       [2 (X-Geom-y clgeom)]
		       [2 (X-Geom-width clgeom)]
		       [2 (X-Geom-height clgeom)]
		       [2 (X-Geom-border-width clgeom)] ;XXX
		       [1 nil]		;pad override
		       [1 nil]		;pad
		       )))
    ))


;; cl predicates
;;;###autoload
(defun xwem-cl-alive-p (cl)
  "Return non-nil if CL is alive i.e. in `xwem-clients' list."
  (memq cl xwem-clients))

;;;###autoload
(defun xwem-cl-exclude-p (cl)
  "Return non-nil if CL should be excluded from clients list."
  (and (xwem-cl-manda cl) (xwem-manda-exclude-p (xwem-cl-manda cl))))


;;;###autoload
(defun xwem-cl-normal-list (clients &optional predic)
  "Return list of normal clients.
CLIENTS is list of xwem clients frome which we should exclude.
If PREDIC given it will be called on each client and should return nil to exclude client."
  (let ((cls nil))
    (while clients
      (when (and (not (xwem-cl-exclude-p (car clients)))
		 (if predic (funcall predic (car clients)) t))
	(setq cls (nconc cls (list (car clients)))))
      (setq clients (cdr clients)))
    cls))

(defun xwem-cl-other (cl &optional visible)
  "Return other xwem's client from list of clients where is CL.
Clients not visible in window are preferred to visible, unless VISIBLE
is non-nil. Special clients excluded.

If CL is not actually xwem client, nil returned."
  (if (xwem-cl-p cl)
      (let ((cll (cond ((eq xwem-cl-other-strategy 'any) xwem-clients)

		       ((eq xwem-cl-other-strategy 'samewin)
			(xwem-win-make-cl-list-sort-by-recency (xwem-cl-win cl)))

		       ((eq xwem-cl-other-strategy 'sameframe)
			(xwem-frame-make-cl-list (xwem-cl-frame cl)))

		       (t xwem-clients)))
	    (rcl nil)
	    (notgoodcl nil))		;not so good candidate as rcl

	(while cll
	  (when (not (eq (car cll) cl))	;skip ourself
	    (if (and (not (xwem-cl-exclude-p (car cll)))
		     (or visible (not (xwem-win-cl-current-p (car cll)))))
		(progn
		  (setq rcl (car cll))
		  (setq cll nil))

	      (when (and visible (null notgoodcl))
		(setq notgoodcl (car cll)))))
	  (setq cll (cdr cll)))
    
	(or rcl notgoodcl))

    ;; [else] invalid CL
    nil))

(defun xwem-cl-bury (cl)
  "Put CL to the and of clients list.
Maybe used in `xwem-cl-manage-hook' or `xwem-cl-demanage-hook'."
  (setq xwem-clients
	(nconc (delete cl xwem-clients) (list cl)))
  nil)					; continue hooks processing


;;; Manda functions begin
;;;###autoload
(defun xwem-cl-correct-size-for-size (cl new-geom &optional x-type y-type)
  "Make CL's geometry as close to NEW-GEOM as possible.
X-TYPE is one of 'center 'left or 'right, default is 'center.
Y-TYPE is one of 'center 'top or 'bottom, default is 'center."
  (let* ((hthi (X-Geom-border-width new-geom))
	 (clgmt (xwem-cl-xgeom cl))
	 (wi-rmd 0)
	 (he-rmd 0)
	 wmnh bw bh wi-st he-st wi he)

    (setq he (- (X-Geom-height new-geom) (* 2 hthi)))
    (setq wi (- (X-Geom-width new-geom) (* 2 hthi)))

    (setq wmnh (xwem-hints-wm-normal-hints (xwem-cl-hints cl)))

    (when wmnh
      (setq bw (X-WMSize-width wmnh))
      (setq bh (X-WMSize-height wmnh))

      (when (X-WMSize-presizeinc-p wmnh)
	(setq wi-st (X-WMSize-width-inc wmnh)) ;width step
	(setq he-st (X-WMSize-height-inc wmnh)) ;height step
	)

      ;; - Calculate size reminders
      ;; - Adjust wi-rmd and he-rmd if needed
      (when wi-st
	(setq wi-rmd (% (abs (- wi bw)) wi-st))
	(when (> bw wi)
	  (setq wi-rmd (- wi-st wi-rmd))))

      (when he-st
	(setq he-rmd (% (abs (- he bh)) he-st))
	(when (> bh he)
	  (setq he-rmd (- he-st he-rmd)))))

    (unless (X-Geom-p clgmt)
      (setf (xwem-cl-xgeom cl) (make-X-Geom))
      (setq clgmt (xwem-cl-xgeom cl)))

    ;; Now adjust geometry according to X-TYPE and Y-TYPE layout
    (cond ((eq x-type 'left)
	   (setf (X-Geom-x clgmt) (X-Geom-x new-geom)))
	  ((eq x-type 'right)
	   (setf (X-Geom-x clgmt) (+ (X-Geom-x new-geom) hthi wi-rmd)))
	  (t				; 'center or any other
	   (setf (X-Geom-x clgmt) (+ (X-Geom-x new-geom) hthi (/ wi-rmd 2)))))
    (cond ((eq y-type 'top)
	   (setf (X-Geom-y clgmt) (X-Geom-y new-geom)))
	  ((eq y-type 'bottom)
	   (setf (X-Geom-y clgmt) (+ (X-Geom-y new-geom) hthi he-rmd)))
	  (t
	   (setf (X-Geom-y clgmt) (+ (X-Geom-y new-geom) hthi (/ he-rmd 2)))))
    (setf (X-Geom-width clgmt) (- wi wi-rmd))
    (setf (X-Geom-height clgmt) (- he he-rmd))))

(defun xwem-cl-correct-size (cl)
  "Corect CL's xgeom according to WM_NORMAL_HINTS and other stuff."
  (let ((wmnh (xwem-hints-wm-normal-hints (xwem-cl-hints cl)))
	(clgeom (xwem-cl-xgeom cl)))
    (when (xwem-cl-transient-for cl)
      ;; Program specified size
      (when (X-WMSize-ussize-p wmnh)
	(setf (X-Geom-width clgeom) (X-WMSize-width wmnh))
	(setf (X-Geom-height clgeom) (X-WMSize-height wmnh)))

      ;; Program specified position
      (when (X-WMSize-uspos-p wmnh)
	(setf (X-Geom-x clgeom) (X-WMSize-x wmnh))
	(setf (X-Geom-y clgeom) (X-WMSize-y wmnh)))
      )))

(defun xwem-cl-domanage (cl &optional sfwin)
  "Real manage job."
  (let* ((old-win (xwem-cl-win cl))
         (new-win (or sfwin (xwem-win-selected)))
         (old-cl (and (xwem-win-p new-win) (xwem-win-cl new-win))))
    ;; When there no xwem window to manage CL, just demanage it
    (if (not (xwem-win-p new-win))
        (xwem-manda-demanage cl)

      (if (xwem-win-cl-current-p cl new-win)
          ;; CL already in NEW-WIN - only refiting needed
          (xwem-manda-refit cl)

        ;; When client moves from frame to other frame, state should
        ;; be unknown.  [Hmm, why]?
;        (when (not (eq (xwem-cl-frame cl)
;                       (xwem-win-frame new-win)))
;          (xwem-client-change-state cl 'unknown))

        ;; First of all demanage client CL
        (when (and (xwem-win-p old-win)
                   (not (eq old-win new-win)))
          (xwem-manda-demanage cl))

        (setf (xwem-win-cl new-win) cl)
        (setf (xwem-cl-win cl) new-win)
        (xwem-manda-refit cl t)
        (xwem-client-show cl 'managed-current)
        
        ;; Hide OLD-CL
        (when (xwem-cl-p old-cl)
          (xwem-client-hide old-cl 'managed))
        ))

    ;; Update recency field
    (setf (xwem-cl-recency cl) (current-time))

    ;; Finally run hooks
    (run-hook-with-args 'xwem-cl-manage-hook cl)
    ))
  
(defun xwem-cl-manage (cl &optional sfwin)
  "Setup CL to be used in SFWIN.
If SFWIWN is ommited `xwem-win-selected' will be used.
TODO: Handle special clients in different way."
  (xwem-cl-p cl 'xwem-cl-manage)
  (when sfwin
    (xwem-win-p sfwin 'xwem-cl-manage))

  (if (not (xwem-misc-xwin-valid-p (xwem-cl-xwin cl)))
      ;; CL suddenly died
      (xwem-cl-hdestroy-notify cl nil)
        
    (xwem-cl-domanage cl sfwin))
  )

(defun xwem-cl-demanage (cl &optional state)
  "Desetup CL from xwem win.
Used when deleting window or frame.
When CLEAR is non-nil then xwem window client for CL will be setted to nil."
  (if (eq state 'destroyed)
      (setf (xwem-cl-state cl) 'destroyed)
    (xwem-client-hide cl (or state 'demanaged)))

  ;; If demanaged CL is current in it's window try to manage other
  ;; client.
  (let ((owin (xwem-cl-win cl))
        ocl)
    (when (xwem-win-cl-current-p cl)
      (setf (xwem-win-cl owin) nil)
      (when (xwem-cl-p (setq ocl (xwem-cl-other cl)))
        (xwem-manda-manage ocl owin))))

  ;; Now run on-demanage hooks
  (run-hook-with-args 'xwem-cl-demanage-hook cl)
  )

(defun xwem-cl-refit (cl &optional need-reparent)
  "Refit CL in its window frame.
If NEED-REPARENT is non-nil than also reparent it to some frame."
  (xwem-win-p (xwem-cl-win cl) 'xwem-cl-refit)

  (let* ((frame (xwem-cl-frame cl))
	 (xwem-win (xwem-cl-win cl))
	 (swwidth (xwem-face-tag 'xwem-face-frame-selected-win-selected :line-width))
	 (nwwidth (xwem-face-tag 'xwem-face-frame-selected-win-nonselected :line-width))
	 (hthi (max (if (numberp swwidth) swwidth 0)
		    (if (numberp nwwidth) nwwidth 0)))
	 (clgmt (xwem-cl-xgeom cl))
	 (wi-rmd 0)
	 (he-rmd 0)
	 wmnh bw bh wi-st he-st wi he)

    (setq he (- (xwem-win-height xwem-win) (* 2 hthi)))
    (setq wi (- (xwem-win-width xwem-win) (* 2 hthi)))

    (setq wmnh (xwem-hints-wm-normal-hints (xwem-cl-hints cl)))
    (X-Dpy-log (xwem-dpy) "Get wmnh = %S\n" 'wmnh)
    (when wmnh
      (setq bw (X-WMSize-width wmnh))
      (setq bh (X-WMSize-height wmnh))

      (when (X-WMSize-presizeinc-p wmnh)
	(setq wi-st (X-WMSize-width-inc wmnh)) ;width step
	(setq he-st (X-WMSize-height-inc wmnh)) ;height step
	)

      ;; - Calculate size reminders
      ;; - Adjust wi-rmd and he-rmd if needed
      (when wi-st
	(setq wi-rmd (% (abs (- wi bw)) wi-st))
	(when (> bw wi)
	  (setq wi-rmd (- wi-st wi-rmd))))

      (when he-st
	(setq he-rmd (% (abs (- he bh)) he-st))
	(when (> bh he)
	  (setq he-rmd (- he-st he-rmd)))))

    (unless (X-Geom-p clgmt)
      (setf (xwem-cl-xgeom cl) (make-X-Geom))
      (setq clgmt (xwem-cl-xgeom cl)))

    (setf (X-Geom-x clgmt) (+ (xwem-win-x xwem-win) hthi (/ wi-rmd 2)))
    (setf (X-Geom-y clgmt) (+ (xwem-win-y xwem-win) hthi (/ he-rmd 2)))
    (setf (X-Geom-width clgmt) (- wi wi-rmd))
    (setf (X-Geom-height clgmt) (- he he-rmd))

    (if need-reparent
      (XReparentWindow (xwem-dpy) (xwem-cl-xwin cl) 
		       (xwem-frame-xwin frame)
		       (X-Geom-x clgmt) (X-Geom-y clgmt))

      (XMoveWindow (xwem-dpy) (xwem-cl-xwin cl) (X-Geom-x clgmt) (X-Geom-y clgmt)))

    (X-Dpy-log (xwem-dpy) "Get size: wi=%d,%d he=%d,%d\n" 'wi '(X-Geom-width clgmt) 'he '(X-Geom-height clgmt))
    (XResizeWindow (xwem-dpy) (xwem-cl-xwin cl)
		   (X-Geom-width clgmt) (X-Geom-height clgmt))

    (xwem-cl-send-config cl)
  ))

;; I think special CLs should be handled in very different way then
;; normals. It is the one of things TODO.
;;
(defun xwem-cl-iconify (cl)
  "Iconify CL. Used to handle Iconify ClientMessage from special CL."
  (xwem-manda-demanage cl 'iconified)
  )

;;;###autoload(autoload 'xwem-client-iconify "xwem-clients" "" t)
(define-xwem-command xwem-client-iconify (cl)
  "Iconifies selected client."
  (xwem-interactive (list (xwem-cl-selected)))

  (if (xwem-cl-p cl)
      (xwem-cl-iconify cl)

    (xwem-message 'warn "No client in selected window.")))

;;; Manda functions ends here

(defun xwem-cl-query-cl (prompt &optional predic)
  "Query for CL, using XWEM's minibuffer.
PREDIC is function, wich passed with cl as argument and must return
non-nil to make cl be in listing."
  (xwem-under-minib-focus
   (let* ((rcl nil)
	  (clsnl (xwem-cl-normal-list xwem-clients predic))
	  (clns (mapcar
		 (lambda (cl)
		   (cons (xwem-client-name cl clsnl) cl))
		 clsnl))
	  (name (flet ((iswitchb-make-buflist
			(default)
			(setq iswitchb-buflist (mapcar (lambda (cl) (car cl)) clns))))
		  (iswitchb-read-buffer prompt))))

     (while clns
       (when (string= (caar clns) name)
	 (setq rcl (cdar clns))
	 (setq clns nil))
       (setq clns (cdr clns)))
     rcl)))

;;;###autoload(autoload 'xwem-cl-switch "xwem-clients" "" t)
(define-xwem-command xwem-cl-switch (arg)
  "Interactively switch to some client window, using 'iswitchb.
When used with prefix ARG, then filter clients to selected widow only."
  (xwem-interactive "P")

  (let* ((pred (when arg
		 (lambda (cl)
		   (eq (xwem-cl-win cl) (xwem-win-selected)))))
	 (cl (xwem-read-client (if arg "XWEM-CL win: "
				 "XWEM-CL: ")
			       pred)))
    (when cl
      (xwem-manda-manage cl))
  ))

;;;###autoload(autoload 'xwem-cl-switch-other-win "xwem-clients" "" t)
(define-xwem-command xwem-cl-switch-other-win (cl &optional arg)
  "Switch to CL in other window.
When used with prefix ARG, then focuse to that other window."
  (xwem-interactive "cXWEM-CL Other: \nP")

  (let ((wn (xwem-win-next (xwem-win-selected)))
	(xwem-cl-manage-hook nil))	; skip setup hooks

    (when cl
      (when (xwem-win-only-one-p (xwem-win-selected))
	(xwem-frame-split-vert nil)
	(setq wn (xwem-win-next (xwem-win-selected))))

      (when wn
	(xwem-manda-manage cl wn)

	(when arg
	  (xwem-window-select wn)))
      )))

;;;###autoload(autoload 'xwem-cl-switch-other-frame "xwem-clients" "" t)
(define-xwem-command xwem-cl-switch-other-frame (cl &optional arg)
  "Switch to CL in other XWEM frame.
When used with prefix ARG, then create embedded frame, if creation is
needed at all."
  (xwem-interactive "cXWEM-CL Other frame: \nP")

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

    (xwem-manda-manage cl (xwem-frame-selwin ofr))
    (xwem-frame-select ofr))
  )

;;;###autoload(autoload 'xwem-cl-switch-to-other "xwem-clients" "" t)
(define-xwem-command xwem-cl-switch-to-other (n &optional window)
  "Switch to other client."
  (xwem-interactive "p")

  (let* ((win (or window (xwem-win-selected)))
	 (ocl (xwem-win-cl win)))
    (while (> n 0)
      (setq ocl (xwem-cl-other ocl))
      (setq n (- n 1)))
    (if (xwem-cl-p ocl)
	(xwem-manda-manage ocl win)
      (xwem-message 'note "No other client available."))))

;;;###autoload(autoload 'xwem-cl-switch-to-other-in-other-win "xwem-clients" "" t)
(define-xwem-command xwem-cl-switch-to-other-in-other-win (n)
  "Like `xwem-cl-switch-to-other', but in other window."
  (xwem-interactive "p")

  (xwem-cl-switch-to-other n (xwem-window-other 1)))
	 
;;;###autoload(autoload 'xwem-kill-cl-and-window "xwem-clients" "" t)
(define-xwem-command xwem-kill-cl-and-window (arg)
  "Kill selected client and window.
If used with prefix ARG then kill client in other window and other
window (not implemented)."
  (xwem-interactive "P")

  (let* ((win (if arg (xwem-window-other 1) (xwem-win-selected)))
	 (cl (xwem-win-cl win)))

    (when (xwem-cl-p cl)
      ;; Deassociate CL from WIN so no client will be managed when we
      ;; kill CL.
      (setf (xwem-cl-win cl) nil)
      (setf (xwem-win-cl win) nil)
      (xwem-client-kill t cl)

      ;; Make sure CL is removed from clients list
      (xwem-remove-client cl))

    (xwem-window-delete win)
    (xwem-frame-redraw (xwem-win-frame win))
  ))

;;;###autoload(autoload 'xwem-cl-transpose "xwem-clients" "" t)
(define-xwem-command xwem-cl-transpose (arg &optional cl)
  "Transpose CL with client at right in CL's WIN.
If ARG is non-nil transpose with left client.
If CL is ommited than selected client will be used."
  (xwem-interactive "P")

  (let* ((cl (or cl (xwem-cl-selected)))
         (sw (xwem-cl-win cl))
	 (tai (cadr (member cl (funcall (if arg 'reverse 'identity) (xwem-win-make-cl-list sw))))))
    (when (not (xwem-cl-p tai))
      (setq tai (cadr (member cl (funcall (if arg 'identity 'reverse) (xwem-win-make-cl-list sw))))))

    (when (and (xwem-cl-p cl) (xwem-cl-p tai))
      (xwem-list-exchange-els xwem-clients cl tai)

      (run-hook-with-args 'xwem-win-clients-change-hook sw))
    ))

(defun xwem-client-rearrange-top (cl)
  "Move CL on top of `xwem-clients'."
  (when (xwem-win-selected-p (xwem-cl-win cl))
    (setq xwem-clients (cons cl (delete cl xwem-clients))))

  nil)					;continue hooks processing

;;;###autoload
(defun xwem-init-clients ()
  "Clients part initializer"
  (xwem-message 'msg "Initializing clients ... wait")

  (setq xwem-clients nil)

  ;; Gentle handling of window splitting
  (add-hook 'xwem-win-after-split-hook 'xwem-cl-other-on-split)

  (when xwem-cl-use-set-focus
    (add-hook 'xwem-cl-manage-hook 'xwem-client-focus))

  (when xwem-cl-use-recent-cl-on-top
    (add-hook 'xwem-cl-manage-hook 'xwem-client-rearrange-top))
;    (add-hook 'xwem-cl-demanage-hook 'xwem-cl-bury))

  ;; Setup
  (when xwem-cl-use-parent-xwin
    (add-hook 'xwem-cl-create-hook 'xwem-cl-parent-on-creation)
    (add-hook 'xwem-cl-destroy-hook 'xwem-cl-parent-on-destroy)
    (add-hook 'xwem-cl-state-change-hook 'xwem-cl-parent-on-change-state))
  )

;;;###autoload
(defun xwem-client-sendmsg-atom (cl atom &optional time)
  "Send Client message to client CL."
  (XSendEvent (xwem-dpy) (xwem-cl-xwin cl) nil 0
	      (X-Create-message
	       (list [1 X-ClientMessage] ;type
		     [1 32]		;format
		     [2 1000]		;XXX seq
		     [4 (X-Win-id (xwem-cl-xwin cl))] ; window
		     [4 (X-Atom-id (X-Atom-find-by-name (xwem-dpy) "WM_PROTOCOLS"))]
		     [4 (X-Atom-id atom)]
		     [4 (or time X-CurrentTime)]
		     [4 nil]))))

(defun xwem-client-close (cl)
  "Close xwem client CL in safe manner.
Return non-nil, if CL supports WM_DELETE_WINDOW."
  (when (XWMProtocol-set-p (xwem-dpy) (xwem-hints-wm-protocols (xwem-cl-hints cl)) "WM_DELETE_WINDOW")
    (xwem-client-sendmsg-atom cl (X-Atom-find-by-name (xwem-dpy) "WM_DELETE_WINDOW"))
    t))

;;;###autoload
(defun xwem-client-focus (cl &optional revto force)
  "Focus xwem client's CL window.
By default this function does useful things only if CL is selected CL
or FORCE is non-nil.
Return non-nil, if CL supports WM_TAKE_FOCUS."
  (when (or force
	    (and (xwem-cl-p cl) (eq cl (xwem-cl-selected))))
    (xwem-focus-set (xwem-cl-xwin cl))

    ;; TODO: - we can't use WM_TAKE_FOCUS here because X-CurrentTime
    ;; disalowed as timestamp, we need some real event
    ;; (xwem-last-xevent?) to get timestamp from.
;    (when (XWMProtocol-set-p (xwem-dpy) (xwem-hints-wm-protocols (xwem-cl-hints cl)) "WM_TAKE_FOCUS")
;      (xwem-client-sendmsg-atom cl (X-Atom-find-by-name (xwem-dpy) "WM_TAKE_FOCUS")))))

    ))

;;;###autoload
(defun xwem-client-change-state (cl state)
  "Change WM_STATE for CL, STATE is one of 'managed, 'iconified, 'withdrawn, etc."
  (let ((old-state (xwem-cl-state cl)))
    (setf (xwem-cl-state cl) state)

    (XSetWMState (xwem-dpy) (xwem-cl-xwin cl)
                 (cond ((eq state 'managed) X-NormalState)
                       ((eq state 'normal) X-NormalState)

                       ((eq state 'iconified) X-IconicState)

                       (t X-WithdrawnState)))

    (run-hook-with-args 'xwem-cl-state-change-hook cl old-state state)
    ))

;;;###autoload
(defsubst xwem-cl-managed-p (cl &optional win)
  "Return non-nil if client CL is managed, i.e. has 'managed or 'normal state."
  (and (or (not win) (eq (xwem-cl-win cl) win))
       (or (eq (xwem-cl-state cl) 'managed)
           (eq (xwem-cl-state cl) 'managed-current))))

;;; Creating new client
(defun xwem-cl-presetup (cl)
  "Reparent client CL. CL should be already setuped.
NOTE: specials clients presetuped as any other."
  (let ((xwin (xwem-cl-xwin cl)))

    (if (not (xwem-frame-p (xwem-frame-find 'xwin xwin)))
        (progn
          ;; Normal client(not an embedded frame)
          (XSelectInput (xwem-dpy) xwin (xwem-cl-ev-mask cl))
          (X-Win-EventHandler-add-new xwin 'xwem-cl-events-handler 100))

      ;; Embedded frame
      (XSelectInput (xwem-dpy) xwin (Xmask-or xwem-frame-ev-mask (xwem-cl-ev-mask cl)))
      (X-Win-EventHandler-add-new xwin 'xwem-cl-events-handler 100
                                  (list X-PropertyNotify X-FocusIn X-FocusOut X-LeaveNotify X-EnterNotify)))
    ;; XXX
    (XSetWindowBorderWidth (xwem-dpy) xwin 0)

    ;; Fetch some window properties
    (setf (xwem-cl-hints cl)
	  (make-xwem-hints :wm-normal-hints (XGetWMNormalHints (xwem-dpy) xwin)
			   :wm-hints (XGetWMHints (xwem-dpy) xwin)
			   :wm-class (XGetWMClass (xwem-dpy) xwin)
			   :wm-command (XGetWMCommand (xwem-dpy) xwin)
			   :wm-name (XGetWMName (xwem-dpy) xwin)
			   :wm-transient-for (XGetWMTransientFor (xwem-dpy) xwin)
			   :wm-protocols (XGetWMProtocols (xwem-dpy) xwin)))

    (when (zerop (length (xwem-hints-wm-name (xwem-cl-hints cl))))
      ;; WMNAME is empty
      (setf (xwem-hints-wm-name (xwem-cl-hints cl)) "<noname>"))

    (setf (xwem-cl-transient-for cl)
	  (xwem-hints-wm-transient-for (xwem-cl-hints cl)))

    ))

;;;###autoload
(defun xwem-make-client (win &optional props xwem-win)
  "Make new client window.
WIN   - X Window.
PROPS - Properties list for new client.
XWEM-WIN - xwem window where new client should be managed(if possible)."

  (let (attrs new-cl)
    (when (setq attrs (xwem-misc-xwin-valid-p win)) ; just to check that window still alive
      (setq new-cl (make-xwem-cl :plist props))

      (setf (xwem-cl-xwin new-cl) win)
      (X-Win-put-prop win 'xwem-cl new-cl)
      (X-Dpy-log (xwem-dpy) "New Client making name=%s\n" '(XGetWMName (xwem-dpy) win))

      (xwem-cl-presetup new-cl)

      (setf (xwem-cl-xattrs new-cl) attrs)
      (setf (xwem-cl-xgeom new-cl) (XGetGeometry (xwem-dpy) win))
      (setf (xwem-cl-start-time new-cl) (current-time))

      ;; Add to clients list, because manage function from manda may use
      ;; it.
      (setq xwem-clients (cons new-cl xwem-clients))

      ;; Walk manage database to find how to deal with this client
      (let ((mdis (xwem-manda-find-inst new-cl)))
        (if (not mdis)
            (progn
              (xwem-message 'err "Client not in manage database")
              (error "Client not described in manage database"))

          (setf (xwem-cl-manda new-cl) mdis)

          ;; Check for Win's expectations
          (let ((wmcmd (xwem-hints-wm-command (xwem-cl-hints new-cl)))
                (dwin nil))		;destination win
	      
            ;; Find a window who expects NEW-CL
            (setq dwin
                  (catch 'dwin
                    (mapc (lambda (fr)
                            (xwem-win-map
                             (lambda (win)
                               (when (> (xwem-win-get-expt win wmcmd) 0)
                                 (xwem-win-expt-dec win wmcmd)
                                 (throw 'dwin win)))
                             (xwem-frame-selwin fr)))
                          xwem-frames-list)))
	    
            ;; Setup focus mode
            (xwem-focus-mode-set new-cl xwem-default-focus-mode)

            ;; Run new client hook
            (run-hook-with-args 'xwem-cl-create-hook new-cl)

            ;; Finnally manage new client
            (if (xwem-win-p dwin)
                (xwem-manda-manage new-cl dwin)
              (xwem-manda-manage new-cl)))
          )))
    ))


;; Operations on other clients
(defun xwem-cl-manage-other-cl (cl &optional win)
  "Manage other client to CL in WIN."
  (let ((ocl (xwem-cl-other cl)))
    (when (xwem-cl-p ocl)
      (xwem-manda-manage ocl win))))

(defun xwem-cl-other-on-split (win how new-size)
  "Manage current WIN's cl in othen window.
To be used in `xwem-win-after-split-hook'.
HOW is split type.
NEW-SIZE is size of newly created window."
  (when xwem-cl-other-on-split
    (xwem-cl-manage-other-cl (xwem-win-cl win) (xwem-win-next win))))


;; Commands
;;;###autoload(autoload 'xwem-client-turn-on-other-on-split "xwem-clients" "" t)
(define-xwem-command xwem-client-turn-on-other-on-split ()
  "Turn on `xwem-cl-other-on-split' minor mode."
  (xwem-interactive)

  (setq xwem-cl-other-on-split t)
  (xwem-message 'info "Other on split minor mode is ON."))

;;;###autoload(autoload 'xwem-client-turn-off-other-on-split "xwem-clients" "" t)
(define-xwem-command xwem-client-turn-off-other-on-split ()
  "Turn off `xwem-cl-other-on-split' minor mode."
  (xwem-interactive)

  (setq xwem-cl-other-on-split nil)
  (xwem-message 'info "Other on split minor mode is OFF."))

;;;###autoload(autoload 'xwem-client-toggle-other-on-split "xwem-clients" "" t)
(define-xwem-command xwem-client-toggle-other-on-split (arg)
  "Toggle `xwem-cl-other-on-split' minor mode.
Negative ARG turns it off, positive turns it on."
  (xwem-interactive "P")

  (if (numberp arg)
      (if (> arg 0)
	  (setq xwem-cl-other-on-split nil)
	(setq xwem-cl-other-on-split t)))

  (if xwem-cl-other-on-split
      (xwem-client-turn-off-other-on-split)
    (xwem-client-turn-on-other-on-split)))
  
;;;###autoload(autoload 'xwem-client-kill "xwem-clients" "" t)
(define-xwem-command xwem-client-kill (arg &optional cl)
  "Kill xwem client CL. Also destroys CL's X window.
If used with prefix ARG is given, force CL to die, by default WM_DELETE_WINDOW will be probed.
If CL is `nil' than client in `xwem-win-selected' assumed."
  ;; TODO: - take icccm stuff(like WM_DELETE_WINDOW) into account
  ;;       - switch to other client
  (xwem-interactive (list xwem-prefix-arg (xwem-cl-selected)))

  (let ((client (or cl (xwem-cl-selected))))
    (if (xwem-cl-p client)
	(if arg
            ;; Force killing
            (XDestroyWindow (xwem-dpy) (xwem-cl-xwin client))
          ;; else try soft killing
	  (or (xwem-client-close client) (xwem-client-kill t client)))

      (xwem-message 'warn "No Active client found."))))

;;;###autoload(autoload 'xwem-client-query-kill "xwem-clients" "" t)
(define-xwem-command xwem-client-query-kill (arg client)
  "Kill CLIENT.
Prefix ARG directly passed to `xwem-client-kill'."
  (xwem-interactive (list
                    xwem-prefix-arg
                    ;; Sort clients, so selected client will be first
                    (let* ((csel (xwem-cl-selected))
                           (xwem-clients (sort (copy-list xwem-clients)
                                               (lambda (cl1 cl2)
                                                 (eq cl1 csel)))))
                      (xwem-read-client "Kill client: "))))

  (when (xwem-cl-p client)
    (xwem-client-kill arg client))
  )

;;;###autoload(autoload 'xwem-client-demanage-others "xwem-clients" "" t)
(define-xwem-command xwem-client-demanage-others (arg)
  "Demanage others then selected client in selected window.
If ARG given, remain ARG most recent clients."
  (xwem-interactive "p")

  (let* ((win (xwem-win-selected))
         (rcls (nthcdr arg (xwem-win-make-cl-list-sort-by-recency win))))
    ;; cls in RCLS already demanaged
    (mapc (lambda (cl)
            (setf (xwem-cl-state cl) 'unknown))
          rcls)

    ;; If something changed, run on-change hooks
    (when rcls
      (run-hook-with-args 'xwem-win-clients-change-hook win))
    ))

;;;###autoload(autoload 'xwem-client-run-copy "xwem-clients" "" t)
(define-xwem-command xwem-client-run-copy (arg &optional cl)
  "Run the same command as selected CL.
With prefix arg run it in other window.
With double prefix arg run in other window and select.
With numeric prefix arg run ARG copies."
  (xwem-interactive "P")
  
  (let* ((cl (or cl (xwem-cl-selected)))
         (nw (and (xwem-cl-p cl) (xwem-cl-win cl))))

    (if (not (xwem-cl-p cl))
	(xwem-message 'warn "No client selected to copy.")

      (let ((cmd (xwem-hints-wm-command (xwem-cl-hints cl)))
	    (cnt (if (numberp arg) arg 1)) ;how many clients to start
	    (i 0))
	(if (or (not (stringp cmd)) (string= cmd ""))
	    (xwem-message 'warn "Invalid cmd: \"%s\"" cmd)

	  (when (and (listp arg) (not (null arg)))
	    (setq nw (xwem-win-next nw))
	    (when (not (xwem-win-p nw))
	      ;; Create window
	      (xwem-frame-split-vert nil)
	      (setq nw (xwem-win-next (xwem-win-selected))))

	    (when (xwem-win-p nw)
	      (when (= (prefix-numeric-value arg) 4)
		(xwem-win-expt-inc nw cmd cnt))

	      (when (= (prefix-numeric-value arg) 16)
		(xwem-window-select-maybe-redraw nw))))

	  (when (xwem-win-p nw)
	    (while (< i cnt)
	      (xwem-execute-program cmd)
	      (setq i (1+ i))))
    )))))

;;;###autoload(autoload 'xwem-client-run-copy-other-win "xwem-clients" "" t)
(define-xwem-command xwem-client-run-copy-other-win (arg &optional cl)
  "Run copy of selected client in other window.
With prefix ARG, make horizontal split instead of vertical if split
really needed."
  (xwem-interactive "P")

  (let ((cl (or cl (xwem-cl-selected)))
        (xwem-win-after-split-hook nil)  ; prevent hooks
        cmd own)
    (when (or (not (xwem-cl-p cl))
              (not (xwem-win-p (xwem-cl-win cl))))
      (error "Can't run copy of invalid client"))

    (setq cmd (xwem-hints-wm-command (xwem-cl-hints cl)))
    (setq own (xwem-window-other 1 (xwem-cl-win cl)))

    (when cmd
      ;; 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))))

      ;; Install expectance
      (xwem-win-expt-inc own cmd)

      ;; Finnaly run command
      (xwem-execute-program cmd))
    ))

;;;###autoload(autoload 'xwem-client-run-copy-other-frame "xwem-clients" "" t)
(define-xwem-command xwem-client-run-copy-other-frame (arg &optional cl)
  "Run copy of selected client in other frame.
If prefix ARG is specified, create embedded frame, if creation is
needed at all."
  (xwem-interactive "P")

  (let ((cl (or cl (xwem-cl-selected)))
        cmd ofr)

    (when (or (not (xwem-cl-p cl))
              (not (xwem-frame-p (xwem-cl-frame cl))))
      (error "Can't run copy of invalide client"))

    (setq cmd (xwem-hints-wm-command (xwem-cl-hints cl)))
    (setq ofr (xwem-frame-other (xwem-cl-frame cl)))
    (when cmd
      (unless (xwem-frame-p ofr)
        (setq ofr (xwem-make-frame-1 arg nil nil t)))

      ;; Setup expectance
      (xwem-win-expt-inc (xwem-frame-selwin ofr) cmd)

      (xwem-frame-select ofr)

      ;; Finnaly run command
      (xwem-execute-program cmd))
    ))

(defun xwem-cl-prog-geom (cl)
  "Get program specified geometry for CL."
  (let ((wmnh (xwem-hints-wm-normal-hints (xwem-cl-hints cl))))
    (if (and wmnh (X-WMSize-psize-p wmnh))
	(cons (X-WMSize-width wmnh)	;program specified width
	      (X-WMSize-height wmnh))	;program specified height
      nil)))

(defun xwem-cl-base-geom (cl)
  "Return base width and height for CL."
  (let ((wmnh (xwem-hints-wm-normal-hints (xwem-cl-hints cl))))
    (if (and wmnh (X-WMSize-pbasesize-p wmnh))
	(cons (X-WMSize-base-width wmnh)	;base width
	      (X-WMSize-base-height wmnh))	;base height
      nil)))

(defun xwem-cl-min-geom (cl)
  "Returns minimal geometry for CL."
  (let ((wmnh (xwem-hints-wm-normal-hints (xwem-cl-hints cl))))
    (if (and wmnh (X-WMSize-pminsize-p wmnh))
	(cons (X-WMSize-min-width wmnh)
	      (X-WMSize-min-height wmnh))
      nil)))

(defun xwem-cl-step-geom (cl)
  "Returns vertical and horisontal step's width for CL."
  (let ((wmnh (xwem-hints-wm-normal-hints (xwem-cl-hints cl))))
    (if (and wmnh (X-WMSize-presizeinc-p wmnh))
	(cons (X-WMSize-width-inc wmnh)
	      (X-WMSize-height-inc wmnh))
      nil)))

;;;###autoload
(defun xwem-cl-get-usize (cl)
  "Returns cons cell (uwi . uhe) - CL's size in steps."
  (let* ((clgmt (xwem-cl-xgeom cl))
	 (wmnh (xwem-hints-wm-normal-hints (xwem-cl-hints cl)))
	 (steps (xwem-cl-step-geom cl))
	 (base (xwem-cl-base-geom cl))
	 (minsize (xwem-cl-min-geom cl))
	 (uwi (X-Geom-width clgmt))
	 (uhe (X-Geom-height clgmt)))
	 
    (if (and steps
	     (not (= (car steps) 0))
	     (not (= (cdr steps) 0)))
	(when (or base minsize)
	  (progn
	    (setq uwi (- uwi (if (X-WMSize-pbasesize-p wmnh)
				 (car base)
			       (car minsize))))
	    (setq uhe (- uhe (if (X-WMSize-pbasesize-p wmnh)
				 (cdr base)
			       (cdr minsize))))))
      (setq steps '(1 . 1)))

    (cons (/ uwi (car steps))
	  (/ uhe (cdr steps)))))

;;;###autoload
(defun xwem-cl-get-psize (cl)
  "Return pixel size of CL (pwi . phe)."
  (let ((gmt (xwem-cl-xgeom cl)))
    (cons (X-Geom-width gmt) (X-Geom-height gmt))))

(unless (fboundp 'subtract-time)
  (defun subtract-time (t1 t2)
    "Subtract two internal times."
    (let ((borrow (< (cadr t1) (cadr t2))))
      (list (- (car t1) (car t2) (if borrow 1 0))
	    (- (+ (if borrow 65536 0) (cadr t1)) (cadr t2))))))

;;;###autoload
(defun xwem-cl-get-uptime (cl &optional format)
  "Return CL's uptime.
FORMAT can contain %-sequences to substitute parts of the uptime.
%d is replaced by the days
%h is replaced by the hours
%m is replaced by the minutes
%s is replaced by the seconds
%A is replaced by autogenerated format."
  (let ((upt (nth 1 (subtract-time (current-time) (xwem-cl-start-time cl))))
	(fmt (or format "%A"))
	(days 0)
	(hours 0)
	(minutes 0)
	(seconds 0)
	(rup ""))
    
    (when (> upt (* 60 60 24))
      (setq days (/ upt (* 60 60 24))))

    (when (> upt (* 60 60))
      (setq hours (% (/ upt (* 60 60)) 24)))

    (when (> upt 60)
      (setq minutes (% (/ upt 60) 60)))

    (setq seconds (% upt 60))

    (let ((flst (string-to-list fmt))
	  chr)
      (while flst
	(setq chr (car flst))
	(cond ((= chr ?%)
	       (setq flst (cdr flst))
	       (setq chr (car flst))
	       (cond ((= chr ?d)
		      (setq rup (concat rup (format "%d" days))))
		     ((= chr ?h)
		      (setq rup (concat rup (format "%d" hours))))
		     ((= chr ?m)
		      (setq rup (concat rup (format "%d" minutes))))
		     ((= chr ?s)
		      (setq rup (concat rup (format "%d" seconds))))
		     ((= chr ?A)
		      (setq rup (concat
				 (cond ((> days 0) (format "%dd %dh" days hours))
				       ((> hours 0) (format "%dh %dm" hours minutes))
				       ((> minutes 0) (format "%dm %ds" minutes seconds))
				       ((> seconds 0) (format "%d seconds" seconds))
				       (t "")))))
		     (t (error "Invalid format"))))
		  
	      (t (setq rup (concat rup (char-to-string chr)))))
	(setq flst (cdr flst))))
    rup))

;;;###autoload(autoload 'xwem-client-info "xwem-clients" "" t)
(define-xwem-command xwem-client-info (&optional cl)
  "Display info about xwem client CL."
  (xwem-interactive)

  (let ((client (or cl (xwem-cl-selected))))
    (if (xwem-cl-p client)
	(let ((usz (xwem-cl-get-usize client))
	      (psz (xwem-cl-get-psize client)))
	  (xwem-message 'info "id: 0x%d, usize: %dx%d, psize: %dx%d, uptime: %s, name: `%s'"
			(X-Win-id (xwem-cl-xwin client))
			(car usz) (cdr usz)
			(car psz) (car psz)
			(xwem-cl-get-uptime client)
			(xwem-client-name client)))
      (xwem-message 'warn "No active clients found.")))
  )

;;;###autoload(autoload 'xwem-cl-pop-to-client "xwem-clients" "" t)
(define-xwem-command xwem-cl-pop-to-client (cl &optional warp)
  "Pop to client CL, i.e. switch to its frame and manage it.
If CL have no frame, popup it in current frame."
  (xwem-interactive "cXWEM-CL Pop: ")

  (if (xwem-cl-alive-p cl)
    (let ((fr (or (xwem-cl-frame cl) (xwem-frame-selected)))
	  (clw (or (xwem-cl-win cl) (xwem-win-selected))))
      (when (not (xwem-frame-selected-p fr))
	(xwem-frame-select fr))
      (when (not (xwem-win-selected-p clw))
	(xwem-window-select-maybe-redraw clw))
      (xwem-manda-manage cl clw)

      (when warp
	(XWarpPointer (xwem-dpy) X-None (xwem-cl-xwin cl) 0 0 0 0 10 10)))

    (xwem-message 'info "Can't jump to dead client ..")))

;;;###autoload(autoload 'xwem-cl-set-title "xwem-clients" "" t)
(define-xwem-command xwem-cl-set-title (title &optional cl)
  "Set new TITLE for client CL."
  (xwem-interactive "sNet title: ")

  (let ((ccl (xwem-win-cl (or cl (xwem-win-selected)))))
    (if (not (xwem-cl-p ccl))
	(error "No currently selected client.")
      (XSetWMName (xwem-dpy) (xwem-cl-xwin ccl) title))))

;;;###autoload(autoload 'xwem-client-unset-mark "xwem-clients" "" t)
(define-xwem-command xwem-client-unset-mark (&optional cl)
  "Uset mark on CL."
  (xwem-interactive (list (xwem-cl-selected)))

  (when (member cl xwem-cl-mark-ring)
    (setq xwem-cl-mark-ring (delete cl xwem-cl-mark-ring))

    ;; Now run on-mark hooks
    (run-hook-with-args 'xwem-cl-mark-hook cl 'unmark)))
  
;;;###autoload(autoload 'xwem-client-set-mark "xwem-clients" "" t)
(define-xwem-command xwem-client-set-mark (arg &optional cl)
  "Mark selected client CL.
If CL is ommited or `xwem-client-set-mark' called interactively then
selected client assumed.
With no prefix ARG push selected client to `xwem-cl-mark-ring'.
With ARG, jump to last marked client, pop value from `xwem-cl-mark-ring'."
  (xwem-interactive (list xwem-prefix-arg
			  (if xwem-prefix-arg
			      (pop xwem-cl-mark-ring)
			    (xwem-cl-selected))))

  (unless (xwem-cl-p cl)
    (if arg
	(error "Empty `xwem-cl-mark-ring'.")
      (error "No selected client.")))

  (if arg
      (progn
	;; Put client at the end of `xwem-cl-mark-ring'
	(if xwem-cl-mark-ring
	    (setcdr (last xwem-cl-mark-ring) (cons cl nil))
	  (setq xwem-cl-mark-ring (cons cl nil)))
	(xwem-cl-pop-to-client cl))

    ;; Push cl and adjust `xwem-cl-mark-ring' according to
    ;; `xwem-cl-mark-ring-max' value if needed.
    (when (= (length xwem-cl-mark-ring) xwem-cl-mark-ring-max)
      ;; Remove last item
      (xwem-client-unset-mark (car (last xwem-cl-mark-ring))))

    (push cl xwem-cl-mark-ring)

    ;; Now run on-mark hooks
    (run-hook-with-args 'xwem-cl-mark-hook cl 'mark)

    (xwem-message 'info "Marking selected client, total ring size %d"
		  (length xwem-cl-mark-ring))
    ))

;;;###autoload
(defun xwem-fini-clients ()
  "Fini all clients."
  (while xwem-clients
    ;; TODO: finalize client in (car xwem-clients)
    (setq xwem-clients (cdr xwem-clients))))

;;;###autoload
(defun xwem-client-hide (cl &optional new-state)
  "Hide CL's window. Optionally you may specify NEW-STATE."
  ;; Just move off the screen
  (XMoveWindow (xwem-dpy) (xwem-cl-xwin cl)
               (X-Geom-width (xwem-rootgeom))
               (X-Geom-height (xwem-rootgeom)))

  (XUnmapWindow (xwem-dpy) (xwem-cl-xwin cl))
  (xwem-client-change-state cl (or new-state 'iconified))
  )

;;;###autoload
(defun xwem-client-show (cl &optional new-state)
  "Show xwem client CL."
  ;; Make sure CL's frame is CL's parent
  (XReparentWindow (xwem-dpy) (xwem-cl-xwin cl)
                   (xwem-frame-xwin (xwem-cl-frame cl))
                   (X-Geom-width (xwem-rootgeom)) (X-Geom-height (xwem-rootgeom)))

  (if (xwem-cl-transient-for cl)
      (XRaiseWindow (xwem-dpy) (xwem-cl-xwin cl))

    ;; Must be lowered
    (XLowerWindow (xwem-dpy) (xwem-cl-xwin cl)))

  (XMoveWindow (xwem-dpy) (xwem-cl-xwin cl)
               (X-Geom-x (xwem-cl-xgeom cl))
               (X-Geom-y (xwem-cl-xgeom cl)))

  (XMapWindow (xwem-dpy) (xwem-cl-xwin cl))
  (xwem-client-change-state cl (or new-state 'managed-current))
  )


;;; Events handling for client windows
(defun xwem-cl-hproperty (cl xev)
  "PropertyNotify."
  (let ((xwin (xwem-cl-xwin cl))
        (atom-id (X-Atom-id (X-Event-xproperty-atom xev)))
        (state (X-Event-xproperty-state xev))
        rhook)

    ;; Some CL's property changed
    (X-Dpy-log (xwem-dpy) "CLIENT .. PropertyNotify: Atom-id = %d\n" 'atom-id)

    (cond 
     ((and (= atom-id (X-Atom-id XA-wm-normal-hints)) (= state X-PropertyNewValue))
      (setf (xwem-hints-wm-normal-hints (xwem-cl-hints cl)) (XGetWMNormalHints (xwem-dpy) xwin))
      (setq rhook 'xwem-cl-wmnh-change-hooks))

     ((and (= atom-id (X-Atom-id XA-wm-hints)) (= state X-PropertyNewValue))
      (setf (xwem-hints-wm-hints (xwem-cl-hints cl)) (XGetWMHints (xwem-dpy) xwin))
      (setq rhook 'xwem-cl-wmh-change-hooks))

     ((and (= atom-id (X-Atom-id XA-wm-class)) (= state X-PropertyNewValue))
      (setf (xwem-hints-wm-class (xwem-cl-hints cl)) (XGetWMClass (xwem-dpy) xwin))
      (setq rhook 'xwem-cl-wmclass-change-hooks))

     ((and (= atom-id (X-Atom-id XA-wm-command)) (= state X-PropertyNewValue))
      (setf (xwem-hints-wm-command (xwem-cl-hints cl)) (XGetWMCommand (xwem-dpy) xwin))
      (setq rhook 'xwem-cl-wmcommand-chage-hooks))

     ((and (= atom-id (X-Atom-id XA-wm-name)) (= state X-PropertyNewValue))
      (setf (xwem-hints-wm-name (xwem-cl-hints cl)) (XGetWMName (xwem-dpy) xwin))
      (unless (equal (xwem-hints-wm-name (xwem-cl-hints cl)) (xwem-cl-saved-name cl))
        (setf (xwem-cl-saved-name cl) (xwem-hints-wm-name (xwem-cl-hints cl)))
        (setq rhook 'xwem-cl-wmname-change-hooks)))
     )

    ;; Run RHOOK
    (when rhook
      (run-hook-with-args rhook cl))
    ))

(defun xwem-cl-hconfigure-request (cl xev)
  "ConfigureRequest event XEV."
  )

;;;###autoload
(defun xwem-cl-hdestroy-notify (cl xev)
  "DestroyNotify event XEV."
  (setf (xwem-cl-state cl) 'destroyed)
  (xwem-manda-demanage cl 'destroyed)

  (xwem-remove-client cl)

  ;; Now run on-destroy hooks
  (run-hook-with-args 'xwem-cl-destroy-hook cl)

  ;; Make client not valid for futher referencing
  (X-invalidate-cl-struct cl)
  )

(defun xwem-cl-hunmap-notify (cl xev)
  "UnmapNotify event XEV."
  )

(defun xwem-cl-hmap-notify (cl xev)
  "MapNotify event XEV."
  )

(defun xwem-cl-hmap-request (cl xev)
  "MapRequest event XEV."
  (X-Dpy-log (X-Event-dpy xev) "XWEM-ROOT-HMAP-REQUEST: win=%S\n" (X-Event-win xev))

  (let ((cl (xwem-find-client (X-Event-win xev))))
    (if (xwem-cl-p cl)
	(xwem-manda-manage cl)

      (xwem-make-client (X-Event-win xev)))
    ))

(defun xwem-cl-hclient-message (cl xev)
  "ClientMessage event XEV."
  (let ((type (length (X-Event-xclient-msg xev))))	; 5 -> 32, 10 -> 16, 20 -> 8

    (X-Dpy-log (xwem-dpy) "XWEM-CLIENT: in ClientMessage: type=%S msg(0)=%S\n"
               'type  '(car (nth 0 (X-Event-xclient-msg xev))))

    (cond ((and (= type 5)
                (= (car (nth 0 (X-Event-xclient-msg xev))) X-IconicState))
           (xwem-manda-iconify cl))
          )
    ))

(defun xwem-cl-events-handler (xdpy xwin xev)
  "Events handler for root window."
  (X-Dpy-log xdpy "CLIENT HANDLER: xev type=%S, win=%S\n" '(X-Event-name xev) '(X-Win-id (X-Event-win xev)))

  (let ((cl (X-Win-get-prop xwin 'xwem-cl)))
    (when (xwem-cl-p cl)
      (X-Event-CASE xev
        ((:X-KeyPress :X-ButtonPress :X-ButtonRelease)
         (xwem-kbd-handle-keybutton xev))

        ;; Focusing mode
        (:X-FocusIn (xwem-focus-mode-invoke cl 'focus-in xev))
        (:X-FocusOut (xwem-focus-mode-invoke cl 'focus-out xev))
        (:X-EnterNotify (xwem-focus-mode-invoke cl 'enter xev))
        (:X-LeaveNotify (xwem-focus-mode-invoke cl 'leave xev))

        ;; Various events
        (:X-PropertyNotify (xwem-cl-hproperty cl xev))
        (:X-MapRequest (xwem-cl-hmap-request cl xev))
        (:X-ConfigureRequest (xwem-cl-hconfigure-request cl xev))
        (:X-ClientMessage (xwem-cl-hclient-message cl xev))

        (:X-DestroyNotify
         (setq cl (xwem-find-client (X-Event-xdestroywindow-window xev)))
         (when (xwem-cl-p cl)
           (xwem-cl-hdestroy-notify cl xev)))

        ;; Not really used now, but ...
        (:X-UnmapNotify (xwem-cl-hunmap-notify cl xev))
        (:X-MapNotify (xwem-cl-hmap-notify cl xev))
        )
      )))

;;; CL's parent xwin hacks
(defun xwem-cl-parent-on-creation (cl)
  "CL just created."
  (xwem-cl-put-prop cl 'parent-xwin
    (XCreateWindow (xwem-dpy) nil 0 0 1 1 0 nil nil nil (make-X-Attr))))

(defun xwem-cl-parent-on-change-state (cl old-state new-state)
  "CL changed state."
  (let ((pwin (xwem-cl-get-prop cl 'parent-xwin)))
    (when (X-Win-p pwin)
      (cond ((or (eq new-state 'managed)
                 (eq new-state 'iconified)
                 (eq new-state 'demanaged))
             ;; Some applications, such as mozilla, when running with
             ;; -remote tries to find another mozilla instance to run
             ;; in it, it seaches lowerest client, but it is not
             ;; guarantied, because xwem frame holds many clients.
             (XReparentWindow (xwem-dpy) (xwem-cl-xwin cl) pwin 0 0)
             (XLowerWindow (xwem-dpy) (xwem-cl-xwin cl)))
            )
      )))

(defun xwem-cl-parent-on-destroy (cl)
  "CL is about to be destroyed."
  (let ((pwin (xwem-cl-get-prop cl 'parent-xwin)))
    (when (X-Win-p pwin)
      (XDestroyWindow (xwem-dpy) pwin))))


(provide 'xwem-clients)

;;; xwem-clients.el ends here
