
package org.simtk.isimsu;

import javax.swing.*;
import javax.swing.filechooser.FileFilter;
import java.util.*;
import java.net.*;
import java.io.*;
import java.awt.Container;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.event.*;

public class GetPymolLocation {
	
	// url for muffin
	
	URL pymolUrl;
	
	// topLevel for FileChooser dialog window
	
	java.awt.Component topLevel;
	
	// logging reference
	
	LogDialog logDialog;
	
	// constructor
	
	GetPymolLocation( java.awt.Component inputTopLevel, LogDialog inputLogDialog ){
	   topLevel  = inputTopLevel;
	   logDialog = inputLogDialog;
	   pymolUrl  = null;
	}
	
	// get Pymol Url
	
	URL getPymolUrl(){
		
        String methodName = "getPymolUrl";
		if( pymolUrl == null ){
			try {
		
			   // pymolUrl  = new URL( "http://public.simtk.org/~cmbruns/isim_interface/webstart/pymol" );
			   pymolUrl  = new URL( "http://public.simtk.org" );
			} catch( MalformedURLException exception ){
				logDialog.append( methodName + " invalid pymol URL " + exception.getMessage() );
			}
		}
		return pymolUrl;
	}
	
	// get Pymol location from user
	
	String getPymolLocationfromUser( String osName ){
		
      GetPyMolLocationFromUserDialog getPyMolLocationFromUserDialog = new GetPyMolLocationFromUserDialog( topLevel, osName );
      logDialog.append( "Getting Pymol path from user" );
      
      File pymolLocation = getPyMolLocationFromUserDialog.getPymolLocation();
      String path;
      
      if( pymolLocation != null ){
         if( pymolLocation.isDirectory() ){
            logDialog.append( "User chose directory: try to find executable." );  
            path = checkForPymolBasedOnOs( osName, pymolLocation );
            if( path != null ){
            	pymolLocation = new File( path );
            }
          }
          
	      try {
		      path = pymolLocation.getCanonicalPath();
	      } catch( IOException exception ){
		      logDialog.append( "Problem getting canonical path: " + exception.toString() );
		      path = null;
	      }
 
         return path;
      } else {
         return null;
      }

	}
	
   // return true if Pymol location is valid; else false
	
	boolean isValidPymol( String pymolDirectory, String pymolExecutable ){
		
	   // check that directory exists and if it does that the executable is in the directory
		
	   File directory = new File( pymolDirectory );
	   if( directory.isDirectory() ){
		   logDialog.append( "Directory=<" + pymolDirectory + "> exists.\n" );
		   try {
		      String fileName = getFullFileName( pymolDirectory, pymolExecutable );
		      File pymolExecutableFile = new File( fileName );
		      if( pymolExecutableFile.isFile() ){
			      return true;
		      } 
		   } catch( Exception exception ){
			   return false;
		   }
		   logDialog.append( "Directory=<" + pymolDirectory + "> exists, but executable=" +
				              pymolExecutable + " is missing.\n" );
	   } else {
		   logDialog.append( "Directory=<" + pymolDirectory + "> does not exist.\n" );		  
	   }
	   return false;
	}
	
	String getFullFileName( String pymolDirectory, String pymolExecutable ){	
		return pymolDirectory + System.getProperty( "file.separator" ) + pymolExecutable;			
	}
	
	// get Pymol location from muffin
	
	String getPymolLocationFromMuffin( ){
		
		MuffinWrapper muffinWrapper = new MuffinWrapper( logDialog );
		
		String muffinContents = muffinWrapper.getMuffinContents( getPymolUrl() );
		// String muffinContents = null;
	    if( muffinContents == null ){
	    	logDialog.append( "No muffin avalaible for URL=<" + getPymolUrl() + ">" );
	    } else {
	    	logDialog.append( "muffin for URL=<" + getPymolUrl() + ">: " + muffinContents );
	    }
	    return muffinContents;

	}
	
	// write muffin containing Pymol location
	
	boolean writePymolLocationToMuffin( String muffinContents ){
		
		MuffinWrapper muffinWrapper = new MuffinWrapper( logDialog );
		return muffinWrapper.writeMuffinContents( getPymolUrl(), muffinContents );
	}
	
