;;; jde-help.el
;; $Revision: 1.4 $ 

;; Author: Paul Kinnucan <paulk@mathworks.com>, Phillip Lord <plord@hgmp.mrc.ac.uk>
;; Maintainer: Paul Kinnucan
;; Keywords: java, tools

;; Copyright (C) 1999, 2001 Paul Kinnucan.

;; 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 2, or (at your option)
;; any later version.

;; 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.

;; You should have received a copy of the GNU General Public License
;; along with GNU Emacs; see the file COPYING.  If not, write to the
;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
;; Boston, MA 02111-1307, USA.

(require 'beanshell)
(require 'jde-widgets)
(require 'eieio)

(makunbound 'jde-help-docsets)
(defcustom jde-help-docsets (list (list "javadoc" "http://java.sun.com/j2se/1.3/docs/api" nil))
  "*Lists collections of HTML files documenting Java classes. 
This list is used by the `jde-help-class' command to find help for 
a class. You can specify the following information for each docset:

Docset type

  The following types are valid: 

  * javadoc. 

    Collections generated by the javadoc command.

  * Other

    Collections of HTML class documentation files generated by some
    other means.

Docset directory

   Directory containing the collection, e.g., d:/jdk1.3/docs/api.
   The docset directory may be located on a remote system in which
   case this field should specify the URL of the docset directory,
   e.g., http://www.javasoft.com/j2se/1.3/docs/api. The GNU utility, wget, 
   or the w3 function `url-file-exists' must be installed on your
   system to find javadoc pages located on 
   remote systems. Native Windows and cygwin ports of wget
   are readily available on the Internet. Make sure that wget is
   in Emacs `exec-path' before attempting to access documentation
   on remote systems. See `jde-help-remote-file-exists-function'
   for more information.

Doc lookup function

   Should specify a function that accepts a fully qualified class name, 
   e.g., java.awt.String, and a docset directory and returns a path to 
   an HTML file that documents that class, e.g., 
   d:/jdk1.2/docs/api/java/awt/String.html. This field must be specified
   for non-javadoc collections. It is ignored for javadoc colletions.
"
  :group 'jde-project
  :type '(repeat 
	  (list
	   (radio-button-choice
	    :format "%t \n%v"
	    :tag "Docset type:"
	    (const "javadoc")
	    (const "Other"))
	   (file :tag "Docset directory")
	   (function :tag "Doc lookup function:"))))

;;(makunbound 'jde-help-remote-file-exists-function)
(defcustom jde-help-remote-file-exists-function (list "wget")
  "Specifies the function the jde uses to retrieve remote documents.
wget is a Unix utility available on Windows as part of the Cygwin
package. `url-file-exists' is part of the url Emacs Lisp library,
which is included in the Emacs w3 package."
  :group 'jde-project
  :type '(list
	  (radio-button-choice
	   :format "%t \n%v"
	   :tag "Function:"
	   (const "wget")
	   (const "url-file-exists")))
  :set '(lambda (sym val)
	  (if (and
	       (string= (car val) "url-file-exists")
	       (locate-library "url"))
	       (autoload 'url-file-exists "url" nil nil nil))
	  (set-default sym val)))

(defun jde-file-to-url (file)
  "Convert FILE path to a URL. If FILE is a DOS path, this
function replaces the colon in the drive specifier with a
vertical bar (|) because both Internet Explorer and Netscape
accept the resulting URL whereas Netscape does not accept
a drive specifier with a colon."
  (if (or (string-match "http:" file) 
	  (string-match "file:" file))
      file    
    (format "file://%s" 
	    ;; Check for DOS path.
	    (if (string-match "[a-zA-Z]:" file)
		(substitute ?| ?: file)
	      (jde-convert-cygwin-path file)))))

(defun jde-help-docset-get-type (docset)
  (nth 0 docset))

(defun jde-help-docset-get-dir (docset)
  (let ((path (nth 1 docset)))
    (if (string-match "http:" path)
	path
      (jde-normalize-path (nth 1 docset) 'jde-help-docsets))))

(defun jde-help-docset-get-lookup-function (docset)
  (nth 2 docset))

(defun jde-help-find-javadoc (class docset-dir)
  "Searches DOCSET-DIR for the javadoc HTML page
for CLASS and, if found, returns the URL of the
javadoc page for CLASS. This function uses the function
specified by `jde-help-remote-file-exists-function'
to verify the existence of pages located on remote systems."
  (let ((class-path
         (concat (substitute ?/ ?. class) ".html")) 
	url)
    (cond
     ((string-match "http:" docset-dir)
      (setq url (concat docset-dir "/" class-path))
             (if (string= 
		  (car jde-help-remote-file-exists-function) 
		  "url-file-exists")
	  (if (fboundp 'url-file-exists)
	      (if (not
		   (url-file-exists url))
		  (setq url nil))
	    (error "Cannot find url-file-exists function"))
        (if (executable-find 
	     (if (eq system-type 'windows-nt) "wget.exe" "wget"))
            (if (not
                 (string-match
                  "200"
                  (shell-command-to-string
                   (concat "wget --spider " url))))
                (setq url nil))
          (error
           (concat "Cannot find wget. This utility is needed "
                   "to access javadoc on remote systems.")))))
     (t
      (let ((doc-path
             (expand-file-name class-path docset-dir)))
        (if (file-exists-p doc-path)
            (setq url (jde-file-to-url doc-path))))))
    url))


(defun jde-help-get-doc (class) 
"Gets URL to the HTML file for CLASS where CLASS is a 
qualified class name."
  (if class
      (if jde-help-docsets
	(let ((paths
	       (mapcar
		(lambda (docset)
		  (cond
		   ((string= (jde-help-docset-get-type docset) "javadoc")
		    (jde-help-find-javadoc
		      class
		      (jde-help-docset-get-dir docset))) 
		   (t
		    (apply
		     (jde-help-docset-get-lookup-function docset)
		     class
		     (list (jde-help-docset-get-dir docset))))))
		jde-help-docsets)))
	  (setq paths (delq nil paths))
	  ;; Return first file found.
	  (if paths (car paths) paths))
	(error "%s" "Help error: No docsets available. See jde-help-docsets."))))


(defun jde-help-symbol-internal (class)
  (let ((doc-file (jde-help-get-doc class)))
    (if doc-file 
	(jde-help-show-document doc-file)
      (message "Error: cannot find documentation for %s" class))))

(defun jde-help-symbol ()
  "Displays help for a symbol. The symbol may reference an object, a class,
or a method or field. If the symbol references a class, this function displays the 
javadoc for the class. If the symbol references an object,  this method 
displays the javadoc for the class of the object. If the symbol references a field or
a method, this function displays the javadoc for the class of the object of which
the field or method is a member. Eventually this function will be enhanced to position
the javadoc at the point where the method or field is documented."
  (interactive)
  (condition-case err
      (let* ((unqualified-name (thing-at-point 'symbol))
	     (class-name (jde-complete-get-qualified-name unqualified-name)))
	(if (not class-name)
	    (let ((parse-result (jde-help-parse-symbol-at-point)))
	      (if parse-result
		  (progn
		    (setq unqualified-name  (car parse-result))
		    (setq class-name (jde-complete-get-qualified-name unqualified-name)))))) 
	(if class-name
	    (jde-help-symbol-internal class-name)
	  (message "Error: cannot find class '%s' on the current classpath." unqualified-name)))
    (error
     (message "%s" (error-message-string err)))))
  

(defun jde-help-show-document (doc-file)
  "Displays DOC-FILE in the default browser."
  (browse-url (jde-file-to-url doc-file)))

(defun jde-help-parse-symbol-at-point ()
  "Returns (cons TYPE MEMBER) where TYPE is the declared type of
the object referenced by the (qualified) name at point and MEMBER is the
field or method referenced by the name if qualified."
  (let ((parse-result (jde-parse-qualified-name-at-point)))
    (if parse-result
	(let* ((qualifier (car parse-result))
	       (name (cdr parse-result))
	       (obj (if qualifier qualifier name))
	       (member (if qualifier name)))
	  (if (not
	       (and 
		qualifier
		(string-match "[.]" qualifier)))
	      (let ((declared-type (car (jde-parse-declared-type-of obj))))
		(if declared-type
		    (cons declared-type  member))))))))

(defun jde-help-class (&optional class-name)
  "Return help for  CLASS."
  (interactive)
  (let ((class
	 (or class-name
	     (read-from-minibuffer "Class: " (thing-at-point 'symbol)))))
    (lexical-let (help-class)
      (fset 'help-class
	    (lambda (class)
	      (let ((doc-file (jde-help-get-doc class)))
		(if doc-file 
		    (jde-help-show-document doc-file)
		  (message "Error: cannot find documentation for %s" class)))))
      (jde-parse-select-qualified-class-name
       class 'help-class))))


(defun jde-help-show-class-member-doc (docfile)
  "Show DOCFILE in the browser defined by `browse-url-browser-function'
where DOCFILE is assumed to include the anchor for a class member. This
function creates a temporary HTML file that redirects the browser to
DOCFILE. This is a workaround made necessary by the fact that the
default browser function for Windows uses the Windows ShellExecute function 
to invoke Internet Explorer and for some reason ShellExecute does not pass 
the anchor to IE."    
  (let* ((temp-directory
	  (or (if (boundp 'temporary-file-directory) temporary-file-directory)
	      (if (fboundp 'temp-directory) (temp-directory))))
	 (metafile (expand-file-name "jde_meta.html" temp-directory))
	 (buff (find-file-noselect metafile))
	 (standard-output buff))
    (if buff
	(save-excursion
	  (set-buffer buff)
	  (erase-buffer)
	  (princ "<HTML>\n<HEAD>\n")
	  (princ 
	   (format "<META HTTP-EQUIV=Refresh CONTENT=\"0; URL=%s\">\n" 
		   (jde-file-to-url docfile)))
	  (princ "</HEAD>\n</HTML>")
	  (save-buffer)
	  (jde-help-show-document metafile))
      (error "Unable to create a temporary file in %s directory."
	     temporary-file-directory))))

(defun jde-help-popup-class-member-menu (class &optional title)
  "Popup a menu of the fields and methods defined by CLASS.
Return the member selected by the user."
  (let ((classinfo 
	  (jde-complete-get-classinfo class)))  
    (if classinfo
	(let ((pair 
	       (if (= (length classinfo) 1)
              ;; if only one item match, return it 
              (car classinfo)
	      ;; delegates menu handling to imenu :-)
	      (imenu--mouse-menu classinfo  
				 (jde-cursor-posn-as-event) ; Popup window at text cursor
				 (or title "Class Members")))))
	  (cdr pair))
      (message "Class %s has no members." class))))



(defun jde-help-class-member (&optional class-name)
  "Pop up a menu of the fields and methods of CLASS.
Then search `jde-help-docsets' for javadoc for CLASS. If found, 
point the browser to the doc for the selected method or
field. Note: this command does not check whether the doc
for CLASS actually documents the selected class member."
  (interactive)
  (let ((class
	 (or class-name
	     (read-from-minibuffer "Class: " (thing-at-point 'symbol)))))
    (lexical-let (help-class-member)
      (fset 'help-class-member
	    (lambda (class)
	      (let ((doc-file (jde-help-get-doc class)))
		(if doc-file 
		    (let ((member (jde-help-popup-class-member-menu class)))
		      (if member
			  (jde-help-show-class-member-doc
			   (concat doc-file "#" member))))
		  (message "Error: cannot find documentation for %s" class)))))
      (jde-parse-select-qualified-class-name
       class 'help-class-member))))


(defun jde-open-class-source ( &optional unqual-class )
  "Displays source of the class whose name appears at point in the current
Java buffer. This command finds only classes that reside in the source paths
specified by `jde-db-source-directories'. You should provide a global setting
for this variable in your .emacs file to accommodate source files that are
not associated with any project."
  (interactive)
  (condition-case err
      (let* ((unqualified-name 
 	      (or unqual-class
		  (read-from-minibuffer "Class: " (thing-at-point 'symbol))))
 	     (class-names 
 	      ;;expand the names into full names, or a list of names
 	      (jde-jeval-r 
 	       (concat 
 		"jde.util.JdeUtilities.getQualifiedName(\"" 
 		unqualified-name "\");"))))
 	;;Check return value of QualifiedName
 	(if (or (eq class-names nil)
		(not (listp class-names)))
 	    (error "Cannot find %s" unqualified-name))
	;; Turn off switching project settings to avoid 
	;; resetting jde-db-source-directories.
	(let ((old-value jde-project-context-switching-enabled-p))
	  (setq jde-project-context-switching-enabled-p nil)
	  ;;If the list is only one long
	  (if (eq 1 (length class-names))
	      ;;then show it
	      (progn(other-window 1)
		    (jde-find-class-source (car class-names)))
	     	  ;;else let the user choose
	    (let ((dialog
		   (jde-open-class-source-chooser-dialog
		    "show sources dialog"
		    :classes class-names)))
	      (jde-dialog-show dialog)))
	  (setq jde-project-context-switching-enabled-p old-value)))
    (error
     (message "%s" (error-message-string err)))))

(defalias 'jde-show-class-source 'jde-open-class-source)

(defclass jde-open-class-source-chooser-dialog (jde-dialog)
  ((classes     :initarg :classes
		:type list
		:documentation
		"Classes that match the unqualified class name.")
   (check-boxes :initarg :check-boxes
		:documentation
		"Radio buttons used to select source file."))
  "Dialog used to specify which classes to show the source for.")

(defmethod jde-dialog-create ((this jde-open-class-source-chooser-dialog))
    (widget-insert "Several classes match the name you specified.\n")
    (widget-insert "Select the ones you want to view.\n")
    (widget-insert "Then click the OK button.\n\n" )

    (let ((items
	   (mapcar
	    (lambda (class)
	      (list
	       'const
	       :format "%v"
	       class))
	    (oref this classes))))

      (oset this check-boxes
	    (widget-create
	     (list 'checklist :entry-format " %b %v\n" :args items)))
      (widget-insert "\n")))

(defmethod jde-dialog-ok ((this jde-open-class-source-chooser-dialog))
  (let ((dialog-buffer (current-buffer)))
    (mapc (lambda (x) 
	    (other-window 1)
	    (jde-find-class-source x)) 
	  (widget-value (oref this check-boxes)))
    (kill-buffer dialog-buffer)))

;; Borrowed from java-open library.
(defun jde-open-base-class-source ()
  "Open source file of base class of class defined in current buffer."
  (interactive)
  (let ((class-name
        (file-name-sans-extension 
         (file-name-nondirectory (buffer-file-name)))))
    (save-excursion
      (goto-char (point-min))
      (if (re-search-forward
           (concat "class " class-name 
                   " extends *[a-zA-Z_][a-zA-Z0-9_]*") nil t)
          (jde-open-class-source)
        (error "Failed to determine base class of \"%s\"" class-name)))))


(provide 'jde-help)

;; $Log: jde-help.el,v $
;; Revision 1.4  2001/10/14 22:20:31  andyp
;; Sync to 2.2.8
;;
;; Revision 1.30  2001/08/10 06:14:01  paulk
;; * Add support for cygwin paths to jde-file-to-url.
;;
;; Revision 1.29  2001/08/09 04:46:55  paulk
;; * XEmacs compatibility fix. Now accommodates the way XEmacs specifies the temp directory. Thanks to Dr. Volker Zell.
;;
;; * Now replaces the colon in the DOS drive prefix with a vertical bar when forming URL's. This is done to accommodate Netscape.
;;
;; Revision 1.28  2001/08/08 05:56:12  paulk
;; Removed prompt from jde-help-symbol.
;;
;; Revision 1.27  2001/08/08 05:22:18  paulk
;; Adds jde-help-class-member command.
;;
;; Revision 1.26  2001/08/04 05:30:20  paulk
;; Fixed jde-help-symbol so that it prompts you to enter the symbol. Also, if more than once class of the same name exists, prompts you to select the appropriate class.
;;
;; Revision 1.25  2001/06/12 07:18:55  paulk
;; Changed jde-parse-declared-type-of to return a qualified type.
;; Thanks to "Evan Easton" <evan@eeaston.com> .
;;
;; Revision 1.24  2001/05/31 05:14:39  paulk
;; Provide support for per-project caching of class data in the Beanshell. Thanks to Matt Conway.
;;
;; Revision 1.23  2001/05/31 02:25:39  paulk
;; User can now force the JDE to use either wget or url-file-exists to verify existence of a remote file.
;; Thanks to Luis Miguel Hernanz Iglesias <luish@germinus.com> for suggesting this enhancement.
;;
;; Revision 1.22  2001/04/19 04:39:41  paulk
;; Fixed regression error caused by normalizing paths. Now checks to ensure that path is local before trying to normalize it.
;;
;; Revision 1.21  2001/04/16 05:53:51  paulk
;; Normalized paths.
;;
;; Revision 1.20  2001/04/08 04:11:40  paulk
;; jde-help-find-javadoc now uses url-file-exists (from the w3 package) if it is in your load-path. Otherwise, it uses wget. Thanks to Knut Wannheden <wannhedenk@post.ch> and  klaus.berndl@sdm.de for this fix.
;;
;; Revision 1.19  2001/03/29 02:46:52  paulk
;; Replaced jde-find-exec with executable-find, which is defined by executable.el available with both the Emacs and XEmacs distributions.
;;
;; Revision 1.18  2001/03/27 17:49:33  paulk
;; Eliminate dependency on which package by including the function jde-find-exec and replacing references to the which command with jde-find-exec. Thanks to klaus.berndl@sdm.de for suggesting this change and providing the implementation of jde-find-exec.
;;
;; Revision 1.17  2001/03/27 16:44:50  paulk
;; Updated to require which package. Removed extraneous definition of jde-help-find-javadoc. Thanks to klaus.berndl@sdm.de and Brad Giaccio <bgiaccio@psrw.com> for reporting these problems.
;;
;; Revision 1.16  2001/03/12 05:30:15  paulk
;; Can now access javadoc anywhere on the Web. Thanks to Adrian Robert <arobert@polexis.com> for providing the initial version of this enhancement.
;;
;; Revision 1.15  2001/02/04 01:31:13  paulk
;; Changed declaration of customized variables to permit completion of paths.
;;
;; Revision 1.14  2000/10/08 12:55:39  paulk
;; *** empty log message ***
;;
;; Revision 1.13  2000/08/12 04:47:10  paulk
;; Fixed regression error in jde-help-symbol-at-point.
;;
;; Revision 1.12  2000/02/09 05:06:49  paulk
;; Replaced jde-help-class with jde-help-symbol method. The new method
;; gets help for the symbol at point. The symbol may refer to a class,
;; an object, or a method or field.
;;
;; Revision 1.11  2000/02/01 04:11:56  paulk
;; ReleaseNotes.txt
;;
;; Revision 1.10  2000/01/18 07:11:25  paulk
;; Added jde-show-class-source. Thanks to Phil Lord for the initial
;; implementation of this command.
;;
;; Revision 1.9  2000/01/15 08:06:25  paulk
;; Eliminated some globally bound symbols.
;;
;; Revision 1.8  1999/09/30 04:46:10  paulk
;; Fixed typo spotted by David Biesack.
;;
;; Revision 1.7  1999/09/18 03:26:39  paulk
;; Now prepends "file://" to doc file when invoking browse-url. Hopefully
;; this will fix the problem reported by one user where the browser
;; prepends http://www to doc file path.
;;
;; Revision 1.6  1999/08/20 00:44:43  paulk
;; Corrected spelling of Phillip Lord's name.
;;
;; Revision 1.5  1999/06/26 00:00:12  paulk
;; Type javadoc now sufficient to specify both Java 1 and Java 2 javadoc docsets.
;;
;; Revision 1.4  1999/06/25 01:38:17  paulk
;; Enhanced to support doc collections of any type.
;;
;; Revision 1.3  1999/06/17 22:27:33  paulk
;; Bug fix.
;;
;; Revision 1.2  1999/06/17 21:53:05  paulk
;; Eliminated separate customization group for help variables.
;;
;; Revision 1.1  1999/06/17 21:47:15  paulk
;; Initial revision
;;

;; End of jde-help.el
