From: <eg...@us...> - 2008-03-21 15:29:40
|
Revision: 10465 http://cdk.svn.sourceforge.net/cdk/?rev=10465&view=rev Author: egonw Date: 2008-03-21 08:29:37 -0700 (Fri, 21 Mar 2008) Log Message: ----------- Ported patch 9998 Modified Paths: -------------- cdk/branches/egonw-jchempaint-newtrunk/src/main/org/openscience/cdk/applications/swing/MoleculeViewer2D.java cdk/branches/egonw-jchempaint-newtrunk/src/main/org/openscience/cdk/applications/swing/MoleculeViewer2DPanel.java cdk/branches/egonw-jchempaint-newtrunk/src/main/org/openscience/cdk/controller/AbstractController2D.java cdk/branches/egonw-jchempaint-newtrunk/src/main/org/openscience/cdk/controller/Controller2D.java cdk/branches/egonw-jchempaint-newtrunk/src/main/org/openscience/cdk/geometry/GeometryTools.java cdk/branches/egonw-jchempaint-newtrunk/src/main/org/openscience/cdk/layout/AtomPlacer.java cdk/branches/egonw-jchempaint-newtrunk/src/main/org/openscience/cdk/layout/HydrogenPlacer.java cdk/branches/egonw-jchempaint-newtrunk/src/main/org/openscience/cdk/renderer/AbstractRenderer2D.java cdk/branches/egonw-jchempaint-newtrunk/src/main/org/openscience/cdk/renderer/ArrowRenderer2D.java cdk/branches/egonw-jchempaint-newtrunk/src/main/org/openscience/cdk/renderer/Renderer2D.java cdk/branches/egonw-jchempaint-newtrunk/src/main/org/openscience/cdk/renderer/SimpleRenderer2D.java cdk/branches/egonw-jchempaint-newtrunk/src/main/org/openscience/cdk/renderer/progz/SomeToolBar.java cdk/branches/egonw-jchempaint-newtrunk/src/test/org/openscience/cdk/geometry/GeometryToolsTest.java cdk/branches/egonw-jchempaint-newtrunk/src/test/org/openscience/cdk/renderer/ArrowRenderer2DTest.java cdk/branches/egonw-jchempaint-newtrunk/src/test/org/openscience/cdk/renderer/Renderer2DTest.java Added Paths: ----------- cdk/branches/egonw-jchempaint-newtrunk/src/main/org/openscience/cdk/renderer/progz/JCPPropertyHandler.java Removed Paths: ------------- cdk/branches/egonw-jchempaint-newtrunk/build-jchempaint.xml cdk/branches/egonw-jchempaint-newtrunk/src/main/org/openscience/cdk/applications/jchempaint/InsertTextPanel.java cdk/branches/egonw-jchempaint-newtrunk/src/main/org/openscience/cdk/applications/jchempaint/JCPPropertyHandler.java cdk/branches/egonw-jchempaint-newtrunk/src/main/org/openscience/cdk/applications/jchempaint/JChemPaintEditorPanel.java cdk/branches/egonw-jchempaint-newtrunk/src/main/org/openscience/cdk/applications/jchempaint/JChemPaintMenuBar.java cdk/branches/egonw-jchempaint-newtrunk/src/main/org/openscience/cdk/applications/jchempaint/JChemPaintPanel.java cdk/branches/egonw-jchempaint-newtrunk/src/main/org/openscience/cdk/applications/jchempaint/JChemPaintPopupMenu.java cdk/branches/egonw-jchempaint-newtrunk/src/main/org/openscience/cdk/applications/jchempaint/JChemPaintViewerOnlyPanel.java cdk/branches/egonw-jchempaint-newtrunk/src/main/org/openscience/cdk/applications/jchempaint/ToolBarMaker.java cdk/branches/egonw-jchempaint-newtrunk/src/main/org/openscience/cdk/applications/jchempaint/action/ cdk/branches/egonw-jchempaint-newtrunk/src/main/org/openscience/cdk/applications/jchempaint/applet/ cdk/branches/egonw-jchempaint-newtrunk/src/main/org/openscience/cdk/applications/jchempaint/application/ cdk/branches/egonw-jchempaint-newtrunk/src/main/org/openscience/cdk/applications/jchempaint/dialogs/ Deleted: cdk/branches/egonw-jchempaint-newtrunk/build-jchempaint.xml =================================================================== --- cdk/branches/egonw-jchempaint-newtrunk/build-jchempaint.xml 2008-03-21 14:50:50 UTC (rev 10464) +++ cdk/branches/egonw-jchempaint-newtrunk/build-jchempaint.xml 2008-03-21 15:29:37 UTC (rev 10465) @@ -1,158 +0,0 @@ -<project name="JCPCDK" default="dist-jcp" basedir="."> - <import file="build.xml"/> - - <target id="dist-jcp" name="dist-jcp" depends="dist-all, compile-jcp, unjar-libjars, unjar-cdkjars" - description="Builds the JChemPaint application"> - <jar jarfile="${dist}/jar/jchempaint-${jcp.version}.jar"> - <manifest> - <attribute name="Main-Class" value="org.openscience.cdk.applications.jchempaint.application.JChemPaint"/> - <section name="org/openscience/cdk/applications/jchempaint/"> - <attribute name="Specification-Title" value="JChemPaint"/> - <attribute name="Specification-Version" value="2.2"/> - <attribute name="Specification-Vendor" value="The CDK Project"/> - <attribute name="Implementation-Title" value="org.openscience.cdk.applications.jchempaint"/> - <attribute name="Implementation-Version" value="${jcp.version}"/> - <attribute name="Implementation-Vendor" value="The CDK Project"/> - </section> - </manifest> - <fileset dir="${appjars.dir}"> - <include name="**/*" /> - </fileset> - <fileset dir="${src}"> - <includesfile name="${metainf}/jchempaint.application.datafiles"/> - </fileset> - </jar> - </target> - - <target id="jcp-only" name="jcp-only" - description="Builds the JChemPaint application"> - <antcall target="compile-module"> - <param name="module" value="jchempaint"/> - <param name="source" value="${src}/main"/> - </antcall> - <antcall target="compile-module"> - <param name="module" value="jchempaint.application"/> - <param name="source" value="${src}/main"/> - </antcall> - <antcall target="compile-module"> - <param name="module" value="jchempaint.applet"/> - <param name="source" value="${src}/main"/> - </antcall> - <unjar dest="${appjars.dir}"> - <fileset dir="${dist}/jar"> - <include name="cdk-jchempaint.jar"/> - <include name="cdk-jchempaint.application.jar"/> - <include name="cdk-jchempaint.applet.jar"/> - </fileset> - </unjar> - - <!-- then zip up things --> - <jar jarfile="${dist}/jar/jchempaint-${jcp.version}.jar"> - <manifest> - <attribute name="Main-Class" value="org.openscience.cdk.applications.jchempaint.application.JChemPaint"/> - <section name="org/openscience/cdk/applications/jchempaint/"> - <attribute name="Specification-Title" value="JChemPaint"/> - <attribute name="Specification-Version" value="1.0"/> - <attribute name="Specification-Vendor" value="The CDK Project"/> - <attribute name="Implementation-Title" value="org.openscience.cdk"/> - <attribute name="Implementation-Version" value="${jcp.version}"/> - <attribute name="Implementation-Vendor" value="The CDK Project"/> - </section> - </manifest> - <fileset dir="${appjars.dir}"> - <include name="**/*" /> - </fileset> - <fileset dir="${src}"> - <includesfile name="${metainf}/jchempaint.application.datafiles"/> - </fileset> - </jar> - </target> - - <target id="unjar" name="unjar" description="unjars a lot"> - <unjar dest="${appjars.dir}"> - <fileset dir="${lib}"> - <includesfile name="${metainf}/applications.libdepends"/> - <includesfile name="${metainf}/core.libdepends"/> - <includesfile name="${metainf}/data.libdepends"/> - <includesfile name="${metainf}/experimental.libdepends"/> - <includesfile name="${metainf}/extra.libdepends"/> - <includesfile name="${metainf}/io.libdepends"/> - <includesfile name="${metainf}/libiocml.libdepends"/> - <includesfile name="${metainf}/qsar.libdepends"/> - <includesfile name="${metainf}/render.libdepends"/> - <includesfile name="${metainf}/standard.libdepends"/> - <includesfile name="${metainf}/svg.libdepends"/> - <includesfile name="${metainf}/sdg.libdepends"/> - <includesfile name="${metainf}/control.libdepends"/> - <includesfile name="${metainf}/jchempaint.libdepends"/> - </fileset> - </unjar> - </target> - - <target id="unjar-libjars" name="unjar-libjars"> - <unjar dest="${appjars.dir}"> - <fileset dir="${lib}"> - <includesfile name="${metainf}/applications.libdepends"/> - <includesfile name="${metainf}/core.libdepends"/> - <includesfile name="${metainf}/data.libdepends"/> - <includesfile name="${metainf}/experimental.libdepends"/> - <includesfile name="${metainf}/extra.libdepends"/> - <includesfile name="${metainf}/io.libdepends"/> - <includesfile name="${metainf}/libiocml.libdepends"/> - <includesfile name="${metainf}/qsar.libdepends"/> - <includesfile name="${metainf}/render.libdepends"/> - <includesfile name="${metainf}/standard.libdepends"/> - <includesfile name="${metainf}/svg.libdepends"/> - <includesfile name="${metainf}/jchempaint.libdepends"/> - </fileset> - </unjar> - </target> - - <target id="unjar-cdkjars" name="unjar-cdkjars"> - <unjar dest="${appjars.dir}"> - <fileset dir="${dist}/jar"> - <include name="cdk-applications.jar"/> - <include name="cdk-core.jar"/> - <include name="cdk-data.jar"/> - <include name="cdk-experimental.jar"/> - <include name="cdk-extra.jar"/> - <include name="cdk-interfaces.jar"/> - <include name="cdk-inchi.jar"/> - <include name="cdk-io.jar"/> - <include name="cdk-libiocml.jar"/> - <include name="cdk-qsar.jar"/> - <include name="cdk-render.jar"/> - <include name="cdk-standard.jar"/> - <include name="cdk-svg.jar"/> - <include name="cdk-jchempaint.jar"/> - <include name="cdk-jchempaint.application.jar"/> - <include name="cdk-jchempaint.applet.jar"/> - <include name="cdk-nonotify.jar"/> - <include name="cdk-valencycheck.jar"/> - <include name="cdk-smiles.jar"/> - <include name="cdk-sdg.jar"/> - <include name="cdk-control.jar"/> - </fileset> - </unjar> - </target> - - <target id="compile-jcp" name="compile-jcp"> - <antcall target="compile-module"> - <param name="module" value="jchempaint"/> - <param name="source" value="${src}/main"/> - </antcall> - <antcall target="compile-module"> - <param name="module" value="jchempaint.application"/> - <param name="source" value="${src}/main"/> - </antcall> - <antcall target="compile-module"> - <param name="module" value="jchempaint.applet"/> - <param name="source" value="${src}/main"/> - </antcall> - </target> - - -</project> - - - Deleted: cdk/branches/egonw-jchempaint-newtrunk/src/main/org/openscience/cdk/applications/jchempaint/InsertTextPanel.java =================================================================== --- cdk/branches/egonw-jchempaint-newtrunk/src/main/org/openscience/cdk/applications/jchempaint/InsertTextPanel.java 2008-03-21 14:50:50 UTC (rev 10464) +++ cdk/branches/egonw-jchempaint-newtrunk/src/main/org/openscience/cdk/applications/jchempaint/InsertTextPanel.java 2008-03-21 15:29:37 UTC (rev 10465) @@ -1,311 +0,0 @@ -/* - * -* Copyright (C) 2001-2007 Rajarshi Guha <raj...@us...> -* -* Contact: cdk...@li... -* -* This program is free software; you can redistribute it and/or -* modify it under the terms of the GNU Lesser General Public License -* as published by the Free Software Foundation; either version 2.1 -* of the License, or (at your option) any later version. -* All we ask is that proper credit is given for our work, which includes -* - but is not limited to - adding the above copyright notice to the beginning -* of your source code files, and to any copyright notice that you may distribute -* with programs based on this work. -* -* 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 Lesser General Public License for more details. -* -* You should have received a copy of the GNU Lesser General Public License -* along with this program; if not, write to the Free Software -* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. -* -*/ -package org.openscience.cdk.applications.jchempaint; - -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.Insets; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; -import java.net.URL; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import javax.swing.JButton; -import javax.swing.JComboBox; -import javax.swing.JFrame; -import javax.swing.JOptionPane; -import javax.swing.JPanel; -import javax.swing.text.JTextComponent; -import javax.vecmath.Vector2d; - -import net.sf.jniinchi.INCHI_RET; - -import org.openscience.cdk.DefaultChemObjectBuilder; -import org.openscience.cdk.MoleculeSet; -import org.openscience.cdk.exception.CDKException; -import org.openscience.cdk.exception.InvalidSmilesException; -import org.openscience.cdk.geometry.GeometryTools; -import org.openscience.cdk.inchi.InChIGeneratorFactory; -import org.openscience.cdk.inchi.InChIToStructure; -import org.openscience.cdk.interfaces.IAtomContainer; -import org.openscience.cdk.interfaces.IMolecule; -import org.openscience.cdk.layout.StructureDiagramGenerator; -import org.openscience.cdk.layout.TemplateHandler; -import org.openscience.cdk.renderer.Renderer2DModel; -import org.openscience.cdk.smiles.SmilesParser; -import org.openscience.cdk.tools.manipulator.ChemModelManipulator; - -/** - * A panel containing a text field and button to directly insert SMILES or InChI's - * - * @author Rajarshi Guha - * @cdk.module jchempaint - * @cdk.svnrev $Revision: 9162 $ - * @cdk.require swing - */ -public class InsertTextPanel extends JPanel implements ActionListener { - - private JChemPaintPanel jChemPaintPanel; - private JComboBox textCombo; - private JTextComponent editor; - private JFrame closeafter=null; - - - public InsertTextPanel(JChemPaintPanel jChemPaintPanel, JFrame closeafter) { - super(); - this.closeafter=closeafter; - setLayout(new GridBagLayout()); - - List oldText = new ArrayList(); - oldText.add(""); - - textCombo = new JComboBox(oldText.toArray()); - textCombo.setEditable(true); - textCombo.setToolTipText("Enter a CAS, SMILES or InChI string"); - - textCombo.addActionListener(this); - editor = (JTextComponent) textCombo.getEditor().getEditorComponent(); - - - JButton button = new JButton("Insert"); - button.addActionListener(this); - - GridBagConstraints gridBagConstraints = new GridBagConstraints(); - - - gridBagConstraints.gridx = 0; - gridBagConstraints.gridy = 0; - gridBagConstraints.fill = GridBagConstraints.HORIZONTAL; - gridBagConstraints.anchor = GridBagConstraints.FIRST_LINE_START; - gridBagConstraints.weightx = 0.5; - gridBagConstraints.ipadx = 5; - gridBagConstraints.insets = new Insets(0, 0, 0, 5); - add(textCombo, gridBagConstraints); - - gridBagConstraints.insets = new Insets(0, 0, 2, 0); - gridBagConstraints.ipadx = 5; - gridBagConstraints.ipady = 2; - gridBagConstraints.weightx = 0.0; - gridBagConstraints.gridx = 1; - add(button, gridBagConstraints); - - - this.jChemPaintPanel = jChemPaintPanel; - } - - public void actionPerformed(ActionEvent actionEvent) { - String actionCommand = actionEvent.getActionCommand(); - if (actionCommand.equals("comboBoxEdited") || actionCommand.equals("Insert")) { - IMolecule molecule = getMolecule(); - if (molecule == null) return; - generateModel(molecule); - if(closeafter!=null) - closeafter.setVisible(false); - } - } - - private IMolecule getMolecule() { - - IMolecule molecule; - String text = (String) textCombo.getSelectedItem(); - text = text.trim(); // clean up extra white space - - if (text.equals("")) return null; - - if (text.startsWith("InChI")) { // handle it as an InChI - try { - InChIGeneratorFactory inchiFactory = new InChIGeneratorFactory(); - InChIToStructure inchiToStructure = inchiFactory.getInChIToStructure(text); - INCHI_RET status = inchiToStructure.getReturnStatus(); - if (status != INCHI_RET.OKAY) { - JOptionPane.showMessageDialog(jChemPaintPanel, "Could not process InChI"); - return null; - } - IAtomContainer atomContainer = inchiToStructure.getAtomContainer(); - molecule = atomContainer.getBuilder().newMolecule(atomContainer); - } catch (CDKException e2) { - JOptionPane.showMessageDialog(jChemPaintPanel, "Could not load InChI subsystem"); - return null; - } - } else if (isCASNumber(text)) { // is it a CAS number? - try { - molecule = getMoleculeFromCAS(text); - } catch (IOException e) { - JOptionPane.showMessageDialog(jChemPaintPanel, "Error in reading data from PubChem"); - return null; - } - } else { // OK, it must be a SMILES - SmilesParser smilesParser = new SmilesParser(DefaultChemObjectBuilder.getInstance()); - try { - molecule = smilesParser.parseSmiles(text); - } catch (InvalidSmilesException e1) { - JOptionPane.showMessageDialog(jChemPaintPanel, "Invalid SMILES specified"); - return null; - } - } - - // OK, we have a valid molecule, save it and show it - String tmp = (String) textCombo.getItemAt(0); - if (tmp.equals("")) textCombo.removeItemAt(0); - textCombo.addItem(text); - editor.setText(""); - - return molecule; - } - - private boolean isCASNumber(String text) { - String[] chars = text.split("-"); - if (chars.length != 3) return false; - for (int i = 0; i < 3; i++) { - if (i == 2 && chars[i].length() != 1) return false; - if (i == 1 && chars[i].length() != 2) return false; - if (i == 0 && chars[i].length() > 6) return false; - try { - Integer.parseInt(chars[i]); - } catch (NumberFormatException e) { - return false; - } - } - return true; - } - - private IMolecule getMoleculeFromCAS(String cas) throws IOException { - String data; - - String firstURL = "http://www.ncbi.nlm.nih.gov/entrez/query.fcgi?db=pccompound&term=" + cas; - - data = getDataFromURL(firstURL); - - Pattern pattern = Pattern.compile("http://pubchem.ncbi.nlm.nih.gov/summary/summary.cgi\\?cid=(\\d*)"); - Matcher matcher = pattern.matcher(data); - - String cid = null; - boolean found = false; - while (matcher.find()) { - cid = matcher.group(1); - try { // should be an integer - Integer.parseInt(cid); - found = true; - break; - } catch (NumberFormatException e) { - continue; - } - } - if (!found) return null; - - String secondURL = "http://eutils.ncbi.nlm.nih.gov/entrez/eutils/esummary.fcgi?tool=jcppubchem&db=pccompound&id=" + cid; - data = getDataFromURL(secondURL); - - pattern = Pattern.compile("<Item Name=\"CanonicalSmile\" Type=\"String\">([^\\s]*?)</Item>"); - matcher = pattern.matcher(data); - String smiles = null; - found = false; - while (matcher.find()) { - smiles = matcher.group(1); - if (smiles != null || !smiles.equals("")) { - found = true; - break; - } - } - if (!found) return null; - - // got the canonical SMILES, lets get the molecule - SmilesParser smilesParser = new SmilesParser(DefaultChemObjectBuilder.getInstance()); - IMolecule molecule; - try { - molecule = smilesParser.parseSmiles(smiles); - } catch (InvalidSmilesException e1) { - JOptionPane.showMessageDialog(jChemPaintPanel, "Couldn't process data from PubChem"); - return null; - } - return molecule; - } - - private String getDataFromURL(String url) throws IOException { - URL theURL = new URL(url); - BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(theURL.openStream())); - String data = ""; - String line; - while ((line = bufferedReader.readLine()) != null) data += line; - bufferedReader.close(); - return data; - } - - public void generateModel(IMolecule molecule) { - if (molecule == null) return; - - // ok, get relevent bits from active model - JChemPaintModel jcpModel = jChemPaintPanel.getJChemPaintModel(); - Renderer2DModel renderModel = jcpModel.getRendererModel(); - org.openscience.cdk.interfaces.IChemModel chemModel = jcpModel.getChemModel(); - org.openscience.cdk.interfaces.IMoleculeSet moleculeSet = chemModel.getMoleculeSet(); - if (moleculeSet == null) { - moleculeSet = new MoleculeSet(); - } - - // ok, now generate 2D coordinates - StructureDiagramGenerator sdg = new StructureDiagramGenerator(); - sdg.setTemplateHandler(new TemplateHandler(moleculeSet.getBuilder())); - try { - sdg.setMolecule(molecule); - sdg.generateCoordinates(new Vector2d(0, 1)); - molecule = sdg.getMolecule(); - double bondLength = renderModel.getBondLength(); - double scaleFactor = GeometryTools.getScaleFactor(molecule, bondLength,jChemPaintPanel.getJChemPaintModel().getRendererModel().getRenderingCoordinates()); - GeometryTools.scaleMolecule(molecule, scaleFactor, renderModel.getRenderingCoordinates()); - //if there are no atoms in the actual chemModel all 2D-coordinates would be set to NaN - if (ChemModelManipulator.getAtomCount(chemModel) != 0) { - IAtomContainer container = chemModel.getBuilder().newAtomContainer(); - Iterator containers = ChemModelManipulator.getAllAtomContainers(chemModel).iterator(); - while (containers.hasNext()) { - container.add((IAtomContainer)containers.next()); - } - GeometryTools.translate2DCenterTo((IAtomContainer)molecule, - GeometryTools.get2DCenter(container, - jChemPaintPanel.getJChemPaintModel().getRendererModel().getRenderingCoordinates() - ), - jChemPaintPanel.getJChemPaintModel().getRendererModel().getRenderingCoordinates() - ); - } - GeometryTools.translate2D(molecule, 5 * bondLength, 0, renderModel.getRenderingCoordinates()); // in pixels - } catch (Exception exc) { - exc.printStackTrace(); - } - - moleculeSet.addMolecule(molecule); -// renderModel.setSelectedPart(m); - jChemPaintPanel.getChemModel().setMoleculeSet(moleculeSet); - jChemPaintPanel.scaleAndCenterMolecule(jChemPaintPanel.getChemModel()); - jcpModel.fireChange(jChemPaintPanel.getChemModel()); - } -} Deleted: cdk/branches/egonw-jchempaint-newtrunk/src/main/org/openscience/cdk/applications/jchempaint/JCPPropertyHandler.java =================================================================== --- cdk/branches/egonw-jchempaint-newtrunk/src/main/org/openscience/cdk/applications/jchempaint/JCPPropertyHandler.java 2008-03-21 14:50:50 UTC (rev 10464) +++ cdk/branches/egonw-jchempaint-newtrunk/src/main/org/openscience/cdk/applications/jchempaint/JCPPropertyHandler.java 2008-03-21 15:29:37 UTC (rev 10465) @@ -1,355 +0,0 @@ -/* - * $RCSfile$ - * $Author$ - * $Date$ - * $Revision$ - * - * Copyright (C) 1997-2007 The JChemPaint project - * - * Contact: jch...@li... - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 - * of the License, or (at your option) any later version. - * All we ask is that proper credit is given for our work, which includes - * - but is not limited to - adding the above copyright notice to the beginning - * of your source code files, and to any copyright notice that you may distribute - * with programs based on this work. - * - * 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 Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - */ -package org.openscience.cdk.applications.jchempaint; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.net.URL; -import java.util.Locale; -import java.util.MissingResourceException; -import java.util.Properties; -import java.util.ResourceBundle; - -import org.openscience.cdk.tools.LoggingTool; - -/** - * A property manager for JChemPaint. - * - * @cdk.module jchempaint - * @cdk.svnrev $Revision$ - * @author steinbeck - */ -public class JCPPropertyHandler -{ - - private static JCPPropertyHandler jcpPropsHandler = null; - - private LoggingTool logger; - private Properties currentProperties; - //private File defaultPropsFile; - private File userPropsFile; - //private File userAtypeFile; - private File uhome; - private File ujcpdir; - private ResourceBundle guiDefinition; - private ResourceBundle resources; - private Properties shortCutProps; - - - /** - * Constructor for the JCPPropertyHandler object - */ - private JCPPropertyHandler() - { - logger = new LoggingTool(this); - currentProperties = null; - //defaultPropsFile = null; - userPropsFile = null; - //userAtypeFile = null; - uhome = null; - ujcpdir = null; - guiDefinition = null; - } - - - /** - * Gets the instance attribute of the JCPPropertyHandler class - * - *@return The instance value - */ - public static JCPPropertyHandler getInstance() - { - if (jcpPropsHandler == null) - { - jcpPropsHandler = new JCPPropertyHandler(); - } - return jcpPropsHandler; - } - - - /** - * Gets the jCPProperties attribute of the JCPPropertyHandler object - * - *@return The jCPProperties value - */ - public Properties getJCPProperties() - { - if (currentProperties == null) - { - reloadProperties(); - } - return currentProperties; - } - - public void reloadProperties() - { - Properties applicationProps = null; - Properties defaultProps = null; - InputStream defaultStream; - try - { - defaultStream = JCPPropertyHandler.class.getResourceAsStream("resources/text/JChemPaintResources.properties"); - defaultProps = new Properties(); - defaultProps.load(defaultStream); - defaultStream.close(); - logger.info("Loaded properties from jar"); - } catch (Exception exception) - { - logger.error("There was a problem retrieving JChemPaint's default properties."); - logger.debug(exception); - } - - try - { - // set up real properties - applicationProps = new Properties(defaultProps); - FileInputStream appStream = new FileInputStream(getUserPropsFile()); - applicationProps.load(appStream); - appStream.close(); - logger.info("Loaded user properties from file"); - } catch (FileNotFoundException exception) - { - logger.warn("User does not have localized properties in "); - } catch (Exception exception) - { - logger.error("There was a problem retrieving the user properties from file"); - logger.debug(exception); - } - currentProperties = applicationProps; - } - - public void saveProperties() - { - try - { - FileOutputStream appStream = new FileOutputStream(getUserPropsFile()); - currentProperties.store(appStream, null); - appStream.flush(); - appStream.close(); - logger.info("Properties save to ", getUserPropsFile()); - } catch (Exception exception) - { - logger.error("An error has occured while storing properties"); - logger.error("to file "); - logger.debug(exception); - } - } - - - /** - * Gets the userHome attribute of the JCPPropertyHandler object - * - *@return The userHome value - */ - public File getUserHome() - { - if (uhome == null) - { - try - { - uhome = new File(System.getProperty("user.home")); - } catch (Exception exc) - { - logger.error("Could not read a system property. Failing!"); - logger.debug(exc); - } - } - return uhome; - } - - - /** - * Gets the jChemPaintDir attribute of the JCPPropertyHandler object - * - *@return The jChemPaintDir value - */ - public File getJChemPaintDir() - { - if (ujcpdir == null) - { - try - { - ujcpdir = new File(getUserHome(), ".jchempaint"); - ujcpdir.mkdirs(); - } catch (Exception exc) - { - logger.error("Could read a JChemPaint dir. I might be in a sandbox."); - logger.debug(exc); - } - } - return ujcpdir; - } - - - /** - * Gets the userPropsFile attribute of the JCPPropertyHandler object - * - *@return The userPropsFile value - */ - public File getUserPropsFile() - { - if (userPropsFile == null) - { - try - { - userPropsFile = new File(getJChemPaintDir(), "properties"); - } catch (Exception exc) - { - logger.error("Could not read a system property. I might be in a sandbox."); - logger.debug(exc); - } - } - return userPropsFile; - } - - - /** - * Gets the gUIDefinition attribute of the JCPPropertyHandler object - * - * @return The gUIDefinition value - */ - public ResourceBundle getGUIDefinition() - { - if (guiDefinition == null) - { - String guiString = null; - try - { - guiString = System.getProperty("gui"); - } catch (Exception exc) - { - logger.error("Could not read a system property. I might be in a sandbox."); - } - if (guiString == null) - { - guiString = "stable"; - } - guiDefinition = getGUIDefinition(guiString); - } - return guiDefinition; - } - - public ResourceBundle getGUIDefinition(String guiString) { - try { - String resource = "org.openscience.cdk.applications.jchempaint.resources.text.JCPGUI_" + guiString; - guiDefinition = ResourceBundle.getBundle(resource, Locale.getDefault()); - } catch (Exception exc) { - logger.error("Could not read a GUI definition: " + exc.getMessage()); - logger.debug(exc); - } - return guiDefinition; - } - - public Properties getJCPShort_Cuts() { - if (shortCutProps == null) { - try { - String propertiesFile = "org/openscience/cdk/applications/jchempaint/resources/text/JCPShort_Cuts.properties"; - shortCutProps = new Properties(); - InputStream appStream = this.getClass().getClassLoader().getResourceAsStream(propertiesFile); - shortCutProps.load(appStream); - appStream.close(); - } catch (FileNotFoundException fnfe) {fnfe.printStackTrace();} catch (IOException ioe) {} - } - return shortCutProps; - } - - /** - * Gets the resources attribute of the JCPPropertyHandler object - * - *@return The resources value - */ - public ResourceBundle getResources() - { - if (resources == null) - { - try - { - String resource = "org.openscience.cdk.applications.jchempaint.resources.text.JChemPaintResources"; - resources = ResourceBundle.getBundle(resource); - } catch (Exception exc) - { - logger.error("Could not read the resources."); - logger.debug(exc); - } - } - return resources; - } - - - /** - * Returns an URL build from the path of this object and another part that is - * searched in the properties file. Used to find the images for the buttons. - * - *@param key String The String that says which image is searched - *@return URL The URL where the image is located - */ - public URL getResource(String key) - { - String name = getResourceString(key); - logger.debug("resource name: ", name); - if (name != null) - { - URL url = this.getClass().getResource(name); - return url; - } else - { - logger.error("ResourceString is null for: ", key); - } - return null; - } - - - /** - * Returns the ResourceString from the properties file that follows the given - * String. - * - *@param key String The String to be looked after - *@return String The String that follows the key in the properties file - */ - public String getResourceString(String key) - { - String str; - try - { - str = getResources().getString(key); - } catch (MissingResourceException mre) - { - logger.error("Could not find resource: ", mre.getMessage()); - logger.debug(mre); - str = null; - } - return str; - } - -} - Deleted: cdk/branches/egonw-jchempaint-newtrunk/src/main/org/openscience/cdk/applications/jchempaint/JChemPaintEditorPanel.java =================================================================== --- cdk/branches/egonw-jchempaint-newtrunk/src/main/org/openscience/cdk/applications/jchempaint/JChemPaintEditorPanel.java 2008-03-21 14:50:50 UTC (rev 10464) +++ cdk/branches/egonw-jchempaint-newtrunk/src/main/org/openscience/cdk/applications/jchempaint/JChemPaintEditorPanel.java 2008-03-21 15:29:37 UTC (rev 10465) @@ -1,852 +0,0 @@ -/* $RCSfile$ - * $Author$ - * $Date$ - * $Revision$ - * - * Copyright (C) 1997-2007 The JChemPaint project - * - * Contact: jch...@li... - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 - * of the License, or (at your option) any later version. - * All we ask is that proper credit is given for our work, which includes - * - but is not limited to - adding the above copyright notice to the beginning - * of your source code files, and to any copyright notice that you may distribute - * with programs based on this work. - * - * 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 Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - */ -package org.openscience.cdk.applications.jchempaint; - -import java.awt.BorderLayout; -import java.awt.Color; -import java.awt.Container; -import java.awt.Dimension; -import java.awt.Graphics2D; -import java.awt.event.ComponentAdapter; -import java.awt.event.ComponentEvent; -import java.awt.image.BufferedImage; -import java.awt.image.RenderedImage; -import java.io.File; -import java.io.FileReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.util.Calendar; -import java.util.Enumeration; -import java.util.EventObject; -import java.util.HashMap; -import java.util.Iterator; -import java.util.StringTokenizer; - -import javax.swing.JFrame; -import javax.swing.JScrollPane; -import javax.swing.JToolBar; -import javax.swing.JViewport; -import javax.swing.event.ChangeEvent; -import javax.swing.event.ChangeListener; -import javax.swing.event.EventListenerList; -import javax.vecmath.Point2d; -import javax.vecmath.Vector2d; - -import org.openscience.cdk.Atom; -import org.openscience.cdk.Bond; -import org.openscience.cdk.ChemModel; -import org.openscience.cdk.DefaultChemObjectBuilder; -import org.openscience.cdk.PseudoAtom; -import org.openscience.cdk.Reaction; -import org.openscience.cdk.applications.jchempaint.dnd.JCPTransferHandler; -import org.openscience.cdk.applications.undoredo.JCPUndoRedoHandler; -import org.openscience.cdk.controller.PopupController2D; -import org.openscience.cdk.dict.DictionaryDatabase; -import org.openscience.cdk.event.ICDKChangeListener; -import org.openscience.cdk.geometry.GeometryTools; -import org.openscience.cdk.interfaces.IAtomContainer; -import org.openscience.cdk.interfaces.IChemModel; -import org.openscience.cdk.interfaces.IMoleculeSet; -import org.openscience.cdk.renderer.Renderer2D; -import org.openscience.cdk.renderer.Renderer2DModel; -import org.openscience.cdk.smiles.SmilesParser; -import org.openscience.cdk.tools.LoggingTool; -import org.openscience.cdk.tools.manipulator.ChemModelManipulator; -import org.openscience.cdk.tools.manipulator.MoleculeSetManipulator; -import org.openscience.cdk.tools.manipulator.ReactionManipulator; -import org.openscience.cdk.validate.BasicValidator; -import org.openscience.cdk.validate.CDKValidator; -import org.openscience.cdk.validate.DictionaryValidator; -import org.openscience.cdk.validate.PDBValidator; -import org.openscience.cdk.validate.ValencyValidator; -import org.openscience.cdk.validate.ValidatorEngine; - -/** - * This class implements an editing JChemPaintPanel. - * - *@author steinbeck - *@cdk.created 16. Februar 2005 - *@cdk.module jchempaint - * @cdk.svnrev $Revision$ - *@see JChemPaintViewerOnlyPanel - */ -public class JChemPaintEditorPanel extends JChemPaintPanel - implements ChangeListener, ICDKChangeListener -{ - - private static final long serialVersionUID = -5369372292013788887L; - static String JCP_MODEL_CHANGED = "1"; - static String JCP_CLOSING = "2"; - - String lastEventReason; - - String recentSymbol = "C"; - - private static DictionaryDatabase dictdb = null; - private static ValidatorEngine engine = null; - private static LoggingTool logger; - - boolean showMenuBar = true; - boolean showToolBar = true; - boolean showStatusBar = true; - boolean showInsertTextField = true; - - protected EventListenerList changeListeners = null; - - - /** - * Constructor for the panel - * - */ - public JChemPaintEditorPanel(){ - this(1, null); - } - - - public JChemPaintEditorPanel(int lines, Dimension panelDimension) { - this(lines, panelDimension, false, "stable"); - } - - public JChemPaintEditorPanel(int lines, Dimension panelDimension, String guiString) { - this(lines, panelDimension, false, guiString); - } - /** - * Constructor for the panel - * - *@param lines How many lines should the horizontal toolbar have? - */ - public JChemPaintEditorPanel(int lines, Dimension panelDimension, - boolean isEmbedded, String guiString) - { - super(); - if (isEmbedded == true) { - this.setEmbedded(); - } - this.guiString = guiString; - customizeView(); - super.setJChemPaintModel(new JChemPaintModel(),null); - setShowToolBar(true, lines); - if(!guiString.equals("applet")){ - setShowInsertTextField(true); - - } - if (logger == null) - { - logger = new LoggingTool(this); - } - this.setTransferHandler(new JCPTransferHandler("JCPPanel")); - logger.debug("JCPPanel set and done..."); - if (panelDimension != null && this.isEmbedded()) { - super.getJChemPaintModel().getRendererModel().setBackgroundDimension(panelDimension); - viewerDimension = new Dimension(((int) panelDimension.getWidth()) + 10, ((int) panelDimension.getHeight() + 10)); - super.setPreferredSize(viewerDimension); - } - } - - - /** - * Tells if a menu is shown - * - *@return The showMenu value - */ - public boolean getShowMenuBar() { - return showMenuBar; - } - - - /** - * Sets if a menu is shown - * - *@param showMenuBar The new showMenuBar value - */ - public void setShowMenuBar(boolean showMenuBar) { - this.showMenuBar = showMenuBar; - customizeView(); - } - - - /** - * Tells if a status bar is shown - * - *@return The showStatusBar value - */ - public boolean getShowStatusBar() { - return showStatusBar; - } - - /** - * Indicates whether the insert text field is shown. - * - * @return true is the text field widget is to be shown, false otherwise - */ - public boolean getShowInsertTextField() { - return showInsertTextField; - } - - public void customizeView() { - if (showMenuBar) { - if (menu == null) { - menu = new JChemPaintMenuBar(this, this.guiString); - } - add(menu, BorderLayout.NORTH); - revalidate(); - } else { - try { - remove(menu); - revalidate(); - } catch (Exception exc) { - logger.debug("Error in removing menu"); - } - } - if (showStatusBar) { - if (statusBar == null) { - statusBar = new StatusBar(); - } - add(statusBar, BorderLayout.SOUTH); - revalidate(); - } else { - try { - remove(statusBar); - revalidate(); - } catch (Exception exc) { - logger.debug("Error in removing status bar"); - } - } - } - - void setupIfModelNotEmpty() - { - IAtomContainer ac = jchemPaintModel.getChemModel().getBuilder().newAtomContainer(); - Iterator containers = ChemModelManipulator.getAllAtomContainers(jchemPaintModel.getChemModel()).iterator(); - while (containers.hasNext()) ac.add((IAtomContainer)containers.next()); - - Renderer2DModel rendererModel = jchemPaintModel.getRendererModel(); - if (ac.getAtomCount() != 0) - { - logger.info("ChemModel is already non-empty! Sizing things to get it visible!"); - // do some magic to get it all in one page - Dimension oneMoleculeDimension = new Dimension(600, 400); - // should be based on molecule/reaction size! - Dimension dimension = makeChemModelFit( - oneMoleculeDimension, jchemPaintModel.getChemModel() - ); - rendererModel.setBackgroundDimension(dimension); - - /* - * this code ensures that the molecule ends up somewhere in the model - * of the view screen - */ - GeometryTools.translateAllPositive(ac,rendererModel.getRenderingCoordinates()); - double scaleFactor = GeometryTools.getScaleFactor(ac, rendererModel.getBondLength(),jchemPaintModel.getRendererModel().getRenderingCoordinates()); - GeometryTools.scaleMolecule(ac, scaleFactor,rendererModel.getRenderingCoordinates()); - layoutInTable(oneMoleculeDimension, jchemPaintModel.getChemModel(),jchemPaintModel.getRendererModel()); - // GeometryTools.center(ac, getPreferredSize()); - // GeometryTools.center(ac, new Dimension(300,200)); - } - } - - public void registerModel(JChemPaintModel model) - { - String filename = "org/openscience/cdk/applications/jchempaint/resources/text/funcgroups.txt"; - InputStream ins = this.getClass().getClassLoader().getResourceAsStream(filename); - - HashMap funcgroups=new HashMap(); - SmilesParser sp=new SmilesParser(DefaultChemObjectBuilder.getInstance()); - StringBuffer sb=new StringBuffer(); - InputStreamReader isr = new InputStreamReader(ins); - try{ - while(true){ - int i=isr.read(); - if(i==-1){ - break; - }else if(((char)i)=='\n' || ((char)i)=='\r'){ - if(!sb.toString().equals("")){ - StringTokenizer st=new StringTokenizer(sb.toString()); - String key=(String)st.nextElement(); - String value=(String)st.nextElement(); - funcgroups.put(key, sp.parseSmiles(value)); - sb=new StringBuffer(); - } - }else{ - sb.append((char)i); - } - } - if(!sb.toString().equals("")){ - StringTokenizer st=new StringTokenizer(sb.toString()); - String key=(String)st.nextElement(); - String value=(String)st.nextElement(); - funcgroups.put(key, sp.parseSmiles(value)); - } - }catch(Exception ex){ - ex.printStackTrace(); - logger.error("cannot instantiate funcgroupsmap",ex.getMessage()); - } - - - PopupController2D inputAdapter = new PopupController2D(model.getChemModel(), model.getRendererModel(),model.getControllerModel(), lastAction, this.moveButton, funcgroups); - JCPUndoRedoHandler undoRedoHandler=new JCPUndoRedoHandler(model.getControllerModel()); - inputAdapter.setUndoRedoHandler(undoRedoHandler); - setupPopupMenus(inputAdapter); - Renderer2DModel rendererModel = model.getRendererModel(); - model.getControllerModel().setBondPointerLength(rendererModel.getBondLength()); - model.getControllerModel().setRingPointerLength(rendererModel.getBondLength()); - - model.getRendererModel().addCDKChangeListener(this); - inputAdapter.addCDKChangeListener(model); - //drawingPanel.setJChemPaintModel(model); - drawingPanel.addMouseListener(inputAdapter); - drawingPanel.addMouseMotionListener(inputAdapter); - //Somehow this registration does not work. If it would, element symbols could be changed via keyboard - drawingPanel.addKeyListener(inputAdapter); - } - - - /** - * Returns the value of showToolbar. - * - *@return The showToolbar value - */ - public boolean getShowToolBar() - { - return showToolBar; - } - - /** - * Returns the value of lastEventReason. - */ - public String getLastEventReason() - { - return lastEventReason; - } - - /** - * Sets the value of lastEventReason. - * @param lastEventReason The value to assign lastEventReason. - */ - public void setLastEventReason(String lastEventReason) - { - this.lastEventReason = lastEventReason; - } - - - /** - * Sets the value of showToolbar. - * - *@param showToolBar The value to assign showToolbar. - */ - public void setShowToolBar(boolean showToolBar) - { - setShowToolBar(showToolBar, 1); - } - - - /** - * Sets if statusbar should be shown - * - *@param showStatusBar The value to assign showStatusBar. - */ - public void setShowStatusBar(boolean showStatusBar) { - this.showStatusBar = showStatusBar; - customizeView(); - } - - /** - * Set to indicate whetehr the insert text field should be used. - * - * @param showInsertTextField true is the text entry widget is to be shown - */ - public void setShowInsertTextField(boolean showInsertTextField) { - this.showInsertTextField = showInsertTextField; - if (showInsertTextField) { - if (insertTextPanel == null) insertTextPanel = new InsertTextPanel(this,null); - topContainer.add(insertTextPanel, BorderLayout.SOUTH); - } else { - topContainer.remove(insertTextPanel); - } - mainContainer.revalidate(); - } - - - /** - * Sets the value of showToolbar. - * - *@param showToolBar The value to assign showToolbar. - */ - public void setShowToolBar(boolean showToolBar, int lines) { - this.showToolBar = showToolBar; - if (showToolBar) { - if (toolBar == null) { - toolBar = ToolBarMaker.getToolbar(this, lines); - } - topContainer.add(toolBar, BorderLayout.NORTH); - mainContainer.revalidate(); - } else { - try { - topContainer.remove(toolBar); - mainContainer.revalidate(); - } catch (Exception exc) { - logger.debug("Error in removing tool bar"); - } - } - - } - - - /** - * Overwrites the default background color and returns the color taken from - * the Renderer2DModel. - * - *@return The background value - */ - public Color getBackground() - { - if (jchemPaintModel != null) - { - return jchemPaintModel.getRendererModel().getBackColor(); - } else - { - return Color.WHITE; - } - } - - - /** - * Gets the toolBar attribute of the JChemPaintPanel object - * - *@return The toolBar value - */ - public JToolBar getToolBar() - { - return toolBar; - } - - /** - * Gets the menu attribute of the JChemPaintPanel object - * - *@return The menu value - */ - public JChemPaintMenuBar getMenu() - { - return menu; - } - - - /** - * Creates a new JFrame that owns a new JChemPaintModel and returns it. - * - *@return The new JFrame containing the JChemPaintEditorPanel - */ - public static JFrame getEmptyFrameWithModel() - { - JChemPaintModel model = new JChemPaintModel(); - model.setTitle(getNewFrameName()); - model.setAuthor(JCPPropertyHandler.getInstance().getJCPProperties().getProperty("General.UserName")); - Package self = Package.getPackage("org.openscience.cdk.applications.jchempaint"); - String version = self.getImplementationVersion(); - model.setSoftware("JChemPaint " + version); - model.setGendate((Calendar.getInstance()).getTime().toString()); - JFrame jcpf = getNewFrame(model); - return jcpf; - } - /** - * Creates a new JFrame that owns a new JChemPaintModel and returns it which contains - * a model. - * - *@param mod The JChemPaintModel - *@return The new JFrame containing the JChemPaintEditorPanel - */ - public static JFrame getFrameWithModel(IChemModel mod) - { - JChemPaintModel model = new JChemPaintModel(mod); - model.setTitle(mod.getID()); - model.setAuthor(JCPPropertyHandler.getInstance().getJCPProperties().getProperty("General.UserName")); - Package self = Package.getPackage("org.openscience.cdk.applications.jchempaint"); - String version = self.getImplementationVersion(); - model.setSoftware("JChemPaint " + version); - model.setGendate((Calendar.getInstance()).getTime().toString()); - JFrame jcpf = getNewFrame(model); - return jcpf; - } - - /** - * Creates a new JChemPaintEditorPanel and assigns a given Model to it. - * - *@param model The model to be assigned to the new frame. - *@return The new JChemPaintFrame with its new JChemPaintModel - */ - public static JFrame getNewFrame(JChemPaintModel model) - { - JFrame frame = new JFrame(); - frame.addWindowListener(new JChemPaintPanel.AppCloser()); - frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); - JChemPaintEditorPanel jcpep = new JChemPaintEditorPanel(); - frame.getContentPane().add(jcpep); - jcpep.registerModel(model); - jcpep.setJChemPaintModel(model,null); - frame.setTitle(model.getTitle()); - //This ensures that the drawingpanel is never smaller than the application - frame.addComponentListener(new ComponentAdapter(){ - public void componentResized(ComponentEvent e) { - if(((JChemPaintEditorPanel)((JFrame)e.getSource()).getContentPane().getComponent(0)).getJChemPaintModel().getRendererModel().getBackgroundDimension().width<((JFrame)e.getSource()).getWidth()-30) - ((JChemPaintEditorPanel)((JFrame)e.getSource()).getContentPane().getComponent(0)).getJChemPaintModel().getRendererModel().setBackgroundDimension(new Dimension(((JFrame)e.getSource()).getWidth()-30,((JChemPaintEditorPanel)((JFrame)e.getSource()).getContentPane().getComponent(0)).getJChemPaintModel().getRendererModel().getBackgroundDimension().height)); - if(((JChemPaintEditorPanel)((JFrame)e.getSource()).getContentPane().getComponent(0)).getJChemPaintModel().getRendererModel().getBackgroundDimension().height<((JFrame)e.getSource()).getHeight()-30) - ((JChemPaintEditorPanel)((JFrame)e.getSource()).getContentPane().getComponent(0)).getJChemPaintModel().getRendererModel().setBackgroundDimension(new Dimension(((JChemPaintEditorPanel)((JFrame)e.getSource()).getContentPane().getComponent(0)).getJChemPaintModel().getRendererModel().getBackgroundDimension().width,((JFrame)e.getSource()).getHeight()-30)); - } - }); - model.getControllerModel().setAutoUpdateImplicitHydrogens(true); - model.getRendererModel().setShowEndCarbons(true); - return frame; - } - - public void setupPopupMenus(PopupController2D inputAdapter) - { - if (inputAdapter.getPopupMenu(Atom.class) == null) - { - inputAdapter.setPopupMenu(Atom.class, new JChemPaintPopupMenu(this, "atom")); - } - if (inputAdapter.getPopupMenu(PseudoAtom.class) == null) - { - inputAdapter.setPopupMenu(PseudoAtom.class, new JChemPaintPopupMenu(this, "pseudo")); - } - if (inputAdapter.getPopupMenu(Bond.class) == null) - { - inputAdapter.setPopupMenu(Bond.class, new JChemPaintPopupMenu(this, "bond")); - } - if (inputAdapter.getPopupMenu(ChemModel.class) == null) - { - inputAdapter.setPopupMenu(ChemModel.class, new JChemPaintPopupMenu(this, "chemmodel")); - } - if (inputAdapter.getPopupMenu(Reaction.class) == null) - { - inputAdapter.setPopupMenu(Reaction.class, new JChemPaintPopupMenu(this, "reaction")); - } - } - - public RenderedImage takeSnapshot() - { - BufferedImage image = null; - try - { - logger.info("Making snapshot... "); - - Renderer2D r2d = new Renderer2D(jchemPaintModel.getRendererModel()); - r2d.setRenderer2DModel(jchemPaintModel.getRendererModel()); - IChemModel model = null; - try { - model = (IChemModel) jchemPaintModel.getChemModel().clone(); - } catch (CloneNotSupportedException exception) { - logger.error("Clone of IChemModel failed: ", exception.getMessage()); - logger.debug(exception); - return null; - } - IAtomContainer ac = model.getBuilder().newAtomContainer(); - Iterator containers = MoleculeSetManipulator.getAllAtomContainers(model.getMoleculeSet()).iterator(); - while (containers.hasNext()) ac.add((IAtomContainer)containers.next()); - HashMap oldrenderingcoordinates=new HashMap(); - Iterator it=jchemPaintModel.getRendererModel().getRenderingCoordinates().keySet().iterator(); - while(it.hasNext()){ - Object key=it.next(); - oldrenderingcoordinates.put(key,new Point2d(((Point2d)jchemPaintModel.getRendererModel().getRenderingCoordinates().get(key)).x,((Point2d)jchemPaintModel.getRendererModel().getRenderingCoordinates().get(key)).y)); - } - Dimension dim = GeometryTools.get2DDimension(ac,jchemPaintModel.getRendererModel().getRenderingCoordinates()); - GeometryTools.translateAllPositive(ac,jchemPaintModel.getRendererModel().getRenderingCoordinates()); - GeometryTools.translate2D(ac, new Vector2d(40,40),jchemPaintModel.getRendererModel().getRenderingCoordinates()); - it=jchemPaintModel.getRendererModel().getRenderingCoordinates().keySet().iterator(); - while(it.hasNext()){ - Point2d point =(Point2d)jchemPaintModel.getRendererModel().getRenderingCoordinates().get(it.next()); - point.y=(int)dim.getHeight()+80-point.y; - } - image = new BufferedImage((int)dim.getWidth()+80, (int)dim.getHeight()+80, BufferedImage.TYPE_INT_ARGB); - Graphics2D snapGraphics = image.createGraphics(); - snapGraphics.setBackground(Color.WHITE); - snapGraphics.clearRect(0,0,(int)dim.getWidth()+80, (int)dim.getHeight()+80); - r2d.useScreenSize=false; - r2d.paintMolecule(ac, (Graphics2D) snapGraphics,false,true); - r2d.useScreenSize=true; - jchemPaintModel.getRendererModel().setRenderingCoordinates(oldrenderingcoordinates); - logger.info("created..."); - - - logger.debug("painting succeeded."); - } catch (NullPointerException e) - { - image = null; - } - return image; - } - - - /** - * Method to notify this CDKChangeListener if something has changed in another - * object - * - *@param e The EventObject containing information on the nature and source of - * the event - */ - public void stateChanged(EventObject e) - { - //FIXME was dependant on ReallyPaintPanel.drawingnow - drawingPanel.repaint(); - } - - - /** - * Enlarges the 'one molecule' dimension to fit a set of reactions or - * molecules. - * - *@param baseDim Description of the Parameter - *@param model Description of the Parameter - *@return Description of the Return Value - */ - private Dimension makeChemModelFit(Dimension baseDim, IChemModel model) - { - Dimension newDim = new Dimension(baseDim); - // a bit ugly, but assume moleculeSet *or* reactionSet - IMoleculeSet moleculeSet = model.getMoleculeSet(); - if (moleculeSet != null) - { - newDim.height = newDim.height * (moleculeSet.getMoleculeCount()); - return newDim; - } - org.openscience.cdk.interfaces.IReactionSet reactionSet = model.getReactionSet(); - if (reactionSet != null) - { - newDim.height = newDim.height * (reactionSet.getReactionCount()); - } - return newDim; - } - - - /** - * Lays out the molecules in a MoleculeSet, or reaction in a ReactionSet - * in a one column table. - * - *@param baseDim Description of the Parameter - *@param model Description of the Parameter - */ - private void layoutInTable(Dimension baseDim, IChemModel model, Renderer2DModel rm) - { - // a bit ugly, but assume moleculeSet *or* reactionSet - IMoleculeSet moleculeSet = model.getMoleculeSet(); - if (moleculeSet != null) - { - for (int i = 0; i < moleculeSet.getAtomContainerCount(); i++) - { - GeometryTools.center(moleculeSet.getAtomContainer(i), baseDim,rm.getRenderingCoordinates()); - GeometryTools.translate2D(moleculeSet.getAtomContainer(i), 0, baseDim.height * i,rm.getRenderingCoordinates()); - } - return; - } - org.openscience.cdk.interfaces.IReactionSet reactionSet = model.getReactionSet(); - if (reactionSet != null) - { - - for (int i = 1; i <= reactionSet.getReactionCount(); i++) - { - IAtomContainer ac = reactionSet.getBuilder().newAtomContainer(); - Iterator containers = ReactionManipulator.getAllAtomContainers(reactionSet.getReaction(i - 1)).iterator(); - while (containers.hasNext()) ac.add((IAtomContainer)containers.next()); - GeometryTools.center(ac, baseDim,rm.getRenderingCoordinates()); - GeometryTools.translate2D(ac, 0, baseDim.height * (reactionSet.getReactionCount() - i),rm.getRenderingCoordinates()); - } - } - } - - - /** - * Gets the validatorEngine attribute of the JChemPaintEditorPanel class - * - *@return The validatorEngine value - */ - public static ValidatorEngine getValidatorEngine() - { - if (engine == null) - { - engine = new ValidatorEngine(); - // default validators - engine.addValidator(new BasicValidator()); - engine.addValidator(new ValencyValidator()); - engine.addValidator(new CDKValidator()); - engine.addValidator(new DictionaryValidator(dictdb)); - engine.addValidator(new PDBValidator()); - } - return engine; - } - - - /** - * Gets the dictionaryDatabase attribute of the JChemPaint object - * - *@return The dictionaryDatabase value - */ - public static DictionaryDatabase getDictionaryDatabase() - { - if (dictdb == null) - { - dictdb = new DictionaryDatabase(); - try - { - File dictdir = new File(JCPPropertyHandler.getInstance().getJChemPaintDir(), "dicts"); - logger.info("User dict dir: ", dictdir); - logger.debug(" exists: ", dictdir.exists()); - logger.debug(" isDirectory: ", dictdir.isDirectory()); - if (dictdir.exists() && dictdir.isDirectory()) - { - File[] dicts = dictdir.listFiles(); - for (int i = 0; i < dicts.length; i++) - { - // loop over these files and load them - try - { - FileReader reader = new FileReader... [truncated message content] |