	// cascade through strategies for getting Pymol location
	
	String getPymolLocation( String osName ){
		
     logDialog.setPrintToOutFile( true );
	 logDialog.append( "getPymolLocation: begin\n" );

      // (1) try muffin
      // (2) try generic locations based on OS (Windows, Mac, Linux)
      // (3) ask user for location
      // If muffin absent, then write muffin
      
		String pymolLocation = getPymolLocationFromMuffin();
	    // String pymolLocation = getPymolLocationfromUser( osName );
		
		// check that muffin contents are valid (assume here that muffin is full path
		// name to executable file)
		
		if( pymolLocation != null ){
		   File pymolFile       = new File( pymolLocation );
		   if( !isValidPymol( pymolFile.getParent(), pymolFile.getName() ) ){
			   pymolLocation = null;  
		   }
		}
		
		// try to get location based on OS type
		
		if( pymolLocation == null ){
			logDialog.append( "getPymolLocation: No muffin or muffin location invalid.\n" );
			pymolLocation = checkForPymolBasedOnOs( osName, null );
			if( pymolLocation == null ){
			   pymolLocation = getPymolLocationfromUser( osName );
               writePymolLocationToMuffin( pymolLocation );
			}
			
			/*
            if( writePymolLocationToMuffin( pymolLocation ) ){
			   logDialog.append( "getPymolLocation:  wrote muffin=<" + pymolLocation + ">\n" );
            } else {
            	logDialog.append( "getPymolLocation:  could not write muffin.\n" );            	
            }
            */
			
		} else {
			logDialog.append( "getPymolLocation: muffin contained string=<" + pymolLocation + ">\n" );
		}
		logDialog.append( "getPymolLocation:" + osName + "\n" );
		
        // check if X11 installed
      
		if( osName.compareTo( "Mac" ) == 0 && GetPymolLocation.isX11Installed( osName ) < 1 ){
           RemindUserToInstallX11Dialog remindUserToInstallX11Dialog = new RemindUserToInstallX11Dialog( topLevel, osName );
           remindUserToInstallX11Dialog.getIsDone();
        }
				
		return pymolLocation;
	}
	
   // get environment setting for Pymol_Path
   
   String getPymolEnvironmentPath( String pymolLocation, String osName ){

      File pymolExecutableFile      = new File( pymolLocation );
      File parentDirectoryFile      = pymolExecutableFile.getParentFile();
      String executableName         = pymolExecutableFile.getName();
      File environmentPymolPathFile = null;

		if( osName.compareTo( "Mac" ) == 0 && executableName.compareTo( "MacPyMOL" ) == 0 ){
         parentDirectoryFile = parentDirectoryFile.getParentFile(); 

         // move up two levels in the file hierarchy if Pymol is being called from a Mac bundle
         // to get to the pymol directory 
         
         if( parentDirectoryFile != null ){
            parentDirectoryFile      = parentDirectoryFile.getParentFile(); 
            environmentPymolPathFile = new File( parentDirectoryFile, "pymol" );
            if( !environmentPymolPathFile.exists() ){
		    	   logDialog.append( "Mac directory <" + environmentPymolPathFile.getPath() + "> does not exist.\n" );
               environmentPymolPathFile = null;
            }
         }
      }

      // default is directory executable resides in
      
      if( environmentPymolPathFile == null ){
         environmentPymolPathFile = parentDirectoryFile;
      }

      // report if directory does not exist
      
      if( !environmentPymolPathFile.exists() ){
		   logDialog.append( "Pymol directory <" + environmentPymolPathFile.getPath() + "> does not exist.\n" );
      }

      try {
         return environmentPymolPathFile.getCanonicalPath();
      } catch( Exception exception ){
		   logDialog.append( "Probem getting canonical path for <" + environmentPymolPathFile.getPath() + ">.\n" );
         return environmentPymolPathFile.getPath();
      }

   }

   // get environment setting for PythonPath
   
