;;; xwem-keyboard.el --- Keyboard support for XWEM.

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

;; Authors: Zajcev Evgeny <zevlg@yandex.ru>
;;	    Alex Ott <ottalex@narod.ru>
;; Created: 21 Mar 2003
;; Keywords: xwem, xlib
;; X-CVS: $Id: xwem-keyboard.el,v 1.8 2004/07/14 08:38:56 youngs 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:
;;
;; `xwem-global-map' is normal keymap used by xwem.
;;
;; Set `xwem-keyboard-echo-keystrokes' to t if you want echoing of
;; incomplete commands in echo area.

;;; Code:


(eval-when-compile
  (require 'xwem-clients))
(require 'xlib-xtest)
(require 'xwem-compat)

;;{{{ [-] Custamizable xwem-keyboard group

;;; Customize variables
(defgroup xwem-keyboard nil
  "Group to customize keyboard in XWEM."
  :prefix "xwem-"
  :group 'xwem)

(defcustom xwem-pre-command-hook nil
  "*Hooks to run just before executing command.
This may examine `xwem-this-command' variable to find out which
command is about to be run, or may change it to cause a different
command to run."
  :type 'hook
  :group 'xwem-keyboard
  :group 'xwem-hooks)

(defcustom xwem-post-command-hook nil
  "*Hooks to run after command execution."
  :type 'hook
  :group 'xwem-keyboard
  :group 'xwem-hooks)

(defcustom xwem-keyboard-echo-keystrokes t
  "*If non-nil than echo unfinished commands in echo area."
  :type 'boolean
  :group 'xwem-keyboard)

(defcustom xwem-hyper-modifier 'hyper
  "*This is a little trick of how ``H'' interpretted in `xwem-kbd' specification."
  :type '(choice (const :tag "Meta" meta)
		 (const :tag "Control" control)
		 (const :tag "Super" super)
		 (const :tag "Hyper" hyper))
  :group 'xwem-keyboard)

(defcustom xwem-meta-modifier 'meta
  "*This is a little trick of how ``M'' interpretted in `xwem-kbd' specification."
  :type '(choice (const :tag "Meta" meta)
		 (const :tag "Control" control)
		 (const :tag "Super" super)
		 (const :tag "Hyper" hyper))
  :group 'xwem-keyboard)
		 
(defcustom xwem-control-modifier 'control
  "*This is a little trick of how ``C'' interpretted in `xwem-kbd'."
  :type '(choice (const :tag "Meta" meta)
		 (const :tag "Control" control)
		 (const :tag "Super" super)
		 (const :tag "Hyper" hyper))
  :group 'xwem-keyboard)

(defcustom xwem-kbd-evillocks (list XK-NumLock XK-Caps-Lock)
  "List of evil locks."
  :type `(repeat (choice (const :tag "NumLock" ,XK-NumLock)
                         (const :tag "CapsLock" ,XK-Caps-Lock)
                         ;; TODO: add others .. which?
                         ))
  :group 'xwem-keyboard)

(defvar xwem-kbd-evilmasks (list 0)
  "List of evil masks.
Internal variable, DO NOT MODIFY.")

(defcustom xwem-quit-key [(hyper ?g)]
  "Quit command key."
  :type 'sexp
  :group 'xwem-keyboard)

(defcustom xwem-quit-command 'xwem-keyboard-quit
  "Default command to be called when `xwem-quit-key' pressed."
  :type 'function
  :group 'xwem-keyboard)

(defcustom xwem-help-key [(hyper ?h)]
  "Help command key."
  :type 'sexp
  :group 'xwem-keyboard)

(defcustom xwem-prefix-help-command 'xwem-describe-prefix-bindings
  "Default command to be called when `xwem-help-key' pressed."
  :type 'function
  :group 'xwem-keys)

(defcustom xwem-universal-key [(hyper ?u)]
  "Key for universal argument commands."
  :type 'sexp
  :group 'xwem-keyboard)

(defcustom xwem-kbd-quit-hook nil
  "*Hooks to be runned when KBD exits.
Runned only on \\<xwem-global-map>\\[xwem-kbd-quit], but not on
\\<xwem-global-map>\\[xwem-keyboard-quit]."
  :type 'hook
  :group 'xwem-keyboard
  :group 'xwem-hooks)

;;}}}

;;{{{ [-] Internal variables

;;;###autoload
(defvar xwem-override-global-map nil
  "Keymap that overrides only `xwem-global-map'.
But can't override `xwem-kbd-private-prefix-map'!
You should *bind* this, not set it.")

;;;###autoload
(defvar xwem-override-map nil
  "Keymap that overrides all other keymaps.
But can't override `xwem-kbd-private-prefix-map'!
You should *bind* this, not set it.")

;;;###autoload
(defvar xwem-kbd-now-grabbing nil
  "Non-nil indicates that we now grabbing keyboard.
Internal variable, do not modify.")

(defvar xwem-xkeys-mapping nil
  "X KeyMapping fetched from X server.
Internal variable, do not modify.")

(defvar xwem-kbd-private-modifiers (make-vector 7 nil)
  "Private modifers [shift lock control meta hyper super numlocks].
Internal variable, do not modify.")

(defvar xwem-xmods-mapping nil
  "X ModifierMapping fetched from X server.
Internal variable, do not modify.")

;;;###autoload
(defvar xwem-event-window nil "Window that receive last keypress event.")
;;;###autoload
(defvar xwem-last-event nil "Last keypress event.")
;;;###autoload
(defvar xwem-last-xevent nil "Last keypress/buttonpress X Event.")
;;;###autoload
(defvar xwem-this-command-keys [] "List of pressed keys to execute command.")
;;;###autoload
(defvar xwem-this-command nil "The command now being executed.")
;;;###autoload
(defvar xwem-last-command nil "The last command executed.")

;; Private variables
(defvar xwem-kbd-private-prefix-map nil
  "Private variable holds prefix keymap or symbol that holds keymap.
Internal variable, do not modify.")

(defvar xwem-kbd-last-prefix-map nil "Last value of `xwem-kbd-private-prefix-map'.")

;; Special modes for reading key or keysequence
(defvar xwem-kbd-reading-key nil
  "Non-nil mean we are reading for key.
Actually references symbol to which save readed key.
Internal variable, do not modify.")

(defvar xwem-kbd-reading-keyseq nil
 "Non-nil mean we are reading key sequence.
Actually references symbol to which save readed key sequence.
Internal variable, do not modify.")

;;}}}


;;{{{ [-] Reading key and keysequence

(defvar xwem-saved-this-command-keys nil
  "Saved value of `xwem-this-command-keys'.")

;;;###autoload
(defun xwem-kbd (spec)
  "Just like `kbd' but take into account values of `xwem-hyper-modifier' and `xwem-meta-modifier'."
  (let ((keys (key-sequence-list-description (kbd spec))))
    (mapvector (lambda (key)
		 (let ((rkey (last key))
		       (rmods (butlast key)))
		   (when (member 'meta key)
		     (setq rmods (delete 'meta rmods))
		     (setq rkey (cons xwem-meta-modifier rkey)))
		   (when (member 'hyper key)
		     (setq rmods (delete 'hyper rmods))
		     (setq rkey (cons xwem-hyper-modifier rkey)))
                   (when (member 'control key)
                     (setq rmods (delete 'control rmods))
                     (setq rkey (cons xwem-control-modifier rkey)))

		   (when rmods
		     (setq rkey (nconc rmods rkey)))
		   rkey))
	       keys)))

(defun xwem-read-keys-start (keyseq-p keyvar)
  "Start reading key or key sequence.
KEYSEQ-P is non-nil when staring reading key sequence.
KEYVAR is place where to store readed key or key sequence."
  (xwem-kbd-start-grabbing)

  (setq xwem-saved-this-command-keys xwem-this-command-keys)
  (setq xwem-this-command-keys [])
  (if keyseq-p
      (setq xwem-kbd-reading-keyseq keyvar)
    (setq xwem-kbd-reading-key keyvar))

  (xwem-recursive-edit))

(defun xwem-read-keys-stop (keyseq-p)
  "Stop reading key or key sequence.
If KEYSEQ-P is non-nil than stop reading key sequence."
  (set (if keyseq-p xwem-kbd-reading-keyseq xwem-kbd-reading-key)
       xwem-this-command-keys)
  (if keyseq-p
    (setq xwem-kbd-reading-keyseq nil)
    (setq xwem-kbd-reading-key nil))

  (xwem-kbd-set-current-prefix-keymap nil)
  (setq xwem-this-command-keys xwem-saved-this-command-keys)

  (xwem-exit-recursive-edit))

;; Read key, install active grab
;;;###autoload
(defun xwem-read-key (&optional prompt no-minib-focus-p)
  "Read single key press, prompting PROMPT in `xwem-minibuffer'.
If NO-MINIB-FOCUS-P is non-nil, focus `xwem-minibuffer' while reading."
  (let ((xwem-keyboard-echo-keystrokes t)
	key)

    (when prompt
      (xwem-message 'msg prompt))

    (if no-minib-focus-p
	(xwem-read-keys-start nil 'key)

      (xwem-under-minib-focus
       (xwem-read-keys-start nil 'key)))

    (aref key 0)))

;; Read keysequence which binds to command
;;;###autoload
(defun xwem-read-key-sequence (&optional prompt)
  "Read key sequence that call command prompting PROMPT."
  (let ((xwem-keyboard-echo-keystrokes t)
	keys)
    (xwem-under-minib-focus
     (when prompt
       (xwem-message 'msg prompt))

     (xwem-read-keys-start t 'keys))
    keys))

;;}}}

;;{{{ [-] Defining new key

;;;###autoload
(defun xwem-define-key (win keymap key command)
  "Add KEY to KEYMAP to execute COMMAND and grab KEY on WIN.
When command is `nil', then undefine KEY in KEYMAP and ungrab KEY."
  (define-key keymap key command)
  (xwem-kbd-graugra-key key win (if command 'grab 'ungrab)))

;;;###autoload
(defun xwem-global-set-key (key command)
  "Define KEY to call COMMAND, when xwem is already run.
If command is `nil' then undefine KEY in `xwem-global-map' and ungrab KEY."
  (define-key xwem-global-map key command)
  (mapc (lambda (frm)
	  (xwem-kbd-graugra-key key (xwem-frame-xwin frm)
				(if command 'grab 'ungrab)))
	xwem-frames-list))

;;}}}

;;{{{ [-] local keymap

;;;###autoload
(defun xwem-local-map (cl)
  "Return local map for CL."
  (and (xwem-cl-p cl) (xwem-cl-get-prop cl 'xwem-local-keymap)))

;;;###autoload
(defun xwem-local-set-key (key command &optional cl)
  "Set KEY to call COMMAND in CL's local keymap.
If COMMAND is `nil' then undefine KEY in CL's local map and ungrab KEY.
If CL is ommited `xwem-cl-selected' assumed."
  (let* ((ccl (or cl (xwem-cl-selected)))
         (kmap (xwem-local-map ccl)))

    (unless (keymapp kmap)
      ;; Create new local keymap for client
      (setq kmap (make-sparse-keymap))
      (set-keymap-parents kmap (list xwem-global-map))
      (xwem-cl-put-prop ccl 'xwem-local-keymap kmap))

    (define-key kmap key command)
    (xwem-kbd-graugra-key key (xwem-cl-xwin ccl)
                          (if command 'grab 'ungrab))))

;;}}}

;;{{{ [-] Undefined command processing

;;;###autoload(autoload 'xwem-undefined-command "xwem-keyboard" "" t)
(define-xwem-command xwem-undefined-command ()
  "Called when key is not binded."
  (xwem-interactive)
  (xwem-message 'warn "Command undefined for key %S." xwem-last-event))

;;;###autoload(autoload 'xwem-self-insert-or-undefined "xwem-keyboard" "" t)
(define-xwem-command xwem-self-insert-or-undefined (arg)
  "Self insert or undefined command.
Prefix ARG specifies how many characters to insert."
  (xwem-interactive "*_p")
  
  (let ((lev xwem-last-event))
    ;; TODO:
    ;;   * Check is LEV is actually self insertable event
    (if arg
	(xwem-key-send-ekeys (make-vector arg lev))
      
      (xwem-message 'warn "%s is not defined, prefix arg is %S."
		    (key-description xwem-this-command-keys) arg)
    )))

;;}}}

;;{{{ [-] Quiting keyboarding

;;;###autoload(autoload 'xwem-keyboard-quit "xwem-keyboard" "" t)
(define-xwem-command xwem-keyboard-quit ()
  "Send quit signal."
  (xwem-interactive)
  
  (signal 'quit '(xwem))
  (xwem-message 'info "quit."))

;;;###autoload(autoload 'xwem-kbd-quit "xwem-keyboard" "" t)
(define-xwem-command xwem-kbd-quit ()
  "Quit from keyboard haldling."
  (xwem-interactive)

  (xwem-kbd-stop-grabbing)
  (setq xwem-kbd-private-prefix-map nil)
  (XSetInputFocus (xwem-dpy) X-PointerRoot X-RevertToPointerRoot X-CurrentTime)
  (xwem-message 'note "[kbd-quit] InputFocus is PonterRoot, prfxmap is nil.")

  (run-hooks 'xwem-kbd-quit-hook)
  )

;;}}}

;;{{{ [-] Initializators

(defun xwem-kbd-initialize-private-modifiers ()
  "Create internal modifier representation to speedup futher work.
Also update `xwem-kbd-evilmasks' if `xwem-kbd-evillocks' is non-nil."
  (setq xwem-kbd-private-modifiers (make-vector 7 nil))
  (let* ((ctrls (list (car (xwem-kbd-xksym->xkcode XK-Control-L))
		      (car (xwem-kbd-xksym->xkcode XK-Control-R))))
         (locks (list (car (xwem-kbd-xksym->xkcode XK-Caps-Lock))))
	 (shifts (list (car (xwem-kbd-xksym->xkcode XK-Shift-L))
		       (car (xwem-kbd-xksym->xkcode XK-Shift-R))))
	 (metas (list (car (xwem-kbd-xksym->xkcode XK-Meta-L))
		      (car (xwem-kbd-xksym->xkcode XK-Meta-R))))
	 (hypers (list (car (xwem-kbd-xksym->xkcode XK-Hyper-L))
		       (car (xwem-kbd-xksym->xkcode XK-Hyper-R))))
	 (supers (list (car (xwem-kbd-xksym->xkcode XK-Super-L))
		       (car (xwem-kbd-xksym->xkcode XK-Super-R))))
         (numlocks (list (car (xwem-kbd-xksym->xkcode XK-NumLock))))
         (evils (mapcar (lambda (ks)
                          (car (xwem-kbd-xksym->xkcode ks))) xwem-kbd-evillocks))
	 (mlist (mapcar 'truncate (list X-Shift X-Lock X-Control X-Mod1 X-Mod2
                                        X-Mod3 X-Mod4 X-Mod5)))
	 (slist (car (last xwem-xmods-mapping))))
    
    (while slist
      ;; Update some private modifier mask
      (when (intersection (car slist) shifts)
	(aset xwem-kbd-private-modifiers 0 (cons (car mlist) (aref xwem-kbd-private-modifiers 0))))
      (when (intersection (car slist) locks)
	(aset xwem-kbd-private-modifiers 1 (cons (car mlist) (aref xwem-kbd-private-modifiers 1))))
      (when (intersection (car slist) ctrls)
	(aset xwem-kbd-private-modifiers 2 (cons (car mlist) (aref xwem-kbd-private-modifiers 2))))
      (when (intersection (car slist) metas)
	(aset xwem-kbd-private-modifiers 3 (cons (car mlist) (aref xwem-kbd-private-modifiers 3))))
      (when (intersection (car slist) hypers)
	(aset xwem-kbd-private-modifiers 4 (cons (car mlist) (aref xwem-kbd-private-modifiers 4))))
      (when (intersection (car slist) supers)
	(aset xwem-kbd-private-modifiers 5 (cons (car mlist) (aref xwem-kbd-private-modifiers 5))))
      (when (intersection (car slist) numlocks)
	(aset xwem-kbd-private-modifiers 6 (cons (car mlist) (aref xwem-kbd-private-modifiers 6))))

      ;; Update Evil locks
      (when (intersection (car slist) evils)
        (push (car mlist) xwem-kbd-evilmasks))

      (setq slist (cdr slist))
      (setq mlist (cdr mlist)))))

;;;###autoload
(defun xwem-kbd-init ()
  "Init part for keys.
Fetches KeyboardMapping from the X server and stores it in
`xwem-xkeys-mapping'"
  (xwem-message 'msg "Initializing keyboard ... wait")
  (xwem-kbd-set-current-prefix-keymap nil)

  ;; Hmm FSFmacs issued "invalid instraction" in `XGetKeyboardMapping'
  (setq xwem-xkeys-mapping
 	(XGetKeyboardMapping (xwem-dpy)
 			     (X-Dpy-min-keycode (xwem-dpy))
 			     (- (X-Dpy-max-keycode (xwem-dpy))
				(X-Dpy-min-keycode (xwem-dpy)))))

  (setq xwem-xmods-mapping
	(XGetModifierMapping (xwem-dpy)))

  ;; Initialize `xwem-kbd-private-modifiers'
  (xwem-kbd-initialize-private-modifiers)

  ;; Initialize keyboard macrosing
  (xwem-keymacro-init)
  )

;;}}}

;;{{{ [-] Converters

;; Convertors
(defun xwem-kbd-xksym->emacs (ksym)
  "Convert KSYM to Emacs key symbol."
  (cond
   ;; ksym is list for buttons
   ((listp ksym)
    (let ((kval (car ksym)))
      (cond ((= kval 1) 'button1)
	    ((= kval 2) 'button2)
	    ((= kval 3) 'button3)
	    ((= kval 4) 'button4)
	    ((= kval 5) 'button5)
	    (t nil))))			;can't be!!!

   ((= ksym XK-BackSpace) 'backspace)
   ((= ksym XK-Tab) 'tab)
   ((= ksym XK-Linefeed) 'linefeed)
   ((= ksym XK-Return) 'return)
   ((= ksym XK-Escape) 'escape)
   ((= ksym XK-Delete) 'delete)

   ((= ksym XK-Home) 'home)
   ((= ksym XK-End) 'end)
   ((= ksym XK-Left) 'left)
   ((= ksym XK-Right) 'right)
   ((= ksym XK-Up) 'up)
   ((= ksym XK-Down) 'down)

   ((= ksym XK-Insert) 'insert)
   ((= ksym XK-Pause) 'pause)
   ((= ksym XK-Space) 'space)
   ;; TODO: add more

   ((= ksym XK-F1) 'f1)
   ((= ksym XK-F2) 'f2)
   ((= ksym XK-F3) 'f3)
   ((= ksym XK-F4) 'f4)
   ((= ksym XK-F5) 'f5)
   ((= ksym XK-F6) 'f6)
   ((= ksym XK-F7) 'f7)
   ((= ksym XK-F8) 'f8)
   ((= ksym XK-F9) 'f9)
   ((= ksym XK-F10) 'f10)
   ((= ksym XK-F11) 'f11)
   ((= ksym XK-F12) 'f12)

   ((= ksym 0) nil)

   (t (XCharacter ksym))))		;nil or proper character

(defun xwem-kbd-emacs->xksym (ksym)
  "Convert back from Emacs key symbol KSYM to proper X key symbol."
  (cond ((null ksym) 0)			;hmm

	((symbolp ksym)
	 (let ((osymname (symbol-name ksym))
	       (symname (downcase (symbol-name ksym))))
	   (cond ((string= symname "backspace") XK-BackSpace)
		 ((string= symname "tab") XK-Tab)
		 ((string= symname "linefeed") XK-Return) ;XXX
		 ((string= symname "linefeed") XK-Linefeed)
		 ((string= symname "return") XK-Return)
		 ((string= symname "escape") XK-Escape)
		 ((string= symname "delete") XK-Delete)
		 ((string= symname "space") XK-Space)

		 ((string= symname "home") XK-Home)
		 ((string= symname "end") XK-End)
		 ((string= symname "left") XK-Left)
		 ((string= symname "right") XK-Right)
		 ((string= symname "up") XK-Up)
		 ((string= symname "down") XK-Down)

		 ((string= symname "insert") XK-Insert)
		 ((string= symname "pause") XK-Pause)

		 ;; Mouse buttons
		 ((string= symname "button1") (list X-XButton1))
		 ((string= symname "button2") (list X-XButton2))
		 ((string= symname "button3") (list X-XButton3))
		 ((string= symname "button4") (list X-XButton4))
		 ((string= symname "button5") (list X-XButton5))

		 ;; Functional keys
		 ((string-match "[fF]\\([0-9]+\\)" symname)
		  (symbol-value
		   (intern
		    (concat "XK-F"
			    (substring symname (match-beginning 1)
				       (match-end 1))))))

		 (t (Xforcenum (string-to-char osymname))))))

	((characterp ksym) (Xforcenum ksym)) ;Should not be there

	(t 0)))				;HMM!

(defun xwem-kbd-emods->xmodmask (emods)
  "Convert Emacs modifiers list EMODS to X modifers mask."
  (Xmask-or
   (if (member 'control emods) (xwem-kbd-controlmask) 0)
   (if (member 'shift emods) (xwem-kbd-shiftmask) 0)
   (if (member 'meta emods) (xwem-kbd-metamask) 0)
   (if (member 'hyper emods) (xwem-kbd-hypermask) 0)
   (if (member 'super emods) (xwem-kbd-supermask) 0)))

(defun xwem-kbd-xmodmask->emods (mmask)
  "Convert X modifiers mask MMASK to Emacs modifiers list."
  (let (rmods)
    (when (Xtest mmask (xwem-kbd-controlmask))
      (push 'control rmods))
    (when (Xtest mmask (xwem-kbd-shiftmask))
      (push 'shift rmods))
    (when (Xtest mmask (xwem-kbd-hypermask))
      (push 'hyper rmods))
    (when (Xtest mmask (xwem-kbd-metamask))
      (push 'meta rmods))
    (when (Xtest mmask (xwem-kbd-supermask))
      (push 'super rmods))
    rmods))

;; keysyms and keycodes converters
(defun xwem-kbd-xksym->xkcode (ksym)
  "Convert keysym KSYM to keycode.
Convert keysym to cons cell where car is keycode and cdr is modifiers
list, using `xwem-xkeys-mapping' list.
NOTE: only 'shift modifier supported."
  (setq ksym (float ksym))		; for sure
  (let ((kslist (car (last xwem-xkeys-mapping)))
	(kcode (X-Dpy-min-keycode (xwem-dpy)))
	(kmods nil)
	kel)

    (while kslist
      (setq kel (car kslist))
      (if (member ksym kel)
	  (progn
	    (cond ((= ksym (nth 0 kel)) nil)
		  ((= ksym (nth 1 kel))
		   (setq kmods (cons 'shift kmods)))
		  (t nil))
	    (setq kslist nil))

	(setq kslist (cdr kslist))
	(setq kcode (1+ kcode))
	))
    (cons kcode kmods)))

(defun xwem-kbd-xkcode->xksym (kcode)
  "Convert key code KCODE to keysym.
KeyCode -> KeySyms list in form (base shift caps ShiftCaps)."
  (nth (- kcode (X-Dpy-min-keycode (xwem-dpy))) (car (last xwem-xkeys-mapping)))
  )

;;; Various subroutines
;;;###autoload
(defun xwem-kbd-emod->kcode (emod &optional any)
  "Convert Emacs modifier EMOD to X keycode.
Behaviour is undefined If ANY argument is supplied.
DO NOT RELY ON THIS FUNCTION."
  (let* ((mods (car (last xwem-xmods-mapping)))
	 (rmod (cond ((eq emod 'shift) (nth 0 mods))
		     ;; locks skiped
		     ((eq emod 'control) (nth 2 mods))
		     ((eq emod 'meta) (nth 3 mods))
		     ;; numlock skiped
		     ((eq emod 'hyper) (nth 5 mods))
		     ((eq emod 'super) (nth 6 mods))
		     (t (error (format "Bad modifier `%S'" emod))))))
    (if any
	rmod
      (car rmod))))

;;;###autoload
(defun xwem-kbd-kcode->emod (kcode)
  "Convert key code KCODE to Emacs modifier, if KCODE is actually a modifier.
See also `xwem-kbd-kcode-modifier-p'."
  (let* ((mods (car (last xwem-xmods-mapping)))
	 (rmod (cond ((member kcode (nth 0 mods)) 'shift)
		     ;; locks skiped
		     ((member kcode (nth 2 mods)) 'control)
		     ((member kcode (nth 3 mods)) 'meta)
		     ;; numlock skiped
		     ((member kcode (nth 5 mods)) 'hyper)
		     ((member kcode (nth 6 mods)) 'super)
		     (t nil))))
    rmod))

;;;###autoload
(defun xwem-kbd-kcode-modifier-p (kcode)
  "Return non-nil if key code KCODE is modifier."
  (let ((mods (car (last xwem-xmods-mapping))))
    (while (and mods
		(not (member kcode (car mods))))
      (setq mods (cdr mods)))
    (car mods)))

(defun xwem-kbd-adjust-keycode (keycode modifiers)
  "Convert KEYCODE to keysym according to MODIFIERS."
  ;; XXX only 'shift modifier supported
  (if (and (member 'shift modifiers)
	   (> (cadr (xwem-kbd-xkcode->xksym keycode)) 0))
      (cadr (xwem-kbd-xkcode->xksym keycode))

    (car (xwem-kbd-xkcode->xksym keycode))))

(defun xwem-kbd-adjust-modifiers (keycode modifiers)
  "According to KEYCODE adjust MODIFIERS, i.e. remove 'shift."
  (if (and (member 'shift modifiers)
	   keycode (> (cadr (xwem-kbd-xkcode->xksym keycode)) 0))
      ;; 'shift in modifiers and keysym is valid, so we remove 'shift
      (remove 'shift modifiers)
    
    modifiers))

;;;###autoload
(defun xwem-kbd-xevents->emacs-events (xevs &optional trust-modbits)
  "Convert X-Events XEVS to Emacs events.

If TRUST-MODBITS is non-nil than we can trust modifier bits in
X-Event, otherwise we are trying to keep track of modifiers presses
and releases.  This is needed because core X events obtained from
RECORD extension does not have valid inforamtion about modifiers
bits."

  ;; NOTE: events garbbed using RECORD extension does not have correct
  ;; state field.
  (let ((rxevs (cond ((listp xevs) (vconcat xevs))
		     ((vectorp xevs) xevs)
		     (t xevs)))
	eevs xevtype kcode mbutton current-modifiers)

    ;; TODO:
    ;;   - Change `mapcar' to `mapvector'
    (setq eevs
	  (mapcar (lambda (xev)
		    (setq xevtype (X-Event-type xev))

		    (unless (member xevtype (list X-KeyPress X-KeyRelease X-ButtonPress X-ButtonRelease X-MotionNotify))
		      (error "Invalid event type: %s" (X-Event-name xev)))

		    (setq kcode nil
			  mbutton nil)
		    (cond ((member xevtype (list X-KeyPress X-KeyRelease))
			   (setq kcode (X-Event-xkey-keycode xev)))
			  ((member xevtype (list X-ButtonPress X-ButtonRelease))
			   (setq mbutton (X-Event-xbutton-button xev))))

		    (if (xwem-kbd-kcode-modifier-p kcode)
			;; KCODE is actually modifier
			(if (= (X-Event-type xev) X-KeyPress)
			    (setq current-modifiers (cons (xwem-kbd-kcode->emod kcode) current-modifiers))
			  (setq current-modifiers (delete (xwem-kbd-kcode->emod kcode) current-modifiers)))

		      ;; Skip normal key realese events
		      (unless (eq xevtype X-KeyRelease)

			;; If we can trust modifier bits, get information about
			;; modifiers currently pressed from state field.
			(when trust-modbits
			  (setq current-modifiers
				(xwem-kbd-xmodmask->emods
				 (cond ((eq xevtype X-KeyPress) (X-Event-xkey-state xev))
				       ((member xevtype (list X-ButtonPress X-ButtonRelease))
					(X-Event-xbutton-state xev))
				       ((eq xevtype X-MotionNotify) (X-Event-xmotion-state xev))))))

			(make-event (cond ((eq xevtype X-KeyPress) 'key-press)
					  ((eq xevtype X-ButtonPress) 'button-press)
					  ((eq xevtype X-ButtonRelease) 'button-release)
					  ((eq xevtype X-MotionNotify) 'motion)
					  (t (error "Unknown event: %s" (X-Event-name xev))))
				    (nconc (when (member xevtype (list X-ButtonPress X-ButtonRelease X-MotionNotify))
					     (list 'x (cond ((member xevtype (list X-ButtonPress X-ButtonRelease))
							     (X-Event-xbutton-root-x xev)) ; XXX what about 'channel?
							    (t (X-Event-xmotion-root-x xev)))
						   'y (cond ((member xevtype (list X-ButtonPress X-ButtonRelease))
							     (X-Event-xbutton-root-y xev)) ; XXX what about 'channel?
							    (t (X-Event-xmotion-root-y xev)))))
					   (list 'modifiers (xwem-kbd-adjust-modifiers kcode current-modifiers))
					   (when (eq xevtype X-KeyPress)
					     (list 'key (xwem-kbd-xksym->emacs
							 (xwem-kbd-adjust-keycode kcode current-modifiers))))
					   (when (member xevtype (list X-ButtonPress X-ButtonRelease))
					     (list 'button mbutton)))))
		      ))
		  rxevs))
    
    ;; Remove non-events from list
    (delete* nil eevs :test (lambda (el1 el2) (not (eventp el2))))
    ))

(defun xwem-kbd-emacs-events->xevents (events)
  "Convert Emacs EVENTS list to X events list."
  )

;;;###autoload
(defun xwem-kbd-ekeys->eevents (ekeys)
  "Convert Emacs keys sequence EKEYS to Emacs events vector."
  (mapvector (lambda (key)
	       (let (mods keychar)

		 (if (listp key)
		     (progn
		       (setq keychar (car (last key)))
		       (setq mods (butlast key)))
		   (setq keychar key))

		 (make-event 'key-press (list 'modifiers mods
					      'key keychar))))
	     ekeys))

;;}}}

;;{{{ [-] Sending

;; Sending(using XTEST)
(defun xwem-key-sendseq (keycode-seq)
  "Emulate KEYCODE-SEQ.
KEYCODE-SEQ is list of cons cells where car is event type and cdr is keycode.
Supported event types are `X-Xtest-KeyPress' and `X-Xtest-KeyRelease'."
  (mapc (lambda (ksel)
	  (let ((ktype (car ksel))
		(kcode nil)
		(ktime nil))
	    (cond ((vectorp (cdr ksel))
		   (setq kcode (aref (cdr ksel) 0))
		   (setq ktime (aref (cdr ksel) 1)))
		  (t
		   (setq kcode (cdr ksel))
		   (setq ktime X-CurrentTime)))
	    (X-XTest-FakeInput (xwem-dpy) ktype kcode X-None 0 0 ktime)))
	keycode-seq))

;;;###autoload
(defun xwem-key-send-ekeys (keys)
  "Send Emacs key sequence KEYS using XTEST extension."
  (let (lseq)
    (mapc (lambda (key)
	    (let (mods code)
	      (setq mods (mapcar (lambda (mm)
				   (xwem-kbd-emod->kcode mm))
				 (butlast key)))

		;; Now calculade key CODE maybe add shift modifier
		(setq code (xwem-kbd-xksym->xkcode
			    (xwem-kbd-emacs->xksym (car (last key)))))
		(setq mods (nconc mods (mapcar (lambda (mm)
						 (xwem-kbd-emod->kcode mm))
					       (cdr code))))
		(setq code (car code))

		(mapc (lambda (mod)
			(setq lseq (cons (cons X-Xtest-KeyPress mod) lseq)))
		      mods)
		(setq lseq (cons (cons X-Xtest-KeyPress code) lseq))
		(setq lseq (cons (cons X-Xtest-KeyRelease code) lseq))
		(mapc (lambda (mod)
			(setq lseq (cons (cons X-Xtest-KeyRelease mod) lseq)))
		      mods)
		))
	  (key-sequence-list-description keys))
    
    (setq lseq (nreverse lseq))
    (xwem-key-sendseq lseq)))

;;;###autoload
(defun xwem-kbd-wait-key-release (keycode)
  "Wait for key with KEYCODE for release."
  (unless xwem-executing-kbd-macro

    ;; Increase events queue protecs so no events will be
    ;; processed inside `XIfEvent'.
    (incf (X-Dpy-evq-protects (xwem-dpy)))

    ;; Wait for a keyrelease
    (unwind-protect
	(XIfEvent (xwem-dpy)
		  (lambda (xev)
		    (and (= (X-Event-type xev) X-KeyRelease)
			 (= (X-Event-xkey-keycode xev) keycode))))
		
      ;; Allow later events processing
      (decf (X-Dpy-evq-protects (xwem-dpy))))))

;;;###autoload
(defun xwem-kbd-force-mods-release ()
  "Force release of some modifiers."
  (let* ((xmods (car (last xwem-xmods-mapping)))
	 (mods (list (car (nth 0 xmods))        ; shift
		     (car (nth 2 xmods))	; control
		     (car (nth 3 xmods))	; meta
		     (car (nth 5 xmods))	; hyper
		     (car (nth 6 xmods)))))	; super
    (mapc (lambda (mod)
	    (X-XTest-FakeInput (xwem-dpy) X-Xtest-KeyRelease mod (xwem-rootwin) 0 0))
	  (delete 0 mods))
    ))

(defun xwem-kbd-wait-button-release (button)
  "Wait for BUTTON for release."
  )

;;}}}

;;{{{ [-] keypress/KeyRelease processing

(defun xwem-kbd-echolastkey ()
  "Echo key sequence already pressed in xwem minibuffer."
  (when xwem-keyboard-echo-keystrokes
    ;; XXX if there message from XWEM in minibuffer than add, otherwise
    (if (xwem-interactive-p)
	(append-message 'command (concat (single-key-description xwem-last-event) " "))

      (xwem-clear-message)
      (display-message 'command (key-description xwem-this-command-keys)))))

;;;###autoload
(defun xwem-kbd-current-map ()
  "Return current prefix map."
  (let ((cm (or xwem-kbd-private-prefix-map xwem-override-map
                (xwem-kbd-current-local-map)
                xwem-override-global-map xwem-global-map)))
    (when (symbolp cm)
      (setq cm (symbol-function cm)))
    cm))

;;;###autoload
(defun xwem-kbd-global-map-current-p ()
  "Return non-nil if `xwem-global-map' is current prefix map."
  (eq (xwem-kbd-current-map) (or xwem-override-global-map xwem-global-map)))

;;;###autoload
(defun xwem-kbd-current-local-map ()
  "Return current local keymap."
  (let* ((xwin (X-Event-CASE xwem-last-xevent
                 (:X-KeyPress
                  (X-Event-xkey-child xwem-last-xevent))
                 ((:X-ButtonPress :X-ButtonRelease)
                  (X-Event-xbutton-child xwem-last-xevent))
                 (:X-MotionNotify
                  (X-Event-xmotion-child xwem-last-xevent))))
         (cl (xwem-find-client xwin)))
    (unless (xwem-cl-p cl)
      ;; Last chance
      (setq cl (xwem-find-client xwem-event-window)))

    (and (xwem-cl-p cl) (xwem-local-map cl))))

;;;###autoload
(defun xwem-kbd-set-current-prefix-keymap (newkeymap)
  "Set current keymap to NEWKEYMAP.

Use (xwem-kbd-set-current-prefix-keymap nil) to set current keymap
to `xwem-global-keymap' instead of
(xwem-kbd-set-current-prefix-keymap xwem-global-map)."
  (setq xwem-kbd-private-prefix-map newkeymap))

(defun xwem-kbd-handle-keyrelease (xdpy win xev)
  "On XDPY and window WIN handle KeyRelease event XEV."
  ;; TODO:
  ;;  - modifiers tracker
  nil)

;;;###autoload
(defun xwem-kbd-key-binding (keys &optional keymap accept-default)
  "Return key binding corresponding to KEYS in KEYMAP.
If KEYMAP is ommited, `xwem-global-map' will be used.
`xwem-kbd-key-binding' omits default KEYMAP binding unless
ACCEPT-DEFAULT is non-nil."

  (lookup-key (or keymap (xwem-kbd-current-map)) keys accept-default))

;;;###autoload
(defun xwem-kbd-key-binding-evs (evs &optional keymap accept-default)
  "Return key binding corresponding to Emacs events EVS in KEYMAP.
If KEYMAP is ommited, `xwem-global-map' will be used.
ACCEPT-DEFAULT is the same as for `xwem-kbd-key-binding'."
  (xwem-kbd-key-binding (events-to-keys evs) keymap accept-default))

;;;###autoload
(defun xwem-kbd-handle-keybutton (xev)
  "On display XDPY and window WIN handle KeyPress or ButtonPress event XEV."
  (if (and (= (X-Event-type xev) X-KeyPress)
	   (xwem-kbd-kcode-modifier-p (X-Event-xkey-keycode xev)))
      ;; Seems that we are grabbing keyboard now and modifier
      ;; pressed or it is case when some smart modifier pressed.
      nil

    (xwem-kbd-handle-keybutton-from-emacs
     (car (xwem-kbd-xevents->emacs-events (list xev) t)) xev)))

;;;###autoload
(defun xwem-kbd-handle-keybutton-from-emacs (eev &optional xev)
  "Handle Emacs event EEV originated from XWEM.
Optional X-Event XEV, if passed to obtain X specific information."
  (let (lkm)

    ;; Remember some information about XEV event.
    (when (X-Event-p xev)
      (setq xwem-event-window (X-Event-win xev))
      (setq xwem-last-xevent xev))

    (setq xwem-last-event eev)

    (setq xwem-this-command-keys
	  (vconcat xwem-this-command-keys (vector xwem-last-event)))

    (setq lkm (xwem-kbd-key-binding-evs (vector xwem-last-event)))
    (X-Dpy-log (xwem-dpy) "LOCAL KEYMAP=%S, bind=%S"
               '(xwem-kbd-current-local-map)
               '(xwem-kbd-key-binding (events-to-keys (vector xwem-last-event)))
               )

    ;; XXX -- maybe echoing should be done in `xwem-kbd-process-after-lookup'?
    (xwem-kbd-echolastkey)

    (xwem-kbd-process-after-lookup lkm)))
  
(defun xwem-kbd-process-after-lookup (lkm)
  "Process keymap or command entry LKM after `lookup-key'."
  (X-Dpy-log (xwem-dpy) "lkm = %S\n" 'lkm)

  (let ((slkm lkm)			;save lkm
	(prfx-plist (when (and xwem-kbd-private-prefix-map
			       (symbolp xwem-kbd-private-prefix-map))
		      (symbol-plist xwem-kbd-private-prefix-map)))
	(splist (when (symbolp lkm) (symbol-plist lkm))))

    (when (and (symbolp lkm)
	       (functionp lkm)
	       (keymapp (symbol-function lkm)))
      (setq lkm (symbol-function lkm)))

    (X-Dpy-log (xwem-dpy) "PRFX-PLIST = %S, SPLIST = %S\n" 'prfx-plist 'splist)

    ;; Check for special mode, when we just reading single keystroke
    (when xwem-kbd-reading-key
      (xwem-read-keys-stop nil))

    ;; Last chance to try default command
    (when (null lkm)
      (setq lkm (keymap-default-binding (xwem-kbd-current-map)))
      (setq splist (and (symbolp lkm) (symbol-plist lkm))))

    ;; Check is there need for prefix help or quit command
    (when (and (null lkm)
               xwem-kbd-now-grabbing)
      (setq lkm
	    (let ((etk (events-to-keys (vector xwem-last-event))))
	      (cond ((equal etk xwem-help-key) xwem-prefix-help-command)
		    ((equal etk xwem-quit-key) xwem-quit-command)
		    (t nil)))))

    ;; Now take a look at lkm
    (cond ((null lkm)
	   ;; Check are we reading keysequence now
	   (when xwem-kbd-reading-keyseq
	     (xwem-read-keys-stop t))

           (unless (eq (event-type xwem-last-event) 'button-release)
             (xwem-play-sound 'undefined-key)
             (xwem-message 'info "%s not binded." (key-description xwem-this-command-keys)))

	   (xwem-kbd-stop-grabbing)
	   (xwem-kbd-set-current-prefix-keymap nil)
	   (setq xwem-this-command-keys [])
	   (setq xwem-kbd-reading-key nil)
	   (setq xwem-kbd-reading-keyseq nil)

	   (let ((ex-fun (plist-get prfx-plist 'exit-fun)))
	     (when ex-fun (funcall ex-fun)))
	   )

	  ;; Prefix map
	  ((keymapp lkm)

	   (xwem-kbd-set-current-prefix-keymap slkm)
	   (let ((enter-fun (plist-get splist 'enter-fun)))
	     (when enter-fun (funcall enter-fun)))

	   (xwem-kbd-start-grabbing))

	  ;; Binded command or something else
	  (t

	   ;; Check are we reading keysequence now
	   (when xwem-kbd-reading-keyseq
	     (xwem-read-keys-stop t))

           ;; Reset privat keymap prefix
           (xwem-kbd-set-current-prefix-keymap nil)

	   ;; Now run command or keyboard macro
	   (unwind-protect
	       (condition-case err
		   (cond ((vectorp lkm)
                          ;; Keyboard macro.
                          ;; Wait for keyrelease, ungrab keyboard, than play it.
                          (when (= (X-Event-type xwem-last-xevent) X-KeyPress)
                            (xwem-kbd-wait-key-release (X-Event-xkey-keycode xwem-last-xevent)))
                          (xwem-kbd-stop-grabbing)
                          (xwem-keymacro-internal-play lkm (prefix-numeric-value xwem-prefix-arg)))

			 ((commandp lkm)
                          ;; Execute command
                          (setq xwem-this-command lkm)
                          (run-hooks 'xwem-pre-command-hook)

                          (call-interactively xwem-this-command)

                          (setq xwem-last-command xwem-this-command))

			 (t (error "Unknown lkm %S" lkm)))

		 (error
		  (xwem-play-sound 'command-fail)
		  (xwem-message 'err-nobeep "In cmd(%S): %s" lkm (error-message-string err)))

		 (quit
		  (if (and (boundp 'xwem-bypass-quit)
			   (symbol-value 'xwem-bypass-quit))
		      (signal 'quit (list 'xwem-bypass-quit (symbol-value 'xwem-bypass-quit)))

		  (xwem-play-sound 'quit)
		  (xwem-message 'info "Quit: %s" err))))

             ;; XXX Generic post command processing
             (when (xwem-kbd-global-map-current-p)
               (xwem-kbd-stop-grabbing)
               (setq xwem-this-command-keys []))
             )

	   ;; Run post command hook
	   (run-hooks 'xwem-post-command-hook)
	   )

	  (t (error
	      (format "Hm .. strange lkm=%S" lkm))))))

;;}}}

;;{{{ [-] Grabbing

(defun xwem-kbd-graugra-key (key win mode &optional button-mask)
  "Grab or Ungrab KEY on WIN.
MODE is either 'grab or 'ungrab.
BUTTON-MASK is mask passed to `XGrabButton' if MODE is 'grab and key
is actually a mouse key."
  (let* ((key (aref (key-sequence-list-description key) 0))
	 (kmods (butlast key))
	 (ksyko (xwem-kbd-emacs->xksym (car (last key))))
	 mouse)

    (if (listp ksyko)
	(setq mouse (car ksyko))
      
      (setq ksyko (xwem-kbd-xksym->xkcode ksyko))
      (when (eq (cadr ksyko) 'shift)
	(setq kmods (cons 'shift kmods)))
      (setq ksyko (car ksyko)))

    (setq kmods (xwem-kbd-emods->xmodmask kmods))

    ;; Take into account evil masks
    (mapc (lambda (m1)
            (mapc (lambda (m2)
                    (if mouse
                        (if (eq mode 'grab)
                            (XGrabButton (xwem-dpy) mouse (Xmask-or kmods m1 m2) win
                                         (or button-mask (Xmask-or XM-ButtonPress XM-ButtonRelease)) nil t)
                          (XUngrabButton (xwem-dpy) mouse (Xmask-or kmods m1 m2) win))

                      (if (eq mode 'grab)
                          (XGrabKey (xwem-dpy) ksyko (Xmask-or kmods m1 m2) win t)
                        (XUngrabKey (xwem-dpy) ksyko (Xmask-or kmods m1 m2) win))))
                  xwem-kbd-evilmasks))
          xwem-kbd-evilmasks)
    ))

(defun xwem-kbd-grab-key (key win)
  "Grab KEY on WIN."
  (xwem-kbd-graugra-key key win 'grab))

(defun xwem-kbd-ungrab-key (key win)
  "Stop grabbing KEY on WIN."
  (xwem-kbd-graugra-key key win 'ungrab))

;;;###autoload
(defun xwem-kbd-install-grab (keymap win)
  "Install KEYMAP grabs on X window WIN."
  (map-keymap (lambda (key unused)
		(xwem-kbd-grab-key key win))
	      keymap))

;;;###autoload
(defun xwem-kbd-uninstall-grab (keymap win)
  "Uninstall KEYMAP grabs on X window WIN."
  (map-keymap (lambda (key unused)
		(xwem-kbd-ungrab-key key win))
	      keymap))

;;;###autoload
(defun xwem-kbd-start-grabbing (&optional cursor)
  "Begin grabbing keyboard (some key-prefix is entered).
Optionally you can specify CURSOR to be used, while grabbing."
  (unless xwem-kbd-now-grabbing
    (unless xwem-executing-kbd-macro
      (XGrabKeyboard (xwem-dpy) (or (xwem-focus-xcurrent) (xwem-rootwin)) nil)
      (xwem-mouse-grab (or cursor xwem-cursor-wait)))
    
    (setq xwem-kbd-now-grabbing t)))

;;;###autoload
(defun xwem-kbd-start-grabbing-sync (&optional cursor)
  "Same as `xwem-kbd-start-grabbing', but initiate grabs in Sync mode.
CURSOR argument is same is for `xwem-kbd-start-grabbing'."
  (unless xwem-kbd-now-grabbing
    (unless xwem-executing-kbd-macro
      (XGrabKeyboard (xwem-dpy) (or (xwem-focus-xcurrent) (xwem-rootwin))
                     nil X-GrabModeSync X-GrabModeSync)
      (xwem-mouse-grab (or cursor xwem-cursor-wait))
      )

    (setq xwem-kbd-now-grabbing t)))

;;;###autoload
(defun xwem-kbd-stop-grabbing ()
  "Stop grabbing keyboard."
  (when xwem-kbd-now-grabbing
    (unless xwem-executing-kbd-macro
      (XUngrabKeyboard (xwem-dpy))
      (xwem-mouse-ungrab))

    (setq xwem-kbd-now-grabbing nil)))

;;; FIXME: this does bad, naughty things.
;; ;;;###autoload(autoload 'xwem-kbd-quote-command "xwem-keyboard" "" t)
;; (define-xwem-command xwem-kbd-quote-command ()
;;   "Pass event EV to currently active window.
;; DOES NOT WORK."
;;   (xwem-interactive "_")

;;   (let ((xwin (xwem-focus-xcurrent)))
;;     (when (X-Win-p xwin)
;;       (XGrabKeyboard (xwem-dpy) xwin nil X-GrabModeAsync X-GrabModeSync)
;;       (XGrabPointer (xwem-dpy) xwin (Xmask-or XM-ButtonPress XM-ButtonRelease)
;; 		    xwem-cursor-quote nil X-GrabModeSync)
;;       (XAllowEvents (xwem-dpy) X-SyncBoth)

;;       (xwem-message 'info "[Quote key]")
;;       (unwind-protect
;; 	  (let ((done nil)
;; 		xev)
;; 	    (while (not done)
;; 	      (setq xev (xwem-next-event 1))
;;               (cond ((X-Event-p xev)
;;                      (if (and (member (X-Event-type xev)
;;                                       (list X-KeyPress X-ButtonPress X-ButtonRelease))
;;                               (xwem-kbd-xevents->emacs-events (list xev) t))
;;                          (progn
;;                            (xwem-message 'info "here")
;;                            (XAllowEvents (xwem-dpy) X-ReplayKeyboard)
;;                            (XAllowEvents (xwem-dpy) X-ReplayPointer)
;;                            (xwem-clear-message)
;;                            (setq done t))

;;                        (XAllowEvents (X-Event-dpy xev) X-SyncBoth)))
;;                     (t (setq done t)))))

;; 	(XUngrabKeyboard (xwem-dpy))
;; 	(XUngrabPointer (xwem-dpy))
;; 	))))

;;}}}

;;{{{ [-] Universal argument

;;;###autoload
(defvar xwem-prefix-arg nil
"The value of the prefix argument for this editing command.

It may be a number, or the symbol `-' for just a minus sign as arg, or
a list whose car is a number for just one or more
\\<xwem-global-map>\\[xwem-universal-argument] or `nil' if no argument
has been specified.  This is what `\\(xwem-interactive \"P\"\\)'
returns.")

(defconst xwem-universal-map
  (let ((map (make-sparse-keymap)))
    (set-keymap-default-binding map 'xwem-universal-command)
    (define-key map xwem-universal-key 'xwem-universal-more)
    (define-key map [?-] 'xwem-universal-minus)
    (define-key map [?0] 'xwem-universal-digit)
    (define-key map [?1] 'xwem-universal-digit)
    (define-key map [?2] 'xwem-universal-digit)
    (define-key map [?3] 'xwem-universal-digit)
    (define-key map [?4] 'xwem-universal-digit)
    (define-key map [?5] 'xwem-universal-digit)
    (define-key map [?6] 'xwem-universal-digit)
    (define-key map [?7] 'xwem-universal-digit)
    (define-key map [?8] 'xwem-universal-digit)
    (define-key map [?9] 'xwem-universal-digit)
    map)
  "Keymap used while processing \\<xwem-global-map>\\[xwem-universal-argument].")

(defun xwem-universal-common-begin ()
  "Common begin for universal argument."
  (if xwem-kbd-now-grabbing
      (setq xwem-override-map xwem-universal-map)

    ;; Start grabbing
    (xwem-kbd-start-grabbing)
    (setq xwem-override-map xwem-universal-map)))

;;;###autoload(autoload 'xwem-universal-argument "xwem-keyboard" "" t)
(define-xwem-command xwem-universal-argument ()
  "Begin a numeric argument for the following command.
Digits or minus sign following
\\<xwem-global-map>\\[xwem-universal-argument] make up the numeric
argument.  \\<xwem-global-map>\\[xwem-universal-argument] following the
digits or minus sign ends the argument.
\\<xwem-global-map>\\[xwem-universal-argument] without digits or minus
sign provides 4 as argument.
Repeating \\<xwem-global-map>\\[xwem-universal-argument] without digits or
minus sign multiplies the argument by 4 each time."
  (xwem-interactive)

  (setq xwem-prefix-arg (list 4))
  (xwem-universal-common-begin))

;; A subsequent H-u means to multiply the factor by 4 if we've typed
;; nothing but H-u's otherwise it means to terminate the prefix arg.
;;;###autoload(autoload 'xwem-universal-more "xwem-keyboard" "" t)
(define-xwem-command xwem-universal-more (arg)
  "A subsequent \\<xwem-universal-map>\\[xwem-universal-more] means to
  multiply the factor by 4 if we've typed nothing but
  \\<xwem-universal-map>\\[xwem-universal-more]'s; otherwise it means
  to terminate the prefix arg."
  (xwem-interactive "P")

  (if (consp arg)
      (setq xwem-prefix-arg (list (* 4 (car arg))))
    
    (setq xwem-prefix-arg arg)
    (setq xwem-override-map nil)))

;;;###autoload(autoload 'xwem-universal-minus "xwem-keyboard" "" t)
(define-xwem-command xwem-universal-minus (arg)
  "Begin a negative numeric argument for the next command.
\\<xwem-global-map>\\[xwem-universal-argument] following digits or
minus sign ends the argument."
  (xwem-interactive "P")

  (setq xwem-prefix-arg (cond ((integerp arg) (- arg))
			      ((eq arg '-) nil)
			      (t '-)))
  (xwem-universal-common-begin))

;;;###autoload(autoload 'xwem-universal-digit "xwem-keyboard" "" t)
(define-xwem-command xwem-universal-digit (arg)
  "Part of the numeric argument for the next command.
\\<xwem-global-map>\\[xwem-universal-argument] following digits or
minus sign ends the argument."
  (xwem-interactive "P")

  (let* ((num (event-key xwem-last-event))
	 (digit (- num ?0)))
    (cond ((integerp arg)
	   (setq xwem-prefix-arg (+ (* arg 10) (if (< arg 0) (-  digit) digit))))
	  ((eq arg '-)
	   ;; Treat -0 as just -, so that -01 will work.
	   (setq xwem-prefix-arg (if (zerop digit) '- (- digit))))

	  (t (setq xwem-prefix-arg digit)))

    (xwem-universal-common-begin)))

(defun xwem-reset-this-command-lengths ()
  "For some documentation look at `reset-this-command-lengths'."
  ;; This brokes some things, like H-1 H-2 H-3 will not be properly
  ;; displayed in minibuffer, so i disabled it.

  ;; Also there is notice in event-stream.c to
  ;; `reset-this-command-lengths':
  ;;
  ;;   /* #### I don't understand this at all, so currently it does nothing.
  ;;   If there is ever a problem, maybe someone should investigate. */

  ; (setq xwem-this-command-keys (vector xwem-last-event))
  )

;;;###autoload(autoload 'xwem-universal-command "xwem-keyboard" "" t)
(define-xwem-command xwem-universal-command (arg)
  "Handle universal argument functionality."
  (xwem-interactive "P")

  (setq xwem-prefix-arg arg)
  (xwem-reset-this-command-lengths)
  (xwem-kbd-set-current-prefix-keymap nil)

  (setq xwem-override-map nil)

  (xwem-kbd-process-after-lookup
   (xwem-kbd-key-binding-evs (vector xwem-last-event)))
  )

;;}}}


(provide 'xwem-keyboard)

;;; xwem-keyboard.el ends here
