;;; xwem-strokes.el --- Strokes support by XWEM.

;; Copyright (C) 2003-2005 by XWEM Org.

;; Author: Zajcev Evgeny <zevlg@yandex.ru>
;;         Steve Youngs  <steve@youngs.au.com>
;; Created: Thu Dec  4 17:42:12 MSK 2003
;; Keywords: xwem, xlib
;; X-CVS: $Id: xwem-strokes.el,v 1.10 2005/04/04 19:54:16 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:

;; 

;;; Code:

(require 'strokes)
(require 'xwem-load)
(require 'xwem-misc)

;;; Customisation
(defgroup xwem-strokes nil
  "Group to customize XWEM strokes."
  :prefix "xwem-strokes-"
  :group 'xwem)

(defcustom xwem-strokes-grid 25
  "*XWEM strokes Grid resolution.
Look at `strokes-grid-resolution' for details."
  :type 'integer
  :group 'xwem-strokes)

(defcustom xwem-strokes-minimum-match-score 2000
  "*Take a look at `strokes-minimum-match-score'."
  :type 'integer
  :group 'xwem-strokes)

(defcustom xwem-strokes-file "xwem-strokes.el"
  "*File contained strokes for xwem stroke mode."
  :type 'file
  :group 'xwem-strokes)

(defcustom xwem-strokes-click-command 'xwem-strokes-default-click-command
  "*Command to execute when stroke is actually a `click'."
  :type 'function
  :group 'xwem-strokes)

(defcustom xwem-strokes-cursor-type '(X-XC-dot)
  "*Type of cursor to use when XWEM enters strokes mode."
  :type (xwem-cursor-shape-choice)
  :set (xwem-cus-set-cursor-shape xwem-strokes-cursor)
  :initialize 'custom-initialize-default
  :group 'xwem-strokes)

(defcustom xwem-strokes-cursor-foreground-color "#00ea00"
  "*Cursor's foreground color when XWEM in strokes mode."
  :type 'color
  :set (xwem-cus-set-cursor-foreground xwem-strokes-cursor)
  :initialize 'custom-initialize-default
  :group 'xwem-strokes)

(defcustom xwem-strokes-cursor-background-color "#002800"
  "*Cursor's background color when XWEM in strokes mode."
  :type 'color
  :set (xwem-cus-set-cursor-background xwem-strokes-cursor)
  :initialize 'custom-initialize-default
  :group 'xwem-strokes)

(defcustom xwem-strokes-gc-function 'X-GXCopy
  "Function applied to draw strokes."
  :type (xwem-gc-function-choice)
  :group 'xwem-strokes)

(define-xwem-face xwem-strokes-face
  `(((background light)
     (:foreground "red4" :background "black"))
    ((background dark)
     (:foreground "red" :background "black"))
    ((background begin light)
     (:foreground "magenta4" :background "black"
      :line-width 12 :cap-style X-CapRound))
    ((background begin dark)
     (:foreground "magenta" :background "black"
      :line-width 12 :cap-style X-CapRound))
    (t (:foreground "red4" :background "black"
        :line-width 8 :cap-style X-CapRound
        :subwindow-mode X-IncludeInferiors
        :function (eval xwem-strokes-gc-function))))
  "Face used to draw strokes."
  :group 'xwem-strokes
  :group 'xwem-faces)

;;; Internal variables

;; Stroke variables
(defvar xwem-strokes-keymap 
  (let ((map (make-sparse-keymap)))
    (set-keymap-default-binding map 'xwem-strokes-nocmd)

    (define-key map [button2] 'xwem-strokes-idescribe)
    (define-key map [button1] 'xwem-strokes-ibutton1)
    (define-key map [button1up] 'xwem-strokes-ibutton1up)
    (define-key map [(meta button1up)] 'xwem-strokes-ibutton1up)
    (define-key map [(control button1up)] 'xwem-strokes-ibutton1up)
    (define-key map [(meta control button1up)] 'xwem-strokes-ibutton1up)
    (define-key map [button3] 'xwem-strokes-ibutton3)
    map)
  "Keymap being used while in strokes event loop.")

(defvar xwem-strokes-map nil "Stroke map for XWEM.")

(defvar xwem-strokes-curr nil
  "Current events list, it passed to `stroke-' routines.")
(defvar xwem-strokes-defining nil
  "Non-nil mean that we defining stroke now.")

(defvar xwem-strokes-background-mode nil
  "Saved background mode.")

(defvar xwem-strokes-cursor nil
  "Cursor used while reading stroke.")

;; Functions
(define-xwem-command xwem-strokes-default-click-command ()
  "Default command to execute when strokes detected click.
Click is detected when no mouse moving occured while doing stroke."
  (xwem-interactive)
  (xwem-message 'info "Such an ugly `xwem-strokes-click-command', which you normally should customize."))

(defun xwem-strokes-save-strokes ()
  "Save user defined strokes to file named by `xwem-strokes-file'.
Modification to `strokes-prompt-user-save-strokes' to work with xwem's stuff."
  (let ((strokes-global-map xwem-strokes-map)
        (strokes-file (expand-file-name xwem-strokes-file xwem-dir)))

    (flet ((yes-or-no-p-maybe-dialog-box (prompt)
            #'(lambda () (xwem-under-minibuffer (yes-or-no-p prompt)))))
      (funcall 'strokes-prompt-user-save-strokes))
    
    ;; Fix stroke-file ..
    (when (file-exists-p strokes-file)
      (let ((b (find-file-noselect strokes-file)))
        (with-current-buffer b
          (when (search-forward "strokes-global-map")
            (replace-match "xwem-strokes-map"))
          (save-buffer))
        (kill-buffer b)))
    ))

(defun xwem-strokes-load-strokes ()
  "Load user defined strokes from file named by `xwem-strokes-file'."
  (if (file-exists-p (expand-file-name xwem-strokes-file xwem-dir))
;      (xwem-under-minibuffer
;       (and (y-or-n-p
;            (format "XWEM: No strokes loaded.  Load `%s'? "
;                    (expand-file-name xwem-strokes-file xwem-dir)))
      (let ((strokes-file (expand-file-name xwem-strokes-file xwem-dir)))
        (strokes-load-user-strokes))))

(defun xwem-strokes-cmd-valid-p (cmd)
  "Return non-nil if CMD is valid to be run after stroke."
  ;; NOTE: string/keyboard macro/interactive function/interactive
  ;; lambda are valid commands.
  (commandp cmd))

(defun xwem-strokes-cmd-type (cmd)
  "Return type of strokes command CMD.
Type is one of \"string\", \"kbd macro\", \"symbol\" or \"function\"."
  (cond ((stringp cmd) "string")
        ((vectorp cmd) "kbd macro")
        ((symbolp cmd) "symbol")
        ((functionp cmd) "function")
        (t "unknown")))

(defun xwem-strokes-cmd-description (cmd)
  "Return description of strokes command CMD."
  (let ((ctype (xwem-strokes-cmd-type cmd)))
    (cond ((string= ctype "string") (concat "\"" cmd "\""))
          ((string= ctype "kbd macro") (key-description cmd))
          ((string= ctype "symbol") (format "%S" cmd))
          ((string= ctype "function") (format "%S" cmd)))))

(defun xwem-strokes-read-command (&optional prompt)
  "Read command, prompting PROMPT.  Command may be interactive command or string."
  ;; TODO: - write me
  ;;   * Emacs command
  ;;   * Emacs string
  ;;   * XWEM binded keyboard macro
  (condition-case nil
      (let* ((type (xwem-completing-read
                    "XWEM Stroke type: " '(("key") ("command") ("string"))
                    nil t "command"))
             (cmd (cond ((string= type "command")
                         (xwem-read-command "XWEM Stroke command: "))
                        ((string= type "string")
                         (xwem-read-from-minibuffer "XWEM Stroke string: "))
                        ((string= type "key")
                         (let ((xwem-interactively t))
                           (prog1
                               (xwem-kbd-get-binding
                                (xwem-read-key-sequence "XWEM Stroke key: "))
                             (xwem-kbd-stop-grabbing))))
                        (t nil))))
        cmd)
    (t nil)))

(defun xwem-strokes-execute-command (cmd)
  "Execute CMD.  CMD is one of interactive command or keysequence."
  (if (xwem-strokes-cmd-valid-p cmd)
    (cond ((stringp cmd)
           (xwem-deffered-funcall 'xwem-kbd-force-mods-release)
           (xwem-deffered-funcall
            'xwem-kbd-add-pending-keys cmd (xwem-cl-selected)))

          ((vectorp cmd)
           (xwem-kbd-force-mods-release)
           (setq xwem-this-command-keys []) ; XXX
           (xwem-keymacro-execute-keys cmd))

          (t (command-execute cmd)))

    (xwem-message 'error "Invalid strokes command `%S'" cmd)))

(defun xwem-strokes-execute-stroke (stroke)
  "Given STROKE, execute the command corresponds to it."
  (let* ((match (strokes-match-stroke stroke xwem-strokes-map))
         (command (car match))
         (score (cdr match)))
    (cond ((strokes-click-p stroke)
           (command-execute xwem-strokes-click-command))

          ((and match (<= score xwem-strokes-minimum-match-score))
           (xwem-message 'info "Executing stroke: '%s'"
                         (xwem-strokes-cmd-description command))
           (xwem-strokes-execute-command command))

          ((null xwem-strokes-map)
           ;; First try loading strokes file
           (xwem-strokes-load-strokes)

           (if (null xwem-strokes-map)
               (xwem-message 'error "No strokes defined; use `xwem-strokes-global-set-stroke'")

             ;; Re-execute stroke in hope it will be founded in loaded
             ;; xwem-strokes-map.
             (xwem-strokes-execute-stroke stroke)))

          (t (xwem-message 'error "No stroke matches; see variable `xwem-strokes-minimum-match-score'")))
    ))

(defun xwem-strokes-define-or-execute (st)
  "Bind stroke ST to command or execute."
  (if (not xwem-strokes-defining)
      ;; Execute stroke
      (xwem-strokes-execute-stroke st)

    ;; Attach command to stroke
    (setq xwem-strokes-defining nil)
    (let ((cmdorstr (xwem-strokes-read-command)))
      (when (xwem-strokes-cmd-valid-p cmdorstr)
        (strokes-define-stroke xwem-strokes-map st cmdorstr)
        (xwem-message 'info "New stroke defined.")))))

(defun xwem-strokes-start-new (x y)
  "Start new stroke or new stick at X Y point."
  (push (cons x y) xwem-strokes-curr)
  (setq xwem-strokes-background-mode
        (xwem-misc-xwin-background-mode (xwem-rootwin) x y))
  (XDrawArc (xwem-dpy) (xwem-rootwin)
            (xwem-face-get-gc 'xwem-strokes-face
              (list 'background 'begin xwem-strokes-background-mode))
            x y 1 1 0 (* 360 64)))

(defun xwem-strokes-continue (x y)
  "Continue stroke at X Y."
  (let* ((xsc xwem-strokes-curr)
         (old-x (if (car xsc) (X-Point-x (car xsc)) x))
         (old-y (if (car xsc) (X-Point-y (car xsc)) y)))
               
    (push (cons x y) xwem-strokes-curr)
    (XDrawLine (xwem-dpy) (xwem-rootwin)
               (xwem-face-get-gc 'xwem-strokes-face
                 (list 'background xwem-strokes-background-mode))
               old-x old-y x y)))

;;;###autoload(autoload 'xwem-strokes-define "xwem-strokes" "" t)
(define-xwem-command xwem-strokes-define (arg)
  "Define new stroke.
If used with prefix ARG, then define new complex stroke.
See also documentation for the `strokes-define-stroke' function."
  (xwem-interactive "P")

  (if arg
      (xwem-strokes-cmplx-begin '(4))
    (xwem-strokes-begin '(4))))

(defun xwem-strokes-motion (xev)
  "Handles motion notify events."
  (if (strokes-lift-p (car xwem-strokes-curr))
      ;; Before new stick in complex stroke, should not happen because
      ;; we select for ButtonMotion, i.e. report motion events only
      ;; when some button pressed.
      nil
    (xwem-strokes-continue
     (X-Event-xmotion-root-x xev) (X-Event-xmotion-root-y xev))))

;;; Interactive commands

;;;###autoload(autoload 'xwem-strokes-ibutton1 "xwem-strokes" "" t)
(define-xwem-command xwem-strokes-ibutton1 ()
  "On button1 command."
  (xwem-interactive)

  (declare (special xwem-stroke-complexp))
  (declare (special xwem-stroke-done))

  (xwem-strokes-start-new (X-Event-xbutton-root-x xwem-last-xevent)
                          (X-Event-xbutton-root-y xwem-last-xevent)))

;;;###autoload(autoload 'xwem-strokes-idescribe "xwem-strokes" "" t)
(define-xwem-command xwem-strokes-idescribe ()
  "Describe current stroke."
  (xwem-interactive)

  (declare (special xwem-stroke-complexp))
  (declare (special xwem-stroke-done))

  (xwem-strokes-describe-current))

;;;###autoload(autoload 'xwem-strokes-ibutton1up "xwem-strokes" "" t)
(define-xwem-command xwem-strokes-ibutton1up ()
  "On button1 up command."
  (xwem-interactive)

  (declare (special xwem-stroke-complexp))
  (declare (special xwem-stroke-done))

  (if (not xwem-stroke-complexp)
      (progn (setq xwem-strokes-curr (nreverse xwem-strokes-curr))
             (setq xwem-stroke-done t))

    (push strokes-lift xwem-strokes-curr)))

;;;###autoload(autoload 'xwem-strokes-ibutton3 "xwem-strokes" "" t)
(define-xwem-command xwem-strokes-ibutton3 ()
  "On button3 up command."
  (xwem-interactive)

  (declare (special xwem-stroke-complexp))
  (declare (special xwem-stroke-done))

  (setq xwem-strokes-curr (nreverse (cdr xwem-strokes-curr)))
  (when (strokes-lift-p (car xwem-strokes-curr))
    (setq xwem-strokes-curr (cdr xwem-strokes-curr)))
  (setq xwem-stroke-done t))

;;;###autoload(autoload 'xwem-strokes-nocmd "xwem-strokes" "" t)
(define-xwem-command xwem-strokes-nocmd ()
  "`nil' command."
  (xwem-interactive))

(defun xwem-strokes-go (complexp)
  "Install stuff needed to handle stroke input.
If COMPLEXP is non-nil than setup all for complex stroke input."
  ;; TODO:
  ;;   - Check whether there already button release event, so we wount
  ;;     start stroke in that case

  ;; Grab pointer
  (xwem-mouse-grab xwem-strokes-cursor (xwem-rootwin)
                   (Xmask-or XM-ButtonPress XM-ButtonRelease XM-ButtonMotion))

  (setq xwem-strokes-curr nil)
  (xwem-strokes-start-new (X-Event-xbutton-root-x xwem-last-xevent)
                          (X-Event-xbutton-root-y xwem-last-xevent))
  ;; Event loop
  (xwem-unwind-protect
      (let ((gc-cons-threshold most-positive-fixnum) ; inhibit GC'ing
            (xwem-override-local-map xwem-strokes-keymap) ; override local keymap
            (xwem-keyboard-echo-keystrokes nil) ; Do not show
            (xwem-stroke-complexp complexp)
            (xwem-stroke-done nil)
            xev)
        (declare (special xwem-stroke-done))
        (declare (special xwem-stroke-complexp))

        (while (not xwem-stroke-done)
          (X-Event-CASE (setq xev (xwem-next-event))
            (:X-MotionNotify (xwem-strokes-motion xev))
            ((:X-KeyPress :X-ButtonPress :X-ButtonRelease)
             (xwem-dispatch-command-xevent xev)))))
    (xwem-strokes-done))

  ;; Execute or define stroke
  (let* ((grid-locs (strokes-renormalize-to-grid
                     xwem-strokes-curr xwem-strokes-grid))
         (st (strokes-fill-stroke
              (strokes-eliminate-consecutive-redundancies grid-locs))))
    (xwem-strokes-define-or-execute st)))

(defun xwem-strokes-done (&optional xev)
  "Uninstalls stuff installed by `xwem-strokes-go'.
XEV is last processed X-Event."
  (XUngrabPointer (xwem-dpy))

  (let ((xsc (or xwem-strokes-curr
                 (list (or (and xev (cons (X-Event-xbutton-root-x xev)
                                          (X-Event-xbutton-root-y xev)))
                           (cons 0 0)))))
        (x 10000000) (y 1000000) (xma 0) (yma 0)
        (thi (* 2 (max (xwem-face-line-width 'xwem-strokes-face
                                             '(background begin light))
                       (xwem-face-line-width 'xwem-strokes-face
                                             '(background begin dark))
                       (xwem-face-line-width 'xwem-strokes-face)))))

    (while xsc
      (while (not (consp (car xsc)))
        ;; cut off lifts
        (setq xsc (cdr xsc)))

      (when (< (caar xsc) x)
        (setq x (caar xsc)))
      (when (> (caar xsc) xma)
        (setq xma (caar xsc)))

      (when (< (cdar xsc) y)
        (setq y (cdar xsc)))
      (when (> (cdar xsc) yma)
        (setq yma (cdar xsc)))

      (setq xsc (cdr xsc)))

    (xwem-root-refresh
     (- x thi) (- y thi) (+ (- xma x) (* 2 thi)) (+ (- yma y) (* thi 2)))))

(defun xwem-strokes-describe-current ()
  "Describe current complex stroke."
  (let ((pix-lock (copy-list xwem-strokes-curr))        ; because of nreverse
        (match nil))

    (setq pix-lock (nreverse (cdr pix-lock)))
    (when (strokes-lift-p (car pix-lock))
      (setq pix-lock (cdr pix-lock)))

    (setq match (strokes-match-stroke
                 (strokes-fill-stroke
                  (strokes-eliminate-consecutive-redundancies
                   (strokes-renormalize-to-grid pix-lock xwem-strokes-grid)))
                 xwem-strokes-map))

    (xwem-message 'info "Current stroke executes: %S" (car match))))

;;;###autoload(autoload 'xwem-strokes-begin "xwem-strokes" "" t)
(define-xwem-command xwem-strokes-begin (arg)
  "Begin to input simple stroke.
If prefix ARG is given start to define simple stroke."
  (xwem-interactive "P")

  (when arg
    (setq xwem-strokes-defining t))

  (xwem-strokes-go nil))

;;;###autoload(autoload 'xwem-strokes-cmplx-begin "xwem-strokes" "" t)
(define-xwem-command xwem-strokes-cmplx-begin (arg)
  "Begin to input complex stroke(i.e. which has more than one strokes).
If prefix ARG is given start to define new complex stroke."
  (xwem-interactive "P")
  
  (when arg
    (setq xwem-strokes-defining t))

  (xwem-strokes-go t))

;;;###autoload(autoload 'xwem-strokes-unset-last-stroke "xwem-strokes" "" t)
(define-xwem-command xwem-strokes-unset-last-stroke (arg)
  "Removes last stroke from `xwem-strokes-map'.
With prefix ARG do not require a confirmation"
  (xwem-interactive
   (list (or xwem-prefix-arg
             (y-or-n-p (format "XWEM: Really delete last stroke (%s)"
                               (xwem-strokes-cmd-description
                                (cdr (car xwem-strokes-map))))))))

  (if arg
      (progn
        (setq xwem-strokes-map (cdr xwem-strokes-map))
        (xwem-message 'info "Last stroke has been deleted."))
    (xwem-message 'info "Nothing done.")))

(defun xwem-strokes-sort (smap &optional how)
  "Sort strokes map SMAP."
  (sort (copy-list smap)
        #'(lambda (s1 s2)
            (let ((c1 (cdr s1))
                  (c2 (cdr s2)))
              (cond ((and (stringp c1) (stringp c2))
                     (string-lessp c1 c2))
                    ((and (symbolp c1) (symbolp 2))
                     (string-lessp (symbol-name c1) (symbol-name c2)))
                    ((stringp c1) t)
                    ((and (vectorp c1) (not (stringp c2))) t)
                    ((and (symbolp c1) (not (stringp c2)) (not (vectorp c2))) t)
                    ((and (functionp c1) (not (stringp c2))
                          (not (vectorp c2)) (not (symbolp c2))) t))))
        ))
  
;;;###autoload(autoload 'xwem-strokes-list "xwem-strokes" "" t)
(define-xwem-command xwem-strokes-list (arg)
  "List strokes defined for XWEM use.
With prefix ARG sort strokes by command (NOT IMPLEMENTED YET)."
  (xwem-interactive "P")
  
  (unless xwem-strokes-map
    (xwem-strokes-load-strokes))

  (let ((stb (get-buffer-create "*XWEM Strokes*")))
    (xwem-special-popup-frame stb)
    (with-current-buffer  stb
      (setq buffer-read-only nil)
      (erase-buffer)
      (insert
       "Command type     Command                                     Stroke\n"
       "------------     -------                                     ------")
      (mapc #'(lambda (stdef)
                (let ((stroke (car stdef))
                      (stroke-cmd (cdr stdef)))
                  (when (xwem-strokes-cmd-valid-p stroke-cmd)
                    (strokes-xpm-for-stroke stroke " *strokes-xpm*")
                    (newline 1)
                    (insert-char ?\x20 62)
                    (beginning-of-line)
                    (insert (xwem-strokes-cmd-type stroke-cmd))
                    (beginning-of-line)
                    (forward-char 17)
                    (insert (xwem-strokes-cmd-description stroke-cmd))
                    (beginning-of-line)
                    (forward-char 62)
                    (make-annotation
                     (make-glyph
                      (list
                       (vector 'xpm
                               :data (buffer-substring
                                      (point-min " *strokes-xpm*")
                                      (point-max " *strokes-xpm*")
                                      " *strokes-xpm*"))
                       [string :data "[Image]"]))
                     (1- (point)) 'text)
                    (add-text-properties
                     (point-at-bol) (point-at-eol) (list 'face 'underline))
                    )))
            (if arg
                (xwem-strokes-sort xwem-strokes-map)
              xwem-strokes-map))

      (kill-region (min (1+ (point)) (point-max)) (point-max))
      (goto-char (point-min))

      ;; Start viewing mode
      (view-mode)

      (define-key view-minor-mode-map (kbd "q")
        #'(lambda ()
            (interactive)
            (kill-buffer (current-buffer))
            (define-key view-minor-mode-map (kbd "q") 'view-quit)))
      )))

(defun xwem-strokes-init ()
  "Initialize strokes support."
  (xwem-message 'init "Initializing strokes ...")

  (setq xwem-strokes-curr nil)
  (setq  xwem-strokes-cursor
         (xwem-make-cursor xwem-strokes-cursor-type
                           xwem-strokes-cursor-foreground-color
                           xwem-strokes-cursor-background-color))

  (xwem-message 'init "Initializing strokes ... done"))


(if xwem-started
    (xwem-strokes-init)
  (add-hook 'xwem-after-init-hook 'xwem-strokes-init))


(provide 'xwem-strokes)

;;; xwem-strokes.el ends here