   String getPythonEnvironmentPath( String pymolLocation, String osName ){

      String pymolPath      = getPymolEnvironmentPath( pymolLocation, osName );
      File pythonPathFile   = new File( pymolPath, "ext");

      // report if directory does not exist
      
      if( !pythonPathFile.exists() ){
		   logDialog.append( "Python directory <" + pythonPathFile.getPath() + "> does not exist.\n" );
      }

      try {
         return pythonPathFile.getCanonicalPath();
      } catch( Exception exception ){
		   logDialog.append( "Probem getting canonical path for <" + pythonPathFile.getPath() + ">.\n" );
         return pythonPathFile.getPath();
      }

   }

   // cascade through strategies for getting Pymol location
	
	String checkForPymolBasedOnOs( String osName, File directoryToCheck ){
	
		String methodName = new String( "checkForPymolBasedOnOs" );
		
      // add possible/common directories for pymol to genericPymolLocations list
      // and set name of executable for each OS
      // then loop through directories searching for one that contains
      // the executable
      
      // load list and set executable file name
      
		LinkedList<String> genericPymolLocations = new LinkedList<String>();
		String[] pymolExecutableName             = getPymolExecutableFileNameBasedOnOs( osName );
		
		if( directoryToCheck != null ){
			genericPymolLocations.add( directoryToCheck.toString() );		
		} else {
		   if( osName.compareTo( "Windows" ) == 0 ){
		   	  genericPymolLocations.add( "C:\\Program Files\\DeLano Scientific\\PyMOL\\");		
			  genericPymolLocations.add( "C:\\Program Files (x86)\\DeLano Scientific\\PyMOL\\");
		   } else if( osName.compareTo( "Linux" ) == 0 ){
		      genericPymolLocations.add( "/usr/local/bin");							
		   } else if( osName.compareTo( "Mac" ) == 0 ){
			  // genericPymolLocations.add( "/Applications/PyMOLX11Hybrid.app/Contents/MacOS");
		      genericPymolLocations.add( "/Applications/MacPyMOL.app/Contents/MacOS");
			  genericPymolLocations.add( "/Applications/PyMOLX11Hybrid.app/Contents/MacOS");
			// genericPymolLocations.add( "/usr/local/bin" );			
			// genericPymolLocations.add( "/Users/simbios/friedrim/src/pymolBranch/webstart/pymol/mac/dir_pymol" );
		   }
		}
		
      // search for executable in directories until one is found or
      // all possibilites exhausted
      
		String pymolLocation   = null;
		for( int ii = 0; ii < pymolExecutableName.length; ii++ ){
			
		   if( pymolExecutableName[ii] != null ){
			  logDialog.append( methodName + "Trying File=<" + pymolExecutableName[ii] + ">\n" );
			  
		      Iterator<String> it    = genericPymolLocations.iterator();
		      while( it.hasNext() ){
		         String directoryName = it.next();
		          logDialog.append( "Checking directory=<" + directoryName + ">" );
		          if( isValidPymol( directoryName, pymolExecutableName[ii] ) ){
		    	     logDialog.append( " Is Valid directory/file \n" );
		    	     return getFullFileName( directoryName, pymolExecutableName[ii] );
		          }
		      }
		    }
		    logDialog.append( "\n" );
		}
		
		logDialog.append( methodName + " No hits for " + osName );
		
		return pymolLocation;
	}

   // get possible excutable name(s) based on the OS
	
	String[] getPymolExecutableFileNameBasedOnOs( String osName ){
	
		// String methodName = new String( "getPymolExecutableFileNameBasedOnOs" );
		      
		String[] pymolExecutableName = new String[2];
		for( int ii = 1; ii < pymolExecutableName.length; ii++ ){
		   pymolExecutableName[ii]       = null;
		}
		
		if( osName.compareTo( "Windows" ) == 0 ){			
			pymolExecutableName[0] = new String( "pymolwin.exe" );	
		} else if( osName.compareTo( "Linux" ) == 0 ){						
			pymolExecutableName[0] = new String( "pymol.exe" );	
		} else if( osName.compareTo( "Mac" ) == 0 ){
			pymolExecutableName[0] = new String( "MacPyMOL" );	
			pymolExecutableName[1] = new String( "pymol.exe" );
		} else {
			pymolExecutableName[0] = new String( "pymol.exe" );
		}
		
		return pymolExecutableName;
	}

