tree-widget.el 31.1 KB
Newer Older
David Ponce's avatar
David Ponce committed
1 2
;;; tree-widget.el --- Tree widget

Paul Eggert's avatar
Paul Eggert committed
3
;; Copyright (C) 2004-2019 Free Software Foundation, Inc.
David Ponce's avatar
David Ponce committed
4 5 6 7 8 9 10

;; Author: David Ponce <david@dponce.com>
;; Created: 16 Feb 2001
;; Keywords: extensions

;; This file is part of GNU Emacs

11 12 13 14
;; GNU Emacs 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 3 of the License, or
;; (at your option) any later version.
David Ponce's avatar
David Ponce committed
15

16 17 18 19
;; GNU Emacs 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.
David Ponce's avatar
David Ponce committed
20 21

;; You should have received a copy of the GNU General Public License
22
;; along with GNU Emacs.  If not, see <https://www.gnu.org/licenses/>.
David Ponce's avatar
David Ponce committed
23 24 25 26 27 28 29 30

;;; Commentary:
;;
;; This library provide a tree widget useful to display data
;; structures organized in a hierarchical order.
;;
;; The following properties are specific to the tree widget:
;;
31 32 33
;; :open
;;    Set to non-nil to expand the tree.  By default the tree is
;;    collapsed.
David Ponce's avatar
David Ponce committed
34
;;
35 36 37 38 39
;; :node
;;    Specify the widget used to represent the value of a tree node.
;;    By default this is an `item' widget which displays the
;;    tree-widget :tag property value if defined, or a string
;;    representation of the tree-widget value.
David Ponce's avatar
David Ponce committed
40
;;
41 42 43 44
;; :keep
;;    Specify a list of properties to keep when the tree is collapsed
;;    so they can be recovered when the tree is expanded.  This
;;    property can be used in child widgets too.
David Ponce's avatar
David Ponce committed
45
;;
46 47 48 49
;; :expander (obsoletes :dynargs)
;;    Specify a function to be called to dynamically provide the
;;    tree's children in response to an expand request.  This function
;;    will be passed the tree widget and must return a list of child
David Ponce's avatar
David Ponce committed
50 51
;;    widgets.  Child widgets returned by the :expander function are
;;    stored in the :args property of the tree widget.
David Ponce's avatar
David Ponce committed
52
;;
David Ponce's avatar
David Ponce committed
53 54 55 56 57 58 59
;; :expander-p
;;    Specify a predicate which must return non-nil to indicate that
;;    the :expander function above has to be called.  By default, to
;;    speed up successive expand requests, the :expander-p predicate
;;    return non-nil when the :args value is nil.  So, by default, to
;;    refresh child values, it is necessary to set the :args property
;;    to nil, then redraw the tree.
David Ponce's avatar
David Ponce committed
60
;;
David Ponce's avatar
David Ponce committed
61 62 63 64 65 66 67 68 69 70 71 72 73
;; :open-icon  (default `tree-widget-open-icon')
;; :close-icon (default `tree-widget-close-icon')
;; :empty-icon (default `tree-widget-empty-icon')
;; :leaf-icon  (default `tree-widget-leaf-icon')
;;    Those properties define the icon widgets associated to tree
;;    nodes.  Icon widgets must derive from the `tree-widget-icon'
;;    widget.  The :tag and :glyph-name property values are
;;    respectively used when drawing the text and graphic
;;    representation of the tree.  The :tag value must be a string
;;    that represent a node icon, like "[+]" for example.  The
;;    :glyph-name value must the name of an image found in the current
;;    theme, like "close" for example (see also the variable
;;    `tree-widget-theme').
David Ponce's avatar
David Ponce committed
74
;;
David Ponce's avatar
David Ponce committed
75 76 77 78 79 80 81 82 83 84 85
;; :guide      (default `tree-widget-guide')
;; :end-guide  (default `tree-widget-end-guide')
;; :no-guide   (default `tree-widget-no-guide')
;; :handle     (default `tree-widget-handle')
;; :no-handle  (default `tree-widget-no-handle')
;;    Those properties define `item'-like widgets used to draw the
;;    tree guide lines.  The :tag property value is used when drawing
;;    the text representation of the tree.  The graphic look and feel
;;    is given by the images named "guide", "no-guide", "end-guide",
;;    "handle", and "no-handle" found in the current theme (see also
;;    the variable `tree-widget-theme').
David Ponce's avatar
David Ponce committed
86
;;
David Ponce's avatar
David Ponce committed
87
;; These are the default :tag values for icons, and guide lines:
David Ponce's avatar
David Ponce committed
88
;;
David Ponce's avatar
David Ponce committed
89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
;; open-icon    "[-]"
;; close-icon   "[+]"
;; empty-icon   "[X]"
;; leaf-icon    ""
;; guide        " |"
;; no-guide     "  "
;; end-guide    " `"
;; handle       "-"
;; no-handle    " "
;;
;; The text representation of a tree looks like this:
;;
;; [-] 1        (open-icon :node)
;;  |-[+] 1.0   (guide+handle+close-icon :node)
;;  |-[X] 1.1   (guide+handle+empty-icon :node)
;;  `-[-] 1.2   (end-guide+handle+open-icon :node)
;;     |- 1.2.1 (no-guide+no-handle+guide+handle+leaf-icon leaf)
;;     `- 1.2.2 (no-guide+no-handle+end-guide+handle+leaf-icon leaf)
David Ponce's avatar
David Ponce committed
107
;;
108 109 110 111
;; By default, images will be used instead of strings to draw a
;; nice-looking tree.  See the `tree-widget-image-enable',
;; `tree-widget-themes-directory', and `tree-widget-theme' options for
;; more details.
David Ponce's avatar
David Ponce committed
112 113 114 115 116 117 118 119 120 121

;;; History:
;;

;;; Code:
(require 'wid-edit)

;;; Customization
;;
(defgroup tree-widget nil
122
  "Customization support for the Tree Widget library."
123
  :version "22.1"
David Ponce's avatar
David Ponce committed
124 125
  :group 'widgets)

126
(defcustom tree-widget-image-enable t
127
  "Non-nil means that tree-widget will try to use images."
David Ponce's avatar
David Ponce committed
128
  :type  'boolean
129 130
  :group 'tree-widget
  :version "27.1")
David Ponce's avatar
David Ponce committed
131

132 133 134 135 136 137 138
(defvar tree-widget-themes-load-path
  '(load-path
    (let ((dir (if (fboundp 'locate-data-directory)
                   (locate-data-directory "tree-widget") ;; XEmacs
                 data-directory)))
      (and dir (list dir (expand-file-name "images" dir))))
    )
David Ponce's avatar
David Ponce committed
139 140 141
  "List of locations in which to search for the themes sub-directory.
Each element is an expression that will be recursively evaluated until
it returns a single directory or a list of directories.
142 143 144 145 146 147 148
The default is to search in the `load-path' first, then in the
\"images\" sub directory in the data directory, then in the data
directory.
The data directory is the value of the variable `data-directory' on
Emacs, and what `(locate-data-directory \"tree-widget\")' returns on
XEmacs.")

David Ponce's avatar
David Ponce committed
149
(defcustom tree-widget-themes-directory "tree-widget"
Lute Kamstra's avatar
Lute Kamstra committed
150
  "Name of the directory in which to look for an image theme.
David Ponce's avatar
David Ponce committed
151
When nil use the directory where the tree-widget library is located.
David Ponce's avatar
David Ponce committed
152 153
When it is a relative name, search in all occurrences of that sub
directory in the path specified by `tree-widget-themes-load-path'.
154
The default is to use the \"tree-widget\" relative name."
David Ponce's avatar
David Ponce committed
155
  :type '(choice (const :tag "Default" "tree-widget")
David Ponce's avatar
David Ponce committed
156
                 (const :tag "Where is this library" nil)
David Ponce's avatar
David Ponce committed
157 158 159 160
                 (directory :format "%{%t%}:\n%v"))
  :group 'tree-widget)

(defcustom tree-widget-theme nil
Lute Kamstra's avatar
Lute Kamstra committed
161
  "Name of the theme in which to look for images.
David Ponce's avatar
David Ponce committed
162 163 164 165
This is a sub directory of the themes directory specified by the
`tree-widget-themes-directory' option.
The default theme is \"default\".  When an image is not found in a
theme, it is searched in its parent theme.
David Ponce's avatar
David Ponce committed
166 167 168

A complete theme must at least contain images with these file names
with a supported extension (see also `tree-widget-image-formats'):
169 170 171 172 173 174 175 176

\"guide\"
  A vertical guide line.
\"no-guide\"
  An invisible vertical guide line.
\"end-guide\"
  End of a vertical guide line.
\"handle\"
David Ponce's avatar
David Ponce committed
177
  Horizontal guide line that joins the vertical guide line to an icon.
178
\"no-handle\"
David Ponce's avatar
David Ponce committed
179 180 181 182 183 184 185 186 187 188 189 190 191
  An invisible handle.

Plus images whose name is given by the :glyph-name property of the
icon widgets used to draw the tree.  By default these images are used:

\"open\"
  Icon associated to an expanded tree.
\"close\"
  Icon associated to a collapsed tree.
\"empty\"
  Icon associated to an expanded tree with no child.
\"leaf\"
  Icon associated to a leaf node."
David Ponce's avatar
David Ponce committed
192 193 194 195 196 197
  :type '(choice (const  :tag "Default" nil)
                 (string :tag "Name"))
  :group 'tree-widget)

(defcustom tree-widget-image-properties-emacs
  '(:ascent center :mask (heuristic t))
Lute Kamstra's avatar
Lute Kamstra committed
198
  "Default properties of Emacs images."
David Ponce's avatar
David Ponce committed
199 200 201 202 203
  :type 'plist
  :group 'tree-widget)

(defcustom tree-widget-image-properties-xemacs
  nil
Lute Kamstra's avatar
Lute Kamstra committed
204
  "Default properties of XEmacs images."
David Ponce's avatar
David Ponce committed
205 206
  :type 'plist
  :group 'tree-widget)
David Ponce's avatar
David Ponce committed
207 208 209

(defcustom tree-widget-space-width 0.5
  "Amount of space between an icon image and a node widget.
210 211
Must be a valid space :width display property.
See Info node `(elisp)Specified Space'."
David Ponce's avatar
David Ponce committed
212
  :group 'tree-widget
213 214
  :type '(choice (number :tag "Multiple of normal character width")
                 sexp))
David Ponce's avatar
David Ponce committed
215 216 217

;;; Image support
;;
218
(eval-and-compile ;; Emacs/XEmacs compatibility stuff
David Ponce's avatar
David Ponce committed
219 220 221 222 223 224 225 226 227
  (cond
   ;; XEmacs
   ((featurep 'xemacs)
    (defsubst tree-widget-use-image-p ()
      "Return non-nil if image support is currently enabled."
      (and tree-widget-image-enable
           widget-glyph-enable
           (console-on-window-system-p)))
    (defsubst tree-widget-create-image (type file &optional props)
228 229
      "Create an image of type TYPE from FILE, and return it.
Give the image the specified properties PROPS."
David Ponce's avatar
David Ponce committed
230 231
      (apply 'make-glyph `([,type :file ,file ,@props])))
    (defsubst tree-widget-image-formats ()
232
      "Return the alist of image formats/file name extensions.
David Ponce's avatar
David Ponce committed
233 234 235 236 237 238 239
See also the option `widget-image-file-name-suffixes'."
      (delq nil
            (mapcar
             #'(lambda (fmt)
                 (and (valid-image-instantiator-format-p (car fmt)) fmt))
             widget-image-file-name-suffixes)))
    )
240
   ;; Emacs
David Ponce's avatar
David Ponce committed
241 242 243 244 245 246 247
   (t
    (defsubst tree-widget-use-image-p ()
      "Return non-nil if image support is currently enabled."
      (and tree-widget-image-enable
           widget-image-enable
           (display-images-p)))
    (defsubst tree-widget-create-image (type file &optional props)
248 249
      "Create an image of type TYPE from FILE, and return it.
Give the image the specified properties PROPS."
David Ponce's avatar
David Ponce committed
250 251
      (apply 'create-image `(,file ,type nil ,@props)))
    (defsubst tree-widget-image-formats ()
252
      "Return the alist of image formats/file name extensions.
253
See also the option `widget-image-conversion'."
David Ponce's avatar
David Ponce committed
254 255 256 257 258 259 260 261 262 263 264 265 266
      (delq nil
            (mapcar
             #'(lambda (fmt)
                 (and (image-type-available-p (car fmt)) fmt))
             widget-image-conversion)))
    ))
  )

;; Buffer local cache of theme data.
(defvar tree-widget--theme nil)

(defsubst tree-widget-theme-name ()
  "Return the current theme name, or nil if no theme is active."
David Ponce's avatar
David Ponce committed
267 268 269 270 271 272 273 274
  (and tree-widget--theme (car (aref tree-widget--theme 0))))

(defsubst tree-widget-set-parent-theme (name)
  "Set to NAME the parent theme of the current theme.
The default parent theme is the \"default\" theme."
  (unless (member name (aref tree-widget--theme 0))
    (aset tree-widget--theme 0
          (append (aref tree-widget--theme 0) (list name)))
275 276 277 278 279 280 281 282 283
    ;; Load the theme setup from the first directory where the theme
    ;; is found.
    (catch 'found
      (dolist (dir (tree-widget-themes-path))
        (setq dir (expand-file-name name dir))
        (when (file-accessible-directory-p dir)
          (throw 'found
                 (load (expand-file-name
                        "tree-widget-theme-setup" dir) t)))))))
David Ponce's avatar
David Ponce committed
284 285

(defun tree-widget-set-theme (&optional name)
David Ponce's avatar
David Ponce committed
286
  "In the current buffer, set the theme to use for images.
287 288
The current buffer must be where the tree widget is drawn.
Optional argument NAME is the name of the theme to use.  It defaults
David Ponce's avatar
David Ponce committed
289
to the value of the variable `tree-widget-theme'.
David Ponce's avatar
David Ponce committed
290 291 292 293 294 295 296 297
Does nothing if NAME is already the current theme.

If there is a \"tree-widget-theme-setup\" library in the theme
directory, load it to setup a parent theme or the images properties.
Typically it should contain something like this:

  (tree-widget-set-parent-theme \"my-parent-theme\")
  (tree-widget-set-image-properties
298 299 300
   (if (featurep \\='xemacs)
       \\='(:ascent center)
     \\='(:ascent center :mask (heuristic t))
David Ponce's avatar
David Ponce committed
301
     ))"
David Ponce's avatar
David Ponce committed
302
  (or name (setq name (or tree-widget-theme "default")))
303
  (unless (string-equal name (tree-widget-theme-name))
David Ponce's avatar
David Ponce committed
304 305
    (set (make-local-variable 'tree-widget--theme)
         (make-vector 4 nil))
David Ponce's avatar
David Ponce committed
306 307
      (tree-widget-set-parent-theme name)
      (tree-widget-set-parent-theme "default")))
David Ponce's avatar
David Ponce committed
308

309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334
(defun tree-widget--locate-sub-directory (name path &optional found)
  "Locate all occurrences of the sub-directory NAME in PATH.
Return a list of absolute directory names in reverse order, or nil if
not found."
  (condition-case err
      (dolist (elt path)
        (setq elt (eval elt))
        (cond
         ((stringp elt)
          (and (file-accessible-directory-p
                (setq elt (expand-file-name name elt)))
               (push elt found)))
         (elt
          (setq found (tree-widget--locate-sub-directory
                       name (if (atom elt) (list elt) elt) found)))))
    (error
     (message "In tree-widget--locate-sub-directory: %s"
              (error-message-string err))))
  found)

(defun tree-widget-themes-path ()
  "Return the path where to search for a theme.
It is specified in variable `tree-widget-themes-directory'.
Return a list of absolute directory names, or nil when no directory
has been found accessible."
  (let ((path (aref tree-widget--theme 1)))
335
    (cond
336 337 338 339
     ;; No directory was found.
     ((eq path 'void) nil)
     ;; The list of directories is available in the cache.
     (path)
340 341
     ;; Use the directory where this library is located.
     ((null tree-widget-themes-directory)
342 343 344 345 346 347 348
      (when (setq path (locate-library "tree-widget"))
        (setq path (file-name-directory path))
        (setq path (and (file-accessible-directory-p path)
                        (list path)))
        ;; Store the result in the cache for later use.
        (aset tree-widget--theme 1 (or path 'void))
        path))
349 350
     ;; Check accessibility of absolute directory name.
     ((file-name-absolute-p tree-widget-themes-directory)
351 352 353 354 355 356
      (setq path (expand-file-name tree-widget-themes-directory))
      (setq path (and (file-accessible-directory-p path)
                      (list path)))
      ;; Store the result in the cache for later use.
      (aset tree-widget--theme 1 (or path 'void))
      path)
357 358
     ;; Locate a sub-directory in `tree-widget-themes-load-path'.
     (t
359 360 361 362 363 364
      (setq path (nreverse (tree-widget--locate-sub-directory
                            tree-widget-themes-directory
                            tree-widget-themes-load-path)))
      ;; Store the result in the cache for later use.
      (aset tree-widget--theme 1 (or path 'void))
      path))))
David Ponce's avatar
David Ponce committed
365

366
(defconst tree-widget--cursors
367 368 369
  ;; Pointer shapes when the mouse pointer is over inactive
  ;; tree-widget images.  This feature works since Emacs 22, and
  ;; ignored on older versions, and XEmacs.
370 371 372 373 374 375 376 377
  '(
    ("guide"     . arrow)
    ("no-guide"  . arrow)
    ("end-guide" . arrow)
    ("handle"    . arrow)
    ("no-handle" . arrow)
    ))

David Ponce's avatar
David Ponce committed
378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397
(defsubst tree-widget-set-image-properties (props)
  "In current theme, set images properties to PROPS.
Does nothing if images properties have already been set for that
theme."
  (or (aref tree-widget--theme 2)
      (aset tree-widget--theme 2 props)))

(defsubst tree-widget-image-properties (name)
  "Return the properties of image NAME in current theme.
Default global properties are provided for respectively Emacs and
XEmacs in the variables `tree-widget-image-properties-emacs', and
`tree-widget-image-properties-xemacs'."
  ;; Add the pointer shape
  (cons :pointer
        (cons (or (cdr (assoc name tree-widget--cursors)) 'hand)
              (tree-widget-set-image-properties
               (if (featurep 'xemacs)
                   tree-widget-image-properties-xemacs
                 tree-widget-image-properties-emacs)))))

398 399
(defun tree-widget-lookup-image (name)
  "Look up in current theme for an image with NAME.
David Ponce's avatar
David Ponce committed
400 401
Search first in current theme, then in parent themes (see also the
function `tree-widget-set-parent-theme').
402 403
Return the first image found having a supported format, or nil if not
found."
404 405 406 407 408 409 410 411 412 413 414 415 416 417
  (let (file)
    (catch 'found
      (dolist (default-directory (tree-widget-themes-path))
        (dolist (dir (aref tree-widget--theme 0))
          (dolist (fmt (tree-widget-image-formats))
            (dolist (ext (cdr fmt))
              (setq file (expand-file-name (concat name ext) dir))
              (and (file-readable-p file)
                   (file-regular-p file)
                   (throw 'found
                          (tree-widget-create-image
                           (car fmt) file
                           (tree-widget-image-properties name))))))))
      nil)))
David Ponce's avatar
David Ponce committed
418 419 420 421

(defun tree-widget-find-image (name)
  "Find the image with NAME in current theme.
NAME is an image file name sans extension.
422
Return the image found, or nil if not found."
David Ponce's avatar
David Ponce committed
423 424 425
  (when (tree-widget-use-image-p)
    ;; Ensure there is an active theme.
    (tree-widget-set-theme (tree-widget-theme-name))
426 427 428 429 430 431 432 433 434 435
    (let ((image (assoc name (aref tree-widget--theme 3))))
      ;; The image NAME is found in the cache.
      (if image
          (cdr image)
        ;; Search the image in current, and default themes.
        (prog1
            (setq image (tree-widget-lookup-image name))
          ;; Store image reference in the cache for later use.
          (push (cons name image) (aref tree-widget--theme 3))))
      )))
David Ponce's avatar
David Ponce committed
436 437 438

;;; Widgets
;;
439 440 441 442 443 444 445 446 447
(defun tree-widget-button-click (event)
  "Move to the position clicked on, and if it is a button, invoke it.
EVENT is the mouse event received."
  (interactive "e")
  (mouse-set-point event)
  (let ((pos (widget-event-point event)))
    (if (get-char-property pos 'button)
        (widget-button-click event))))

David Ponce's avatar
David Ponce committed
448
(defvar tree-widget-button-keymap
449 450 451 452 453
  (let ((km (make-sparse-keymap)))
    (if (boundp 'widget-button-keymap)
        ;; XEmacs
        (progn
          (set-keymap-parent km widget-button-keymap)
454
          (define-key km [button1] 'tree-widget-button-click))
455 456
      ;; Emacs
      (set-keymap-parent km widget-keymap)
457
      (define-key km [down-mouse-1] 'tree-widget-button-click))
458 459 460
    km)
  "Keymap used inside node buttons.
Handle mouse button 1 click on buttons.")
David Ponce's avatar
David Ponce committed
461

David Ponce's avatar
David Ponce committed
462 463
(define-widget 'tree-widget-icon 'push-button
  "Basic widget other tree-widget icons are derived from."
David Ponce's avatar
David Ponce committed
464 465 466
  :format        "%[%t%]"
  :button-keymap tree-widget-button-keymap ; XEmacs
  :keymap        tree-widget-button-keymap ; Emacs
David Ponce's avatar
David Ponce committed
467 468 469
  :create        'tree-widget-icon-create
  :action        'tree-widget-icon-action
  :help-echo     'tree-widget-icon-help-echo
David Ponce's avatar
David Ponce committed
470 471
  )

David Ponce's avatar
David Ponce committed
472 473 474 475
(define-widget 'tree-widget-open-icon 'tree-widget-icon
  "Icon for an expanded tree-widget node."
  :tag        "[-]"
  :glyph-name "open"
David Ponce's avatar
David Ponce committed
476 477
  )

David Ponce's avatar
David Ponce committed
478 479 480 481
(define-widget 'tree-widget-empty-icon 'tree-widget-icon
  "Icon for an expanded tree-widget node with no child."
  :tag        "[X]"
  :glyph-name "empty"
David Ponce's avatar
David Ponce committed
482 483
  )

David Ponce's avatar
David Ponce committed
484 485 486 487
(define-widget 'tree-widget-close-icon 'tree-widget-icon
  "Icon for a collapsed tree-widget node."
  :tag        "[+]"
  :glyph-name "close"
David Ponce's avatar
David Ponce committed
488 489
  )

David Ponce's avatar
David Ponce committed
490 491 492 493 494
(define-widget 'tree-widget-leaf-icon 'tree-widget-icon
  "Icon for a tree-widget leaf node."
  :tag        ""
  :glyph-name "leaf"
  :button-face 'default
David Ponce's avatar
David Ponce committed
495 496 497
  )

(define-widget 'tree-widget-guide 'item
498
  "Vertical guide line."
David Ponce's avatar
David Ponce committed
499 500 501 502 503 504
  :tag       " |"
  ;;:tag-glyph (tree-widget-find-image "guide")
  :format    "%t"
  )

(define-widget 'tree-widget-end-guide 'item
505
  "End of a vertical guide line."
506
  :tag       " \\=`"
David Ponce's avatar
David Ponce committed
507 508 509 510 511
  ;;:tag-glyph (tree-widget-find-image "end-guide")
  :format    "%t"
  )

(define-widget 'tree-widget-no-guide 'item
512
  "Invisible vertical guide line."
David Ponce's avatar
David Ponce committed
513 514 515 516 517 518
  :tag       "  "
  ;;:tag-glyph (tree-widget-find-image "no-guide")
  :format    "%t"
  )

(define-widget 'tree-widget-handle 'item
519
  "Horizontal guide line that joins a vertical guide line to a node."
David Ponce's avatar
David Ponce committed
520
  :tag       "-"
David Ponce's avatar
David Ponce committed
521 522 523 524 525
  ;;:tag-glyph (tree-widget-find-image "handle")
  :format    "%t"
  )

(define-widget 'tree-widget-no-handle 'item
526
  "Invisible handle."
David Ponce's avatar
David Ponce committed
527 528 529 530 531 532 533 534
  :tag       " "
  ;;:tag-glyph (tree-widget-find-image "no-handle")
  :format    "%t"
  )

(define-widget 'tree-widget 'default
  "Tree widget."
  :format         "%v"
David Ponce's avatar
David Ponce committed
535
  :convert-widget 'tree-widget-convert-widget
David Ponce's avatar
David Ponce committed
536
  :value-get      'widget-value-value-get
537
  :value-delete   'widget-children-value-delete
David Ponce's avatar
David Ponce committed
538
  :value-create   'tree-widget-value-create
David Ponce's avatar
David Ponce committed
539 540
  :action         'tree-widget-action
  :help-echo      'tree-widget-help-echo
David Ponce's avatar
David Ponce committed
541
  :expander-p     'tree-widget-expander-p
David Ponce's avatar
David Ponce committed
542 543 544 545
  :open-icon      'tree-widget-open-icon
  :close-icon     'tree-widget-close-icon
  :empty-icon     'tree-widget-empty-icon
  :leaf-icon      'tree-widget-leaf-icon
546 547 548 549 550
  :guide          'tree-widget-guide
  :end-guide      'tree-widget-end-guide
  :no-guide       'tree-widget-no-guide
  :handle         'tree-widget-handle
  :no-handle      'tree-widget-no-handle
David Ponce's avatar
David Ponce committed
551 552 553 554 555
  )

;;; Widget support functions
;;
(defun tree-widget-p (widget)
556
  "Return non-nil if WIDGET is a tree-widget."
David Ponce's avatar
David Ponce committed
557 558 559 560 561
  (let ((type (widget-type widget)))
    (while (and type (not (eq type 'tree-widget)))
      (setq type (widget-type (get type 'widget-type))))
    (eq type 'tree-widget)))

562 563 564 565 566
(defun tree-widget-node (widget)
  "Return WIDGET's :node child widget.
If not found, setup an `item' widget as default.
Signal an error if the :node widget is a tree-widget.
WIDGET is, or derives from, a tree-widget."
David Ponce's avatar
David Ponce committed
567
  (let ((node (widget-get widget :node)))
568 569 570 571 572
    (if node
        ;; Check that the :node widget is not a tree-widget.
        (and (tree-widget-p node)
             (error "Invalid tree-widget :node %S" node))
      ;; Setup an item widget as default :node.
David Ponce's avatar
David Ponce committed
573 574 575 576 577 578 579
      (setq node `(item :tag ,(or (widget-get widget :tag)
                                  (widget-princ-to-string
                                   (widget-value widget)))))
      (widget-put widget :node node))
    node))

(defun tree-widget-keep (arg widget)
580
  "Save in ARG the WIDGET's properties specified by :keep."
David Ponce's avatar
David Ponce committed
581 582 583 584 585
  (dolist (prop (widget-get widget :keep))
    (widget-put arg prop (widget-get widget prop))))

(defun tree-widget-children-value-save (widget &optional args node)
  "Save WIDGET children values.
586 587 588 589 590 591 592 593
WIDGET is, or derives from, a tree-widget.
Children properties and values are saved in ARGS if non-nil, else in
WIDGET's :args property value.  Properties and values of the
WIDGET's :node sub-widget are saved in NODE if non-nil, else in
WIDGET's :node sub-widget."
  (let ((args (cons (or node (widget-get widget :node))
                    (or args (widget-get widget :args))))
        (children (widget-get widget :children))
David Ponce's avatar
David Ponce committed
594 595 596 597 598 599 600 601 602 603 604
        arg child)
    (while (and args children)
      (setq arg      (car args)
            args     (cdr args)
            child    (car children)
            children (cdr children))
       (if (tree-widget-p child)
;;;; The child is a tree node.
           (progn
             ;; Backtrack :args and :node properties.
             (widget-put arg :args (widget-get child :args))
605
             (widget-put arg :node (widget-get child :node))
David Ponce's avatar
David Ponce committed
606 607 608 609 610 611 612 613 614 615 616 617
             ;; Save :open property.
             (widget-put arg :open (widget-get child :open))
             ;; The node is open.
             (when (widget-get child :open)
               ;; Save the widget value.
               (widget-put arg :value (widget-value child))
               ;; Save properties specified in :keep.
               (tree-widget-keep arg child)
               ;; Save children.
               (tree-widget-children-value-save
                child (widget-get arg :args) (widget-get arg :node))))
;;;; Another non tree node.
618
         ;; Save the widget value.
David Ponce's avatar
David Ponce committed
619 620
         (widget-put arg :value (widget-value child))
         ;; Save properties specified in :keep.
621
         (tree-widget-keep arg child)))))
David Ponce's avatar
David Ponce committed
622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650

;;; Widget creation
;;
(defvar tree-widget-before-create-icon-functions nil
  "Hooks run before to create a tree-widget icon.
Each function is passed the icon widget not yet created.
The value of the icon widget :node property is a tree :node widget or
a leaf node widget, not yet created.
This hook can be used to dynamically change properties of the icon and
associated node widgets.  For example, to dynamically change the look
and feel of the tree-widget by changing the values of the :tag
and :glyph-name properties of the icon widget.
This hook should be local in the buffer setup to display widgets.")

(defun tree-widget-icon-create (icon)
  "Create the ICON widget."
  (run-hook-with-args 'tree-widget-before-create-icon-functions icon)
  (widget-put icon :tag-glyph
              (tree-widget-find-image (widget-get icon :glyph-name)))
  ;; Ensure there is at least one char to display the image.
  (and (widget-get icon :tag-glyph)
       (equal "" (or (widget-get icon :tag) ""))
       (widget-put icon :tag " "))
  (widget-default-create icon)
  ;; Insert space between the icon and the node widget.
  (insert-char ?  1)
  (put-text-property
   (1- (point)) (point)
   'display (list 'space :width tree-widget-space-width)))
David Ponce's avatar
David Ponce committed
651

David Ponce's avatar
David Ponce committed
652 653 654 655 656 657 658 659
(defun tree-widget-convert-widget (widget)
  "Convert :args as widget types in WIDGET."
  (let ((tree (widget-types-convert-widget widget)))
    ;; Compatibility
    (widget-put tree :expander (or (widget-get tree :expander)
                                   (widget-get tree :dynargs)))
    tree))

660 661
(defvar widget-glyph-enable) ; XEmacs

David Ponce's avatar
David Ponce committed
662
(defun tree-widget-value-create (tree)
663 664 665
  "Create the TREE tree-widget."
  (let* ((node   (tree-widget-node tree))
         (flags  (widget-get tree :tree-widget--guide-flags))
666
         (indent (widget-get tree :indent))
667
         ;; Setup widget's image support.  Looking up for images, and
668
         ;; setting widgets' :tag-glyph is done here, to allow us to
669 670 671
         ;; dynamically change the image theme.
         (widget-image-enable (tree-widget-use-image-p))     ; Emacs
         (widget-glyph-enable widget-image-enable)           ; XEmacs
David Ponce's avatar
David Ponce committed
672
         children buttons)
673
    (and indent (not (widget-get tree :parent))
674
         (insert-char ?\  indent))
David Ponce's avatar
David Ponce committed
675
    (if (widget-get tree :open)
676
;;;; Expanded node.
677
        (let ((args     (widget-get tree :args))
678 679 680 681 682
              (guide    (widget-get tree :guide))
              (noguide  (widget-get tree :no-guide))
              (endguide (widget-get tree :end-guide))
              (handle   (widget-get tree :handle))
              (nohandle (widget-get tree :no-handle))
683 684 685 686
              (guidi    (tree-widget-find-image "guide"))
              (noguidi  (tree-widget-find-image "no-guide"))
              (endguidi (tree-widget-find-image "end-guide"))
              (handli   (tree-widget-find-image "handle"))
David Ponce's avatar
David Ponce committed
687
              (nohandli (tree-widget-find-image "no-handle")))
David Ponce's avatar
David Ponce committed
688 689 690 691 692
          ;; Request children at run time, when requested.
          (when (and (widget-get tree :expander)
                     (widget-apply tree :expander-p))
            (setq args (mapcar 'widget-convert
                               (widget-apply tree :expander)))
693
            (widget-put tree :args args))
694 695
          ;; Defer the node widget creation after icon creation.
          (widget-put tree :node (widget-convert node))
David Ponce's avatar
David Ponce committed
696
          ;; Create the icon widget for the expanded tree.
David Ponce's avatar
David Ponce committed
697
          (push (widget-create-child-and-convert
698 699 700
                 tree (widget-get tree (if args :open-icon :empty-icon))
                 ;; Pass the node widget to child.
                 :node (widget-get tree :node))
David Ponce's avatar
David Ponce committed
701
                buttons)
David Ponce's avatar
David Ponce committed
702
          ;; Create the tree node widget.
703 704
          (push (widget-create-child tree (widget-get tree :node))
                children)
David Ponce's avatar
David Ponce committed
705 706 707
          ;; Update the icon :node with the created node widget.
          (widget-put (car buttons) :node (car children))
          ;; Create the tree children.
David Ponce's avatar
David Ponce committed
708
          (while args
David Ponce's avatar
David Ponce committed
709 710
            (setq node (car args)
                  args (cdr args))
711
            (and indent (insert-char ?\  indent))
712
            ;; Insert guide lines elements from previous levels.
713
            (dolist (f (reverse flags))
David Ponce's avatar
David Ponce committed
714 715 716 717
              (widget-create-child-and-convert
               tree (if f guide noguide)
               :tag-glyph (if f guidi noguidi))
              (widget-create-child-and-convert
718 719
               tree nohandle :tag-glyph nohandli))
            ;; Insert guide line element for this level.
David Ponce's avatar
David Ponce committed
720 721 722 723 724 725
            (widget-create-child-and-convert
             tree (if args guide endguide)
             :tag-glyph (if args guidi endguidi))
            ;; Insert the node handle line
            (widget-create-child-and-convert
             tree handle :tag-glyph handli)
David Ponce's avatar
David Ponce committed
726 727 728 729 730 731 732
            (if (tree-widget-p node)
                ;; Create a sub-tree node.
                (push (widget-create-child-and-convert
                       tree node :tree-widget--guide-flags
                       (cons (if args t) flags))
                      children)
              ;; Create the icon widget for a leaf node.
David Ponce's avatar
David Ponce committed
733
              (push (widget-create-child-and-convert
David Ponce's avatar
David Ponce committed
734 735 736 737 738 739 740 741 742 743 744
                     tree (widget-get tree :leaf-icon)
                     ;; At this point the node widget isn't yet created.
                     :node (setq node (widget-convert
                                       node :tree-widget--guide-flags
                                       (cons (if args t) flags)))
                     :tree-widget--leaf-flag t)
                    buttons)
              ;; Create the leaf node widget.
              (push (widget-create-child tree node) children)
              ;; Update the icon :node with the created node widget.
              (widget-put (car buttons) :node (car children)))))
745
;;;; Collapsed node.
746 747
      ;; Defer the node widget creation after icon creation.
      (widget-put tree :node (widget-convert node))
David Ponce's avatar
David Ponce committed
748
      ;; Create the icon widget for the collapsed tree.
David Ponce's avatar
David Ponce committed
749
      (push (widget-create-child-and-convert
750 751 752
             tree (widget-get tree :close-icon)
             ;; Pass the node widget to child.
             :node (widget-get tree :node))
David Ponce's avatar
David Ponce committed
753
            buttons)
David Ponce's avatar
David Ponce committed
754
      ;; Create the tree node widget.
755 756
      (push (widget-create-child tree (widget-get tree :node))
            children)
David Ponce's avatar
David Ponce committed
757 758 759 760
      ;; Update the icon :node with the created node widget.
      (widget-put (car buttons) :node (car children)))
    ;; Save widget children and buttons.  The tree-widget :node child
    ;; is the first element in :children.
David Ponce's avatar
David Ponce committed
761
    (widget-put tree :children (nreverse children))
David Ponce's avatar
David Ponce committed
762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796
    (widget-put tree :buttons  buttons)))

;;; Widget callbacks
;;
(defsubst tree-widget-leaf-node-icon-p (icon)
  "Return non-nil if ICON is a leaf node icon.
That is, if its :node property value is a leaf node widget."
  (widget-get icon :tree-widget--leaf-flag))

(defun tree-widget-icon-action (icon &optional event)
  "Handle the ICON widget :action.
If ICON :node is a leaf node it handles the :action.  The tree-widget
parent of ICON handles the :action otherwise.
Pass the received EVENT to :action."
  (let ((node (widget-get icon (if (tree-widget-leaf-node-icon-p icon)
                                   :node :parent))))
    (widget-apply node :action event)))

(defun tree-widget-icon-help-echo (icon)
  "Return the help-echo string of ICON.
If ICON :node is a leaf node it handles the :help-echo.  The tree-widget
parent of ICON handles the :help-echo otherwise."
  (let* ((node (widget-get icon (if (tree-widget-leaf-node-icon-p icon)
                                    :node :parent)))
         (help-echo (widget-get node :help-echo)))
    (if (functionp help-echo)
        (funcall help-echo node)
      help-echo)))

(defvar tree-widget-after-toggle-functions nil
  "Hooks run after toggling a tree-widget expansion.
Each function is passed a tree-widget.  If the value of the :open
property is non-nil the tree has been expanded, else collapsed.
This hook should be local in the buffer setup to display widgets.")

797
(defun tree-widget-action (tree &optional _event)
David Ponce's avatar
David Ponce committed
798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814
  "Handle the :action of the TREE tree-widget.
That is, toggle expansion of the TREE tree-widget.
Ignore the EVENT argument."
  (let ((open (not (widget-get tree :open))))
    (or open
        ;; Before to collapse the node, save children values so next
        ;; open can recover them.
        (tree-widget-children-value-save tree))
    (widget-put tree :open open)
    (widget-value-set tree open)
    (run-hook-with-args 'tree-widget-after-toggle-functions tree)))

(defun tree-widget-help-echo (tree)
  "Return the help-echo string of the TREE tree-widget."
  (if (widget-get tree :open)
      "Collapse node"
    "Expand node"))
David Ponce's avatar
David Ponce committed
815

David Ponce's avatar
David Ponce committed
816 817 818 819 820
(defun tree-widget-expander-p (tree)
  "Return non-nil if the TREE tree-widget :expander has to be called.
That is, if TREE :args is nil."
  (null (widget-get tree :args)))

David Ponce's avatar
David Ponce committed
821 822 823
(provide 'tree-widget)

;;; tree-widget.el ends here