/** *######################################################################### * * A component of the Gatherer application, part of the Greenstone digital * library suite from the New Zealand Digital Library Project at the * University of Waikato, New Zealand. * * Author: John Thompson, Greenstone Digital Library, University of Waikato * * Copyright (C) 1999 New Zealand Digital Library Project * * This program 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 of the License, or * (at your option) any later version. * * This program 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 this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. *######################################################################## */ package org.greenstone.gatherer.cdm; import java.awt.*; import java.awt.event.*; import java.io.*; import java.net.*; import java.util.*; import javax.swing.*; import javax.swing.event.*; import javax.swing.plaf.*; import javax.swing.plaf.basic.*; import org.apache.xerces.parsers.*; import org.greenstone.gatherer.Configuration; import org.greenstone.gatherer.DebugStream; import org.greenstone.gatherer.Dictionary; import org.greenstone.gatherer.Gatherer; import org.greenstone.gatherer.collection.CollectionContentsChangedListener; import org.greenstone.gatherer.gui.GComboBox; import org.greenstone.gatherer.gui.GLIButton; import org.greenstone.gatherer.gui.ModalDialog; import org.greenstone.gatherer.gui.WarningDialog; import org.greenstone.gatherer.util.StaticStrings; import org.greenstone.gatherer.util.Utility; import org.greenstone.gatherer.util.XMLTools; import org.w3c.dom.*; import org.xml.sax.*; /** This class is for maintaining a list of known plug-ins, and importing new plugins using the parser. */ public class PluginManager extends DOMProxyListModel implements CollectionContentsChangedListener { /** The library 'reserve' of base plugins. */ private ArrayList library = null; /** When asking how many rows are in the model, and if this variables value is true, then this modifier alters the number returned. This funtionality is used to hide the last three rows of the list in low detail modes. */ private boolean modify_row_count = false; /** The controls for editing the contents of this manager. */ private Control controls = null; private DOMProxyListModel model; private JPanel separator; private Plugin separator_plugin; /** Constructor. */ public PluginManager() { super(CollectionDesignManager.collect_config.getDocumentElement(), CollectionConfiguration.PLUGIN_ELEMENT, new Plugin()); DebugStream.println("PluginManager: " + super.getSize() + " plugins parsed."); model = this; // Reload/Create the library loadPlugins(); // adds all the plugins to the library savePlugins(); // Create the separator, cause we can reuse it. separator = getSeparator(); // Listen for CollectionContentsChanged events, so we can give plugin hints when new files are added Gatherer.c_man.addCollectionContentsChangedListener(this); } /** Method to add a new plugin to the library * @param plugin the new base Plugin */ private void addPlugin(Plugin plugin) { if(!library.contains(plugin)) { library.add(plugin); } } /** Method to assign a plugin * @param plugin the Plugin to assign */ private void assignPlugin(Plugin plugin) { if(plugin.getName().equals(StaticStrings.RECPLUG_STR) || plugin.getName().equals(StaticStrings.ARCPLUG_STR)) { addAfter(plugin, separator_plugin); // Adds after separator } else { addBefore(plugin, separator_plugin); } Gatherer.c_man.configurationChanged(); } public static boolean clearPluginCache() { DebugStream.println("deleting plugins.dat"); File plugin_file = new File(Utility.getGLIUserFolder(), "plugins.dat"); if (plugin_file.exists()) { return Utility.delete(plugin_file); } return true; } /** Destructor. */ public void destroy() { Gatherer.c_man.removeCollectionContentsChangedListener(this); if (controls != null) { controls.destroy(); controls = null; } library.clear(); library = null; } /** This function listens for new files being added to the collection and hints about suitable plugins. */ public void fileAddedToCollection(File file) { // First check the plugins already assigned in the collection for (int i = 0; i < super.getSize(); i++) { Plugin assigned_plugin = (Plugin) getElementAt(i); if (assigned_plugin.isSeparator() == false && assigned_plugin.doesProcessFile(file) == true) { // This file will be processed by an assigned plugin, so no suggestion is necessary System.err.println("Processed by assigned plugin: " + assigned_plugin); // System.err.println("Explodes metadata databases: " + assigned_plugin.doesExplodeMetadataDatabases()); return; } } // Next try the plugins NOT already assigned in the collection ArrayList suitable_plugins = new ArrayList(); Object[] unassigned_plugins = getAvailable(); for (int i = 0; i < unassigned_plugins.length; i++) { Plugin unassigned_plugin = (Plugin) unassigned_plugins[i]; if (unassigned_plugin.doesProcessFile(file) == true) { System.err.println("Processed by unassigned plugin: " + unassigned_plugin); suitable_plugins.add(unassigned_plugin); } } // If there appear to be no suitable plugins, warn the user about this and be done if (suitable_plugins.size() == 0) { String[] args = new String[1]; args[0] = file.getName(); WarningDialog warning_dialog = new WarningDialog("warning.NoPluginExpectedToProcessFile", args, null, false); warning_dialog.display(); warning_dialog.dispose(); return; } // Generate a dialog new PluginSuggestionPrompt(file.getName(), suitable_plugins); } public boolean isFileExplodable(File file) { // Temporary hack to test the rest of this, the correct code is below if (file.isFile() && file.getName().endsWith(".mst")) { return true; } // for (int i = 0; i < library.getSize(); i++) { // Plugin plugin = (Plugin) library.get(i); // if (plugin.doesProcessFile(file) == true && plugin.doesExplodeMetadataDatabases() == true) { // return true; // } // } return false; } /** Method to retrieve the control for this manager. * @return the Control */ public Control getControls() { if(controls == null) { // Build controls controls = new PluginControl(); } return controls; } /** Retrieve the base pluging of the given name, or null if no such plugin. * @param name the name of the base plugin to retrieve as a String * @return the Plugin requested or null if no such plugin */ public Plugin getBasePlugin(String name) { int library_size = library.size(); for(int i = 0; i < library_size; i++) { Plugin plugin = (Plugin) library.get(i); if(plugin.getName().equals(name)) { return plugin; } } // No success. return null; } /** Overrides getSize in DOMProxyListModel to take into account the row count modifier used to hide the last three rows in lower detail modes * @return an int indicating the number of rows in the model, or more correctly the desired number of rows to display */ public int getSize() { int result = super.getSize(); if(modify_row_count) { result = result-3; } return result; } /** Called when the detail mode has changed which in turn may cause several design elements to be available/hidden * @param mode the new mode as an int */ public void modeChanged(int mode) { if(controls != null) { ((PluginControl)controls).modeChanged(mode); } } /** Method to move a plugin in the list order. * @param plugin the Plugin you want to move. * @param direction true to move the plugin up, false to move it down. * @param all true to move to move all the way, false for a single step. */ // why are all the error notices there when the buttons are disabled is you cant move??? private void movePlugin(Plugin plugin, boolean direction, boolean all) { // Can't ever move RecPlug or ArcPlug if(super.getSize() < 4) { //DebugStream.println("Not enough plugins to allow moving."); return; } if(plugin.getName().equals(StaticStrings.ARCPLUG_STR) || plugin.getName().equals(StaticStrings.RECPLUG_STR)) { JOptionPane.showMessageDialog(Gatherer.g_man, Dictionary.get("CDM.Move.Fixed"), Dictionary.get("CDM.Move.Title"), JOptionPane.ERROR_MESSAGE); return; } if(all) { // Move to top if(direction) { // Remove the moving plugin remove(plugin); // Retrieve the first plugin Plugin first_plugin = (Plugin) getElementAt(0); // Add the moving plugin before the first plugin addBefore(plugin, first_plugin); first_plugin = null; Gatherer.c_man.configurationChanged(); } else { // Remove the moving plugin remove(plugin); // Add the moving plugin before the separator addBefore(plugin, separator_plugin); Gatherer.c_man.configurationChanged(); } } else { // Try to move the plugin one step in the desired direction. int index = indexOf(plugin); ///ystem.err.println("Index of " + plugin + " = " + index); if(direction) { index--; if(index < 0) { String args[] = new String[2]; args[0] = Dictionary.get("CDM.PlugInManager.PlugIn_Str"); args[1] = plugin.getName(); JOptionPane.showMessageDialog(Gatherer.g_man, Dictionary.get("CDM.Move.At_Top", args), Dictionary.get("CDM.Move.Title"), JOptionPane.ERROR_MESSAGE); return; } remove(plugin); add(index, plugin); Gatherer.c_man.configurationChanged(); } else { index++; Plugin next_plugin = (Plugin) getElementAt(index); if(next_plugin.isSeparator()) { String args[] = new String[1]; args[0] = plugin.getName(); JOptionPane.showMessageDialog(Gatherer.g_man, Dictionary.get("CDM.Move.Cannot", args), Dictionary.get("CDM.Move.Title"), JOptionPane.ERROR_MESSAGE); // Still not going to move RecPlug or ArcPlug. return; } remove(plugin); add(index, plugin); Gatherer.c_man.configurationChanged(); } } } /** We attempt to place the separator between the unfixed and the fixed plugins. Since we only know of two fixed plugins, we search for either of them, and place the separator before them. */ public void placeSeparator() { ///ystem.err.println("Placing separator."); int separator_index = super.getSize(); if(separator_index > 0) { boolean found_fixed = false; int index = separator_index - 1; while(index > 0) { Plugin plugin = (Plugin) getElementAt(index); String name = plugin.getName(); if(name.equals(StaticStrings.RECPLUG_STR) || name.equals(StaticStrings.ARCPLUG_STR)) { found_fixed = true; index--; } else { if(found_fixed) { separator_index = index + 1; index = -1; } else { index--; } } name = null; plugin = null; } } Element element = CollectionDesignManager.collect_config.document.createElement(CollectionConfiguration.PLUGIN_ELEMENT); element.setAttribute(CollectionConfiguration.TYPE_ATTRIBUTE, CollectionConfiguration.SEPARATOR_ATTRIBUTE); element.setAttribute(CollectionConfiguration.SEPARATOR_ATTRIBUTE, CollectionConfiguration.TRUE_STR); separator_plugin = new Plugin(element, null); ///atherer.println("Adding plugin separator at: " + separator_index); add(separator_index, separator_plugin); } /** This method removes an assigned plugin. I was tempted to call it unassign, but remove is more consistant. Note that there is no way to remove a plugin from the library. * @param plugin The Plugin to remove. */ private void removePlugin(Plugin plugin) { remove(plugin); Gatherer.c_man.configurationChanged(); } /** Method to cache the current contents of library (known plugins) to file. */ private void savePlugins() { try { File plugins_dat_file = new File(Utility.getGLIUserFolder(), "plugins.dat"); FileOutputStream file = new FileOutputStream(plugins_dat_file); ObjectOutputStream out = new ObjectOutputStream(file); out.writeObject(library); out.close(); } catch (Exception error) { DebugStream.printStackTrace(error); } } /** Inform the model to hide/show the last three lines on the list. * @param modify_row_count true to hide the last three lines, false otherwise */ private void setHideLines(boolean modify_row_count) { this.modify_row_count = modify_row_count; int original_size = super.getSize(); if(modify_row_count) { fireIntervalRemoved(this, original_size - 4, original_size - 1); } else { fireIntervalAdded(this, original_size - 4, original_size - 1); } } /** Determine the current separator index. */ private int findSeparatorIndex() { int separator_index = super.getSize() - 1; while(separator_index >= 0) { Plugin search = (Plugin) getElementAt(separator_index); if(search.isSeparator()) { return separator_index; } separator_index--; } return separator_index; } /** Retrieve a list of those plugins that are in library but not in the assigned plugins. */ private Object[] getAvailable() { ArrayList available = new ArrayList(); int library_size = library.size(); for(int i = 0; i < library_size; i++) { Plugin plugin = (Plugin) library.get(i); if(!plugin.isAbstract()) { available.add(plugin); } plugin = null; } // Now go through the assigned plugins, and remove any that match. available.removeAll(children()); //DebugStream.println("There are a total of " + library.size() + " plugins in the library."); //DebugStream.println("However " + children().size() + " are in use,"); //DebugStream.println("So only " + available.size() + " remain."); Collections.sort(available); return available.toArray(); } /** Method to extract just the plugins name from a file object. * @param plugin The File which references a certain plugin. * @return A String containing just the plugins name, without extension. */ private String getPluginName(String filename) { String name = filename; if(name.indexOf(".") != -1) { name = name.substring(0, name.indexOf(".")); } return name; } /** Method to load the details of a single plug-in. * @param plugin The plugin File you wish to load. */ private void loadPlugin(String plugin, String lang) { Document document = null; InputStream input_stream = null; // Run pluginfo on this plugin, and then send the results for parsing. try { if (Gatherer.isGsdlRemote) { String launch = Gatherer.cgiBase + "launch"; launch += "?cmd=pluginfo.pl"; launch += "&xml=&language="+lang; launch += "&plug=" + getPluginName(plugin); System.err.println("*** launch = " + launch); URL launch_url = new URL(launch); URLConnection launch_connection = launch_url.openConnection(); input_stream = launch_connection.getInputStream(); } else { String args[] = null; if(Utility.isWindows()) { args = new String[6]; if(Configuration.perl_path != null) { args[0] = Configuration.perl_path; } else { args[0] = "Perl.exe"; } args[1] = Configuration.gsdl_path + "bin" + File.separator + "script" + File.separator + "pluginfo.pl"; args[2] = "-xml"; args[3] = "-language"; args[4] = lang; args[5] = getPluginName(plugin); } else { args = new String[5]; args[0] = "pluginfo.pl"; args[1] = "-xml"; args[2] = "-language"; args[3] = lang; args[4] = getPluginName(plugin); } // Create the process. Runtime runtime = Runtime.getRuntime(); Process process = runtime.exec(args); input_stream = process.getErrorStream(); } StringBuffer xml = Utility.readXMLStream(input_stream); document = CollectionDesignManager.XMLStringToDOM(xml,plugin); } catch (Exception error) { System.err.println("Failed when trying to parse: " + plugin); error.printStackTrace(); } if(document != null) { parseXML(document.getDocumentElement()); } } /** Method to initially load information from the standard plug-ins within the gsdl Perl library. */ private void loadPlugins() { // Attempt to restore the cached file. File plugins_dat_file = new File(Utility.getGLIUserFolder(), "plugins.dat"); try { FileInputStream file = new FileInputStream(plugins_dat_file); ObjectInputStream input = new ObjectInputStream(file); library = (ArrayList) input.readObject(); } catch (Exception error) { DebugStream.println("Unable to open " + plugins_dat_file); } if(library == null) { library = new ArrayList(); if (Gatherer.isGsdlRemote) { String lang = Configuration.getLanguage(); String launch = Gatherer.cgiBase + "launch"; launch += "?cmd=pluginfo.pl"; launch += "&xml=&language="+lang; launch += "&listall="; System.err.println("*** launch = " + launch); try { URL launch_url = new URL(launch); URLConnection launch_connection = launch_url.openConnection(); InputStream input_stream = launch_connection.getInputStream(); loadPlugins(input_stream); } catch (Exception error) { System.err.println("Failed when trying to connect to : " + launch); error.printStackTrace(); } } else { // Retrieve the gsdl home directory... String directory = Configuration.gsdl_path; directory = directory + "perllib" + File.separator + "plugins" + File.separator; loadPlugins(new File(directory)); } } } /** Method to load plug-in information from a specified input stream (could be local or through URL). Of course no plug-ins may be found at this location. * @param input_stream An InputStream indicating the where list of plugins -- encoded in XML -- can be read from */ private void loadPlugins(InputStream input_stream) { StringBuffer xml = Utility.readXMLStream(input_stream); Document document = CollectionDesignManager.XMLStringToDOM(xml, "-listall"); // Parse XML to build up list of plugin names Node root = document.getDocumentElement(); NamedNodeMap attributes = root.getAttributes(); Node length_node = attributes.getNamedItem("length"); String num_plugins_str = length_node.getNodeValue(); int num_plugins = Integer.parseInt(num_plugins_str); String plugin_list[] = new String[num_plugins]; Node node = root.getFirstChild(); int i = 0; while (node != null) { String node_name = node.getNodeName(); if (node_name.equalsIgnoreCase("PluginName")) { String name = XMLTools.getValue(node); plugin_list[i] = name; i++; } node = node.getNextSibling(); } boolean is_windows = Utility.isWindows(); boolean is_mac = Utility.isMac(); String current_lang = Configuration.getLanguage(); if (num_plugins>0) { // Create a progress indicator. ParsingProgress progress = new ParsingProgress(Dictionary.get("CDM.PlugInManager.Parsing.Title"), Dictionary.get("CDM.PlugInManager.Parsing.Message"), num_plugins); for (i=0; iFile indicating the directory to be scanned for plug-ins. */ private void loadPlugins(File directory) { File files[] = directory.listFiles(); boolean is_windows = Utility.isWindows(); boolean is_mac = Utility.isMac(); String current_lang = Configuration.getLanguage(); if(files != null) { // Create a progress indicator. ParsingProgress progress = new ParsingProgress(Dictionary.get("CDM.PlugInManager.Parsing.Title"), Dictionary.get("CDM.PlugInManager.Parsing.Message"), files.length); for(int i = 0; i < files.length; i++) { // We only want to check Perl Modules. if(files[i].getName().endsWith(".pm")) { if (files[i].getName().equals("GMLPlug.pm") || ((is_windows || is_mac) && files[i].getName().equals("DBPlug.pm"))) { // don't load GMLPlug or DBPlug for windows } else { loadPlugin(files[i].getName(), current_lang); } } progress.inc(); } progress.dispose(); progress.destroy(); progress = null; } } private Plugin parseXML(Node root) { Plugin plugin = new Plugin(); String node_name = null; for (Node node = root.getFirstChild(); node != null; node = node.getNextSibling()) { node_name = node.getNodeName(); if(node_name.equalsIgnoreCase("Name")) { String name = XMLTools.getValue(node); // We can save ourselves some processing time if a plugin with this name already exists in our manager. If so retrieve it and return it. Plugin existing = getBasePlugin(name); if(existing != null) { return existing; } plugin.setName(name); } else if (node_name.equalsIgnoreCase("Desc")) { plugin.setDescription(XMLTools.getValue(node)); } else if (node_name.equalsIgnoreCase("Abstract")) { plugin.setIsAbstract(XMLTools.getValue(node).equalsIgnoreCase(StaticStrings.YES_STR)); } else if (node_name.equalsIgnoreCase("Explodes")) { plugin.setDoesExplodeMetadataDatabases(XMLTools.getValue(node).equalsIgnoreCase(StaticStrings.YES_STR)); System.err.println("Plugin " + plugin.getName() + " explodes metadata databases: " + plugin.doesExplodeMetadataDatabases()); } // Parse the multitude of arguments else if(node_name.equalsIgnoreCase("Arguments")) { for(Node arg = node.getFirstChild(); arg != null; arg = arg.getNextSibling()) { node_name = arg.getNodeName(); // An option. if(node_name.equalsIgnoreCase("Option")) { Argument argument = new Argument(); // If its an option we parse the multitude of details an options might have. for(Node det = arg.getFirstChild(); det != null; det = det.getNextSibling()) { node_name = det.getNodeName(); if(node_name.equalsIgnoreCase("Name")) { argument.setName(XMLTools.getValue(det)); } else if(node_name.equalsIgnoreCase("Desc")) { argument.setDescription(XMLTools.getValue(det)); } else if(node_name.equalsIgnoreCase("Type")) { argument.setType(XMLTools.getValue(det)); } else if(node_name.equalsIgnoreCase("Default")) { argument.setDefaultValue(XMLTools.getValue(det)); } else if(node_name.equalsIgnoreCase("List")) { // Two final loops are required to parse lists. for(Node value = det.getFirstChild(); value != null; value = value.getNextSibling()) { if(value.getNodeName().equalsIgnoreCase("Value")) { String key = null; String desc = ""; for(Node subvalue = value.getFirstChild(); subvalue != null; subvalue = subvalue.getNextSibling()) { node_name = subvalue.getNodeName(); if(node_name.equalsIgnoreCase("Name")) { key = XMLTools.getValue(subvalue); } else if(node_name.equalsIgnoreCase("Desc")) { desc = XMLTools.getValue(subvalue); } } if(key != null) { argument.addOption(key, desc); } } } } else if(node_name.equalsIgnoreCase("Required")) { String v = XMLTools.getValue(det); if(v != null && v.equalsIgnoreCase("yes")) { argument.setRequired(true); } } else if(node_name.equals(StaticStrings.RANGE_ELEMENT)) { String range_raw = XMLTools.getValue(det); int index = -1; if((index = range_raw.indexOf(StaticStrings.COMMA_CHARACTER)) != -1) { if(index > 0) { try { String first_number = range_raw.substring(0, index); argument.setMinimum(Integer.parseInt(first_number)); first_number = null; } catch(Exception exception) { } } if(index + 1 < range_raw.length()) { try { String second_number = range_raw.substring(index + 1); argument.setMaximum(Integer.parseInt(second_number)); second_number = null; } catch(Exception exception) { } } } // Else it wasn't a valid range anyway, so ignore it } } plugin.addArgument(argument); } // A super plugin class. else if(node_name.equalsIgnoreCase("PlugInfo")) { Plugin super_plugin = parseXML(arg); plugin.setSuper(super_plugin); } } } } if(plugin.getName() != null) { addPlugin(plugin); return plugin; } return null; } /** A class which provodes controls for assigned and editing plugins. */ private class PluginControl extends JPanel implements Control { /** Button for adding plugins. */ private JButton add = null; /** Button for configuring the selected plugin. */ private JButton configure = null; /** Buttom to move an assinged plugin as low in the order as possible. */ //private JButton move_bottom_button = null; /** Button to move an assigned plugin one position lower in the order. */ private JButton move_down_button = null; /** Button to move an assigned plugin as high in the order as possible. */ //private JButton move_top_button = null; /** Button to move an assigned plugin one position higher in the order. */ private JButton move_up_button = null; /** Button to remove the selected plugin. */ private JButton remove = null; /** A combobox containing all of the known plugins, including those that may have already been assigned. */ private GComboBox plugin = null; /** The label next to the plugin combobox. */ private JLabel plugin_label = null; /** The label above the assigned plugin list. */ private JLabel plugin_list_label = null; /** The title of this view. */ private JLabel title = null; /** A list of assigned plugins. */ private JList plugin_list = null; /** The area where the add, configure and remove buttons are placed. */ private JPanel button_pane = null; /** The region which divides the central portion of the view into list and controls */ private JPanel central_pane = null; /** The area where title label and instructions sit. */ private JPanel header_pane = null; /** The area where movement buttons are placed. */ private JPanel movement_pane = null; /** The small region containing the plugin combobox and its label. */ private JPanel plugin_pane = null; /** The pane containing the assigned plugin list and its label. */ private JPanel plugin_list_pane = null; /** The text area containing instructions on the use of this control. */ private JTextArea instructions = null; /** Constructor. */ public PluginControl() { // Create add = new GLIButton(); add.setMnemonic(KeyEvent.VK_A); Dictionary.registerBoth(add, "CDM.PlugInManager.Add", "CDM.PlugInManager.Add_Tooltip"); button_pane = new JPanel(); central_pane = new JPanel(); configure = new GLIButton(); configure.setEnabled(false); configure.setMnemonic(KeyEvent.VK_C); Dictionary.registerBoth(configure, "CDM.PlugInManager.Configure", "CDM.PlugInManager.Configure_Tooltip"); header_pane = new JPanel(); instructions = new JTextArea(); instructions.setBackground(Configuration.getColor("coloring.collection_tree_background", false)); instructions.setEditable(false); instructions.setLineWrap(true); instructions.setRows(6); instructions.setWrapStyleWord(true); Dictionary.registerText(instructions, "CDM.PlugInManager.Instructions"); move_up_button = new JButton("", Utility.getImage("arrow-up.gif")); move_up_button.setEnabled(false); move_up_button.setMnemonic(KeyEvent.VK_U); //move_up_button.setPreferredSize(Utility.DOUBLE_IMAGE_BUTTON_SIZE); Dictionary.registerBoth(move_up_button, "CDM.Move.Move_Up", "CDM.Move.Move_Up_Tooltip"); move_down_button = new JButton("", Utility.getImage("arrow-down.gif")); move_down_button.setEnabled(false); move_down_button.setMnemonic(KeyEvent.VK_D); //move_down_button.setPreferredSize(Utility.DOUBLE_IMAGE_BUTTON_SIZE); Dictionary.registerBoth(move_down_button, "CDM.Move.Move_Down", "CDM.Move.Move_Down_Tooltip"); movement_pane = new JPanel(); PluginComboboxListener picl = new PluginComboboxListener(); plugin = new GComboBox(getAvailable()); plugin.setBackgroundNonSelectionColor(Configuration.getColor("coloring.editable_background", false)); plugin.setBackgroundSelectionColor(Configuration.getColor("coloring.collection_selection_background", false)); plugin.setEditable(true); plugin.setTextNonSelectionColor(Configuration.getColor("coloring.workspace_tree_foreground", false)); plugin.setTextSelectionColor(Configuration.getColor("coloring.collection_selection_foreground", false)); picl.itemStateChanged(new ItemEvent(plugin, 0, null, ItemEvent.SELECTED)); plugin_label = new JLabel(); Dictionary.registerText(plugin_label, "CDM.PlugInManager.PlugIn"); plugin_list = new JList(model); plugin_list.setCellRenderer(new ListRenderer()); plugin_list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); plugin_list_label = new JLabel(); plugin_list_label.setHorizontalAlignment(JLabel.CENTER); plugin_list_label.setOpaque(true); Dictionary.registerText(plugin_list_label, "CDM.PlugInManager.Assigned"); plugin_list_pane = new JPanel(); plugin_pane = new JPanel(); remove = new GLIButton(); remove.setEnabled(false); remove.setMnemonic(KeyEvent.VK_R); Dictionary.registerBoth(remove, "CDM.PlugInManager.Remove", "CDM.PlugInManager.Remove_Tooltip"); title = new JLabel(); title.setHorizontalAlignment(JLabel.CENTER); title.setOpaque(true); Dictionary.registerText(title, "CDM.PlugInManager.Title"); // Listeners add.addActionListener(new AddListener()); configure.addActionListener(new ConfigureListener()); MoveListener ml = new MoveListener(); //move_bottom_button.addActionListener(ml); move_down_button.addActionListener(ml); //move_top_button.addActionListener(ml); move_up_button.addActionListener(ml); plugin.addItemListener(picl); remove.addActionListener(new RemoveListener()); plugin_list.addMouseListener(new ClickListener()); plugin_list.addListSelectionListener(new ListListener()); picl = null; // Layout title.setBorder(BorderFactory.createEmptyBorder(0,0,2,0)); instructions.setBorder(BorderFactory.createEmptyBorder(2,5,2,5)); header_pane.setLayout(new BorderLayout()); header_pane.add(title, BorderLayout.NORTH); header_pane.add(new JScrollPane(instructions), BorderLayout.CENTER); plugin_list_label.setBorder(BorderFactory.createEmptyBorder(0,2,0,2)); movement_pane.setBorder(BorderFactory.createEmptyBorder(0,2,0,0)); movement_pane.setLayout(new GridLayout(4,1)); movement_pane.add(move_up_button); movement_pane.add(new JPanel()); movement_pane.add(new JPanel()); movement_pane.add(move_down_button); plugin_list_pane.setLayout(new BorderLayout()); plugin_list_pane.add(plugin_list_label, BorderLayout.NORTH); plugin_list_pane.add(new JScrollPane(plugin_list), BorderLayout.CENTER); modeChanged(Configuration.getMode()); // Whether the movement buttons are visible is mode dependant plugin_label.setBorder(BorderFactory.createEmptyBorder(0,0,5,0)); plugin_pane.setBorder(BorderFactory.createEmptyBorder(5,0,5,0)); plugin_pane.setLayout(new BorderLayout(5,0)); plugin_pane.add(plugin_label, BorderLayout.WEST); plugin_pane.add(plugin, BorderLayout.CENTER); button_pane.setLayout(new GridLayout(1,3)); button_pane.add(add); button_pane.add(configure); button_pane.add(remove); // Scope these mad bordering skillz. // !! TO DO: Dictionary registration !! JPanel temp = new JPanel(new BorderLayout()); temp.setBorder (BorderFactory.createCompoundBorder (BorderFactory.createEmptyBorder(5,0,5,0), BorderFactory.createCompoundBorder (BorderFactory.createTitledBorder(Dictionary.get("CDM.PlugInManager.Controls")), BorderFactory.createEmptyBorder(2,2,2,2)))); temp.add(plugin_pane, BorderLayout.NORTH); temp.add(button_pane, BorderLayout.SOUTH); central_pane.setLayout(new BorderLayout()); central_pane.add(plugin_list_pane, BorderLayout.CENTER); central_pane.add(temp, BorderLayout.SOUTH); setBorder(BorderFactory.createEmptyBorder(5,5,5,5)); setLayout(new BorderLayout()); add(header_pane, BorderLayout.NORTH); add(central_pane, BorderLayout.CENTER); } /** Method which acts like a destructor, tidying up references to persistant objects. */ public void destroy() { } /** This method is overridden to ensure the instructions are scrolled to top, before the super classes updateUI() is called. */ public void gainFocus() { if(instructions != null) { instructions.setCaretPosition(0); } super.updateUI(); } public void loseFocus() { } /** The current detail mode controls two aspects of plugin manager: whether the movement buttons are visible and whether the fixed position plugins Arc and RecPlug are in the list * @param mode the current mode as an int, which can be matched against static ints in the Configuration class */ public void modeChanged(int mode) { // First of all we clear the current selection, as there can be some serious problems if the user selects the plugins we're hiding, or had the last plugin selected before we unhid the last three plugin_list.clearSelection(); // The first change is dependant on whether the user is systems mode or higher if(mode >= Configuration.SYSTEMS_MODE) { // Show movement buttons plugin_list_pane.add(movement_pane, BorderLayout.EAST); // Do we show Arc and RecPlugs or hide them and the separator line setHideLines(!(mode >= Configuration.EXPERT_MODE)); } // Otherwise hide the movement buttons and fixed plugins else { plugin_list_pane.remove(movement_pane); setHideLines(true); } plugin_list_pane.updateUI(); } /** This class listens for actions upon the add button in the controls, and if detected calls the assignPlugin() method. */ private class AddListener implements ActionListener { /** Any implementation of ActionListener must include this method so that we can be informed when an action has occured on one of our target controls. * @param event An ActionEvent containing information garnered from the control action. */ public void actionPerformed(ActionEvent event) { Object selected_object = plugin.getSelectedItem(); if(selected_object != null) { // Retrieve the base plugin if any Plugin base_plugin = getBasePlugin(selected_object.toString()); // Create a new element in the DOM Element element = CollectionDesignManager.collect_config.document.createElement(CollectionConfiguration.PLUGIN_ELEMENT); // Remember that the plugin supplied might be a custom string rather than a base plugin Plugin new_plugin = null; if(base_plugin != null) { //DebugStream.println("New Plugin based on existing Plugin"); element.setAttribute(CollectionConfiguration.TYPE_ATTRIBUTE, base_plugin.getName()); new_plugin = new Plugin(element, base_plugin); } else { //DebugStream.println("New Custom Plugin"); element.setAttribute(CollectionConfiguration.TYPE_ATTRIBUTE, selected_object.toString()); new_plugin = new Plugin(element, null); } if(!model.contains(new_plugin) || new_plugin.getName().equals(StaticStrings.UNKNOWNPLUG_STR)) { // Automatically chain to configuration. This ensures required arguments are filled out. ArgumentConfiguration ac = new ArgumentConfiguration(new_plugin); if(ac.display()) { assignPlugin(new_plugin); plugin_list.setSelectedValue(new_plugin, true); // Since we weren't cancelled, and if there was a base plugin, ensure it no longer is shown as available, unless it is the UnknownPlugin which can be added several times if(base_plugin != null && !base_plugin.getName().equals(StaticStrings.UNKNOWNPLUG_STR)) { plugin.removeItem(base_plugin); } } ac = null; new_plugin = null; plugin.setSelectedIndex(0); } else { JOptionPane.showMessageDialog(Gatherer.g_man, Dictionary.get("CDM.PlugInManager.PlugIn_Exists"), Dictionary.get("General.Error"), JOptionPane.ERROR_MESSAGE); } base_plugin = null; } } } /** Listens for double clicks apon the list and react as if the configure button was pushed. */ private class ClickListener extends MouseAdapter { /** Called whenever the mouse is clicked over a registered component, we use this to chain through to the configure prompt. * @param event A MouseEvent containing information about the mouse click. */ public void mouseClicked(MouseEvent event) { if(event.getClickCount() == 2 ) { if(!plugin_list.isSelectionEmpty()) { Plugin plugin = (Plugin) plugin_list.getSelectedValue(); if(!plugin.isSeparator()) { ArgumentConfiguration ac = new ArgumentConfiguration(plugin); if(ac.display()) { refresh(plugin); } ac.destroy(); ac = null; } } } } } /** This class listens for actions upon the configure button in the controls, and if detected creates a new ArgumentConfiguration dialog box to allow for configuration. * @see org.greenstone.gatherer.cdm.ArgumentConfiguration */ private class ConfigureListener implements ActionListener { /** Any implementation of ActionListener must include this method so that we can be informed when an action has occured on one of our target controls. * @param event An ActionEvent containing information garnered from the control action. */ public void actionPerformed(ActionEvent event) { if(!plugin_list.isSelectionEmpty()) { Plugin plugin = (Plugin) plugin_list.getSelectedValue(); if(!plugin.isSeparator()) { ArgumentConfiguration ac = new ArgumentConfiguration(plugin); if(ac.display()) { refresh(plugin); } ac.destroy(); ac = null; } } } } /** listens for changes in the list selection and enables the configure and remove buttons if there is a selection, disables them if there is no selection */ private class ListListener implements ListSelectionListener { public void valueChanged(ListSelectionEvent e) { if (!e.getValueIsAdjusting()) { // we get two events for one change in list selection - use the false one (the second one) if (plugin_list.isSelectionEmpty()) { //move_top_button.setEnabled(false); move_up_button.setEnabled(false); move_down_button.setEnabled(false); //move_bottom_button.setEnabled(false); configure.setEnabled(false); remove.setEnabled(false); } else { Plugin selected_plugin = (Plugin) plugin_list.getSelectedValue(); if(selected_plugin.isSeparator()) { //move_top_button.setEnabled(false); move_up_button.setEnabled(false); move_down_button.setEnabled(false); //move_bottom_button.setEnabled(false); configure.setEnabled(false); remove.setEnabled(false); } else { configure.setEnabled(true); String plugin_name = selected_plugin.getName(); // Some buttons are only available for plugins other than ArcPlug and RecPlug if(plugin_name.equals(StaticStrings.ARCPLUG_STR) || plugin_name.equals(StaticStrings.RECPLUG_STR) ) { //move_top_button.setEnabled(false); move_up_button.setEnabled(false); move_down_button.setEnabled(false); //move_bottom_button.setEnabled(false); remove.setEnabled(false); } else { // don't let people remove GAPlug if (plugin_name.equals(StaticStrings.GAPLUG_STR)) { remove.setEnabled(false); } else { remove.setEnabled(true); } // Move ups are only enabled if the selected plugin isn't already at the top Plugin first_plugin = (Plugin) getElementAt(0); if(!first_plugin.equals(selected_plugin)) { //move_top_button.setEnabled(true); move_up_button.setEnabled(true); } else { //move_top_button.setEnabled(false); move_up_button.setEnabled(false); } // And move downs are only allowed when the selected plugin isn't at an index one less than the separator line. int separator_index = findSeparatorIndex(); int selected_index = plugin_list.getSelectedIndex(); if(selected_index < separator_index - 1) { move_down_button.setEnabled(true); //move_bottom_button.setEnabled(true); } else { move_down_button.setEnabled(false); //move_bottom_button.setEnabled(false); } } selected_plugin = null; plugin_name = null; } } } } } /** A special list renderer which is able to render separating lines as well. */ private class ListRenderer extends DefaultListCellRenderer { /** Return a component that has been configured to display the specified value. That component's paint method is then called to "render" the cell. If it is necessary to compute the dimensions of a list because the list cells do not have a fixed size, this method is called to generate a component on which getPreferredSize can be invoked. * @param list - The JList we're painting. * @param value - The value returned by list.getModel().getElementAt(index) as an Object. * @param index - The cells index as an int. * @param isSelected - true if the specified cell was selected. * @param cellHasFocus - true if the specified cell has the focus. * @return A Component whose paint() method will render the specified value. * @see javax.swing.JList * @see javax.swing.JSeparator * @see javax.swing.ListModel * @see javax.swing.ListSelectionModel */ public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { Plugin plugin = (Plugin) value; if(plugin.isSeparator()) { return separator; } else { return super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); } } } /** Listens for actions apon the move buttons in the manager controls, and if detected calls the movePlugin() method of the manager with the appropriate details. */ private class MoveListener implements ActionListener { /** Any implementation of ActionListener must include this method so that we can be informed when an action has occured on one of our target controls. * @param event An ActionEvent containing information garnered from the control action. */ public void actionPerformed(ActionEvent event) { if (!plugin_list.isSelectionEmpty()) { Object object = plugin_list.getSelectedValue(); if (object instanceof Plugin) { Plugin plugin = (Plugin) object; //if (event.getSource() == move_top_button) { // movePlugin(plugin, true, true); //} //else if (event.getSource() == move_up_button) { movePlugin(plugin, true, false); } else if (event.getSource() == move_down_button) { movePlugin(plugin, false, false); } //else if (event.getSource() == move_bottom_button) { // movePlugin(plugin, false, true); //} plugin_list.setSelectedValue(plugin, true); } } } } /** This listener reacts to changes in the current selection of the plugin combobox. */ private class PluginComboboxListener implements ItemListener { /** When a user selects a certain plugin, update the tooltip to show the plugin description. */ public void itemStateChanged(ItemEvent event) { if(event.getStateChange() == ItemEvent.SELECTED) { // Retrieve the selected plugin Object current_selection = plugin.getSelectedItem(); // And reset the tooltip. If the plugin is null or is a string, then go back to the default message if(current_selection == null || current_selection instanceof String) { Dictionary.registerTooltip(plugin, "CDM.PlugInManager.PlugIn_Tooltip"); } else { Plugin current_plugin = (Plugin) current_selection; Dictionary.registerTooltipText(plugin, Utility.formatHTMLWidth(current_plugin.getDescription(), 40)); current_plugin = null; } current_selection = null; } } } /** This class listens for actions upon the remove button in the controls, and if detected calls the removePlugin() method. */ private class RemoveListener implements ActionListener { /** Any implementation of ActionListener must include this method so that we can be informed when an action has occured on one of our target controls. * @param event An ActionEvent containing information garnered from the control action. */ public void actionPerformed(ActionEvent event) { int selected_index = plugin_list.getSelectedIndex(); if(selected_index != -1) { Plugin selected_plugin = (Plugin) plugin_list.getSelectedValue(); removePlugin(selected_plugin); selected_plugin = null; // Select the next plugin if available if(selected_index < plugin_list.getModel().getSize()) { // If the new selection is above the separator we can remove it if(selected_index < findSeparatorIndex()) { plugin_list.setSelectedIndex(selected_index); // don't allow removal of GAPlug if (((Plugin)plugin_list.getSelectedValue()).getName().equals(StaticStrings.GAPLUG_STR)) { remove.setEnabled(false); } else { remove.setEnabled(true); } } // Otherwise select the first non-removable plugin else { plugin_list.setSelectedIndex(selected_index + 1); remove.setEnabled(false); } } else { remove.setEnabled(false); } // Refresh the available plugins plugin.setModel(new DefaultComboBoxModel(getAvailable())); } else { remove.setEnabled(false); } } } } private class PluginSuggestionPrompt extends ModalDialog implements ActionListener { private Dimension size = new Dimension(400, 200); private GComboBox suitable_plugins_combobox = null; private GLIButton add_button = null; private GLIButton ignore_button = null; public PluginSuggestionPrompt(String filename, ArrayList suitable_plugins) { super(Gatherer.g_man, true); setModal(true); setSize(size); Dictionary.setText(this, "CDM.PluginManager.SuggestedPluginListTitle"); String[] args = new String[1]; args[0] = filename; JTextArea instructions_textarea = new JTextArea(); instructions_textarea.setCaretPosition(0); instructions_textarea.setEditable(false); instructions_textarea.setLineWrap(true); instructions_textarea.setRows(5); instructions_textarea.setWrapStyleWord(true); Dictionary.setText(instructions_textarea, "CDM.PluginManager.Plugin_Suggestion_Prompt", args); JLabel suitable_plugins_label = new JLabel(); Dictionary.registerText(suitable_plugins_label, "CDM.PlugInManager.PlugIn"); suitable_plugins_label.setBorder(BorderFactory.createEmptyBorder(0,0,5,0)); suitable_plugins_combobox = new GComboBox(suitable_plugins); suitable_plugins_combobox.setBackgroundNonSelectionColor(Configuration.getColor("coloring.editable_background", false)); suitable_plugins_combobox.setBackgroundSelectionColor(Configuration.getColor("coloring.collection_selection_background", false)); suitable_plugins_combobox.setTextNonSelectionColor(Configuration.getColor("coloring.workspace_tree_foreground", false)); suitable_plugins_combobox.setTextSelectionColor(Configuration.getColor("coloring.collection_selection_foreground", false)); JPanel suitable_plugins_pane = new JPanel(); //suitable_plugins_pane.setBorder(BorderFactory.createEmptyBorder(5,0,5,0)); suitable_plugins_pane.setLayout(new BorderLayout(5,0)); suitable_plugins_pane.add(suitable_plugins_label, BorderLayout.WEST); suitable_plugins_pane.add(suitable_plugins_combobox, BorderLayout.CENTER); add_button = new GLIButton(); Dictionary.setBoth(add_button, "CDM.PlugInManager.Add", "CDM.PlugInManager.Add_Tooltip"); ignore_button = new GLIButton(); Dictionary.setBoth(ignore_button, "CDM.PlugInManager.Ignore","CDM.PlugInManager.Ignore_Tooltip" ); add_button.addActionListener(this); ignore_button.addActionListener(this); JPanel button_pane = new JPanel(); button_pane.setLayout(new GridLayout(1,2,5,0)); button_pane.add(add_button); button_pane.add(ignore_button); JPanel controls_pane = new JPanel(); controls_pane.setBorder(BorderFactory.createEmptyBorder(5,0,0,0)); controls_pane.setLayout(new GridLayout(2,1,0,5)); controls_pane.add(suitable_plugins_pane); controls_pane.add(button_pane); JPanel content_pane = (JPanel) getContentPane(); content_pane.setBorder(BorderFactory.createEmptyBorder(5,5,5,5)); content_pane.setLayout(new BorderLayout()); content_pane.add(instructions_textarea, BorderLayout.CENTER); content_pane.add(controls_pane, BorderLayout.SOUTH); // Show Dimension screen_size = Configuration.screen_size; setLocation((screen_size.width - size.width) / 2, (screen_size.height - size.height) / 2); setVisible(true); } public void actionPerformed(ActionEvent event) { if(event.getSource() == add_button) { // add the selected plugin to the list Object selected_object = suitable_plugins_combobox.getSelectedItem(); Plugin base_plugin = getBasePlugin(selected_object.toString()); // Create a new element in the DOM Element element = CollectionDesignManager.collect_config.document.createElement(CollectionConfiguration.PLUGIN_ELEMENT); // Remember that the plugin supplied might be a custom string rather than a base plugin Plugin new_plugin = null; if(base_plugin != null) { //DebugStream.println("New Plugin based on existing Plugin"); element.setAttribute(CollectionConfiguration.TYPE_ATTRIBUTE, base_plugin.getName()); new_plugin = new Plugin(element, base_plugin); } else { //DebugStream.println("New Custom Plugin"); element.setAttribute(CollectionConfiguration.TYPE_ATTRIBUTE, selected_object.toString()); new_plugin = new Plugin(element, null); } assignPlugin(new_plugin); } // else do nothing // close the dialog setVisible(false); } } /** Creates a list separator. * Found on Google Groups. Code courtesy of Paul Farwell. */ private JPanel getSeparator() { // We put the separator inside a panel to control its appearance JPanel _sepPanel = new JPanel(); _sepPanel.setOpaque(false); _sepPanel.setBorder(BorderFactory.createEmptyBorder(1, 3, 1, 3)); _sepPanel.setLayout(new BoxLayout(_sepPanel, BoxLayout.Y_AXIS)); _sepPanel.add(Box.createRigidArea(new Dimension(0, 4))); // We have to be a little careful here, as the default UI for separators under MacOS is a blank box. Instead we force a BasicUI look _sepPanel.add(new BasicSeparator()); _sepPanel.add(Box.createRigidArea(new Dimension(0, 4))); return _sepPanel; } /** This class behaves just like a normal JSeparator except that, no matter what the current settings in the UIManager are, it always paints itself with BasicSeparatorUI. */ private class BasicSeparator extends JSeparator { private ComponentUI basic_ui; public BasicSeparator() { super(); basic_ui = new BasicSeparatorUI(); } public void paintComponent(Graphics g) { if (basic_ui != null) { basic_ui.update(g, this); } } } }