	// return File object or null if Pymol executable not found 
	
	//File pymolExecutableFile( String osName ){
	//	String pymolLocation = getPymolLocation( osName );
	//	if( pymolLocation != null ){
	//		return new File( pymolLocation, getPymolExecutableFileNameBasedOnOs( osName ) );
	//	}
	//	return null;
	// }

	// return File object containing Pymol path or null if path not found 
   
	File getPymolPath( String osName ){
		String pymolLocation = getPymolLocation( osName );
		if( pymolLocation != null ){
			return new File( pymolLocation );
		}
		return null;
	}
	
//	 return File object containing Pymol path or null if path not found 
	   
	String getPathToPymolExecutable( String osName ){
		
		String pymolLocation  = getPymolLocation( osName );
		logDialog.append( "getPathToPymolExecutable: begin\n" );
		return pymolLocation;
	}

   // return  1 if X11 is installed
   // return  0 if unknown if X11 is installed
   // return -1 if X11 appears not to be installed
   
   static int isX11Installed( String osName ){

      if( osName.compareTo( "Mac" ) == 0 ){
  		   File x11Directory = new File( "/Applications/Utilities/X11.app" );
		   return x11Directory.exists() ? 1 : -1;
      }
      
      return 0;
   }
}

// class used to get Pymol location from user

@SuppressWarnings("serial") class GetPyMolLocationFromUserDialog extends JFrame {
    
    File _pymolLocation;
    boolean _done = false;
    JFileChooser _chooser;
    java.awt.Component _topLevel;
    String _osName;
    boolean _x11Exists;
    
    public GetPyMolLocationFromUserDialog( java.awt.Component inputTopLevel, String osName ){
        
        _topLevel      = inputTopLevel;        
        _pymolLocation = null;
        _osName        = osName;
        _done          = false;
        _x11Exists     = true;
        
        initializeDialog();
    }
    
    java.awt.Component getTopLevel( ){ return _topLevel; }
    
    void setPymolLocation( File inputPymolLocation ){
    	_pymolLocation = inputPymolLocation;
    }
    
    void setIsDone( boolean inputIsDone ){
    	_done = inputIsDone;
    }

    void initializeDialog( ){
    	
        setTitle( "Choose Pymol executable");
      
        Container content = getContentPane();
        JPanel contentPanel = new JPanel();
        contentPanel.setLayout( new BoxLayout(contentPanel, BoxLayout.Y_AXIS));
        
        content.add( new JScrollPane(contentPanel) );

        String pymolDownloadUrl = null;
        if( _osName.compareTo( "Mac" ) == 0 ){
           if( GetPymolLocation.isX11Installed( _osName ) == 1 ){
 		       _x11Exists = true;
           } else {
 		       _x11Exists = false;
           }
           pymolDownloadUrl = new String( "http://delsci.com/macpymol/" );
        } else {
           pymolDownloadUrl = new String( "http://delsci.com/rel/099/" );
        }
       
        contentPanel.add(Box.createRigidArea(new Dimension(0,5)));
        JTextArea label = new JTextArea(getExplanatoryHeader());
        label.setAlignmentX(Component.CENTER_ALIGNMENT);
        contentPanel.add(label);
        
        contentPanel.add(Box.createRigidArea(new Dimension(0,8)));
        contentPanel.add(new JSeparator());
        contentPanel.add(Box.createRigidArea(new Dimension(0,8)));
         
        JButton button = new JButton( "Select location of Pymol Execuable" );
        button.addActionListener( new LaunchPymolFileChooser( this, _osName ) );
        button.setAlignmentX(Component.CENTER_ALIGNMENT);
        contentPanel.add( button );
        
        BrowserLaunchListener browserLaunchListener = new 
        BrowserLaunchListener( _topLevel, pymolDownloadUrl );
        button = new JButton( "Download Pymol" );
        button.addActionListener( browserLaunchListener );
        button.setAlignmentX(Component.CENTER_ALIGNMENT);
        contentPanel.add( button );
        
        if( _osName.compareTo( "Mac" ) == 0 && !_x11Exists ){
  		   
            browserLaunchListener = new 
        	      BrowserLaunchListener( _topLevel, "http://www.apple.com/downloads/macosx/apple/x11formacosx.html" );
        	button = new JButton( "Download X11" );
        	button.addActionListener( browserLaunchListener );
        	button.setAlignmentX(Component.CENTER_ALIGNMENT);
            contentPanel.add(button);
		    
        }

        pack();
   }
   
