;;; xetla-browse.el --- Arch archives/library browser

;; Copyright (C) 2004 by Stefan Reichoer (GPL)
;; Copyright (C) 2004 Steve Youngs (BSD)

;; Author:        Steve Youngs <steve@eicq.org>
;; Maintainer:    Steve Youngs <steve@eicq.org>
;; Created:       2004-11-25
;; Keywords:      archive arch tla

;; Based on xtla-browse.el by: Masatake YAMATO <jet@gyve.org>

;; This file is part of XEtla.

;; Redistribution and use in source and binary forms, with or without
;; modification, are permitted provided that the following conditions
;; are met:
;;
;; 1. Redistributions of source code must retain the above copyright
;;    notice, this list of conditions and the following disclaimer.
;;
;; 2. Redistributions in binary form must reproduce the above copyright
;;    notice, this list of conditions and the following disclaimer in the
;;    documentation and/or other materials provided with the distribution.
;;
;; 3. Neither the name of the author nor the names of any contributors
;;    may be used to endorse or promote products derived from this
;;    software without specific prior written permission.
;;
;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR
;; IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
;; DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
;; FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
;; CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
;; SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
;; BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
;; WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
;; OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
;; IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

;;; Commentary:
;;
;; Contributions from:
;;    Stefan Reichoer, <stefan@xsteve.at>
;;    Matthieu Moy <Matthieu.Moy@imag.fr>
;;    Masatake YAMATO <jet@gyve.org>
;;    Milan Zamazal <pdm@zamazal.org>
;;    Martin Pool <mbp@sourcefrog.net>
;;    Robert Widhopf-Fenk <hack@robf.de>
;;    Mark Triggs <mst@dishevelled.net>

;; 1. Load xetla-browse.el
;; 2. M-x xetla-browse RET

;;; TODO:
;; - Generic refresh
;;

;;; History:
;;