    String getExplanatoryHeader( ){
    	
       Vector<String> lineBuffer = new Vector<String>(); 
       lineBuffer.addElement( "\n" );
       lineBuffer.addElement( "The program was unable to locate Pymol on the current machine." );
	   lineBuffer.addElement( "If Pymol is installed, please select the location of the " );
	   lineBuffer.addElement( "Pymol executable in the File chooser activated by clicking on the" );
	   lineBuffer.addElement( "'Select location of Pymol Executable' button below.\n" );
	   lineBuffer.addElement( "If Pymol is not installed, then the 'Download Pymol' button will take your" );
	   lineBuffer.addElement( "browser to the Pymol download site. Also you might find the following web site" );
	   lineBuffer.addElement( "http://www.pymolwiki.org/index.php/MAC_Install useful.\n" );
	   
	   lineBuffer.addElement( "Typical locations for Pymol on " + _osName + " machines include the following:" );
	   
	   if( _osName.compareTo( "Windows" ) == 0 ){
		   
	      lineBuffer.addElement( "Windows:   C:\\Program Files\\DeLano Scientific\\PyMOL\\pymolwin.exe");
	      lineBuffer.addElement( "Windows:   C:\\Program Files (x86)\\DeLano Scientific\\PyMOL\\pymolwin.exe");
	      
	   } else if( _osName.compareTo( "Mac") == 0 ){
		   		  
		  lineBuffer.addElement( "In the Applications folder:");
	      lineBuffer.addElement( "   MacPyMOL (see note below)");
	      lineBuffer.addElement( "   PyMOLX11Hybrid\n");
	      // lineBuffer.addElement( "   MacPyMOL.app/Contents/MacOS/MacPyMOL (see note below)");
	      // lineBuffer.addElement( "   PyMOLX11Hybrid.app/Contents/MacOS/MacPyMOL\n");
	      
	      lineBuffer.addElement( "Due to an incompatibility between Tcl/Tk and the Apple Aqua graphical interface, ");
	      lineBuffer.addElement( "the Pymol view will not run under the Aqua interface. Currently the only");	      	      
	      lineBuffer.addElement( "workaround is to use the X11 graphical interface instead of Aqua. As a " );	
	      lineBuffer.addElement( "result, the 'look-and-feel' of the Pymol interface may not be what you expect.\n" );	
	      
	      if( !_x11Exists ){
	    	 lineBuffer.addElement( "Unfortunately it appears that X11 is not currently installed on this machine.\n");
	    	 lineBuffer.addElement( RemindUserToInstallX11Dialog.getExplanatoryHeader( false ) );	
	      } else {
	    	  lineBuffer.addElement( "The good news is that it appears that X11 is installed on this machine. ");
	      }
	   } else {
	      lineBuffer.addElement( "Linux:     /usr/local/bin/pymol.exe");
	   }
	   
	  StringBuffer message          = new StringBuffer( "" );
      Iterator<String> listIterator = lineBuffer.iterator();
      while( listIterator.hasNext() ){
         String line = listIterator.next();
         message.append( "   " + line + "   \n" );
      }
	   return message.toString();
	 
   }

   File getPymolLocation( ){
	  
	  setVisible(true);
	  while( !_done && _pymolLocation == null ){
		 try {
		    Thread.sleep( 1000 );
		 } catch( Exception exception ){
			 _done = true;
	     }
	  }
	  setVisible(false);
	  
      return _pymolLocation;
   }

}

class LaunchPymolFileChooser implements ActionListener {
	
	GetPyMolLocationFromUserDialog _getPyMolLocationFromUserDialog;
	String _osName;
	LaunchPymolFileChooser( GetPyMolLocationFromUserDialog getPyMolLocationFromUserDialog, String osName  ){ 
		_getPyMolLocationFromUserDialog = getPyMolLocationFromUserDialog;
		_osName = osName;
	}
	      
	public void actionPerformed( ActionEvent e ){
		JFileChooser _chooser = new JFileChooser( "Select location of Pymol Executable");
	    // PymolFileFilter filter = new PymolFileFilter( _osName );
	    //filter.addExtension("jpg");
	    //filter.addExtension("gif");
	    // filter.setDescription("JPG & GIF Images");
	    // _chooser.setFileFilter(filter);

		_chooser.setFileSelectionMode(JFileChooser.FILES_ONLY );
		int retval = _chooser.showOpenDialog( _getPyMolLocationFromUserDialog.getTopLevel() );		  
	    if( retval == JFileChooser.APPROVE_OPTION ){
	    	if( _osName.compareToIgnoreCase( "Mac" ) == 0 ){
	    		
	    	   // on Mac cannot go into Application subdirectories -- evidently 
	    	   // Java FileView does not allow it
	    	   // hence must add rest of path to actual executable
	    		
	           File macFile = _chooser.getSelectedFile();
	           if( macFile.isDirectory() ){
	        	     System.out.println( "Mac directory=<" + macFile.toString() + "> chosen." );
	        	     File executable = new File( macFile.getPath() + "/Contents/MacOS/MacPyMOL" );
	        	     if( executable.exists() ){
	        	        macFile = executable;
	        	        System.out.println( "Mac directory=<" + executable.toString() + "> exists." );
	        	     } else {
	        	    	System.out.println( "Mac directory=<" + executable.toString() + "> does not exist." );
	        	     }
	           }
	           _getPyMolLocationFromUserDialog.setPymolLocation( macFile );
	    	} else {
	    	   _getPyMolLocationFromUserDialog.setPymolLocation( _chooser.getSelectedFile() );
	    	}
	    } else {
	    	_getPyMolLocationFromUserDialog.setIsDone( true );
	    }      
	}
}

// class used to get Pymol location from user

class PymolFileFilter extends FileFilter {
    
   String _osName;
   
   public PymolFileFilter( String osName ){              
      _osName = osName;        
   }
    
   public boolean accept( File file ){
	  
	   if(file.isDirectory() || file.getName().compareToIgnoreCase( "pymol.exe" ) == 0 ){
		   return true;
	   }
	   if( _osName != null ){   
		   if( _osName.compareToIgnoreCase( "Mac" ) == 0 ){
		      if( file.getName().compareToIgnoreCase( "MacPyMOL" ) == 0 ){
		    	  return true;
		      }
		   }
	   }
	   return false;
   }
   public String getDescription( ){
	   return new String( "pymol.exe" ); 
   }
}

// class used to get Pymol location from user

@SuppressWarnings("serial") class RemindUserToInstallX11Dialog extends JFrame implements ActionListener {
    
   java.awt.Component _topLevel;
   String _osName;
   boolean _x11Exists;
   boolean _done;
    
   public RemindUserToInstallX11Dialog( java.awt.Component inputTopLevel, String osName ){
        
      _topLevel      = inputTopLevel;        
      _osName        = osName;
      _x11Exists     = true;
      _done          = false;
        
      initializeDialog();
   }
    
   java.awt.Component getTopLevel( ){ return _topLevel; }
    