;;; Code:
(eval-when-compile
  (require 'cl)
  (autoload 'easy-mmode-define-keymap "easy-mmode")
  (autoload 'ad-add-advice "advice"))

(require 'jde-tree-widget)
(require 'xetla)

(defvar xetla-browse-buffer-name "*xetla-browse*")
(defvar xetla-browse-buffer-type 'browse)
(xetla-add-buffer-type xetla-browse-buffer-type
                        xetla-browse-buffer-name)

;; --------------------------------------
;; Open node tracking
;; --------------------------------------
(defvar xetla-browse-open-list '()
  "List holding the name of open nodes.")

(defun xetla-browse-open-list-member (archive
                                     &optional category branch version)
  "Return a node, ARCHIVE/CATEGORY-BRANCH-VERSION is opend or not.
CATEGORY, BRANCH, VERSION are optional."
  (let ((name (list archive category branch version nil)))
    (member name xetla-browse-open-list)))

(defun xetla-browse-open-list-add (archive
                                  &optional category branch version)
  "Add a node specified by the arguments to 'xetla-browse-open-list'.
ARCHIVE/CATEGORY-BRANCH-VERSION,  ARCHIVE/CATEGORY-BRANCH,
ARCHIVE/CATEGORY, ARCHIVE are added.  CATEGORY, BRANCH, VERSION
are optional."
  (xetla-browse-open-list-add-internal (list archive category branch version nil))
  (xetla-browse-open-list-add-internal (list archive category branch nil nil))
  (xetla-browse-open-list-add-internal (list archive category nil nil nil))
  (xetla-browse-open-list-add-internal (list archive nil nil nil nil))
  (xetla-browse-open-list-add-internal (list nil nil nil nil nil)))

(defun xetla-browse-open-list-add-internal (name)
  "Add NAME to `xetla-browse-open-list'."
  (unless (xetla-browse-open-list-member (xetla-name-archive name)
                                        (xetla-name-category name)
                                        (xetla-name-branch name)
                                        (xetla-name-version name))
    (push name xetla-browse-open-list)))

(defun xetla-browse-open-list-remove (archive
                                     &optional category branch version)
  "Remove ARCHIVE/CATEGORY-BRANCH-VERSION from `xetla-browse-open-list'.
CATEGORY, BRANCH and VERSION are optional."
  (let ((name (list archive category branch version nil)))
    (setq xetla-browse-open-list (delete name xetla-browse-open-list))))

(defun xetla-browse-open-tracker (tree)
  "Add or remove a node represented by TREE to/from `xetla-browse-open-list'.
If TREE is opened, it is added.  Else it is removed."
  (let* ((node (widget-get tree :node))
         (a (widget-get node :archive))
         (c (widget-get node :category))
         (b (widget-get node :branch))
         (v (widget-get node :version)))
  (if (widget-get tree :open)
      (xetla-browse-open-list-add a c b v)
    (xetla-browse-open-list-remove a c b v))))

(defun xetla-browse-find-archives-root-widget ()
  "Return the root widget of archives tree."
  (save-excursion
    (goto-char (point-min))
    (re-search-forward " Archives$")
    (backward-char 1)
    (xetla-widget-node-get-at)))

(defun xetla-browse-find-named-widget (parent name type)
  "Find a widget specified with arguments.
PARENT specifies the parent widget.
NAME is the name of the widget.
TYPE is the type of widget.  You can specify :archive, :category,
:branch, or :version."
  (let* ((args (widget-get parent :args))
         (index (position name args :test (lambda (e w)
                                               (let ((node (widget-get w :node)))
                                                 ;; Next line is hack for version node.
                                                 (unless node (setq node w))
                                                 (string= e (widget-get node type))))))
         (tree (when index (nth index (widget-get parent :children))))
         (node (when tree (save-excursion (goto-char (widget-get tree :from))
                                          (goto-char (next-single-property-change (point) 'widget))
                                          (xetla-widget-node-get-at)))))
    node))


(defun xetla-browse-find-widget (archive
                                &optional category branch version)
  "Return a list of widgets: (root archive category branch version)
root is always the root of the tree, of type `xetla-widget-root-node'.
archive is the widget representing ARCHIVE, of type
`xetla-widget-archive-node'.  The last items are potentially nil if
CATEGORY, BRANCH or VERSION is nil.  Otherwise, they are respectively
of type `xetla-widget-category-node', `xetla-widget-revision-node' and
`xetla-widget-version-node'."
  (let* ((root (xetla-browse-find-archives-root-widget))
         (a    (xetla-browse-find-named-widget
                (widget-get root :parent) archive :archive))
         (c    (and a category
                    (xetla-browse-find-named-widget
                     (widget-get a :parent) category :category)))
         (b    (and c branch
                    (xetla-browse-find-named-widget
                     (widget-get c :parent) branch :branch)))
         (v    (and b version
                    (xetla-browse-find-named-widget
                     (widget-get b :parent) version :version))))
    (list root a c b v)))

(defun xetla-browse-find-single-widget (archive
                                       &optional category branch
                                       version)
  "Similar to `xetla-browse-find-widget'.
Difference is it returns only the widget representing the last non-nil
widget of the list.  The means of ARCHIVE, CATEGORY, BRANCH and VERSION
are the same as that of `xetla-browse-find-widget'."
  (let ((widgets (xetla-browse-find-widget archive category branch
                                          version)))
    (or (nth 4 widgets)
        (nth 3 widgets)
        (nth 2 widgets)
        (nth 1 widgets)
        (error "Widget not found.  Please fill-in a bug report"))))

(defun xetla-browse-find-real-widget (widget)
  "Find real(complete) widget from incomplete WIDGET.
When trying to find widgets using (widget-get ... :args), we
sometimes find an incomplete widget, having no :from or :to
information for example.  This function takes as an argument an
incomplete widget, and finds the corresponding full widget.

WIDGET must be of type xetla-widget-*-node."
  (case (widget-type widget)
    (xetla-widget-archive-node
     (xetla-browse-find-single-widget
      (widget-get widget :archive)))
    (xetla-widget-category-node
     (xetla-browse-find-single-widget
      (widget-get widget :archive)
      (widget-get widget :category)))
    (xetla-widget-branch-node
     (xetla-browse-find-single-widget
      (widget-get widget :archive)
      (widget-get widget :category)
      (widget-get widget :branch)))
    (xetla-widget-version-node
     (xetla-browse-find-single-widget
      (widget-get widget :archive)
      (widget-get widget :category)
      (widget-get widget :version)))))

(defun* xetla-browse-open (flash archive
                                &optional category branch version)
  (let (widgets root a c b v)

    (unless archive
      (return-from xetla-browse-open nil))
    (setq widgets (xetla-browse-find-widget archive category branch nil))
    (setq root (nth 0 widgets))
    (unless root
      (error "Cannot find root archives node"))
    (xetla-widget-node-toggle-subtree-internal root 'open)

    (setq widgets (xetla-browse-find-widget archive category branch nil))
    (setq a (nth 1 widgets))
    (unless category
      (if a
          (progn (when flash
                   (goto-char (widget-get a :from))
                   (xetla-flash-line))
            (return-from xetla-browse-open nil))
        (error "Cannot find archive node for: %s" archive)))
    (xetla-widget-node-toggle-subtree-internal a 'open)

    (setq widgets (xetla-browse-find-widget archive category branch nil))
    (setq c (nth 2 widgets))
    (unless branch
      (if c
          (progn (when flash
                   (goto-char (widget-get c :from))
                   (xetla-flash-line))
            (return-from xetla-browse-open nil))
        (error "Cannot find category node for: %s/%s" archive category)))
    (xetla-widget-node-toggle-subtree-internal c 'open)

    (setq widgets (xetla-browse-find-widget archive category branch nil))
    (setq b (nth 3 widgets))
    (unless version
      (if b
          (progn (when flash
                   (goto-char (widget-get b :from))
                   (xetla-flash-line))
            (return-from xetla-browse-open nil))
        (error "Cannot find branch node for: %s/%s-%s" archive category branch)))
    (xetla-widget-node-toggle-subtree-internal b 'open)

    (setq widgets (xetla-browse-find-widget archive category branch version))
    (setq v (nth 4 widgets))
    (if v
        (progn (when flash
                 (goto-char (widget-get v :from))
                 (xetla-flash-line))
          (return-from xetla-browse-open nil))
      (error "Cannot find branch node for: %s/%s-%s-%s" archive category branch version)))
  )

;; --------------------------------------
;; Abstract Super Widget
;; --------------------------------------
(define-widget 'xetla-widget-node 'item
  "Abstract super widget for xetla-widget-*-node."
  :xetla-type nil
  :format "%[ %t%]%{%v%}\n"
  :face nil
  :keymap nil
  :menu nil
  :marks " "
  :keep '(:marks :open)
  :open-subtree (if (fboundp 'tree-widget-open-node)
		    'tree-widget-open-node
		  'xetla-tree-widget-node-toggle-subtree-for-tree-widget-v1)
  :close-subtree (if (fboundp 'tree-widget-open-node)
		     'tree-widget-close-node
		   'xetla-tree-widget-node-toggle-subtree-for-tree-widget-v1))

(defvar xetla-widget-node-map
  (let ((map (copy-keymap xetla-context-map-template)))
    (define-key map [return]
      'xetla-widget-node-toggle-subtree)
    (define-key map [button2]
      'xetla-widget-node-toggle-subtree-by-mouse)
    (define-key map "\C-m"
      'xetla-widget-node-toggle-subtree)
    (define-key map (xetla-prefix-buffer ?p)
      'xetla-show-process-buffer)
    (define-key map (xetla-prefix-buffer ?L)
      'xetla-open-internal-log-buffer)
    (define-key map (xetla-prefix-buffer xetla-key-show-bookmark)
      'xetla-bookmarks)
    (define-key map xetla-keyvec-kill-ring
      'xetla-widget-node-save-name-to-kill-ring)
    (define-key map xetla-keyvec-add-bookmark
      'xetla-widget-node-add-bookmark)
    map)
  "Keymap commonly used in xetla-widget-*-node.")

(defun xetla-widget-node-value-create (widget keyword)
  "Create value for WIDGET.
KEYWORD is used to get the base string to create the value."
  (insert (let* ((marks (widget-get widget :marks))
                 (string (widget-get widget keyword))
                 (value (xetla-widget-node-install-ui-element
                         widget (if (string= string "") "<empty>"
                                  string))))
            (concat marks value))))

(defun xetla-widget-node-install-ui-element (widget value &optional face)
  "Create a string with keymap, menu and face properties.
The keymap and menu are retrieved from WIDGET.
The string is copied from VALUE.
FACE is useds as the face."
  (let ((prop-value (xetla-face-add value
                                   (if face face (widget-get widget :face))
                                   (widget-get widget :keymap)
                                   (widget-get widget :menu))))
    (put-text-property 0 (length value)
                       'widget widget
                       prop-value)
    prop-value))

(defun xetla-widget-node-get-at (&optional point)
  "Get widget at POINT."
  (get-text-property (if point point (point)) 'widget))

(defun xetla-widget-node-get-name (&optional point)
  "Get name list associated widget under the POINT."
  (let ((widget (xetla-widget-node-get-at point)))
    (list (widget-get widget :archive)
          (widget-get widget :category)
          (widget-get widget :branch)
          (widget-get widget :version)
          nil)))

(defun xetla-widget-node-get-type (&optional point)
  "Get type of widget under the POINT.

Can be either 'archive, 'category, 'branch, 'version or nil for the
root of the tree."
  (let ((widget (xetla-widget-node-get-at point)))
    (widget-get widget :xetla-type)))

(defun xetla-widget-get-ancestor (widget level)
  "Get the ancestor widget of WIDGET.
\"ancestor\" widget stands for the LEVEL upper widget
in the archives tree."
  (let ((i 0)
        (parent widget))
    (while (< i level)
      (setq parent (widget-get parent :parent)
            i (1+ i)))
    parent))

(defun xetla-widget-node-refresh (&optional level point
                                           archive
                                           category
                                           branch)
  "Refresh node and LEVEL subnode at the POINT.
Before refreshing node, names cache are also refreshed if
ARCHIVE, CATEGORY, and/or BRANCH are specified."
  (interactive)
  (unless level (setq level 1))
  (unless point (setq point (point)))
  (if branch
      (xetla-archive-tree-build-versions archive
                                        category
                                        branch
                                        nil t)
    (if category
        (xetla-archive-tree-build-branches archive
                                          category
                                          nil t)
      (if archive
          (xetla-archive-tree-build-categories archive
                                              nil
                                              t)
        (xetla-archive-tree-build-archives nil t))))
  (let* ((widget (xetla-widget-node-get-at point))
         (tree (xetla-widget-get-ancestor widget level)))
    (widget-put tree :args nil)
    (widget-value-set tree (widget-value tree))
    (widget-setup)))

(defun xetla-widget-node-synchronize-mirror-to-remote ()
  "Synchronizes the mirror for the archive at point to remote from local."
  (interactive)
  (let* ((name (xetla-widget-node-get-name))
         (archive (xetla-name-archive name))
         (type (xetla-archive-type archive))
         mirror source)
    (cond
     ((eq type 'normal)
      (setq mirror (xetla-archive-name-mirror archive t))
      (unless mirror
        (error "No mirror archive for `%s'" archive)))
     ((eq type 'mirror)
      (setq source (xetla-archive-name-source archive t))
      (if source
          (setq archive source)
        (error "No source archive for `%s'" archive)))
     (t (error "Cannot mirror to a source archive: `%s'" archive)))
    (xetla-archive-mirror archive
                        (xetla-name-category name)
                          (xetla-name-branch name)
                          (xetla-name-version name)
                          nil)))

(defun xetla-widget-node-synchronize-mirror-to-local ()
  "Synchronizes the mirror for the archive at point to local from remote."
  (interactive)
  ;; TODO
  )

(defun xetla-widget-node-save-name-to-kill-ring ()
  "Save the name under point to `kill-ring'."
  (interactive)
  (let ((name (xetla-name-construct (xetla-widget-node-get-name))))
    (when (equal "" name)
      (error "No widget under the point"))
    (kill-new name)
    (message "Name: %s" name)))

(defun xetla-widget-node-add-bookmark ()
  "Add a name associated with a widget at point to xetla's bookmarks."
  (interactive)
  (let* ((target (xetla-widget-node-get-name))
         (target-fq (xetla-name-construct target))
         (bookmark (read-from-minibuffer (format "Name of Bookmark for `%s': "
                                                 target-fq))))
    (xetla-bookmarks-add bookmark target)
    (when (y-or-n-p "View bookmarks? ")
      (xetla-bookmarks))
    (message "bookmark %s(=> %s) added." bookmark target-fq)))

(defun xetla-widget-node-toggle-subtree (&optional point force)
  "Toggle between closing and opening the node at POINT.
You can specify a symbol, `open' or `close' to FORCE to force
the node to open or to close."
  (interactive)
  (xetla-widget-node-toggle-subtree-internal
   (xetla-widget-node-get-at point) force))

(defun xetla-widget-node-toggle-subtree-recursive (&optional point
                                                            force)
  "Same as `xetla-widget-node-toggle-subtree'.
The difference is that when the node is expanded, expands it
recursively, which means all the children will also be expanded.  (this
may take looong).
Meaning of POINT and FORCE are the same as that of
`xetla-widget-node-toggle-subtree'."
  (interactive)
  (xetla-widget-node-toggle-subtree-internal
   (xetla-widget-node-get-at point) force t))

(defun xetla-widget-node-toggle-subtree-internal (widget force
                                                        &optional
                                                        recursive)
  "Toggle between closing and opening the WIDGET.
You can specify a symbol, `open' or `close' to FORCE to force
the node to open or to close.  If RECURSIVE is non-nil, the opening
or closing are applied recursively."
  (let* ((open-subtree (widget-get widget :open-subtree))
         (close-subtree (widget-get widget :close-subtree)))
    (cond
     ((or (eq force 'open)
          (and (not force)
               (not (widget-get (widget-get widget :parent) :open))))
      (when open-subtree (funcall open-subtree widget))
      (when recursive
        (xetla-widget-node-toggle-subtree-recursion widget 'open)))
     ((or (eq force 'close)
	  (and (not force)
               (widget-get (widget-get widget :parent) :open)))
      (when (and recursive
                 (widget-get (widget-get widget :parent) :open))
        (when open-subtree (funcall open-subtree widget))
        (xetla-widget-node-toggle-subtree-recursion widget 'close))
      (when close-subtree (funcall close-subtree widget))))))

(defun xetla-widget-node-toggle-subtree-recursion (widget force)
  "A helper function for 'xetla-widget-node-toggle-subtree-internal'.
Apply all sub node of WIDGET opening or closing which is specified
by FORCE."
  (let ((args (widget-get (widget-get widget :parent) :args)))
    (dolist (arg args)
      (let* ((t-widget (widget-get arg :node))
             ;; surprisingly, t-widget doesn't have all the
             ;; necessary fields. Look for the _real_ widget.
             (full-widget
              (xetla-browse-find-real-widget t-widget)))
        (unless (eq (widget-type t-widget)
                    (widget-type full-widget))
          (error "Incorrect widget.  Please contact the developers"))
        (when full-widget
          (xetla-widget-node-toggle-subtree-internal
           full-widget force t))))))

(defun xetla-tree-widget-node-toggle-subtree-for-tree-widget-v1 (widget)
  "Toggle tree node function used in `xetla-browse' with tree-widget ver.1.0.5.
The code is the almost same as in tree-widget-toggle-folding tree-widget version
1.0.5.

Original documents say:
  \"Toggle a `tree-widget' folding.
WIDGET is a `tree-widget-node-handle-widget' and its parent the
`tree-widget' itself.  IGNORE other arguments.\""
  (let* ((parent (widget-get widget :parent))
	 ;; Original code
	 ; (open   (widget-value widget))
	 ;; Here `parent' is used instead of `widget'.
	 (open   (widget-value parent)))
    (if open
	(tree-widget-children-value-save parent))
    (widget-put parent :open (not open))
    (widget-value-set parent (not open))
    (run-hook-with-args 'tree-widget-after-toggle-functions parent)))

(xetla-make-bymouse-function xetla-widget-node-toggle-subtree)

;; --------------------------------------
;; My-id
;; --------------------------------------
(define-widget 'xetla-widget-my-id 'push-button
  "Widget to control xetla's my-id."
  :format "%{My-id:%} %[%t%]"
  :sample-face 'bold
  :button-face 'widget-field-face
  :notify 'xetla-widget-my-id-set
  :help-echo "Click here to change my-id")

(defun xetla-widget-my-id-set (self changed event)
  "Set my-id to my-id-widget.
SELF is not used.  CHANGED is just passed to `widget-value-set'.
EVENT is also not used."
  (let ((new-id (xetla-my-id t)))
    (widget-value-set changed new-id)
    (widget-setup)))

;; --------------------------------------
;; Root node
;; --------------------------------------
(define-widget 'xetla-widget-root-node 'xetla-widget-node
  "Root node widget for trees in xetla-browse buffer."
  :value-create 'xetla-widget-root-node-value-create
  :format " %v\n"
  :face 'bold)

(defun xetla-widget-root-node-value-create (widget)
  "Create a value for root node represented by WIDGET."
  (insert (xetla-widget-node-install-ui-element
           widget
           (widget-get widget :tag))))

(defvar xetla-widget-archives-root-node-map
  (let ((map (copy-keymap xetla-widget-node-map)))
    (define-key map xetla-keyvec-refresh
      'xetla-widget-node-refresh)
    (define-key map (xetla-prefix-add ?a)
      'xetla-widget-archives-root-node-make-archive)
    (define-key map (xetla-prefix-add ?r)
      'xetla-widget-archives-root-node-register-archive)
    map)
  "Keymap used on the archives root node.")

(easy-menu-define xetla-widget-archives-root-node-menu nil
  "Menu used on the root archives item in `xetla-browse-mode' buffer."
  '("Archives Root"
    ["Update Archives List"
     xetla-widget-node-refresh t]
    ["Make New Archive..."
     xetla-widget-archives-root-node-make-archive t]
    ["Register Archive"
     xetla-widget-archives-root-node-register-archive t]))

(defun xetla-widget-archives-root-node-make-archive ()
  "Call `xetla-make-archive-internal' interactively  then update the tree of `xetla-browse'."
  (interactive)
  (call-interactively 'xetla-make-archive-internal)
  (xetla-widget-node-refresh 1))

(defun xetla-widget-archives-root-node-goto (name)
  "Move the point to beginning of line in where the NAME is.
This may be useful to search an archive named NAME."
  (goto-char (point-min))
  (search-forward name)
  (beginning-of-line))

(defun xetla-widget-archives-root-node-register-archive ()
  "Call `xetla-register-archive-internal' interactively ; then update the tree of `xetla-browse'."
  (interactive)
  (let* ((result (call-interactively 'xetla-register-archive-internal))
         (archive-registered (nth 0 result))
         (archive (nth 1 result))
         (xetla-response (nth 3 result)))
    (when archive-registered
      (xetla-widget-node-refresh 1)
      (message xetla-response)
      (xetla-widget-archives-root-node-goto
       (if (string-match ".+: \\(.+\\)" xetla-response)
           (match-string 1 xetla-response)
         archive))
      (xetla-flash-line))))


;; --------------------------------------
;; Archive
;; --------------------------------------
(defface xetla-location
  '((((class color) (background dark)) (:foreground "gray"))
    (((class color) (background light)) (:foreground "gray"))
    (t (:bold t)))
  "Face to highlight xetla's archive location."
  :group 'xetla-faces)

(make-face 'xetla-location-ftp
	   "Face to highlight xetla's archive ftp location.")
(set-face-parent 'xetla-location-ftp 'xetla-location)

(make-face 'xetla-location-sftp
	   "Face to highlight xetla's archive sftp location.")
(set-face-parent 'xetla-location-sftp 'xetla-location)
(set-face-foreground 'xetla-location-sftp "gray50")

(make-face 'xetla-location-http
		  "Face to highlight xetla's archive sftp location.")
(set-face-parent 'xetla-location-http 'xetla-location)
(set-face-foreground 'xetla-location-http "gray60")

(make-face 'xetla-location-local
	   "Face to highlight xetla's local archive.")
(set-face-parent 'xetla-location-local 'xetla-location)
(set-face-foreground 'xetla-location-local "gray30")

(defvar xetla-widget-archive-node-map
  (let ((map (copy-keymap xetla-widget-node-map)))
    (define-key map xetla-keyvec-refresh
      'xetla-widget-archive-node-refresh)
    (define-key map "*" 'xetla-widget-archive-node-select-default)
    (define-key map xetla-keyvec-remove
      'xetla-widget-archive-node-unregister-archive)
    (define-key map (xetla-prefix-add ?c)
      'xetla-widget-archive-node-make-category)
    (define-key map (xetla-prefix-apply-from-here xetla-key-reflect)
      'xetla-widget-archive-node-start-project)
    (define-key map xetla-keyvec-reflect
      'xetla-widget-node-synchronize-mirror-to-remote)
    (define-key map xetla-keyvec-get
      'xetla-widget-node-synchronize-mirror-to-local)
    (define-key map (xetla-prefix-add xetla-key-reflect)
      'xetla-widget-archive-node-make-mirror-at-remote)
    (define-key map (xetla-prefix-add xetla-key-get)
      'xetla-widget-archive-node-make-mirror-at-local)
    map)
  "Keymap used on xetla-widget-archive-node.")

(easy-menu-define xetla-widget-archive-node-menu nil
  "Menu used on a archive item in `xetla-browse-mode' buffer."
  '("Archive"
    ["Update Categories List"      xetla-widget-archive-node-refresh t]
    ["Set Default Archive"         xetla-widget-archive-node-select-default t]
    ["Remove Archive Registration" xetla-widget-archive-node-unregister-archive t]
    ["Make New Category..."        xetla-widget-archive-node-make-category t]
    ["Start Project from Here"     xetla-widget-archive-node-start-project t]
    ["Add a Bookmark"              xetla-widget-node-add-bookmark t]
    ("Remote Mirror"
     ["Synchronize Mirror to Remote From Local"
      xetla-widget-node-synchronize-mirror-to-remote
      (let* ((archive (xetla-name-archive (xetla-widget-node-get-name)))
             (type (xetla-archive-type archive)))
        (or (and (eq type 'normal)
                 (xetla-archive-name-mirror archive t))
            (and (eq type 'mirror)
                 (xetla-archive-name-source archive t))))]
     ["Create a Mirror at Remote"
      xetla-widget-archive-node-make-mirror-at-remote
      (eq (xetla-archive-type (xetla-name-archive (xetla-widget-node-get-name)))
          'normal)])
    ("Local Mirror"
     ["Synchronize Mirror to Local[TODO]"
      ;; TODO
      xetla-widget-node-synchronize-mirror-to-local nil]
     ["Create a Mirror at Local" xetla-widget-archive-node-make-mirror-at-local
      (eq (xetla-archive-type (xetla-name-archive (xetla-widget-node-get-name)))
          'source)]
     "-"
     ["Convert to SOURCE archive" xetla-widget-archive-node-convert-to-source
      (eq (xetla-archive-type (xetla-name-archive (xetla-widget-node-get-name)))
          'normal)])
    ["Save Name to Kill Ring" xetla-widget-node-save-name-to-kill-ring t]))

(defconst xetla-widget-archive-node-tag "a")
(defconst xetla-widget-archive-node-default-tag "A")

(define-widget 'xetla-widget-archive-node 'xetla-widget-node
  "Archive node in xetla-browse."
  :tag xetla-widget-archive-node-tag
  :value-create 'xetla-widget-archive-node-value-create
  :xetla-type 'archive
  :face 'xetla-archive-name
  :keymap 'xetla-widget-archive-node-map
  :menu xetla-widget-archive-node-menu
  :archive nil
  :archive-location nil
  :archive-defaultp nil)

(defvar xetla-widget-archive-node-list nil)
(defun xetla-browse-expand-archives (root)
  "Expand ROOT widget."
  (or (and (not current-prefix-arg) (widget-get root :args))
      (let ((default-archive (xetla-my-default-archive)))
        (setq xetla-widget-archive-node-list nil)
        (mapcar
         (lambda (archive)
           (let ((res
                  `(tree-widget
                    :open ,(xetla-browse-open-list-member (car archive))
                    :has-children t
                    :dynargs xetla-browse-expand-categories
                    :node (xetla-widget-archive-node
                           :tag ,(if (equal default-archive (car archive))
                                     xetla-widget-archive-node-default-tag
                                   xetla-widget-archive-node-tag)
                           :archive ,(car archive)
                           :archive-location ,(cadr archive)
                           :archive-defaultp ,(equal
                                               default-archive
                                               (car
                                                archive))))))
             (widget-put (widget-get res :node) :parent res)
             res))
         (let* ((l xetla-archive-tree))
           (when (or (null l) current-prefix-arg)
             (xetla-archive-tree-build-archives nil t))
           xetla-archive-tree)))))

(defun xetla-widget-archive-node-value-create (widget)
  "Create values for WIDGET."
  (push widget xetla-widget-archive-node-list)
  (insert (let* ((archive  (widget-get widget :archive))
                 (location (widget-get widget :archive-location))
                 (defaultp (widget-get widget :archive-defaultp))
                 (marks    (widget-get widget :marks))
                 (value (progn
                          (case (xetla-archive-type archive)
                            (mirror (widget-put widget :face 'xetla-mirror-archive-name))
                            (source (widget-put widget :face 'xetla-source-archive-name)))
                          ;;
                          ;; It seems that XEmacs's format hides text properties.
                          ;;
                          (concat marks
                                  (xetla-widget-node-install-ui-element
                                   widget archive (when defaultp
                                                    'xetla-marked))
                                  " => "
                                  (xetla-widget-archive-put-face-on-location
                                   location)))))
            value)))

(defun xetla-widget-archive-put-face-on-location (location)
  "Set face to LOCATION based on the location type(ftp, sftp, http or local)."
(let ((face (case (xetla-location-type location)
                (ftp 'xetla-location-ftp)
                (sftp 'xetla-location-sftp)
                (http 'xetla-location-http)
                (local 'xetla-location-local)))
        (location (copy-sequence location)))
    (put-text-property 0 (length location)
                       'face face location)
    location))

(defun xetla-widget-archive-node-refresh ()
  "Refresh an archive node under the point."
  (interactive)
  (xetla-widget-node-refresh 1 nil
                            (xetla-name-archive
                             (xetla-widget-node-get-name))))

(defun xetla-widget-archive-node-select-default ()
  "Mark a widget associated with the default archive.
Unmark widgets not associated with the default archive.
`:archive-defaultp' keyword is used to mark."
  (interactive)
  (mapc
   (lambda (widget)
     (when (equal xetla-widget-archive-node-default-tag
                  (widget-get widget :tag))
       (widget-put widget :tag xetla-widget-archive-node-tag)
       (widget-put widget :archive-defaultp nil)
       (widget-value-set widget (widget-value widget))))
   xetla-widget-archive-node-list)
  (let* ((widget (xetla-widget-node-get-at))
         (archive (xetla-name-archive (xetla-widget-node-get-name) )))
    (xetla-my-default-archive archive)
    (widget-put widget :tag xetla-widget-archive-node-default-tag)
    (widget-put widget :archive-defaultp t)
    (widget-value-set widget (widget-value widget))))

(defun xetla-widget-archive-node-unregister-archive ()
  "Delete the registration of the archive under the point."
  (interactive)
  (let ((archive (xetla-name-archive (xetla-widget-node-get-name))))
    (if archive
        (progn (xetla-unregister-archive archive t)
               (xetla-widget-node-refresh 2))
      (error "No archive under the point"))))

(defun xetla-widget-archive-node-make-category ()
  "Make new category in the archive under the point."
  (interactive)
  (let* ((name (xetla-widget-node-get-name))
         (archive (xetla-name-archive name))
         (l (xetla-name-read "New Category: "
                            archive
                            'prompt)))
    (xetla-make-category (xetla-name-archive l) (xetla-name-category l))
    (xetla-widget-node-refresh 1 nil (xetla-name-archive l))
    (xetla-browse-open t
                      (xetla-name-archive l)
                      (xetla-name-category l))
    ))

(defun xetla-widget-archive-node-convert-to-source ()
  "Convert the archive under the point to a source archive."
  (interactive)
  (let* ((widget (xetla-widget-node-get-at))
         (archive (widget-get widget :archive))
         (location (widget-get widget :archive-location))
         (result (xetla-archive-convert-to-source-archive archive location)))
    (let ((archive-registered (nth 0 result))
          (archive (nth 1 result))
          (xetla-response (nth 3 result)))
      (when archive-registered
        (xetla-widget-node-refresh 2)
        (message xetla-response)
        (xetla-widget-archives-root-node-goto
         (if (string-match ".+: \\(.+\\)" xetla-response)
             (match-string 1 xetla-response)
           archive))
        (xetla-flash-line)))))

(defun xetla-widget-archive-node-start-project ()
  "Start new project in the archive unde the point."
  (interactive)
  (let* ((archive (xetla-name-archive (xetla-widget-node-get-name)))
         (buffer (current-buffer))
         (p (point))
         (result (xetla-start-project archive 'synchronously))
         (category (xetla-name-category (car result)))
         (branch (xetla-name-branch (car result)))
         (version (xetla-name-version (car result)))
         )
    (with-current-buffer buffer
      (xetla-widget-node-refresh 1 p archive)
      (xetla-browse-open t
                        archive category branch version))))

(defun xetla-widget-archive-node-make-mirror-at-remote ()
  "Create a mirror for the local archive under the point at somewhere remote."
  (interactive)
  (let ((archive (xetla-name-archive (xetla-widget-node-get-name))))
    (unless archive
      (error "No archive under the point"))
    (xetla-mirror-archive archive nil nil nil nil)
    (xetla-widget-node-refresh 2)
    (xetla-widget-archives-root-node-goto (format "%s-MIRROR" archive))
    (xetla-flash-line)))

(defun xetla-widget-archive-node-make-mirror-at-local ()
  "Create a mirror for the remote archive under the point to local."
  (interactive)
  (let ((archive (xetla-name-archive (xetla-widget-node-get-name))))
    (unless archive
      (error "No archive under the point"))
    (xetla-mirror-from-archive archive nil)
    (xetla-widget-node-refresh 2)
    (string-match "\\(.*\\)-SOURCE$" archive)
    (xetla-widget-archives-root-node-goto
     ;; Adding a space not to match SOURCE archive.
     (concat (match-string 1 archive) " "))
    (xetla-flash-line)))

;; --------------------------------------
;; Categories
;; --------------------------------------
(defvar xetla-widget-category-node-map
  (let ((map (copy-keymap xetla-widget-node-map)))
    (define-key map xetla-keyvec-refresh
      'xetla-widget-category-node-refresh)
    (define-key map (xetla-prefix-add ?b)
      'xetla-widget-category-node-make-branch)
    map)
  "Keymap used on xetla-widget-category-node.")

(easy-menu-define xetla-widget-category-node-menu nil
  "Menu used on a archive item in `xetla-browse-mode' buffer."
  '("Category"
    ["Update Branches List" xetla-widget-category-node-refresh t]
    ["Remove Category[NOT IMPLEMENTED]" nil t]
    ["Make New Branch..." xetla-widget-category-node-make-branch t]
    ["Add a Bookmark" xetla-widget-node-add-bookmark t]
    ["Synchronize Mirror to Remote"
     xetla-widget-node-synchronize-mirror-to-remote t]
    ["Save Name to Kill Ring" xetla-widget-node-save-name-to-kill-ring t]))

(define-widget 'xetla-widget-category-node 'xetla-widget-node
  "Category node in xetla-browse."
  :tag "c"
  :value-create 'xetla-widget-category-node-value-create
  :xetla-type 'category
  :face 'xetla-category-name
  :keymap 'xetla-widget-category-node-map
  :menu xetla-widget-category-node-menu
  :archive nil
  :category nil)

(defun xetla-browse-expand-categories (archive)
  "Expand ARCHIVE widget."
  (or (and (not current-prefix-arg) (widget-get archive :args))
      (let ((archive-name (widget-get
                           (widget-get archive :node)
                           :archive)))
        (mapcar
         (lambda (category)
           (let ((res `(tree-widget
                        :open ,(xetla-browse-open-list-member archive-name
                                                             (car category))
                        :has-children t
                        :dynargs xetla-browse-expand-branches
                        :node (xetla-widget-category-node
                               :archive ,archive-name
                               :category ,(car category)))))
             (widget-put (widget-get res :node) :parent res)
             res))
         (let* ((l (cddr (xetla-archive-tree-get-archive
                          archive-name))))
           (when (or (null l) current-prefix-arg)
             (xetla-archive-tree-build-categories archive-name nil t))
           (cddr (xetla-archive-tree-get-archive archive-name)))))))

(defun xetla-widget-category-node-value-create (widget)
  "Create values for category WIDGET."
  (xetla-widget-node-value-create widget :category))

(defun xetla-widget-category-node-refresh ()
  "Refresh a category widget at the point."
  (interactive)
  (let ((name (xetla-widget-node-get-name)))
    (xetla-widget-node-refresh 1 nil
                              (xetla-name-archive name)
                              (xetla-name-category name))))

(defun xetla-widget-category-node-make-branch ()
  "Make new branch in the category under the point."
  (interactive)
  (let* ((name (xetla-widget-node-get-name))
         (archive (xetla-name-archive name))
         (category  (xetla-name-category name))
         (l (xetla-name-read "New Branch: "
                            archive
                            category
                            'prompt)))
    (xetla-make-branch (xetla-name-archive l)
		     (xetla-name-category l)
		     (xetla-name-branch l))
    (xetla-widget-node-refresh 1 nil
			      (xetla-name-archive l)
			      (xetla-name-category l))
    (xetla-browse-open t
                      (xetla-name-archive l)
                      (xetla-name-category l)
                      (xetla-name-branch l))))

;; --------------------------------------
;; Branch
;; --------------------------------------
(defvar xetla-widget-branch-node-map
  (let ((map (copy-keymap xetla-widget-node-map)))
    (define-key map xetla-keyvec-refresh
      'xetla-widget-branch-node-refresh)
    (define-key map (xetla-prefix-add ?v)
      'xetla-widget-branch-node-make-version)
    (define-key map xetla-keyvec-get
      'xetla-widget-branch-node-get-branch)
    map)
  "Keymap used on xetla-widget-branch-node.")

(easy-menu-define xetla-widget-branch-node-menu nil
  "Menu used on a archive item in `xetla-browse-mode' buffer."
  '("Branch"
    ["Update Version List" xetla-widget-branch-node-refresh t]
    ["Remove Branch Registration[NOT IMPLEMENTED]" nil t]
    ["Make New Version..." xetla-widget-branch-node-make-version t]
    ["Get..."              xetla-widget-branch-node-get-branch t]
    ["Add a Bookmark" xetla-widget-node-add-bookmark t]
    ["Synchronize Mirror to Remote"
     xetla-widget-node-synchronize-mirror-to-remote t]
    ["Save Name to Kill Ring" xetla-widget-node-save-name-to-kill-ring t]))

(define-widget 'xetla-widget-branch-node 'xetla-widget-node
  "Branch node in xetla-browse."
  :tag "b"
  :value-create 'xetla-widget-branch-node-value-create
  :xetla-type 'branch
  :face 'xetla-branch-name
  :keymap 'xetla-widget-branch-node-map
  :menu xetla-widget-branch-node-menu
  :archive nil
  :category nil
  :branch nil)

(defun xetla-browse-expand-branches (category)
  "Expand CATEGORY widget."
  (or (and (not current-prefix-arg) (widget-get category :args))
      (let* ((parent-node   (widget-get category :node))
             (archive-name  (widget-get parent-node :archive))
             (category-name (widget-get parent-node :category)))
        (mapcar
         (lambda (branch)
           (let ((res
                  `(tree-widget
                    :open ,(xetla-browse-open-list-member archive-name
                                                         category-name
                                                         (car branch))
                    :has-children t
                    :leaf-control xetla-widget-version-control
                    :dynargs xetla-browse-expand-versions
                    :node (xetla-widget-branch-node
                           :archive ,archive-name
                           :category ,category-name
                           :branch ,(car branch)))))
             (widget-put (widget-get res :node) :parent res)
             res))
         (let* ((l (cdr (xetla-archive-tree-get-category
                         archive-name
                         category-name))))
           (when (or (null l) current-prefix-arg)
             (xetla-archive-tree-build-branches archive-name
                                               category-name
                                               nil t))
           (cdr (xetla-archive-tree-get-category archive-name
                                                category-name)))))))

(defun xetla-widget-branch-node-value-create (widget)
  "Create values for branch WIDGET."
  (xetla-widget-node-value-create widget :branch))

(defun xetla-widget-branch-node-refresh ()
  "Refresh a branch widget at the point."
  (interactive)
  (let ((name (xetla-widget-node-get-name)))
    (xetla-widget-node-refresh 1 nil
			      (xetla-name-archive name)
			      (xetla-name-category name)
			      (xetla-name-branch name))))

(defun xetla-widget-branch-node-make-version ()
  "Make new version in the branch under the point."
  (interactive)
  (let* ((name (xetla-widget-node-get-name))
         (archive (xetla-name-archive name))
         (category (xetla-name-category name))
         (branch (xetla-name-category name))
         (l (xetla-name-read "New Version: "
                            archive
                            category
                            branch
                            'prompt)))
    (xetla-make-version (xetla-name-archive l)
		      (xetla-name-category l)
		      (xetla-name-branch l)
		      (xetla-name-version l))
    (xetla-widget-node-refresh 1 nil
			      (xetla-name-archive l)
			      (xetla-name-category l)
			      (xetla-name-branch l))
    (xetla-browse-open t
                      (xetla-name-archive l)
                      (xetla-name-category l)
                      (xetla-name-branch l)
                      (xetla-name-version l))))

(defun xetla-widget-branch-node-get-branch ()
  "Run `tla get' against the branch at point."
  (interactive)
  (let* ((name (xetla-widget-node-get-name))
	 (archive (xetla-name-archive name))
	 (category (xetla-name-category name))
	 (branch (xetla-name-branch name))
         (directory (expand-file-name
                     (read-directory-name
                      (format "Restore \"%s\" to: "
                              (progn
                                (unless branch
                                  (error "No branch under the point"))
                                (xetla-name-construct
                                 archive category branch)))))))
    (if branch
        (xetla-get directory
                 'ask
                 archive
                 category
                 branch)
      (error "No branch under the point"))))


;; --------------------------------------
;; Version
;; --------------------------------------
(defvar xetla-widget-version-node-map
  (let ((map (copy-keymap xetla-widget-node-map)))
    (define-key map xetla-keyvec-refresh
      'xetla-widget-version-node-show-revisions)
    (define-key map xetla-keyvec-get
      'xetla-widget-version-node-get-version)
    (define-key map xetla-keyvec-tag 'xetla-widget-version-node-tag)
    map)
  "Keymap used on xetla-widget-version-node.")

(easy-menu-define xetla-widget-version-node-menu nil
  "Menu used on a archive item in `xetla-browse-mode' buffer."
  '("Version"
    ["Show Revisions" xetla-widget-version-node-show-revisions t]
    ["Remove Version Registration[NOT IMPLEMENTED]" nil t]
    ["Get..." xetla-widget-version-node-get-version t]
    ["Add a Bookmark" xetla-widget-node-add-bookmark t]
    ["Synchronize Mirror to Remote"
     xetla-widget-node-synchronize-mirror-to-remote t]
    ["Put Tag..." xetla-widget-version-node-tag t]
    ["Save Name to Kill Ring" xetla-widget-node-save-name-to-kill-ring t]))

(define-widget 'xetla-widget-version-node 'xetla-widget-node
  "Version node in xetla-browse."
  :tag "v"
  :value-create 'xetla-widget-version-node-value-create
  :xetla-type 'version
  :face 'xetla-version-name
  :keymap 'xetla-widget-version-node-map
  :menu   xetla-widget-version-node-menu
  :archive nil
  :category nil
  :branch nil
  :version nil
  :open-subtree 'xetla-widget-version-node-open-subtree
  :close-subtree 'xetla-widget-version-node-open-subtree)


(define-widget 'xetla-widget-version-control 'tree-widget-empty-control
  "Control widget that represents a leaf version node."
  :tag       "[->]"
  :format    "%[%t%]"
  :action  'xetla-widget-version-control-show-revisions)

(defun xetla-widget-version-control-show-revisions (widget &optional event)
  "Show revisions in a version associated with WIDGET.
The version is under the point or place where click EVENT is created."
  (if event
      (mouse-set-point event))
  (let ((pos (next-single-property-change (point)
                                          'widget
                                          (current-buffer)
                                          (point-at-eol))))
    (when pos
      (xetla-widget-version-node-show-revisions pos))))

(defun xetla-browse-expand-versions (branch)
  "Expand BRANCH widget."
  (or (and (not current-prefix-arg) (widget-get branch :args))
      (let* ((parent-node   (widget-get branch :node))
             (archive-name  (widget-get parent-node :archive))
             (category-name (widget-get parent-node :category))
             (branch-name (widget-get parent-node :branch)))
        (mapcar (lambda (version)
                  `(xetla-widget-version-node
                        :archive  ,archive-name
                        :category ,category-name
                        :branch   ,branch-name
                        :version  ,(car version)))
                (let* ((l (cdr (xetla-archive-tree-get-branch archive-name
                                                             category-name
                                                             branch-name))))
                  (when (or (null l) current-prefix-arg)
                    (xetla-archive-tree-build-versions archive-name
                                                      category-name
                                                      branch-name
                                                      nil t))
                  (cdr (xetla-archive-tree-get-branch archive-name
                                                     category-name
                                                     branch-name)))))))

(defun xetla-widget-version-node-value-create (widget)
  "Create values for version WIDGET."
  (xetla-widget-node-value-create widget :version))

(defun xetla-widget-version-node-show-revisions (&optional point)
  "Show revisions in the version under the POINT.
If POINT is nil, use the point under `point'."
  (interactive)
  (let ((name (xetla-widget-node-get-name (or point (point)))))
    (xetla-revisions (xetla-name-archive name)
		   (xetla-name-category name)
		   (xetla-name-branch name)
		   (xetla-name-version name)
		   nil nil)))

(defun xetla-widget-version-node-get-version ()
  "Run \"tla get\" against the version at point."
  (interactive)
  (let* ((name (xetla-widget-node-get-name))
	 (archive (xetla-name-archive name))
	 (category (xetla-name-category name))
	 (branch (xetla-name-branch name))
	 (version (xetla-name-version name))
         (directory (expand-file-name
                     (read-directory-name
                      (format "Restore \"%s\" to: "
                              (progn
                                (unless version
                                  (error "No version under the point"))
                                (xetla-name-construct
                                 archive category branch version)))))))
    (if version
        (xetla-get directory
                 'ask
                 archive
                 category
                 branch
		 version)
      (error "No version under the point"))))

(defun xetla-widget-version-node-tag ()
  "Run tla tag from the version under the point."
  (interactive)
  (let* ((from (xetla-widget-node-get-name))
	 (from-fq (xetla-name-construct from))
	 (to   (xetla-name-read (format "Tag from `%s' to: " from-fq)
			       'prompt 'prompt 'prompt 'prompt))
	 (to-fq (xetla-name-construct to)))
    (unless from
      (error "No version under the point"))
    (unless to-fq
      (error "Wrong version tagged to is given"))
    (save-excursion
      (xetla-version-tag-internal from-fq to-fq 'synchronously))
    (xetla-widget-node-refresh 1 nil
			      (xetla-name-archive to-fq)
			      (xetla-name-category to-fq)
			      (xetla-name-branch to-fq))
    (xetla-browse-open t
                      (xetla-name-archive to-fq)
                      (xetla-name-category to-fq)
                      (xetla-name-branch to-fq)
                      (xetla-name-version to-fq))))

(defun xetla-widget-version-node-open-subtree (widget)
  "List revisions in the version associated with WIDGET."
  (xetla-revisions (widget-get widget :archive)
                 (widget-get widget :category)
                 (widget-get widget :branch)
                 (widget-get widget :version)
                 nil nil))

;; --------------------------------------
;; Entry point
;; --------------------------------------
;; TODO: Filtered by GROUP in bookmark
;;;###autoload
(defun xetla-browse (&optional initial-open-list append)
  "Browse registered archives as trees within one buffer.
You can specify the node should be opened by alist,
INITIAL-OPEN-LIST.  If APPEND is nil, the nodes not in
INITIAL-OPEN-LIST are made closed.  If non-nil, the nodes
already opened are kept open."

  (interactive)
  (switch-to-buffer (xetla-get-buffer-create
                     xetla-browse-buffer-type))
  (make-local-variable 'xetla-browse-open-list)
  (setq truncate-lines t)

  (let (building)
    (if (zerop (buffer-size))
        (progn (setq building t)
               (xetla-browse-set-initial-open-list initial-open-list t))
      (if append
          (progn
            (setq building nil)
            (xetla-browse-set-initial-open-list initial-open-list nil))
        (if (y-or-n-p (format "Remove old %s? " (buffer-name)))
            (progn (setq building t)
                   (xetla-browse-set-initial-open-list initial-open-list nil))
          (setq building nil)
          (xetla-browse-set-initial-open-list initial-open-list t))))

    (if building
        (progn
          (xetla-browse-erase-buffer)
          (xetla-browse-build-buffer))
      (mapc
       (lambda (elt)
         (xetla-browse-open nil
                           (xetla-name-archive elt)
                           (xetla-name-category elt)
                           (xetla-name-branch elt)
                           (xetla-name-version elt)))
       xetla-browse-open-list)))
  (goto-char (point-min))
  (xetla-browse-mode))

(defun xetla-browse-set-initial-open-list (list clearp)
  "Insert LIST to `xetla-browse-open-list'.
If CLEARP is set, clear `xetla-browse-open-list' before insertion.
This is a helper function for `xetla-browse'."
  (when clearp
    (setq xetla-browse-open-list nil))
  (mapc
   (lambda (elt)
     (xetla-browse-open-list-add (xetla-name-archive elt)
                                (xetla-name-category elt)
                                (xetla-name-branch elt)
                                (xetla-name-version elt)))
   list))
(defun xetla-browse-erase-buffer ()
  "Erase *xetla-browse* buffer."
  (let ((inhibit-read-only t))
    (erase-buffer))
  ;; remove-extent is not portable enough.
  (mapc #'delete-extent
        (mapcar-extents #'identity
                        nil nil (point-min) (point-max)
                        'all-extents-closed-open)))

(defun xetla-browse-build-buffer ()
  "Insert contents of *xetla-buffer*."
  ;; Xetla config
  (widget-create 'tree-widget
                 :open t
                 :node '(item :format "%[%t%]\n"
                              :tag "Personal Configuration")
                 :has-chidren t
                 `(xetla-widget-my-id ,(xetla-my-id)))

  (widget-insert "\n")

  ;; Archives
  (add-hook 'tree-widget-after-toggle-functions
            'xetla-browse-open-tracker)
  (widget-create 'tree-widget
                 :open t
                 :node `(xetla-widget-root-node
                         :xetla-type archives-root
                         :tag "Archives"
                         :keymap xetla-widget-archives-root-node-map
                         :menu ,xetla-widget-archives-root-node-menu)
                 :has-children t
                 :dynargs 'xetla-browse-expand-archives)
  ;; Libraries
  ;; TODO
  (widget-setup))

(defun xetla-browse-toggle-subtree-maybe ()
  "Run `xetla-browse-toggle-subtree'.
Before running a widget is searched and move the point to
the widget if it is found.  If no widget is found,
`widget-button-press'."
  (interactive)
  (let ((p (next-single-property-change (point-at-bol)
                                        'widget
                                        nil
                                        (point-at-eol))))
    (if (and p (xetla-widget-node-get-type p))
        (xetla-widget-node-toggle-subtree p)
      (widget-button-press (point)))))

(defun xetla-browse-dash ()
  "Move the point to the place where a widget is in the current line."
  (interactive)
  (let ((p (next-single-property-change (point-at-bol)
                                        'widget
                                        nil
                                        (point-at-eol))))
    (when (and p (xetla-widget-node-get-type p))
      (goto-char p)
      (xetla-flash-line))))

(defvar xetla-browse-map
  (let ((map (copy-keymap widget-keymap)))
    (define-key map xetla-keyvec-help 'describe-mode)
    (define-key map (xetla-prefix-buffer ?p) 'xetla-show-process-buffer)
    (define-key map (xetla-prefix-buffer ?L) 'xetla-open-internal-log-buffer)
    (define-key map (xetla-prefix-buffer xetla-key-show-bookmark) 'xetla-bookmarks)
    (define-key map [return] 'xetla-browse-toggle-subtree-maybe)
    (define-key map "\C-m" 'xetla-browse-toggle-subtree-maybe)
    (define-key map " " 'xetla-browse-dash)
    (define-key map xetla-keyvec-next     'next-line)
    (define-key map xetla-keyvec-previous 'previous-line)
    (define-key map xetla-keyvec-quit     'kill-this-buffer)
    (define-key map [?+] 'xetla-widget-node-toggle-subtree-recursive)
    map)
  "Keymap used in `xetla-browse-mode'.")

(defun xetla-browse-mode ()
  "Mode for browsing xetla's archives.
Don't use this function.  Instead call `xetla-browse'."
  (setq major-mode 'xetla-browse-mode
        mode-name "xetla-browse")
  (use-local-map xetla-browse-map)
  (set-buffer-modified-p nil)
  (run-hooks 'xetla-browse-mode-hook))

(provide 'xetla-browse)

;;; xetla-browse.el ends here