   void initializeDialog( ){
    	
      setTitle( "X11 installation");
      
      if( _osName.compareTo( "Mac" ) == 0 ){
          if( GetPymolLocation.isX11Installed( _osName ) == 1 ){
		       _x11Exists = true;
          } else {
		       _x11Exists = false;
          }
       }

      JPanel contentPanel = new JPanel();
      contentPanel.setLayout( new BoxLayout(contentPanel, BoxLayout.Y_AXIS));
      setContentPane( contentPanel );
        
      contentPanel.add(Box.createRigidArea(new Dimension(0,5)));
      JTextArea label = new JTextArea(getExplanatoryHeader( true ));
      label.setAlignmentX(Component.CENTER_ALIGNMENT);
      contentPanel.add(label);
        
      contentPanel.add(Box.createRigidArea(new Dimension(0,8)));
      contentPanel.add(new JSeparator());
      contentPanel.add(Box.createRigidArea(new Dimension(0,8)));

      if( _osName.compareTo( "Mac" ) == 0 ){
        	
		   if( !_x11Exists ){
        	   BrowserLaunchListener browserLaunchListener = new 
        	      BrowserLaunchListener( _topLevel, "http://www.apple.com/downloads/macosx/apple/x11formacosx.html" );
        	   JButton button = new JButton( "Download X11" );
        	   button.addActionListener( browserLaunchListener );
        	   button.setAlignmentX(Component.CENTER_ALIGNMENT);
               contentPanel.add(button);
         } else {
            return;
         }
      }
        
      JButton button = new JButton( "Ok" );
      button.setAlignmentX(Component.CENTER_ALIGNMENT);
      button.addActionListener( this );
      contentPanel.add(button);

      pack();
      _done = false;
   }
   
   static String getExplanatoryHeader( boolean includePreface  ){
    	
      Vector<String> lineBuffer = new Vector<String>(); 
      if( includePreface ){
	     lineBuffer.addElement( "The program did not find the X11 software in the Applications/Utilities folder." );
	     lineBuffer.addElement( "Due to an incompatibility between Tcl/Tk and the Apple Aqua graphical interface, ");
	     lineBuffer.addElement( "the Pymol view will not run under the Aqua interface. Currently the only");
	     lineBuffer.addElement( "workaround is to use the X11 graphical interface instead of Aqua." );
	     lineBuffer.addElement( "The downside to this workaround is that X11 must be installed.\n" );	
      }
	  lineBuffer.addElement( "For older Macs, the 'Download X11' button at the bottom of this dialog" );	
	  lineBuffer.addElement( "will take your browser to the Apple X11 download page which has" );
	  lineBuffer.addElement( "instructions for installing X11.\n" );
      lineBuffer.addElement( "For newer Macs if you use the download version from the Mac website, " );
      lineBuffer.addElement( "then during the installation of X11, you may get a message stating:\n");
	  lineBuffer.addElement( "'You cannot install X11 on this volume. Newer Software already exists" );
	  lineBuffer.addElement( "on your computer'.\n" );
	  lineBuffer.addElement( "In this case, you can install X11 from the original installation disk" );
	  lineBuffer.addElement( "(the X11 on the Apple web site is an old version that was made" );
      lineBuffer.addElement( "available because X11 didn't originally come on the Mac OS install disks). " );
      lineBuffer.addElement( " " );
      lineBuffer.addElement( "After placing the OS install disk into the CD/DVD drive, " );
      lineBuffer.addElement( "scroll down the main directory until you see the package icon with" );
      lineBuffer.addElement( "the filename 'Optional Installs' (Don't run the Install Mac :OS X icon.)." );
      lineBuffer.addElement( "Double-click on 'Optional Installs' and go through the first few screens. " );
      lineBuffer.addElement( "Choose your boot hard drive. When it gives you a list of Package Names, " );
      lineBuffer.addElement( "click the expand triangle next to Applications. Then check 'X11' and click install." );
      lineBuffer.addElement( " " );
      lineBuffer.addElement( "After installing X11, you can reclick the '3D Pymol View' button in the" );
      lineBuffer.addElement( "'Ion Counts' dialog to launch Pymol" );
      

      // format for dialog
      
	   StringBuffer message          = new StringBuffer( "" );
      Iterator<String> listIterator = lineBuffer.iterator();
      while( listIterator.hasNext() ){
         String line = listIterator.next();
         message.append( "   " + line + "   \n" );
      }
	   return message.toString();
   }
   
   boolean getIsDone( ){
		  
      setVisible(true);
	  while( !_done ){
			 try {
			    Thread.sleep( 1000 );
			 } catch( Exception exception ){
				 _done = true;
		     }
		  }
		  setVisible(false);
		  
	      return true;
	   
   }


	public void actionPerformed( ActionEvent e ){
      _done = true;
      return;
	}

}
