keyword
stringclasses
7 values
repo_name
stringlengths
8
98
file_path
stringlengths
4
244
file_extension
stringclasses
29 values
file_size
int64
0
84.1M
line_count
int64
0
1.6M
content
stringlengths
1
84.1M
language
stringclasses
14 values
2D
JChemPaint/jchempaint
app-osx/make-dmg.sh
.sh
398
18
#!/bin/bash set -e DIR=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd ) APP=$DIR/target/*.app SRCFOLDER=$DIR/target/tmp VOLNAME=JChemPaint DMGFILE=$DIR/target/$VOLNAME.dmg [ -e $SRCFOLDER ] && rm -rf $SRCFOLDER # cleanup existing mkdir $SRCFOLDER && cp -r $APP $SRCFOLDER && ln -s /Applications $SRCFOLDER hdiutil create -srcfolder $SRCFOLDER $DMGFILE -volname $VOLNAME
Shell
2D
JChemPaint/jchempaint
app-osx/codesign-app.sh
.sh
1,655
47
#!/bin/bash set -e MACOS_DEVELOPER_IDENTITY=$1 if [[ -z $MACOS_DEVELOPER_IDENTITY ]]; then echo "usage: ./codesign-dep.sh \${{ secrets.MACOS_DEVELOPER_IDENTITY }}" exit 1; fi DIR=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd ) TARGETDIR=$DIR/target APPNAME=$TARGETDIR/JChemPaint.app CLSPATH=$APPNAME/Contents/Java/classpath # these JARs have native jnilib/dylib's which need to be signed JNA=$CLSPATH/net/java/dev/jna/jna/*/jna-*.jar JNAINCHI_AARCH64=$CLSPATH/io/github/dan2097/jna-inchi-darwin-aarch64/*/jna-inchi-darwin-aarch64-*.jar JNAINCHI_X86_64=$CLSPATH/io/github/dan2097/jna-inchi-darwin-x86-64/*/jna-inchi-darwin-x86-64-*.jar FLATLAF=$CLSPATH/com/formdev/flatlaf/*/flatlaf-*.jar JCPAPPOSX=$CLSPATH/org/openscience/jchempaint/jchempaint-app-osx/*/jchempaint-app-osx-*-SNAPSHOT.jar TMPDIR=$TARGETDIR/tmp [[ -e $TMPDIR ]] && rm -rf $TMPDIR JARFILES=($JNA $JNAINCHI_AARCH64 $JNAINCHI_X86_64 $FLATLAF $JCPAPPOSX) for JARFILE in "${JARFILES[@]}"; do echo "Repacking $JARFILE" mkdir -p $TMPDIR pushd $TMPDIR jar xf $JARFILE find . -name "*.dylib" -exec codesign --verbose --force --timestamp --options=runtime --entitlements $DIR/entitlements.plist --sign $MACOS_DEVELOPER_IDENTITY --deep {} \; find . -name "*.jnilib" -exec codesign --verbose --force --timestamp --options=runtime --entitlements $DIR/entitlements.plist --sign $MACOS_DEVELOPER_IDENTITY --deep {} \; rm $JARFILE jar cf $JARFILE * popd rm -rf $TMPDIR done codesign --verbose --force --timestamp --options=runtime --entitlements $DIR/entitlements.plist --sign $MACOS_DEVELOPER_IDENTITY --deep $APPNAME
Shell
2D
JChemPaint/jchempaint
app-osx/src/main/java/org/openscience/jchempaint/OsxClipboard.java
.java
5,877
162
package org.openscience.jchempaint; import org.openscience.jchempaint.action.CopyPasteAction; import java.awt.datatransfer.Clipboard; import java.awt.datatransfer.ClipboardOwner; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.FlavorListener; import java.awt.datatransfer.Transferable; import java.awt.datatransfer.UnsupportedFlavorException; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; public class OsxClipboard extends Clipboard { static { try (InputStream in = OsxClipboard.class.getResourceAsStream("libSetClipboard.dylib")) { if (in == null) { System.err.println("Error: Could not find libSetClipboard!"); } File file = File.createTempFile("libSetClipboard", "dylib"); try (FileOutputStream fout = new FileOutputStream(file)) { byte[] buffer = new byte[4096]; int read; while ((read = in.read(buffer)) >= 0) { fout.write(buffer, 0, read); } } System.load(file.getAbsolutePath()); } catch (IOException e) { throw new RuntimeException(e); } } Clipboard delegate; public OsxClipboard(Clipboard delegate) { super(delegate.getName()); this.delegate = delegate; } public static native void setClipboard(byte[] pdfFile, byte[] svgFile, byte[] pngData, String smi); @Override public String getName() { return delegate.getName(); } @Override public synchronized Transferable getContents(Object requestor) { return delegate.getContents(requestor); } @Override public DataFlavor[] getAvailableDataFlavors() { return delegate.getAvailableDataFlavors(); } @Override public boolean isDataFlavorAvailable(DataFlavor flavor) { return delegate.isDataFlavorAvailable(flavor); } @Override public Object getData(DataFlavor flavor) throws UnsupportedFlavorException, IOException { return delegate.getData(flavor); } @Override public synchronized void addFlavorListener(FlavorListener listener) { delegate.addFlavorListener(listener); } @Override public synchronized void removeFlavorListener(FlavorListener listener) { delegate.removeFlavorListener(listener); } @Override public synchronized FlavorListener[] getFlavorListeners() { return delegate.getFlavorListeners(); } @Override public synchronized void setContents(Transferable contents, ClipboardOwner owner) { try { // if we are copying just a simple string (e.g. SMILES/MOLfile) if (contents.getTransferDataFlavors().length == 1 && contents.isDataFlavorSupported(DataFlavor.stringFlavor)) { delegate.setContents(contents, owner); return; } // we can't handle the custom mime-type via the native specific code // or more specifically I can't work out how to do it, so we set these // here then add on the PDF/SVG data. Note setting the string data // here also messes up the native logic so we leave that for the // native code (in swift) delegate.setContents(new Transferable() { @Override public DataFlavor[] getTransferDataFlavors() { return new DataFlavor[]{ CopyPasteAction.MOL_FLAVOR, CopyPasteAction.SMI_FLAVOR, CopyPasteAction.CML_FLAVOR }; } @Override public boolean isDataFlavorSupported(DataFlavor flavor) { if (!contents.isDataFlavorSupported(flavor)) return false; return flavor == CopyPasteAction.MOL_FLAVOR || flavor == CopyPasteAction.SMI_FLAVOR || flavor == CopyPasteAction.CML_FLAVOR; } @Override public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException { if (isDataFlavorSupported(flavor)) return contents.getTransferData(flavor); return null; } }, owner); if (contents.isDataFlavorSupported(CopyPasteAction.PDF_FLAVOR) && contents.isDataFlavorSupported(CopyPasteAction.SVG_FLAVOR)) { InputStream pdfData = (InputStream) contents.getTransferData(CopyPasteAction.PDF_FLAVOR); InputStream svgData = (InputStream) contents.getTransferData(CopyPasteAction.SVG_FLAVOR); String strData = (String) contents.getTransferData(DataFlavor.stringFlavor); setClipboard(toByteArray(pdfData), toByteArray(svgData), new byte[0], strData); } } catch (UnsupportedFlavorException | IOException e) { throw new RuntimeException(e); } } private byte[] toByteArray(InputStream is) { try (ByteArrayOutputStream bout = new ByteArrayOutputStream()) { byte[] buffer = new byte[4096]; int read; while ((read = is.read(buffer)) >= 0) { bout.write(buffer, 0, read); } return bout.toByteArray(); } catch (IOException e) { return new byte[0]; } } }
Java
2D
JChemPaint/jchempaint
inchi-nestedvm/src/main/java/org/openscience/jchempaint/inchi/StdInChIGenerator.java
.java
8,409
242
/* * Copyright (C) 2009 Mark Rijnbeek <mark_rynbeek@users.sf.net> * * Contact: cdk-devel@lists.sourceforge.net * * 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.jchempaint.inchi; import org.iupac.StdInChI; import org.openscience.cdk.exception.CDKException; import org.openscience.cdk.interfaces.IAtomContainer; import org.openscience.cdk.io.MDLV2000Writer; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintStream; import java.io.StringWriter; import java.util.ArrayList; import java.util.List; /** * Generates InChI data using a C->Java conversion of the InChI command * line tool 'stdinchi'.<br> * Conversion of this C program was done with NestedVM, an example of this * particular conversion can be found here:<br> * http://depth-first.com/articles/2007/12/03/.<br> * General info is at http://wiki.brianweb.net/NestedVM/QuickStartGuide. * <br><br> * This class does file based operations, all files are temporary and * are deleted afterwards.<br> * Thread safety is hard to enforce with file based operations, but the class * does work on uniquely named files per request. * <br> * * @author Mark Rijnbeek * */ public class StdInChIGenerator extends StdInChITool { /* * Booleans for structure perception */ /** * Set to true for option -NEWPSOFF: Both ends of wedge point to stereo centers. */ private boolean bothWedgeEndsPointToStereoCenter=false; /** * Set to true for option -DoNotAddH: Don't add H according to usual valences: all H are explicit. */ private boolean hydrogensNotAdded=false; /** * Set to true for option -SNon: Exclude stereo */ private boolean stereoExcluded=false; /** * Generate InChI for a given atom container.<BR> * Take current user's home directory as temporary dir.<BR> * Overloads {@linkplain #generateInchi(org.openscience.cdk.interfaces.IAtomContainer, String)} * * @param molfile * @return InChI generated from Molfile * @throws java.io.IOException * @throws org.openscience.cdk.exception.CDKException */ public InChI generateInchi(IAtomContainer atc) throws IOException, CDKException { String workingDir=System.getProperty("user.dir")+ System.getProperty("file.separator"); return generateInchi(atc,workingDir); } /** * Generate InChI for a give atom container.<BR> * Temporary working directory provided as argument. * * @param molfile * @param workingDir working directory including a final slash * @return InChI generated from Molfile * @throws java.io.IOException * @throws org.openscience.cdk.exception.CDKException */ public InChI generateInchi(IAtomContainer atc, String workingDir) throws IOException, CDKException { //Prevent standard error being written with detailed log PrintStream stErr = System.err; System.setErr(new PrintStream(new ByteArrayOutputStream())); InChI inchi = new InChI(); // Use random file numbering to make class thread safe(r) String tmpFileBase = "cdk"+getFileSeq(); // Set up temporary file names for generator to work with String tmpMolFile = workingDir + tmpFileBase + MOLFILE_EXTENSION; String tmpOutFile = workingDir + tmpFileBase + OUTFILE_EXTENSION; String tmpLogFile = workingDir + tmpFileBase + LOGFILE_EXTENSION; String tmpPrbFile = workingDir + tmpFileBase + PROBFILE_EXTENSION; try { StringWriter writer = new StringWriter(); MDLV2000Writer mdlWriter = new MDLV2000Writer(writer); mdlWriter.write(atc); String mdl = writer.toString(); mdlWriter.close(); //Write the Molfile String into a file for the generator to work on. FileWriter fstream = new FileWriter(tmpMolFile); BufferedWriter out = new BufferedWriter(fstream); out.write(mdl); out.close(); //Prepare an array for the InChI generator. List<String> argsList = new ArrayList<String>(); argsList.add(""); argsList.add(tmpMolFile); argsList.add(tmpOutFile); argsList.add(tmpLogFile); argsList.add(tmpPrbFile); argsList.add("-Key"); if(bothWedgeEndsPointToStereoCenter) argsList.add("-NEWPSOFF"); if(hydrogensNotAdded) argsList.add("-DoNotAddH"); if(stereoExcluded) argsList.add("-SNon"); String[] args = new String[argsList.size()]; args=argsList.toArray(args); //Call the actual InChI generation. StdInChI stdinchi = new StdInChI(); stdinchi.run(args); // Read the generated InChi from the output file FileInputStream fInstream = new FileInputStream(tmpOutFile); DataInputStream in = new DataInputStream(fInstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; while ((strLine = br.readLine()) != null) { if (strLine.startsWith("InChI=")) { inchi.setInChI(strLine); } if (strLine.startsWith("AuxInfo=")) { inchi.setAuxInfo(strLine); } if (strLine.startsWith("InChIKey=") ) { inchi.setKey(strLine); } } in.close(); if (inchi.getInChI()==null) { //Something went wrong .. pick up the error from the log file String errMsg=getErrorMsg (tmpLogFile); if(!errMsg.equals("")) { throw new CDKException (errMsg); } else { throw new CDKException ("Unknown problem with InChI generation."); } } } finally { /* Delete any temporary files */ deleteFileIfExists(tmpMolFile); deleteFileIfExists(tmpOutFile); deleteFileIfExists(tmpLogFile); deleteFileIfExists(tmpPrbFile); System.setErr(stErr); } return inchi; } public boolean isBothWedgeEndsPointToStereoCenter() { return bothWedgeEndsPointToStereoCenter; } public void setBothWedgeEndsPointToStereoCenter( boolean bothWedgeEndsPointToStereoCenter) { this.bothWedgeEndsPointToStereoCenter = bothWedgeEndsPointToStereoCenter; } public boolean isHydrogensNotAdded() { return hydrogensNotAdded; } public void setHydrogensNotAdded(boolean hydrogensNotAdded) { this.hydrogensNotAdded = hydrogensNotAdded; } public boolean isStereoExcluded() { return stereoExcluded; } public void setStereoExcluded(boolean stereoExcluded) { this.stereoExcluded = stereoExcluded; } }
Java
2D
JChemPaint/jchempaint
inchi-nestedvm/src/main/java/org/openscience/jchempaint/inchi/StdInChIParser.java
.java
7,592
205
/* * Copyright (C) 2009 Mark Rijnbeek <mark_rynbeek@users.sf.net> * * Contact: cdk-devel@lists.sourceforge.net * * 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.jchempaint.inchi; import org.iupac.StdInChI; import org.openscience.cdk.CDKConstants; import org.openscience.cdk.ChemFile; import org.openscience.cdk.ChemObject; import org.openscience.cdk.exception.CDKException; import org.openscience.cdk.interfaces.IAtomContainer; import org.openscience.cdk.io.MDLV2000Reader; import org.openscience.cdk.layout.StructureDiagramGenerator; import org.openscience.cdk.tools.manipulator.ChemFileManipulator; import java.io.BufferedWriter; import java.io.ByteArrayOutputStream; import java.io.FileInputStream; import java.io.FileWriter; import java.io.InputStream; import java.io.PrintStream; import java.util.ArrayList; import java.util.List; /** * Parses an InChI string into an IAtomContainer using a C->Java conversion * of the InChI command line tool 'stdinchi'.<br> * Conversion of this C program was done with NestedVM, an example of this * particular conversion can be found here:<br> * http://depth-first.com/articles/2007/12/03/.<br> * General info is at http://wiki.brianweb.net/NestedVM/QuickStartGuide. * <br><br> * This class does file based operations, all files are temporary and * are deleted afterwards.<br> * Thread safety is hard to enforce with file based operations, but the class * does work on uniquely named files per request. * <br> * * @author Mark Rijnbeek * */ public class StdInChIParser extends StdInChITool{ /** * Generate InChI for a given atom container.<BR> * Take current user's home directory as temporary dir.<BR> * Overloads {@linkplain #parseInchi(String, String)}. * * @param inchi to convert to an IAtomContainer * @return CDK IAtomContainer * @throws Exception */ public IAtomContainer parseInchi(String inchi)throws Exception { String workingDir=System.getProperty("user.dir")+ System.getProperty("file.separator"); return parseInchi(inchi,workingDir); } /** * Generate InChI for a given atom container.<BR> * Temporary working directory provided as argument. * @param inchi to convert to an IAtomContainer * @param workingDir * @return CDK IAtomContainer * @throws Exception */ public IAtomContainer parseInchi(String inchi, String workingDir) throws Exception { //Prevent standard error being written with detailed log PrintStream stErr = System.err; System.setErr(new PrintStream(new ByteArrayOutputStream())); IAtomContainer atc=null; // Use random file numbering to make class thread safe(r) String tmpFileBase = "cdk"+getFileSeq(); //System.out.println(tmpFileBase); // Set up temporary file names for generator to work with String tmpInFile = workingDir + tmpFileBase + INFILE_EXTENSION; String tmpOutFile = workingDir + tmpFileBase + OUTFILE_EXTENSION; String tmpMolFile = workingDir + tmpFileBase + MOLFILE_EXTENSION; String tmpLogFile = workingDir + tmpFileBase + LOGFILE_EXTENSION; String tmpPrbFile = workingDir + tmpFileBase + PROBFILE_EXTENSION; try { //From InChI to full InChI ----------------------------------------- // write user InChi to file BufferedWriter out = new BufferedWriter(new FileWriter(tmpInFile)); out.write(inchi+eol); out.close(); //Prepare an array for the InChI generator. List<String> argsList = new ArrayList<String>(); argsList.add(""); argsList.add(tmpInFile); argsList.add(tmpOutFile); argsList.add(tmpLogFile); argsList.add(tmpPrbFile); argsList.add("-InChI2Struct"); String[] args = new String[argsList.size()]; args=argsList.toArray(args); //Call to make the full InChI file based on user's basic InChI StdInChI stdinchi = new StdInChI(); stdinchi.run(args); //Check if something went wrong .. pick up any error from log file String errMsg=getErrorMsg (tmpLogFile); if(!errMsg.equals("")) { throw new CDKException (errMsg); } //From full InChI to Molfile --------------------------------------- argsList = new ArrayList<String>(); argsList.add(""); argsList.add(tmpOutFile); argsList.add(tmpMolFile); argsList.add(tmpLogFile); argsList.add(tmpPrbFile); argsList.add("-OutputSDF"); args = new String[argsList.size()]; args=argsList.toArray(args); //Call to make the full InChI file StdInChI stdinchi2 = new StdInChI(); stdinchi2.run(args); //Check if something went wrong .. pick up any error from log file errMsg=getErrorMsg (tmpLogFile); if(!errMsg.equals("")) { throw new CDKException (errMsg); } //From Molfile to Atom container ----------------------------------- InputStream ins = new FileInputStream(tmpMolFile); MDLV2000Reader reader = new MDLV2000Reader(ins); ChemFile chemFile = (ChemFile)reader.read((ChemObject)new ChemFile()); reader.close(); atc= ChemFileManipulator.getAllAtomContainers(chemFile).get(0); atc.setProperty(CDKConstants.TITLE, null); // Generate coordinates for the atom container StructureDiagramGenerator sdg = new StructureDiagramGenerator((IAtomContainer)atc); sdg.generateCoordinates(); } finally { //Always delete any temporary files deleteFileIfExists(tmpInFile); deleteFileIfExists(tmpOutFile); deleteFileIfExists(tmpMolFile); deleteFileIfExists(tmpLogFile); deleteFileIfExists(tmpPrbFile); System.setErr(stErr); } return atc; } public static void main(String[] args) throws Exception { StdInChIParser parser = new StdInChIParser(); IAtomContainer m = parser.parseInchi("InChI=1S/C2H6/c1-2/h1-2H3"); for (int i = 0; i < 10; i++) { StdInChIGenerator gen = new StdInChIGenerator(); gen.generateInchi(m); } } }
Java
2D
JChemPaint/jchempaint
inchi-nestedvm/src/main/java/org/openscience/jchempaint/inchi/StdInChIHandler.java
.java
930
31
package org.openscience.jchempaint.inchi; import org.openscience.cdk.exception.CDKException; import org.openscience.cdk.interfaces.IAtomContainer; import java.io.IOException; /** * @author John May */ public final class StdInChIHandler implements InChIHandler { @Override public IAtomContainer parse(InChI inchi) throws CDKException { try { return new StdInChIParser().parseInchi(inchi.getInChI()); } catch (Exception e) { throw new CDKException("Could not parse InChI", e); } } @Override public InChI generate(IAtomContainer container) throws CDKException { try { return new StdInChIGenerator().generateInchi(container); } catch (CDKException e) { throw new CDKException("Could not generate InChI", e); } catch (IOException e) { throw new CDKException("Could not generate InChI", e); } } }
Java
2D
JChemPaint/jchempaint
inchi-nestedvm/src/main/java/org/openscience/jchempaint/inchi/StdInChIReader.java
.java
2,938
83
/* * Copyright (C) 2009 Mark Rijnbeek <mark_rynbeek@users.sf.net> * * Contact: cdk-devel@lists.sourceforge.net * * 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.jchempaint.inchi; import org.openscience.cdk.AtomContainerSet; import org.openscience.cdk.ChemModel; import org.openscience.cdk.exception.CDKException; import org.openscience.cdk.interfaces.IAtomContainer; import org.openscience.cdk.interfaces.IAtomContainerSet; import org.openscience.cdk.interfaces.IChemModel; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.URL; /** * Class to read an InChI file which expected to be some text file * with InChI=.... lines in there. These lines are fed into the StdInChIParser * * @author markr * */ public class StdInChIReader { /** * Read the InChI=.. lines from a give text file containing InChI(s) * @param url * @return chemModel with molecule set with molecule(s) created using InChI * @throws org.openscience.cdk.exception.CDKException */ public static IChemModel readInChI(URL url) throws CDKException { IChemModel chemModel = new ChemModel(); try { IAtomContainerSet moleculeSet = new AtomContainerSet(); chemModel.setMoleculeSet(moleculeSet); StdInChIParser parser = new StdInChIParser(); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String line; while ((line = in.readLine()) != null) { if (line.toLowerCase().startsWith("inchi=")) { IAtomContainer atc = parser.parseInchi(line); moleculeSet.addAtomContainer(atc); } } in.close(); } catch (Exception e) { e.printStackTrace(); throw new CDKException(e.getMessage()); } return chemModel; } }
Java
2D
JChemPaint/jchempaint
inchi-nestedvm/src/main/java/org/openscience/jchempaint/inchi/StdInChITool.java
.java
3,534
104
/* * Copyright (C) 2009 Mark Rijnbeek <mark_rynbeek@users.sf.net> * * Contact: cdk-devel@lists.sourceforge.net * * 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.jchempaint.inchi; import java.io.BufferedReader; import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; /** * Abstract class offering common functionality when * invoking {@linkplain org.iupac.StdInChI}. * * @author markr * */ abstract class StdInChITool { final static String INFILE_EXTENSION = ".in"; final static String OUTFILE_EXTENSION = ".out"; final static String MOLFILE_EXTENSION = ".mol"; final static String LOGFILE_EXTENSION = ".log"; final static String PROBFILE_EXTENSION = ".prb"; public static String eol = System.getProperty("line.separator"); private static int seqNum=0; /** * Helper method to issue a file sequence number for a temporary file * name required by StdInChI class * @return file sequence number */ synchronized int getFileSeq () { if (seqNum>=99999) seqNum=0; return ++seqNum; } /** * Helper method for InChi conversion, gets rid of temporary files. * @param fileName * @throws java.io.IOException */ void deleteFileIfExists(String fileName) throws IOException { File f = new File(fileName); if (f.exists()) { boolean success = f.delete(); if (!success) { throw new IOException ("Warning - could not remove temporary file " + fileName); } } } /** * Helper method to distill error message from StdInChI log file. * @param tmpLogFile * @return * @throws java.io.IOException */ String getErrorMsg (String tmpLogFile) throws IOException { StringBuffer msg = new StringBuffer(); File f = new File(tmpLogFile); if (f.exists()) { FileInputStream fInstream = new FileInputStream(tmpLogFile); DataInputStream in = new DataInputStream(fInstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; while ((strLine = br.readLine()) != null) { if (strLine.contains("Syntax error")||strLine.contains("Error")) { msg.append(strLine+eol); } } in.close(); } return msg.toString(); } }
Java
2D
JChemPaint/jchempaint
inchi-nestedvm/src/test/java/org/openscience/jchempaint/inchi/StdInChIGeneratorTest.java
.java
9,424
259
package org.openscience.jchempaint.inchi; import javax.vecmath.Point2d; import javax.vecmath.Point3d; import org.junit.Assert; import org.junit.Test; import org.openscience.cdk.Atom; import org.openscience.cdk.AtomContainer; import org.openscience.cdk.Bond; import org.openscience.cdk.interfaces.IAtom; import org.openscience.cdk.interfaces.IAtomContainer; import org.openscience.cdk.interfaces.IBond; public class StdInChIGeneratorTest { protected StdInChIGenerator gen = new StdInChIGenerator(); /** * Tests element name is correctly passed to InChI. * * @throws Exception */ @Test public void testGetInchiFromChlorineAtom() throws Exception { IAtomContainer ac = new AtomContainer(); ac.addAtom(new Atom("Cl")); gen.setHydrogensNotAdded(true); Assert.assertEquals(gen.generateInchi(ac).getInChI(), "InChI=1S/Cl"); gen.setHydrogensNotAdded(false); } /** * Tests charge is correctly passed to InChI. * * @throws Exception */ @Test public void testGetInchiFromLithiumIon() throws Exception { IAtomContainer ac = new AtomContainer(); IAtom a = new Atom("Li"); a.setFormalCharge(+1); ac.addAtom(a); gen.setHydrogensNotAdded(true); Assert.assertEquals(gen.generateInchi(ac).getInChI(), "InChI=1S/Li/q+1"); gen.setHydrogensNotAdded(false); } /** * Tests isotopic mass is correctly passed to InChI. * * @throws Exception */ @Test public void testGetInchiFromChlorine37Atom() throws Exception { IAtomContainer ac = new AtomContainer(); IAtom a = new Atom("Cl"); a.setMassNumber(37); ac.addAtom(a); gen.setHydrogensNotAdded(true); Assert.assertEquals(gen.generateInchi(ac).getInChI(), "InChI=1S/Cl/i1+2"); gen.setHydrogensNotAdded(false); } /** * Tests implicit hydrogen count is correctly passed to InChI. * * @throws Exception */ @Test public void testGetInchiFromHydrogenChlorideImplicitH() throws Exception { IAtomContainer ac = new AtomContainer(); IAtom a = new Atom("Cl"); a.setImplicitHydrogenCount(1); ac.addAtom(a); Assert.assertEquals(gen.generateInchi(ac).getInChI(), "InChI=1S/ClH/h1H"); } /** * Tests radical state is correctly passed to InChI. * * @throws Exception */ //@Test public void testGetInchiFromMethylRadical() throws Exception { // IAtomContainer ac = new AtomContainer(); // IAtom a = new Atom("C"); // a.setImplicitHydrogenCount(3); // ac.addAtom(a); // ac.addSingleElectron(new SingleElectron(a)); // Assert.assertEquals(gen.generateInchi(ac).getInChI(), "InChI=1S/CH3/h1H3"); // //} /** * Tests single bond is correctly passed to InChI. * * @throws Exception */ @Test public void testGetInchiFromEthane() throws Exception { IAtomContainer ac = new AtomContainer(); IAtom a1 = new Atom("C"); IAtom a2 = new Atom("C"); a1.setImplicitHydrogenCount(3); a2.setImplicitHydrogenCount(3); ac.addAtom(a1); ac.addAtom(a2); ac.addBond(new Bond(a1, a2, IBond.Order.SINGLE)); InChI inchi = gen.generateInchi(ac); Assert.assertEquals(inchi.getInChI(), "InChI=1S/C2H6/c1-2/h1-2H3"); Assert.assertEquals("InChIKey=OTMSDBZUPAUEDD-UHFFFAOYSA-N", inchi.getKey()); } /** * Tests double bond is correctly passed to InChI. * * @throws Exception */ @Test public void testGetInchiFromEthene() throws Exception { IAtomContainer ac = new AtomContainer(); IAtom a1 = new Atom("C"); IAtom a2 = new Atom("C"); a1.setImplicitHydrogenCount(2); a2.setImplicitHydrogenCount(2); ac.addAtom(a1); ac.addAtom(a2); ac.addBond(new Bond(a1, a2, IBond.Order.DOUBLE)); Assert.assertEquals(gen.generateInchi(ac).getInChI(), "InChI=1S/C2H4/c1-2/h1-2H2"); } /** * Tests triple bond is correctly passed to InChI. * * @throws Exception */ @Test public void testGetInchiFromEthyne() throws Exception { IAtomContainer ac = new AtomContainer(); IAtom a1 = new Atom("C"); IAtom a2 = new Atom("C"); a1.setImplicitHydrogenCount(1); a2.setImplicitHydrogenCount(1); ac.addAtom(a1); ac.addAtom(a2); ac.addBond(new Bond(a1, a2, IBond.Order.TRIPLE)); Assert.assertEquals(gen.generateInchi(ac).getInChI(), "InChI=1S/C2H2/c1-2/h1-2H"); } /** * Tests 2D coordinates are correctly passed to InChI. * * @throws Exception */ @Test public void testGetInchiEandZ12Dichloroethene2D() throws Exception { // (E)-1,2-dichloroethene IAtomContainer acE = new AtomContainer(); IAtom a1E = new Atom("C", new Point2d(2.866, -0.250)); IAtom a2E = new Atom("C", new Point2d(3.732, 0.250)); IAtom a3E = new Atom("Cl", new Point2d(2.000, 2.500)); IAtom a4E = new Atom("Cl", new Point2d(4.598, -0.250)); a1E.setImplicitHydrogenCount(1); a2E.setImplicitHydrogenCount(1); acE.addAtom(a1E); acE.addAtom(a2E); acE.addAtom(a3E); acE.addAtom(a4E); acE.addBond(new Bond(a1E, a2E, IBond.Order.DOUBLE)); acE.addBond(new Bond(a1E, a3E, IBond.Order.SINGLE)); acE.addBond(new Bond(a2E, a4E, IBond.Order.SINGLE)); Assert.assertEquals(gen.generateInchi(acE).getInChI(), "InChI=1S/C2H2Cl2/c3-1-2-4/h1-2H/b2-1+"); // (Z)-1,2-dichloroethene IAtomContainer acZ = new AtomContainer(); IAtom a1Z = new Atom("C", new Point2d(2.866, -0.440)); IAtom a2Z = new Atom("C", new Point2d(3.732, 0.060)); IAtom a3Z = new Atom("Cl", new Point2d(2.000, 0.060)); IAtom a4Z = new Atom("Cl", new Point2d(3.732, 1.060)); a1Z.setImplicitHydrogenCount(1); a2Z.setImplicitHydrogenCount(1); acZ.addAtom(a1Z); acZ.addAtom(a2Z); acZ.addAtom(a3Z); acZ.addAtom(a4Z); acZ.addBond(new Bond(a1Z, a2Z, IBond.Order.DOUBLE)); acZ.addBond(new Bond(a1Z, a3Z, IBond.Order.SINGLE)); acZ.addBond(new Bond(a2Z, a4Z, IBond.Order.SINGLE)); Assert.assertEquals(gen.generateInchi(acZ).getInChI(), "InChI=1S/C2H2Cl2/c3-1-2-4/h1-2H/b2-1-"); } /** * Tests 3D coordinates are correctly passed to InChI. * * @throws Exception */ @Test public void testGetInchiFromLandDAlanine3D() throws Exception { // L-Alanine IAtomContainer acL = new AtomContainer(); IAtom a1L = new Atom("C", new Point3d(-0.358, 0.819, 20.655)); IAtom a2L = new Atom("C", new Point3d(-1.598, -0.032, 20.905)); IAtom a3L = new Atom("N", new Point3d(-0.275, 2.014, 21.574)); IAtom a4L = new Atom("C", new Point3d(0.952, 0.043, 20.838)); IAtom a5L = new Atom("O", new Point3d(-2.678, 0.479, 21.093)); IAtom a6L = new Atom("O", new Point3d(-1.596, -1.239, 20.958)); a1L.setImplicitHydrogenCount(1); a3L.setImplicitHydrogenCount(2); a4L.setImplicitHydrogenCount(3); a5L.setImplicitHydrogenCount(1); acL.addAtom(a1L); acL.addAtom(a2L); acL.addAtom(a3L); acL.addAtom(a4L); acL.addAtom(a5L); acL.addAtom(a6L); acL.addBond(new Bond(a1L, a2L, IBond.Order.SINGLE)); acL.addBond(new Bond(a1L, a3L, IBond.Order.SINGLE)); acL.addBond(new Bond(a1L, a4L, IBond.Order.SINGLE)); acL.addBond(new Bond(a2L, a5L, IBond.Order.SINGLE)); acL.addBond(new Bond(a2L, a6L, IBond.Order.DOUBLE)); Assert.assertEquals(gen.generateInchi(acL).getInChI(), "InChI=1S/C3H7NO2/c1-2(4)3(5)6/h2H,4H2,1H3,(H,5,6)/t2-/m0/s1"); // D-Alanine IAtomContainer acD = new AtomContainer(); IAtom a1D = new Atom("C", new Point3d(0.358, 0.819, 20.655)); IAtom a2D = new Atom("C", new Point3d(1.598, -0.032, 20.905)); IAtom a3D = new Atom("N", new Point3d(0.275, 2.014, 21.574)); IAtom a4D = new Atom("C", new Point3d(-0.952, 0.043, 20.838)); IAtom a5D = new Atom("O", new Point3d(2.678, 0.479, 21.093)); IAtom a6D = new Atom("O", new Point3d(1.596, -1.239, 20.958)); a1D.setImplicitHydrogenCount(1); a3D.setImplicitHydrogenCount(2); a4D.setImplicitHydrogenCount(3); a5D.setImplicitHydrogenCount(1); acD.addAtom(a1D); acD.addAtom(a2D); acD.addAtom(a3D); acD.addAtom(a4D); acD.addAtom(a5D); acD.addAtom(a6D); acD.addBond(new Bond(a1D, a2D, IBond.Order.SINGLE)); acD.addBond(new Bond(a1D, a3D, IBond.Order.SINGLE)); acD.addBond(new Bond(a1D, a4D, IBond.Order.SINGLE)); acD.addBond(new Bond(a2D, a5D, IBond.Order.SINGLE)); acD.addBond(new Bond(a2D, a6D, IBond.Order.DOUBLE)); //"InChI=1S/C3H7NO2/c1-2(4)3(5)6/h2H,4H2,1H3,(H,5,6)/t2-/m1/s1"); Assert.assertEquals(gen.generateInchi(acL).getInChI(), "InChI=1S/C3H7NO2/c1-2(4)3(5)6/h2H,4H2,1H3,(H,5,6)/t2-/m0/s1"); } }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/GT.java
.java
14,089
429
/* $RCSfile$ * $Author: nicove $ * $Date: 2008-11-08 09:57:38 +0000 (Sat, 08 Nov 2008) $ * $Revision: 10261 $ * * Copyright (C) 2005 Miguel, Jmol Development, www.jmol.org * * Contact: miguel@jmol.org * * This library 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. * * This library 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 library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ package org.openscience.jchempaint; import org.openscience.cdk.tools.ILoggingTool; import org.openscience.cdk.tools.LoggingToolFactory; import java.text.MessageFormat; import java.util.Locale; import java.util.MissingResourceException; import java.util.ResourceBundle; public class GT { private static boolean ignoreApplicationBundle = false; private static GT getTextWrapper; private ResourceBundle[] translationResources = null; private int translationResourcesCount = 0; private boolean doTranslate = true; private String language; private static ILoggingTool logger = LoggingToolFactory.createLoggingTool(GT.class); public GT(String la) { getTranslation(la); } private GT() { getTranslation(null); } // ============= // Language list // ============= public static class Language { public final String code; public final String language; public final boolean display; public Language(String code, String language, boolean display) { this.code = code; this.language = language; this.display = display; } } private static Language[] languageList; //private static String languagePath; public static Language[] getLanguageList() { return (languageList != null ? languageList : getTextWrapper().createLanguageList()); } /** * This is the place to put the list of supported languages. It is accessed * by JmolPopup to create the menu list. Note that the names are in GT._ * even though we set doTranslate false. That ensures that the language name * IN THIS LIST is untranslated, but it provides the code xgettext needs in * order to provide the list of names that will need translation by translators * (the .po files). Later, in JmolPopup.updateLanguageMenu(), GT._() is used * again to create the actual, localized menu item name. * * list order: * * The order presented here is the order in which the list will be presented in the * popup menu. In addition, the order of variants is significant. In all cases, place * common-language entries in the following order: * * la_co_va * la_co * la * * In addition, there really is no need for "la" by itself. Every translator introduces * a bias from their originating country. It would be perfectly fine if we had NO "la" * items, and just la_co. Thus, we could have just: * * pt_BR * pt_PT * * In this case, the "default" language translation should be entered LAST. * * If a user selects pt_ZQ, the code below will find (a) that we don't support pt_ZQ, * (b) that we don't support pt_ZQ_anything, (c) that we don't support pt, and, finally, * that we do support pt_PT, and it will select that one, returning to the user the message * that language = "pt_PT" instead of pt_ZQ. * * For that matter, we don't even need anything more than * * la_co_va * * because the algorithm will track that down from anything starting with la, and in all cases * find the closest match. * * Introduced in Jmol 11.1.34 * Author Bob Hanson May 7, 2007 * @return list of codes and untranslated names */ synchronized private Language[] createLanguageList() { boolean wasTranslating = doTranslate; doTranslate = false; languageList = new Language[] { new Language("en_US", GT.get("American English"), true), // global default for "en" will be "en_US" new Language("ar", GT.get("Arabic"), true), new Language("pt_BR", GT.get("Brazilian Portuguese"), true), new Language("ca", GT.get("Catalan"), true), new Language("zh", GT.get("Chinese"), true), new Language("cs", GT.get("Czech"), true), new Language("nl", GT.get("Dutch"), true), new Language("de", GT.get("German"), true), new Language("hu", GT.get("Hungarian"), true), new Language("pl", GT.get("Polish"), true), new Language("ru", GT.get("Russian"), true), new Language("es", GT.get("Spanish"), true), new Language("th", GT.get("Thai"), true), }; doTranslate = wasTranslating; return languageList; } private String getSupported(String languageCode, boolean isExact) { if (languageCode == null) return null; if (languageList == null) createLanguageList(); for (int i = 0; i < languageList.length; i++) { if (languageList[i].code.equalsIgnoreCase(languageCode)) return languageList[i].code; } return (isExact ? null : findClosest(languageCode)); } /** * * @param la * @return a localization of the desired language, but not it exactly */ private String findClosest(String la) { for (int i = languageList.length; --i >= 0; ) { if (languageList[i].code.startsWith(la)) return languageList[i].code; } return null; } public static String getLanguage() { return getTextWrapper().language; } synchronized private void getTranslation(String langCode) { Locale locale; translationResources = null; translationResourcesCount = 0; getTextWrapper = this; if (langCode != null && langCode.length() == 0) langCode="none"; if (langCode != null) language = langCode; if ("none".equals(language)) language = null; if (language == null && (locale = Locale.getDefault()) != null) { language = locale.getLanguage(); if (locale.getCountry() != null) { language += "_" + locale.getCountry(); if (locale.getVariant() != null && locale.getVariant().length() > 0) language += "_" + locale.getVariant(); } } if (language == null) language = "en"; int i; String la = language; String la_co = language; String la_co_va = language; if ((i = language.indexOf("_")) >= 0) { la = la.substring(0, i); if ((i = language.indexOf("_", ++i)) >= 0) { la_co = language.substring(0, i); } else { la_co_va = null; } } else { la_co = null; la_co_va = null; } /* * find the best match. In each case, if the match is not found, * but a variation at the next level higher exists, pick that variation. * So, for example, if fr_CA does not exist, but fr_FR does, then * we choose fr_FR, because that is taken as the "base" class for French. * * Or, if the language requested is "fr", and there is no fr.po, but there * is an fr_FR.po, then return that. * * Thus, the user is informed of which country/variant is in effect, * if they want to know. * */ if ((language = getSupported(la_co_va, false)) == null && (language = getSupported(la_co, false)) == null && (language = getSupported(la, false)) == null) { language = "en"; logger.debug(language + " not supported -- using en"); return; } la_co_va = null; la_co = null; switch (language.length()) { case 2: la = language; break; case 5: la_co = language; la = language.substring(0, 2); break; default: la_co_va = language; la_co = language.substring(0, 5); la = language.substring(0, 2); } /* * Time to determine exactly what .po files we actually have. * No need to check a file twice. * */ la_co = getSupported(la_co, false); la = getSupported(la, false); if (la == la_co || "en_US".equals(la)) la = null; if (la_co == la_co_va) la_co = null; if ("en_US".equals(la_co)) return; logger.debug("Instantiating gettext wrapper for " + language + " using files for language:" + la + " country:" + la_co + " variant:" + la_co_va); if (!ignoreApplicationBundle) addBundles("Jmol", la_co_va, la_co, la); addBundles("JmolApplet", la_co_va, la_co, la); } private void addBundles(String type, String la_co_va, String la_co, String la) { try { String className = "app.i18n"; if (la_co_va != null) addBundle(className, la_co_va); if (la_co != null) addBundle(className, la_co); if (la != null) addBundle(className, la); } catch (Exception exception) { logger.error("Some exception occurred!", exception); translationResources = null; translationResourcesCount = 0; } } private void addBundle(String className, String name) { Class<?> bundleClass = null; className += ".Messages_" + name; // if (languagePath != null // && !ZipUtil.isZipFile(languagePath + "_i18n_" + name + ".jar")) // return; try { bundleClass = Class.forName(className); } catch (Throwable e) { logger.error("GT could not find the class " + className); } if (bundleClass == null || !ResourceBundle.class.isAssignableFrom(bundleClass)) return; try { ResourceBundle myBundle = (ResourceBundle) bundleClass.newInstance(); if (myBundle != null) { if (translationResources == null) { translationResources = new ResourceBundle[8]; translationResourcesCount = 0; } translationResources[translationResourcesCount] = myBundle; translationResourcesCount++; logger.debug("GT adding " + className); } } catch (IllegalAccessException e) { logger.warn("Illegal Access Exception: " + e.getMessage()); } catch (InstantiationException e) { logger.warn("Instantiation Excaption: " + e.getMessage()); } } private static GT getTextWrapper() { return (getTextWrapper == null ? getTextWrapper = new GT() : getTextWrapper); } public static void ignoreApplicationBundle() { ignoreApplicationBundle = true; } public static void setDoTranslate(boolean TF) { getTextWrapper().doTranslate = TF; } public static boolean getDoTranslate() { return getTextWrapper().doTranslate; } public static String get(String string) { return getTextWrapper().getString(string); } public static String get(String string, String item) { return getTextWrapper().getString(string, new Object[] { item }); } public static String get(String string, int item) { return getTextWrapper().getString(string, new Object[] { new Integer(item) }); } public static String get(String string, Object[] objects) { return getTextWrapper().getString(string, objects); } //forced translations public static String get(String string, boolean t) { return get(string, (Object[]) null, t); } public static String get(String string, String item, boolean t) { return get(string, new Object[]{item}); } public static String get(String string, int item, boolean t) { return get(string, new Object[]{new Integer(item)}); } public static synchronized String get(String string, Object[] objects, boolean t) { boolean wasTranslating; if (!(wasTranslating = getTextWrapper().doTranslate)) setDoTranslate(true); String str = (objects == null ? get(string) : get(string, objects)); if (!wasTranslating) setDoTranslate(false); return str; } public static String getStringNoExtraction(String string) { return getTextWrapper().getString(string); } private String getString(String string) { if (!doTranslate || translationResourcesCount == 0) return string; for (int bundle = 0; bundle < translationResourcesCount; bundle++) { try { String trans = translationResources[bundle].getString(string); return trans; } catch (MissingResourceException e) { // Normal } } logger.info("No trans, using default: " + string); return string; } private String getString(String string, Object[] objects) { String trans = null; if (!doTranslate) return MessageFormat.format(string, objects); for (int bundle = 0; bundle < translationResourcesCount; bundle++) { try { trans = MessageFormat.format(translationResources[bundle] .getString(string), objects); return trans; } catch (MissingResourceException e) { // Normal } } trans = MessageFormat.format(string, objects); if (translationResourcesCount > 0) { logger.debug("No trans, using default: " + trans); } return trans; } public static String escapeHTML(String msg) { char ch; for (int i = msg.length(); --i >= 0;) if ((ch = msg.charAt(i)) > 0x7F) { msg = msg.substring(0, i) + "&#" + ((int)ch) + ";" + msg.substring(i + 1); } return msg; } public static void setLanguagePath(String languagePath) { //GT.languagePath = languagePath; } public static void setLanguage(String language){ getTextWrapper = new GT(language); } }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/JChemPaintMenuHelper.java
.java
14,645
334
package org.openscience.jchempaint; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.Image; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.MissingResourceException; import java.util.Properties; import java.util.Set; import javax.swing.ImageIcon; import javax.swing.JCheckBoxMenuItem; import javax.swing.JComponent; import javax.swing.JMenu; import javax.swing.JMenuItem; import javax.swing.JPopupMenu; import javax.swing.KeyStroke; import javax.swing.event.MenuEvent; import javax.swing.event.MenuListener; import org.openscience.cdk.config.Isotopes; import org.openscience.cdk.interfaces.IAtom; import org.openscience.cdk.interfaces.IIsotope; import org.openscience.cdk.tools.ILoggingTool; import org.openscience.cdk.tools.LoggingToolFactory; import org.openscience.jchempaint.action.JCPAction; /** * A class containing various helper methods used in JChemPaintMenuBar and JChemPaintPopupMenu. * */ public class JChemPaintMenuHelper { private static ILoggingTool logger = LoggingToolFactory.createLoggingTool(JChemPaintMenuHelper.class); private JCPAction jcpaction; private static List<String> usedKeys; /** * Constructor for JChemPaintMenuHelper */ public JChemPaintMenuHelper(){ usedKeys = new ArrayList<String>(); } /** * Return the JCPAction instance associated with this JCPPanel. * * @return The jCPAction value */ private JCPAction getJCPAction() { if (jcpaction == null) { jcpaction = new JCPAction(); } return jcpaction; } /** * Returns the definition of the subitems of a menu as in the properties files. * * @param key The key for which subitems to return * @param guiString The string identifying the gui to build (i. e. the properties file to use) * @return The resource string */ public String getMenuResourceString(String key, String guiString) { String str; try { str = JCPPropertyHandler.getInstance(true).getGUIDefinition(guiString).getString(key); } catch (MissingResourceException mre) { str = null; } return str; } /** * Creates a JMenu given by a String with all the MenuItems specified in the * properties file. * * @param key The String used to identify the Menu * @param jcpPanel Description of the Parameter * @param isPopup Tells if this menu will be a popup one or not * @param guiString The string identifying the gui to build (i. e. the properties file to use) * @param blocked A list of menuitesm/buttons which should be ignored when building gui. * @return The created JMenu */ protected JComponent createMenu(AbstractJChemPaintPanel jcpPanel, String key, boolean isPopup, String guiString, Set<String> blocked) { logger.debug("Creating menu: ", key); JMenu menu = new JMenu(jcpPanel.getMenuTextMaker().getText(key)); menu.setName(key); return createMenu(jcpPanel, key, isPopup, guiString, menu, blocked); } /** * Creates a JMenu given by a String with all the MenuItems specified in the * properties file. * * @param key The String used to identify the Menu * @param jcpPanel Description of the Parameter * @param isPopup Tells if this menu will be a popup one or not * @param guiString The string identifying the gui to build (i. e. the properties file to use) * @param menu The menu to add the new menu to (must either be JMenu or JPopupMenu) * @param blocked A list of menuitesm/buttons which should be ignored when building gui. * @return The created JMenu */ protected JComponent createMenu(final AbstractJChemPaintPanel jcpPanel, String key, boolean isPopup, String guiString, final JComponent menu, Set<String> blocked) { // block entire menu if (blocked.contains(key)){ return null; } String[] itemKeys = StringHelper.tokenize(getMenuResourceString(key, guiString)); for (int i = 0; i < itemKeys.length; i++) { if (!blocked.contains(itemKeys[i]) && !blocked.contains(itemKeys[i].substring(1))){ if (itemKeys[i].equals("-")) { if(menu instanceof JMenu) ((JMenu)menu).addSeparator(); else ((JPopupMenu)menu).addSeparator(); } else if (itemKeys[i].startsWith("@")) { JComponent me = createMenu(jcpPanel, itemKeys[i].substring(1), isPopup, guiString, blocked); menu.add(me); } else { JMenuItem mi = createMenuItem(jcpPanel, itemKeys[i], isPopup); menu.add(mi); } } } if(key.equals("isotopeChange")){ ((JMenu)menu).addMenuListener(new MenuListener(){ public void menuCanceled(MenuEvent arg0) { } public void menuDeselected(MenuEvent arg0) { } public void menuSelected(MenuEvent arg0) { menu.removeAll(); //the following condition is nasty, but necessary, since depending on if model and/or selection //is empty, various commands return null if((SwingPopupModule.lastAtomPopupedFor!=null && SwingPopupModule.lastAtomPopupedFor.getSymbol()!=null) || (jcpPanel.getRenderPanel().getRenderer().getRenderer2DModel().getSelection()!=null && !jcpPanel.getRenderPanel().getRenderer().getRenderer2DModel().getSelection().elements(IAtom.class).isEmpty())){ try { String symbol; if(jcpPanel.getRenderPanel().getRenderer().getRenderer2DModel().getSelection().getConnectedAtomContainer()!=null && !jcpPanel.getRenderPanel().getRenderer().getRenderer2DModel().getSelection().elements(IAtom.class).isEmpty()) symbol = jcpPanel.getRenderPanel().getRenderer().getRenderer2DModel().getSelection().getConnectedAtomContainer().getAtom(0).getSymbol(); else symbol = SwingPopupModule.lastAtomPopupedFor.getSymbol(); IIsotope[] isotopes = Isotopes.getInstance().getIsotopes(symbol); for(int i=0;i<isotopes.length;i++){ String cmd=isotopes[i].getSymbol()+isotopes[i].getMassNumber(); JMenuItem mi = new JMenuItem(cmd); mi.setName(cmd); usedKeys.add(cmd); String astr="org.openscience.jchempaint.action.ChangeIsotopeAction@specific"+isotopes[i].getMassNumber(); mi.setActionCommand(astr); JCPAction action = getJCPAction().getAction(jcpPanel, astr, false); if (action != null) { // sync some action properties with menu mi.setEnabled(action.isEnabled()); mi.addActionListener(action); logger.debug("Coupled action to new menu item..."); } menu.add(mi); } } catch (IOException e) { e.printStackTrace(); } }else{ menu.add(new JChemPaintMenuHelper().createMenuItem(jcpPanel, "majorPlusThree", false)); menu.add(new JChemPaintMenuHelper().createMenuItem(jcpPanel, "majorPlusTwo", false)); menu.add(new JChemPaintMenuHelper().createMenuItem(jcpPanel, "majorPlusOne", false)); menu.add(new JChemPaintMenuHelper().createMenuItem(jcpPanel, "major", false)); menu.add(new JChemPaintMenuHelper().createMenuItem(jcpPanel, "majorMinusOne", false)); menu.add(new JChemPaintMenuHelper().createMenuItem(jcpPanel, "majorMinusTwo", false)); menu.add(new JChemPaintMenuHelper().createMenuItem(jcpPanel, "majorMinusThree", false)); jcpPanel.enOrDisableMenus((JMenu)menu, jcpPanel.getRenderPanel().getRenderer().getRenderer2DModel().getSelection()==null || !jcpPanel.getRenderPanel().getRenderer().getRenderer2DModel().getSelection().isFilled() && jcpPanel.getRenderPanel().getRenderer().getRenderer2DModel().getHighlightedAtom()==null ? false : true); } } }); } //we make large menus two columns JPopupMenu p; if(menu instanceof JMenu) p = ((JMenu)menu).getPopupMenu(); else p = (JChemPaintPopupMenu)menu; if(p.getComponents().length>30){ Dimension d = p.getPreferredSize(); d = new Dimension((int)(d.width * 2.5), (int)(d.height * 0.7)); p.setPreferredSize(d); p.setLayout(new FlowLayout()); } if(menu instanceof JMenu) jcpPanel.menus.add((JMenu)menu); else if(menu instanceof JChemPaintPopupMenu) jcpPanel.popupmenuitems.put(key, (JChemPaintPopupMenu)menu); return menu; } /** * Creates a JMenuItem given by a String and adds the right ActionListener to * it. * * @param cmd String The String to identify the MenuItem * @param jcpPanel Description of the Parameter * @param isPopupMenu Tells if this menu will be a popup one or not * @return JMenuItem The created JMenuItem */ protected JMenuItem createMenuItem(AbstractJChemPaintPanel jcpPanel, String cmd, boolean isPopupMenu) { logger.debug("Creating menu item: ", cmd); boolean isCheckBox=false; if (cmd.endsWith("+")){ isCheckBox=true; cmd=cmd.substring(0, cmd.length() - 1); } boolean isChecked=false; if (cmd.endsWith("+")){ isChecked=true; cmd=cmd.substring(0, cmd.length() - 1); } JCPPropertyHandler jcpph = JCPPropertyHandler.getInstance(true); Properties userProps = jcpph.getJCPProperties(); if (userProps.containsKey(cmd + ".value")) { isChecked = Boolean.parseBoolean(userProps.getProperty(cmd + ".value")); } String translation = "***" + cmd + "***"; try { translation = jcpPanel.getMenuTextMaker().getText(cmd); logger.debug("Found translation: ", translation); } catch (MissingResourceException mre) { logger.error("Could not find translation for: " + cmd); } JMenuItem mi = null; if (isCheckBox) { mi = new JCheckBoxMenuItem(translation); mi.setSelected(isChecked); } else { mi = new JMenuItem(translation); } if (!jcpph.getBool("useFontIcons", true)) { URL url = jcpph.getOptionalResource(cmd + JCPAction.imageSuffix); if (url != null) { ImageIcon image = new ImageIcon(url); Image img = image.getImage(); Image newimg = img.getScaledInstance(16, 16, java.awt.Image.SCALE_SMOOTH); mi.setIcon(new ImageIcon(newimg)); URL disabledurl = jcpph.getOptionalResource(cmd + JCPAction.disabled_imageSuffix); if (disabledurl != null) { ImageIcon disabledimage = new ImageIcon(disabledurl); if (image != null) { Image disabledimg = disabledimage.getImage(); Image disablednewimg = disabledimg.getScaledInstance(16, 16, java.awt.Image.SCALE_SMOOTH); mi.setDisabledIcon(new ImageIcon(disablednewimg)); } } } } //this is to avoid to get a menu with the same name twice if(usedKeys.contains(cmd)) mi.setName(cmd+"2"); else mi.setName(cmd); usedKeys.add(cmd); logger.debug("Created new menu item..."); String astr = JCPPropertyHandler.getInstance(true).getResourceString(cmd + JCPAction.actionSuffix); if (astr == null) { astr = cmd; } mi.setActionCommand(astr); JCPAction action = getJCPAction().getAction(jcpPanel, astr, isPopupMenu); if (action != null) { // sync some action properties with menu mi.setEnabled(action.isEnabled()); mi.addActionListener(action); logger.debug("Coupled action to new menu item..."); } else { logger.error("Could not find JCPAction class for:" + astr); mi.setEnabled(false); } if(!isPopupMenu) addShortCuts(cmd, mi, jcpPanel); if(cmd.equals("undo")) jcpPanel.undoMenu=mi; if(cmd.equals("redo")) jcpPanel.redoMenu=mi; jcpPanel.menus.add((JMenuItem)mi); return mi; } /** * Adds ShortCuts to the JChemPaintMenuBar object.<br> * This simplifies and replaces the previous approach using Keycodes (VK_xxx) * Keycodes do not work across different keyboards, notably the + key * for zooming is problematic.<br> * More here: http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4262044 * * @param cmd String The String to identify the MenuItem. * @param mi the regarding MenuItem. * @param jcp The JChemPaintPanel this menu is used for. */ private void addShortCuts(String cmd, JMenuItem mi, AbstractJChemPaintPanel jcp) { Properties shortCutProps = JCPPropertyHandler.getInstance(true).getJCPShort_Cuts(); String keyString = shortCutProps.getProperty(cmd); if (keyString != null) { KeyStroke keyStroke = KeyStroke.getKeyStroke(keyString); mi.setAccelerator(keyStroke); jcp.getInputMap().put(keyStroke, mi); jcp.getActionMap().put(mi, mi.getAction()); } } }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/AbstractJChemPaintPanel.java
.java
21,174
640
/* * $RCSfile$ * $Author: egonw $ * $Date: 2007-01-04 17:26:00 +0000 (Thu, 04 Jan 2007) $ * $Revision: 7634 $ * * Copyright (C) 2008 Stefan Kuhn * Some portions Copyright (C) 2009 Konstantin Tokarev * * Contact: cdk-jchempaint@lists.sourceforge.net * * 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.jchempaint; import java.awt.BorderLayout; import java.awt.Container; import java.awt.Image; import java.awt.image.*; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.io.ByteArrayOutputStream; import java.io.PrintStream; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.SwingConstants; import javax.swing.filechooser.FileFilter; import javax.swing.undo.UndoManager; import org.openscience.cdk.exception.CDKException; import org.openscience.cdk.interfaces.IChemModel; import org.openscience.cdk.tools.ILoggingTool; import org.openscience.cdk.tools.LoggingToolFactory; import org.openscience.jchempaint.action.CreateSmilesAction; import org.openscience.jchempaint.action.JCPAction; import org.openscience.jchempaint.action.SaveAction; import org.openscience.jchempaint.applet.JChemPaintEditorApplet; import org.openscience.jchempaint.controller.ControllerHub; import org.openscience.jchempaint.renderer.selection.LogicalSelection; /** * An abstract superclass for the viewer and editor panel. * */ public abstract class AbstractJChemPaintPanel extends JPanel{ private static final long serialVersionUID = -6591788750314560180L; // buttons/menus are remembered in here using the string from config files as key Map<String, JButton> buttons=new HashMap<String, JButton>(); List<JMenuItem> menus=new ArrayList<JMenuItem>(); Map<String, JChemPaintPopupMenu> popupmenuitems=new HashMap<String, JChemPaintPopupMenu>(); protected InsertTextPanel insertTextPanel = null; protected String guistring; protected RenderPanel renderPanel; private FileFilter currentSaveFileFilter; private FileFilter currentOpenFileFilter; private File currentWorkDirectory; private boolean showToolBar = true; private boolean showMenuBar = true; private JMenuBar menu; private JComponent uppertoolbar; private JComponent lefttoolbar; private JComponent lowertoolbar; private JComponent righttoolbar; protected JPanel topContainer = null; protected JPanel centerContainer = null; private JComponent lastActionButton; protected JMenuItem undoMenu; protected JMenuItem redoMenu; protected JMenu rgroupMenu; protected boolean debug=false; protected boolean modified = false; private File isAlreadyAFile; private File lastOpenedFile; private static ILoggingTool logger = LoggingToolFactory.createLoggingTool(AbstractJChemPaintPanel.class); protected static String appTitle = ""; protected JCPMenuTextMaker menuTextMaker = null; protected Set<String> blockList; /** * The blocklist is a set of all elements which should not be shown. * * @return The blocked actions. */ public Set<String> getBlockedActions() { return blockList; } /** * Gets the RenderPanel in this panel. * * @return The RenderPanel. */ public RenderPanel getRenderPanel() { return renderPanel; } /** * Return the ControllerHub of this JCPPanel * * @return The ControllerHub */ public ControllerHub get2DHub() { return renderPanel.getHub(); } /** * Returns the chemmodel used in this panel. * * @return The chemmodel usedin this panel. */ public IChemModel getChemModel(){ return renderPanel.getChemModel(); } /** Access the menu bar. */ public JMenuBar getJMenuBar() { return menu; } /** * Sets the chemmodel used in this panel. * * @param model The chemmodel to use. */ public void setChemModel(IChemModel model){ renderPanel.setChemModel(model); //we need to do this to avoid npes later renderPanel.getRenderer().getRenderer2DModel().setSelection(new LogicalSelection(LogicalSelection.Type.NONE)); } /** * Gives the smiles for the current chemmodel in this panel. * * @return The smiles for the current chemmodel in this panel. * @throws CDKException * @throws ClassNotFoundException * @throws IOException * @throws CloneNotSupportedException */ public String getSmiles() throws CDKException, ClassNotFoundException, IOException, CloneNotSupportedException{ return CreateSmilesAction.getSmiles(getChemModel()); } /** * This method handles an error when we do not know what to do. It clearly * announces to the user that an error occured. This is preferable compared * to failing silently. * * @param ex The throwable which occured. */ public void announceError(Throwable ex){ ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(baos); ex.printStackTrace(ps); String trace = baos.toString(); JOptionPane.showMessageDialog(this, GT.get("The error was:")+" "+ex.getMessage()+". "+GT.get("\nYou can file a bug report at ")+ "https://github.com/JChemPaint/jchempaint/issues "+ GT.get("\nWe apologize for any inconvenience!") + trace, GT.get("Error occured"), JOptionPane.ERROR_MESSAGE); logger.error(ex.getMessage()); } /** * Update the menu bars and toolbars to current language. */ public void updateMenusWithLanguage() { menuTextMaker.init(guistring); Iterator<String> it = buttons.keySet().iterator(); while(it.hasNext()){ String key = it.next(); JButton button = buttons.get(key); button.setToolTipText(menuTextMaker.getText(key + JCPAction.TIPSUFFIX)); } Iterator<JMenuItem> it2 = menus.iterator(); while(it2.hasNext()){ JMenuItem button = it2.next(); button.setText(JCPMenuTextMaker.getInstance(guistring).getText(button.getName().charAt(button.getName().length()-1)=='2' ? button.getName().substring(0,button.getName().length()-1) : button.getName())); } it = popupmenuitems.keySet().iterator(); while(it.hasNext()){ String key = it.next(); JChemPaintPopupMenu button = popupmenuitems.get(key); ((JMenuItem)button.getComponent(0)).setText(menuTextMaker.getText(key.substring(0,key.length()-5) + "MenuTitle")); } if(insertTextPanel!=null){ insertTextPanel.updateLanguage(); } } public String getGuistring() { return guistring; } /** * Called to force a re-centring of the displayed structure. * * @param isNewChemModel */ public void setIsNewChemModel(boolean isNewChemModel) { this.renderPanel.setIsNewChemModel(isNewChemModel); } public Container getTopLevelContainer() { Container parent = this.getParent(); while(parent.getParent()!=null) parent = parent.getParent(); return parent; } public String getSVGString() { return this.renderPanel.toSVG(); } public byte[] getPDF() { return this.renderPanel.toPDF(); } public Image takeSnapshot() { return this.renderPanel.takeSnapshot(); } public Image takeTransparentSnapshot() { Image snapshot = takeSnapshot(); ImageFilter filter = new RGBImageFilter() { // Alpha bits are set to opaque public int markerRGB = renderPanel.getRenderer().getRenderer2DModel().getBackColor().getRGB() | 0xFF000000; public final int filterRGB(int x, int y, int rgb) { if ( ( rgb | 0xFF000000 ) == markerRGB ) { // Mark the alpha bits as zero - transparent return 0x00FFFFFF & rgb; } else { // nothing to do return rgb; } } }; ImageProducer ip = new FilteredImageSource(snapshot.getSource(), filter); return Toolkit.getDefaultToolkit().createImage(ip); } /** * Gets the currentOpenFileFilter attribute of the JChemPaintPanel object * *@return The currentOpenFileFilter value */ public FileFilter getCurrentOpenFileFilter() { return currentOpenFileFilter; } /** * Sets the currentOpenFileFilter attribute of the JChemPaintPanel object * *@param ff * The new currentOpenFileFilter value */ public void setCurrentOpenFileFilter(FileFilter ff) { this.currentOpenFileFilter = ff; } /** * Gets the currentSaveFileFilter attribute of the JChemPaintPanel object * *@return The currentSaveFileFilter value */ public FileFilter getCurrentSaveFileFilter() { return currentSaveFileFilter; } /** * Sets the currentSaveFileFilter attribute of the JChemPaintPanel object * *@param ff * The new currentSaveFileFilter value */ public void setCurrentSaveFileFilter(FileFilter ff) { this.currentSaveFileFilter = ff; } /** * Gets the currentWorkDirectory attribute of the JChemPaintPanel object * *@return The currentWorkDirectory value */ public File getCurrentWorkDirectory() { return currentWorkDirectory; } /** * Sets the currentWorkDirectory attribute of the JChemPaintPanel object * *@param cwd * The new currentWorkDirectory value */ public void setCurrentWorkDirectory(File cwd) { this.currentWorkDirectory = cwd; } /** * Set to indicate whether the insert text field should be used. * * @param showInsertTextField * true is the text entry widget is to be shown */ public void setShowInsertTextField(boolean showInsertTextField) { JCPPropertyHandler propertyHandler = JCPPropertyHandler.getInstance(true); propertyHandler.getJCPProperties().setProperty("insertstructure.value", Boolean.toString(showInsertTextField)); propertyHandler.saveProperties(); customizeView(); } /** * Tells if the enter text field is currently shown or not. * * @return text field shown or not */ public boolean getShowInsertTextField() { JCPPropertyHandler propertyHandler = JCPPropertyHandler.getInstance(true); Properties properties = propertyHandler.getJCPProperties(); return properties.containsKey("insertstructure.value") && Boolean.parseBoolean(properties.getProperty("insertstructure.value")); } /** * 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(); } /** * Returns the value of showToolbar. * *@return The showToolbar value */ public boolean getShowToolBar() { return showToolBar; } /** * Sets the value of showToolbar. * *@param showToolBar * The value to assign showToolbar. */ public void setShowToolBar(boolean showToolBar) { this.showToolBar = showToolBar; customizeView(); } public void customizeView() { if (showMenuBar) { if (menu == null) { menu = new JChemPaintMenuBar(this, this.guistring, blockList); topContainer.add(menu, BorderLayout.NORTH); } } else { topContainer.remove(menu); } if (showToolBar) { if (uppertoolbar == null) { uppertoolbar = JCPToolBar.getToolbar(this, "uppertoolbar", SwingConstants.HORIZONTAL, blockList); } if (lefttoolbar == null) { lefttoolbar = JCPToolBar.getToolbar(this, "lefttoolbar", SwingConstants.VERTICAL, blockList); } if (righttoolbar == null) { righttoolbar = JCPToolBar.getToolbar(this, "righttoolbar", SwingConstants.VERTICAL, blockList); } if (lowertoolbar == null) { lowertoolbar = JCPToolBar.getToolbar(this, "lowertoolbar", SwingConstants.HORIZONTAL, blockList); } if (uppertoolbar != null) topContainer.add(uppertoolbar, BorderLayout.SOUTH); if (lefttoolbar != null) centerContainer.add(lefttoolbar, BorderLayout.WEST); if (righttoolbar != null) centerContainer.add(righttoolbar, BorderLayout.EAST); if (lowertoolbar != null) centerContainer.add(lowertoolbar, BorderLayout.SOUTH); } else { topContainer.remove(uppertoolbar); centerContainer.remove(lowertoolbar); centerContainer.remove(lefttoolbar); centerContainer.remove(righttoolbar); } if (getShowInsertTextField()) { if (insertTextPanel == null) insertTextPanel = new InsertTextPanel(this, null); centerContainer.add(insertTextPanel, BorderLayout.NORTH); } else { if (insertTextPanel != null) centerContainer.remove(insertTextPanel); } topContainer.revalidate(); revalidate(); } /** * Helps in keeping the current action button highlighted - needs to be set * if a new action button is choosen * * @param actionButton * The new action button */ public void setLastActionButton(JComponent actionButton) { lastActionButton = actionButton; } /** * Helps in keeping the current action button highlighted * * @return The last action button used */ public JComponent getLastActionButton() { return lastActionButton; } /** * Enables or disables all JMenuItems in a JMenu. * * @param root The JMenu to search in. * @param b Enable or disable. */ protected void enOrDisableMenus(JMenu root, boolean b) { for(int i=0;i<root.getItemCount();i++){ if(root.getItem(i) instanceof JMenu){ ((JMenu)root.getItem(i)).setEnabled(b); }else if(root.getItem(i) instanceof JMenuItem){ ((JMenuItem)root.getItem(i)).setEnabled(b); } } } /** * Shows a warning if the JCPPanel has unsaved content and does save, if the * user wants to do it. * * @return * OptionPane.YES_OPTION/OptionPane.NO_OPTION/OptionPane.CANCEL_OPTION */ public int showWarning() { if (modified && !guistring.equals(JChemPaintEditorApplet.GUI_APPLET)) { // TODO // && // !getIsOpenedByViewer()) // { int answer = JOptionPane.showConfirmDialog(this, renderPanel .getChemModel().getID() + " " + GT.get("has unsaved data. Do you want to save it?"), GT.get("Unsaved data"), JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE); if (answer == JOptionPane.YES_OPTION) { SaveAction saveaction = new SaveAction(this, false); saveaction.actionPerformed(new ActionEvent( this, 12, "")); if(saveaction.getWasCancelled()) answer = JOptionPane.CANCEL_OPTION; } return answer; } else if (guistring.equals(JChemPaintEditorApplet.GUI_APPLET)) { // In case of the applet we do not ask for save but put the clear // into the undo stack // ClearAllEdit coa = null; // TODO undo redo missing coa = new // ClearAllEdit(this.getChemModel(),(IAtomContainerSet)this.getChemModel().getMoleculeSet().clone(),this.getChemModel().getReactionSet()); // this.jchemPaintModel.getControllerModel().getUndoSupport().postEdit(coa); return JOptionPane.YES_OPTION; } else { return JOptionPane.YES_OPTION; } } /** * Tells if debug output is desired or not. * * @return debug output or not. */ public boolean isDebug() { return debug; } /** * Gets the lastOpenedFile attribute of the JChemPaintPanel object * *@return The lastOpenedFile value */ public File getLastOpenedFile() { return lastOpenedFile; } /** * Sets the lastOpenedFile attribute of the JChemPaintPanel object * *@param lof * The new lastOpenedFile value */ public void setLastOpenedFile(File lof) { this.lastOpenedFile = lof; } /** * Sets the file currently used for saving this Panel. * *@param value * The new isAlreadyAFile value */ public void setIsAlreadyAFile(File value) { isAlreadyAFile = value; } /** * Returns the file currently used for saving this Panel, null if not yet * saved * *@return The currently used file */ public File isAlreadyAFile() { return isAlreadyAFile; } public void updateUndoRedoControls() { UndoManager undoManager = renderPanel.getUndoManager(); JButton redoButton=buttons.get("redo"); JButton undoButton=buttons.get("undo"); if (undoManager.canRedo()) { redoButton.setEnabled(true); redoMenu.setEnabled(true); redoButton.setToolTipText(GT.get("Redo")+": "+undoManager.getRedoPresentationName()); } else { redoButton.setEnabled(false); redoMenu.setEnabled(false); redoButton.setToolTipText(GT.get("No redo possible")); } if (undoManager.canUndo()) { undoButton.setEnabled(true); undoMenu.setEnabled(true); undoButton.setToolTipText(GT.get("Undo")+": "+undoManager.getUndoPresentationName()); } else { undoButton.setEnabled(false); undoMenu.setEnabled(false); undoButton.setToolTipText(GT.get("No undo possible")); } } public static String getAppTitle() { return appTitle; } public void setAppTitle(String title) { appTitle = title; } /** * Allows setting of the is modified stage (e. g. after save) * * @param isModified * is modified */ public void setModified(boolean isModified) { this.modified = isModified; Container c = this.getTopLevelContainer(); if (c instanceof JFrame) { String id = renderPanel.getChemModel().getID(); //String title = ((JFrame) c).getTitle(); if (isModified) ((JFrame) c).setTitle('*' + id + AbstractJChemPaintPanel.getAppTitle()); else ((JFrame) c).setTitle(id + AbstractJChemPaintPanel.getAppTitle()); } } public boolean isModified() { return modified; } public JCPMenuTextMaker getMenuTextMaker() { return menuTextMaker; } }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/JExternalFrame.java
.java
3,905
130
/* * $RCSfile$ * $Author: egonw $ * $Date: 2007-01-04 17:26:00 +0000 (Thu, 04 Jan 2007) $ * $Revision: 7634 $ * * Copyright (C) 1997-2008 Dirk Hermanns * * Contact: cdk-jchempaint@lists.sourceforge.net * * 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.jchempaint; import java.awt.BorderLayout; import java.awt.Component; import java.awt.Container; import java.awt.Dimension; import java.awt.Point; import javax.swing.JFrame; import javax.swing.JPanel; /** * This class allows to transfer an embedded or applet viewer or editor panel * to an external frame. This frame can be resized. */ public class JExternalFrame extends JFrame { private static final long serialVersionUID = -6607817663610291396L; private Component theComponent = null; private Container theParent = null; private JPanel dummyPanel = null; private boolean initialized = false; private Dimension embeddedSize = null; /** * @return Returns the dummyPanel. */ private JPanel getDummyPanel() { if (dummyPanel == null) dummyPanel = new JPanel(); return dummyPanel; } /** * @param comp Component that is transfered to the external frame */ public void show(Component comp) { int deltaW = 0; int deltaH = 0; int deltaX = 0; int deltaY = 0; Point embeddedScreenLocation = null; theComponent = comp; if (comp == null) return; theParent = comp.getParent(); if (theParent == null) return; if (!initialized) { embeddedScreenLocation = new Point(theComponent.getLocationOnScreen()); embeddedSize = theComponent.getSize(embeddedSize); getContentPane().setLayout(new BorderLayout()); this.setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); this.setSize(200,150); } super.setVisible(true); if (!initialized) { this.validate(); this.repaint(); deltaW = this.getWidth() - getContentPane().getWidth(); deltaH = this.getHeight() - getContentPane().getHeight(); deltaX = embeddedScreenLocation.x - getContentPane().getLocationOnScreen().x; deltaY = embeddedScreenLocation.y - getContentPane().getLocationOnScreen().y; } theParent.remove(theComponent); theParent.add(getDummyPanel()); theParent.validate(); theParent.repaint(); if (!initialized) { this.setBounds(this.getLocationOnScreen().x + deltaX, + this.getLocationOnScreen().y + deltaY, embeddedSize.width + deltaW, embeddedSize.height + deltaH); } getContentPane().add(theComponent, BorderLayout.CENTER); initialized = true; this.validate(); this.toFront(); this.repaint(); } /* (non-Javadoc) * @see java.awt.Window#dispose() */ public void dispose() { theParent.remove(getDummyPanel()); this.getContentPane().remove(theComponent); theComponent.setSize(embeddedSize); theParent.add(theComponent, BorderLayout.CENTER); super.dispose(); theParent.validate(); theParent.repaint(); } }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/AtomBondSet.java
.java
2,243
93
package org.openscience.jchempaint; import org.openscience.cdk.AtomRef; import org.openscience.cdk.BondRef; import org.openscience.cdk.interfaces.IAtom; import org.openscience.cdk.interfaces.IAtomContainer; import org.openscience.cdk.interfaces.IBond; import java.util.ArrayList; import java.util.List; /** * CDK 2.10 onwards enforces an invariant on AtomContainer's that a bond * can not be stored unless it's atoms are also stored (a dangling bond). * You must also add atoms before bonds in AtomContainer now. * <br/> * This class allows arbitrary sets of atoms and bonds to be stored without * the no dangling bonds constraint. This is required because sometimes we merge * /delete/update bonds. */ public class AtomBondSet { private final List<IAtom> atoms = new ArrayList<>(); private final List<IBond> bonds = new ArrayList<>(); public AtomBondSet() { } public AtomBondSet(IAtomContainer mol) { for (IAtom atom : mol.atoms()) atoms.add(AtomRef.deref(atom)); for (IBond bond : mol.bonds()) bonds.add(BondRef.deref(bond)); } public Iterable<IAtom> atoms() { return atoms; } public Iterable<IBond> bonds() { return bonds; } public int getAtomCount() { return atoms.size(); } public int getBondCount() { return bonds.size(); } public void add(IAtom atom) { atoms.add(atom); } public void add(IBond bond) { bonds.add(bond); } public void remove(IBond bond) { bonds.remove(bond); } public void remove(IAtom atom) { atoms.remove(atom); } public boolean contains(IAtom atom) { return atoms.contains(atom); } public boolean contains(IBond bond) { return bonds.contains(bond); } public boolean isEmpty() { return atoms.isEmpty() && bonds.isEmpty(); } public IAtom getSingleAtom() { if (atoms.size() != 1) throw new IllegalArgumentException(); return atoms.get(0); } @Override public String toString() { return "AtomBondSet{" + "atoms=" + atoms.size() + ", bonds=" + bonds.size() + '}'; } }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/JCPPropertyHandler.java
.java
14,406
406
/* * $RCSfile$ * $Author: egonw $ * $Date: 2007-01-04 17:26:00 +0000 (Thu, 04 Jan 2007) $ * $Revision: 7634 $ * * Copyright (C) 1997-2008 Stefan Kuhn * * Contact: cdk-jchempaint@lists.sourceforge.net * * 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.jchempaint; import java.awt.Color; 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.renderer.generators.BasicAtomGenerator; import org.openscience.cdk.tools.ILoggingTool; import org.openscience.cdk.tools.LoggingToolFactory; import org.openscience.jchempaint.action.JCPAction; import org.openscience.jchempaint.renderer.JChemPaintRendererModel; /** * A property manager for JChemPaint. * */ public class JCPPropertyHandler { private static JCPPropertyHandler jcpPropsHandler = null; private static ILoggingTool logger = LoggingToolFactory.createLoggingTool(JCPPropertyHandler.class); 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; private boolean useUserSettings; private static boolean oldUseUserSettings; /** * Constructor for the JCPPropertyHandler. * * @param useUserSettings Should user setting (in $HOME/.jchempaint/properties) be used or not? */ public JCPPropertyHandler(boolean useUserSettings) { this.useUserSettings = useUserSettings; } /** * Gets the instance attribute of the JCPPropertyHandler class. * * @param useUserSettings Should user setting (in $HOME/.jchempaint/properties) be used or not? * @return The instance value. */ public static JCPPropertyHandler getInstance(boolean useUserSettings) { if (jcpPropsHandler == null || oldUseUserSettings!=useUserSettings) { jcpPropsHandler = new JCPPropertyHandler(useUserSettings); oldUseUserSettings = useUserSettings; } return jcpPropsHandler; } /** * Gets the jCPProperties attribute of the JCPPropertyHandler object * *@return The jCPProperties value */ public Properties getJCPProperties() { if (currentProperties == null) { reloadProperties(useUserSettings); } return currentProperties; } public void reloadProperties(boolean useUserSettings) { Properties applicationProps = null; Properties defaultProps = null; InputStream defaultStream; try { defaultStream = this.getClass().getClassLoader().getResourceAsStream("org/openscience/jchempaint/resources/JChemPaintResources.properties"); defaultProps = new Properties(); defaultProps.load(defaultStream); defaultStream.close(); //the language setting is not in default file, but taken from platform settings defaultProps.setProperty("General.language",GT.getLanguage()); logger.info("Loaded properties from jar"); } catch (Exception exception) { logger.error("There was a problem retrieving JChemPaint's default properties."); logger.debug(exception); } applicationProps = new Properties(defaultProps); if(useUserSettings){ try { // set up real properties 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; } public ResourceBundle getGUIDefinition(String guiString) { try { String resource = "org.openscience.jchempaint.resources.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/jchempaint/resources/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.jchempaint.resources.JChemPaintResources"; resources = ResourceBundle.getBundle(resource); } catch (Exception exc) { logger.error("Could not read the resources."); logger.debug(exc); } } return resources; } public boolean getBool(String key, boolean defaultValue) { String val = currentProperties.getProperty(key); return val != null ? "true".equalsIgnoreCase(val) : defaultValue; } /** * 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 resource URL from the properties file that follows the given * String, if the resource is not found, no log message is emitted. * * @param key String The String to be looked after * @return URL The URL where the image is located */ public URL getOptionalResource(String key) { try { return getClass().getResource(getResources().getString(key)); } catch (MissingResourceException ignore) { 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; } public String getVersion(){ return this.getJCPProperties().getProperty("General.JCPVersion"); } /** * Set rendering preferences using this property handler instance. * * @param model rendering model */ public void setRenderingPreferences(JChemPaintRendererModel model) { model.setAtomRadius(Double.parseDouble(JCPPropertyHandler.getInstance(useUserSettings) .getJCPProperties().getProperty("AtomRadius"))); model.setBackColor(new Color(Integer.parseInt(JCPPropertyHandler.getInstance(useUserSettings) .getJCPProperties().getProperty("BackColor", String.valueOf(Color.white.getRGB()))))); model.setBondWidth(Double.parseDouble(JCPPropertyHandler.getInstance(useUserSettings) .getJCPProperties().getProperty("BondWidth"))); model.setWedgeWidth(Double.parseDouble(JCPPropertyHandler.getInstance(useUserSettings) .getJCPProperties().getProperty("WedgeWidth"))); model.setBondSeparation(Double.parseDouble(JCPPropertyHandler.getInstance(useUserSettings) .getJCPProperties().getProperty("BondSpacing"))); model.setHashSpacing(Double.parseDouble(JCPPropertyHandler.getInstance(useUserSettings) .getJCPProperties().getProperty("HashSpacing"))); model.setCompactShape(JCPPropertyHandler.getInstance(useUserSettings).getJCPProperties() .getProperty("CompactShape").equals("square") ? BasicAtomGenerator.Shape.SQUARE : BasicAtomGenerator.Shape.OVAL); model.setIsCompact(Boolean.parseBoolean(JCPPropertyHandler.getInstance(useUserSettings) .getJCPProperties().getProperty("IsCompact"))); model.setColorAtomsByType(Boolean.parseBoolean(JCPPropertyHandler.getInstance(useUserSettings) .getJCPProperties().getProperty("ColorAtomsByType"))); model.setShowImplicitHydrogens(Boolean.parseBoolean(JCPPropertyHandler.getInstance(useUserSettings) .getJCPProperties().getProperty("ShowImplicitHydrogens"))); model.setDrawNumbers(Boolean.parseBoolean(JCPPropertyHandler.getInstance(useUserSettings) .getJCPProperties().getProperty("DrawNumbers"))); model.setKekuleStructure(Boolean.parseBoolean(JCPPropertyHandler.getInstance(useUserSettings) .getJCPProperties().getProperty("KekuleStructure"))); model.setShowEndCarbons(Boolean.parseBoolean(JCPPropertyHandler.getInstance(useUserSettings) .getJCPProperties().getProperty("ShowEndCarbons"))); model.setShowExplicitHydrogens(Boolean.parseBoolean(JCPPropertyHandler.getInstance(useUserSettings) .getJCPProperties().getProperty("ShowExplicitHydrogens"))); model.setHighlightDistance(Double.parseDouble(JCPPropertyHandler.getInstance(useUserSettings) .getJCPProperties().getProperty("HighlightDistance"))); model.setFitToScreen(Boolean.parseBoolean(JCPPropertyHandler.getInstance(useUserSettings) .getJCPProperties().getProperty("FitToScreen"))); model.setShowAromaticity(Boolean.parseBoolean(JCPPropertyHandler.getInstance(useUserSettings) .getJCPProperties().getProperty("ShowAromaticity"))); model.setWedgeWidth(Double.parseDouble(JCPPropertyHandler.getInstance(useUserSettings) .getJCPProperties().getProperty("WedgeWidth"))); model.setShowReactionBoxes(Boolean.parseBoolean(JCPPropertyHandler.getInstance(useUserSettings) .getJCPProperties().getProperty("ShowReactionBoxes"))); } }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/JCPMenuTextMaker.java
.java
22,011
405
/* * $RCSfile$ * $Author: egonw $ * $Date: 2007-01-04 17:26:00 +0000 (Thu, 04 Jan 2007) $ * $Revision: 7634 $ * * Copyright (C) 1997-2008 Stefan Kuhn * * Contact: cdk-jchempaint@lists.sourceforge.net * * 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.jchempaint; import java.util.HashMap; import java.util.Map; import org.openscience.jchempaint.applet.JChemPaintEditorApplet; /** * This class held text entries for menu items, tool tips etc., which are * configured in the JCPGUI_*.properties files. They all need an entry * in the entries map to be recognized by the localization system. The same * is true about the DrawModeString for the status bar, which come from * controller modules in cdk and are only in English there. * */ public class JCPMenuTextMaker { private static JCPMenuTextMaker instance=null; protected Map<String,String> entries=new HashMap<String,String>(); /** * The constructor. Protected since class is a singleton. */ protected JCPMenuTextMaker(String guistring){ init(guistring); } public void init(String guistring){ entries.clear(); entries.put("file", GT.get("File")); entries.put("new", GT.get("New")); entries.put("atomMenuTitle", GT.get("Atom Popup Menu")); entries.put("pseudoMenuTitle", GT.get("Pseudo Atom Popup Menu")); entries.put("open", GT.get("Open")); entries.put("saveAs", GT.get("Save As...")); entries.put("view", GT.get("View")); entries.put("print", GT.get("Print...")); entries.put("export", GT.get("Save As Image...")); entries.put("save", GT.get("Save")); entries.put("edit", GT.get("Edit")); entries.put("report", GT.get("Report")); entries.put("close", GT.get("Close")); entries.put("exit", GT.get("Exit")); entries.put("undo", GT.get("Undo")); entries.put("redo", GT.get("Redo")); entries.put("selectAll", GT.get("Select All")); entries.put("copy", GT.get("Copy")); entries.put("copyAsSmiles", GT.get("Copy As SMILES")); entries.put("copyAsMolfile", GT.get("Copy As MOLfile")); entries.put("eraser", GT.get("Delete")); entries.put("paste", GT.get("Paste")); entries.put("pasteTemplate", GT.get("All Templates")); entries.put("cut", GT.get("Cut")); entries.put("atomMenu", GT.get("Atom")); entries.put("bondMenu", GT.get("Bond")); entries.put("tools", GT.get("Tools")); entries.put("templates", GT.get("Templates")); entries.put("radical", GT.get("Radical")); entries.put("bond", GT.get("Single")); entries.put("double_bond", GT.get("Double")); entries.put("triple_bond", GT.get("Triple")); entries.put("quad_bond", GT.get("Quadruple")); entries.put("down_bond", GT.get("Stereo Down")); entries.put("up_bond", GT.get("Stereo Up")); entries.put("undefined_bond", GT.get("Undefined Stereo")); entries.put("undefined_stereo_bond", GT.get("Undefined E/Z")); entries.put("hollow_wedge_bond", GT.get("Hollow Wedge")); entries.put("bold_bond", GT.get("Bold Bond")); entries.put("hash_bond", GT.get("Hashed Bond")); entries.put("dash_bond", GT.get("Dashed Bond")); entries.put("arom_bond", GT.get("Aromatic Bond")); entries.put("coordination_bond", GT.get("Coordination Bond")); entries.put("formalCharge", GT.get("Charge")); entries.put("plus", GT.get("Plus")); entries.put("minus", GT.get("Minus")); entries.put("hydrogen", GT.get("Implicit Hydrogens")); entries.put("flip", GT.get("Flip")); entries.put("cleanup", GT.get("Clean Structure")); entries.put("toolbar", GT.get("Toolbar")); entries.put("menubar", GT.get("Menubar")); entries.put("insertstructure", GT.get("Direct Entry as SMILES/InChI/CAS")); entries.put("zoomin", GT.get("Zoom In")); entries.put("zoomout", GT.get("Zoom Out")); entries.put("zoomoriginal", GT.get("Zoom 100%")); entries.put("options", GT.get("Preferences...")); entries.put("createSMILES", GT.get("Create SMILES")); entries.put("createInChI", GT.get("Create InChI")); entries.put("help", GT.get("Help")); entries.put("tutorial", GT.get("Basic Tutorial")); entries.put("rgpTutorial", GT.get("R-group Tutorial")); entries.put("feedback", GT.get("Report Feedback")); entries.put("license", GT.get("License")); entries.put("about", GT.get("About")); entries.put("hydroon", GT.get("On All")); entries.put("hydrooff", GT.get("Off")); entries.put("flipHorizontal", GT.get("Horizontal")); entries.put("flipVertical", GT.get("Vertical")); entries.put("selectFromChemObject", GT.get("Select")); entries.put("symbolChange", GT.get("Change Element")); entries.put("periodictable", GT.get("Periodic Table")); entries.put("enterelement", GT.get("Custom")); entries.put("isotopeChange", GT.get("Isotopes")); entries.put("convertToRadical", GT.get("Add Single Electron")); entries.put("Add Single Electron", GT.get("Add Single Electron")); entries.put("convertFromRadical", GT.get("Remove Single Electron")); entries.put("Remove Single Electron", GT.get("Remove Single Electron")); entries.put("showChemObjectProperties", GT.get("Properties")); entries.put("showACProperties", GT.get("Molecule Properties")); entries.put("makeNormal", GT.get("Convert to Regular Atom")); entries.put("commonSymbols", GT.get("Common Elements")); entries.put("halogenSymbols", GT.get("Halogens")); entries.put("nobelSymbols", GT.get("Nobel Gases")); entries.put("alkaliMetals", GT.get("Alkali Metals")); entries.put("alkaliEarthMetals", GT.get("Alkali Earth Metals")); entries.put("transitionMetals", GT.get("Transition Metals")); entries.put("metals", GT.get("Metals")); entries.put("metalloids", GT.get("Metalloids")); entries.put("Transition m", GT.get("Non-Metals")); entries.put("pseudoSymbols", GT.get("R Group")); entries.put("attachmentPoints", GT.get("Attachment Point")); entries.put("majorPlusThree", GT.get("Major Plus {0}", "3")); entries.put("majorPlusTwo", GT.get("Major Plus {0}", "2")); entries.put("majorPlusOne", GT.get("Major Plus {0}", "1")); entries.put("major", GT.get("Major Isotope")); entries.put("majorMinusOne", GT.get("Major Minus {0}", "1")); entries.put("majorMinusTwo", GT.get("Major Minus {0}", "2")); entries.put("majorMinusThree", GT.get("Major Minus {0}", "3")); entries.put("valence", GT.get("Valence")); entries.put("valenceOff", GT.get("Valence Off")); entries.put("valence1", GT.get("Valence {0}", "1")); entries.put("valence2", GT.get("Valence {0}", "2")); entries.put("valence3", GT.get("Valence {0}", "3")); entries.put("valence4", GT.get("Valence {0}", "4")); entries.put("valence5", GT.get("Valence {0}", "5")); entries.put("valence6", GT.get("Valence {0}", "6")); entries.put("valence7", GT.get("Valence {0}", "7")); entries.put("valence8", GT.get("Valence {0}", "8")); entries.put("symbolC", GT.get("C")); entries.put("symbolO", GT.get("O")); entries.put("symbolN", GT.get("N")); entries.put("symbolH", GT.get("H")); entries.put("symbolP", GT.get("P")); entries.put("symbolS", GT.get("S")); entries.put("symbolF", GT.get("F")); entries.put("symbolCl", GT.get("Cl")); entries.put("symbolBr", GT.get("Br")); entries.put("symbolI", GT.get("I")); entries.put("symbolHe", GT.get("He")); entries.put("symbolNe", GT.get("Ne")); entries.put("symbolAr", GT.get("Ar")); entries.put("symbolB", GT.get("B")); entries.put("symbolP", GT.get("P")); entries.put("symbolLi", GT.get("Li")); entries.put("symbolBe", GT.get("Be")); entries.put("symbolNa", GT.get("Na")); entries.put("symbolMg", GT.get("Mg")); entries.put("symbolAl", GT.get("Al")); entries.put("symbolSi", GT.get("Si")); entries.put("symbolFe", GT.get("Fe")); entries.put("symbolCo", GT.get("Co")); entries.put("symbolAg", GT.get("Ag")); entries.put("symbolPt", GT.get("Pt")); entries.put("symbolAu", GT.get("Au")); entries.put("symbolHg", GT.get("Hg")); entries.put("symbolCu", GT.get("Cu")); entries.put("symbolNi", GT.get("Ni")); entries.put("symbolZn", GT.get("Zn")); entries.put("symbolSn", GT.get("Sn")); entries.put("symbolK", GT.get("K")); entries.put("symbolRb", GT.get("Rb")); entries.put("symbolCs", GT.get("Cs")); entries.put("symbolFr", GT.get("Fr")); entries.put("symbolCa", GT.get("Ca")); entries.put("symbolSr", GT.get("Sr")); entries.put("symbolBa", GT.get("Ba")); entries.put("symbolRa", GT.get("Ra")); entries.put("symbolSc", GT.get("Sc")); entries.put("symbolTi", GT.get("Ti")); entries.put("symbolV", GT.get("V")); entries.put("symbolCr", GT.get("Cr")); entries.put("symbolMn", GT.get("Mn")); entries.put("symbolY", GT.get("Y")); entries.put("symbolZr", GT.get("Zr")); entries.put("symbolNb", GT.get("Nb")); entries.put("symbolMo", GT.get("Mo")); entries.put("symbolTc", GT.get("Tc")); entries.put("symbolRu", GT.get("Ru")); entries.put("symbolRh", GT.get("Rh")); entries.put("symbolPd", GT.get("Pd")); entries.put("symbolCd", GT.get("Cd")); entries.put("symbolHf", GT.get("Hf")); entries.put("symbolTa", GT.get("Ta")); entries.put("symbolW", GT.get("W")); entries.put("symbolRe", GT.get("Re")); entries.put("symbolOs", GT.get("Os")); entries.put("symbolIr", GT.get("Ir")); entries.put("symbolRf", GT.get("Rf")); entries.put("symbolDb", GT.get("Db")); entries.put("symbolSg", GT.get("Sg")); entries.put("symbolBh", GT.get("Bh")); entries.put("symbolHs", GT.get("Hs")); entries.put("symbolMt", GT.get("Mt")); entries.put("symbolDs", GT.get("Ds")); entries.put("symbolRg", GT.get("Rg")); entries.put("symbolGa", GT.get("Ga")); entries.put("symbolIn", GT.get("In")); entries.put("symbolTl", GT.get("Tl")); entries.put("symbolPb", GT.get("Pb")); entries.put("symbolBi", GT.get("Bi")); entries.put("symbolGe", GT.get("Ge")); entries.put("symbolAs", GT.get("As")); entries.put("symbolSb", GT.get("Sb")); entries.put("symbolTe", GT.get("Te")); entries.put("symbolPo", GT.get("Po")); entries.put("pseudoStar", GT.get("Variable Attachment Point *")); entries.put("pseudoR", GT.get("R")); entries.put("pseudoRX", GT.get("Other...")); entries.put("pseudoR1", GT.get("R1")); entries.put("pseudoR2", GT.get("R2")); entries.put("pseudoR3", GT.get("R3")); entries.put("pseudoR4", GT.get("R4")); entries.put("pseudoAP1", GT.get("1")); entries.put("pseudoAP2", GT.get("2")); entries.put("pseudoAP3", GT.get("3")); entries.put("bondToolTooltip", GT.get("Draw Bonds and Atoms")); entries.put("reactionArrowTooltip", GT.get("Makes a Reaction by Drawing a Reaction Arrow")); entries.put("double_bondToolTooltip", GT.get("Draw Double Bonds")); entries.put("triple_bondToolTooltip", GT.get("Draw Triple Bonds")); entries.put("cyclesymbolTooltip", GT.get("Change the Atom's Symbol")); entries.put("periodictableTooltip", GT.get("Select new drawing symbol from periodic table")); entries.put("enterelementTooltip", GT.get("Enter an element symbol via keyboard")); entries.put("up_bondTooltip", GT.get("Make the Bonds Stereo Up")); entries.put("hollow_wedge_bondTooltip", GT.get("Make/add a hollow Wedge")); entries.put("bold_bondTooltip", GT.get("Make a bold bond")); entries.put("hash_bondTooltip", GT.get("Make a hashed bond")); entries.put("dash_bondTooltip", GT.get("Make a dashed bond")); entries.put("arom_bondTooltip", GT.get("Make a aromatic bond")); entries.put("coordination_bondTooltip", GT.get("Make a coordination bond")); entries.put("chainTooltip", GT.get("Draw a chain")); entries.put("down_bondTooltip", GT.get("Make the Bonds Stereo Down")); entries.put("plusTooltip", GT.get("Increase the charge on an Atom")); entries.put("minusTooltip", GT.get("Decrease the charge on an Atom")); entries.put("eraserTooltip", GT.get("Delete atoms and bonds")); entries.put("lassoTooltip", GT.get("Select atoms and bonds in a free-form region")); entries.put("selectTooltip", GT.get("Select objects in a rectangle / move objects")); entries.put("triangleTooltip", GT.get("Add a propane ring")); entries.put("squareTooltip", GT.get("Add a butane ring")); entries.put("pentagonTooltip", GT.get("Add a pentane ring")); entries.put("hexagonTooltip", GT.get("Add a hexane ring")); entries.put("heptagonTooltip", GT.get("Add a heptane ring")); entries.put("octagonTooltip", GT.get("Add a octane ring")); entries.put("cyclopentadieneTooltip", GT.get("Add a cyclopentadiene ring")); entries.put("chairleftTooltip", GT.get("Add a left handed cyclohexane chair")); entries.put("chairrightTooltip", GT.get("Add a right handed cyclohexane chair")); entries.put("benzeneTooltip", GT.get("Add a benzene ring")); entries.put("cleanupTooltip", GT.get("Relayout the structures")); if(guistring.equals(JChemPaintEditorApplet.GUI_APPLET)) entries.put("newTooltip", GT.get("Clear")); else entries.put("newTooltip", GT.get("Create new file")); entries.put("openTooltip", GT.get("Open existing file")); entries.put("saveTooltip", GT.get("Save current file")); entries.put("printTooltip", GT.get("Print current file")); entries.put("redoTooltip", GT.get("Redo Action")); entries.put("saveAsTooltip", GT.get("Save to a file")); entries.put("undoTooltip", GT.get("Undo Action")); entries.put("zoominTooltip", GT.get("Zoom in")); entries.put("zoomoutTooltip", GT.get("Zoom out")); entries.put("undefined_bondTooltip", GT.get("Stereo up or stereo down bond")); entries.put("undefined_stereo_bondTooltip", GT.get("Any stereo bond")); entries.put("rotateTooltip", GT.get("Rotate selection")); entries.put("rotate3dTooltip", GT.get("Rotate selection in space")); entries.put("cutTooltip", GT.get("Cut selection")); entries.put("copyTooltip", GT.get("Copy selection to clipboard")); entries.put("pasteTooltip", GT.get("Paste from clipboard")); entries.put("flipVerticalTooltip", GT.get("Flip vertical")); entries.put("flipHorizontalTooltip", GT.get("Flip horizontal")); entries.put("pasteTemplateTooltip", GT.get("Choose from complex templates")); entries.put("bondMenuTitle", GT.get("Bond Popup Menu")); entries.put("chemmodelMenuTitle", GT.get("ChemModel Popup Menu")); entries.put("Enter Element or Group", GT.get("Enter Element or Group")); entries.put("Add Atom Or Change Element", GT.get("Add Atom Or Change Element")); entries.put("Draw Bond", GT.get("Draw Bond")); entries.put("Draw Double Bond", GT.get("Draw Double Bond")); entries.put("Draw Triple Bond", GT.get("Draw Triple Bond")); entries.put("Draw Quadruple Bond", GT.get("Draw Quadruple Bond")); entries.put("Ring 3", GT.get("Ring {0}", "3")); entries.put("Ring 4", GT.get("Ring {0}", "4")); entries.put("Ring 5", GT.get("Ring {0}", "5")); entries.put("Ring 6", GT.get("Ring {0}", "6")); entries.put("Ring 7", GT.get("Ring {0}", "7")); entries.put("Ring 8", GT.get("Ring {0}", "8")); entries.put("Add or convert to bond up", GT.get("Add or convert to bond up")); entries.put("Add or convert to bond down", GT.get("Add or convert to bond down")); entries.put("Decrease Charge", GT.get("Decrease Charge")); entries.put("Increase Charge", GT.get("Increase Charge")); entries.put("Cycle Symbol", GT.get("Cyclic change of symbol")); entries.put("Delete", GT.get("Delete")); entries.put("Move", GT.get("Move")); entries.put("Rotate", GT.get("Rotate")); entries.put("Rotate in space", GT.get("Rotate in space")); entries.put("Benzene", GT.get("Benzene")); entries.put("Select in Free Form", GT.get("Select in Free Form")); entries.put("Select Square", GT.get("Select / Move")); entries.put("CTooltip", GT.get("Change drawing symbol to {0}", "C")); entries.put("HTooltip", GT.get("Change drawing symbol to {0}", "H")); entries.put("OTooltip", GT.get("Change drawing symbol to {0}", "O")); entries.put("NTooltip", GT.get("Change drawing symbol to {0}", "N")); entries.put("PTooltip", GT.get("Change drawing symbol to {0}", "P")); entries.put("STooltip", GT.get("Change drawing symbol to {0}", "S")); entries.put("FTooltip", GT.get("Change drawing symbol to {0}", "F")); entries.put("ClTooltip", GT.get("Change drawing symbol to {0}", "Cl")); entries.put("BrTooltip", GT.get("Change drawing symbol to {0}", "Br")); entries.put("ITooltip", GT.get("Change drawing symbol to {0}", "I")); entries.put("enterRTooltip", GT.get("Draw any functional group")); entries.put("reaction", GT.get("Reaction")); entries.put("addReactantToNewReaction", GT.get("Make Reactant in New Reaction")); entries.put("addReactantToExistingReaction", GT.get("Make Reactant in Existing Reaction")); entries.put("addProductToNewReaction", GT.get("Make Product in New Reaction")); entries.put("addProductToExistingReaction", GT.get("Make Product in Existing Reaction")); entries.put("selectReactants", GT.get("Select Reactants")); entries.put("selectProducts", GT.get("Select Products")); entries.put("reactionMenuTitle", GT.get("Reaction Popup Menu")); entries.put("alkaloids", GT.get("Alkaloids")); entries.put("amino_acids", GT.get("Amino Acids")); entries.put("beta_lactams", GT.get("Beta Lactams")); entries.put("carbohydrates", GT.get("Carbohydrates")); entries.put("inositols", GT.get("Inositols")); entries.put("lipids", GT.get("Lipids")); entries.put("miscellaneous", GT.get("Miscellaneous")); entries.put("nucleosides", GT.get("Nucleosides")); entries.put("porphyrins", GT.get("Porphyrins")); entries.put("protecting_groups", GT.get("Protecting Groups")); entries.put("steroids", GT.get("Steroids")); entries.put("pahs", GT.get("PAHs")); entries.put("language", GT.get("Language")); entries.put("rgroup", GT.get("R-groups")); entries.put("rgroupMenu", GT.get("R-groups")); entries.put("rgroupAtomMenu", GT.get("R-group attachment")); entries.put("rgroupBondMenu", GT.get("R-group attachment")); entries.put("setRoot", GT.get("Define as Root Structure")); entries.put("setSubstitute", GT.get("Define as Substituent")); entries.put("setAtomApoAction1", GT.get("Set as first attachment point")); entries.put("setAtomApoAction2", GT.get("Set as second attachment point")); entries.put("setBondApoAction1", GT.get("Set as bond for first attachment point")); entries.put("setBondApoAction2", GT.get("Set as bond for second attachment point")); entries.put("rgpAdvanced", GT.get("Advanced R-group logic")); entries.put("rgpGenerate", GT.get("Generate possible configurations (sdf) ")); entries.put("rgpGenerateSmi", GT.get("Generate possible configurations (SMILES) ")); entries.put("clearRgroup", GT.get("Clear R-Group")); } /** * Gives the text for an item. * * @param key The key for the text * @return The text in current language */ public String getText(String key){ if(entries.get(key)==null) return key; else return entries.get(key); } /** * Gives an instance of JCPMenuTextMaker. * * @return The instance */ public static JCPMenuTextMaker getInstance(String guistring){ if(instance==null){ instance=new JCPMenuTextMaker(guistring); } return instance; } }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/JCPTransferHandler.java
.java
7,157
220
package org.openscience.jchempaint; import javax.swing.TransferHandler; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.Transferable; import java.awt.datatransfer.UnsupportedFlavorException; import java.io.File; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; import javax.swing.JComponent; import javax.swing.JOptionPane; import org.openscience.jchempaint.application.JChemPaint; import org.openscience.jchempaint.JChemPaintPanel; import org.openscience.jchempaint.applet.JChemPaintEditorApplet; import org.openscience.jchempaint.renderer.selection.LogicalSelection; import org.openscience.jchempaint.controller.undoredo.IUndoRedoable; import org.openscience.cdk.interfaces.IChemModel; public class JCPTransferHandler extends TransferHandler { private static final long serialVersionUID = 1L; private static final String URI_LIST_MIME_TYPE = "text/uri-list;class=java.lang.String"; private DataFlavor fileFlavor, stringFlavor; private DataFlavor uriListFlavor; private JChemPaintPanel jcpPanel; public JCPTransferHandler(JChemPaintPanel panel) { fileFlavor = DataFlavor.javaFileListFlavor; stringFlavor = DataFlavor.stringFlavor; try { uriListFlavor = new DataFlavor(URI_LIST_MIME_TYPE); } catch (ClassNotFoundException e) { e.printStackTrace(); } jcpPanel = panel; } @Override public boolean importData(JComponent c, Transferable t) { if (!canImport(c, t.getTransferDataFlavors())) { return false; } try { // Windows if (hasFileFlavor(t.getTransferDataFlavors())) { @SuppressWarnings("unchecked") final java.util.List<File> files = (java.util.List<File>) t.getTransferData(fileFlavor); process(files); return true; // Linux }else if(hasURIListFlavor(t.getTransferDataFlavors())){ final List<File> files = textURIListToFileList((String) t.getTransferData(uriListFlavor)); if(files.size()>0){ process(files); } }else if (hasStringFlavor(t.getTransferDataFlavors())) { String str = ((String) t.getTransferData(stringFlavor)); System.out.println(str); return true; } } catch (UnsupportedFlavorException ufe) { System.out.println("importData: unsupported data flavor"); } catch (IOException ieo) { System.out.println("importData: I/O exception"); } return false; } @Override public int getSourceActions(JComponent c) { return COPY; } @Override public boolean canImport(JComponent c, DataFlavor[] flavors) { if (hasFileFlavor(flavors)) { return true; } if (hasStringFlavor(flavors)) { return true; } return false; } private boolean hasFileFlavor(DataFlavor[] flavors) { for (int i = 0; i < flavors.length; i++) { if (fileFlavor.equals(flavors[i])) { return true; } } return false; } private boolean hasStringFlavor(DataFlavor[] flavors) { for (int i = 0; i < flavors.length; i++) { if (stringFlavor.equals(flavors[i])) { return true; } } return false; } private void process(java.util.List<File> l){ for (File f : l) { // Taken from OpenAction with small changes if (jcpPanel.getGuistring().equals( JChemPaintEditorApplet.GUI_APPLET) || JChemPaintPanel.getAllAtomContainersInOne(jcpPanel.getChemModel()).getAtomCount()==0) { int clear = jcpPanel.showWarning(); if (clear == JOptionPane.YES_OPTION) { try { IChemModel chemModel = null; chemModel = JChemPaint.readFromFile(f, null, jcpPanel); if (jcpPanel.get2DHub().getUndoRedoFactory() != null && jcpPanel.get2DHub().getUndoRedoHandler() != null) { IUndoRedoable undoredo = jcpPanel.get2DHub() .getUndoRedoFactory().getLoadNewModelEdit( jcpPanel.getChemModel(), null, jcpPanel.getChemModel() .getMoleculeSet(), jcpPanel.getChemModel() .getReactionSet(), chemModel.getMoleculeSet(), chemModel.getReactionSet(), "Load " + f.getName()); jcpPanel.get2DHub().getUndoRedoHandler().postEdit( undoredo); } jcpPanel.getChemModel().setMoleculeSet( chemModel.getMoleculeSet()); jcpPanel.getChemModel().setReactionSet(chemModel.getReactionSet()); jcpPanel.getRenderPanel().getRenderer() .getRenderer2DModel().setSelection( new LogicalSelection( LogicalSelection.Type.NONE)); // the newly opened file should nicely fit the screen jcpPanel.getRenderPanel().setFitToScreen(true); jcpPanel.getRenderPanel().update( jcpPanel.getRenderPanel().getGraphics()); // enable zooming by removing constraint jcpPanel.getRenderPanel().setFitToScreen(false); } catch (Exception e1) { // TODO Auto-generated catch block e1.printStackTrace(); jcpPanel.announceError(e1); } } } else { JChemPaint.showInstance(f, null, null, jcpPanel.isDebug()); } } } private boolean hasURIListFlavor(DataFlavor[] flavors) { for (int i = 0; i < flavors.length; i++) { if (uriListFlavor.equals(flavors[i])) { return true; } } return false; } private static List<File> textURIListToFileList(String data) { List<File> list = new ArrayList<File>(1); for (StringTokenizer st = new StringTokenizer(data, "\r\n"); st.hasMoreTokens();) { String s = st.nextToken(); if (s.startsWith("#")) { // the line is a comment (as per the RFC 2483) continue; } try { URI uri = new URI(s); File file = new File(uri); list.add(file); } catch (URISyntaxException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } } return list; } }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/JChemPaintPopupMenu.java
.java
2,742
81
/* * $RCSfile$ * $Author: egonw $ * $Date: 2007-01-04 17:26:00 +0000 (Thu, 04 Jan 2007) $ * $Revision: 7634 $ * * Copyright (C) 1997-2008 Christoph Steinbeck * * Contact: cdk-jchempaint@lists.sourceforge.net * * 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.jchempaint; import java.util.List; import java.util.Set; import javax.swing.JMenuItem; import javax.swing.JPopupMenu; import org.openscience.cdk.interfaces.IChemObject; /** * A pop-up menu for JChemPaint * */ public class JChemPaintPopupMenu extends JPopupMenu { private static final long serialVersionUID = -1172105004348414589L; private IChemObject source; private JChemPaintMenuHelper menuHelper=new JChemPaintMenuHelper(); public void setSource(IChemObject object) { this.source = object; } public IChemObject getSource() { return this.source; } /** * Constructor for the JChemPaintPopupMenu object. * * @param jcpPanel The JChemPaintPanel this menu is used for. * @param type The String used to identify the Menu * @param guiString The string identifying the gui to build (i. e. the properties file to use) * @param blocked A list of menuitesm/buttons which should be ignored when building gui. */ JChemPaintPopupMenu(JChemPaintPanel jcpPanel, String type, String guiString, Set<String> blocked) { String menuTitle = jcpPanel.getMenuTextMaker().getText(type + "MenuTitle"); JMenuItem titleMenuItem = new JMenuItem(menuTitle); titleMenuItem.setEnabled(false); titleMenuItem.setArmed(false); this.add(titleMenuItem); this.addSeparator(); this.setLabel(type); menuHelper.createMenu(jcpPanel, type + "popup", true, guiString, this, blocked); } }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/InsertTextPanel.java
.java
9,669
257
/* * $RCSfile$ * $Author: egonw $ * $Date: 2007-01-04 17:26:00 +0000 (Thu, 04 Jan 2007) $ * $Revision: 7634 $ * * Copyright (C) 1997-2008 Rajarshi Guha, Stefan Kuhn * * Contact: cdk-jchempaint@lists.sourceforge.net * * 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.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.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 org.openscience.cdk.DefaultChemObjectBuilder; import org.openscience.cdk.exception.CDKException; import org.openscience.cdk.exception.InvalidSmilesException; import org.openscience.cdk.interfaces.IAtomContainer; import org.openscience.cdk.smiles.SmilesParser; import org.openscience.jchempaint.application.JChemPaint; import org.openscience.jchempaint.inchi.InChITool; /** * A panel containing a text field and button to directly insert SMILES or InChI's * */ public class InsertTextPanel extends JPanel implements ActionListener { private static final long serialVersionUID = -5329451371043240706L; private AbstractJChemPaintPanel jChemPaintPanel; private JComboBox<String> textCombo; private JTextComponent editor; private JFrame closeafter = null; private JButton button = new JButton(GT.get("Insert")); public InsertTextPanel(AbstractJChemPaintPanel jChemPaintPanel, JFrame closeafter) { super(); this.closeafter = closeafter; setLayout(new GridBagLayout()); List<String> oldText = new ArrayList<String>(); oldText.add(""); textCombo = new JComboBox<String>(oldText.toArray(new String[]{})); textCombo.setEditable(true); textCombo.setToolTipText(GT.get("Enter a CAS, SMILES or InChI string")); // textCombo.addActionListener(this); // this can cause double inserts editor = (JTextComponent) textCombo.getEditor().getEditorComponent(); 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(GT.get("Insert"))) { IAtomContainer molecule = getMolecule(); if (molecule == null) return; try { JChemPaint.generateModel(jChemPaintPanel, molecule, true, true); } catch (CDKException e) { e.printStackTrace(); return; } if (closeafter != null) closeafter.setVisible(false); } } private IAtomContainer getMolecule() { IAtomContainer 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 { IAtomContainer atomContainer = InChITool.parseInChI(text); molecule = atomContainer.getBuilder().newInstance(IAtomContainer.class, atomContainer); } catch (Exception e2) { JOptionPane.showMessageDialog(jChemPaintPanel, GT.get("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, GT.get("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, GT.get("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 IAtomContainer getMoleculeFromCAS(String cas) throws IOException { String firstURL = "http://www.ncbi.nlm.nih.gov/entrez/query.fcgi?db=pccompound&term=" + cas; String 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 = ""; found = false; while (matcher.find()) { smiles = matcher.group(1); if (!smiles.equals("")) { found = true; break; } } if (!found) return null; // got the canonical SMILES, lets get the molecule SmilesParser smilesParser = new SmilesParser(DefaultChemObjectBuilder.getInstance()); try { IAtomContainer mol=smilesParser.parseSmiles(smiles); //for some reason, smilesparser sets valencies, which we don't want in jcp for(int i=0;i<mol.getAtomCount();i++){ mol.getAtom(i).setValency(null); } return mol; } catch (InvalidSmilesException e1) { JOptionPane.showMessageDialog(jChemPaintPanel, "Couldn't process data from PubChem"); return null; } } 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 updateLanguage() { textCombo.setToolTipText(GT.get("Enter a CAS, SMILES or InChI string")); button.setText(GT.get("Insert")); } }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/RenderPanel.java
.java
27,918
676
/* * $RCSfile$ * $Author: egonw $ * $Date: 2007-01-04 17:26:00 +0000 (Thu, 04 Jan 2007) $ * $Revision: 7634 $ * * Copyright (C) 1997-2008 Stefan Kuhn * * Contact: cdk-jchempaint@lists.sourceforge.net * * 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.jchempaint; import org.openscience.cdk.depict.DepictionGenerator; import org.openscience.cdk.exception.CDKException; import org.openscience.cdk.interfaces.IAtom; import org.openscience.cdk.interfaces.IAtomContainer; import org.openscience.cdk.interfaces.IAtomContainerSet; import org.openscience.cdk.interfaces.IChemModel; import org.openscience.cdk.renderer.RendererModel; import org.openscience.cdk.renderer.SymbolVisibility; import org.openscience.cdk.renderer.color.CDK2DAtomColors; import org.openscience.cdk.renderer.color.IAtomColorer; import org.openscience.cdk.renderer.color.UniColor; import org.openscience.cdk.renderer.font.AWTFontManager; import org.openscience.cdk.renderer.generators.BasicSceneGenerator; import org.openscience.cdk.renderer.generators.IGenerator; import org.openscience.cdk.renderer.generators.RingGenerator; import org.openscience.cdk.renderer.generators.standard.StandardGenerator; import org.openscience.cdk.renderer.selection.IChemObjectSelection; import org.openscience.cdk.silent.SilentChemObjectBuilder; import org.openscience.cdk.tools.ILoggingTool; import org.openscience.cdk.tools.LoggingToolFactory; import org.openscience.cdk.tools.manipulator.ChemModelManipulator; import org.openscience.cdk.tools.manipulator.MolecularFormulaManipulator; import org.openscience.jchempaint.action.ZoomAction; import org.openscience.jchempaint.applet.JChemPaintAbstractApplet; import org.openscience.jchempaint.controller.ControllerHub; import org.openscience.jchempaint.controller.ControllerModel; import org.openscience.jchempaint.controller.IControllerModule; import org.openscience.jchempaint.controller.IViewEventRelay; import org.openscience.jchempaint.controller.PhantomArrowGenerator; import org.openscience.jchempaint.controller.PhantomAtomGenerator; import org.openscience.jchempaint.controller.PhantomBondGenerator; import org.openscience.jchempaint.controller.PhantomTextGenerator; import org.openscience.jchempaint.controller.SwingMouseEventRelay; import org.openscience.jchempaint.controller.undoredo.IUndoListener; import org.openscience.jchempaint.controller.undoredo.IUndoRedoable; import org.openscience.jchempaint.controller.undoredo.UndoRedoHandler; import org.openscience.jchempaint.renderer.JChemPaintRendererModel; import org.openscience.jchempaint.renderer.Renderer; import org.openscience.jchempaint.renderer.generators.AtomContainerBoundsGenerator; import org.openscience.jchempaint.renderer.generators.AtomContainerTitleGenerator; import org.openscience.jchempaint.renderer.generators.BoundsGenerator; import org.openscience.jchempaint.renderer.generators.ExtendedAtomGenerator; import org.openscience.jchempaint.renderer.generators.ExternalHighlightAtomGenerator; import org.openscience.jchempaint.renderer.generators.ExternalHighlightBondGenerator; import org.openscience.jchempaint.renderer.generators.HighlightAtomGenerator; import org.openscience.jchempaint.renderer.generators.HighlightBondGenerator; import org.openscience.jchempaint.renderer.generators.IReactionGenerator; import org.openscience.jchempaint.renderer.generators.LonePairGenerator; import org.openscience.jchempaint.renderer.generators.MappingGenerator; import org.openscience.jchempaint.renderer.generators.MergeAtomsGenerator; import org.openscience.jchempaint.renderer.generators.ProductsBoxGenerator; import org.openscience.jchempaint.renderer.generators.RadicalGenerator; import org.openscience.jchempaint.renderer.generators.ReactantsBoxGenerator; import org.openscience.jchempaint.renderer.generators.ReactionArrowGenerator; import org.openscience.jchempaint.renderer.generators.ReactionBoxGenerator; import org.openscience.jchempaint.renderer.generators.ReactionPlusGenerator; import org.openscience.jchempaint.renderer.generators.SelectAtomGenerator; import org.openscience.jchempaint.renderer.generators.SelectBondGenerator; import org.openscience.jchempaint.renderer.generators.SelectControlGenerator; import org.openscience.jchempaint.renderer.generators.SelectionToolGenerator; import org.openscience.jchempaint.renderer.generators.TooltipGenerator; import org.openscience.jchempaint.renderer.visitor.AWTDrawVisitor; import org.openscience.jchempaint.undoredo.SwingUndoRedoFactory; import org.openscience.jchempaint.undoredo.SwingUndoableEdit; import javax.swing.JPanel; import javax.swing.undo.UndoManager; import javax.swing.undo.UndoableEdit; import java.awt.Color; import java.awt.Container; import java.awt.Dimension; import java.awt.Font; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.GraphicsEnvironment; import java.awt.Image; import java.awt.Rectangle; import java.awt.geom.Rectangle2D; import java.io.IOException; import java.text.NumberFormat; import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class RenderPanel extends JPanel implements IViewEventRelay, IUndoListener { private static final ILoggingTool log = LoggingToolFactory.createLoggingTool(RenderPanel.class); protected Renderer renderer; private boolean isNewChemModel; private ControllerHub hub; private ControllerModel controllerModel; private SwingMouseEventRelay mouseEventRelay; private boolean fitToScreen; private boolean zoomWide; private boolean shouldPaintFromCache = false; private UndoManager undoManager = new UndoManager(); private boolean debug = false; private PhantomAtomGenerator pag = new PhantomAtomGenerator(); private PhantomBondGenerator pbg = new PhantomBondGenerator(); private PhantomArrowGenerator prg = new PhantomArrowGenerator(); private PhantomTextGenerator ptg = new PhantomTextGenerator(); boolean isFirstDrawing = true; public RenderPanel(IChemModel chemModel, int width, int height, boolean fitToScreen, boolean debug, boolean isViewer, JChemPaintAbstractApplet applet) throws IOException { this.debug = debug; this.setupMachinery(chemModel, fitToScreen, isViewer, applet); this.setupPanel(width, height); this.fitToScreen = fitToScreen; int limit = Integer.parseInt(JCPPropertyHandler.getInstance(true) .getJCPProperties().getProperty("General.UndoStackSize")); undoManager.setLimit(limit); JCPPropertyHandler.getInstance(true). setRenderingPreferences(this.renderer.getRenderer2DModel()); updateDisplayOptions(); } public void setFitToScreen(boolean fitToScreen) { this.renderer.getRenderer2DModel().setFitToScreen(fitToScreen); } public void setZoomWide(boolean zoomWide) { this.zoomWide = zoomWide; } public IChemModel getChemModel() { return this.hub.getIChemModel(); } public void setChemModel(IChemModel model) { this.hub.setChemModel(model); } public ControllerHub getHub() { return hub; } private void setupMachinery(IChemModel chemModel, boolean fitToScreen, boolean isViewer, JChemPaintAbstractApplet applet) throws IOException { // setup the Renderer and the controller 'model' if (this.renderer == null) { this.renderer = new Renderer( makeGenerators(chemModel, false), makeReactionGenerators(), new AWTFontManager()); // any specific rendering settings defaults that overwrite user settings should go here //this.renderer.getRenderer2DModel().setShowEndCarbons(false); //this.renderer.getRenderer2DModel().setShowAromaticity(false); } this.setFitToScreen(fitToScreen); this.controllerModel = new ControllerModel(); UndoRedoHandler undoredohandler = new UndoRedoHandler(); undoredohandler.addIUndoListener(this); // connect the Renderer to the Hub this.hub = new ControllerHub(controllerModel, renderer, chemModel, this, undoredohandler, new SwingUndoRedoFactory(), isViewer, applet); pbg.setControllerHub(hub); pag.setControllerHub(hub); prg.setControllerHub(hub); ptg.setControllerHub(hub); // connect mouse events from Panel to the Hub this.mouseEventRelay = new SwingMouseEventRelay(this.hub); this.addMouseListener(mouseEventRelay); this.addMouseMotionListener(mouseEventRelay); this.addMouseWheelListener(mouseEventRelay); this.isNewChemModel = true; updateDisplayOptions(); } public RendererModel getRendererModel() { return renderer.getRenderer2DModel(); } public void updateDisplayOptions() { // tweaks the standard generator stroke options JChemPaintRendererModel model = this.renderer.getRenderer2DModel(); if (model.hasParameter(StandardGenerator.Visibility.class)) { if (model.getKekuleStructure()) { model.getParameter(StandardGenerator.Visibility.class) .setValue(SymbolVisibility.all()); } else if (model.getShowEndCarbons()) { model.getParameter(StandardGenerator.Visibility.class) .setValue(SymbolVisibility.iupacRecommendations()); } else { model.getParameter(StandardGenerator.Visibility.class) .setValue(SymbolVisibility.iupacRecommendationsWithoutTerminalCarbon()); } } if (model.hasParameter(StandardGenerator.DelocalisedDonutsBondDisplay.class)) { model.getParameter(StandardGenerator.DelocalisedDonutsBondDisplay.class) .setValue(model.getShowAromaticity()); } if (model.hasParameter(StandardGenerator.AtomColor.class)) { Color color = model.getBackColor(); double darkness = 1-(0.299*color.getRed() + 0.587*color.getGreen() + 0.114*color.getBlue())/255; if (darkness < 0.5) { if (model.getColorAtomsByType()) model.getParameter(StandardGenerator.AtomColor.class) .setValue(new CDK2DAtomColors()); else model.getParameter(StandardGenerator.AtomColor.class) .setValue(new UniColor(Color.BLACK)); } else { if (model.getColorAtomsByType()) { model.getParameter(StandardGenerator.AtomColor.class) .setValue(new IAtomColorer() { private final CDK2DAtomColors base = new CDK2DAtomColors(); @Override public Color getAtomColor(IAtom atom) { if (atom.getAtomicNumber() == null || atom.getAtomicNumber() == IAtom.C || atom.getAtomicNumber() == IAtom.Wildcard || atom.getAtomicNumber() == IAtom.H) return Color.WHITE; return base.getAtomColor(atom); } }); } else { model.getParameter(StandardGenerator.AtomColor.class) .setValue(new UniColor(Color.WHITE)); } } } if (model.hasParameter(RendererModel.SelectionColor.class)) { model.getParameter(RendererModel.SelectionColor.class) .setValue(null); } } private List<IReactionGenerator> makeReactionGenerators() { List<IReactionGenerator> generators = new ArrayList<IReactionGenerator>(); // generate the bounds first, so that they are to the back if (debug) { generators.add(new BoundsGenerator()); } generators.add(new ReactionBoxGenerator()); generators.add(new ReactionArrowGenerator()); generators.add(new ReactionPlusGenerator()); generators.add(new ReactantsBoxGenerator()); generators.add(new ProductsBoxGenerator()); generators.add(new MappingGenerator()); return generators; } // useSeparateGenerators: // in CDK 2.x we have StandardGenerator which does everything at once // atoms/bonds/Sgroups etc. This is because you need all the information // to correctly place/backoff bonds etc // // It would be nice if this was a preference but we don't configure // until after the generators are setup private List<IGenerator<IAtomContainer>> makeGenerators(IChemModel chemModel, boolean useSeparateGenerators) throws IOException { List<IGenerator<IAtomContainer>> generators = new ArrayList<IGenerator<IAtomContainer>>(); if (debug) { generators.add(new AtomContainerBoundsGenerator()); } generators.add(new BasicSceneGenerator()); if (useSeparateGenerators) { generators.add(new RingGenerator()); generators.add(new ExtendedAtomGenerator()); generators.add(new LonePairGenerator()); generators.add(new RadicalGenerator()); generators.add(new ExternalHighlightAtomGenerator()); generators.add(new ExternalHighlightBondGenerator()); } else { generators.add(new StandardGenerator(new Font(Font.SANS_SERIF, Font.PLAIN, 14))); } generators.add(new HighlightAtomGenerator()); generators.add(new HighlightBondGenerator()); if (useSeparateGenerators) { generators.add(new SelectAtomGenerator()); generators.add(new SelectBondGenerator()); } generators.add(new SelectControlGenerator()); generators.add(new SelectionToolGenerator()); generators.add(new MergeAtomsGenerator()); generators.add(new AtomContainerTitleGenerator()); generators.add(new TooltipGenerator()); // phantom generators generators.add(pbg); generators.add(pag); generators.add(prg); generators.add(ptg); return generators; } private void setupPanel(int width, int height) { this.setBackground(renderer.getRenderer2DModel().getBackColor()); this.setPreferredSize(new Dimension(width, height)); } /** * Render the entire sketch as an SVG string, currently this uses the CDK * depiction generator as we don't want to get the controls. * * @return the SVG */ String toSVG() { IAtomContainer combined = SilentChemObjectBuilder.getInstance().newAtomContainer(); for (IAtomContainer mol : hub.getChemModel().getMoleculeSet()) combined.add(mol); try { return new DepictionGenerator().withParams(renderer.getRenderer2DModel()) .depict(combined) .toSvgStr(); } catch (CDKException e) { return "<svg></svg>"; } } /** * Render the entire sketch as a PDF (byte[]), currently this uses the CDK * depiction generator as we don't want to get the controls. * * @return the PDF */ byte[] toPDF() { IAtomContainer combined = SilentChemObjectBuilder.getInstance().newAtomContainer(); for (IAtomContainer mol : hub.getChemModel().getMoleculeSet()) combined.add(mol); try { return new DepictionGenerator().withParams(renderer.getRenderer2DModel()) .depict(combined).toPdf(); } catch (CDKException e) { return new byte[0]; } } public Image takeSnapshot() { IChemModel chemModel = hub.getIChemModel(); if (isValidChemModel(chemModel)) { Rectangle2D modelBounds = Renderer.calculateBounds(chemModel); Rectangle bounds = renderer.calculateScreenBounds(modelBounds); bounds.height *= 1.1; bounds.width *= 1.1; Image image = GraphicsEnvironment.getLocalGraphicsEnvironment() .getScreenDevices()[0].getDefaultConfiguration() .createCompatibleImage(bounds.width, bounds.height); Graphics2D g = (Graphics2D) image.getGraphics(); takeSnapshot(g, chemModel, bounds, modelBounds); return image; } else { return null; } } public void takeSnapshot(Graphics2D g) { IChemModel chemModel = hub.getIChemModel(); Rectangle2D modelBounds = Renderer.calculateBounds(chemModel); Rectangle bounds = renderer.calculateScreenBounds(modelBounds); this.takeSnapshot(g, hub.getIChemModel(), bounds, modelBounds); } public void takeSnapshot(Graphics2D g, IChemModel chemModel, Rectangle s, Rectangle2D m) { g.setColor(renderer.getRenderer2DModel().getBackColor()); g.fillRect(0, 0, s.width, s.height); renderer.setDrawCenter(s.getWidth() / 2, s.getHeight() / 2); renderer.setModelCenter(m.getCenterX(), m.getCenterY()); renderer.paintChemModel(chemModel, new AWTDrawVisitor(g)); } protected boolean isValidChemModel(IChemModel chemModel) { return chemModel != null && (chemModel.getMoleculeSet() != null || chemModel .getReactionSet() != null); } public void paint(Graphics g) { this.setBackground(renderer.getRenderer2DModel().getBackColor()); super.paint(g); Graphics2D g2 = (Graphics2D) g; if (this.shouldPaintFromCache) { renderer.repaint(new AWTDrawVisitor(g2)); } else { IChemModel chemModel = this.hub.getIChemModel(); if (!isValidChemModel(chemModel)) return; /* * It is more correct to use a rectangle starting at (0,0) than to * use getBounds() as the RenderPanel may be a child of some * container window, and its Graphics will be translated relative to * its parent. */ Rectangle screen = new Rectangle(0, 0, getParent().getWidth() - 20, getParent().getHeight() - 20); if (renderer.getRenderer2DModel().isFitToScreen() || zoomWide) { this.paintChemModelFitToScreen(chemModel, g2, screen); if (zoomWide) zoomWide = false; } else { this.paintChemModel(chemModel, g2, screen); } } // for some reason, the first drawing of a string takes around 0.5 // seconds. // If the user experiences this delay, it's annoying, so we do a dummy // draw. if (isFirstDrawing && this.isVisible()) { g.setFont(((AWTFontManager) renderer.getFontManager()).getFont()); g.setColor(getBackground()); g.drawString("Black", 100, 100); isFirstDrawing = false; } } /** * Paint the chem model not fit-to-screen * * @param chemModel * @param g * @param screen */ private void paintChemModel( IChemModel chemModel, Graphics2D g, Rectangle screen) { if (isNewChemModel) { renderer.setup(chemModel, screen); } Rectangle diagram = renderer.calculateDiagramBounds(chemModel); isNewChemModel = false; this.shouldPaintFromCache = false; // determine the size the canvas needs to be to fit the model if (diagram != null) { Rectangle result = shift(screen, diagram); // this makes sure the toolbars get drawn this.setPreferredSize(new Dimension(result.width, result.height)); this.revalidate(); renderer.paintChemModel(chemModel, new AWTDrawVisitor(g)); } } private void paintChemModelFitToScreen(IChemModel chemModel, Graphics2D g, Rectangle screen) { renderer.paintChemModel(chemModel, new AWTDrawVisitor(g), screen, true); } public void setIsNewChemModel(boolean isNewChemModel) { this.isNewChemModel = isNewChemModel; } public void updateView() { /* * updateView should only be called in a ControllerModule where we * assume that things have changed so we can't use the cache */ this.shouldPaintFromCache = false; this.repaint(); } public void update(Graphics g) { // System.out.println("renderpanel update"); paint(g); } /** * Returns one of the status strings at the given position * * @param position * @return the current status */ public String getStatus(int position) { String status = ""; if (position == 0) { // depict editing mode IControllerModule activeDrawModule = hub.getActiveDrawModule(); if (activeDrawModule == null) { return ""; } else { String mode = activeDrawModule.getDrawModeString(); status = JCPMenuTextMaker.getInstance("applet").getText(mode); } } else if (position == 1) { // depict bruto formula IChemModel chemModel = hub.getIChemModel(); IAtomContainerSet molecules = chemModel.getMoleculeSet(); if (molecules != null && molecules.getAtomContainerCount() > 0) { Iterator<IAtomContainer> containers = ChemModelManipulator .getAllAtomContainers(chemModel).iterator(); int implicitHs = 0; while (containers.hasNext()) { for (IAtom atom : containers.next().atoms()) { if (atom.getImplicitHydrogenCount() != null) { implicitHs += atom.getImplicitHydrogenCount(); } } } status = makeStatusBarString(hub.getFormula(), implicitHs); } } else if (position == 2) { // depict brutto formula of the selected molecule or part of // molecule IChemObjectSelection selection = renderer.getRenderer2DModel() .getSelection(); if (selection != null) { IAtomContainer ac = selection.getConnectedAtomContainer(); if (ac != null) { int implicitHs = 0; for (IAtom atom : ac.atoms()) { if (atom.getImplicitHydrogenCount() != null) { implicitHs += atom.getImplicitHydrogenCount(); } } String formula = MolecularFormulaManipulator .getHTML(MolecularFormulaManipulator .getMolecularFormula(ac), true, false); status = makeStatusBarString(formula, implicitHs); } } } else if (position == 3) { status = GT.get("Zoomfactor") + ": " + NumberFormat.getPercentInstance().format( renderer.getRenderer2DModel().getZoomFactor()); } return status; } private String makeStatusBarString(String formula, int implicitHs) { return "<html>" + formula + "</html>"; } public Renderer getRenderer() { return renderer; } public UndoManager getUndoManager() { return undoManager; } public void doUndo(IUndoRedoable undoredo) { if (undoredo instanceof UndoableEdit) undoManager.addEdit((UndoableEdit) undoredo); else undoManager.addEdit(new SwingUndoableEdit(undoredo)); Container root = this.getParent().getParent().getParent(); if (root instanceof JChemPaintPanel) ((JChemPaintPanel) root).updateUndoRedoControls(); } public Rectangle shift(Rectangle screenBounds, Rectangle diagramBounds) { final int LABEL_MARGIN = 50; // prevents text or labels from dropping off screen int screenMaxX = screenBounds.x + screenBounds.width - LABEL_MARGIN; int screenMaxY = screenBounds.y + screenBounds.height - LABEL_MARGIN; int diagramMaxX = diagramBounds.x + diagramBounds.width; int diagramMaxY = diagramBounds.y + diagramBounds.height; int leftOverlap = screenBounds.x - diagramBounds.x; int rightOverlap = diagramMaxX - screenMaxX; int topOverlap = screenBounds.y - diagramBounds.y; int bottomOverlap = diagramMaxY - screenMaxY; int dx = 0; int dy = 0; int w = screenBounds.width; int h = screenBounds.height; if (leftOverlap > 0) { dx = leftOverlap; } if (rightOverlap > 0) { w += rightOverlap; } if (topOverlap > 0) { dy = topOverlap; } if (bottomOverlap > 0) { h += bottomOverlap; } if (dx != 0 || dy != 0) { // System.out.println("shifting "+dx+" "+dy); this.renderer.shiftDrawCenter(dx, dy); } else { int dxShiftBack = 0, dyShiftBack = 0; if (diagramBounds.x > screenMaxX / 3) { /* prevent drifting off horizontally */ dxShiftBack = -1 * (diagramBounds.x - (screenMaxX / 3)); } if (diagramBounds.y > screenMaxY / 3) { /* prevent drifting off vertically ! */ dyShiftBack = -1 * (diagramBounds.y - (screenMaxY / 3)); } if (dxShiftBack != 0 || dyShiftBack != 0) { if (ZoomAction.zoomDone) { ZoomAction.zoomDone = false; this.renderer.shiftDrawCenter(dxShiftBack, dyShiftBack); // System.out.println("shifting back"); } } } return new Rectangle(dx, dy, w, h); } }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/SwingPopupModule.java
.java
6,970
182
/* * $RCSfile$ * $Author: egonw $ * $Date: 2007-01-04 17:26:00 +0000 (Thu, 04 Jan 2007) $ * $Revision: 7634 $ * * Copyright (C) 2008 Stefan Kuhn * * Contact: cdk-jchempaint@lists.sourceforge.net * * 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.jchempaint; import java.awt.Rectangle; import java.util.Hashtable; import javax.vecmath.Point2d; import org.openscience.cdk.interfaces.IAtom; import org.openscience.cdk.interfaces.IBond; import org.openscience.cdk.interfaces.IChemModel; import org.openscience.cdk.interfaces.IChemObject; import org.openscience.cdk.interfaces.IPseudoAtom; import org.openscience.cdk.interfaces.IReactionSet; import org.openscience.cdk.tools.ILoggingTool; import org.openscience.cdk.tools.LoggingToolFactory; import org.openscience.jchempaint.controller.ControllerModuleAdapter; import org.openscience.jchempaint.controller.IChemModelRelay; import org.openscience.jchempaint.renderer.JChemPaintRendererModel; import org.openscience.jchempaint.renderer.Renderer; public class SwingPopupModule extends ControllerModuleAdapter { private static ILoggingTool logger = LoggingToolFactory.createLoggingTool(SwingPopupModule.class); private static Hashtable<String, JChemPaintPopupMenu> popupMenus = new Hashtable<String, JChemPaintPopupMenu>(); private RenderPanel rendererPanel; private String ID; public static IAtom lastAtomPopupedFor = null; public SwingPopupModule(RenderPanel renderer,IChemModelRelay chemModelRelay) { super(chemModelRelay); this.rendererPanel=renderer; } public String getDrawModeString() { return "Popup menu"; } public void mouseClickedDownRight(Point2d worldCoord) { popupMenuForNearestChemObject(rendererPanel.getRenderer().toScreenCoordinates(worldCoord.x, worldCoord.y)); } /** * Sets the popupMenu attribute of the Controller2D object * *@param someClass The new popupMenu value *@param jchemPaintPopupMenu The new popupMenu value */ public void setPopupMenu(Class<?> someClass, JChemPaintPopupMenu jchemPaintPopupMenu) { SwingPopupModule.popupMenus.put(someClass.getName(), jchemPaintPopupMenu); } /** * Returns the popup menu for this IChemObject if it is set, and null * otherwise. * *@param someClass Description of the Parameter *@return The popupMenu value */ public JChemPaintPopupMenu getPopupMenu(Class<?> classSearched,IChemObject objectInRange) { logger.debug("Searching popup for: ", classSearched.getName()); if (IBond.class.isAssignableFrom(classSearched)) classSearched = IBond.class; else if (IPseudoAtom.class.isAssignableFrom(classSearched)) classSearched = IPseudoAtom.class; // need to get before IAtom! else if (IAtom.class.isAssignableFrom(classSearched)) classSearched = IAtom.class; else if (IChemModel.class.isAssignableFrom(classSearched)) classSearched = IChemModel.class; if (classSearched.getName().startsWith("org.openscience.cdk")) { logger.debug("Searching popup for: ", classSearched.getName()); if (SwingPopupModule.popupMenus.containsKey(classSearched.getName())) { JChemPaintPopupMenu pop =(JChemPaintPopupMenu) SwingPopupModule.popupMenus.get(classSearched.getName()); //R-Group handling: pop up is conditional, only valid for atoms/bond in certain positions for(int x=0; x<pop.getComponentCount(); x++) { if (pop.getComponent(x).getName()!=null && pop.getComponent(x).getName().equals("rgroupBondMenu")) { pop.getComponent(x).setEnabled(false); if(chemModelRelay.getRGroupHandler()!=null && objectInRange instanceof IBond) { pop.getComponent(x).setEnabled(chemModelRelay.getRGroupHandler().isRGroupRootBond((IBond)objectInRange)); } } if (pop.getComponent(x).getName()!=null && pop.getComponent(x).getName().equals("rgroupAtomMenu")) { pop.getComponent(x).setEnabled(false); if(chemModelRelay.getRGroupHandler()!=null && objectInRange instanceof IAtom) { pop.getComponent(x).setEnabled(chemModelRelay.getRGroupHandler().isAtomPartOfSubstitute((IAtom)objectInRange)); } } } return pop; } } return null; } private void popupMenuForNearestChemObject(Point2d mouseCoords) { Renderer renderer = rendererPanel.getRenderer(); JChemPaintRendererModel rendererModel = renderer.getRenderer2DModel(); IChemObject objectInRange = rendererModel.getHighlightedAtom(); if (objectInRange == null) objectInRange = rendererModel.getHighlightedBond(); //look if we are in a reaction box IReactionSet reactionSet = rendererPanel.getChemModel().getReactionSet(); if (objectInRange == null && reactionSet != null && reactionSet.getReactionCount() > 0) { for(int i=0;i<reactionSet.getReactionCount();i++){ Rectangle reactionbounds = renderer.calculateDiagramBounds(reactionSet.getReaction(i)); if (reactionbounds.contains(mouseCoords.x, mouseCoords.y)) objectInRange = reactionSet.getReaction(i); } } if (objectInRange == null) objectInRange = chemModelRelay.getIChemModel(); if (objectInRange instanceof IAtom) lastAtomPopupedFor = (IAtom)objectInRange; JChemPaintPopupMenu popupMenu = getPopupMenu(objectInRange.getClass(), objectInRange); if (popupMenu != null) { popupMenu.setSource(objectInRange); logger.debug("Set popup menu source to: ", objectInRange); popupMenu.show(rendererPanel, (int)mouseCoords.x, (int)mouseCoords.y); } else { logger.warn("Popup menu is null! Could not set source: " + objectInRange.getClass()); } } public String getID() { return ID; } public void setID(String ID) { this.ID = ID; } }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/StringHelper.java
.java
2,101
66
/* * $RCSfile$ * $Author: egonw $ * $Date: 2007-01-04 17:26:00 +0000 (Thu, 04 Jan 2007) $ * $Revision: 7634 $ * * Copyright (C) 1997-2008 Stefan Kuhn * * Contact: cdk-jchempaint@lists.sourceforge.net * * 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.jchempaint; import java.util.StringTokenizer; import java.util.Vector; /** * Helper class for dealing with String objects. * */ public class StringHelper { /** * Partitions a given String into separate words and writes them into an * array. * *@param input String The String to be cutted into pieces *@return String[] The array containing the separate words */ public static String[] tokenize(String input) { Vector<String> vector = new Vector<>(); StringTokenizer tokenizer = new StringTokenizer(input); String seperateWords[]; while (tokenizer.hasMoreTokens()) { vector.addElement(tokenizer.nextToken()); } seperateWords = new String[vector.size()]; for (int i = 0; i < seperateWords.length; i++) { seperateWords[i] = vector.elementAt(i); } return seperateWords; } }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/JChemPaintPanel.java
.java
25,961
623
/* * $RCSfile$ * $Author: egonw $ * $Date: 2007-01-04 17:26:00 +0000 (Thu, 04 Jan 2007) $ * $Revision: 7634 $ * * Copyright (C) 1997-2008 Stefan Kuhn * Some portions Copyright (C) 2009 Konstantin Tokarev * * Contact: cdk-jchempaint@lists.sourceforge.net * * 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.jchempaint; import org.openscience.cdk.Atom; import org.openscience.cdk.Bond; import org.openscience.cdk.ChemModel; import org.openscience.cdk.PseudoAtom; import org.openscience.cdk.event.ICDKChangeListener; import org.openscience.cdk.interfaces.IAtom; import org.openscience.cdk.interfaces.IAtomContainer; import org.openscience.cdk.interfaces.IBond; import org.openscience.cdk.interfaces.IChemModel; import org.openscience.cdk.interfaces.IPseudoAtom; import org.openscience.cdk.renderer.selection.AbstractSelection; import org.openscience.cdk.tools.manipulator.ChemModelManipulator; import org.openscience.jchempaint.applet.JChemPaintAbstractApplet; import org.openscience.jchempaint.application.JChemPaint; import org.openscience.jchempaint.controller.AddBondDragModule; import org.openscience.jchempaint.controller.AddRingModule; import org.openscience.jchempaint.controller.ControllerHub; import org.openscience.jchempaint.controller.IChangeModeListener; import org.openscience.jchempaint.controller.IChemModelEventRelayHandler; import org.openscience.jchempaint.controller.IControllerModule; import org.openscience.jchempaint.controller.MoveModule; import org.openscience.jchempaint.renderer.JChemPaintRendererModel; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Container; import java.awt.Cursor; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.event.WindowListener; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.EventObject; import java.util.List; import java.util.Set; public class JChemPaintPanel extends AbstractJChemPaintPanel implements IChemModelEventRelayHandler, ICDKChangeListener, KeyListener, IChangeModeListener { private static final long serialVersionUID = 7810772571955039160L; public static List<JChemPaintPanel> instances = new ArrayList<JChemPaintPanel>(); private String lastSelectId; private JCPTransferHandler handler; /** * Builds a JCPPanel with a certain model. GUI is that of the application. * * @param chemModel The model to display. */ public JChemPaintPanel(IChemModel chemModel) { this(chemModel, JChemPaint.GUI_APPLICATION, false, null, Collections.emptySet()); } /** * Builds a JCPPanel with a certain model and a certain gui. * * @param chemModel The model to display. * @param gui The gui configuration string * @param debug Should we be in debug mode? * @param applet If this panel is to be in an applet, pass the applet here, else null. * @param blocked A list of menuitesm/buttons which should be ignored when building gui. */ public JChemPaintPanel(IChemModel chemModel, String gui, boolean debug, JChemPaintAbstractApplet applet, Set<String> blocked) { GT.setLanguage(JCPPropertyHandler.getInstance(true).getJCPProperties().getProperty("General.language")); this.guistring = gui; this.blockList = blocked; menuTextMaker = JCPMenuTextMaker.getInstance(guistring); this.debug = debug; try { renderPanel = new RenderPanel(chemModel, getWidth(), getHeight(), false, debug, false, applet); } catch (IOException e) { announceError(e); } if (gui.equals("application")) { setAppTitle(" - " + new JChemPaintMenuHelper().getMenuResourceString("Title", guistring)); } init(); } protected void init() { this.setLayout(new BorderLayout()); topContainer = new JPanel(new BorderLayout()); topContainer.setLayout(new BorderLayout()); this.add(topContainer, BorderLayout.NORTH); renderPanel.getHub().addChangeModeListener(this); renderPanel.setName("renderpanel"); centerContainer = new JPanel(); centerContainer.setLayout(new BorderLayout()); centerContainer.add(new JScrollPane(renderPanel), BorderLayout.CENTER); this.add(centerContainer); customizeView(); updateUndoRedoControls(); SwingPopupModule inputAdapter = new SwingPopupModule(renderPanel, renderPanel.getHub()); setupPopupMenus(inputAdapter, blockList); renderPanel.getHub().registerGeneralControllerModule(inputAdapter); renderPanel.getHub().setEventHandler(this); renderPanel.getRenderer().getRenderer2DModel().addCDKChangeListener( this); instances.add(this); //we set this to true always, the user should have no option to switch it off renderPanel.getHub().getController2DModel().setAutoUpdateImplicitHydrogens(true); this.addKeyListener(this); renderPanel.addMouseListener(new MouseAdapter() { public void mouseExited(MouseEvent e) { //this avoids ghost phantom rings if the user leaves the panel JChemPaintPanel.this.get2DHub().clearPhantoms(); JChemPaintPanel.this.get2DHub().updateView(); } }); handler = new JCPTransferHandler(this); renderPanel.setTransferHandler(handler); } /** * Gets the top level container (JFrame, Applet) of this panel. * * @return The top level container. */ public Container getTopLevelContainer() { return this.getParent().getParent().getParent().getParent(); } /** * If this panel is in a JFrame, sets the title of the JFrame. * * @param title The title to set. */ public void setTitle(String title) { Container topLevelContainer = this.getTopLevelContainer(); if (topLevelContainer instanceof JFrame) { ((JFrame) topLevelContainer).setTitle(title + appTitle); } } /** * Installs popup menus for this panel. * * @param inputAdapter The SwingPopupModule to use for the popup menus. * @param blocked A list of menuitesm/buttons which should be ignored when building gui. */ public void setupPopupMenus(SwingPopupModule inputAdapter, Set<String> blocked) { inputAdapter.setPopupMenu(IPseudoAtom.class, new JChemPaintPopupMenu(this, "pseudo", this.guistring, blocked)); inputAdapter.setPopupMenu(IAtom.class, new JChemPaintPopupMenu(this, "atom", this.guistring, blocked)); inputAdapter.setPopupMenu(IBond.class, new JChemPaintPopupMenu(this, "bond", this.guistring, blocked)); inputAdapter.setPopupMenu(IChemModel.class, new JChemPaintPopupMenu( this, "chemmodel", this.guistring, blocked)); } /** * Class for closing jcp * * @author shk3 * @cdk.created November 23, 2008 */ public final static class AppCloser extends WindowAdapter { /** * closing Event. Shows a warning if this window has unsaved data and * terminates jvm, if last window. * * @param e Description of the Parameter */ public void windowClosing(WindowEvent e) { int clear = ((JChemPaintPanel) ((JFrame) e.getSource()) .getContentPane().getComponents()[0]).showWarning(); if (JOptionPane.CANCEL_OPTION != clear) { for (int i = 0; i < instances.size(); i++) { if (instances.get(i).getTopLevelContainer() == (JFrame) e .getSource()) { instances.remove(i); break; } } ((JFrame) e.getSource()).setVisible(false); ((JFrame) e.getSource()).dispose(); if (instances.size() == 0) {// TODO && // !((JChemPaintPanel)rootFrame.getContentPane().getComponent(0)).isEmbedded()) // { System.exit(0); } } } } /** * Closes all currently opened JCP instances. */ public static void closeAllInstances() { int instancesNumber = instances.size(); for (int i = instancesNumber - 1; i >= 0; i--) { JFrame frame = (JFrame) instances.get(i).getTopLevelContainer(); WindowListener[] wls = (WindowListener[]) (frame .getListeners(WindowListener.class)); wls[0].windowClosing(new WindowEvent(frame, WindowEvent.WINDOW_CLOSING)); } } /* (non-Javadoc) * @see org.openscience.jchempaint.controller.IChemModelEventRelayHandler#coordinatesChanged() */ public void coordinatesChanged() { setModified(true); //move focus this.requestFocusInWindow(); } /* (non-Javadoc) * @see org.openscience.jchempaint.controller.IChemModelEventRelayHandler#selectionChanged() */ public void selectionChanged() { this.requestFocusInWindow(); } /* (non-Javadoc) * @see org.openscience.jchempaint.controller.IChemModelEventRelayHandler#structureChanged() */ public void structureChanged() { setModified(true); //if something changed in the structure, selection should be cleared //this is behaviour like eg in word processors, if you type, selection goes away this.getRenderPanel().getRenderer().getRenderer2DModel().setSelection(AbstractSelection.EMPTY_SELECTION); updateUndoRedoControls(); this.get2DHub().updateView(); //move focus //renderPanel.requestFocusInWindow(); this.requestFocusInWindow(); } /* (non-Javadoc) * @see org.openscience.jchempaint.controller.IChemModelEventRelayHandler#structurePropertiesChanged() */ public void structurePropertiesChanged() { setModified(true); //if something changed in the structure, selection should be cleared //this is behaviour like eg in word processors, if you type, selection goes away this.getRenderPanel().getRenderer().getRenderer2DModel().setSelection(AbstractSelection.EMPTY_SELECTION); //move focus this.requestFocusInWindow(); } /* (non-Javadoc) * @see org.openscience.cdk.event.ICDKChangeListener#stateChanged(java.util.EventObject) */ public void stateChanged(EventObject event) { updateUndoRedoControls(); //move focus this.requestFocusInWindow(); } /* (non-Javadoc) * @see java.awt.event.KeyListener#keyPressed(java.awt.event.KeyEvent) */ public void keyPressed(KeyEvent e) { JChemPaintRendererModel model = renderPanel.getRenderer().getRenderer2DModel(); ControllerHub relay = renderPanel.getHub(); if (relay.setAltInputMode(((e.getModifiersEx() & KeyEvent.ALT_DOWN_MASK) != 0))) { IControllerModule module = this.get2DHub().getActiveDrawModule(); if (module != null) module.updateView(); return; } this.get2DHub().clearPhantoms(); /* * ATOM/BOND Hotkeys * This will be better as two config files * - JCP_AtomHotKeys.properties * - JCP_BondHotKeys.properties * But is functional for now */ switch (e.getKeyCode()) { case KeyEvent.VK_UP: case KeyEvent.VK_DOWN: case KeyEvent.VK_LEFT: case KeyEvent.VK_RIGHT: // re-sync - make sure the highlighted atom has the correct // context (e.g. bonding) based on the current model if (model.getHighlightedAtom() != null) { IAtomContainer container = ChemModelManipulator.getRelevantAtomContainer(relay.getChemModel(), model.getHighlightedAtom()); if (container != null) model.setHighlightedAtom(container.getAtom(container.indexOf(model.getHighlightedAtom()))); else model.setHighlightedAtom(null); } if (model.getHighlightedBond() != null) { IAtomContainer container = ChemModelManipulator.getRelevantAtomContainer(relay.getChemModel(), model.getHighlightedBond()); if (container != null) model.setHighlightedBond(container.getBond(container.indexOf(model.getHighlightedBond()))); else model.setHighlightedBond(null); } model.moveHighlight(e.getKeyCode()); if ((e.getModifiersEx() & KeyEvent.SHIFT_DOWN_MASK) != 0) model.moveHighlight(e.getKeyCode()); this.get2DHub().updateView(); return; } boolean changed = false; // if shift or nothing pressed we do the hot keys for atoms/bonds if (((e.getModifiersEx() & ~(KeyEvent.SHIFT_DOWN_MASK | KeyEvent.ALT_DOWN_MASK)) == 0)) { char x = (char) (e.getKeyCode() >= 'A' && e.getKeyCode() <= 'Z' ? e.getKeyChar() : e.getKeyCode()); if (model.getHighlightedAtom() != null) { IAtom hgAtom = model.getHighlightedAtom(); changed = true; switch (x) { case ' ': relay.selectFragment(hgAtom); break; case '0': relay.addAtom(hgAtom, IAtom.C, true); break; case '1': relay.addAtom(hgAtom, IAtom.C, false); break; case '2': relay.addAcetyl(hgAtom); break; case '3': // fall through 3/a case 'a': relay.addPhenyl(hgAtom, 6, false); break; case '4': relay.addDimethyl(hgAtom, IBond.Display.WedgeBegin); break; case '5': relay.addDimethyl(hgAtom, IBond.Display.WedgeEnd); break; case '6': relay.addRing(hgAtom, 6, false); break; case '7': relay.addRing(hgAtom, 5, false); break; case '8': relay.addAtom(hgAtom, IAtom.C, IBond.Order.DOUBLE, false); break; case '9': relay.addDimethyl(hgAtom, IBond.Display.Solid); break; case 'b': relay.setSymbol(hgAtom, "B"); break; case 'c': relay.setSymbol(hgAtom, "C"); break; case 'd': relay.setSymbol(hgAtom, "H", 2); break; // case "e": break; // ethyl case 'f': relay.setSymbol(hgAtom, "F"); break; case 'h': relay.setSymbol(hgAtom, "H"); break; case 'i': relay.setSymbol(hgAtom, "I"); break; case 'n': case 'w': relay.setSymbol(hgAtom, "N"); break; case 'q': case 'o': relay.setSymbol(hgAtom, "O"); break; case 's': relay.setSymbol(hgAtom, "S"); break; case 'p': relay.setSymbol(hgAtom, "P"); break; case 'r': relay.setSymbol(hgAtom, "R"); break; case 'B': relay.setSymbol(hgAtom, "Br"); break; case 'C': // fall through C/l case 'l': relay.setSymbol(hgAtom, "Cl"); break; case 'S': relay.setSymbol(hgAtom, "Si"); break; case '.': relay.convertToPseudoAtom(hgAtom, "_AP1"); break; default: changed = false; } } else if (model.getHighlightedBond() != null) { IBond hgBond = model.getHighlightedBond(); changed = true; switch (x) { case ' ': relay.selectFragment(hgBond); break; case '1': relay.cycleBondValence(hgBond); break; case '2': relay.changeBond(hgBond, IBond.Order.DOUBLE, IBond.Display.Solid); break; case '3': relay.changeBond(hgBond, IBond.Order.TRIPLE, IBond.Display.Solid); break; case '4': relay.addRing(hgBond, 4, false); break; case '5': relay.addRing(hgBond, 5, false); break; case '6': relay.addRing(hgBond, 6, false); break; case '7': relay.addRing(hgBond, 7, false); break; case '8': relay.addRing(hgBond, 8, false); break; case 'a': relay.addPhenyl(hgBond, 6, false); break; case 'w': relay.changeBond(hgBond, IBond.Order.SINGLE, IBond.Display.WedgeBegin); break; case 'W': // shift + W case 'h': relay.changeBond(hgBond, IBond.Order.SINGLE, IBond.Display.WedgedHashBegin); break; case 'y': relay.changeBond(hgBond, IBond.Order.SINGLE, IBond.Display.Wavy); break; case 'b': relay.changeBond(hgBond, IBond.Order.SINGLE, IBond.Display.Bold); break; default: changed = false; } } else if (model.getSelection() == null || !model.getSelection().isFilled()) { changed = true; switch (x) { case '1': this.get2DHub().setActiveDrawModule(new AddBondDragModule(relay, IBond.Order.SINGLE, true, "bondTool")); break; case '2': this.get2DHub().setActiveDrawModule(new AddBondDragModule(relay, IBond.Order.DOUBLE, true, "double_bondTool")); break; case 'a': this.get2DHub().setActiveDrawModule(new AddRingModule(relay, 6, true, "benzene")); break; case '3': this.get2DHub().setActiveDrawModule(new AddRingModule(relay, 3, false, "triangle")); break; case '4': this.get2DHub().setActiveDrawModule(new AddRingModule(relay, 4, false, "square")); break; case '5': this.get2DHub().setActiveDrawModule(new AddRingModule(relay, 5, false, "pentagon")); break; case '6': this.get2DHub().setActiveDrawModule(new AddRingModule(relay, 6, false, "hexagon")); break; case '7': this.get2DHub().setActiveDrawModule(new AddRingModule(relay, 7, false, "heptagon")); break; case '8': this.get2DHub().setActiveDrawModule(new AddRingModule(relay, 8, false, "octagon")); break; default: changed = false; break; } if (changed) { this.get2DHub().updateView(); changed = false; } } } if (changed) { this.get2DHub().setActiveDrawModule(null); this.get2DHub().updateView(); this.get2DHub().clearPhantoms(); } } /* (non-Javadoc) * @see java.awt.event.KeyListener#keyReleased(java.awt.event.KeyEvent) */ public void keyReleased(KeyEvent e) { ControllerHub relay = renderPanel.getHub(); boolean changed = relay.setAltInputMode(!((e.getModifiersEx() & KeyEvent.ALT_DOWN_MASK) == 0)); if (changed) { this.get2DHub().updateView(); IControllerModule module = this.get2DHub().getActiveDrawModule(); if (module != null) module.updateView(); } } /* (non-Javadoc) * @see java.awt.event.KeyListener#keyTyped(java.awt.event.KeyEvent) */ public void keyTyped(KeyEvent arg0) { } /* (non-Javadoc) * @see org.openscience.jchempaint.controller.IChemModelEventRelayHandler#zoomChanged() */ public void zoomChanged() { //move focus this.requestFocusInWindow(); } /* (non-Javadoc) * @see org.openscience.cdk.controller.ChangeModeListener#modeChanged(org.openscience.cdk.controller.IControllerModule) */ public void modeChanged(IControllerModule newActiveModule) { //move focus this.requestFocusInWindow(); //we set the old button to inactive colour if (this.getLastActionButton() != null) { this.getLastActionButton().setBackground(null); } String actionid = newActiveModule.getID(); //this is because move mode does not have a button if (actionid.equals("move")) actionid = lastSelectId; //we remember the last activated move mode so that we can switch back to it after move if (newActiveModule.getID().equals("select") || newActiveModule.getID().equals("lasso")) lastSelectId = newActiveModule.getID(); //we set the new button to active colour JButton newActionButton = buttons.get(actionid); if (newActionButton != null) { this.setLastActionButton(newActionButton); newActionButton.setBackground(JCPToolBar.BUTON_ACTIVE_COLOR); } if (!(newActiveModule instanceof MoveModule)) { this.renderPanel.setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); this.get2DHub().updateView(); } } /** * Gets all atomcontainers of a chemodel in one AtomContainer. * * @param chemModel The chemodel * @return The result. */ public static IAtomContainer getAllAtomContainersInOne(IChemModel chemModel) { List<IAtomContainer> acs = ChemModelManipulator.getAllAtomContainers(chemModel); IAtomContainer allinone = chemModel.getBuilder().newInstance(IAtomContainer.class); for (int i = 0; i < acs.size(); i++) { allinone.add(acs.get(i)); } return allinone; } }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/JChemPaintMenuBar.java
.java
4,323
118
/* * $RCSfile$ * $Author: egonw $ * $Date: 2007-01-04 17:26:00 +0000 (Thu, 04 Jan 2007) $ * $Revision: 7634 $ * * Copyright (C) 1997-2008 Stefan Kuhn * * Contact: cdk-jchempaint@lists.sourceforge.net * * 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.jchempaint; import java.util.List; import java.util.Set; import javax.swing.Box; import javax.swing.JComponent; import javax.swing.JMenu; import javax.swing.JMenuBar; /** * An extension of JMenuBar for JCP purposes * */ public class JChemPaintMenuBar extends JMenuBar { private static final long serialVersionUID = -8358165408129203644L; private String guiString; private JChemPaintMenuHelper menuHelper=new JChemPaintMenuHelper(); /** * Constructor for the JChemPaintMenuBar object. Creates a JMenuBar with all the menues that are specified in the properties * file. <p> * * The menu items in the bar are defined by the property 'menubar' in * org.openscience.cdk.applications.jchempaint.resources.JChemPaint.properties. * * @param jcpPanel Description of the Parameter * @param guiString Description of the Parameter * @param blocked A list of menuitesm/buttons which should be ignored when building gui. */ public JChemPaintMenuBar(AbstractJChemPaintPanel jcpPanel, String guiString, Set<String> blocked) { this.guiString = guiString; addNormalMenuBar(jcpPanel, menuHelper.getMenuResourceString("menubar", guiString), blocked); this.add(Box.createHorizontalGlue()); this.add(menuHelper.createMenu(jcpPanel, "help", false, guiString, blocked)); } /** * Adds a feature to the NormalMenuBar attribute of the JChemPaintMenuBar * object * * @param jcpPanel The feature to be added to the NormalMenuBar * attribute * @param menuDefinition The feature to be added to the NormalMenuBar * attribute * @param blocked A list of menuitesm/buttons which should be ignored when building gui. */ private void addNormalMenuBar(AbstractJChemPaintPanel jcpPanel, String menuDefinition, Set<String> blocked) { String definition = menuDefinition; String[] menuKeys = StringHelper.tokenize(definition); for (int i = 0; i < menuKeys.length; i++) { JComponent m; if(menuHelper.getMenuResourceString(menuKeys[i], guiString)==null) m = menuHelper.createMenuItem(jcpPanel, menuKeys[i], false); else m = menuHelper.createMenu(jcpPanel, menuKeys[i], false, guiString, blocked); if (m != null) { this.add(m); } } } /** * Creates a JMenu which can be part of the menu of an application embedding jcp. * * @param jcpPanel Description of the Parameter * @return The created JMenu * @param blocked A list of menuitesm/buttons which should be ignored when building gui. */ public JMenu getMenuForEmbedded(JChemPaintPanel jcpPanel, Set<String> blocked) { String definition = menuHelper.getMenuResourceString("menubar", guiString); String[] menuKeys = StringHelper.tokenize(definition); JMenu superMenu = new JMenu("JChemPaint"); for (int i = 0; i < menuKeys.length; i++) { JComponent m = menuHelper.createMenu(jcpPanel, menuKeys[i], false, guiString, blocked); if (m != null) { superMenu.add(m); } } return (superMenu); } }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/JCPToolBar.java
.java
13,196
342
/* * $RCSfile$ * $Author: egonw $ * $Date: 2007-01-04 17:26:00 +0000 (Thu, 04 Jan 2007) $ * $Revision: 7634 $ * * Copyright (C) 1997-2008 Stefan Kuhn * * Contact: cdk-jchempaint@lists.sourceforge.net * * 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.jchempaint; import java.awt.Color; import java.awt.Font; import java.awt.FontFormatException; import java.awt.Insets; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.MissingResourceException; import java.util.Properties; import java.util.ResourceBundle; import java.util.Set; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JToolBar; import javax.swing.SwingConstants; import javax.swing.border.EmptyBorder; import com.formdev.flatlaf.util.UIScale; import org.openscience.cdk.interfaces.IBond; import org.openscience.cdk.tools.ILoggingTool; import org.openscience.cdk.tools.LoggingToolFactory; import org.openscience.jchempaint.action.JCPAction; import org.openscience.jchempaint.controller.AddBondDragModule; import org.openscience.jchempaint.controller.ControllerHub; import org.openscience.jchempaint.controller.IControllerModule; import org.openscience.jchempaint.controller.SelectSquareModule; /** * This class makes the JCPToolBar * */ public class JCPToolBar extends JToolBar { private static ILoggingTool logger = LoggingToolFactory.createLoggingTool(JCPToolBar.class); public static Color BUTON_ACTIVE_COLOR = new Color(98, 182, 207, 111); private static final float ICON_FONT_SIZE = 22.0f; // JWM: not entirely sure how to get the text centered correctly public static final Insets ICON_FONT_INSETS = new Insets(2, 0, 0, 0); private static Font iconFont; private static Properties iconFontMap; static { try (InputStream in = JCPToolBar.class.getResourceAsStream("fonts/JCPIcons.ttf")) { if (in != null) iconFont = Font.createFont(Font.TRUETYPE_FONT, in) .deriveFont(UIScale.scale(ICON_FONT_SIZE)); } catch (FontFormatException | IOException e) { logger.error("Could not load JCP Icon font: " + e.getMessage()); } try (InputStream in = JCPToolBar.class.getResourceAsStream("fonts/JCPIcons.map")) { if (in != null) { iconFontMap = new Properties(); iconFontMap.load(in); } } catch (IOException e) { logger.error("Could not load JCP Icon font: " + e.getMessage()); } if (iconFont == null || iconFontMap == null) { iconFont = null; iconFontMap = null; } } public JCPToolBar(int orientation) { super(orientation); } /** * Gets the toolbar attribute of the MainContainerPanel object * * @param chemPaintPanel the application/applet panel * @param key the toolbar key (the properties file is used to determine the items) * @param direction {@link SwingConstants#HORIZONTAL} or {@link SwingConstants#VERTICAL} * @param blocked A list of menuitesm/buttons which should be ignored when building gui. * @return The toolbar value */ public static JComponent getToolbar(AbstractJChemPaintPanel chemPaintPanel, String key, int direction, Set<String> blocked) { ResourceBundle bundle = JCPPropertyHandler.getInstance(true) .getGUIDefinition(chemPaintPanel.getGuistring()); if (!bundle.containsKey(key)) return null; String[] resourceStrings = bundle.getString(key).split(","); List<JToolBar> toolBars = new ArrayList<>(); for (String resourceString : resourceStrings) { JToolBar toolbar = createToolbar(direction, resourceString.trim(), chemPaintPanel, blocked); if (toolbar != null) toolBars.add(toolbar); } if (toolBars.isEmpty()) return null; else if (toolBars.size() == 1) return toolBars.get(0); else { // we make the box in the opposite orientation Box box = new Box(direction ^ 0x1); for (JToolBar toolBar : toolBars) box.add(toolBar); return box; } } /** * Gets the menuResourceString attribute of the JChemPaint object * * @param key Description of the Parameter * @return The menuResourceString value */ static String getToolbarResourceString(String key, String guistring) { String str; try { str = JCPPropertyHandler.getInstance(true).getGUIDefinition(guistring).getString(key); } catch (MissingResourceException mre) { mre.printStackTrace(); str = null; } return str; } /** * Creates a JButton given by a String with an Image and adds the right * ActionListener to it. * *@param key String The string used to identify the button *@param elementtype If true a special type of button for element symbols will be created *@return JButton The JButton with already added ActionListener */ static JButton createToolbarButton(String key, AbstractJChemPaintPanel chemPaintPanel, boolean elementtype) { JCPPropertyHandler jcpph = JCPPropertyHandler.getInstance(true); JButton b; String symbol = iconFont != null ? iconFontMap.getProperty(key, null) : null; if (symbol != null && jcpph.getBool("useFontIcons", true)) { b = new JButton(symbol); b.setFont(iconFont); b.setVerticalTextPosition(SwingConstants.CENTER); b.setHorizontalTextPosition(SwingConstants.CENTER); b.setMargin(ICON_FONT_INSETS); } else { // image icon logger.debug("Trying to find resource for key: ", key); URL url = jcpph.getResource(key + JCPAction.imageSuffix); logger.debug("Trying to find resource: ", url); if (url == null) { logger.error("Cannot find resource: ", key, JCPAction.imageSuffix); return null; } ImageIcon image = new ImageIcon(url); if (image.getImage() == null) { logger.error("Cannot find image: ", url); return null; } b = new JButton(image) { private static final long serialVersionUID = 1478990892406874403L; public float getAlignmentY() { return 0.5f; } }; URL disabledurl = jcpph.getOptionalResource(key + JCPAction.disabled_imageSuffix); logger.debug("Trying to find resource: ", url); if (disabledurl != null){ b.setDisabledIcon(new ImageIcon(disabledurl)); } b.setMargin(new Insets(1, 1, 1, 1)); } String astr = null; if (elementtype) astr = jcpph.getResourceString("symbol" + key + JCPAction.actionSuffix); else astr = jcpph.getResourceString(key + JCPAction.actionSuffix); if (astr == null) { astr = key; } JCPAction a = new JCPAction().getAction(chemPaintPanel, astr); if (a != null) { b.setActionCommand(astr); logger.debug("Coupling action to button..."); b.addActionListener(a); b.setEnabled(a.isEnabled()); } else { logger.error("Could not find JCPAction class for:", astr); b.setEnabled(false); } try { // TODO: use getMenuTextMaker? String tip = JCPMenuTextMaker.getInstance("applet").getText(key + JCPAction.TIPSUFFIX); if (tip != null) { b.setToolTipText(tip); } } catch (MissingResourceException e) { logger.warn("Could not find Tooltip resource for: ", key); logger.debug(e); } b.setRequestFocusEnabled(false); b.setName(key); b.setOpaque(false); b.setBackground(null); chemPaintPanel.buttons.put(key, b); return b; } /** * Creates a toolbar given by a String with all the buttons that are * specified in the properties file. * * @param orientation int The orientation of the toolbar * @param resourceString string used to configure the toolbar items * @param blocked A list of menuitems/buttons which should be ignored when * building gui. * @return Component The created toolbar */ private static JToolBar createToolbar(int orientation, String resourceString, AbstractJChemPaintPanel chemPaintPanel, Set<String> blocked) { JCPToolBar toolbar = new JCPToolBar(orientation); if (resourceString == null) { return null; } if (orientation == SwingConstants.HORIZONTAL) { toolbar.setLayout(new BoxLayout(toolbar, BoxLayout.LINE_AXIS)); } else if (orientation == SwingConstants.VERTICAL) { toolbar.setLayout(new BoxLayout(toolbar, BoxLayout.PAGE_AXIS)); } String[] toolKeys = StringHelper.tokenize(resourceString); JButton button = null; for (String toolKey : toolKeys) { if (toolKey.equals("|")) { toolbar.addSeparator(); } else if (toolKey.equals("-")) { toolbar.add(createSpacerButton()); } else if (!blocked.contains(toolKey)) { button = createToolbarButton(toolKey, chemPaintPanel, toolKey.length() < 3); /* * if (toolKeys[i].equals("lasso")) { selectButton = button; } */ if (button != null) { toolbar.add(button); if (toolKey.equals("bondTool")) { chemPaintPanel.setLastActionButton(button); AddBondDragModule activeModule = new AddBondDragModule(chemPaintPanel.get2DHub(), IBond.Display.Solid, true); activeModule.setID(toolKey); chemPaintPanel.get2DHub().setActiveDrawModule(activeModule); } } else { logger.error("Could not create button" + toolKey); } } } if (orientation == SwingConstants.HORIZONTAL) { toolbar.add(Box.createHorizontalGlue()); } else { toolbar.add(Box.createVerticalGlue()); } ControllerHub relay = chemPaintPanel.get2DHub(); IControllerModule m = new SelectSquareModule(relay); m.setID("select"); relay.setFallbackModule(m); return toolbar; } private static JButton createSpacerButton() { JButton blank = new JButton(" "); if (iconFont != null) blank.setFont(iconFont); blank.setVerticalTextPosition(SwingConstants.CENTER); blank.setHorizontalTextPosition(SwingConstants.CENTER); blank.setMargin(ICON_FONT_INSETS); blank.setEnabled(false); blank.setOpaque(false); blank.setBorder(new EmptyBorder(2,2,2,2)); blank.setBackground(null); return blank; } }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/JChemPaintViewerPanel.java
.java
2,234
61
/* * $RCSfile$ * $Author: egonw $ * $Date: 2007-01-04 17:26:00 +0000 (Thu, 04 Jan 2007) $ * $Revision: 7634 $ * * Copyright (C) 1997-2008 Stefan Kuhn * * Contact: cdk-jchempaint@lists.sourceforge.net * * 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.jchempaint; import java.awt.BorderLayout; import java.awt.ScrollPane; import java.io.IOException; import org.openscience.cdk.interfaces.IChemModel; import org.openscience.jchempaint.applet.JChemPaintAbstractApplet; public class JChemPaintViewerPanel extends AbstractJChemPaintPanel { /** * Builds a JCPViewerPanel with a certain model * * @param chemModel The model */ public JChemPaintViewerPanel(IChemModel chemModel, int width, int height, boolean fitToScreen, boolean debug, JChemPaintAbstractApplet applet){ this.setLayout(new BorderLayout()); try { renderPanel = new RenderPanel(chemModel, this.getWidth(), this.getHeight(), fitToScreen, debug, true, applet); } catch (IOException e) { announceError(e); } if (!fitToScreen) { ScrollPane scroller = new ScrollPane(); scroller.add(renderPanel); this.add(scroller, BorderLayout.CENTER); } else { this.add(renderPanel,BorderLayout.CENTER); } } }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/rgroups/RGroupHandler.java
.java
20,347
553
/* * Copyright (C) 2010 Mark Rijnbeek * Contact: cdk-jchempaint@lists.sourceforge.net * * 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.jchempaint.rgroups; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; import javax.swing.JOptionPane; import javax.vecmath.Point2d; import org.openscience.cdk.AtomRef; import org.openscience.cdk.CDKConstants; import org.openscience.cdk.exception.CDKException; import org.openscience.cdk.geometry.GeometryUtil; import org.openscience.cdk.interfaces.IAtom; import org.openscience.cdk.interfaces.IAtomContainer; import org.openscience.cdk.interfaces.IBond; import org.openscience.cdk.interfaces.IChemModel; import org.openscience.cdk.interfaces.IAtomContainerSet; import org.openscience.cdk.interfaces.IPseudoAtom; import org.openscience.cdk.isomorphism.matchers.IRGroupQuery; import org.openscience.cdk.isomorphism.matchers.RGroup; import org.openscience.cdk.isomorphism.matchers.IRGroup; import org.openscience.cdk.isomorphism.matchers.RGroupList; import org.openscience.cdk.isomorphism.matchers.IRGroupList; import org.openscience.cdk.isomorphism.matchers.RGroupQuery; import org.openscience.cdk.tools.manipulator.ChemModelManipulator; import org.openscience.jchempaint.AbstractJChemPaintPanel; import org.openscience.jchempaint.AtomBondSet; import org.openscience.jchempaint.GT; import org.openscience.jchempaint.controller.IChemModelRelay; /** * Provides common functionality for JChempants to handle R-groups, such * as lay out, clean up and verifying operations. */ public class RGroupHandler { private final AbstractJChemPaintPanel jcpPanel; public RGroupHandler (IRGroupQuery _rGroupQuery, AbstractJChemPaintPanel jcpPanel) { rGroupQuery = _rGroupQuery; this.jcpPanel = jcpPanel; } private IRGroupQuery rGroupQuery; public IRGroupQuery getrGroupQuery() { return rGroupQuery; } public void setrGroupQuery(IRGroupQuery rGroupQuery) { this.rGroupQuery = rGroupQuery; } /** * Creates a {@link org.openscience.cdk.interfaces.IAtomContainerSet} from a * provided {@link org.openscience.cdk.isomorphism.matchers.IRGroupQuery). * The root structure becomes the atom container as position zero, the * substitutes follow on position 1..n, ordered by R-group number. * * @param chemModel * @param RgroupQuery * @throws CDKException */ public IAtomContainerSet getMoleculeSet (IChemModel chemModel) throws CDKException { if (rGroupQuery==null || rGroupQuery.getRootStructure() == null || rGroupQuery.getRootStructure().getAtomCount()==0) throw new CDKException( "The R-group is empty"); IAtomContainerSet moleculeSet = chemModel.getBuilder().newInstance(IAtomContainerSet.class); moleculeSet.addAtomContainer(rGroupQuery.getRootStructure()); chemModel.setMoleculeSet(moleculeSet); for (int rgrpNum : sortRGroupNumbers()) { IRGroupList rgrpList = rGroupQuery.getRGroupDefinitions().get(rgrpNum); for (IRGroup rgrp : rgrpList.getRGroups()) { chemModel.getMoleculeSet().addAtomContainer(rgrp.getGroup()); } } return moleculeSet; } /** * Helper to get an ordered list of R-group numbers for a certain IRGroupQuery. * @param RgroupQuery * @return an ordered list of R-group numbers in rgroupQuery. */ private List<Integer> sortRGroupNumbers () { List<Integer> rNumbers = new ArrayList<Integer>(); if (rGroupQuery!=null) { for (Iterator<Integer> itr = rGroupQuery.getRGroupDefinitions().keySet().iterator(); itr.hasNext(); ) { rNumbers.add(itr.next()); } Collections.sort(rNumbers); } return rNumbers; } /** * Changes atom coordinates so that the substitutes of the R-group are lined * up underneath the root structure, resulting in a clear presentation. * Method intended to be used after reading an external R-group files (RG files), * overriding the coordinates in the file. * @param RgroupQuery * @throws CDKException */ public void layoutRgroup() throws CDKException { if (rGroupQuery==null || rGroupQuery.getRootStructure() == null || rGroupQuery.getRootStructure().getAtomCount()==0) throw new CDKException( "The R-group is empty"); /* * This is how we want to layout: * * {Root structure} * * {R1.a} {R1.b} {R1.c} ... * {R2.a} {R2.b} ... * {R3.a} {R3.b} {R3.c} ... * .... * .. */ final double MARGIN = 3; IAtomContainer rootStruct=rGroupQuery.getRootStructure(); double xLeft=(findBoundary(rootStruct,true,true,Double.POSITIVE_INFINITY)); double yBottom=(findBoundary(rootStruct,false,true,Double.POSITIVE_INFINITY))-MARGIN; double minListYBottom=yBottom; for (int rgrpNum : sortRGroupNumbers()) { double listXRight = xLeft; IRGroupList rgrpList = rGroupQuery.getRGroupDefinitions().get(rgrpNum); List<IRGroup> rGroups = rgrpList.getRGroups(); List<double[]> bounds = new ArrayList<>(); double maxHeight = 0; for (IRGroup rgrp : rGroups) { double[] minMax = GeometryUtil.getMinMax(rgrp.getGroup()); bounds.add(minMax); maxHeight = Math.max(minMax[3] - minMax[1], maxHeight); } for (int i = 0; i < rGroups.size(); i++) { IRGroup rgrp = rGroups.get(i); double[] minmax = bounds.get(i); double rgrpXleft = minmax[0]; double rgrpYtop = minmax[3]; double rgrpHeight = minmax[3] - minmax[1]; double shiftX = (listXRight - rgrpXleft); double shiftY = (yBottom - rgrpYtop) - (maxHeight - rgrpHeight) / 2; for (IAtom atom : rgrp.getGroup().atoms()) { atom.setPoint2d(new Point2d(atom.getPoint2d().x + shiftX, atom.getPoint2d().y + shiftY)); } minListYBottom = (findBoundary(rgrp.getGroup(), false, true, minListYBottom)); double rgrpXRight = (findBoundary(rgrp.getGroup(), true, false, Double.NEGATIVE_INFINITY)); listXRight = rgrpXRight + MARGIN; } yBottom = minListYBottom - MARGIN; } } /** * Helper method to find boundaries of a given atom container. * @param atc atom container * @param isX true if interested in X boundary, false for Y * @param smallest true if we want smallest, false if largest * @param startVal starting point * @return boundary coordinate (x or y) */ private double findBoundary(IAtomContainer atc, boolean isX, boolean smallest, double startVal) { double retVal=startVal; for (IAtom atom : atc.atoms()) { if (isX) if (smallest) { if(atom.getPoint2d().x<retVal) retVal = atom.getPoint2d().x; } else { if(atom.getPoint2d().x>retVal) retVal = atom.getPoint2d().x; } else if (smallest) { if(atom.getPoint2d().y<retVal) retVal = atom.getPoint2d().y; } else { if(atom.getPoint2d().y>retVal) retVal = atom.getPoint2d().y; } } return retVal; } /** * Cleans up atom containers in the R-group that do not exists (anymore) * in the molecule set in the hub, possibly due to deletion or merging. * @param moleculeSet */ public void cleanUpRGroup(IAtomContainerSet moleculeSet){ List<Integer> rgrpToRemove=new ArrayList<Integer>(); if (rGroupQuery!=null){ Map<Integer,IRGroupList> def = rGroupQuery.getRGroupDefinitions(); for(Iterator<Integer> itr= def.keySet().iterator();itr.hasNext();) { //Remove RGroups with empty atom containers from RGroupLists int rgrpNum=itr.next(); List<IRGroup> rgpList = def.get(rgrpNum).getRGroups(); for (int i = 0; i < rgpList.size(); i++) { if(!exists(rgpList.get(i).getGroup(),moleculeSet) || rgpList.get(i).getGroup().getAtomCount()==0) { rgpList.remove(i); } } //Drop RGroupLists that don't have any content atom-wise int atomCount=0; for (IRGroup rgrp :rGroupQuery.getRGroupDefinitions().get(rgrpNum).getRGroups()) { atomCount+=rgrp.getGroup().getAtomCount(); } if (atomCount==0) { rgrpToRemove.add(rgrpNum); } } for (Integer rgrpNum : rgrpToRemove) { rGroupQuery.getRGroupDefinitions().remove(rgrpNum); } } } /** * Helper method for {@link #cleanUpRGroup(IAtomContainerSet)}, checks if * an atom container referred to in the R-group still exists in the current * molecule set in the hub. * @param atcRgrp * @param chemModel */ private boolean exists(IAtomContainer atcRgrp,IAtomContainerSet moleculeSet) { for (IAtomContainer atc : moleculeSet.atomContainers()) { if(atc==atcRgrp) return true; } return false; } /** * The RGroupQuery references atom containers (the root and the substitutes). * However, other JCP modules can re-create the atom containers, such as happens * in {@link org.openscience.jchempaint.controller.undoredo.RemoveAtomsAndBondsEdit}. * In such cases, this method needs to be called to reset the atom containers in the * RGroup to the newly created ones. * * @param newSet molecule set with freshly created containers (but existing atoms) * @throws CDKException */ public void adjustAtomContainers(IAtomContainerSet newSet) throws CDKException { //System.out.println("^^^ adjustAtomContainers(IAtomContainerSet newSet)"); boolean hasRoot = false; if (rGroupQuery != null) { // collected up the 'live atoms' Set<IAtom> activeAtoms = new HashSet<>(); for (IAtomContainer newAtc : newSet.atomContainers()) { for (IAtom atom : newAtc.atoms()) activeAtoms.add(atom); } for (IAtomContainer newAtc : newSet.atomContainers()) { atoms: for (IAtom movedAtom : newAtc.atoms()) { if (rGroupQuery.getRootStructure().contains(movedAtom)) { //System.out.println("set root "+newAtc.hashCode()); newAtc.setProperty(CDKConstants.CTAB_SGROUPS, rGroupQuery.getRootStructure().getProperty(CDKConstants.CTAB_SGROUPS)); rGroupQuery.setRootStructure(newAtc); newAtc.setProperty(CDKConstants.TITLE, RGroup.ROOT_LABEL); hasRoot = true; break atoms; } else { Map<Integer, IRGroupList> def = rGroupQuery.getRGroupDefinitions(); for (int rgrpNum : def.keySet()) { List<IRGroup> rgpList = def.get(rgrpNum).getRGroups(); for (IRGroup rgp : rgpList) { // Check if rgp is of type RGroup before calling setGroup if (rgp != null && rgp.getGroup().contains(movedAtom)) { // Safely cast to RGroup if (rgp instanceof RGroup) { RGroup concreteRgp = (RGroup) rgp; concreteRgp.setGroup(newAtc); newAtc.setProperty(CDKConstants.TITLE, RGroup.makeLabel(rgrpNum)); break atoms; } } } } } } } if (!hasRoot) { System.err.println(">>BAD: lost track of the R-group"); this.rGroupQuery = null; for (IAtomContainer atc : newSet.atomContainers()) { atc.setProperty(CDKConstants.TITLE, null); } throw new CDKException("R-group invalidated"); } // Remove any R groups which have no 'active' atoms Map<Integer, IRGroupList> def = rGroupQuery.getRGroupDefinitions(); for (int rgrpNum : def.keySet()) { def.get(rgrpNum).getRGroups().removeIf(g -> { for (IAtom a : g.getGroup().atoms()) { if (activeAtoms.contains(AtomRef.deref(a))) return false; } return true; }); } } } /** * Verifies if a merge is allowed from the R-Group's point of view. * Merging between the root structure and r-group substitutes is not allowed, * because it does not makes sense (plus the root structure could get lost). * @param hub controller hub that is about to do a merge. */ public boolean isMergeAllowed(IChemModelRelay hub) { //System.out.println("^^^ isMergeAllowed(IChemModelRelay hub)"); if (rGroupQuery!=null) { for (Iterator<IAtom> it = hub.getRenderer().getRenderer2DModel().getMerge().keySet().iterator(); it.hasNext();) { IAtom mergedAtom = it.next(); IAtom mergedPartnerAtom = hub.getRenderer().getRenderer2DModel().getMerge().get(mergedAtom); IAtomContainer container1 = ChemModelManipulator.getRelevantAtomContainer(hub.getChemModel(), mergedAtom); IAtomContainer container2 = ChemModelManipulator.getRelevantAtomContainer(hub.getChemModel(), mergedPartnerAtom); if(container1!=container2) { List<IAtomContainer> substitutes = rGroupQuery.getSubstituents(); if ((container1==rGroupQuery.getRootStructure() && substitutes.contains(container2)) || (container2==rGroupQuery.getRootStructure() && substitutes.contains(container1))) { JOptionPane.showMessageDialog(jcpPanel.getRenderPanel(), GT.get("This operation is not allowed in the R-Group configuration."), GT.get("R-Group alert"), JOptionPane.INFORMATION_MESSAGE); return false; } } } } return true; } /** * Hashes the R-group's atom container-related information. * This can be used in the undo/redo of modules that change/drop/swap atom containers * such as merging. * @return hash mash of RGroup data */ public Map<Integer,Map<Integer,Integer>> makeHash() { Map<Integer,Map<Integer,Integer>> rgrpHash = new HashMap<Integer,Map<Integer,Integer>>(); if(rGroupQuery!=null) { Map<Integer,IRGroupList> def = rGroupQuery.getRGroupDefinitions(); for(Iterator<Integer> itr= def.keySet().iterator();itr.hasNext();) { int rgrpNum=itr.next(); List<IRGroup> rgpList = def.get(rgrpNum).getRGroups(); for(IRGroup rgp : rgpList) { if (rgp!=null) { Map<Integer,Integer> hash = new HashMap<Integer,Integer>(); hash.put(0, rgp.getGroup()==null?null:rgp.getGroup().hashCode()); hash.put(1, rgp.getFirstAttachmentPoint()==null?null:rgp.getFirstAttachmentPoint().hashCode()); hash.put(2, rgp.getSecondAttachmentPoint()==null?null:rgp.getSecondAttachmentPoint().hashCode()); rgrpHash.put(rgp.hashCode(),hash); } } } Map<Integer,Integer> root = new HashMap<Integer,Integer>(); root.put(0,rGroupQuery.getRootStructure().hashCode()); rgrpHash.put(-1,root ); } return rgrpHash; } /** * See restores what was saved by makeHash(). */ public void restoreFromHash(Map<Integer,Map<Integer,Integer>> mash, IAtomContainerSet mset) { if(rGroupQuery!=null) { int rootHash = mash.get(-1).get(0); rGroupQuery.setRootStructure(findContainer(rootHash,mset)); Map<Integer,IRGroupList> def = rGroupQuery.getRGroupDefinitions(); for (Iterator<Integer>rgpHashItr=mash.keySet().iterator(); rgpHashItr.hasNext();) { int rgpHash = rgpHashItr.next(); restore: for(Iterator<Integer> itr= def.keySet().iterator();itr.hasNext();) { int rgrpNum=itr.next(); List<IRGroup> rgpList = def.get(rgrpNum).getRGroups(); for (IRGroup rgp : rgpList) { if (rgp != null && rgp.hashCode() == rgpHash) { // Ensure rgp is an instance of RGroup if (rgp instanceof RGroup) { RGroup concreteRgp = (RGroup) rgp; // Cast rgp to RGroup // Now you can safely call setGroup concreteRgp.setGroup(findContainer(mash.get(rgpHash).get(0), mset)); } break restore; // Exit the loop when done } } } } } } /** * Method to detect if removing atoms/bonds has unwanted results for * the R-group. * * @param atc * @param hub * @return */ public boolean checkRGroupOkayForDelete(AtomBondSet atc, IChemModelRelay hub) { //Check if the root would still remain there (partly) after a delete.. if(rGroupQuery!=null) { boolean rootRemains=false; root: for(IAtom a : rGroupQuery.getRootStructure().atoms()) { if (!atc.contains(a)){ rootRemains=true; break root; } } if (!rootRemains) { int answer = JOptionPane.showConfirmDialog(jcpPanel.getRenderPanel(), GT.get("This operation would irreversibly remove the R-Group query. Continue?"), GT.get("R-Group alert"), JOptionPane.YES_NO_OPTION); if(answer == JOptionPane.NO_OPTION) return false; } } return true; } /** * TODO * @param at * @param hub * @return */ public boolean checkRGroupOkayForDelete(IAtom at,IChemModelRelay hub ) { AtomBondSet tmp = new AtomBondSet(); tmp.add(at); return (checkRGroupOkayForDelete(tmp,hub)); } /** * TODO * @param atcHash * @param mset * @return */ private IAtomContainer findContainer (Integer atcHash, IAtomContainerSet mset) { if(atcHash!=null) for (IAtomContainer atc : mset.atomContainers()) { if(atc.hashCode()==atcHash) return atc; } return null; } /** * TODO * @param atHash * @param atc * @return */ private IAtom findAtom (Integer atHash, IAtomContainer atc) { if (atHash!=null) for (IAtom at : atc.atoms()) { if(at.hashCode()==atHash) return at; } return null; } /** * Method to check whether a given atom is part of one of the substitutes. * @param atom */ public boolean isAtomPartOfSubstitute(IAtom atom) { if (rGroupQuery!=null && rGroupQuery.getRGroupDefinitions()!=null) { for (Iterator<Integer> itr = rGroupQuery.getRGroupDefinitions().keySet().iterator(); itr.hasNext(); ) { IRGroupList rgpList =rGroupQuery.getRGroupDefinitions().get(itr.next()); if(rgpList!=null && rgpList.getRGroups()!=null) { for (IRGroup rgrp: rgpList.getRGroups() ) { if(rgrp.getGroup().contains(atom)) { return true; } } } } } return false; } /** * Method to check whether a given bond exists in the root and is attached * to an R-Group. * @param bond */ public boolean isRGroupRootBond(IBond bond) { if (rGroupQuery!=null && rGroupQuery.getRootStructure()!=null && rGroupQuery.getRootStructure().contains(bond)) { for(IAtom atom : bond.atoms()) { if (atom instanceof IPseudoAtom && RGroupQuery.isValidRgroupQueryLabel(((IPseudoAtom)atom).getLabel())) { return true; } } } return false; } }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/io/ChemicalFilesFilter.java
.java
1,585
68
/** * */ package org.openscience.jchempaint.io; import java.io.File; /** * Displays all CML/SMILES/IUPAC/SDF/MOL/RXN files * in a filechooser * * @author ralf * */ public class ChemicalFilesFilter extends javax.swing.filechooser.FileFilter { /** * Get the extension of a file. * Gets the extension attribute of the JCPFileFilter class * *@param f Description of the Parameter *@return The extension value */ public static String getExtension(File f) { String ext = null; String s = f.getName(); int i = s.lastIndexOf('.'); if (i > 0 && i < s.length() - 1) { ext = s.substring(i + 1).toLowerCase(); } return ext; } public boolean accept(File f) { if (f.isDirectory()) { return true; } String extension = getExtension(f); if (extension != null) { extension = extension.toLowerCase(); if (extension.equals("cml") || extension.equals("smi") || extension.equals("smiles") || extension.equals("sdf") || extension.equals("txt") || extension.equals("iupac") || extension.equals("inchi") || extension.equals("mol") || extension.equals("rxn")) { return true; } else { return false; } } return false; } //The description of this filter public String getDescription() { return "CML/SMILES/IUPAC/SDF/MOL/RXN"; } }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/io/JCPFileView.java
.java
3,324
129
/* * $RCSfile$ * $Author: egonw $ * $Date: 2007-01-04 17:26:00 +0000 (Thu, 04 Jan 2007) $ * $Revision: 7634 $ * * Copyright (C) 1997-2008 Stefan Kuhn * * Contact: cdk-jchempaint@lists.sourceforge.net * * 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.jchempaint.io; import java.io.File; import javax.swing.Icon; /** * The file view class * */ public class JCPFileView extends javax.swing.filechooser.FileView { /** * Gets the name attribute of the JCPFileView object * *@param f Description of the Parameter *@return The name value */ public String getName(File f) { return null; // let the L&F FileView figure this out } /** * Gets the description attribute of the JCPFileView object * *@param f Description of the Parameter *@return The description value */ public String getDescription(File f) { return null; // let the L&F FileView figure this out } /** * Gets the traversable attribute of the JCPFileView object * *@param f Description of the Parameter *@return The traversable value */ public Boolean isTraversable(File f) { return null; // let the L&F FileView figure this out } /** * Gets the typeDescription attribute of the JCPFileView object * *@param f Description of the Parameter *@return The typeDescription value */ public String getTypeDescription(File f) { String extension = JCPFileFilter.getExtension(f); JCPFileFilter jcpff = new JCPFileFilter(extension); String type = null; if (extension != null) { type = jcpff.getDescription(); } return type; } /** * Gets the icon attribute of the JCPFileView object * *@param f Description of the Parameter *@return The icon value */ public Icon getIcon(File f) { Icon icon = null; // String extension = JCPFileFilter.getExtension(f); // if (extension != null) { // if (extension.equals(Utils.jpeg) || // extension.equals(Utils.jpg)) { // icon = jpgIcon; // } else if (extension.equals(Utils.gif)) { // icon = gifIcon; // } else if (extension.equals(Utils.tiff) || // extension.equals(Utils.tif)) { // icon = tiffIcon; // } // } return icon; } }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/io/JCPSaveFileFilter.java
.java
2,968
82
/* * $RCSfile$ * $Author: egonw $ * $Date: 2007-01-04 17:26:00 +0000 (Thu, 04 Jan 2007) $ * $Revision: 7634 $ * * Copyright (C) 1997-2008 Stefan Kuhn * * Contact: cdk-jchempaint@lists.sourceforge.net * * 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.jchempaint.io; import javax.swing.JFileChooser; import org.openscience.jchempaint.GT; /** * It intentionally extends JCPFileFilter to remove redundant * data. * */ public class JCPSaveFileFilter extends JCPFileFilter { // only those extensions are given here that are *not* on JCPFileFilter public final static String svg = "svg"; public final static String smiles = "smiles"; public final static String cdk = "cdk"; public JCPSaveFileFilter(String type) { super(type); } /** * Adds the JCPFileFilter to the JFileChooser object. */ public static void addChoosableFileFilters(JFileChooser chooser) { chooser.addChoosableFileFilter(new JCPFileFilter(JCPFileFilter.mol)); chooser.addChoosableFileFilter(new JCPSaveFileFilter(JCPSaveFileFilter.cdk)); chooser.addChoosableFileFilter(new JCPFileFilter(JCPFileFilter.cml)); chooser.addChoosableFileFilter(new JCPFileFilter(JCPFileFilter.rxn)); chooser.addChoosableFileFilter(new JCPSaveFileFilter(JCPSaveFileFilter.smiles)); chooser.addChoosableFileFilter(new JCPFileFilter(JCPFileFilter.inchi)); } /** * The description of this filter. */ public String getDescription() { String type = (String)types.get(0); String result = super.getDescription(); if (result == null) { if (type.equals(svg)) { result = "Scalable Vector Graphics"; } else if (type.equals(smiles)) { result = "SMILES"; } else if (type.equals(cdk)) { result = GT.get("CDK source code fragment"); } } return result; } }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/io/FileHandler.java
.java
5,965
166
package org.openscience.jchempaint.io; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.Reader; import java.net.URL; import javax.swing.JOptionPane; import org.openscience.cdk.exception.CDKException; import org.openscience.cdk.io.CMLReader; import org.openscience.cdk.io.FormatFactory; import org.openscience.cdk.io.INChIReader; import org.openscience.cdk.io.ISimpleChemObjectReader; import org.openscience.cdk.io.MDLRXNV2000Reader; import org.openscience.cdk.io.MDLV2000Reader; import org.openscience.cdk.io.RGroupQueryReader; import org.openscience.cdk.io.SMILESReader; import org.openscience.cdk.io.formats.CMLFormat; import org.openscience.cdk.io.formats.IChemFormat; import org.openscience.cdk.io.formats.MDLV2000Format; import org.openscience.cdk.io.formats.RGroupQueryFormat; import org.openscience.jchempaint.GT; /** * Some file handling operation, moved out of JChemPaint class. * @author markr */ public class FileHandler { /** * Creates a reader for a given URL, guessing the file type * using the various IChemFormats. * @param url * @param urlString * @param type * @return * @throws CDKException */ public static ISimpleChemObjectReader createReader(URL url,String urlString, String type) throws CDKException { String ext = type; // handle all degenerate cases first if (type == null || type.equals("")) { int i = urlString.lastIndexOf('.'); if (i > 0 && i < urlString.length() - 1) ext = urlString.substring(i + 1).toLowerCase(); else ext = "mol"; } ISimpleChemObjectReader cor = null; try { /* ReaderFactory.createReader was used before to find the right reader, but this * created problems (when applet shrunk with Yguard) because of the classloader * used in the ReaderFactory, runtime errors. * Instead, we avoid ReaderFactory and pick the right reader below ourselves. */ Reader input = new BufferedReader(getReader(url)); FormatFactory formatFactory = new FormatFactory(8192); IChemFormat format=formatFactory.guessFormat(input); if (format!=null) { if (format instanceof RGroupQueryFormat ) { cor = new RGroupQueryReader(); cor.setReader(input); } else if (format instanceof CMLFormat ) { cor = new CMLReader(urlString); cor.setReader(url.openStream()); } else if (format instanceof MDLV2000Format ) { cor = new MDLV2000Reader(getReader(url)); cor.setReader(input); } // SMILES format is never guessed :( //else if (format instanceof SMILESFormat ) { // cor = new SMILESReader(getReader(url)); // cor.setReader(input); //} //InChI format is never guessed :( //else if (format instanceof INChIPlainTextFormat ) { // cor = new INChIPlainTextReader(getReader(url)); // cor.setReader(input); //} } } catch (Exception exc) { exc.printStackTrace(); } if (cor == null) { // try to determine from user's guess type = ext; if (type.equals(JCPFileFilter.cml)|| type.equals(JCPFileFilter.xml)) { cor = new CMLReader(urlString); } else if (type.equals(JCPFileFilter.sdf)) { cor = new MDLV2000Reader(getReader(url)); } else if (type.equals(JCPFileFilter.mol)) { cor = new MDLV2000Reader(getReader(url)); } else if (type.equals(JCPFileFilter.inchi)) { try { cor = new INChIReader(new URL(urlString).openStream()); } catch (Exception e) { e.printStackTrace(); } } else if (type.equals(JCPFileFilter.rxn)) { cor = new MDLRXNV2000Reader(getReader(url)); } else if (type.equals(JCPFileFilter.smi) || type.equals("smiles")) { cor = new SMILESReader(getReader(url)); } } if (cor == null) { throw new CDKException(GT.get("Could not determine file format")); } // Take care of files called .mol, but having several, sdf-style entries if (cor instanceof MDLV2000Reader) { try { BufferedReader in = new BufferedReader(getReader(url)); String line; while ((line = in.readLine()) != null) { if (line.equals("$$$$")) { String message = GT .get("It seems you opened a mol or sdf" + " file containing several molecules. " + "Only the first one will be shown"); JOptionPane.showMessageDialog(null, message, GT .get("sdf-like file"), JOptionPane.INFORMATION_MESSAGE); break; } } } catch (IOException ex) { // we do nothing - firstly if IO does not work, we should not // get here, secondly, if only this does not work, don't worry ex.printStackTrace(); } } return cor; } /** * Private helper method to construct a reader from a URL. * @param url * @return */ private static Reader getReader(URL url) { InputStreamReader reader = null; try { reader = new InputStreamReader(url.openStream()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return reader; } }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/io/IJCPFileFilter.java
.java
1,660
54
/* * $RCSfile$ * $Author: egonw $ * $Date: 2007-01-04 17:26:00 +0000 (Thu, 04 Jan 2007) $ * $Revision: 7634 $ * * Copyright (C) 1997-2008 Stefan Kuhn * * Contact: cdk-jchempaint@lists.sourceforge.net * * 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.jchempaint.io; /** * The interface for JCP file filters * */ public interface IJCPFileFilter { /** * Gets the type attribute of the JCPFileFilterInterface object * *@return The type value */ public String getType(); /** * Sets the type attribute of the JCPFileFilterInterface object * *@param type The new type value */ public void setType(String type); }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/io/JCPFileFilter.java
.java
5,753
241
/* * $RCSfile$ * $Author: egonw $ * $Date: 2007-01-04 17:26:00 +0000 (Thu, 04 Jan 2007) $ * $Revision: 7634 $ * * Copyright (C) 1997-2008 Stefan Kuhn * * Contact: cdk-jchempaint@lists.sourceforge.net * * 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.jchempaint.io; import java.io.File; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.swing.JFileChooser; import org.openscience.jchempaint.GT; /** * A file filter for JCP * */ public class JCPFileFilter extends javax.swing.filechooser.FileFilter implements IJCPFileFilter { /** * Description of the Field */ public final static String rxn = "rxn"; /** * Description of the Field */ public final static String sdf = "sdf"; /** * Description of the Field */ public final static String mol = "mol"; /** * Description of the Field */ public final static String cml = "cml"; /** * Description of the Field */ public final static String xml = "xml"; /** * Description of the Field */ public final static String inchi = "txt"; /** * Description of the Field */ public final static String smi = "smi"; /** * Description of the Field */ protected List<String> types; /** * Alternative extensions to indicate file type. For example * a SMILES file is standard "xxx.smi", but could also be "xxx.smiles". * Add more alternatives to this map when required. */ public static Map<String, String> alternativeExtensions; static { alternativeExtensions = new HashMap<String, String>(); alternativeExtensions.put("smiles", "smi"); alternativeExtensions.put("smil", "smi"); } /** * Constructor for the JCPFileFilter object * *@param type Description of the Parameter */ public JCPFileFilter(String type) { super(); types = new ArrayList<>(); types.add(type); } /** * Adds the JCPFileFilter to the JFileChooser object. * *@param chooser The feature to be added to the ChoosableFileFilters * attribute */ public static void addChoosableFileFilters(JFileChooser chooser) { chooser.addChoosableFileFilter(new JCPSaveFileFilter(JCPFileFilter.cml)); chooser.addChoosableFileFilter(new JCPFileFilter(JCPFileFilter.smi)); chooser.addChoosableFileFilter(new JCPFileFilter(JCPFileFilter.inchi)); chooser.addChoosableFileFilter(new JCPFileFilter(JCPFileFilter.sdf)); chooser.addChoosableFileFilter(new JCPFileFilter(JCPFileFilter.rxn)); JCPFileFilter molFilter = new JCPFileFilter(JCPFileFilter.mol); //molFilter.addType(JCPFileFilter.mol); chooser.addChoosableFileFilter(molFilter); } /** * Get the extension of a file. * Gets the extension attribute of the JCPFileFilter class * *@param f Description of the Parameter *@return The extension value */ public static String getExtension(File f) { String ext = null; String s = f.getName(); int i = s.lastIndexOf('.'); if (i > 0 && i < s.length() - 1) { ext = s.substring(i + 1).toLowerCase(); } return ext; } private boolean isAlternative (String extension, String type ) { for ( Iterator<String> alternatives = alternativeExtensions.keySet().iterator();alternatives.hasNext();) { String alt = alternatives.next(); if (alt.equals(extension)) if (alternativeExtensions.get(alt).equals(type)) return true; } return false; } // Accept all directories and all gif, jpg, or tiff files. public boolean accept(File f) { if (f.isDirectory()) { return true; } String extension = getExtension(f); if (extension != null) { if (types.contains(extension) || isAlternative (extension, types.get(0)) ) { return true; } else { return false; } } return false; } /** * Gets a descriptive string for the currently choosen file type * *@return The description */ public String getDescription() { String type = types.get(0); if (type.equals(mol)) { return GT.get("MDL molfile"); } if (type.equals(sdf)) { return GT.get("MDL SDfile"); } if (type.equals(rxn)) { return GT.get("MDL RXNfile"); } if (type.equals(inchi)) { return GT.get("IUPAC Chemical Identifier"); } if (type.equals(smi)) { return "SMILES"; } if (type.equals(cml) || type.equals(xml)) { return "Chemical Markup Language"; } return null; } /** * Gets the type attribute of the JCPFileFilter object * *@return The type value */ public String getType() { return types.get(0); } /** * Sets the type attribute of the JCPFileFilter object * *@param type The new type value */ public void setType(String type) { types.add(type); } }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/io/JCPExportFileFilter.java
.java
4,148
130
/* $RCSfile$ * $Author: egonw $ * $Date: 2007-01-04 17:26:00 +0000 (Thu, 04 Jan 2007) $ * $Revision: 7634 $ * * Copyright (C) 2003-2007 The JChemPaint project * * Contact: jchempaint-devel@lists.sourceforge.net * * 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.jchempaint.io; import java.io.File; import java.util.List; import java.util.ArrayList; import javax.swing.JFileChooser; /** * An export filter for JCP file formats * * @cdk.module jchempaint * @author Egon Willighagen * @cdk.created 2003-04-01 */ public class JCPExportFileFilter extends javax.swing.filechooser.FileFilter implements IJCPFileFilter { // only those extensions are given here that are *not* on JCPFileFilter public final static String bmp = "bmp"; public final static String png = "png"; public final static String jpg = "jpg"; public final static String svg = "svg"; public final static String pdf = "pdf"; protected List<String> types; public JCPExportFileFilter(String type) { super(); types = new ArrayList<String>(); types.add(type); } /** * Adds the JCPFileFilter to the JFileChooser object. */ public static void addChoosableFileFilters(JFileChooser chooser) { chooser.addChoosableFileFilter(new JCPExportFileFilter(JCPExportFileFilter.pdf)); chooser.addChoosableFileFilter(new JCPExportFileFilter(JCPExportFileFilter.svg)); chooser.addChoosableFileFilter(new JCPExportFileFilter(JCPExportFileFilter.png)); chooser.addChoosableFileFilter(new JCPExportFileFilter(JCPExportFileFilter.bmp)); chooser.addChoosableFileFilter(new JCPExportFileFilter(JCPExportFileFilter.jpg)); } /** * The description of this filter. */ public String getDescription() { String type = (String)types.get(0); String result = "Unknown"; if (type.equals(png)) { result = "PNG"; } else if (type.equals(bmp)) { result = "BMP"; } else if (type.equals(jpg)) { result = "JPEG"; } else if (type.equals(svg)) { result = "Scalable Vector Graphics"; } else if (type.equals(pdf)) { result = "PDF"; } return result; } // Accept all directories and all gif, jpg, or tiff files. public boolean accept(File f) { boolean accepted = false; if (f.isDirectory()) { accepted = true; } String extension = getExtension(f); if (extension != null) { if (types.contains(extension)) { accepted = true; } } return accepted; } /* * Get the extension of a file. */ public static String getExtension(File f) { String ext = null; String s = f.getName(); int i = s.lastIndexOf('.'); if (i > 0 && i < s.length() - 1) { ext = s.substring(i+1).toLowerCase(); } return ext; } public String getType() { return (String)types.get(0); } public void setType(String type) { types.add(type); } }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/applet/JChemPaintEditorApplet.java
.java
2,191
52
/* * $RCSfile$ * $Author: egonw $ * $Date: 2007-01-04 17:26:00 +0000 (Thu, 04 Jan 2007) $ * $Revision: 7634 $ * * Copyright (C) 1997-2008 Stefan Kuhn * * Contact: cdk-jchempaint@lists.sourceforge.net * * 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.jchempaint.applet; import org.openscience.cdk.DefaultChemObjectBuilder; import org.openscience.cdk.interfaces.IAtomContainer; import org.openscience.cdk.interfaces.IChemModel; import org.openscience.cdk.interfaces.IAtomContainerSet; import org.openscience.jchempaint.JChemPaintPanel; public class JChemPaintEditorApplet extends JChemPaintAbstractApplet{ public static final String GUI_APPLET="applet"; public void init() { super.init(); IChemModel chemModel = DefaultChemObjectBuilder.getInstance().newInstance(IChemModel.class); chemModel.setMoleculeSet(chemModel.getBuilder().newInstance(IAtomContainerSet.class)); chemModel.getMoleculeSet().addAtomContainer(chemModel.getBuilder().newInstance(IAtomContainer.class)); JChemPaintPanel p = new JChemPaintPanel(chemModel,GUI_APPLET,debug,this, this.blocked); p.setName("appletframe"); p.setShowInsertTextField(true); setTheJcpp(p); this.add(p); } }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/applet/JChemPaintViewerApplet.java
.java
3,569
91
/* * $RCSfile$ * $Author: egonw $ * $Date: 2007-01-04 17:26:00 +0000 (Thu, 04 Jan 2007) $ * $Revision: 7634 $ * * Copyright (C) 1997-2008 Stefan Kuhn * * Contact: cdk-jchempaint@lists.sourceforge.net * * 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.jchempaint.applet; import java.applet.Applet; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import org.openscience.cdk.ChemModel; import org.openscience.jchempaint.JChemPaintViewerPanel; public class JChemPaintViewerApplet extends JChemPaintAbstractApplet{ int oldnumber=-1; public void init() { boolean fitToScreen = false; String scrollbarParam = this.getParameter("scrollbars"); if (scrollbarParam != null && scrollbarParam.equals("false")) { fitToScreen = true; } JChemPaintViewerPanel p = new JChemPaintViewerPanel( new ChemModel(), getWidth(), getHeight(), fitToScreen, debug, this); setTheJcpp(p); this.add(p); super.init(); } /** * Handles interaction with a peak table * @param atomNumber atom number of peaks highlighted in table */ public void highlightPeakInTable(int atomNumber) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException{ if(getParameter("highlightTable")==null || getParameter("highlightTable").equals("false")) return; Class<?>[] paratypes={new Applet().getClass()}; Class<?> jso = Class.forName("netscape.javascript.JSObject"); Method getWindowMethod=jso.getMethod("getWindow", paratypes); Object win=getWindowMethod.invoke(jso, new Object[] {this}); Class<?>[] paratypes2={new String("").getClass()}; Method evalMethod=jso.getMethod("eval", paratypes2); Class<?>[] paratypes3={new String("").getClass(),new Object().getClass()}; Method setMemberMethod=jso.getMethod("setMember", paratypes3); if(oldnumber!=-1){ Object tr = evalMethod.invoke(win,new Object[]{"document.getElementById(\"tableid"+oldnumber+"\").style"}); if((oldnumber+1)%2==0) setMemberMethod.invoke(tr, new Object[]{"backgroundColor","#D3D3D3"}); else setMemberMethod.invoke(tr, new Object[]{"backgroundColor","white"}); } Object tr = evalMethod.invoke(win,new Object[]{"document.getElementById(\"tableid"+atomNumber+"\").style"}); if(tr==null){ oldnumber=-1; }else{ setMemberMethod.invoke(tr, new Object[]{"backgroundColor","#FF6600"}); oldnumber=atomNumber; } } }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/applet/JChemPaintAbstractApplet.java
.java
27,868
721
/* * $RCSfile$ * $Author: egonw $ * $Date: 2007-01-04 17:26:00 +0000 (Thu, 04 Jan 2007) $ * $Revision: 7634 $ * * Copyright (C) 1997-2008 Stefan Kuhn * * Contact: cdk-jchempaint@lists.sourceforge.net * * 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.jchempaint.applet; import java.awt.Color; import java.awt.Container; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.IOException; import java.io.StringReader; import java.io.StringWriter; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.ResourceBundle; import java.util.Set; import java.util.StringTokenizer; import javax.swing.JApplet; import org.openscience.cdk.ChemModel; import org.openscience.cdk.DefaultChemObjectBuilder; import org.openscience.cdk.config.Isotopes; import org.openscience.cdk.exception.CDKException; import org.openscience.cdk.interfaces.IAtom; import org.openscience.cdk.interfaces.IAtomContainer; import org.openscience.cdk.interfaces.IChemModel; import org.openscience.cdk.interfaces.IMolecularFormula; import org.openscience.cdk.io.ISimpleChemObjectReader; import org.openscience.cdk.io.MDLV2000Reader; import org.openscience.cdk.io.MDLV2000Writer; import org.openscience.cdk.io.RGroupQueryReader; import org.openscience.cdk.io.RGroupQueryWriter; import org.openscience.cdk.io.IChemObjectReader.Mode; import org.openscience.cdk.smiles.SmilesParser; import org.openscience.cdk.tools.CDKHydrogenAdder; import org.openscience.cdk.tools.manipulator.ChemModelManipulator; import org.openscience.cdk.tools.manipulator.MolecularFormulaManipulator; import org.openscience.jchempaint.AbstractJChemPaintPanel; import org.openscience.jchempaint.GT; import org.openscience.jchempaint.JChemPaintPanel; import org.openscience.jchempaint.JExternalFrame; import org.openscience.jchempaint.StringHelper; import org.openscience.jchempaint.action.CreateSmilesAction; import org.openscience.jchempaint.application.JChemPaint; import org.openscience.jchempaint.controller.IControllerModel; import org.openscience.jchempaint.renderer.JChemPaintRendererModel; import org.openscience.cdk.renderer.selection.IChemObjectSelection; import org.openscience.jchempaint.renderer.selection.LogicalSelection; /** * An abstract class for JCP applets, doing parameter parsing. * * @jcp.params * */ public abstract class JChemPaintAbstractApplet extends JApplet { private AbstractJChemPaintPanel theJcpp = null; private JExternalFrame jexf; protected boolean debug = false; protected Set<String> blocked = new HashSet<>(); private static String appletInfo = "JChemPaint Applet. See http://jchempaint.github.com " + "for more information"; public static String[][] paramInfo; static{ List<List<String>> infos = new ArrayList<List<String>>(); infos.add(Arrays.asList("background", "color", "Background color as integer or hex starting with #")); infos.add(Arrays.asList("atomNumbersVisible", "true or false", "should atom numbers be shown")); infos.add(Arrays.asList("load", "url", "URL of the chemical data")); infos.add(Arrays.asList("compact", "true or false", "compact means elements shown as dots, no figures etc. (default false)" )); infos.add(Arrays.asList("tooltips", "string like 'atomumber|test|atomnumber|text'", "the texts will be used as tooltips for the respective atoms (leave out if none required")); infos.add(Arrays.asList("impliciths", "true or false", "the implicit hs will be added from start (default true)")); infos.add(Arrays.asList("spectrumRenderer", "string", "name of a spectrum applet (see subproject in NMRShiftDB) where peaks should be highlighted when hovering over atom")); infos.add(Arrays.asList("hightlightTable", "true or false", "if true peaks in a table will be highlighted when hovering over atom, ids are assumed to be tableidX, where X=atomnumber starting with 0 (default false)" )); infos.add(Arrays.asList("smiles", "string", "a structure to load as smiles")); infos.add(Arrays.asList("mol", "string", "a structure to load as MOL V2000")); infos.add(Arrays.asList("scrollbars", "true or false", "if the molecule is too big to be displayed in normal size, shall scrollbars be used (default) or the molecule be resized - only for viewer applet")); infos.add(Arrays.asList("dotranslate", "true or false", "should user interface be translated (default) or not (e. g. if you want an English-only webpage)")); infos.add(Arrays.asList("language", "language code", "a valid language code to use for ui language")); infos.add(Arrays.asList("detachable", "true or false", "should the applet be detacheable by a double click (default false)")); infos.add(Arrays.asList("detachableeditor", "true or false", "should the applet be detacheable as an editor by a double click (default false), only for viewer")); infos.add(Arrays.asList("debug", "true or false", "switches on debug output (default false)")); String resource = "org.openscience.jchempaint.resources.features"; ResourceBundle featuresDefinition = ResourceBundle.getBundle(resource, Locale.getDefault()); Iterator<String> featuresit = featuresDefinition.keySet().iterator(); while(featuresit.hasNext()){ String feature = featuresit.next(); infos.add(Arrays.asList(feature,"on or off","switches on or off the ui elements of this feature (default on)")); } paramInfo = new String[infos.size()][3]; for(int i=0;i<infos.size();i++){ paramInfo[i]=infos.get(i).toArray(new String[3]); } } /** * Gives basic information about the applet. * @see java.applet.Applet#getAppletInfo() */ @Override public String getAppletInfo() { return appletInfo; } /** * Gives informations about applet params. * @see java.applet.Applet#getParameterInfo() */ @Override public String[][] getParameterInfo() { return paramInfo; } /** * loads a molecule from url or smiles */ protected void loadModelFromParam() { URL fileURL = null; String smiles = null; String mol = null; try { URL documentBase = getDocumentBase(); String load = getParameter("load"); if (load != null) fileURL = new URL(documentBase, load); smiles = getParameter("smiles"); mol = getParameter("mol"); } catch (Exception exception) { theJcpp.announceError(exception); } if (fileURL != null) loadModelFromUrl(fileURL, theJcpp); if (smiles != null) loadModelFromSmiles(smiles); if (mol != null) { try { setMolFileWithReplace(mol); } catch (Exception exception) { theJcpp.announceError(exception); } } } /** * Loads a molecule from a smiles into jcp * * @param fileURL */ public void loadModelFromSmiles(String smiles) { if (smiles != null) { try { SmilesParser sp = new SmilesParser(DefaultChemObjectBuilder .getInstance()); IAtomContainer mol = sp.parseSmiles(smiles); //for some reason, smilesparser sets valencies, which we don't want in jcp for(int i=0;i<mol.getAtomCount();i++){ mol.getAtom(i).setValency(null); } JChemPaint.generateModel(theJcpp, mol, true, true); /*StructureDiagramGenerator sdg = new StructureDiagramGenerator(); sdg.setMolecule(mol); sdg.generateCoordinates(new Vector2d(0, 1)); mol = sdg.getMolecule(); mol = new FixBondOrdersTool().kekuliseAromaticRings(mol); IChemModel chemModel = DefaultChemObjectBuilder.getInstance() .newInstance(IChemModel.class); chemModel.setMoleculeSet(DefaultChemObjectBuilder.getInstance() .newInstance(IAtomContainerSet.class)); chemModel.getMoleculeSet().addAtomContainer(mol); theJcpp.setChemModel(chemModel); IUndoRedoFactory undoRedoFactory= theJcpp.get2DHub().getUndoRedoFactory(); UndoRedoHandler undoRedoHandler= theJcpp.get2DHub().getUndoRedoHandler(); if (undoRedoFactory!=null) { IUndoRedoable undoredo = undoRedoFactory.getAddAtomsAndBondsEdit(theJcpp.get2DHub().getIChemModel(), mol, null, "Paste", theJcpp.get2DHub()); undoRedoHandler.postEdit(undoredo); } theJcpp.updateUndoRedoControls();*/ } catch (Exception exception) { theJcpp.announceError(exception); } } else { theJcpp.setChemModel(new ChemModel()); } } public void setSmiles(String smiles) { loadModelFromSmiles(smiles); theJcpp.get2DHub().updateView(); repaint(); } /** * Loads a molecule from a url into jcp * * @param fileURL */ public void loadModelFromUrl(URL fileURL, AbstractJChemPaintPanel panel) { try { IChemModel chemModel = JChemPaint.readFromFileReader(fileURL, fileURL.toString(), null, panel); theJcpp.setChemModel(chemModel); } catch (Exception exception) { theJcpp.announceError(exception); } } /** * NOT FOR USE FROM JavaScript. */ @Override public void start() { // Parameter parsing goes here loadModelFromParam(); JChemPaintRendererModel rendererModel = theJcpp.get2DHub().getRenderer() .getRenderer2DModel(); IChemModel chemModel = theJcpp.getChemModel(); IControllerModel controllerModel = theJcpp.get2DHub() .getController2DModel(); String atomNumbers = getParameter("atomNumbersVisible"); if (atomNumbers != null) { if (atomNumbers.equals("true")) rendererModel.setDrawNumbers(true); } String background = getParameter("background"); if (background != null) { if (background.indexOf("#") == 0) rendererModel.setBackColor(Color.decode(background)); else rendererModel.setBackColor(new Color(Integer .parseInt(background))); theJcpp.getRenderPanel() .setBackground(rendererModel.getBackColor()); } if (getParameter("compact") != null && getParameter("compact").equals("true")) { rendererModel.setIsCompact(true); } if (getParameter("tooltips") != null) { StringTokenizer st = new StringTokenizer(getParameter("tooltips"), "|"); IAtomContainer container = theJcpp.getChemModel().getBuilder() .newInstance(IAtomContainer.class); Iterator<IAtomContainer> containers = ChemModelManipulator .getAllAtomContainers(chemModel).iterator(); while (containers.hasNext()) { IAtomContainer ac=containers.next(); container.add(ac); } while (st.hasMoreTokens()) { IAtom atom = container .getAtom(Integer.parseInt(st.nextToken()) - 1); rendererModel.getToolTipTextMap().put(atom, st.nextToken()); } rendererModel.setShowTooltip(true); } if (getParameter("dotranslate") != null && getParameter("dotranslate").equals("false")) { GT.setDoTranslate(false); } if (getParameter("language") != null) { GT.setLanguage(getParameter("language")); theJcpp.updateMenusWithLanguage(); } if (getParameter("debug") != null && getParameter("debug").equals("true")) { this.debug = true; } if ( (getParameter("impliciths") == null) || (getParameter("impliciths") != null && getParameter("impliciths").equals("true")) ) { controllerModel.setAutoUpdateImplicitHydrogens(true); rendererModel.setShowImplicitHydrogens(true); rendererModel.setShowEndCarbons(true); } else { controllerModel.setAutoUpdateImplicitHydrogens(false); rendererModel.setShowImplicitHydrogens(false); rendererModel.setShowEndCarbons(false); if (chemModel != null) { List<IAtomContainer> atomContainers = ChemModelManipulator .getAllAtomContainers(chemModel); for (int i = 0; i < atomContainers.size(); i++) { try { CDKHydrogenAdder.getInstance( atomContainers.get(i).getBuilder()) .addImplicitHydrogens(atomContainers.get(i)); } catch (CDKException e) { // do nothing } } } } } /** * NOT FOR USE FROM JavaScript. */ @Override public void init() { String resource = "org.openscience.jchempaint.resources.features"; ResourceBundle featuresDefinition = ResourceBundle.getBundle(resource, Locale.getDefault()); Iterator<String> featuresit = featuresDefinition.keySet().iterator(); while(featuresit.hasNext()){ String feature = featuresit.next(); if (getParameter(feature) != null && getParameter(feature).equals("off")) { blocked.add(feature); String[] members = StringHelper.tokenize(featuresDefinition.getString(feature)); Collections.addAll(blocked, members); } } prepareExternalFrame(); } /** * NOT FOR USE FROM JavaScript. */ @Override public void stop() { } /** * @return Returns the theJcpp. */ private AbstractJChemPaintPanel getTheJcpp() { return theJcpp; } /** * @param theJcpp * The theJcpp to set. */ protected void setTheJcpp(AbstractJChemPaintPanel theJcpp) { this.theJcpp = theJcpp; } /** * Gives a mol file of the current molecules in the editor (not reactions). * RGroup queries are also saved as .mol files by convention. * * @return The mol file * @throws CDKException */ public String getMolFile() throws CDKException { StringWriter sw = new StringWriter(); org.openscience.cdk.interfaces.IChemModel som = theJcpp.getChemModel(); if (theJcpp.get2DHub().getRGroupHandler()!=null) { try (RGroupQueryWriter rgw = new RGroupQueryWriter(sw)) { rgw.write(theJcpp.get2DHub().getRGroupHandler().getrGroupQuery()); rgw.close(); } catch (IOException e) { e.printStackTrace(); } } else { MDLV2000Writer mdlwriter = new MDLV2000Writer(sw); mdlwriter.write(som); try { mdlwriter.close(); } catch (IOException e) { e.printStackTrace(); } } return (sw.toString()); } /** * Gives a smiles of the current editor content * * @return The smiles * @throws CloneNotSupportedException * @throws IOException * @throws ClassNotFoundException * @throws CDKException */ public String getSmiles() throws CDKException, ClassNotFoundException, IOException, CloneNotSupportedException { return CreateSmilesAction.getSmiles(theJcpp.getChemModel()); } /** * Gives a chiral smiles of the current editor content * * @return The smiles * @throws CloneNotSupportedException * @throws IOException * @throws ClassNotFoundException * @throws CDKException */ public String getSmilesChiral() throws CDKException, ClassNotFoundException, IOException, CloneNotSupportedException { return CreateSmilesAction.getSmiles(theJcpp.getChemModel()); } /** * This method sets a structure in the editor and leaves the old one. This * method replaces all \n characters with the system line separator. This * can be used when setting a mol file in an applet without knowing which * platform the applet is running on. * * @param mol * The mol file to set (V2000) * @throws Exception */ public void addMolFileWithReplace(String mol) throws Exception { StringBuffer newmol = new StringBuffer(); int s = 0; int e = 0; while ((e = mol.indexOf("\\n", s)) >= 0) { newmol.append(mol.substring(s, e)); newmol.append(System.getProperty("line.separator")); s = e + 2; } newmol.append(mol.substring(s)); MDLV2000Reader reader = new MDLV2000Reader(new StringReader(newmol .toString())); IAtomContainer cdkmol = (IAtomContainer) reader.read(DefaultChemObjectBuilder .getInstance().newInstance(IAtomContainer.class)); reader.close(); JChemPaint.generateModel(theJcpp, cdkmol, false,true); theJcpp.get2DHub().updateView(); // the newly opened file should nicely fit the screen theJcpp.getRenderPanel().setFitToScreen(true); theJcpp.getRenderPanel().update( theJcpp.getRenderPanel().getGraphics()); // enable zooming by removing constraint theJcpp.getRenderPanel().setFitToScreen(false); } /** * This method sets a new structure in the editor and removes the old one. * This method replaces all \n characters with the system line separator. * This can be used when setting a mol file in an applet without knowing * which platform the applet is running on. * * @param mol * The mol file to set * @throws CDKException */ public void setMolFileWithReplace(String mol) throws CDKException { StringBuffer newmol = new StringBuffer(); int s = 0; int e = 0; while ((e = mol.indexOf("\\n", s)) >= 0) { newmol.append(mol.substring(s, e)); newmol.append(System.getProperty("line.separator")); s = e + 2; } setMolFile(newmol.toString()); } /** * This method sets a new structure in the editor and removes the old one. * * @param mol * @throws Exception */ public void setMolFile(String mol) throws CDKException { ISimpleChemObjectReader cor=null; IChemModel chemModel = null; if (mol.contains("$RGP")) { cor= new RGroupQueryReader(new StringReader(mol)); chemModel=JChemPaint.getChemModelFromReader(cor, theJcpp); } else { cor= new MDLV2000Reader(new StringReader(mol), Mode.RELAXED); chemModel=JChemPaint.getChemModelFromReader(cor, theJcpp); JChemPaint.cleanUpChemModel(chemModel,true, theJcpp); } theJcpp.setChemModel(chemModel); theJcpp.get2DHub().updateView(); // the newly opened file should nicely fit the screen theJcpp.getRenderPanel().setFitToScreen(true); theJcpp.getRenderPanel().update(theJcpp.getRenderPanel().getGraphics()); // ..enable zooming by removing constraint again theJcpp.getRenderPanel().setFitToScreen(false); } /** * Clears the applet */ public void clear() { theJcpp.get2DHub().zap(); theJcpp.get2DHub().updateView(); theJcpp.getRenderPanel().getRenderer().getRenderer2DModel() .setZoomFactor(1); IChemObjectSelection selection = new LogicalSelection( LogicalSelection.Type.NONE); theJcpp.getRenderPanel().getRenderer().getRenderer2DModel() .setSelection(selection); } /** * A method for highlighting atoms from JavaScript * * @param atom * The atom number (starting with 0), -1 sets empty selection. */ public void selectAtom(int atom) { JChemPaintRendererModel rendererModel = theJcpp.get2DHub().getRenderer() .getRenderer2DModel(); IChemModel chemModel = theJcpp.getChemModel(); rendererModel.setExternalHighlightColor(Color.RED); IAtomContainer ac = chemModel.getMoleculeSet().getBuilder() .newInstance(IAtomContainer.class); if(atom!=-1){ ac.addAtom(chemModel.getMoleculeSet().getAtomContainer(0).getAtom(atom)); rendererModel.setExternalSelectedPart(ac); }else{ rendererModel.setExternalSelectedPart(null); } getTheJcpp().get2DHub().updateView(); } /** * Makes all implicit hydrogens explicit (same as using * Edit->Hydrogens->Make all Implicit Hydrogens Explicit) */ public void makeHydrogensExplicit() { getTheJcpp().get2DHub().makeAllImplicitExplicit(); getTheJcpp().repaint(); } /** * Makes all explicit hydrogens implicit (same as using * Edit->Hydrogens->Make all Explicit Hydrogens Implicit) */ public void makeHydrogensImplicit() { getTheJcpp().get2DHub().makeAllExplicitImplicit(); getTheJcpp().repaint(); } /** * Tells the mass of the model. This includes all fragments * currently displayed and all their implicit and explicit Hs. * Masses of elements are those of natural abundance. Isotopes are not considered. * * @return */ public double getMolMass(){ IMolecularFormula wholeModel = theJcpp.get2DHub().getIChemModel().getBuilder() .newInstance(IMolecularFormula.class); Iterator<IAtomContainer> containers = ChemModelManipulator .getAllAtomContainers(theJcpp.get2DHub().getIChemModel()).iterator(); int implicitHs = 0; while (containers.hasNext()) { for (IAtom atom : containers.next().atoms()) { wholeModel.addIsotope(atom); if (atom.getImplicitHydrogenCount() != null) { implicitHs += atom.getImplicitHydrogenCount(); } } } try { if (implicitHs > 0) wholeModel.addIsotope(Isotopes.getInstance().getMajorIsotope(1), implicitHs); } catch (IOException e) { // do nothing } return MolecularFormulaManipulator.getNaturalExactMass(wholeModel); } /** * Tells the molecular formula of the model. This includes all fragments * currently displayed and all their implicit and explicit Hs. * * @return The formula. */ public String getMolFormula(){ return theJcpp.get2DHub().getFormula(); } /** * @return Returns the jexf. */ private JExternalFrame getJexf() { if (jexf == null) jexf = new JExternalFrame(); return jexf; } /** * sets title for external frame adds listener for double clicks in order to * open external frame */ private void prepareExternalFrame() { if (this.getParameter("name") != null) getJexf().setTitle(this.getParameter("name")); if (getParameter("detachable") != null && getParameter("detachable").equals("true")) { getTheJcpp().getRenderPanel().addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent e) { Container applet = (Container)e.getSource(); while(!(applet instanceof JChemPaintEditorApplet || applet instanceof JChemPaintViewerApplet)){ applet=applet.getParent(); } if (e.getButton() == 1 && e.getClickCount() == 2 && applet instanceof JChemPaintViewerApplet) if (!getJexf().isShowing()) { getJexf().show(getTheJcpp()); } } }); } if (getParameter("detachableeditor") != null && getParameter("detachableeditor").equals("true")) { getTheJcpp().getRenderPanel().addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent e) { Container applet = (Container)e.getSource(); while(!(applet instanceof JChemPaintEditorApplet || applet instanceof JChemPaintViewerApplet)){ applet=applet.getParent(); } if (e.getButton() == 1 && e.getClickCount() == 2 && applet instanceof JChemPaintViewerApplet) if (!getJexf().isShowing()) { final JChemPaintPanel p = new JChemPaintPanel(theJcpp.getChemModel(), JChemPaintEditorApplet.GUI_APPLET, debug, JChemPaintAbstractApplet.this, blocked); p.setName("appletframe"); p.setShowInsertTextField(false); p.getChemModel().setID("JChemPaint Editor"); getJexf(); jexf.setTitle("JChemPaint Editor"); jexf.add(p); jexf.pack(); jexf.setVisible(true); jexf.addWindowListener(new WindowAdapter(){ public void windowClosing(WindowEvent e) { JChemPaintAbstractApplet.this.setChemModel(p.getChemModel()); } }); } } }); } } protected void setChemModel(IChemModel chemModel) { theJcpp.setChemModel(chemModel); theJcpp.get2DHub().updateView(); } }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/dialog/EnterElementSwingModule.java
.java
12,201
274
/* * $RCSfile$ * $Author: egonw $ * $Date: 2007-01-04 17:26:00 +0000 (Thu, 04 Jan 2007) $ * $Revision: 7634 $ * * Copyright (C) 1997-2008 Stefan Kuhn * * Contact: cdk-jchempaint@lists.sourceforge.net * * 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.jchempaint.dialog; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Set; import javax.swing.JOptionPane; import javax.vecmath.Point2d; import org.openscience.cdk.DefaultChemObjectBuilder; import org.openscience.cdk.config.IsotopeFactory; import org.openscience.cdk.config.Isotopes; import org.openscience.cdk.exception.CDKException; import org.openscience.cdk.exception.InvalidSmilesException; import org.openscience.cdk.interfaces.IAtom; import org.openscience.cdk.interfaces.IAtomContainer; import org.openscience.cdk.interfaces.IBond; import org.openscience.cdk.interfaces.IChemModel; import org.openscience.cdk.interfaces.IIsotope; import org.openscience.cdk.interfaces.IAtomContainerSet; import org.openscience.cdk.layout.RingPlacer; import org.openscience.cdk.layout.StructureDiagramGenerator; import org.openscience.cdk.smiles.SmilesParser; import org.openscience.cdk.tools.manipulator.ChemModelManipulator; import org.openscience.jchempaint.AtomBondSet; import org.openscience.jchempaint.GT; import org.openscience.jchempaint.controller.ControllerModuleAdapter; import org.openscience.jchempaint.controller.IChemModelRelay; import org.openscience.jchempaint.controller.undoredo.CompoundEdit; import org.openscience.jchempaint.controller.undoredo.IUndoRedoFactory; import org.openscience.jchempaint.controller.undoredo.IUndoRedoable; public class EnterElementSwingModule extends ControllerModuleAdapter { private final SmilesParser smipar = new SmilesParser(DefaultChemObjectBuilder.getInstance()); private List<String> funcgroupnames = new ArrayList<>(); private HashMap<String, String> funcgroupsmap = new HashMap<>(); private final static RingPlacer ringPlacer = new RingPlacer(); private String ID; public EnterElementSwingModule(IChemModelRelay chemModelRelay) { super(chemModelRelay); String filename = "org/openscience/jchempaint/resources/funcgroups.txt"; Set<String> uniq = new HashSet<>(); try (InputStream in = this.getClass().getClassLoader().getResourceAsStream(filename); InputStreamReader rdr = new InputStreamReader(in, StandardCharsets.UTF_8); BufferedReader brdr = new BufferedReader(rdr)) { String line; while ((line = brdr.readLine()) != null) { if (line.isEmpty() || line.charAt(0) == '#') continue; String[] fields = line.split("\t", 2); if (fields.length != 2) { System.err.println("Bad line in funcgroups.txt: " + line); continue; } String abbr = fields[0]; String value = fields[1]; if (uniq.add(value)) funcgroupnames.add(abbr); funcgroupsmap.put(abbr.toLowerCase(Locale.ROOT), value); } } catch (IOException ex) { // ignored } } private boolean isSmilesFrag(String str) { if (str.isEmpty() || str.charAt(0) != '*') return false; try { smipar.parseSmiles(str); return true; } catch (InvalidSmilesException e) { return false; } } public void mouseClickedDown(Point2d worldCoord, int modifiers) { IAtom atom = chemModelRelay.getRenderer() .getRenderer2DModel() .getHighlightedAtom(); String[] funcGroupsKeys = new String[funcgroupnames.size() + 1]; funcGroupsKeys[0] = ""; // fow now presume only terminal atoms can have functional groups, so // we populate the selection box if (atom != null && atom.getBondCount() == 1) { int h = 1; for (String name : funcgroupnames) { funcGroupsKeys[h++] = name; } } String label = EnterElementOrGroupDialog.showDialog(null, null, "Enter an element symbol or choose/enter a functional group abbreviation:", "Enter element", funcGroupsKeys, "", ""); try { String smiles = funcgroupsmap.get(label.toLowerCase(Locale.ROOT)); //this means a functional group was entered IChemModel chemModel = chemModelRelay.getIChemModel(); if (smiles != null && !smiles.isEmpty()) { if (addSmiles(smiles, chemModel, atom, label)) return; } else if (isSmilesFrag(label)) { if (addSmiles(label, chemModel, atom, label)) return; } else if (!label.isEmpty()) { if (Character.isLowerCase(label.toCharArray()[0])) label = Character.toUpperCase(label.charAt(0)) + label.substring(1); IsotopeFactory ifa = Isotopes.getInstance(); IIsotope iso = ifa.getMajorIsotope(label); if (iso != null) { if (atom == null) { AtomBondSet addatom = new AtomBondSet(); addatom.add(chemModelRelay.addAtomWithoutUndo(label, worldCoord, false)); if (chemModelRelay.getUndoRedoFactory() != null && chemModelRelay.getUndoRedoHandler() != null) { IUndoRedoable undoredo = chemModelRelay.getUndoRedoFactory().getAddAtomsAndBondsEdit(chemModel, addatom, null, GT.get("Add Atom"), chemModelRelay); chemModelRelay.getUndoRedoHandler().postEdit(undoredo); } } else { chemModelRelay.setSymbol(atom, label); } chemModelRelay.getController2DModel().setDrawElement(label); } else { JOptionPane.showMessageDialog(null, GT.get("{0} is not a valid element symbol or functional group.", label), GT.get("No valid input"), JOptionPane.WARNING_MESSAGE); } } chemModelRelay.updateView(); } catch (Exception ex) { ex.printStackTrace(); } } private boolean addSmiles(String smiles, IChemModel chemModel, IAtom highlightAtom, String label) throws CDKException { IAtomContainer funcgroup = smipar.parseSmiles(smiles); IAtomContainer container = ChemModelManipulator.getRelevantAtomContainer(chemModel, highlightAtom); AtomBondSet added = new AtomBondSet(); AtomBondSet deleted = new AtomBondSet(); Set<IAtom> afix = new HashSet<>(); Set<IBond> bfix = new HashSet<>(); IUndoRedoable delEdit = null; IAtom lastplaced = null; if (container == null) { if (chemModel.getMoleculeSet() == null) chemModel.setMoleculeSet(funcgroup.getBuilder().newInstance(IAtomContainerSet.class)); chemModel.getMoleculeSet().addAtomContainer(funcgroup); funcgroup.getAtom(0).setPoint2d(new Point2d(0, 0)); lastplaced = funcgroup.getAtom(0); container = funcgroup; } else { if (highlightAtom.getBondCount() != 1) { JOptionPane.showMessageDialog(null, GT.get("Incorrect number of bonds to function group {1}", label), GT.get("No valid input"), JOptionPane.WARNING_MESSAGE); return true; } for (IAtom atom : container.atoms()) afix.add(atom); for (IBond bond : container.bonds()) bfix.add(bond); IBond bondToDelete = highlightAtom.bonds().iterator().next(); deleted.add(bondToDelete); deleted.add(highlightAtom); container.removeAtom(highlightAtom); // JWM: we need to capture the delete NOW before adding // anything else otherwise we get in an inconsistent state IUndoRedoFactory undoRedoFactory = chemModelRelay.getUndoRedoFactory(); if (undoRedoFactory != null && chemModelRelay.getUndoRedoHandler() != null) { delEdit = undoRedoFactory.getRemoveAtomsAndBondsEdit(chemModel, deleted, "", chemModelRelay); } container.add(funcgroup); IAtom attachmentStar = funcgroup.getAtom(0); IAtom attachmentAtom = attachmentStar.bonds().iterator().next().getOther(attachmentStar); container.removeAtom(attachmentStar); IBond newBond = null; if (bondToDelete.getBegin().equals(highlightAtom)) newBond = container.newBond(attachmentAtom, bondToDelete.getOther(highlightAtom), bondToDelete.getOrder()); else if (bondToDelete.getEnd().equals(highlightAtom)) newBond = container.newBond(bondToDelete.getOther(highlightAtom), attachmentAtom, bondToDelete.getOrder()); else throw new IllegalStateException("attachmentAtom is not at either end of one if it's bonds"); newBond.setStereo(bondToDelete.getStereo()); newBond.setDisplay(bondToDelete.getDisplay()); for (IAtom atom : container.atoms()) { if (!afix.contains(atom)) added.add(atom); } for (IBond bond : container.bonds()) { if (!bfix.contains(bond)) added.add(bond); } } StructureDiagramGenerator sdg = new StructureDiagramGenerator(); sdg.setMolecule(container, false, afix, bfix); sdg.generateCoordinates(); IUndoRedoFactory undoRedoFactory = chemModelRelay.getUndoRedoFactory(); if (undoRedoFactory != null && chemModelRelay.getUndoRedoHandler() != null) { IUndoRedoable undoredo = undoRedoFactory.getAddAtomsAndBondsEdit(chemModel, added, null, GT.get("Add Functional Group"), chemModelRelay); if (delEdit != null) undoredo = new CompoundEdit(GT.get("Add Functional Group"), delEdit, undoredo); chemModelRelay.getUndoRedoHandler().postEdit(undoredo); } return false; } public String getDrawModeString() { return "Enter Element or Group"; } public String getID() { return ID; } public void setID(String ID) { this.ID = ID; } }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/dialog/TextViewDialog.java
.java
4,895
151
/* * $RCSfile$ * $Author: egonw $ * $Date: 2007-01-04 17:26:00 +0000 (Thu, 04 Jan 2007) $ * $Revision: 7634 $ * * Copyright (C) 1997-2008 Stefan Kuhn * * Contact: cdk-jchempaint@lists.sourceforge.net * * 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.jchempaint.dialog; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; import org.openscience.jchempaint.GT; /** * A simple text viewing dialog for general use. * * @cdk.module jchempaint * @cdk.created 2003-08-24 */ public class TextViewDialog extends JDialog { private static final long serialVersionUID = -1900643115385413976L; private JTextArea textArea; private JLabel textCaption; /** * @see #TextViewDialog(JFrame, String, Dimension, boolean, int, int) */ public TextViewDialog(JFrame fr, String title) { this(fr, title, null); } /** * @see #TextViewDialog(JFrame, String, Dimension, boolean, int, int) */ public TextViewDialog(JFrame fr, String title, Dimension dim) { this(fr, title, dim, true); } /** * @see #TextViewDialog(JFrame, String, Dimension, boolean, int, int) */ public TextViewDialog(JFrame fr, String title, Dimension dim, boolean wrap) { this(fr, title, dim, wrap, 20, 60); } /** * Constructs a new JTextViewDialog. * * @param fr Parent JFrame * @param title String that will appear in the title bar * @param dim Dimension of the dialog * @param wrap If true, then the lines will be wrapped * @param width Number of chars per line * @param height Number of lines */ public TextViewDialog(JFrame fr, String title, Dimension dim, boolean wrap, int width, int height) { super(fr, title, true); textArea = new JTextArea(width,height); textArea.setEditable(false); textArea.setName("textviewdialogtextarea"); if (wrap) { textArea.setLineWrap(wrap); textArea.setWrapStyleWord(true); } JScrollPane scroller = new JScrollPane(); if (dim != null) scroller.setPreferredSize(dim); else scroller.setPreferredSize(new Dimension(400,200)); scroller.getViewport().add(textArea); JPanel textViewer = new JPanel(new BorderLayout()); //textViewer.setAlignmentX(LEFT_ALIGNMENT); textViewer.add(scroller, BorderLayout.CENTER); JPanel buttonPanel = new JPanel(); buttonPanel.setLayout(new FlowLayout(FlowLayout.RIGHT)); JButton ok = new JButton(GT.get("OK")); ok.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { OKPressed(); } }); buttonPanel.add(ok); getRootPane().setDefaultButton(ok); JPanel container = new JPanel(); container.setLayout(new BorderLayout()); container.validate(); textCaption = new JLabel(""); container.add(textCaption, BorderLayout.NORTH); container.add(textViewer, BorderLayout.CENTER); container.add(buttonPanel, BorderLayout.SOUTH); getContentPane().add(container); pack(); } public void OKPressed() { this.setVisible(false); } public void setText(String text) { textArea.setText(text); } public void setMessage(String caption, String text) { textCaption.setText(caption); textArea.setText(text); } }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/dialog/PeriodicTableDialog.java
.java
2,581
76
/* * $RCSfile$ * $Author: egonw $ * $Date: 2007-01-04 17:26:00 +0000 (Thu, 04 Jan 2007) $ * $Revision: 7634 $ * * Copyright (C) 1997-2008 Egone Willighagen, Miguel Rojas, Geert Josten * * Contact: cdk-jchempaint@lists.sourceforge.net * * 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.jchempaint.dialog; import org.openscience.cdk.event.ICDKChangeListener; import org.openscience.cdk.exception.CDKException; import org.openscience.jchempaint.GT; import javax.swing.JDialog; import javax.swing.JFrame; import java.awt.BorderLayout; import java.awt.Color; import java.io.IOException; import java.util.EventObject; /** * Dialog that shows a periodic table. The selected symbol * can be derived with getChooenSymbol after the dialog has been shown. * getChosenSymbol will be "" if dialog has been cancelled. */ public class PeriodicTableDialog extends JDialog { private static final long serialVersionUID = -1136319713943259980L; private PeriodicTablePanel ptp; public PeriodicTableDialog(JFrame frame) { super(frame, true); doInit(); } public void doInit() { getContentPane().setLayout(new BorderLayout()); getContentPane().setBackground(Color.white); setTitle(GT.get("Choose an element...")); ptp = new PeriodicTablePanel(); getContentPane().add("Center", ptp); pack(); } public String getChosenSymbol() { try { return ptp.getSelectedElement(); } catch (IOException | CDKException ignore) { return ""; } } }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/dialog/FieldTablePanel.java
.java
5,645
163
/* * $RCSfile$ * $Author: egonw $ * $Date: 2007-01-04 17:26:00 +0000 (Thu, 04 Jan 2007) $ * $Revision: 7634 $ * * Copyright (C) 1997-2008 Stefan Kuhn * * Contact: cdk-jchempaint@lists.sourceforge.net * * 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.jchempaint.dialog; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import javax.swing.ImageIcon; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTabbedPane; /** * Swing class that allows easy building of edit forms. * * @cdk.svnrev $Revision: 11740 $ */ public class FieldTablePanel extends JPanel { private static final long serialVersionUID = -697566299504877020L; protected static final int DEF_INSET = 10; protected int rows; protected JTabbedPane tabbedPane; /** * Constructor for field table panel. * * @param hasTabs True=tabs are added, false=fields go directly on here. */ public FieldTablePanel(boolean hasTabs) { if (hasTabs) { setLayout(new BorderLayout()); tabbedPane = new JTabbedPane(); tabbedPane.setName("tabs"); add(tabbedPane, BorderLayout.CENTER); } else { setLayout(new GridBagLayout()); } rows = 0; } /** * Adds a tab. * * @param header The header for the tab. * @return A JPanel, which you will need later to add fields. */ public JPanel addTab(String header) { JPanel panel = new JPanel(); panel.setLayout(new GridBagLayout()); tabbedPane.addTab(header, panel); return panel; } /** * Adds a new JComponent to the 2 column table layout. Both * elements will be layed out in the same row. For larger * <code>JComponent</code>s the addArea() can be used. * * @param labelText The text in left column. * @param component The control to add. * @param panel The panel to add to. This must be either a panel you got from addTab or null if in no tab mode. * @param inset Spacing distance between objects on the panel */ public void addField(String labelText, JComponent component, JPanel panel, int inset) { if (panel == null) panel = this; rows++; JLabel label = new JLabel("", JLabel.TRAILING); if (labelText != null && !labelText.isEmpty()) { label = new JLabel(labelText + ": ", JLabel.TRAILING); } label.setLabelFor(component); addField(label, component, panel, inset); } public void addField(JLabel label, JComponent component, JPanel panel, int inset) { GridBagConstraints constraints = new GridBagConstraints(); constraints.insets = new Insets(inset, inset, inset, inset); constraints.gridx = 0; constraints.gridy = rows; constraints.fill = GridBagConstraints.HORIZONTAL; constraints.anchor = GridBagConstraints.LINE_START; constraints.weightx = 1.0; panel.add(label, constraints); constraints.gridx = 1; constraints.fill = GridBagConstraints.HORIZONTAL; panel.add(component, constraints); } public void addField(String labelText, JComponent component, JPanel panel) { addField(labelText, component, panel, 0); } /** * Adds a new JComponent to the 2 column table layout. The JLabel * will be placed in one row, while the <code>JComponent</code> * will be placed in a second row. * * @see #addField(String, JComponent) */ public void addArea(String labelText, JComponent component) { rows++; GridBagConstraints constraints = new GridBagConstraints(); JLabel label = new JLabel(labelText + ": "); label.setLabelFor(component); constraints.gridx = 0; constraints.gridwidth = 2; constraints.gridy = rows; constraints.fill = GridBagConstraints.HORIZONTAL; constraints.anchor = GridBagConstraints.LINE_START; constraints.weightx = 1.0; add(label, constraints); rows++; constraints.gridy = rows; JScrollPane editorScrollPane = new JScrollPane(component); editorScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); editorScrollPane.setPreferredSize(new Dimension(250, 145)); editorScrollPane.setMinimumSize(new Dimension(10, 10)); add(editorScrollPane, constraints); } }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/dialog/EnterElementOrGroupDialog.java
.java
5,720
147
/* * $RCSfile$ * $Author: egonw $ * $Date: 2007-01-04 17:26:00 +0000 (Thu, 04 Jan 2007) $ * $Revision: 7634 $ * * Copyright (C) 1997-2008 Stefan Kuhn * * Contact: cdk-jchempaint@lists.sourceforge.net * * 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.jchempaint.dialog; import java.awt.BorderLayout; import java.awt.Component; import java.awt.Container; import java.awt.Dimension; import java.awt.Frame; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.BorderFactory; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JDialog; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import org.openscience.jchempaint.GT; public class EnterElementOrGroupDialog extends JDialog implements ActionListener { private static EnterElementOrGroupDialog dialog; private static String value = ""; private JComboBox<?> list; /** * Set up and show the dialog. The first Component argument * determines which frame the dialog depends on; it should be * a component in the dialog's controlling frame. The second * Component argument should be null if you want the dialog * to come up with its left corner in the center of the screen; * otherwise, it should be the component on top of which the * dialog should appear. */ public static String showDialog(Component frameComp, Component locationComp, String labelText, String title, String[] possibleValues, String initialValue, String longValue) { Frame frame = JOptionPane.getFrameForComponent(frameComp); dialog = new EnterElementOrGroupDialog(frame, locationComp, labelText, title, possibleValues, initialValue, longValue); dialog.setVisible(true); return value; } private EnterElementOrGroupDialog(Frame frame, Component locationComp, String labelText, String title, Object[] data, String initialValue, String longValue) { super(frame, title, true); //Create and initialize the buttons. JButton cancelButton = new JButton(GT.get("Cancel")); cancelButton.addActionListener(this); // final JButton setButton = new JButton(GT.get("OK")); setButton.setName("ok"); setButton.setActionCommand("Set"); setButton.addActionListener(this); getRootPane().setDefaultButton(setButton); //main part of the dialog list = new JComboBox<Object>(data); list.setEditable(true); JPanel listPane = new JPanel(); listPane.setLayout(new BoxLayout(listPane, BoxLayout.PAGE_AXIS)); JLabel label = new JLabel(labelText); label.setLabelFor(list); listPane.add(label); listPane.add(Box.createRigidArea(new Dimension(0,5))); listPane.add(list); listPane.setBorder(BorderFactory.createEmptyBorder(10,10,10,10)); //Lay out the buttons from left to right. JPanel buttonPane = new JPanel(); buttonPane.setLayout(new BoxLayout(buttonPane, BoxLayout.LINE_AXIS)); buttonPane.setBorder(BorderFactory.createEmptyBorder(0, 10, 10, 10)); buttonPane.add(Box.createHorizontalGlue()); buttonPane.add(cancelButton); buttonPane.add(Box.createRigidArea(new Dimension(10, 0))); buttonPane.add(setButton); //Put everything together, using the content pane's BorderLayout. Container contentPane = getContentPane(); contentPane.add(listPane, BorderLayout.CENTER); contentPane.add(buttonPane, BorderLayout.PAGE_END); //Initialize values. pack(); setLocationRelativeTo(locationComp); } //Handle clicks on the Set and Cancel buttons. public void actionPerformed(ActionEvent e) { if ("Set".equals(e.getActionCommand())) { EnterElementOrGroupDialog.value = (String) (list.getSelectedItem()); } if (e.getActionCommand().equals("Cancel")) { EnterElementOrGroupDialog.value = ""; } EnterElementOrGroupDialog.dialog.setVisible(false); } }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/dialog/WaitDialog.java
.java
2,180
78
package org.openscience.jchempaint.dialog; import java.awt.FlowLayout; import java.awt.Font; import java.awt.Toolkit; import javax.swing.JDialog; import javax.swing.JLabel; /** * This class is used to display the Wait Dialog. This Dialog is displayed * when the system is busy processing. All the GUI controls in this dialog * are initialized once and the static methods showDialog/hideDialog, uses * this instance to show/hide. * * @since 1.0 * @version 1.0 */ public class WaitDialog extends JDialog { /** * */ private JLabel jLabel1 = new JLabel(); // single instance of this class, used through out the scope of the application private static WaitDialog dlg = new WaitDialog(); /** * The constructor intialies all the GUI controls */ private WaitDialog() { try { jbInit(); } catch(Exception e) { e.printStackTrace(); } } /** * This method intializes all the GUI controls and adds it to the Panel * * @exception Exception if any exception, while creating GUI controls */ private void jbInit() throws Exception { this.getContentPane().setLayout(new FlowLayout(FlowLayout.CENTER)); this.setResizable(false); this.setTitle("Please wait - JChemPaint busy"); jLabel1.setText("Processing in background or loading library..."); jLabel1.setFont(new Font("Tahoma", 1, 13)); this.getContentPane().add(jLabel1, null); } /** * This static method uses pre-created dialog, positions it in the center * and displays it to the user. */ public static void showDialog() { dlg.setSize(300, 70); dlg.setLocation(Toolkit.getDefaultToolkit().getScreenSize().width/2-dlg.getSize().width/2, Toolkit.getDefaultToolkit().getScreenSize().height/2-dlg.getSize().height/2); if (!dlg.isVisible()) dlg.setVisible(true); dlg.paint(dlg.getGraphics()); } /** * This static method hides the wait dialog. */ public static void hideDialog() { if (dlg.isVisible()) dlg.setVisible(false); } }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/dialog/PeriodicTablePanel.java
.java
34,284
1,095
/* * $RCSfile$ * $Author: egonw $ * $Date: 2007-01-04 17:26:00 +0000 (Thu, 04 Jan 2007) $ * $Revision: 7634 $ * * Copyright (C) 1997-2008 Egone Willighagen, Miguel Rojas, Geert Josten * * Contact: cdk-jchempaint@lists.sourceforge.net * * 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.jchempaint.dialog; import org.openscience.cdk.event.ICDKChangeListener; import org.openscience.cdk.exception.CDKException; import org.openscience.cdk.tools.periodictable.PeriodicTable; import org.openscience.jchempaint.GT; import javax.swing.AbstractAction; import javax.swing.BorderFactory; import javax.swing.Box; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JLayeredPane; import javax.swing.JPanel; import javax.swing.SwingUtilities; import javax.swing.border.BevelBorder; import javax.swing.border.EmptyBorder; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.Font; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ComponentAdapter; import java.awt.event.ComponentEvent; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.io.IOException; import java.util.EventObject; import java.util.HashMap; import java.util.Map; import java.util.Vector; /** * JPanel version of the periodic system. * * @author Egon Willighagen * @author Geert Josten * @author Miguel Rojas * @author Konstantin Tokarev * @author Mark Rijnbeek */ public class PeriodicTablePanel extends JPanel { private static final long serialVersionUID = -2539418347261469740L; Vector<ICDKChangeListener> listeners = null; String selectedElement = null; private JPanel panel; //private JLabel label; private JLayeredPane layeredPane; private Map<JButton,Color> buttoncolors = new HashMap<JButton,Color>(); public static int APPLICATION = 0; /*default*/ public static int JCP = 1; /* * set if the button should be written with html - which takes * too long time for loading * APPLICATION = with html * JCP = default */ /** * Constructor of the PeriodicTablePanel object */ public PeriodicTablePanel() { super(); setLayout( new BorderLayout()); layeredPane = new JLayeredPane(); layeredPane.setPreferredSize(new Dimension(581, 435)); final JPanel tp = PTPanel(); tp.setBounds(8,85,570,340); panel = CreateLabelProperties(null); layeredPane.add(tp, Integer.valueOf(0)); layeredPane.add(panel, Integer.valueOf(1)); add(layeredPane); // JWM handling resizing nicely: // JLayeredPane does not resize, we can sort of fix it with // an OverlayLayout but the panel is regenerated on mouse-over // and so it is simpler to set the bounds for each component // based on the current size addComponentListener(new ComponentAdapter() { @Override public void componentResized(ComponentEvent e) { Dimension d = getSize(); tp.setBounds(8,85,d.width-11,d.height-95); int boxWidth = (int)Math.ceil((d.width-11) / 19f); int boxHeight = (int)Math.ceil((d.height-11) / 12f); panel.setBounds(4*boxWidth, (int)(0.5*boxHeight), 8*boxWidth, (int)(4*boxHeight)); } }); } private void resize() { } private JPanel PTPanel() { JPanel panel = new JPanel(); listeners = new Vector<ICDKChangeListener>(); panel.setLayout(new GridLayout(0, 19)); //-------------------------------- Box.createHorizontalGlue(); panel.add(Box.createHorizontalGlue()); JButton butt = new JButton("1"); butt.setBorder(new EmptyBorder(2,2,2,2)); panel.add(butt); //-------------------------------- for (int i = 0; i < 16; i++) { Box.createHorizontalGlue(); panel.add(Box.createHorizontalGlue()); } butt = new JButton("18"); butt.setBorder(new EmptyBorder(2,2,2,2)); panel.add(butt); butt = new JButton("1"); butt.setBorder(new EmptyBorder(2,2,2,2)); panel.add(butt); panel.add(createButton(GT.get("H"))); butt = new JButton("2"); butt.setBorder(new EmptyBorder(2,2,2,2)); panel.add(butt); for (int i = 0; i < 10; i++) { panel.add(Box.createHorizontalGlue()); } butt = new JButton("13"); butt.setBorder(new EmptyBorder(2,2,2,2)); panel.add(butt); butt = new JButton("14"); butt.setBorder(new EmptyBorder(2,2,2,2)); panel.add(butt); butt = new JButton("15"); butt.setBorder(new EmptyBorder(2,2,2,2)); panel.add(butt); butt = new JButton("16"); butt.setBorder(new EmptyBorder(2,2,2,2)); panel.add(butt); butt = new JButton("17"); butt.setBorder(new EmptyBorder(2,2,2,2)); panel.add(butt); // panel.add(createButton(GT.get("He"))); butt = new JButton("2"); butt.setBorder(new EmptyBorder(2,2,2,2)); panel.add(butt); panel.add(createButton(GT.get("Li"))); panel.add(createButton(GT.get("Be"))); for (int i = 0; i < 10; i++) { panel.add(Box.createHorizontalGlue()); } //no metall panel.add(createButton(GT.get("B"))); panel.add(createButton(GT.get("C"))); panel.add(createButton(GT.get("N"))); panel.add(createButton(GT.get("O"))); panel.add(createButton(GT.get("F"))); // panel.add(createButton(GT.get("Ne"))); butt = new JButton("3"); butt.setBorder(new EmptyBorder(2,2,2,2)); panel.add(butt); panel.add(createButton(GT.get("Na"))); panel.add(createButton(GT.get("Mg"))); butt = new JButton("3"); butt.setBorder(new EmptyBorder(2,2,2,2)); panel.add(butt); butt = new JButton("4"); butt.setBorder(new EmptyBorder(2,2,2,2)); panel.add(butt); butt = new JButton("5"); butt.setBorder(new EmptyBorder(2,2,2,2)); panel.add(butt); butt = new JButton("6"); butt.setBorder(new EmptyBorder(2,2,2,2)); panel.add(butt); butt = new JButton("7"); butt.setBorder(new EmptyBorder(2,2,2,2)); panel.add(butt); butt = new JButton("8"); butt.setBorder(new EmptyBorder(2,2,2,2)); panel.add(butt); butt = new JButton("9"); butt.setBorder(new EmptyBorder(2,2,2,2)); panel.add(butt); butt = new JButton("10"); butt.setBorder(new EmptyBorder(2,2,2,2)); panel.add(butt); butt = new JButton("11"); butt.setBorder(new EmptyBorder(2,2,2,2)); panel.add(butt); butt = new JButton("12"); butt.setBorder(new EmptyBorder(2,2,2,2)); panel.add(butt); //no metall panel.add(createButton(GT.get("Al"))); panel.add(createButton(GT.get("Si"))); panel.add(createButton(GT.get("P"))); panel.add(createButton(GT.get("S"))); panel.add(createButton(GT.get("Cl"))); // panel.add(createButton(GT.get("Ar"))); butt = new JButton("4"); butt.setBorder(new EmptyBorder(2,2,2,2)); panel.add(butt); panel.add(createButton(GT.get("K"))); panel.add(createButton(GT.get("Ca"))); //transition panel.add(createButton(GT.get("Sc"))); panel.add(createButton(GT.get("Ti"))); panel.add(createButton(GT.get("V"))); panel.add(createButton(GT.get("Cr"))); panel.add(createButton(GT.get("Mn"))); panel.add(createButton(GT.get("Fe"))); panel.add(createButton(GT.get("Co"))); panel.add(createButton(GT.get("Ni"))); panel.add(createButton(GT.get("Cu"))); panel.add(createButton(GT.get("Zn"))); //no metall panel.add(createButton(GT.get("Ga"))); panel.add(createButton(GT.get("Ge"))); panel.add(createButton(GT.get("As"))); panel.add(createButton(GT.get("Se"))); panel.add(createButton(GT.get("Br"))); // panel.add(createButton(GT.get("Kr"))); butt = new JButton("5"); butt.setBorder(new EmptyBorder(2,2,2,2)); panel.add(butt); panel.add(createButton(GT.get("Rb"))); panel.add(createButton(GT.get("Sr"))); //transition panel.add(createButton(GT.get("Y"))); panel.add(createButton(GT.get("Zr"))); panel.add(createButton(GT.get("Nb"))); panel.add(createButton(GT.get("Mo"))); panel.add(createButton(GT.get("Tc"))); panel.add(createButton(GT.get("Ru"))); panel.add( createButton(GT.get("Rh"))); panel.add(createButton(GT.get("Pd"))); panel.add(createButton(GT.get("Ag"))); panel.add(createButton(GT.get("Cd"))); //no metall panel.add(createButton(GT.get("In"))); panel.add(createButton(GT.get("Sn"))); panel.add(createButton(GT.get("Sb"))); panel.add(createButton(GT.get("Te"))); panel.add(createButton(GT.get("I"))); // panel.add(createButton(GT.get("Xe"))); butt = new JButton("6"); butt.setBorder(new EmptyBorder(2,2,2,2)); panel.add(butt); panel.add(createButton(GT.get("Cs"))); panel.add(createButton(GT.get("Ba"))); //transition panel.add(createButton(GT.get("La"))); panel.add(createButton(GT.get("Hf"))); panel.add(createButton(GT.get("Ta"))); panel.add(createButton(GT.get("W"))); panel.add(createButton(GT.get("Re"))); panel.add(createButton(GT.get("Os"))); panel.add(createButton(GT.get("Ir"))); panel.add(createButton(GT.get("Pt"))); panel.add(createButton(GT.get("Au"))); panel.add(createButton(GT.get("Hg"))); //no metall panel.add(createButton(GT.get("Tl"))); panel.add(createButton(GT.get("Pb"))); panel.add(createButton(GT.get("Bi"))); panel.add(createButton(GT.get("Po"))); panel.add(createButton(GT.get("At"))); // panel.add(createButton(GT.get("Rn"))); butt = new JButton("7"); butt.setBorder(new EmptyBorder(2,2,2,2)); panel.add(butt); panel.add(createButton(GT.get("Fr"))); panel.add(createButton(GT.get("Ra"))); //transition panel.add(createButton(GT.get("Ac"))); panel.add(createButton(GT.get("Rf"))); panel.add(createButton(GT.get("Db"))); panel.add(createButton(GT.get("Sg"))); panel.add(createButton(GT.get("Bh"))); panel.add(createButton(GT.get("Hs"))); panel.add(createButton(GT.get("Mt"))); panel.add(createButton(GT.get("Ds"))); panel.add(createButton(GT.get("Rg"))); panel.add(createButton(GT.get("Cn"))); panel.add(createButton(GT.get("Nh"))); panel.add(createButton(GT.get("Fl"))); panel.add(createButton(GT.get("Mc"))); panel.add(createButton(GT.get("Lv"))); panel.add(createButton(GT.get("Ts"))); panel.add(createButton(GT.get("Og"))); for (int i = 0; i < 3; i++) { panel.add(Box.createHorizontalGlue()); } //Acti panel.add(createButton(GT.get("Ce"))); panel.add(createButton(GT.get("Pr"))); panel.add(createButton(GT.get("Nd"))); panel.add(createButton(GT.get("Pm"))); panel.add(createButton(GT.get("Sm"))); panel.add(createButton(GT.get("Eu"))); panel.add(createButton(GT.get("Gd"))); panel.add(createButton(GT.get("Tb"))); panel.add(createButton(GT.get("Dy"))); panel.add(createButton(GT.get("Ho"))); panel.add(createButton(GT.get("Er"))); panel.add(createButton(GT.get("Tm"))); panel.add(createButton(GT.get("Yb"))); panel.add(createButton(GT.get("Lu"))); for (int i = 0; i < 5; i++) { panel.add(Box.createHorizontalGlue()); } //Lacti panel.add( createButton(GT.get("Th"))); panel.add(createButton(GT.get("Pa"))); panel.add(createButton(GT.get("U"))); panel.add(createButton(GT.get("Np"))); panel.add(createButton(GT.get("Pu"))); panel.add(createButton(GT.get("Am"))); panel.add(createButton(GT.get("Cm"))); panel.add(createButton(GT.get("Bk"))); panel.add(createButton(GT.get("Cf"))); panel.add(createButton(GT.get("Es"))); panel.add(createButton(GT.get("Fm"))); panel.add(createButton(GT.get("Md"))); panel.add(createButton(GT.get("No"))); panel.add(createButton(GT.get("Lr"))); //End panel.setVisible(true); return panel; } /** * create button. Define the color of the font and background * *@param elementS String of the element *@return button JButton */ private JButton createButton(String elementS) { Color colorB = null; String type = PeriodicTable.getChemicalSeries(elementS); if (type != null) { switch (type) { case "Noble Gasses": colorB = new Color(255, 153, 255); break; case "Halogens": colorB = new Color(255, 153, 153); break; case "Nonmetals": colorB = new Color(255, 152, 90); break; case "Metalloids": colorB = new Color(255, 80, 80); break; case "Metals": colorB = new Color(255, 50, 0); break; case "Alkali Earth Metals": colorB = new Color(102, 150, 255); break; case "Alkali Metals": colorB = new Color(130, 130, 255); break; case "Transition metals": colorB = new Color(255, 255, 110); break; case "Lanthanides": colorB = new Color(255, 255, 150); break; case "Actinides": colorB = new Color(255, 255, 200); break; } } JButton button = new ElementButton(elementS, new ElementMouseAction(), elementS); button.setBackground(colorB); button.setName(elementS); buttoncolors.put(button,colorB); return button; } /** * Sets the selectedElement attribute of the PeriodicTablePanel object * *@param selectedElement The new selectedElement value */ public void setSelectedElement(String selectedElement) { this.selectedElement = selectedElement; } /** * Gets the selectedElement attribute of the PeriodicTablePanel object * *@return The selectedElement value */ public String getSelectedElement() throws IOException, CDKException { return selectedElement; } /** * Adds a change listener to the list of listeners * *@param listener The listener added to the list */ public void addCDKChangeListener(ICDKChangeListener listener) { listeners.add(listener); } /** * Removes a change listener from the list of listeners * *@param listener The listener removed from the list */ public void removeCDKChangeListener(ICDKChangeListener listener) { listeners.remove(listener); } /** * Notifies registered listeners of certain changes that have occurred in this * model. */ public void fireChange() { EventObject event = new EventObject(this); for (int i = 0; i < listeners.size(); i++) { ((ICDKChangeListener) listeners.get(i)).stateChanged(event); } } /** * get translated name of element * * @author Geoffrey R. Hutchison * @param atomic number of element * @return the name element to show */ private String elementTranslator(int element) { String result; switch(element) { case 1: result = GT.get("Hydrogen"); break; case 2: result = GT.get("Helium"); break; case 3: result = GT.get("Lithium"); break; case 4: result = GT.get("Beryllium"); break; case 5: result = GT.get("Boron"); break; case 6: result = GT.get("Carbon"); break; case 7: result = GT.get("Nitrogen"); break; case 8: result = GT.get("Oxygen"); break; case 9: result = GT.get("Fluorine"); break; case 10: result = GT.get("Neon"); break; case 11: result = GT.get("Sodium"); break; case 12: result = GT.get("Magnesium"); break; case 13: result = GT.get("Aluminum"); break; case 14: result = GT.get("Silicon"); break; case 15: result = GT.get("Phosphorus"); break; case 16: result = GT.get("Sulfur"); break; case 17: result = GT.get("Chlorine"); break; case 18: result = GT.get("Argon"); break; case 19: result = GT.get("Potassium"); break; case 20: result = GT.get("Calcium"); break; case 21: result = GT.get("Scandium"); break; case 22: result = GT.get("Titanium"); break; case 23: result = GT.get("Vanadium"); break; case 24: result = GT.get("Chromium"); break; case 25: result = GT.get("Manganese"); break; case 26: result = GT.get("Iron"); break; case 27: result = GT.get("Cobalt"); break; case 28: result = GT.get("Nickel"); break; case 29: result = GT.get("Copper"); break; case 30: result = GT.get("Zinc"); break; case 31: result = GT.get("Gallium"); break; case 32: result = GT.get("Germanium"); break; case 33: result = GT.get("Arsenic"); break; case 34: result = GT.get("Selenium"); break; case 35: result = GT.get("Bromine"); break; case 36: result = GT.get("Krypton"); break; case 37: result = GT.get("Rubidium"); break; case 38: result = GT.get("Strontium"); break; case 39: result = GT.get("Yttrium"); break; case 40: result = GT.get("Zirconium"); break; case 41: result = GT.get("Niobium"); break; case 42: result = GT.get("Molybdenum"); break; case 43: result = GT.get("Technetium"); break; case 44: result = GT.get("Ruthenium"); break; case 45: result = GT.get("Rhodium"); break; case 46: result = GT.get("Palladium"); break; case 47: result = GT.get("Silver"); break; case 48: result = GT.get("Cadmium"); break; case 49: result = GT.get("Indium"); break; case 50: result = GT.get("Tin"); break; case 51: result = GT.get("Antimony"); break; case 52: result = GT.get("Tellurium"); break; case 53: result = GT.get("Iodine"); break; case 54: result = GT.get("Xenon"); break; case 55: result = GT.get("Cesium"); break; case 56: result = GT.get("Barium"); break; case 57: result = GT.get("Lanthanum"); break; case 58: result = GT.get("Cerium"); break; case 59: result = GT.get("Praseodymium"); break; case 60: result = GT.get("Neodymium"); break; case 61: result = GT.get("Promethium"); break; case 62: result = GT.get("Samarium"); break; case 63: result = GT.get("Europium"); break; case 64: result = GT.get("Gadolinium"); break; case 65: result = GT.get("Terbium"); break; case 66: result = GT.get("Dysprosium"); break; case 67: result = GT.get("Holmium"); break; case 68: result = GT.get("Erbium"); break; case 69: result = GT.get("Thulium"); break; case 70: result = GT.get("Ytterbium"); break; case 71: result = GT.get("Lutetium"); break; case 72: result = GT.get("Hafnium"); break; case 73: result = GT.get("Tantalum"); break; case 74: result = GT.get("Tungsten"); break; case 75: result = GT.get("Rhenium"); break; case 76: result = GT.get("Osmium"); break; case 77: result = GT.get("Iridium"); break; case 78: result = GT.get("Platinum"); break; case 79: result = GT.get("Gold"); break; case 80: result = GT.get("Mercury"); break; case 81: result = GT.get("Thallium"); break; case 82: result = GT.get("Lead"); break; case 83: result = GT.get("Bismuth"); break; case 84: result = GT.get("Polonium"); break; case 85: result = GT.get("Astatine"); break; case 86: result = GT.get("Radon"); break; case 87: result = GT.get("Francium"); break; case 88: result = GT.get("Radium"); break; case 89: result = GT.get("Actinium"); break; case 90: result = GT.get("Thorium"); break; case 91: result = GT.get("Protactinium"); break; case 92: result = GT.get("Uranium"); break; case 93: result = GT.get("Neptunium"); break; case 94: result = GT.get("Plutonium"); break; case 95: result = GT.get("Americium"); break; case 96: result = GT.get("Curium"); break; case 97: result = GT.get("Berkelium"); break; case 98: result = GT.get("Californium"); break; case 99: result = GT.get("Einsteinium"); break; case 100: result = GT.get("Fermium"); break; case 101: result = GT.get("Mendelevium"); break; case 102: result = GT.get("Nobelium"); break; case 103: result = GT.get("Lawrencium"); break; case 104: result = GT.get("Rutherfordium"); break; case 105: result = GT.get("Dubnium"); break; case 106: result = GT.get("Seaborgium"); break; case 107: result = GT.get("Bohrium"); break; case 108: result = GT.get("Hassium"); break; case 109: result = GT.get("Meitnerium"); break; case 110: result = GT.get("Darmstadtium"); break; case 111: result = GT.get("Roentgenium"); break; case 112: result = GT.get("Copernicium"); break; case 113: result = GT.get("Nihonium"); break; case 114: result = GT.get("Flerovium"); break; case 115: result = GT.get("Moscovium"); break; case 116: result = GT.get("Livermorium"); break; case 117: result = GT.get("Tennessine"); break; case 118: result = GT.get("Oganesson"); break; default: result = GT.get("Unknown"); } return result; } /** * get translated name of element * * @author Konstantin Tokarev * @param chemical serie to translate * @return the String to show */ public String serieTranslator(String type) { if("Noble Gasses".equals(type)) return GT.get("Noble Gases"); else if("Halogens".equals(type)) return GT.get("Halogens"); else if("Nonmetals".equals(type)) return GT.get("Nonmetals"); else if("Metalloids".equals(type)) return GT.get("Metalloids"); else if("Metals".equals(type)) return GT.get("Metals"); else if("Alkali Earth Metals".equals(type)) return GT.get("Alkali Earth Metals"); else if("Alkali Metals".equals(type)) return GT.get("Alkali Metals"); else if("Transition metals".equals(type)) return GT.get("Transition metals"); else if("Lanthanides".equals(type)) return GT.get("Lanthanides"); else if("Actinides".equals(type)) return GT.get("Actinides"); else return GT.get("Unknown"); } /** * get translated name of phase * * @author Konstantin Tokarev * @param phase name to translate * @return the String to show */ public String phaseTranslator(String serie) { if(serie.equals("Gas")) return GT.get("Gas"); else if(serie.equals("Liquid")) return GT.get("Liquid"); else if(serie.equals("Solid")) return GT.get("Solid"); else return GT.get("Unknown"); } /** * Description of the Class * *@author steinbeck *@cdk.created February 10, 2004 */ public class ElementMouseAction implements MouseListener { private static final long serialVersionUID = 6176240749900870566L; public void mouseClicked(MouseEvent e) { } public void mouseEntered(MouseEvent e) { ElementButton button = (ElementButton) e.getSource(); setSelectedElement(button.getElement()); layeredPane.remove(panel); panel = CreateLabelProperties(button.getElement()); layeredPane.add(panel, new Integer(1)); layeredPane.repaint(); button.setBackground(Color.LIGHT_GRAY); } public void mouseExited(MouseEvent e) { ((ElementButton)e.getSource()).setBackground(buttoncolors.get(e.getSource())); } public void mousePressed(MouseEvent e) { } public void mouseReleased(MouseEvent e) { } } /** * This action fragment a molecule which is on the frame JChemPaint * */ class BackAction extends AbstractAction { private static final long serialVersionUID = -8708581865777449553L; public void actionPerformed(ActionEvent e) { layeredPane.remove(panel); panel = CreateLabelProperties(null); layeredPane.add(panel, new Integer(1)); layeredPane.repaint(); } } class ElementButton extends JButton { private static final long serialVersionUID = 1504183423628680664L; private String element; /** * Constructor for the ElementButton object * *@param element Description of the Parameter */ public ElementButton(String element) { super("H"); this.element = element; } /** * Constructor for the ElementButton object * * @param element Description of the Parameter * @param e Description of the Parameter * @param color Description of the Parameter * @param controlViewer Description of the Parameter */ public ElementButton( String element, MouseListener e,String buttonString) { super(buttonString); this.element = element; setFont(new Font("Times-Roman",Font.BOLD, 15)); setBorder( new BevelBorder(BevelBorder.RAISED) ); setToolTipText(elementTranslator(PeriodicTable.getAtomicNumber(element) )); addMouseListener(e); setAction(new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { ElementButton button = (ElementButton) e.getSource(); setSelectedElement(button.getElement()); SwingUtilities.getWindowAncestor(button).setVisible(false); } }); setText(buttonString); } /** * Gets the element attribute of the ElementButton object * *@return The element value */ public String getElement() { return this.element; } } /** * create the Label * *@param elementSymbol String *@return pan JPanel */ private JPanel CreateLabelProperties(String elementSymbol) { JPanel pan = new JPanel(); pan.setLayout(new BorderLayout()); Color color = new Color(255,255,255); JLabel label; if(elementSymbol != null){ Integer group = PeriodicTable.getGroup(elementSymbol); label = new JLabel("<html><FONT SIZE=+2>" +elementTranslator(PeriodicTable.getAtomicNumber(elementSymbol))+" ("+elementSymbol+")</FONT><br> " +GT.get("Atomic No.")+" "+PeriodicTable.getAtomicNumber(elementSymbol) + (group!=null ? ", "+GT.get("Group")+" "+group : "") +", "+GT.get("Period")+" "+ PeriodicTable.getPeriod(elementSymbol)+"</html>"); label.setBorder(BorderFactory.createEmptyBorder(5,5,5,5)); pan.add(label,BorderLayout.NORTH); label = new JLabel("<html><FONT> " +GT.get("CAS RN:")+" "+ PeriodicTable.getCASId(elementSymbol)+"<br> " +GT.get("Element Category:")+" "+serieTranslator(PeriodicTable.getChemicalSeries(elementSymbol))+"<br> " +GT.get("State:")+" "+phaseTranslator(PeriodicTable.getPhase(elementSymbol))+"<br> " +GT.get("Electronegativity:")+" " +(PeriodicTable.getPaulingElectronegativity(elementSymbol)==null ? GT.get("undefined") : PeriodicTable.getPaulingElectronegativity(elementSymbol))+"<br>" +"</FONT></html>"); label.setMinimumSize(new Dimension(165,150)); label.setBorder(BorderFactory.createEmptyBorder(5,5,5,5)); pan.add(label,BorderLayout.CENTER); } else { label = new JLabel(" "+GT.get("Periodic Table of elements")); label.setHorizontalTextPosition(JLabel.CENTER); label.setVerticalTextPosition(JLabel.CENTER); label.setOpaque(true); label.setBackground(color); pan.add(label,BorderLayout.CENTER); } pan.setBackground(color); pan.setForeground(Color.black); pan.setBorder(BorderFactory.createLineBorder(Color.black)); Dimension d = getSize(); int boxWidth = (int)Math.ceil((d.width-11) / 19f); int boxHeight = (int)Math.ceil((d.height-11) / 12f); pan.setBounds(4*boxWidth, (int)(0.5*boxHeight), 8*boxWidth, (int)(4*boxHeight)); return pan; } }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/dialog/TemplateBrowser.java
.java
13,916
269
/* Copyright (C) 2009 Stefan Kuhn <stefan.kuhn@ebi.ac.uk> * * Contact: cdk-jchempaint@lists.sourceforge.net * * 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.jchempaint.dialog; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.io.IOException; import java.net.JarURLConnection; import java.net.URL; import java.util.ArrayList; import java.util.Enumeration; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.TreeMap; import java.util.jar.JarEntry; import java.util.jar.JarFile; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTabbedPane; import javax.swing.SwingConstants; import org.openscience.cdk.CDKConstants; import org.openscience.cdk.DefaultChemObjectBuilder; import org.openscience.cdk.interfaces.IAtomContainer; import org.openscience.cdk.io.MDLV2000Reader; import org.openscience.cdk.io.IChemObjectReader.Mode; import org.openscience.jchempaint.GT; import org.openscience.jchempaint.dialog.templates.DummyClass; /** * This class shows a list of templates. The one chosen by the user can queried * with getChosenmolecule(). The templates are organized in tabs. The headers of * the tabs are the names of all directories in TEMPLATES_PACKAGE. _ in * directory name is replaced by a space. All files in * theses directories named *.mol are read as MOL files and put as a template on * the respective tab. The first line of the MOL file is used as name to * display. If there is a *.png file in the same directy, it is used * as icon. Do not put anything else in these directories. TEMPLATES_PACKAGE must * contain a class called DummyClass for the directory being located. * If wished, the tab can be added to the Templates menu with an action like: * menuitemnameAction=org.openscience.jchempaint.action.CopyPasteAction@pasteX * where X is the directory name. */ public class TemplateBrowser extends JDialog implements ActionListener { private static final long serialVersionUID = -7684345027847830963L; private JPanel myPanel; private JButton yesButton; private JTabbedPane tabbedPane; private Map<JButton, IAtomContainer> mols = new HashMap<JButton, IAtomContainer>(); private IAtomContainer chosenmolecule; public final static String TEMPLATES_PACKAGE = "org/openscience/jchempaint/dialog/templates"; /** * The molecule chosen by the user. * * @return The molecule, null if cancelled. */ public IAtomContainer getChosenmolecule() { return chosenmolecule; } /** * Constructor for TemplateBrowser. * @param tabToSelect a tab with that name will be shown at startup. */ public TemplateBrowser(String tabToSelect) { super((JFrame)null, GT.get("Structure Templates"), true); this.setName("templates"); myPanel = new JPanel(); getContentPane().add(myPanel); myPanel.setLayout(new BorderLayout()); yesButton = new JButton(GT.get("Cancel")); yesButton.addActionListener(this); JPanel bottomPanel =new JPanel(); bottomPanel.add(yesButton); myPanel.add(bottomPanel, BorderLayout.SOUTH); tabbedPane = new JTabbedPane(JTabbedPane.LEFT, JTabbedPane.WRAP_TAB_LAYOUT); Map<String,List<IAtomContainer>> entriesMol = new TreeMap<String,List<IAtomContainer>>(); Map<IAtomContainer, String> entriesMolName = new HashMap<IAtomContainer, String>(); Map<String, Icon> entriesIcon = new HashMap<String, Icon>(); JPanel allPanel = new JPanel(); GridLayout allLayout = new GridLayout(0,6); GridLayout experimentLayout = new GridLayout(0,6); allPanel.setLayout(allLayout); JScrollPane scrollPane = new JScrollPane(allPanel, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); tabbedPane.addTab(GT.get("All"), scrollPane ); try{ createTemplatesMaps(entriesMol, entriesMolName, entriesIcon, true); myPanel.add( tabbedPane, BorderLayout.CENTER ); Iterator<String> it = entriesMol.keySet().iterator(); int count=0; while(it.hasNext()) { String key=it.next(); JPanel panel = new JPanel(); panel.setLayout(experimentLayout); for(int k=0;k<entriesMol.get(key).size();k++){ IAtomContainer cdkmol = entriesMol.get(key).get(k); Icon icon = entriesIcon.get(entriesMolName.get(cdkmol)); JButton button = new JButton(); if(icon!=null) button.setIcon(icon); panel.add(button); button.setPreferredSize(new Dimension(100,120)); button.setMaximumSize(new Dimension(100,120)); button.addActionListener(this); button.setVerticalTextPosition(SwingConstants.BOTTOM); button.setHorizontalTextPosition(SwingConstants.CENTER); button.setText((String)cdkmol.getProperty(CDKConstants.TITLE)); button.setToolTipText((String)cdkmol.getProperty(CDKConstants.TITLE)); button.setFont(button.getFont().deriveFont(10f)); button.setName((String)cdkmol.getProperty(CDKConstants.TITLE)); mols.put(button, cdkmol); JButton allButton = new JButton(); if(icon!=null) allButton.setIcon(icon); panel.add(button); allButton.setPreferredSize(new Dimension(100,120)); allButton.setMaximumSize(new Dimension(100,120)); allButton.addActionListener(this); allButton.setVerticalTextPosition(SwingConstants.BOTTOM); allButton.setHorizontalTextPosition(SwingConstants.CENTER); allButton.setText((String)cdkmol.getProperty(CDKConstants.TITLE)); allButton.setToolTipText((String)cdkmol.getProperty(CDKConstants.TITLE)); allButton.setFont(allButton.getFont().deriveFont(10f)); mols.put(allButton, cdkmol); allPanel.add(allButton); scrollPane.setPreferredSize(new Dimension(allPanel.getPreferredSize().width +scrollPane.getVerticalScrollBar().getPreferredSize().width,360)); scrollPane.getVerticalScrollBar().setUnitIncrement(16); } tabbedPane.addTab(GT.getStringNoExtraction(key.replace('_', ' ')), panel ); if(tabToSelect.equals(key)){ tabbedPane.setSelectedIndex(count+1); } count++; } pack(); setVisible(true); } catch (Exception e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } /* (non-Javadoc) * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent) */ public void actionPerformed(ActionEvent e) { if(e.getSource()!=yesButton){ chosenmolecule = mols.get(e.getSource()); chosenmolecule.removeProperty(CDKConstants.TITLE); } this.setVisible(false); } /** * Extracts templates from directories. * * @param entriesMol A map of category names and structure. * @param entriesMolName A map of structures and names. * @param entriesIcon A map of structures and images. * @param withsubdirs true=all of the above will be filled, false=only names in entriesMol will be filled (values in entriesMol will be empty, other maps as well, these can be passed as null). * @throws Exception Problems reading directories. */ public static void createTemplatesMaps(Map<String, List<IAtomContainer>> entriesMol, Map<IAtomContainer, String> entriesMolName, Map<String, Icon> entriesIcon, boolean withsubdirs) throws Exception{ DummyClass dummy = new DummyClass(); URL loc = dummy.getClass().getProtectionDomain().getCodeSource().getLocation(); try{ // Create a URL that refers to a jar file on the net URL url = new URL("jar:"+loc.toURI()+"!/"); // Get the jar file JarURLConnection conn = (JarURLConnection)url.openConnection(); JarFile jarfile = conn.getJarFile(); for (Enumeration<JarEntry> e = jarfile.entries() ; e.hasMoreElements() ;) { JarEntry entry = e.nextElement(); if(entry.getName().indexOf(TEMPLATES_PACKAGE+"/")==0){ String restname = entry.getName().substring(new String(TEMPLATES_PACKAGE+"/").length()); if(restname.length()>2){ if(restname.indexOf("/")==restname.length()-1){ entriesMol.put(restname.substring(0,restname.length()-1), new ArrayList<IAtomContainer>()); }else if(restname.indexOf("/")>-1 && withsubdirs){ if(entry.getName().indexOf(".mol")>-1){ InputStream ins = dummy.getClass().getClassLoader().getResourceAsStream(entry.getName()); MDLV2000Reader reader = new MDLV2000Reader(ins, Mode.RELAXED); IAtomContainer cdkmol = (IAtomContainer)reader.read(DefaultChemObjectBuilder.getInstance().newInstance(IAtomContainer.class)); reader.close(); entriesMol.get(restname.substring(0,restname.indexOf("/"))).add(cdkmol); entriesMolName.put(cdkmol,entry.getName().substring(0,entry.getName().length()-4)); }else{ Icon icon = new ImageIcon(new URL(url.toString()+entry.getName())); entriesIcon.put(entry.getName().substring(0,entry.getName().length()-4),icon); } } } } } }catch(IOException ex){ //This is a version we fall back to if no jar available. This should be in Eclipse only. File file = new File(new File(dummy.getClass().getProtectionDomain().getCodeSource().getLocation().toURI()).getAbsolutePath()+File.separator+TEMPLATES_PACKAGE.replace('/', File.separatorChar)); for (int i=0;i<file.listFiles().length ; i++) { if(file.listFiles()[i].isDirectory()){ File dir = file.listFiles()[i]; if(!dir.getName().startsWith(".")) { entriesMol.put(dir.getName(), new ArrayList<IAtomContainer>()); if(withsubdirs){ for(int k=0;k<dir.list().length;k++){ if(dir.listFiles()[k].getName().indexOf(".mol")>-1){ MDLV2000Reader reader = new MDLV2000Reader(new FileInputStream(dir.listFiles()[k]), Mode.RELAXED); IAtomContainer cdkmol = (IAtomContainer)reader.read(DefaultChemObjectBuilder.getInstance().newInstance(IAtomContainer.class)); reader.close(); entriesMol.get(dir.getName()).add(cdkmol); entriesMolName.put(cdkmol,dir.listFiles()[k].getName().substring(0,dir.listFiles()[k].getName().length()-4)); }else{ Icon icon = new ImageIcon(dir.listFiles()[k].getAbsolutePath()); if ( dir.listFiles()[k].getName().toLowerCase().endsWith("png")) { entriesIcon.put(dir.listFiles()[k].getName().substring(0,dir.listFiles()[k].getName().length()-4),icon); } } } } } } } } } }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/dialog/HelpDialog.java
.java
6,319
249
/* * $RCSfile$ * $Author: egonw $ * $Date: 2007-01-04 17:26:00 +0000 (Thu, 04 Jan 2007) $ * $Revision: 7634 $ * * Copyright (C) 1997-2008 Stefan Kuhn, Christoph Steinbeck * * Contact: cdk-jchempaint@lists.sourceforge.net * * 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.jchempaint.dialog; import java.awt.BorderLayout; import java.awt.Container; import java.awt.Cursor; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JEditorPane; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.SwingUtilities; import javax.swing.event.HyperlinkEvent; import javax.swing.event.HyperlinkListener; import javax.swing.text.Document; /** * A Dialog showing help information * */ public class HelpDialog extends JDialog implements HyperlinkListener { private static final long serialVersionUID = 510350451152687814L; JEditorPane html; /** * Constructor for the HelpDialog object * *@param fr Description of the Parameter *@param helpfile Description of the Parameter */ public HelpDialog(JFrame fr, String helpfile, String title) { super(fr, title , false); try { URL helpURL = this.getClass().getClassLoader().getResource(helpfile); if (helpURL != null) { html = new JEditorPane(helpURL); } else { html = new JEditorPane("text/plain", "Unable to find url \"" + helpfile + "\"."); } html.setEditable(false); html.addHyperlinkListener(this); } catch (MalformedURLException e) { System.out.println("Malformed URL: " + e); } catch (IOException e) { System.out.println("IOException: " + e); } JScrollPane scroller = new JScrollPane() { private static final long serialVersionUID = -9024998081172061175L; public Dimension getPreferredSize() { return new Dimension(500, 400); } public float getAlignmentX() { return LEFT_ALIGNMENT; } }; scroller.getViewport().add(html); JPanel htmlWrapper = new JPanel(new BorderLayout()); htmlWrapper.setAlignmentX(LEFT_ALIGNMENT); htmlWrapper.add(scroller, BorderLayout.CENTER); JPanel buttonPanel = new JPanel(); buttonPanel.setLayout(new FlowLayout(FlowLayout.RIGHT)); JButton ok = new JButton("OK"); ok.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { OKPressed(); } }); buttonPanel.add(ok); getRootPane().setDefaultButton(ok); JPanel container = new JPanel(); container.setLayout(new BorderLayout()); container.add(htmlWrapper, BorderLayout.CENTER); container.add(buttonPanel, BorderLayout.SOUTH); getContentPane().add(container); pack(); centerDialog(); } public void hyperlinkUpdate(HyperlinkEvent e) { if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) { linkActivated(e.getURL()); } } /** * Follows the reference in an link. The given url is the requested reference. * By default this calls <a href="#setPage">setPage</a> , and if an exception * is thrown the original previous document is restored and a beep sounded. If * an attempt was made to follow a link, but it represented a malformed url, * this method will be called with a null argument. * *@param u the URL to follow */ protected void linkActivated(URL u) { Cursor c = html.getCursor(); Cursor waitCursor = Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR); html.setCursor(waitCursor); SwingUtilities.invokeLater(new PageLoader(u, c)); } /** * temporary class that loads synchronously (although later than the request * so that a cursor change can be done). * *@author steinbeck */ class PageLoader implements Runnable { /** * Constructor for the PageLoader object * *@param u Description of the Parameter *@param c Description of the Parameter */ PageLoader(URL u, Cursor c) { url = u; cursor = c; } /** * Main processing method for the PageLoader object */ public void run() { if (url == null) { // restore the original cursor html.setCursor(cursor); // remove this hack when automatic validation is // activated. Container parent = html.getParent(); parent.repaint(); } else { Document doc = html.getDocument(); try { html.setPage(url); } catch (IOException ioe) { html.setDocument(doc); getToolkit().beep(); } finally { // schedule the cursor to revert after the paint // has happended. url = null; SwingUtilities.invokeLater(this); } } } URL url; Cursor cursor; } protected void centerDialog() { Dimension screenSize = this.getToolkit().getScreenSize(); Dimension size = this.getSize(); screenSize.height = screenSize.height / 2; screenSize.width = screenSize.width / 2; size.height = size.height / 2; size.width = size.width / 2; int y = screenSize.height - size.height; int x = screenSize.width - size.width; this.setLocation(x, y); } public void OKPressed() { this.setVisible(false); } }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/dialog/ModifyRenderOptionsDialog.java
.java
4,730
132
/* * $RCSfile$ * $Author: egonw $ * $Date: 2007-01-04 17:26:00 +0000 (Thu, 04 Jan 2007) $ * $Revision: 7634 $ * * Copyright (C) 1997-2008 Stefan Kuhn * * Contact: cdk-jchempaint@lists.sourceforge.net * * 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.jchempaint.dialog; import java.awt.BorderLayout; import java.awt.Color; import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JPanel; import org.openscience.jchempaint.AbstractJChemPaintPanel; import org.openscience.jchempaint.GT; import org.openscience.jchempaint.dialog.editor.PropertiesModelEditor; import org.openscience.jchempaint.renderer.JChemPaintRendererModel; /** * Simple Dialog that shows the loaded dictionaries.. * */ public class ModifyRenderOptionsDialog extends JDialog { private static final long serialVersionUID = -7228371698429720333L; private PropertiesModelEditor editor; private JChemPaintRendererModel model; private AbstractJChemPaintPanel jcpPanel; private int tabtoshow; /** * Displays the Info Dialog for JChemPaint. * @param tabtoshow Which tab is to be displayed? */ public ModifyRenderOptionsDialog(AbstractJChemPaintPanel jcpPanel, JChemPaintRendererModel model, int tabtoshow) { super(); this.model = model; this.jcpPanel = jcpPanel; this.tabtoshow = tabtoshow; editor = new PropertiesModelEditor(this, jcpPanel, tabtoshow, jcpPanel.getGuistring()); createDialog(); pack(); setVisible(true); } private void createDialog() { getContentPane().setLayout(new BorderLayout()); setBackground(Color.lightGray); setTitle(GT.get("Preferences")); editor.setModel(model); getContentPane().add("Center", editor); JPanel buttonPanel = new JPanel(); buttonPanel.setLayout(new FlowLayout(FlowLayout.RIGHT)); JButton ok = new JButton(GT.get("OK")); ok.setName("ok"); ok.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { OKPressed(); } } ); buttonPanel.add(ok); getRootPane().setDefaultButton(ok); JButton apply = new JButton(GT.get("Apply")); apply.setName("apply"); apply.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { ApplyPressed(false); } } ); buttonPanel.add(apply); JButton cancel = new JButton(GT.get("Cancel")); cancel.setName("cancel"); cancel.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { closeFrame(); } } ); buttonPanel.add(cancel); getRootPane().setDefaultButton(ok); getContentPane().add("South", buttonPanel); validate(); } private void ApplyPressed(boolean close) { // apply new settings editor.applyChanges(close); jcpPanel.get2DHub().updateView(); } private void OKPressed() { ApplyPressed(true); closeFrame(); } public void closeFrame() { dispose(); } }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/dialog/AboutDialog.java
.java
3,704
108
/* * $RCSfile$ * $Author: egonw $ * $Date: 2007-01-04 17:26:00 +0000 (Thu, 04 Jan 2007) $ * $Revision: 7634 $ * * Copyright (C) 1997-2008 Stefan Kuhn, Tobias Helmus * * Contact: cdk-jchempaint@lists.sourceforge.net * * 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.jchempaint.dialog; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Frame; import java.net.URL; import javax.swing.BorderFactory; import javax.swing.ImageIcon; import javax.swing.JDialog; import javax.swing.JLabel; import javax.swing.JTextArea; import javax.swing.border.Border; import org.openscience.cdk.tools.ILoggingTool; import org.openscience.cdk.tools.LoggingToolFactory; import org.openscience.jchempaint.GT; import org.openscience.jchempaint.JCPMenuTextMaker; import org.openscience.jchempaint.JCPPropertyHandler; import org.openscience.jchempaint.action.JCPAction; /** * Simple Dialog that shows the JCP logo and a textfield that allows * the user to copy&amp;paste the URL of JChemPaints main site. * * @cdk.created 27. April 2005 */ public class AboutDialog extends JDialog { private static final long serialVersionUID = 8890609574363086221L; private static ILoggingTool logger = LoggingToolFactory.createLoggingTool(AboutDialog.class); /** Displays the About Dialog for JChemPaint. */ public AboutDialog(Frame owner, String guistring) { super(owner, JCPMenuTextMaker.getInstance(guistring).getText("about")); doInit(); } public void doInit() { String version = JCPPropertyHandler.getInstance(true).getVersion(); String s1 = "JChemPaint " + version + "\n"; s1 += GT.get("An open-source editor for 2D chemical structures."); String s2 = GT.get("An OpenScience project.")+"\n"; s2 += GT.get("See 'http://jchempaint.github.com' for more information."); getContentPane().setLayout(new BorderLayout()); getContentPane().setBackground(Color.white); JLabel label1 = new JLabel(); try { JCPPropertyHandler jcpph = JCPPropertyHandler.getInstance(true); URL url = jcpph.getResource("jcplogo"); ImageIcon icon = new ImageIcon(url); label1 = new JLabel(icon); } catch (Exception exception) { logger.error("Cannot add JCP logo: " + exception.getMessage()); logger.debug(exception); } label1.setBackground(Color.white); Border lb = BorderFactory.createLineBorder(Color.white, 5); JTextArea jtf1 = new JTextArea(s1); jtf1.setBorder(lb); jtf1.setEditable(false); JTextArea jtf2 = new JTextArea(s2); jtf2.setEditable(false); jtf2.setBorder(lb); getContentPane().add("Center", label1); getContentPane().add("North", jtf1); getContentPane().add("South", jtf2); pack(); setVisible(true); } }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/dialog/editor/ReactionEditor.java
.java
3,670
99
/* * $RCSfile$ * $Author: egonw $ * $Date: 2007-01-04 17:26:00 +0000 (Thu, 04 Jan 2007) $ * $Revision: 7634 $ * * Copyright (C) 1997-2008 Stefan Kuhn * * Contact: cdk-jchempaint@lists.sourceforge.net * * 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.jchempaint.dialog.editor; import javax.swing.JComboBox; import javax.swing.JTextField; import org.openscience.cdk.interfaces.IChemObject; import org.openscience.cdk.interfaces.IReaction; import org.openscience.jchempaint.GT; /** */ public class ReactionEditor extends ChemObjectEditor { private static final long serialVersionUID = 2386363253522364974L; private final static String SOLVENT = "org.openscience.cdk.Reaction.Solvent"; private final static String TEMPERATURE = "org.openscience.cdk.Reaction.Temperature"; private JTextField idField; private JComboBox<?> directionField; private JTextField solventField; private JTextField tempField; public ReactionEditor() { super(false); constructPanel(); } private void constructPanel() { idField = new JTextField(40); addField(GT.get("Reaction ID"), idField, this); // the options given next should match the order in the Reaction class! String[] options = { "", GT.get("Forward"), GT.get("Backward"), GT.get("Bidirectional") }; directionField = new JComboBox<Object>(options); addField(GT.get("Direction"), directionField, this); solventField = new JTextField(40); addField(GT.get("Solvent"), solventField, this); tempField = new JTextField(10); addField(GT.get("Temperature"), tempField, this); } public void setChemObject(IChemObject object) { if (object instanceof IReaction) { source = object; // update table contents IReaction reaction = (IReaction)source; idField.setText(reaction.getID()); //TODO //directionField.setSelectedIndex(reaction.getDirection()); solventField.setText((String)reaction.getProperty(SOLVENT)); tempField.setText((String)reaction.getProperty(TEMPERATURE)); } else { throw new IllegalArgumentException("Argument must be an Reaction"); } } public void applyChanges() { IReaction reaction = (IReaction)source; reaction.setID(idField.getText()); //TODO //reaction.setDirection(directionField.getSelectedIndex()); reaction.setProperty(SOLVENT, solventField.getText()); reaction.setProperty(TEMPERATURE, tempField.getText()); } }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/dialog/editor/PseudoAtomEditor.java
.java
2,745
81
/* * $RCSfile$ * $Author: egonw $ * $Date: 2007-01-04 17:26:00 +0000 (Thu, 04 Jan 2007) $ * $Revision: 7634 $ * * Copyright (C) 1997-2008 Stefan Kuhn * * Contact: cdk-jchempaint@lists.sourceforge.net * * 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.jchempaint.dialog.editor; import javax.swing.JOptionPane; import javax.swing.JTextField; import org.openscience.cdk.interfaces.IChemObject; import org.openscience.cdk.interfaces.IPseudoAtom; import org.openscience.cdk.isomorphism.matchers.RGroupQuery; import org.openscience.jchempaint.GT; /** */ public class PseudoAtomEditor extends ChemObjectEditor { private static final long serialVersionUID = 7785262423262705152L; JTextField labelField; public PseudoAtomEditor() { super(false); constructPanel(); } private void constructPanel() { labelField = new JTextField(20); addField(GT.get("Label"), labelField, this); } public void setChemObject(IChemObject object) { if (object instanceof IPseudoAtom) { source = object; // update table contents labelField.setText(((IPseudoAtom)object).getLabel()); } else { throw new IllegalArgumentException("Argument must be an PseudoAtom"); } } public void applyChanges() { String label=labelField.getText(); if (label!=null && label.startsWith("R")&&label.length()>1 && !RGroupQuery.isValidRgroupQueryLabel(label) ) { JOptionPane.showMessageDialog(null, GT.get("This is not a valid R-group label.\nPlease label in range R1 .. R32")); } else { IPseudoAtom atom = (IPseudoAtom)source; atom.setLabel(labelField.getText()); } } }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/dialog/editor/PropertiesModelEditor.java
.java
23,134
547
/* * $RCSfile$ * $Author: egonw $ * $Date: 2007-01-04 17:26:00 +0000 (Thu, 04 Jan 2007) $ * $Revision: 7634 $ * * Copyright (C) 1997-2008 Stefan Kuhn * Some portions Copyright (C) 2009 Konstantin Tokarev * * Contact: cdk-jchempaint@lists.sourceforge.net * * 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.jchempaint.dialog.editor; import com.formdev.flatlaf.FlatDarkLaf; import com.formdev.flatlaf.FlatLightLaf; import com.formdev.flatlaf.themes.FlatMacDarkLaf; import com.formdev.flatlaf.themes.FlatMacLightLaf; import org.openscience.jchempaint.AbstractJChemPaintPanel; import org.openscience.jchempaint.GT; import org.openscience.jchempaint.JCPPropertyHandler; import org.openscience.jchempaint.JChemPaintPanel; import org.openscience.jchempaint.action.JCPAction; import org.openscience.jchempaint.applet.JChemPaintEditorApplet; import org.openscience.jchempaint.dialog.FieldTablePanel; import org.openscience.jchempaint.dialog.ModifyRenderOptionsDialog; import org.openscience.jchempaint.renderer.JChemPaintRendererModel; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JColorChooser; import javax.swing.JComboBox; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JSeparator; import javax.swing.JSpinner; import javax.swing.JTextField; import javax.swing.SpinnerNumberModel; import javax.swing.SwingUtilities; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException; import java.awt.Color; import java.awt.Container; import java.awt.GridBagLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Arrays; import java.util.List; import java.util.Properties; /** * @cdk.bug 1525961 */ public class PropertiesModelEditor extends FieldTablePanel implements ActionListener { private static final long serialVersionUID = 8694652992068950179L; private String guistring; private JCheckBox drawNumbers; //private JCheckBox showAtomAtomMapping; private JCheckBox showAllCarbons; private JCheckBox showEndCarbons; // private JCheckBox showExplicitHydrogens; // // private JCheckBox showImplicitHydrogens; private JCheckBox showAromaticity; //private JCheckBox showAromaticityCDKStyle; private JCheckBox colorAtomsByType; //private JCheckBox showToolTip; private JCheckBox showReactionBoxes; //private JCheckBox useAntiAliasing; private JCheckBox isFitToScreen; private JSpinner strokeWidth; private JSpinner bondSeparation; //private JSlider bondLength; private JSpinner highlightDistance; private JSpinner wedgeWidth; private JSpinner hashSpacing; //private JLabel fontName; //private JButton chooseFontButton; //private String currentFontName; private JLabel color; private JButton chooseColorButton; private Color currentColor; private JDialog frame; private AbstractJChemPaintPanel jcpPanel; private JChemPaintRendererModel model; private JCheckBox askForIOSettings; private JTextField undoStackSize; private JComboBox<?> language; private JComboBox<?> lookAndFeel; private JCheckBox fontIcons; String[] lookAndFeels = {GT.get("System"), "Metal", "Nimbus", "Motif", "GTK", "Windows", "FlatLightLaf", "FlatDarkLaf", "FlatMacLightLaf", "FlatMacDarkLaf"}; private GT.Language[] gtlanguages = GT.getLanguageList(); private int tabtoshow; public PropertiesModelEditor(JDialog frame, AbstractJChemPaintPanel jcpPanel, int tabtoshow, String gui) { super(true); this.frame = frame; this.guistring = gui; this.jcpPanel = jcpPanel; this.tabtoshow = tabtoshow; constructPanel(); } private void constructPanel() { JPanel rendererOptionsPanel = this.addTab(GT.get("Display Preferences")); rendererOptionsPanel.setLayout(new java.awt.GridLayout(1, 2, 5, 0)); JPanel options1 = new JPanel(); options1.setLayout(new BoxLayout(options1, BoxLayout.PAGE_AXIS)); rendererOptionsPanel.add(options1); JPanel options2 = new JPanel(); options2.setLayout(new GridBagLayout()); rendererOptionsPanel.add(options2); //addField("",new JPanel()); //addField("Rendering Settings",new JPanel()); addField("", new JLabel(" "), options1); drawNumbers = new JCheckBox(GT.get("Draw atom numbers")); drawNumbers.setEnabled(false); options1.add(drawNumbers); //addField(GT._("Draw atom numbers"), drawNumbers, options1); //showAtomAtomMapping = new JCheckBox(); //addField(GT._("Show atom-atom mappings"), showAtomAtomMapping); showAllCarbons = new JCheckBox(GT.get("All Carbons Explicit")); options1.add(showAllCarbons); //addField(GT._("Explicit carbons"), useKekuleStructure, options1); showEndCarbons = new JCheckBox(GT.get("Terminal Carbons Explicit")); options1.add(showEndCarbons); //addField(GT._("Show explicit methyl groups"), showEndCarbons, options1); showAromaticity = new JCheckBox(GT.get("Show aromatic ring circles")); showAromaticity.setEnabled(false); options1.add(showAromaticity); //addField(GT._("Show aromatic ring circles"), showAromaticity, options1); //showAromaticityCDKStyle = new JCheckBox(); //addField(GT._("CDK style aromatics"), showAromaticityCDKStyle); colorAtomsByType = new JCheckBox(GT.get("Color atoms by element")); options1.add(colorAtomsByType); //addField(GT._("Color atoms by element"), colorAtomsByType, options1); //useAntiAliasing = new JCheckBox(); //addField(GT._("Use Anti-Aliasing"), useAntiAliasing, options1); //showToolTip = new JCheckBox(); //addField(GT._("Show tooltips"), showToolTip); showReactionBoxes = new JCheckBox(GT.get("Show boxes around reactions")); options1.add(showReactionBoxes); isFitToScreen = new JCheckBox(GT.get("Set fit to screen")); options1.add(isFitToScreen); //addField(GT._("Set fit to screen"), isFitToScreen, options1); color = new JLabel(); color.setText(" " + GT.get("Background Color") + " "); color.setOpaque(true); options1.add(color); chooseColorButton = new JButton(GT.get("Choose")); chooseColorButton.addActionListener(this); chooseColorButton.setActionCommand("chooseColor"); addField(color, chooseColorButton, options2, 0); strokeWidth = new JSpinner(new SpinnerNumberModel(0, 0, 5, 0.1)); addField(GT.get("Bond Width"), strokeWidth, options2); bondSeparation = new JSpinner(new SpinnerNumberModel(.18, 0, 1, .01)); JSpinner.NumberEditor editor = new JSpinner.NumberEditor(bondSeparation, "0%"); bondSeparation.setEditor(editor); addField(GT.get("Bond Spacing (% of length)"), bondSeparation, options2); wedgeWidth = new JSpinner(new SpinnerNumberModel(6.0, 0.0, 15.0, 1.0)); addField(GT.get("Wedge Width"), wedgeWidth, options2); hashSpacing = new JSpinner(new SpinnerNumberModel(0, 0, 10, 0.1)); addField(GT.get("Hash Spacing"), hashSpacing, options2); highlightDistance = new JSpinner(new SpinnerNumberModel(5,0,25,1)); addField(GT.get("Highlight Distance"), highlightDistance, options2); /* currentFontName = ""; fontName = new JLabel(); addField(GT._("Font name"), fontName); chooseFontButton = new JButton(GT._("Choose Font...")); chooseFontButton.addActionListener(this); chooseFontButton.setActionCommand("chooseFont"); addField("", chooseFontButton); */ //addField("", chooseColorButton, options2); JPanel otherOptionsPanel = this.addTab(GT.get("Other Preferences")); undoStackSize = new JTextField(); addField(GT.get("Number of undoable operations"), undoStackSize, otherOptionsPanel); askForIOSettings = new JCheckBox(); addField(GT.get("Ask for CML settings when saving"), askForIOSettings, otherOptionsPanel); if (!guistring.equals(JChemPaintEditorApplet.GUI_APPLET)) { lookAndFeel = new JComboBox<Object>(lookAndFeels); addField(GT.get("Look and feel"), lookAndFeel, otherOptionsPanel); fontIcons = new JCheckBox(); addField(GT.get("Font Icons (restart required)"), fontIcons, otherOptionsPanel); addField("", new JSeparator(), otherOptionsPanel); } String[] languagesstrings = new String[gtlanguages.length]; for (int i = 0; i < gtlanguages.length; i++) { languagesstrings[i] = gtlanguages[i].language; } language = new JComboBox<Object>(languagesstrings); language.setName("language"); for (int i = 0; i < languagesstrings.length; i++) { if (gtlanguages[i].code.equals(GT.getLanguage())) language.setSelectedIndex(i); } addField(GT.get("User Interface Language"), language, otherOptionsPanel); this.tabbedPane.setSelectedIndex(tabtoshow); } public void setModel(JChemPaintRendererModel model) { this.model = model; drawNumbers.setSelected(model.getDrawNumbers()); //showAtomAtomMapping.setSelected(model.getShowAtomAtomMapping()); showAllCarbons.setSelected(model.getKekuleStructure()); showEndCarbons.setSelected(model.getShowEndCarbons()); // showAromaticity.setSelected(false); // dissabled for now //showAromaticityCDKStyle.setSelected(model.getShowAromaticityCDKStyle()); colorAtomsByType.setSelected(model.getColorAtomsByType()); //useAntiAliasing.setSelected(model.getUseAntiAliasing()); //showToolTip.setSelected(model.getShowTooltip()); showReactionBoxes.setSelected(model.getShowReactionBoxes()); isFitToScreen.setSelected(model.isFitToScreen()); strokeWidth.setValue(model.getBondWidth()); bondSeparation.setValue(model.getBondSeparation()); //bondLength.setValue((int)model.getBondLength()); highlightDistance.setValue((int) model.getHighlightDistance()); hashSpacing.setValue(model.getHashSpacing()); wedgeWidth.setValue(model.getWedgeWidth()); /* currentFontName = model.getFontName(); if (!currentFontName.equals("")) { fontName.setText(currentFontName); } */ currentColor = model.getBackColor(); if (currentColor != null) { color.setBackground(currentColor); } //the general settings JCPPropertyHandler jcpph = JCPPropertyHandler.getInstance(true); Properties props = jcpph.getJCPProperties(); askForIOSettings.setSelected(props.getProperty("General.askForIOSettings").equals("true")); undoStackSize.setText(props.getProperty("General.UndoStackSize", "50")); if (!guistring.equals(JChemPaintEditorApplet.GUI_APPLET)) { lookAndFeel.setSelectedIndex(Integer.parseInt(props.getProperty("LookAndFeel", "0"))); fontIcons.setSelected(jcpph.getBool("useFontIcons", true)); } language.setSelectedItem(props.getProperty("General.language")); validate(); } public void applyChanges(boolean close) { Properties props = JCPPropertyHandler.getInstance(true).getJCPProperties(); model.setDrawNumbers(drawNumbers.isSelected()); //model.setShowAtomAtomMapping(showAtomAtomMapping.isSelected()); model.setKekuleStructure(showAllCarbons.isSelected()); model.setShowEndCarbons(showEndCarbons.isSelected()); model.setShowAromaticity(showAromaticity.isSelected()); //model.setShowAromaticityCDKStyle(showAromaticityCDKStyle.isSelected()); model.setColorAtomsByType(colorAtomsByType.isSelected()); //model.setUseAntiAliasing(useAntiAliasing.isSelected()); //model.setShowTooltip(showToolTip.isSelected()); model.setShowReactionBoxes(showReactionBoxes.isSelected()); model.setFitToScreen(isFitToScreen.isSelected()); //model.setBondLength(bondLength.getValue()); model.setBondWidth((double) strokeWidth.getValue()); model.setBondSeparation(((double)bondSeparation.getValue())); model.setWedgeWidth((double) wedgeWidth.getValue()); model.setHashSpacing((double) hashSpacing.getValue()); model.setHighlightDistance((int)highlightDistance.getValue()); model.setBackColor(currentColor); if (language.getSelectedIndex() != -1) { GT.setLanguage(gtlanguages[language.getSelectedIndex()].code); jcpPanel.updateMenusWithLanguage(); updateLanguge(); } props.setProperty("DrawNumbers", String.valueOf(drawNumbers.isSelected())); //props.setProperty("ShowAtomAtomMapping",String.valueOf(showAtomAtomMapping.isSelected())); props.setProperty("KekuleStructure", String.valueOf(showAllCarbons.isSelected())); props.setProperty("ShowEndCarbons", String.valueOf(showEndCarbons.isSelected())); props.setProperty("ShowAromaticity", String.valueOf(showAromaticity.isSelected())); //props.setProperty("ShowAromaticityCDKStyle",String.valueOf(showAromaticityCDKStyle.isSelected())); props.setProperty("ColorAtomsByType", String.valueOf(colorAtomsByType.isSelected())); //props.setProperty("UseAntiAliasing",String.valueOf(useAntiAliasing.isSelected())); //props.setProperty("ShowTooltip",String.valueOf(showToolTip.isSelected())); props.setProperty("ShowReactionBoxes", String.valueOf(showReactionBoxes.isSelected())); props.setProperty("FitToScreen", String.valueOf(isFitToScreen.isSelected())); props.setProperty("BondWidth", String.valueOf(strokeWidth.getValue())); props.setProperty("BondSeparation", String.valueOf(bondSeparation.getValue())); props.setProperty("HighlightDistance", String.valueOf(highlightDistance.getValue())); props.setProperty("WedgeWidth", String.valueOf(wedgeWidth.getValue())); props.setProperty("HashSpacing", String.valueOf(hashSpacing.getValue())); //props.setFontName(currentFontName); String backColorVal = String.valueOf(currentColor.getRGB()); boolean backColorChanged = !backColorVal.equals(props.getProperty("BackColor")); props.setProperty("BackColor", backColorVal); //the general settings props.setProperty("General.askForIOSettings", String.valueOf(askForIOSettings.isSelected()) ); try { int size = Integer.parseInt(undoStackSize.getText()); if (size < 1 || size > 100) throw new Exception("wrong number"); props.setProperty("General.UndoStackSize", undoStackSize.getText()); jcpPanel.getRenderPanel().getUndoManager().setLimit(size); } catch (Exception ex) { JOptionPane.showMessageDialog(this, GT.get("Number of undoable operations") + " " + GT.get("must be a number from 1 to 100"), GT.get("Number of undoable operations"), JOptionPane.WARNING_MESSAGE); } if (!guistring.equals(JChemPaintEditorApplet.GUI_APPLET)) { boolean useFontIcons = fontIcons.isSelected(); String lnfName = ""; try { switch (lookAndFeel.getSelectedIndex()) { case 0: lnfName = UIManager.getSystemLookAndFeelClassName(); break; // System case 1: lnfName = UIManager.getCrossPlatformLookAndFeelClassName(); break; // Metal case 2: lnfName = "com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel"; break; // Nimbus case 3: lnfName = "com.sun.java.swing.plaf.motif.MotifLookAndFeel"; break; // Motif case 4: lnfName = "com.sun.java.swing.plaf.gtk.GTKLookAndFeel"; break; // GTK case 5: lnfName = "com.sun.java.swing.plaf.windows.WindowsLookAndFeel"; break; // Windows case 6: lnfName = FlatLightLaf.class.getName(); break; // FlatLightLaf case 7: lnfName = FlatDarkLaf.class.getName(); break; // FlatDarkLaf case 8: lnfName = FlatMacLightLaf.class.getName(); break; // FlatMacLightLaf case 9: lnfName = FlatMacDarkLaf.class.getName(); break; // FlatMacDarkLaf default: lnfName = ""; } UIManager.setLookAndFeel(lnfName); props.setProperty("useFontIcons", Boolean.toString(useFontIcons)); // when switching UI theme we also set the background color // unless it was changed explicitly if (!backColorChanged) { currentColor = lnfName.contains("Dark") ? new Color(51, 51, 51) : Color.white; color.setBackground(currentColor); model.setBackColor(currentColor); props.setProperty("BackColor", Integer.toString(currentColor.getRGB())); } SwingUtilities.updateComponentTreeUI(frame); frame.pack(); // Apply to all instances of JChemPaint for (int i = 0; i < JChemPaintPanel.instances.size(); i++) { Container c = JChemPaintPanel.instances.get(i).getTopLevelContainer(); if (c instanceof JFrame) { JFrame f = (JFrame) c; SwingUtilities.updateComponentTreeUI(f); f.pack(); } } props.setProperty("LookAndFeel", String.valueOf(lookAndFeel.getSelectedIndex())); props.setProperty("LookAndFeelClass", lnfName); } catch (UnsupportedLookAndFeelException e) { JOptionPane.showMessageDialog(this, GT.get("Look and feel") + " \"" + lookAndFeel.getSelectedItem() + "\" " + GT.get("is not supported on this platform"), GT.get("Unsupported look&feel"), JOptionPane.WARNING_MESSAGE); } catch (ClassNotFoundException e) { JOptionPane.showMessageDialog(this, GT.get("Class not found:") + " " + lnfName); } catch (InstantiationException e) { // handle exception JOptionPane.showMessageDialog(this, GT.get("Instantiation Exception:") + " " + lnfName); } catch (IllegalAccessException e) { JOptionPane.showMessageDialog(this, GT.get("Illegal Access: ") + lnfName); } } jcpPanel.getRenderPanel() .updateDisplayOptions(); JCPPropertyHandler.getInstance(true).saveProperties(); boolean languagechanged = false; for (GT.Language gtlanguage : gtlanguages) { if (gtlanguage.language.equals((String) language.getSelectedItem())) { // en_US/en_GB ~ en (startsWith) String currentLanguage = props.getProperty("General.language"); if (currentLanguage == null || !gtlanguage.code.startsWith(currentLanguage)) { props.setProperty("General.language", gtlanguage.code); languagechanged = true; } break; } } JCPPropertyHandler.getInstance(true).saveProperties(); if (languagechanged && !close) { //we need to rediplay the dialog to change its language this.getParent().getParent().getParent().getParent().setVisible(false); JChemPaintRendererModel renderModel = jcpPanel.get2DHub().getRenderer().getRenderer2DModel(); ModifyRenderOptionsDialog frame = new ModifyRenderOptionsDialog(jcpPanel, renderModel, tabbedPane.getSelectedIndex()); frame.setVisible(true); } } private void updateLanguge() { // TODO here the language of the editor window needs to be updated } /** * Required by the ActionListener interface. */ public void actionPerformed(ActionEvent e) { /* if ("chooseFont".equals(e.getActionCommand())) { Font newFont = JFontChooser.showDialog( this.frame, GT._("Choose a Font"), GT._("Carbon Dioxide"), new Font(currentFontName, Font.PLAIN, 12)); if (newFont != null) { currentFontName = newFont.getFontName(); fontName.setText(currentFontName); } } */ if ("chooseColor".equals(e.getActionCommand())) { Color newColor = JColorChooser.showDialog(this, GT.get("Choose Background Color"), model.getBackColor()); if (newColor != null) { currentColor = newColor; color.setBackground(currentColor); } } } }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/dialog/editor/AtomContainerEditor.java
.java
2,623
77
/* * $RCSfile$ * $Author: egonw $ * $Date: 2007-01-04 17:26:00 +0000 (Thu, 04 Jan 2007) $ * $Revision: 7634 $ * * Copyright (C) 1997-2008 Stefan Kuhn * * Contact: cdk-jchempaint@lists.sourceforge.net * * 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.jchempaint.dialog.editor; import javax.swing.JTextField; import org.openscience.cdk.CDKConstants; import org.openscience.cdk.interfaces.IChemObject; import org.openscience.cdk.interfaces.IAtomContainer; import org.openscience.jchempaint.GT; /** */ public class AtomContainerEditor extends ChemObjectEditor { private static final long serialVersionUID = -5106331683641108940L; JTextField titleField; public AtomContainerEditor() { super(false); constructPanel(); } private void constructPanel() { titleField = new JTextField(30); titleField.setName("Title"); addField(GT.get("Title"), titleField, this); } public void setChemObject(IChemObject object) { if (object instanceof IAtomContainer) { source = object; // update table contents IAtomContainer container = (IAtomContainer)source; String title = ""; if (container.getProperty(CDKConstants.TITLE) != null) title = container.getProperty(CDKConstants.TITLE).toString(); titleField.setText(title); } else { throw new IllegalArgumentException("Argument must be an AtomContainer"); } } public void applyChanges() { source.setProperty(CDKConstants.TITLE, titleField.getText()); } }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/dialog/editor/BondEditor.java
.java
5,364
168
/* * $RCSfile$ * $Author: egonw $ * $Date: 2007-01-04 17:26:00 +0000 (Thu, 04 Jan 2007) $ * $Revision: 7634 $ * * Copyright (C) 1997-2008 Stefan Kuhn * 2012 Ralf Stephan <ralf@ark.in-berlin.de> * * Contact: cdk-jchempaint@lists.sourceforge.net * * 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.jchempaint.dialog.editor; import java.util.List; import java.util.Set; import javax.swing.JComboBox; import org.openscience.cdk.interfaces.IBond; import org.openscience.cdk.interfaces.IChemObject; import org.openscience.cdk.interfaces.IBond.Order; import org.openscience.cdk.interfaces.IBond.Stereo; import org.openscience.jchempaint.GT; import org.openscience.jchempaint.controller.IChemModelRelay; /** */ public class BondEditor extends ChemObjectEditor { private static final long serialVersionUID = -5262566515479485581L; JComboBox<?> orderField; JComboBox<?> stereoField; IChemModelRelay hub; Set<String> blocked; public BondEditor(IChemModelRelay hub, Set<String> blocked) { super(false); this.hub = hub; this.blocked = blocked; constructPanel(); } // Since the order in the following arrays is arbitrary, we must add // index functions, too. private String[] orderString = {GT.get("Single"), GT.get("Double"), GT.get("Triple"), GT.get("Quadruple")}; private String[] stereoString = {GT.get("None"), GT.get("Up"), GT.get("Down"), GT.get("Up or Down"), GT.get("E or Z")}; private static int bondOrderIndex(IBond.Order o) { switch (o) { case SINGLE: return 0; case DOUBLE: return 1; case TRIPLE: return 2; case QUADRUPLE: return 3; } return -1; } private static int bondStereoIndex(IBond.Stereo s) { switch (s) { case NONE: return 0; case UP: return 1; case DOWN: return 2; case UP_OR_DOWN: return 3; case E_OR_Z: return 4; } return -1; } private void constructPanel() { orderField = new JComboBox<Object>(orderString); addField(GT.get("Bond order"), orderField, this); if (!blocked.contains("stereochemistry")) { stereoField = new JComboBox<Object>(stereoString); addField(GT.get("Bond stereo"), stereoField, this); } } public void setChemObject(IChemObject object) { if (object instanceof org.openscience.cdk.interfaces.IBond) { source = object; IBond bond = (IBond) source; orderField.setSelectedIndex(bondOrderIndex(bond.getOrder())); if (!blocked.contains("stereochemistry")) stereoField.setSelectedIndex(bondStereoIndex(bond.getStereo())); } else { throw new IllegalArgumentException("Argument must be an Bond"); } } public void applyChanges() { IBond bond = (IBond) source; int newOrder = orderField.getSelectedIndex(); Order order = null; switch (newOrder) { case 0: order = Order.SINGLE; break; case 1: order = Order.DOUBLE; break; case 2: order = Order.TRIPLE; break; case 3: order = Order.QUADRUPLE; break; } IBond.Display display = null; if (order != Order.SINGLE || stereoField == null) { display = IBond.Display.Solid; } else { int newStereo = stereoField.getSelectedIndex(); switch (newStereo) { case 0: display = IBond.Display.Solid; break; case 1: display = IBond.Display.Up; break; case 2: display = IBond.Display.Down; break; case 3: display = IBond.Display.Wavy; break; case 4: display = IBond.Display.Crossed; break; } } hub.changeBond(bond, order, display); } }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/dialog/editor/ChemObjectPropertyDialog.java
.java
3,836
116
/* * $RCSfile$ * $Author: egonw $ * $Date: 2007-01-04 17:26:00 +0000 (Thu, 04 Jan 2007) $ * $Revision: 7634 $ * * Copyright (C) 1997-2008 Stefan Kuhn * * Contact: cdk-jchempaint@lists.sourceforge.net * * 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.jchempaint.dialog.editor; import java.awt.BorderLayout; import java.awt.Color; import java.awt.FlowLayout; import java.awt.Frame; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JOptionPane; import javax.swing.JPanel; import org.openscience.jchempaint.GT; import org.openscience.jchempaint.controller.ControllerHub; /** * Simple Dialog that shows the loaded dictionaries. * */ public class ChemObjectPropertyDialog extends JDialog { private static final long serialVersionUID = 1850053536210317644L; private ChemObjectEditor editor; private ControllerHub hub; /** * Displays the Info Dialog for JChemPaint. */ public ChemObjectPropertyDialog(Frame frame, ControllerHub hub, ChemObjectEditor editor) { super(frame,"IChemObject Props Dialog"); this.editor = editor; this.hub=hub; createDialog(); pack(); setVisible(true); } private void createDialog(){ getContentPane().setLayout(new BorderLayout()); setBackground(Color.lightGray); setTitle(GT.get("Properties")); getContentPane().add("Center",editor); JPanel buttonPanel = new JPanel(); buttonPanel.setLayout ( new FlowLayout(FlowLayout.RIGHT) ); JButton ok = new JButton(GT.get("OK")); ok.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { OKPressed(); }} ); buttonPanel.add( ok ); JButton cancel = new JButton(GT.get("Cancel")); cancel.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { closeFrame(); }} ); buttonPanel.add( cancel ); getRootPane().setDefaultButton(ok); getContentPane().add("South",buttonPanel); validate(); } private void OKPressed() { if(editor.getMayclose()){ try { editor.applyChanges(); hub.updateView(); closeFrame(); } catch (Exception e) { JOptionPane.showMessageDialog(this,e.getMessage(), GT.get("A problem has occurred"), JOptionPane.WARNING_MESSAGE, null); } }else{ JOptionPane.showMessageDialog(this,GT.get("You did not provide necessary information"), GT.get("Incomplete Information"), JOptionPane.WARNING_MESSAGE, null); } } public void closeFrame() { dispose(); } }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/dialog/editor/RGroupEditor.java
.java
6,534
185
/* * Copyright (C) 2010 Mark Rijnbeek * * Contact: cdk-jchempaint@lists.sourceforge.net * * 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.jchempaint.dialog.editor; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import javax.swing.JComboBox; import javax.swing.JPanel; import javax.swing.JTextField; import org.openscience.cdk.exception.CDKException; import org.openscience.cdk.interfaces.IChemObject; import org.openscience.cdk.isomorphism.matchers.IRGroupQuery; import org.openscience.cdk.isomorphism.matchers.RGroupList; import org.openscience.cdk.isomorphism.matchers.IRGroupList; import org.openscience.jchempaint.GT; import org.openscience.jchempaint.controller.IChemModelRelay; /** * Editor for R-group 'advanced logic': occurrence, restH and the if/then condition. * */ public class RGroupEditor extends ChemObjectEditor { private static final long serialVersionUID = -9076542982586267285L; private IChemModelRelay hub; private List<Integer> rNumbers; private List<JPanel> panels; public RGroupEditor(IChemModelRelay hub) { super(true); this.hub=hub; panels= new ArrayList<JPanel>(); constructPanel(); } private void constructPanel() { rNumbers= new ArrayList<Integer>(); for (Iterator<Integer> rnumItr=hub.getRGroupHandler().getrGroupQuery().getRGroupDefinitions().keySet().iterator(); rnumItr.hasNext();) { rNumbers.add(rnumItr.next()); } Collections.sort(rNumbers); for(Integer r : rNumbers) { JPanel rgrpPanel = this.addTab("R"+r); JTextField occurrenceField = new JTextField(20); occurrenceField.setName("occurrence"); addField(GT.get("Occurrence"), occurrenceField, rgrpPanel,DEF_INSET); String[] trueFalseStrings = { GT.get("True"), GT.get("False")}; JComboBox<?> restHBox= new JComboBox<Object>(trueFalseStrings); restHBox.setName("restH"); addField(GT.get("Rest H"), restHBox, rgrpPanel,DEF_INSET); List<String> otherRnums = new ArrayList<String>(); otherRnums.add(GT.get("None")); for (Iterator<Integer> rnumItr=hub.getRGroupHandler().getrGroupQuery().getRGroupDefinitions().keySet().iterator(); rnumItr.hasNext();) { int r_=rnumItr.next(); if (r_!= r) { otherRnums.add("R"+r_); } } String[] ifThenStrings=(String[])(otherRnums.toArray(new String[otherRnums.size()])); JComboBox<?> ifThenBox = new JComboBox<Object>(ifThenStrings); ifThenBox.setName("ifThen"); addField(GT.get("If R" + r + " then "), ifThenBox, rgrpPanel,DEF_INSET); panels.add(rgrpPanel); } } public void setChemObject(IChemObject object) { if (object instanceof IRGroupQuery) { source = object; IRGroupQuery rgroupQuery = (IRGroupQuery)source; for (int i=0; i< rNumbers.size(); i++) { int r = rNumbers.get(i); JPanel rgrpPanel = panels.get(i); IRGroupList rgrpList = rgroupQuery.getRGroupDefinitions().get(r); JTextField occurrenceField = (JTextField) (rgrpPanel.getComponent(1)); String occ=rgrpList.getOccurrence(); occurrenceField.setText(occ); JComboBox<?> restHBox = (JComboBox<?>) (rgrpPanel.getComponent(3)); boolean restH=rgrpList.isRestH(); String restHString= restH? GT.get("True"): GT.get("False"); restHBox.setSelectedItem(restHString); JComboBox<?> ifThenBox = (JComboBox<?>) (rgrpPanel.getComponent(5)); int ifThenR = rgrpList.getRequiredRGroupNumber(); String ifThenRString= ifThenR==0?GT.get("None"):"R"+ifThenR; ifThenBox.setSelectedItem(ifThenRString); } } else { throw new IllegalArgumentException("Argument must be a IRGroupQuery"); } } public void applyChanges() { IRGroupQuery rgroupQuery = (IRGroupQuery)source; //Validate the "occurence" input for (int i=0; i< rNumbers.size(); i++) { int r = rNumbers.get(i); JPanel rgrpPanel = panels.get(i); IRGroupList rgrpList = rgroupQuery.getRGroupDefinitions().get(r); JTextField occurrenceField = (JTextField) (rgrpPanel.getComponent(1)); String userOccurrenceText=occurrenceField.getText(); if (userOccurrenceText.trim().equals("") || !RGroupList.isValidOccurrenceSyntax(userOccurrenceText)) { throw new RuntimeException (GT.get("Invalid occurrence specified for {0}", "R" + r)); } } //Aply input to model for (int i = 0; i < rNumbers.size(); i++) { int r = rNumbers.get(i); JPanel rgrpPanel = panels.get(i); IRGroupList rgrpList = rgroupQuery.getRGroupDefinitions().get(r); if (rgrpList instanceof RGroupList) { RGroupList rGroupList = (RGroupList) rgrpList; JTextField occurrenceField = (JTextField) (rgrpPanel.getComponent(1)); String userOccurrenceText = occurrenceField.getText(); try { rGroupList.setOccurrence(userOccurrenceText); } catch (CDKException e) { e.printStackTrace(); } JComboBox<?> restHBox = (JComboBox<?>) (rgrpPanel.getComponent(3)); String restHString = (String) (restHBox.getSelectedItem()); if (restHString.equals(GT.get("True"))) rGroupList.setRestH(true); else rGroupList.setRestH(false); JComboBox<?> ifThenBox = (JComboBox<?>) (rgrpPanel.getComponent(5)); String ifThenR = (String) (ifThenBox.getSelectedItem()); if (ifThenR.equals(GT.get("None"))) rGroupList.setRequiredRGroupNumber(0); else { int userRnumInput = Integer.parseInt(ifThenR.substring(1)); rGroupList.setRequiredRGroupNumber(userRnumInput); } } else { throw new IllegalStateException("rgrpList is not an instance of RGroupList"); } } } }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/dialog/editor/ChemObjectEditor.java
.java
1,833
58
/* * $RCSfile$ * $Author: egonw $ * $Date: 2007-01-04 17:26:00 +0000 (Thu, 04 Jan 2007) $ * $Revision: 7634 $ * * Copyright (C) 1997-2008 Stefan Kuhn * * Contact: cdk-jchempaint@lists.sourceforge.net * * 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.jchempaint.dialog.editor; import org.openscience.cdk.interfaces.IChemObject; import org.openscience.jchempaint.dialog.FieldTablePanel; /** */ public abstract class ChemObjectEditor extends FieldTablePanel { public ChemObjectEditor(boolean hasTabs) { super(hasTabs); } protected IChemObject source; protected boolean mayclose=true; public void setChemObject(IChemObject object) { source = object; } public boolean getMayclose(){ return mayclose; } public void applyChanges() {} }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/dialog/editor/AtomEditor.java
.java
7,515
176
/* * $RCSfile$ * $Author: egonw $ * $Date: 2007-01-04 17:26:00 +0000 (Thu, 04 Jan 2007) $ * $Revision: 7634 $ * * Copyright (C) 1997-2008 Stefan Kuhn * * Contact: cdk-jchempaint@lists.sourceforge.net * * 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.jchempaint.dialog.editor; import java.io.IOException; import javax.swing.JSpinner; import javax.swing.JTextField; import javax.swing.SpinnerNumberModel; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import javax.swing.text.Document; import org.openscience.cdk.CDKConstants; import org.openscience.cdk.PseudoAtom; import org.openscience.cdk.config.Isotopes; import org.openscience.cdk.interfaces.IAtom; import org.openscience.cdk.interfaces.IChemObject; import org.openscience.cdk.interfaces.IIsotope; import org.openscience.cdk.tools.ILoggingTool; import org.openscience.cdk.tools.LoggingToolFactory; import org.openscience.jchempaint.GT; import org.openscience.jchempaint.controller.IChemModelRelay; /** */ public class AtomEditor extends ChemObjectEditor { private static final long serialVersionUID = -6693485657147158966L; private static ILoggingTool logger = LoggingToolFactory.createLoggingTool(AtomEditor.class); JTextField symbolField; JSpinner hCountField; JSpinner formalChargeField; JSpinner isotopeField; IChemModelRelay hub; int majorIsotopeNumber; JTextField commentField; public AtomEditor(IChemModelRelay hub) { super(false); constructPanel(); this.hub=hub; super.mayclose=false; } private void constructPanel() { symbolField = new JTextField(4); symbolField.getDocument().addDocumentListener(new MyDocumentListener(this)); addField(GT.get("Symbol"), symbolField, this); hCountField = new JSpinner(new SpinnerNumberModel()); addField(GT.get("H Count"), hCountField, this); formalChargeField = new JSpinner(new SpinnerNumberModel()); addField(GT.get("Formal Charge"), formalChargeField, this); isotopeField = new JSpinner(new SpinnerNumberModel()); addField(GT.get("Isotope number"), isotopeField, this); commentField = new JTextField(16); addField(GT.get("Comment"), commentField, this); } public void setChemObject(IChemObject object) { if (object instanceof IAtom) { source = object; // update table contents IAtom atom = (IAtom)source; symbolField.setText(atom.getSymbol()); hCountField.setValue(new Integer(atom.getImplicitHydrogenCount()==null ? 0 : atom.getImplicitHydrogenCount())); formalChargeField.setValue(new Integer(atom.getFormalCharge())); if(atom.getProperty(CDKConstants.COMMENT)!=null) commentField.setText((String)(atom.getProperty(CDKConstants.COMMENT))); try { IIsotope isotope = Isotopes.getInstance().getMajorIsotope( atom.getSymbol()); majorIsotopeNumber = isotope.getMassNumber(); isotopeField.setValue(atom.getMassNumber()-majorIsotopeNumber); } catch (Exception exception) { logger.error("Error while configuring atom"); logger.debug(exception); isotopeField.setValue(0); } } else { throw new IllegalArgumentException("Argument must be an Atom"); } } public void applyChanges() { IAtom atom = (IAtom)source; try{ if(Isotopes.getInstance().getElement(symbolField.getText())!=null){ if(atom.getImplicitHydrogenCount()==null || atom.getImplicitHydrogenCount()!=((Integer)hCountField.getValue()).intValue()) hub.setImplicitHydrogenCount(atom,((Integer)hCountField.getValue()).intValue()); if(atom.getFormalCharge()==null || atom.getFormalCharge()!=((Integer)formalChargeField.getValue()).intValue()) hub.setCharge(atom,((Integer)formalChargeField.getValue()).intValue()); if(!atom.getSymbol().equals(symbolField.getText())) hub.setSymbol(atom, symbolField.getText()); if(atom.getMassNumber()==null || atom.getMassNumber()!=majorIsotopeNumber+((Integer)isotopeField.getValue()).intValue()) hub.setMassNumber(atom,majorIsotopeNumber+((Integer)isotopeField.getValue()).intValue()); }else{ PseudoAtom pseudo = new PseudoAtom(atom); pseudo.setLabel(symbolField.getText()); pseudo.setImplicitHydrogenCount(((Integer)hCountField.getValue()).intValue()); pseudo.setFormalCharge(((Integer)formalChargeField.getValue()).intValue()); pseudo.setMassNumber(majorIsotopeNumber+((Integer)isotopeField.getValue()).intValue()); } }catch(IOException ex){ if(atom.getImplicitHydrogenCount()!=((Integer)hCountField.getValue()).intValue()) hub.setImplicitHydrogenCount(atom,((Integer)hCountField.getValue()).intValue()); if(atom.getFormalCharge()!=((Integer)formalChargeField.getValue()).intValue()) hub.setCharge(atom,((Integer)formalChargeField.getValue()).intValue()); if(!atom.getSymbol().equals(symbolField.getText())) hub.setSymbol(atom, symbolField.getText()); if(atom.getMassNumber()!=majorIsotopeNumber+((Integer)isotopeField.getValue()).intValue()) hub.setMassNumber(atom,majorIsotopeNumber+((Integer)isotopeField.getValue()).intValue()); logger.error("IOException when trying to test element symbol"); } finally { atom.setProperty(CDKConstants.COMMENT, commentField.getText()); } } class MyDocumentListener implements DocumentListener { AtomEditor atomEditor; public MyDocumentListener(AtomEditor atomEditor){ this.atomEditor = atomEditor; } public void insertUpdate(DocumentEvent e) { checkValidity(e); } public void removeUpdate(DocumentEvent e) { checkValidity(e); } private void checkValidity(DocumentEvent e){ if(((Document)e.getDocument()).getLength()==0) atomEditor.mayclose=false; else atomEditor.mayclose=true; } public void changedUpdate(DocumentEvent e) { //Plain text components do not fire these events } } }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/dialog/templates/DummyClass.java
.java
226
9
package org.openscience.jchempaint.dialog.templates; /* This class does nothing. It must be in the directory where the * subdirectories holding templates are in and is used to locate these. */ public class DummyClass { }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/action/ChangeModeAction.java
.java
4,704
103
/* * $RCSfile$ * $Author: egonw $ * $Date: 2007-01-04 17:26:00 +0000 (Thu, 04 Jan 2007) $ * $Revision: 7634 $ * * Copyright (C) 1997-2008 Stefan Kuhn * * Contact: cdk-jchempaint@lists.sourceforge.net * * 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.jchempaint.action; import java.awt.event.ActionEvent; import org.openscience.jchempaint.controller.AddRingModule; import org.openscience.jchempaint.controller.AtomAtomMappingModule; import org.openscience.jchempaint.controller.ChainModule; import org.openscience.jchempaint.controller.ControllerHub; import org.openscience.jchempaint.controller.IControllerModule; import org.openscience.jchempaint.controller.ReactionArrowModule; import org.openscience.jchempaint.controller.Rotate3DModule; import org.openscience.jchempaint.controller.RotateModule; import org.openscience.jchempaint.controller.SelectLassoModule; import org.openscience.jchempaint.controller.SelectSquareModule; /** * JChemPaint menu actions * */ public class ChangeModeAction extends JCPAction { private static final long serialVersionUID = -4056416630614934238L; public void actionPerformed(ActionEvent e) { ControllerHub hub = jcpPanel.get2DHub(); IControllerModule newActiveModule=null; if (type.equals("lasso")) { newActiveModule=new SelectLassoModule(hub); hub.getController2DModel().setDrawElement("C"); } else if (type.equals("select")) { newActiveModule=new SelectSquareModule(hub); hub.getController2DModel().setDrawElement("C"); } else if (type.equals("triangle")) { newActiveModule=new AddRingModule(hub, 3, false); hub.getController2DModel().setDrawElement("C"); } else if (type.equals("square")) { newActiveModule=new AddRingModule(hub, 4, false); hub.getController2DModel().setDrawElement("C"); } else if (type.equals("pentagon")) { newActiveModule=new AddRingModule(hub, 5, false); hub.getController2DModel().setDrawElement("C"); } else if (type.equals("hexagon")) { newActiveModule=new AddRingModule(hub, 6, false); hub.getController2DModel().setDrawElement("C"); } else if (type.equals("heptagon")) { newActiveModule=new AddRingModule(hub, 7, false); hub.getController2DModel().setDrawElement("C"); } else if (type.equals("octagon")) { newActiveModule=new AddRingModule(hub, 8, false); hub.getController2DModel().setDrawElement("C"); } else if (type.equals("benzene")) { newActiveModule=new AddRingModule(hub, 6, true); hub.getController2DModel().setDrawElement("C"); } else if (type.equals("cyclopentadiene")) { newActiveModule=new AddRingModule(hub, 5, true); hub.getController2DModel().setDrawElement("C"); } else if (type.equals("atomatommapping")) { newActiveModule=new AtomAtomMappingModule(hub); hub.getController2DModel().setDrawElement("C"); } else if (type.equals("rotate")) { newActiveModule=new RotateModule(hub); } else if (type.equals("rotate3d")) { newActiveModule=new Rotate3DModule(hub); } else if (type.equals("reactionArrow")) { newActiveModule=new ReactionArrowModule(hub); } else if (type.equals("chain")) { newActiveModule=new ChainModule(hub); } if(newActiveModule!=null){ newActiveModule.setID(type); hub.setActiveDrawModule(newActiveModule); } } }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/action/CleanupAction.java
.java
2,190
67
/* * $RCSfile$ * $Author: egonw $ * $Date: 2007-01-04 17:26:00 +0000 (Thu, 04 Jan 2007) $ * $Revision: 7634 $ * * Copyright (C) 1997-2008 Stefan Kuhn * * Contact: cdk-jchempaint@lists.sourceforge.net * * 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.jchempaint.action; import java.awt.event.ActionEvent; import org.openscience.jchempaint.controller.IChemModelRelay; import org.openscience.jchempaint.dialog.WaitDialog; /** * Triggers the invocation of the structure diagram generator * */ public class CleanupAction extends JCPAction { private static final long serialVersionUID = -1048878006430754582L; /** * Constructor for the CleanupAction object */ public CleanupAction() { super(); } /** * Re-lays out a molecule * *@param e * Description of the Parameter */ public void actionPerformed(ActionEvent e) { logger.info("Going to perform a clean up..."); WaitDialog.showDialog(); IChemModelRelay hub = jcpPanel.get2DHub(); hub.cleanup(); jcpPanel.setIsNewChemModel(true); WaitDialog.hideDialog(); hub.updateView(); } }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/action/AddHydrogenAction.java
.java
2,309
65
/* * $RCSfile$ * $Author: egonw $ * $Date: 2007-01-04 17:26:00 +0000 (Thu, 04 Jan 2007) $ * $Revision: 7634 $ * * Copyright (C) 1997-2008 Stefan Kuhn, Christoph Steinbeck * * Contact: cdk-jchempaint@lists.sourceforge.net * * 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.jchempaint.action; import java.awt.event.ActionEvent; /** * An action triggering everything related to hydrogens * */ public class AddHydrogenAction extends JCPAction { private static final long serialVersionUID = 7696756423842199080L; public void actionPerformed(ActionEvent event) { logger.debug("Trying to add hydrogen in mode: ", type); if (jcpPanel.getChemModel() != null) { if (type.equals("hydroon")) { jcpPanel.get2DHub().getRenderer().getRenderer2DModel() .setShowImplicitHydrogens(true); jcpPanel.get2DHub().getRenderer().getRenderer2DModel() .setKekuleStructure(true); } else if ( type.equals("hydrooff")) { jcpPanel.get2DHub().getRenderer().getRenderer2DModel() .setShowImplicitHydrogens(false); jcpPanel.get2DHub().getRenderer().getRenderer2DModel() .setKekuleStructure(false); } jcpPanel.get2DHub().updateView(); } } }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/action/ChangeAtomSymbolAction.java
.java
8,239
174
/* * $RCSfile$ * $Author: egonw $ * $Date: 2007-01-04 17:26:00 +0000 (Thu, 04 Jan 2007) $ * $Revision: 7634 $ * * Copyright (C) 1997-2008 Egon Willighagen, Stefan Kuhn * * Contact: cdk-jchempaint@lists.sourceforge.net * * 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.jchempaint.action; import java.awt.event.ActionEvent; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.SwingUtilities; import org.openscience.cdk.config.IsotopeFactory; import org.openscience.cdk.config.Isotopes; import org.openscience.cdk.interfaces.IAtom; import org.openscience.cdk.interfaces.IBond; import org.openscience.cdk.interfaces.IChemObject; import org.openscience.cdk.interfaces.IIsotope; import org.openscience.jchempaint.controller.AddAtomModule; import org.openscience.jchempaint.controller.AddBondDragModule; import org.openscience.jchempaint.controller.IControllerModule; import org.openscience.jchempaint.dialog.EnterElementOrGroupDialog; import org.openscience.jchempaint.dialog.EnterElementSwingModule; import org.openscience.jchempaint.dialog.PeriodicTableDialog; import org.openscience.jchempaint.GT; /** * changes the atom symbol */ public class ChangeAtomSymbolAction extends JCPAction { private static final long serialVersionUID = -8502905723573311893L; private IControllerModule newActiveModule; public void actionPerformed(ActionEvent event) { logger.debug("About to change atom type of relevant atom!"); IChemObject object = getSource(event); logger.debug("Source of call: ", object); Iterator<IAtom> atomsInRange = null; if (object == null){ //this means the main menu was used if(jcpPanel.getRenderPanel().getRenderer().getRenderer2DModel().getSelection()!=null && jcpPanel.getRenderPanel().getRenderer().getRenderer2DModel().getSelection().isFilled()) atomsInRange=jcpPanel.getRenderPanel().getRenderer().getRenderer2DModel().getSelection().elements(IAtom.class).iterator(); }else if (object instanceof IAtom) { List<IAtom> atoms = new ArrayList<IAtom>(); atoms.add((IAtom) object); atomsInRange = atoms.iterator(); } else { List<IAtom> atoms = new ArrayList<IAtom>(); atoms.add(jcpPanel.getRenderPanel().getRenderer().getRenderer2DModel().getHighlightedAtom()); atomsInRange = atoms.iterator(); } String s = event.getActionCommand(); String symbol = s.substring(s.indexOf("@") + 1); if(symbol.equals("periodictable")){ if(jcpPanel.get2DHub().getActiveDrawModule() instanceof AddBondDragModule) newActiveModule=new AddAtomModule(jcpPanel.get2DHub(), ((AddBondDragModule)jcpPanel.get2DHub().getActiveDrawModule()).getStereoForNewBond()); else if(jcpPanel.get2DHub().getActiveDrawModule() instanceof AddAtomModule) newActiveModule=new AddAtomModule(jcpPanel.get2DHub(), ((AddAtomModule)jcpPanel.get2DHub().getActiveDrawModule()).getStereoForNewBond()); else newActiveModule=new AddAtomModule(jcpPanel.get2DHub(), IBond.Display.Solid); newActiveModule.setID(symbol); jcpPanel.get2DHub().setActiveDrawModule(newActiveModule); // open PeriodicTable panel PeriodicTableDialog dialog = new PeriodicTableDialog((JFrame)SwingUtilities.getWindowAncestor(jcpPanel)); dialog.setName("periodictabledialog"); dialog.setVisible(true); symbol=dialog.getChosenSymbol(); if(symbol.isEmpty()) return; jcpPanel.get2DHub().getController2DModel().setDrawElement(symbol); jcpPanel.get2DHub().getController2DModel().setDrawIsotopeNumber(0); jcpPanel.get2DHub().getController2DModel().setDrawPseudoAtom(false); }else if(symbol.equals("enterelement")){ newActiveModule=new EnterElementSwingModule(jcpPanel.get2DHub()); newActiveModule.setID(symbol); jcpPanel.get2DHub().setActiveDrawModule(newActiveModule); if(atomsInRange!=null){ String[] funcGroupsKeys=new String[0]; symbol=EnterElementOrGroupDialog.showDialog(null,null, GT.get("Enter an element symbol:"), GT.get("Enter element"), funcGroupsKeys, "",""); if(symbol!=null && symbol.length()>0){ if(Character.isLowerCase(symbol.toCharArray()[0])) symbol=Character.toUpperCase(symbol.charAt(0))+symbol.substring(1); IsotopeFactory ifa; try { ifa = Isotopes.getInstance(); IIsotope iso=ifa.getMajorIsotope(symbol); if(iso==null){ JOptionPane.showMessageDialog(jcpPanel, GT.get("No valid element symbol entered"), GT.get("Invalid symbol"), JOptionPane.WARNING_MESSAGE); return; } } catch (IOException e) { e.printStackTrace(); return; } } } }else{ //it must be a symbol if(jcpPanel.get2DHub().getActiveDrawModule() instanceof AddBondDragModule) newActiveModule=new AddAtomModule(jcpPanel.get2DHub(), ((AddBondDragModule)jcpPanel.get2DHub().getActiveDrawModule()).getStereoForNewBond()); else if(jcpPanel.get2DHub().getActiveDrawModule() instanceof AddAtomModule) newActiveModule=new AddAtomModule(jcpPanel.get2DHub(), ((AddAtomModule)jcpPanel.get2DHub().getActiveDrawModule()).getStereoForNewBond()); else newActiveModule=new AddAtomModule(jcpPanel.get2DHub(), IBond.Display.Solid); jcpPanel.get2DHub().getController2DModel().setDrawPseudoAtom(false); newActiveModule.setID(symbol); jcpPanel.get2DHub().getController2DModel().setDrawElement(symbol); jcpPanel.get2DHub().getController2DModel().setDrawIsotopeNumber(0); } if(symbol!=null && symbol.length()>0){ jcpPanel.get2DHub().setActiveDrawModule(newActiveModule); if(atomsInRange!=null){ while(atomsInRange.hasNext()){ IAtom atom = atomsInRange.next(); jcpPanel.get2DHub().setSymbol(atom,symbol); //TODO still needed? should this go in hub? // configure the atom, so that the atomic number matches the symbol try { Isotopes.getInstance().configure(atom); } catch (Exception exception) { logger.error("Error while configuring atom"); logger.debug(exception); } } } jcpPanel.get2DHub().updateView(); } } }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/action/ZoomAction.java
.java
2,457
67
/* * $RCSfile$ * $Author: shk3 $ * $Date: 2008-10-02 16:45:12 +0100 (Thu, 02 Oct 2008) $ * $Revision: 12535 $ * * Copyright (C) 2003-2007 The JChemPaint project * * Contact: jchempaint-devel@lists.sourceforge.net * * 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.jchempaint.action; import java.awt.event.ActionEvent; import org.openscience.jchempaint.renderer.JChemPaintRendererModel; /** * @cdk.module jchempaint * @author steinbeck */ public class ZoomAction extends JCPAction { private static final long serialVersionUID = -2459332630141921895L; public static boolean zoomDone=false; public void actionPerformed(ActionEvent e) { JChemPaintRendererModel rendererModel = jcpPanel.getRenderPanel().getRenderer().getRenderer2DModel(); double zoom = rendererModel.getZoomFactor(); logger.debug("Zooming in/out in mode: ", type); if (type.equals("in") && zoom < 10) { rendererModel.setZoomFactor(zoom * 1.2); } else if (type.equals("out") && zoom > .1) { rendererModel.setZoomFactor(zoom / 1.2); } else if (type.equals("original")) { rendererModel.setZoomFactor(1); } else { logger.error("Unkown zoom command: " + type); } zoomDone=true; jcpPanel.get2DHub().updateView(); jcpPanel.getRenderPanel().update(jcpPanel.getRenderPanel().getGraphics()); } }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/action/SaveAction.java
.java
3,561
112
/* * $RCSfile$ * $Author: egonw $ * $Date: 2007-01-04 17:26:00 +0000 (Thu, 04 Jan 2007) $ * $Revision: 7634 $ * * Copyright (C) 1997-2008 Stefan Kuhn * * Contact: cdk-jchempaint@lists.sourceforge.net * * 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.jchempaint.action; import java.awt.event.ActionEvent; import java.io.File; import javax.swing.JOptionPane; import org.openscience.jchempaint.AbstractJChemPaintPanel; import org.openscience.jchempaint.io.JCPFileFilter; import org.openscience.jchempaint.io.JCPSaveFileFilter; /** * Opens a save dialog * */ public class SaveAction extends SaveAsAction { private static final long serialVersionUID = -6748046051686998776L; public SaveAction(){ super(); } /** * Constructor for the SaveAction object * *@param jcpPanel Description of the Parameter *@param isPopupAction Description of the Parameter */ public SaveAction(AbstractJChemPaintPanel jcpPanel, boolean isPopupAction) { super(jcpPanel, isPopupAction); } /** * Saves a file or calls save as, when current content was not yet saved. * *@param event Description of the Parameter */ public void actionPerformed(ActionEvent event) { if(jcpPanel.isAlreadyAFile()==null){ SaveAsAction saveasaction = new SaveAsAction(jcpPanel,false); saveasaction.actionPerformed(event); this.wasCancelled = saveasaction.wasCancelled; }else{ try{ org.openscience.cdk.interfaces.IChemModel model=jcpPanel.getChemModel(); File outFile=jcpPanel.isAlreadyAFile(); type = JCPFileFilter.getExtension(outFile); if (type.equals(JCPSaveFileFilter.mol)) { saveAsMol(model, outFile); } else if (type.equals(JCPSaveFileFilter.cml)) { saveAsCML2(model, outFile); } else if (type.equals(JCPSaveFileFilter.smiles)) { saveAsSMILES(model, outFile); } else if (type.equals(JCPSaveFileFilter.cdk)) { saveAsCDKSourceCode(model, outFile); } else { String error = "Cannot save file in this format: " + type; logger.error(error); JOptionPane.showMessageDialog(jcpPanel, error); return; } jcpPanel.setModified(false); }catch(Exception ex){ String error = "Error while writing file: " + ex.getMessage(); logger.error(error); logger.debug(ex); JOptionPane.showMessageDialog(jcpPanel, error); } } } }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/action/UndoAction.java
.java
2,188
66
/* * $RCSfile$ * $Author: egonw $ * $Date: 2007-01-04 17:26:00 +0000 (Thu, 04 Jan 2007) $ * $Revision: 7634 $ * * Copyright (C) 1997-2008 Stefan Kuhn * * Contact: cdk-jchempaint@lists.sourceforge.net * * 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.jchempaint.action; import java.awt.event.ActionEvent; import org.openscience.jchempaint.renderer.selection.LogicalSelection; /** * An action for making things undone :-) * Beneficial in many situations in your life. * * @cdk.bug 1524599 */ public class UndoAction extends JCPAction { private static final long serialVersionUID = 8552968393233060836L; /** * Undoes the last action. * *@param e Description of the Parameter */ public void actionPerformed(ActionEvent e) { logger.debug("Undo triggered"); if (jcpPanel.getRenderPanel().getUndoManager().canUndo()) { jcpPanel.getRenderPanel().getUndoManager().undo(); } jcpPanel.getRenderPanel().getRenderer().getRenderer2DModel() .setSelection(new LogicalSelection(LogicalSelection.Type.NONE)); jcpPanel.updateUndoRedoControls(); jcpPanel.get2DHub().updateView(); } }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/action/CloseAction.java
.java
1,887
54
/* * $RCSfile$ * $Author: egonw $ * $Date: 2007-01-04 17:26:00 +0000 (Thu, 04 Jan 2007) $ * $Revision: 7634 $ * * Copyright (C) 1997-2008 Stefan Kuhn * * Contact: cdk-jchempaint@lists.sourceforge.net * * 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.jchempaint.action; import java.awt.event.ActionEvent; import java.awt.event.WindowEvent; import java.awt.event.WindowListener; import javax.swing.JFrame; /** * Triggers an exit of the current frame * */ public class CloseAction extends JCPAction { private static final long serialVersionUID = 5877928616913182728L; /** * Closes the current frame */ public void actionPerformed(ActionEvent e) { JFrame jFrame = (JFrame) jcpPanel.getTopLevelContainer(); WindowListener[] wls = jFrame.getWindowListeners(); wls[0].windowClosing(new WindowEvent(jFrame, WindowEvent.WINDOW_CLOSING)); } }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/action/ChangeBondAction.java
.java
7,756
192
/* * $RCSfile$ * $Author: egonw $ * $Date: 2007-01-04 17:26:00 +0000 (Thu, 04 Jan 2007) $ * $Revision: 7634 $ * * Copyright (C) 1997-2008 Egon Willighagen, Stefan Kuhn * Some portions Copyright (C) 2009 Konstantin Tokarev * * Contact: cdk-jchempaint@lists.sourceforge.net * * 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.jchempaint.action; import java.awt.event.ActionEvent; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import org.openscience.cdk.interfaces.IAtom; import org.openscience.cdk.interfaces.IBond; import org.openscience.cdk.interfaces.IChemObject; import org.openscience.jchempaint.controller.AddBondDragModule; /** * changes the atom symbol */ public class ChangeBondAction extends JCPAction { private static final long serialVersionUID = -8502905723573311893L; public void actionPerformed(ActionEvent event) { String s = event.getActionCommand(); String type = s.substring(s.indexOf("@") + 1); //first switch mode AddBondDragModule newActiveModule = new AddBondDragModule(jcpPanel.get2DHub(), IBond.Display.Solid, true); switch (type) { case "down_bond": newActiveModule = new AddBondDragModule(jcpPanel.get2DHub(), IBond.Display.Down, true); break; case "up_bond": newActiveModule = new AddBondDragModule(jcpPanel.get2DHub(), IBond.Display.Up, true); break; case "hollow_wedge_bond": newActiveModule = new AddBondDragModule(jcpPanel.get2DHub(), IBond.Display.HollowWedgeBegin, true); break; case "hash_bond": newActiveModule = new AddBondDragModule(jcpPanel.get2DHub(), IBond.Display.Hash, true); break; case "bold_bond": newActiveModule = new AddBondDragModule(jcpPanel.get2DHub(), IBond.Display.Bold, true); break; case "dash_bond": newActiveModule = new AddBondDragModule(jcpPanel.get2DHub(), IBond.Display.Dash, true); break; case "coordination_bond": newActiveModule = new AddBondDragModule(jcpPanel.get2DHub(), IBond.Display.ArrowEnd, true); break; case "undefined_bond": newActiveModule = new AddBondDragModule(jcpPanel.get2DHub(), IBond.Display.Wavy, true); break; case "undefined_stereo_bond": newActiveModule = new AddBondDragModule(jcpPanel.get2DHub(), IBond.Order.DOUBLE, IBond.Display.Crossed, true, "undefined_stereo_bond"); break; case "bondTool": newActiveModule = new AddBondDragModule(jcpPanel.get2DHub(), IBond.Order.SINGLE, true); break; case "double_bondTool": newActiveModule = new AddBondDragModule(jcpPanel.get2DHub(), IBond.Order.DOUBLE, true); break; case "triple_bondTool": newActiveModule = new AddBondDragModule(jcpPanel.get2DHub(), IBond.Order.TRIPLE, true); break; } if (newActiveModule != null) { // null means that menu was used => don't change module newActiveModule.setID(type); jcpPanel.get2DHub().setActiveDrawModule(newActiveModule); } // xxxTool -> xxx int l = type.length(); if (type.substring(l - 4, l).equals("Tool")) type = type.substring(0, l - 4); //then handle selection or highlight if there is one IChemObject object = getSource(event); Collection<IBond> bondsInRange = null; if (object == null) { //this means the main menu or toolbar was used if (jcpPanel.getRenderPanel().getRenderer().getRenderer2DModel().getSelection() != null && jcpPanel.getRenderPanel().getRenderer().getRenderer2DModel().getSelection().isFilled()) bondsInRange = jcpPanel.getRenderPanel().getRenderer().getRenderer2DModel().getSelection().elements(IBond.class); } else if (object instanceof IBond) { List<IBond> bonds = new ArrayList<IBond>(); bonds.add((IBond) object); bondsInRange = bonds; } else { List<IBond> bonds = new ArrayList<IBond>(); bonds.add(jcpPanel.getRenderPanel().getRenderer().getRenderer2DModel().getHighlightedBond()); bondsInRange = bonds; } if (bondsInRange == null) return; IBond.Display display = null; IBond.Order order = null; switch (type) { case "bond": display = IBond.Display.Solid; order = IBond.Order.SINGLE; break; case "double_bond": display = IBond.Display.Solid; order = IBond.Order.DOUBLE; break; case "triple_bond": display = IBond.Display.Solid; order = IBond.Order.TRIPLE; break; case "quad_bond": display = IBond.Display.Solid; order = IBond.Order.QUADRUPLE; break; case "down_bond": display = IBond.Display.Down; order = IBond.Order.SINGLE; break; case "up_bond": display = IBond.Display.Up; order = IBond.Order.SINGLE; break; case "hollow_wedge_bond": display = IBond.Display.HollowWedgeBegin; order = IBond.Order.SINGLE; break; case "hash_bond": display = IBond.Display.Hash; order = IBond.Order.SINGLE; break; case "bold_bond": display = IBond.Display.Bold; order = IBond.Order.SINGLE; break; case "dash_bond": display = IBond.Display.Dash; order = IBond.Order.SINGLE; break; case "coordination_bond": display = IBond.Display.ArrowEnd; order = IBond.Order.UNSET; break; case "undefined_bond": display = IBond.Display.Wavy; order = IBond.Order.SINGLE; break; case "undefined_stereo_bond": display = IBond.Display.Crossed; order = IBond.Order.DOUBLE; break; } jcpPanel.get2DHub().changeBonds(bondsInRange, order, display); jcpPanel.get2DHub().updateView(); } }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/action/CreateInChIAction.java
.java
3,849
99
/* * Copyright (C) 1997-2009 Christoph Steinbeck, Stefan Kuhn, Mark Rijnbeek * * Contact: cdk-jchempaint@lists.sourceforge.net * * 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.jchempaint.action; import java.awt.event.ActionEvent; import javax.swing.JFrame; import org.openscience.cdk.ChemModel; import org.openscience.cdk.interfaces.IAtomContainer; import org.openscience.jchempaint.GT; import org.openscience.jchempaint.dialog.TextViewDialog; import org.openscience.jchempaint.dialog.WaitDialog; import org.openscience.jchempaint.inchi.InChI; import org.openscience.jchempaint.inchi.InChITool; /** * Creates InChI(s) from the current model, to be displayed to user * in pop out window. * * @cdk.module jchempaint * @author Mark Rijnbeek */ public class CreateInChIAction extends JCPAction { private static final long serialVersionUID = -4886982931009753347L; TextViewDialog dialog = null; JFrame frame = null; public void actionPerformed(ActionEvent e) { logger.debug("Trying to create InChI: ", type); WaitDialog.showDialog(); if (dialog == null) { dialog = new TextViewDialog(frame, "InChI", null, false, 40, 2); } ChemModel model = (ChemModel) jcpPanel.getChemModel(); if (model.getReactionSet() != null && model.getReactionSet().getReactionCount() > 0) { dialog.setMessage( GT.get("Problem"), GT.get("You have reactions in JCP. Reactions cannot be shown as InChI!")); } else { StringBuffer dialogText = new StringBuffer(); int i = 0; String eol = System.getProperty("line.separator"); for (IAtomContainer container : model.getMoleculeSet() .atomContainers()) { if (model.getMoleculeSet().getAtomContainerCount() > 1) { dialogText.append(GT.get("Structure") + " #" + (i + 1) + eol); } try { InChI inchi = InChITool.generateInchi(container); dialogText.append(inchi.getInChI() + eol); dialogText.append(inchi.getAuxInfo()+ eol); dialogText.append(inchi.getKey() + eol); } catch (Exception cdke) { dialogText.append(GT.get("InChI generation failed") + ": " + cdke.getMessage() + eol + eol); } i++; } dialog.setMessage(GT.get("InChI generation") + ":", dialogText .toString()); } WaitDialog.hideDialog(); dialog.setVisible(true); } }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/action/RGroupAction.java
.java
25,711
561
/* * Copyright (C) 2010 Mark Rijnbeek * * Contact: cdk-jchempaint@lists.sourceforge.net * * 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.jchempaint.action; import org.openscience.cdk.CDKConstants; import org.openscience.cdk.DefaultChemObjectBuilder; import org.openscience.cdk.exception.CDKException; import org.openscience.cdk.interfaces.IAtom; import org.openscience.cdk.interfaces.IAtomContainer; import org.openscience.cdk.interfaces.IAtomContainerSet; import org.openscience.cdk.interfaces.IBond; import org.openscience.cdk.interfaces.IChemObject; import org.openscience.cdk.interfaces.IChemObjectBuilder; import org.openscience.cdk.interfaces.IPseudoAtom; import org.openscience.cdk.io.SDFWriter; import org.openscience.cdk.isomorphism.matchers.IRGroup; import org.openscience.cdk.isomorphism.matchers.IRGroupList; import org.openscience.cdk.isomorphism.matchers.IRGroupQuery; import org.openscience.cdk.isomorphism.matchers.RGroup; import org.openscience.cdk.isomorphism.matchers.RGroupList; import org.openscience.cdk.isomorphism.matchers.RGroupQuery; import org.openscience.cdk.renderer.selection.IChemObjectSelection; import org.openscience.cdk.smiles.SmiFlavor; import org.openscience.cdk.smiles.SmilesGenerator; import org.openscience.cdk.tools.manipulator.ChemModelManipulator; import org.openscience.jchempaint.GT; import org.openscience.jchempaint.controller.IChemModelRelay; import org.openscience.jchempaint.controller.undoredo.IUndoRedoable; import org.openscience.jchempaint.dialog.editor.ChemObjectEditor; import org.openscience.jchempaint.dialog.editor.ChemObjectPropertyDialog; import org.openscience.jchempaint.dialog.editor.RGroupEditor; import org.openscience.jchempaint.io.JCPFileView; import org.openscience.jchempaint.rgroups.RGroupHandler; import javax.swing.JDialog; import javax.swing.JFileChooser; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JTextPane; import javax.swing.SwingUtilities; import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.io.File; import java.io.FileWriter; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; /** * Deals with user actions on creating/editing R-groups. * */ public class RGroupAction extends JCPAction { private static final long serialVersionUID = 7387274752039316786L; /** * Handles the user action, such as defining a root structure, substitutes, * attachment atoms and bonds. * * @see org.openscience.jchempaint.action.JCPAction#actionPerformed(java.awt.event.ActionEvent) */ public void actionPerformed(ActionEvent event) { // System.out.println("action iz "+type); IChemObject eventSource = getSource(event); IChemObjectSelection selection = jcpPanel.getRenderPanel().getRenderer().getRenderer2DModel().getSelection(); if (selection == null || !selection.isFilled() && (type.equals("setRoot") || type.equals("setSubstitute"))) { JOptionPane.showMessageDialog(jcpPanel, GT.get("You have not selected any atoms or bonds.")); return; } IChemModelRelay hub = jcpPanel.get2DHub(); boolean isNewRgroup = false; RGroupHandler rGroupHandler = null; Map<IAtom, IAtomContainer> existingAtomDistr = new HashMap<IAtom, IAtomContainer>(); Map<IBond, IAtomContainer> existingBondDistr = new HashMap<IBond, IAtomContainer>(); IAtomContainer existingRoot = null; Map<IAtom, Map<Integer, IBond>> oldRootApo = null; Map<IAtom, Map<Integer, IBond>> newRootApo = null; Map<RGroup, Map<Integer, IAtom>> existingRGroupApo = null; Map<Integer, RGroupList> existingRgroupLists = null; IRGroupQuery rgrpQuery = null; IAtomContainer molecule = null; /* User action: generate possible configurations for the R-group */ if (type.equals("rgpGenerate")) { if ((jcpPanel.get2DHub().getRGroupHandler() == null)) { JOptionPane.showMessageDialog(jcpPanel, GT.get("Please define an R-group (root and substituents) first.")); return; } try { JFileChooser chooser = new JFileChooser(); chooser.setCurrentDirectory(jcpPanel.getCurrentWorkDirectory()); chooser.setFileView(new JCPFileView()); chooser.showSaveDialog(jcpPanel); File outFile = chooser.getSelectedFile(); List<IAtomContainer> molecules = jcpPanel.get2DHub().getRGroupHandler().getrGroupQuery().getAllConfigurations(); if (molecules.size() > 0) { IAtomContainerSet molSet = molecules.get(0).getBuilder().newInstance(IAtomContainerSet.class); for (IAtomContainer mol : molecules) { molSet.addAtomContainer(mol); } SDFWriter sdfWriter = new SDFWriter(new FileWriter(outFile)); sdfWriter.write(molSet); sdfWriter.close(); } } catch (Exception e) { JOptionPane.showMessageDialog(jcpPanel, GT.get("There was an error generating the configurations {0}", e.getMessage())); return; } } else if (type.equals("rgpGenerateSmi")) { if ((jcpPanel.get2DHub().getRGroupHandler() == null)) { JOptionPane.showMessageDialog(jcpPanel, GT.get("Please define an R-group (root and substituents) first.")); return; } try { StringBuilder sb = new StringBuilder(); SmilesGenerator smigen = new SmilesGenerator(SmiFlavor.Default); List<IAtomContainer> molecules = jcpPanel.get2DHub().getRGroupHandler().getrGroupQuery().getAllConfigurations(); for (IAtomContainer mol : molecules) { sb.append(smigen.create(mol)) .append('\n'); } JDialog dialog = new JDialog(SwingUtilities.getWindowAncestor(jcpPanel)); dialog.setSize(512, 512); JTextPane pane = new JTextPane(); pane.setText(sb.toString()); pane.setEditable(false); dialog.add(new JLabel("Possible Molecule Configurations"), BorderLayout.NORTH); dialog.add(pane, BorderLayout.CENTER); dialog.setVisible(true); } catch (Exception e) { JOptionPane.showMessageDialog(jcpPanel, GT.get("There was an error generating the configurations {0}", e.getMessage())); return; } } /* User action: advanced R-group logic */ else if (type.equals("rgpAdvanced")) { if ((jcpPanel.get2DHub().getRGroupHandler() == null)) { JOptionPane.showMessageDialog(jcpPanel, GT.get("Please define an R-group (root and substituent) first.")); return; } jcpPanel.get2DHub().getRGroupHandler().cleanUpRGroup(jcpPanel.get2DHub().getChemModel().getMoleculeSet()); ChemObjectEditor editor = new RGroupEditor(hub); editor.setChemObject(hub.getRGroupHandler().getrGroupQuery()); ChemObjectPropertyDialog frame = new ChemObjectPropertyDialog(JOptionPane.getFrameForComponent(editor), jcpPanel.get2DHub(), editor); frame.pack(); frame.setVisible(true); jcpPanel.get2DHub().updateView(); } //FOLLOWING actions involve undo/redo else { /* User action: generate possible configurations for the R-group */ if (type.equals("clearRgroup")) { if ((jcpPanel.get2DHub().getRGroupHandler() == null)) { JOptionPane.showMessageDialog(jcpPanel, GT.get("There is no R-group defined")); return; } rGroupHandler = hub.getRGroupHandler(); hub.unsetRGroupHandler(); jcpPanel.get2DHub().updateView(); } /* User action : certain bond in the root needs to become attachment bond 1 or 2 */ else if (type.startsWith("setBondApoAction")) { rGroupHandler = hub.getRGroupHandler(); IBond apoBond = (IBond) eventSource; Map<Integer, IBond> apoBonds = null; //Undo/redo business______ IAtom pseudo = null; if (apoBond.getAtom(0) instanceof IPseudoAtom) pseudo = apoBond.getAtom(0); else pseudo = apoBond.getAtom(1); Map<IBond, Integer> bondToApo = new HashMap<>(); Map<Integer, IBond> apoToBond = new HashMap<>(); oldRootApo = rGroupHandler.getrGroupQuery().getRootAttachmentPoints(); newRootApo = new HashMap<>(); if (oldRootApo != null) newRootApo = new HashMap<>(oldRootApo); if (oldRootApo.get(pseudo) != null) { apoBonds = oldRootApo.get(pseudo); for (Map.Entry<Integer, IBond> e : apoBonds.entrySet()) { apoToBond.put(e.getKey(), e.getValue()); bondToApo.put(e.getValue(), e.getKey()); } } //Set the new Root APO newRootApo.put(pseudo, apoToBond); if (newRootApo.get(pseudo) == null) { apoBonds = new HashMap<Integer, IBond>(); newRootApo.put(pseudo, apoBonds); } else apoBonds = newRootApo.get(pseudo); Integer oldApoId = bondToApo.get(apoBond); if (type.endsWith("1")) { if (oldApoId != null && apoBonds.containsKey(1)) apoBonds.put(oldApoId, apoBonds.get(1)); apoBonds.put(1, apoBond); } else if (type.endsWith("2")) { if (oldApoId != null && apoBonds.containsKey(2)) apoBonds.put(oldApoId, apoBonds.get(2)); apoBonds.put(2, apoBond); } rGroupHandler.getrGroupQuery().setRootAttachmentPoints(newRootApo); } /* User action: certain atom+bond selection is to be the root structure. */ else if (type.equals("setRoot")) { IAtomContainer atc = selection.getConnectedAtomContainer(); if (!isProperSelection(atc)) { JOptionPane.showMessageDialog(jcpPanel, GT.get("Please do not make a fragmented selection.")); return; } molecule = createMolecule(atc, existingAtomDistr, existingBondDistr); hub.getChemModel().getMoleculeSet().addAtomContainer(molecule); if (hub.getRGroupHandler() == null) { isNewRgroup = true; rgrpQuery = newRGroupQuery(molecule.getBuilder()); rGroupHandler = new RGroupHandler(rgrpQuery, this.jcpPanel); hub.setRGroupHandler(rGroupHandler); } else { rGroupHandler = hub.getRGroupHandler(); rgrpQuery = hub.getRGroupHandler().getrGroupQuery(); if (rgrpQuery.getRootStructure() != null) { existingRoot = rgrpQuery.getRootStructure(); rgrpQuery.getRootStructure().removeProperty(CDKConstants.TITLE); } } molecule.setProperty(CDKConstants.TITLE, RGroup.ROOT_LABEL); rgrpQuery.setRootStructure(molecule); //Remove old root apo's oldRootApo = rgrpQuery.getRootAttachmentPoints(); rgrpQuery.setRootAttachmentPoints(null); //Define new root apo's Map<IAtom, Map<Integer, IBond>> apoBonds = new HashMap<IAtom, Map<Integer, IBond>>(); for (IAtom atom : molecule.atoms()) { if (atom instanceof IPseudoAtom) { IPseudoAtom pseudo = (IPseudoAtom) atom; if (pseudo.getLabel() != null && RGroupQuery.isValidRgroupQueryLabel(pseudo.getLabel())) { chooseRootAttachmentBonds(pseudo, molecule, apoBonds); } } } rgrpQuery.setRootAttachmentPoints(apoBonds); } /* User action: certain atom+bond selection is to be a substituent. */ else if (type.equals("setSubstitute")) { if (hub.getRGroupHandler() == null || hub.getRGroupHandler().getrGroupQuery() == null || hub.getRGroupHandler().getrGroupQuery().getRootStructure() == null) { JOptionPane.showMessageDialog(jcpPanel, GT.get("Please define a root structure first.")); return; } IAtomContainer atc = selection.getConnectedAtomContainer(); if (!isProperSelection(atc)) { JOptionPane.showMessageDialog(jcpPanel, GT.get("Please do not make a fragmented selection.")); return; } // Check - are there any R-groups -> collect them so that user input can be validated Map<Integer, Integer> validRnumChoices = new HashMap<Integer, Integer>(); for (IAtom atom : hub.getRGroupHandler().getrGroupQuery().getRootStructure().atoms()) { if (atom instanceof IPseudoAtom) { IPseudoAtom pseudo = (IPseudoAtom) atom; if (pseudo.getLabel() != null && RGroupQuery.isValidRgroupQueryLabel(pseudo.getLabel())) { int bondCnt = 0; int rNum = new Integer(pseudo.getLabel().substring(1)); for (IBond b : hub.getRGroupHandler().getrGroupQuery().getRootStructure().bonds()) if (b.contains(atom)) bondCnt++; if ((!validRnumChoices.containsKey(rNum)) || validRnumChoices.containsKey(rNum) && validRnumChoices.get(rNum) < bondCnt) validRnumChoices.put(rNum, bondCnt); } } } // Here we test: the user wants to define a substitute, but are there any R1..R32 groups to begin with? if (validRnumChoices.size() == 0) { JOptionPane.showMessageDialog(jcpPanel, GT.get("There are no numbered R-atoms in the root structure to refer to.")); return; } //Now get user input to determine which R# atom to hook up with the substituent boolean inputOkay = false; String userInput = null; Integer rNum = 0; do { userInput = JOptionPane.showInputDialog(GT.get("Enter an R-group number "), validRnumChoices.get(0)); if (userInput == null) return; try { rNum = new Integer(userInput); if (!validRnumChoices.containsKey(rNum)) JOptionPane.showMessageDialog(null, GT.get("The number you entered has no corresponding R-group in the root.")); else inputOkay = true; } catch (NumberFormatException e) { JOptionPane.showMessageDialog(null, GT.get("This is not a valid R-group label.\nPlease label in range R1 .. R32")); } } while (!inputOkay); rGroupHandler = hub.getRGroupHandler(); rgrpQuery = hub.getRGroupHandler().getrGroupQuery(); if (rgrpQuery.getRGroupDefinitions() == null) { rgrpQuery.setRGroupDefinitions(new HashMap<Integer, IRGroupList>()); } if (rgrpQuery.getRGroupDefinitions().get(rNum) == null) { RGroupList rList = new RGroupList(rNum); rList.setRGroups(new ArrayList<IRGroup>()); rgrpQuery.getRGroupDefinitions().put(rNum, rList); } molecule = createMolecule(atc, existingAtomDistr, existingBondDistr); existingRgroupLists = new HashMap<Integer, RGroupList>(); // Now see if the user's choice for a substituent has overlaps with already defined existing // substitutes. If so, these existing ones get thrown out (we can't have multiple substituents // defined for the same atoms. for (Iterator<Integer> itr = rgrpQuery.getRGroupDefinitions().keySet().iterator(); itr.hasNext(); ) { int rgrpNum = itr.next(); RGroupList rgrpList = (RGroupList) rgrpQuery.getRGroupDefinitions().get(rgrpNum); if (rgrpList != null) { existingRgroupLists.put(rgrpNum, makeClone(rgrpList)); List<IRGroup> cleanList = new ArrayList<IRGroup>(); for (int j = 0; j < rgrpList.getRGroups().size(); j++) { IRGroup subst = rgrpList.getRGroups().get(j); boolean remove = false; removeCheck: for (IAtom atom : molecule.atoms()) { if (subst.getGroup().contains(atom)) { remove = true; break removeCheck; } } if (!remove) { cleanList.add(subst); } } rgrpList.setRGroups(cleanList); } } hub.getChemModel().getMoleculeSet().addAtomContainer(molecule); molecule.setProperty(CDKConstants.TITLE, RGroup.makeLabel(rNum)); RGroup rgrp = new RGroup(); rgrp.setGroup(molecule); rgrpQuery.getRGroupDefinitions().get(rNum).getRGroups().add(rgrp); } if (hub.getUndoRedoFactory() != null && jcpPanel.get2DHub().getUndoRedoHandler() != null) { IUndoRedoable undoredo = jcpPanel.get2DHub().getUndoRedoFactory().getRGroupEdit (type, isNewRgroup, hub, rGroupHandler, existingAtomDistr, existingBondDistr, existingRoot, oldRootApo, newRootApo, existingRGroupApo, existingRgroupLists, molecule); jcpPanel.get2DHub().getUndoRedoHandler().postEdit(undoredo); } jcpPanel.get2DHub().updateView(); } } /** * Initializes an empty RGroupQuery. * * @return a new empty RGroupQuery */ private IRGroupQuery newRGroupQuery(IChemObjectBuilder builder) { IRGroupQuery rgrpQuery = new RGroupQuery(DefaultChemObjectBuilder.getInstance()); rgrpQuery.setRootStructure(builder.newInstance(IAtomContainer.class)); rgrpQuery .setRootAttachmentPoints(new HashMap<IAtom, Map<Integer, IBond>>()); rgrpQuery.setRGroupDefinitions(new HashMap<Integer, IRGroupList>()); return rgrpQuery; } /** * Chooses (picks) one or more attachment bonds for a (new) R# atom that is * a root member. * * @param rAtom * @param root * @param rootAttachmentPoints */ private void chooseRootAttachmentBonds(IAtom rAtom, IAtomContainer root, Map<IAtom, Map<Integer, IBond>> rootAttachmentPoints) { int apoIdx = 1; Map<Integer, IBond> apoBonds = new HashMap<Integer, IBond>(); Iterator<IBond> bonds = root.bonds().iterator(); // Pick up to two apo bonds randomly while (bonds.hasNext() && apoIdx <= 2) { IBond bond = bonds.next(); if (bond.contains(rAtom)) { apoBonds.put((apoIdx), bond); apoIdx++; } } rootAttachmentPoints.put(rAtom, apoBonds); } /** * Determines if a user has made a proper selection for R-Group * manipulation. Proper means: make a selection that includes all * atoms/bonds that are bound together in a structure, not leaving any * orphans dangling. * * @param atc * @return */ private boolean isProperSelection(IAtomContainer atc) { boolean properSelection = true; completeSelection: for (IAtom atom : atc.atoms()) { IAtomContainer modelAtc = ChemModelManipulator .getRelevantAtomContainer(jcpPanel.getChemModel(), atom); List<IAtom> connectedAtoms = new ArrayList<IAtom>(); findConnectedAtoms(atom, modelAtc, connectedAtoms); for (IAtom modelAt : connectedAtoms) { if (!atc.contains(modelAt)) { properSelection = false; break completeSelection; } } } return properSelection; } /** * Starting from start point atom, finds all other atoms connected to it by * traversing a graph. Used to determine a proper selection. * * @param atom * @param atc * @param result */ private void findConnectedAtoms(IAtom atom, IAtomContainer atc, List<IAtom> result) { result.add(atom); for (IBond bond : atc.bonds()) { if (bond.contains(atom)) { IAtom other = bond.getOther(atom); if (!result.contains(other)) { findConnectedAtoms(other, atc, result); } } } } /** * Creates a new molecule based on a user selection, and removes the * selected atoms/bonds from the atom container where they are currently in. */ private IAtomContainer createMolecule(IAtomContainer atc, Map<IAtom, IAtomContainer> existingAtomDistr, Map<IBond, IAtomContainer> existingBondDistr) { for (IBond bond : atc.bonds()) { IAtomContainer original = ChemModelManipulator .getRelevantAtomContainer(jcpPanel.getChemModel(), bond); existingBondDistr.put(bond, original); original.removeBond(bond); } for (IAtom atom : atc.atoms()) { IAtomContainer original = ChemModelManipulator .getRelevantAtomContainer(jcpPanel.getChemModel(), atom); existingAtomDistr.put(atom, original); original.removeAtom(atom); } IAtomContainer molecule = atc.getBuilder().newInstance(IAtomContainer.class); molecule.add(atc); return molecule; } /** * Clones an RGroupList * * @param original * @return */ private static RGroupList makeClone(IRGroupList original) { // Ensure we are working with a valid RGroupList if (!(original instanceof RGroupList)) { throw new IllegalArgumentException("Expected an instance of RGroupList"); } RGroupList clone = new RGroupList(original.getRGroupNumber()); try { clone.setOccurrence(original.getOccurrence()); clone.setRequiredRGroupNumber(original.getRequiredRGroupNumber()); clone.setRestH(original.isRestH()); // Clone the RGroups List<IRGroup> rgpList = new ArrayList<>(); for (IRGroup r : original.getRGroups()) { if (r instanceof RGroup) { rgpList.add((RGroup) r); // Safely cast to RGroup } else { throw new IllegalStateException("Encountered non-RGroup instance in RGroups list"); } } clone.setRGroups(rgpList); // Set the cloned list } catch (CDKException e) { e.printStackTrace(); } return clone; } }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/action/CreateReactionAction.java
.java
6,560
206
/* * $RCSfile$ * $Author: egonw $ * $Date: 2007-01-04 17:26:00 +0000 (Thu, 04 Jan 2007) $ * $Revision: 7634 $ * * Copyright (C) 1997-2008 Christoph Steinbeck, Stefan Kuhn * * Contact: cdk-jchempaint@lists.sourceforge.net * * 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.jchempaint.action; import java.awt.event.ActionEvent; import javax.swing.JOptionPane; import org.openscience.cdk.interfaces.IAtom; import org.openscience.cdk.interfaces.IAtomContainer; import org.openscience.cdk.interfaces.IBond; import org.openscience.cdk.interfaces.IChemModel; import org.openscience.cdk.interfaces.IChemObject; import org.openscience.cdk.interfaces.IReactionSet; import org.openscience.cdk.tools.manipulator.ChemModelManipulator; import org.openscience.jchempaint.GT; import org.openscience.jchempaint.controller.ControllerHub; import org.openscience.jchempaint.controller.IChemModelRelay; import org.openscience.jchempaint.controller.ReactionHub; /** * Creates a reaction object * */ public class CreateReactionAction extends JCPAction { private static final long serialVersionUID = -7625810885316702776L; public void actionPerformed(ActionEvent event) { IChemObject object = getSource(event); logger.debug("CreateReaction action"); IChemModel model = jcpPanel.getChemModel(); IReactionSet reactionSet = model.getReactionSet(); if (reactionSet == null) { reactionSet = model.getBuilder().newInstance(IReactionSet.class); } IAtomContainer container = null; if (object instanceof IAtom) { container = ChemModelManipulator.getRelevantAtomContainer(model, (IAtom) object); } else if(object instanceof IBond) { container = ChemModelManipulator.getRelevantAtomContainer(model, (IBond) object); } else { logger.error("Cannot add to reaction object of type: " + object.getClass().getName()); } if (container == null) { logger.error("Cannot find container to add object to!"); } else { IChemModelRelay hub = jcpPanel.get2DHub(); IAtomContainer newContainer; try { newContainer = (IAtomContainer) container.clone(); if(container.getID()!=null) newContainer.setID(container.getID()); else newContainer.setID("ac"+System.currentTimeMillis()); } catch (CloneNotSupportedException e) { logger.error("Could not clone IAtomContainer: ", e.getMessage()); logger.debug(e); return; } logger.debug("type: ", type); if ("addReactantToNew".equals(type)) { ReactionHub.makeReactantInNewReaction((ControllerHub)hub, newContainer, container); //TODO this.jcpPanel.atomAtomMappingButton.setEnabled(true); } else if ("addReactantToExisting".equals(type)) { if (reactionSet.getReactionCount() == 0) { logger.warn("Cannot add to reaction if no one exists"); JOptionPane.showMessageDialog(jcpPanel, GT.get("No reaction existing. Cannot add therefore to something!"), GT.get("No existing reactions"), JOptionPane.WARNING_MESSAGE); return; } else { Object[] ids = getReactionIDs(reactionSet); String s = (String)ids[0]; if(ids.length>1){ s = (String) JOptionPane.showInputDialog( null, "Reaction Chooser", "Choose reaction to add reaction to", JOptionPane.PLAIN_MESSAGE, null, ids, ids[0] ); } if ((s != null) && (s.length() > 0)) { ReactionHub.makeReactantInExistingReaction((ControllerHub)hub, s, newContainer, container); //TODO this.jcpPanel.atomAtomMappingButton.setEnabled(true); } else { logger.error("No reaction selected"); } } } else if ("addProductToNew".equals(type)) { ReactionHub.makeProductInNewReaction((ControllerHub)hub, newContainer, container); //this.jcpPanel.atomAtomMappingButton.setEnabled(true); } else if ("addProductToExisting".equals(type)) { if (reactionSet.getReactionCount() == 0) { logger.warn("Cannot add to reaction if no one exists"); JOptionPane.showMessageDialog(jcpPanel, GT.get("No reaction existing. Cannot add therefore to something!"), GT.get("No existing reactions"), JOptionPane.WARNING_MESSAGE); return; } else { Object[] ids = getReactionIDs(reactionSet); String s = (String)ids[0]; if(ids.length>1){ s = (String) JOptionPane.showInputDialog( null, "Reaction Chooser", "Choose reaction to add reaction to", JOptionPane.PLAIN_MESSAGE, null, ids, ids[0] ); } if ((s != null) && (s.length() > 0)) { ReactionHub.makeProductInExistingReaction((ControllerHub)hub, s, newContainer, container); //TODO this.jcpPanel.atomAtomMappingButton.setEnabled(true); } else { logger.error("No reaction selected"); } } } else { logger.warn("Don't know about this action type: " + type); return; } } logger.debug("Deleted atom from old container..."); jcpPanel.get2DHub().updateView(); } /** * Gets the reactionIDs attribute of the CreateReactionAction object * *@param reactionSet Description of the Parameter *@return The reactionIDs value */ private Object[] getReactionIDs(IReactionSet reactionSet) { if (reactionSet != null) { String[] ids = new String[reactionSet.getReactionCount()]; for (int i = 0; i < reactionSet.getReactionCount(); i++) { ids[i] = reactionSet.getReaction(i).getID(); } return ids; } else { return new String[0]; } } }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/action/OpenAction.java
.java
7,404
160
/* * $RCSfile$ * $Author: egonw $ * $Date: 2007-01-04 17:26:00 +0000 (Thu, 04 Jan 2007) $ * $Revision: 7634 $ * * Copyright (C) 1997-2008 Stefan Kuhn * * Contact: cdk-jchempaint@lists.sourceforge.net * * 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.jchempaint.action; import java.awt.event.ActionEvent; import javax.swing.JFileChooser; import javax.swing.JOptionPane; import org.openscience.cdk.interfaces.IChemModel; import org.openscience.jchempaint.JChemPaintPanel; import org.openscience.jchempaint.applet.JChemPaintEditorApplet; import org.openscience.jchempaint.application.JChemPaint; import org.openscience.jchempaint.controller.undoredo.IUndoRedoable; import org.openscience.jchempaint.io.ChemicalFilesFilter; import org.openscience.jchempaint.io.JCPFileFilter; import org.openscience.jchempaint.io.JCPFileView; import org.openscience.jchempaint.renderer.selection.LogicalSelection; /** * Shows the open dialog * */ public class OpenAction extends JCPAction { private static final long serialVersionUID = 1030940425527065876L; /** * Opens an empty JChemPaint frame. * * @param e * Description of the Parameter */ public void actionPerformed(ActionEvent e) { JFileChooser chooser = new JFileChooser(); chooser.setCurrentDirectory(jcpPanel.getCurrentWorkDirectory()); chooser.setAcceptAllFileFilterUsed(false); chooser.addChoosableFileFilter(new ChemicalFilesFilter()); chooser.setAcceptAllFileFilterUsed(true); JCPFileFilter.addChoosableFileFilters(chooser); if (jcpPanel.getCurrentOpenFileFilter() != null) { for(int i=0;i<chooser.getChoosableFileFilters().length;i++){ if(chooser.getChoosableFileFilters()[i].getDescription().equals(jcpPanel.getCurrentOpenFileFilter().getDescription())) chooser.setFileFilter(chooser.getChoosableFileFilters()[i]); } } if (jcpPanel.getLastOpenedFile() != null) { chooser.setSelectedFile(jcpPanel.getLastOpenedFile()); } chooser.setFileView(new JCPFileView()); int returnVal = chooser.showOpenDialog(jcpPanel); if (returnVal == JFileChooser.APPROVE_OPTION) { jcpPanel.setCurrentWorkDirectory(chooser.getCurrentDirectory()); jcpPanel.setCurrentOpenFileFilter(chooser.getFileFilter()); javax.swing.filechooser.FileFilter ff = chooser.getFileFilter(); if (ff instanceof JCPFileFilter) { type = ((JCPFileFilter) ff).getType(); } if (jcpPanel.getGuistring().equals( JChemPaintEditorApplet.GUI_APPLET) || JChemPaintPanel.getAllAtomContainersInOne(jcpPanel.getChemModel()).getAtomCount()==0) { int clear = jcpPanel.showWarning(); if (clear == JOptionPane.YES_OPTION) { try { IChemModel chemModel = null; jcpPanel.get2DHub().unsetRGroupHandler(); chemModel = JChemPaint .readFromFileReader(chooser .getSelectedFile().toURI().toURL(), chooser.getSelectedFile().toURI() .toString(), type, jcpPanel); if (jcpPanel.get2DHub().getUndoRedoFactory() != null && jcpPanel.get2DHub().getUndoRedoHandler() != null) { IUndoRedoable undoredo = jcpPanel.get2DHub() .getUndoRedoFactory().getLoadNewModelEdit( jcpPanel.getChemModel(), null, jcpPanel.getChemModel() .getMoleculeSet(), jcpPanel.getChemModel() .getReactionSet(), chemModel.getMoleculeSet(), chemModel.getReactionSet(), "Load " + chooser.getSelectedFile() .getName()); jcpPanel.get2DHub().getUndoRedoHandler().postEdit( undoredo); } jcpPanel.getChemModel().setMoleculeSet( chemModel.getMoleculeSet()); jcpPanel.getChemModel().setReactionSet(chemModel.getReactionSet()); jcpPanel.getRenderPanel().getRenderer() .getRenderer2DModel().setSelection( new LogicalSelection( LogicalSelection.Type.NONE)); // the newly opened file should nicely fit the screen jcpPanel.getRenderPanel().setFitToScreen(true); jcpPanel.getRenderPanel().update( jcpPanel.getRenderPanel().getGraphics()); // enable zooming by removing constraint jcpPanel.getRenderPanel().setFitToScreen(false); jcpPanel.setIsAlreadyAFile(chooser.getSelectedFile()); //in case this is an application, we set the file name as title if (jcpPanel.getGuistring().equals( JChemPaint.GUI_APPLICATION)) ((JChemPaintPanel)jcpPanel).setTitle(chooser .getSelectedFile().getName()); } catch (Exception e1) { // TODO Auto-generated catch block e1.printStackTrace(); jcpPanel.announceError(e1); } } } else { JChemPaint.showInstance(chooser.getSelectedFile(), type, jcpPanel, jcpPanel.isDebug()); } } } }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/action/EditAtomContainerPropsAction.java
.java
2,797
69
/* * $RCSfile$ * $Author: egonw $ * $Date: 2007-01-04 17:26:00 +0000 (Thu, 04 Jan 2007) $ * $Revision: 7634 $ * * Copyright (C) 1997-2008 Egon Willighagen, Stefan Kuhn * * Contact: cdk-jchempaint@lists.sourceforge.net * * 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.jchempaint.action; import java.awt.event.ActionEvent; import javax.swing.JOptionPane; import org.openscience.cdk.interfaces.IAtom; import org.openscience.cdk.interfaces.IAtomContainer; import org.openscience.cdk.interfaces.IBond; import org.openscience.cdk.interfaces.IChemObject; import org.openscience.cdk.tools.manipulator.ChemModelManipulator; import org.openscience.jchempaint.dialog.editor.AtomContainerEditor; import org.openscience.jchempaint.dialog.editor.ChemObjectEditor; import org.openscience.jchempaint.dialog.editor.ChemObjectPropertyDialog; /** * Action for triggering an edit of a IChemObject * */ public class EditAtomContainerPropsAction extends JCPAction { private static final long serialVersionUID = 8489495722307245626L; public void actionPerformed(ActionEvent event) { IChemObject object = getSource(event); logger.debug("Showing object properties for: ", object); ChemObjectEditor editor = new AtomContainerEditor(); IAtomContainer relevantContainer = null; if(object instanceof IAtom) relevantContainer = ChemModelManipulator.getRelevantAtomContainer(jcpPanel.getChemModel(),(IAtom)object); if(object instanceof IBond) relevantContainer = ChemModelManipulator.getRelevantAtomContainer(jcpPanel.getChemModel(),(IBond)object); editor.setChemObject(relevantContainer); ChemObjectPropertyDialog frame = new ChemObjectPropertyDialog(JOptionPane.getFrameForComponent(editor), jcpPanel.get2DHub(), editor); frame.pack(); frame.setVisible(true); } }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/action/CopyPasteAction.java
.java
37,955
813
/* * $RCSfile$ * $Author: egonw $ * $Date: 2007-01-04 17:26:00 +0000 (Thu, 04 Jan 2007) $ * $Revision: 7634 $ * * Copyright (C) 1997-2008 Egon Willighagen, Stefan Kuhn * * Contact: cdk-jchempaint@lists.sourceforge.net * * 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.jchempaint.action; import org.openscience.cdk.ChemFile; import org.openscience.cdk.ChemModel; import org.openscience.cdk.DefaultChemObjectBuilder; import org.openscience.cdk.depict.Depiction; import org.openscience.cdk.depict.DepictionGenerator; import org.openscience.cdk.exception.CDKException; import org.openscience.cdk.geometry.GeometryUtil; import org.openscience.cdk.graph.ConnectivityChecker; import org.openscience.cdk.interfaces.IAtom; import org.openscience.cdk.interfaces.IAtomContainer; import org.openscience.cdk.interfaces.IAtomContainerSet; import org.openscience.cdk.interfaces.IBond; import org.openscience.cdk.interfaces.IChemFile; import org.openscience.cdk.interfaces.IChemModel; import org.openscience.cdk.interfaces.IChemObject; import org.openscience.cdk.interfaces.IChemObjectBuilder; import org.openscience.cdk.interfaces.IReaction; import org.openscience.cdk.io.CMLReader; import org.openscience.cdk.io.IChemObjectWriter; import org.openscience.cdk.io.ISimpleChemObjectReader; import org.openscience.cdk.io.MDLV2000Reader; import org.openscience.cdk.io.MDLV2000Writer; import org.openscience.cdk.io.RGroupQueryReader; import org.openscience.cdk.io.ReaderFactory; import org.openscience.cdk.isomorphism.matchers.IRGroupQuery; import org.openscience.cdk.isomorphism.matchers.RGroupQuery; import org.openscience.cdk.layout.StructureDiagramGenerator; import org.openscience.cdk.renderer.RendererModel; import org.openscience.cdk.renderer.generators.BasicSceneGenerator; import org.openscience.cdk.renderer.selection.IChemObjectSelection; import org.openscience.cdk.smiles.SmilesGenerator; import org.openscience.cdk.smiles.SmilesParser; import org.openscience.cdk.tools.CDKHydrogenAdder; import org.openscience.cdk.tools.manipulator.AtomContainerManipulator; import org.openscience.cdk.tools.manipulator.ChemFileManipulator; import org.openscience.cdk.tools.manipulator.ChemModelManipulator; import org.openscience.cdk.tools.manipulator.MoleculeSetManipulator; import org.openscience.cdk.tools.manipulator.ReactionManipulator; import org.openscience.jchempaint.AtomBondSet; import org.openscience.jchempaint.GT; import org.openscience.jchempaint.JChemPaintPanel; import org.openscience.jchempaint.application.JChemPaint; import org.openscience.jchempaint.controller.ControllerHub; import org.openscience.jchempaint.controller.MoveModule; import org.openscience.jchempaint.controller.SelectSquareModule; import org.openscience.jchempaint.dialog.TemplateBrowser; import org.openscience.jchempaint.inchi.InChITool; import org.openscience.jchempaint.renderer.JChemPaintRendererModel; import org.openscience.jchempaint.renderer.Renderer; import org.openscience.jchempaint.renderer.selection.LogicalSelection; import org.openscience.jchempaint.renderer.selection.RectangleSelection; import org.openscience.jchempaint.renderer.selection.ShapeSelection; import org.openscience.jchempaint.renderer.selection.SingleSelection; import org.openscience.jchempaint.rgroups.RGroupHandler; import javax.swing.JOptionPane; import javax.vecmath.Point2d; import java.awt.Image; import java.awt.datatransfer.Clipboard; import java.awt.datatransfer.ClipboardOwner; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.SystemFlavorMap; import java.awt.datatransfer.Transferable; import java.awt.datatransfer.UnsupportedFlavorException; import java.awt.event.ActionEvent; import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; import java.io.OutputStream; import java.io.StringReader; import java.io.StringWriter; import java.io.Writer; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.util.Collections; /** * Action to copy/paste/cut/erase/select structures. */ public final class CopyPasteAction extends JCPAction { public static final String COPY = "copy"; public static final String COPY_AS_MOLFILE = "copyAsMolfile"; public static final String COPY_AS_SMILES = "copyAsSmiles"; public static final String CUT = "cut"; public static final String ERASER = "eraser"; public static final String PASTE = "paste"; public static final String PASTE_TEMPLATE = "pasteTemplate"; public static final String SELECT_ALL = "selectAll"; public static final String SELECT_FROM_CHEM_OBJECT = "selectFromChemObject"; public static final String SELECT_REACTION_REACTANTS = "selectReactionReactants"; public static final String SELECT_REACTION_PRODUCTS = "selectReactionProducts"; private static final long serialVersionUID = -3343207264261279526L; public static final DataFlavor MOL_FLAVOR = new DataFlavor("chemical/x-mdl-molfile", "MDL MOLfile"); public static final DataFlavor CML_FLAVOR = new DataFlavor("chemical/x-cml", "Chemical Markup Language"); public static final DataFlavor SMI_FLAVOR = new DataFlavor("chemical/x-daylight-smiles", "SMILES"); public static final DataFlavor SVG_FLAVOR = new DataFlavor("image/svg+xml; class=java.io.InputStream", "Scalable Vector Graphics"); public static final DataFlavor INKSCAPE_SVG_FLAVOR = new DataFlavor("image/x-inkscape-svg; class=java.io.InputStream", "Scalable Vector Graphics"); public static final DataFlavor PDF_FLAVOR = new DataFlavor("application/pdf; class=java.io.InputStream", "Portable Document Format"); private Class<? extends Clipboard> clipboardWrapper; @SuppressWarnings("unchecked") public CopyPasteAction() { SystemFlavorMap systemFlavorMap = (SystemFlavorMap) SystemFlavorMap.getDefaultFlavorMap(); systemFlavorMap.addUnencodedNativeForFlavor(SVG_FLAVOR, "image/svg+xml"); systemFlavorMap.addUnencodedNativeForFlavor(INKSCAPE_SVG_FLAVOR, "image/svg+xml"); systemFlavorMap.addUnencodedNativeForFlavor(PDF_FLAVOR, "application/pdf"); // The SystemFlavorMap is ineffective on OS X (https://bugs.openjdk.org/browse/JDK-8136781) // so we have a wrapper which makes the required native calls try { clipboardWrapper = (Class<? extends Clipboard>) Class.forName("org.openscience.jchempaint.OsxClipboard"); } catch (ClassNotFoundException ignored) { // if we can't find the OS X clipboard, we are probably not on // OS X or the build it missing it, either of these is ok } } private void addToClipboard(Clipboard clipboard, IAtomContainer container) { try { for (IBond bond : container.bonds()) if (bond.getAtomCount() < 2 || !container.contains(bond.getAtom(0)) || !container.contains(bond.getAtom(1))) container.removeBond(bond); if (container.getAtomCount() > 0) { JcpSelection jcpselection = new JcpSelection(container.clone(), jcpPanel.getRenderPanel().getRendererModel()); clipboard.setContents(jcpselection, null); } } catch (CloneNotSupportedException ex) { logger.error("CloneNotSupportedException: ", ex.getMessage()); } } private boolean supported(Transferable transfer, DataFlavor flavor) { return transfer != null && transfer.isDataFlavorSupported(flavor); } public void actionPerformed(ActionEvent e) { logger.info(" type ", type); logger.debug(" source ", e.getSource()); JChemPaintRendererModel renderModel = jcpPanel.get2DHub().getRenderer().getRenderer2DModel(); IChemModel chemModel = jcpPanel.getChemModel(); Clipboard clipboard = getClipboard(); if (COPY.equals(type)) { handleSystemClipboard(clipboard); IAtom atomInRange = null; IChemObject object = getSource(e); logger.debug("Source of call: ", object); // JWM: old behaviour would prioritize the highlighted atom/bond // under the cursor, it makes more sense if the selection takes // priority and if no selection then we just copy everything if (renderModel.getSelection().getConnectedAtomContainer() != null) { addToClipboard(clipboard, renderModel.getSelection().getConnectedAtomContainer()); } else { addToClipboard(clipboard, JChemPaintPanel.getAllAtomContainersInOne(chemModel)); } } else if (COPY_AS_SMILES.equals(type)) { handleSystemClipboard(clipboard); try { final IAtomContainer selection = renderModel.getSelection().getConnectedAtomContainer(); if (selection != null) { final IChemObjectBuilder bldr = selection.getBuilder(); IChemModel selectionModel = bldr.newInstance(IChemModel.class); selectionModel.setMoleculeSet(bldr.newInstance(IAtomContainerSet.class)); selectionModel.getMoleculeSet().addAtomContainer(selection); clipboard.setContents(new StringContent(CreateSmilesAction.getSmiles(selectionModel)), null); } else { clipboard.setContents(new StringContent(CreateSmilesAction.getSmiles(chemModel)), null); } } catch (Exception e1) { e1.printStackTrace(); } } else if (COPY_AS_MOLFILE.equals(type)) { handleSystemClipboard(clipboard); try { final IAtomContainer selection = renderModel.getSelection().getConnectedAtomContainer(); if (selection != null) { final IChemObjectBuilder bldr = selection.getBuilder(); IChemModel selectionModel = bldr.newInstance(IChemModel.class); selectionModel.setMoleculeSet(bldr.newInstance(IAtomContainerSet.class)); selectionModel.getMoleculeSet().addAtomContainer(selection); clipboard.setContents(new StringContent(CreateSmilesAction.getMolfile(selectionModel)), null); } else { clipboard.setContents(new StringContent(CreateSmilesAction.getMolfile(chemModel)), null); } } catch (Exception e1) { e1.printStackTrace(); } } else if (ERASER.equals(type)) { jcpPanel.get2DHub().clearPhantoms(); // JWM: we do not "switch" to delete mode, this means you can // quick delete (by key press) and then carry on drawing without // having to switch back to the tool you were using IAtom atomInRange = null; IBond bondInRange = null; IChemObject object = getSource(e); logger.debug("Source of call: ", object); if (object instanceof IAtom) { atomInRange = (IAtom) object; } else { atomInRange = renderModel.getHighlightedAtom(); } if (object instanceof IBond) { bondInRange = (IBond) object; } else { bondInRange = renderModel.getHighlightedBond(); } IAtom newHighlightAtom = null; // Select > Highlight Atom > Highlight Bond if (renderModel.getSelection() != null && renderModel.getSelection().isFilled()) { IChemObjectSelection selection = renderModel.getSelection(); AtomBondSet atomBondSet = new AtomBondSet(); for (IAtom atom : selection.elements(IAtom.class)) { atomBondSet.add(atom); // set the hot spot to the attached atom with the highest index for (IBond bond : atom.bonds()) { IAtom nbor = bond.getOther(atom); if (!selection.contains(nbor) && (newHighlightAtom == null || nbor.getIndex() > newHighlightAtom.getIndex())) newHighlightAtom = nbor; } } for (IBond bond : selection.elements(IBond.class)) atomBondSet.add(bond); jcpPanel.get2DHub().deleteFragment(atomBondSet); renderModel.setSelection(new LogicalSelection(LogicalSelection.Type.NONE)); jcpPanel.get2DHub().updateView(); } else if (atomInRange != null) { if (atomInRange.equals(renderModel.getHighlightedAtom())) { IAtomContainer container = ChemModelManipulator.getRelevantAtomContainer(jcpPanel.getChemModel(), atomInRange); if (container != null) { for (IBond bond : container.getConnectedBondsList(atomInRange)) newHighlightAtom = bond.getOther(atomInRange); } } jcpPanel.get2DHub().removeAtom(atomInRange); } else if (bondInRange != null) { IAtomContainer container = ChemModelManipulator.getRelevantAtomContainer(jcpPanel.getChemModel(), bondInRange); if (container != null) { for (IBond bond : container.getConnectedBondsList(bondInRange.getBegin())) newHighlightAtom = bond.getOther(bondInRange.getBegin()); for (IBond bond : container.getConnectedBondsList(bondInRange.getEnd())) newHighlightAtom = bond.getOther(bondInRange.getEnd()); } jcpPanel.get2DHub().removeBond(bondInRange); } // no new hotspot? go to last atom added if (newHighlightAtom == null) { for (IAtomContainer ac : jcpPanel.getChemModel().getMoleculeSet()) { if (!ac.isEmpty()) newHighlightAtom = ac.getAtom(ac.getAtomCount() - 1); } } jcpPanel.get2DHub().getRenderer().getRenderer2DModel().setHighlightedAtom(newHighlightAtom); jcpPanel.get2DHub().getRenderer().getRenderer2DModel().setHighlightedBond(null); } else if (type.contains(PASTE_TEMPLATE)) { //if templates are shown, we extract the tab to show if any String templatetab = ""; if (type.contains("_")) { templatetab = type.substring(type.indexOf("_") + 1); } TemplateBrowser templateBrowser = new TemplateBrowser(templatetab); if (templateBrowser.getChosenmolecule() != null) { scaleStructure(templateBrowser.getChosenmolecule()); insertStructure(templateBrowser.getChosenmolecule(), renderModel); } } else if (PASTE.equals(type)) { handleSystemClipboard(clipboard); Transferable transfer = clipboard.getContents(null); ISimpleChemObjectReader reader = null; String content = null; DataFlavor[] flavors = transfer.getTransferDataFlavors(); if (supported(transfer, MOL_FLAVOR)) { try { String molfile = (String) transfer.getTransferData(MOL_FLAVOR); try { reader = new MDLV2000Reader(new StringReader(molfile)); } catch (Exception ex) { // JWM: note the reader will not fail until we try to read, // so this logic is not correct reader = new RGroupQueryReader(new StringReader(molfile)); } } catch (UnsupportedFlavorException | IOException ufe) { logger.error("Unsupported flavour: ", MOL_FLAVOR); } } else if (supported(transfer, DataFlavor.stringFlavor)) { try { content = (String) transfer.getTransferData(DataFlavor.stringFlavor); reader = new ReaderFactory().createReader(new StringReader(content)); } catch (Exception e1) { logger.error("Could not read string: ", e1.getMessage()); } } // if it looks like CML - InputStream required. Reader throws error. if (content != null && content.contains("cml")) { reader = new CMLReader(new ByteArrayInputStream(content.getBytes())); } IAtomContainer toPaste = null; boolean rgrpQuery = false; if (reader != null) { IAtomContainer readMolecule = chemModel.getBuilder().newInstance(IAtomContainer.class); try { if (reader.accepts(IAtomContainer.class)) { toPaste = (IAtomContainer) reader.read(readMolecule); } else if (reader.accepts(ChemFile.class)) { toPaste = readMolecule; IChemFile file = (IChemFile) reader.read(new ChemFile()); for (IAtomContainer ac : ChemFileManipulator.getAllAtomContainers(file)) { toPaste.add(ac); } } else if (reader.accepts(RGroupQuery.class)) { rgrpQuery = true; IRGroupQuery rgroupQuery = (RGroupQuery) reader.read(new RGroupQuery(DefaultChemObjectBuilder.getInstance())); chemModel = new ChemModel(); RGroupHandler rgHandler = new RGroupHandler(rgroupQuery, this.jcpPanel); this.jcpPanel.get2DHub().setRGroupHandler(rgHandler); chemModel.setMoleculeSet(rgHandler.getMoleculeSet(chemModel)); rgHandler.layoutRgroup(); } } catch (CDKException e1) { e1.printStackTrace(); } } // Attempt SMILES or InChI if no reader is found for content. if (rgrpQuery != true && toPaste == null && supported(transfer, DataFlavor.stringFlavor)) { try { if (content.toLowerCase().indexOf("inchi") > -1) { toPaste = InChITool.parseInChI(content); } else { SmilesParser sp = new SmilesParser( DefaultChemObjectBuilder.getInstance()); toPaste = sp.parseSmiles( ((String) transfer.getTransferData( DataFlavor.stringFlavor)).trim()); IAtomContainerSet mols = ConnectivityChecker.partitionIntoMolecules(toPaste); for (int i = 0; i < mols.getAtomContainerCount(); i++) { StructureDiagramGenerator sdg = new StructureDiagramGenerator((IAtomContainer) mols.getAtomContainer(i)); sdg.generateCoordinates(); } //SMILES parser sets valencies, unset for (int i = 0; i < toPaste.getAtomCount(); i++) { toPaste.getAtom(i).setValency(null); } } } catch (Exception ex) { jcpPanel.announceError(ex); ex.printStackTrace(); } } if (toPaste != null || rgrpQuery == true) { // jcpPanel.getRenderPanel().setZoomWide(true); // jcpPanel.get2DHub().getRenderer().getRenderer2DModel().setZoomFactor(1); if (rgrpQuery == true) { this.jcpPanel.setChemModel(chemModel); } else { scaleStructure(toPaste); insertStructure(toPaste, renderModel); } } else { JOptionPane.showMessageDialog(jcpPanel, GT.get("The content you tried to copy could not be read to any known format"), GT.get("Could not process content"), JOptionPane.WARNING_MESSAGE); } } else if (type.equals(CUT)) { handleSystemClipboard(clipboard); IAtom atomInRange = null; IBond bondInRange = null; IChemObject object = getSource(e); logger.debug("Source of call: ", object); if (object instanceof IAtom) { atomInRange = (IAtom) object; } else { atomInRange = renderModel.getHighlightedAtom(); } if (object instanceof IBond) { bondInRange = (IBond) object; } else { bondInRange = renderModel.getHighlightedBond(); } IAtomContainer tocopyclone = jcpPanel.getChemModel().getBuilder().newInstance(IAtomContainer.class); if (atomInRange != null) { tocopyclone.addAtom(atomInRange); jcpPanel.get2DHub().removeAtom(atomInRange); renderModel.setHighlightedAtom(null); } else if (bondInRange != null) { tocopyclone.addBond(bondInRange); jcpPanel.get2DHub().removeBond(bondInRange); } else if (renderModel.getSelection() != null && renderModel.getSelection().getConnectedAtomContainer() != null) { IChemObjectSelection selection = renderModel.getSelection(); IAtomContainer selected = selection.getConnectedAtomContainer(); tocopyclone.add(selected); jcpPanel.get2DHub().deleteFragment(new AtomBondSet(selected)); renderModel.setSelection(new LogicalSelection( LogicalSelection.Type.NONE)); jcpPanel.get2DHub().updateView(); } if (tocopyclone.getAtomCount() > 0 || tocopyclone.getBondCount() > 0) addToClipboard(clipboard, tocopyclone); } else if (type.equals(SELECT_ALL)) { ControllerHub hub = jcpPanel.get2DHub(); IChemObjectSelection allSelection = new LogicalSelection(LogicalSelection.Type.ALL); allSelection.select(hub.getIChemModel()); renderModel.setSelection(allSelection); SelectSquareModule succusorModule = new SelectSquareModule(hub); succusorModule.setID("select"); MoveModule newActiveModule = new MoveModule(hub, succusorModule); newActiveModule.setID("move"); hub.setActiveDrawModule(newActiveModule); } else if (type.equals(SELECT_FROM_CHEM_OBJECT)) { // FIXME: implement for others than Reaction, Atom, Bond IChemObject object = getSource(e); if (object instanceof IAtom) { SingleSelection<IAtom> container = new SingleSelection<IAtom>((IAtom) object); renderModel.setSelection(container); } else if (object instanceof IBond) { SingleSelection<IBond> container = new SingleSelection(object); renderModel.setSelection(container); } else if (object instanceof IReaction) { IAtomContainer wholeModel = jcpPanel.getChemModel().getBuilder().newInstance(IAtomContainer.class); for (IAtomContainer container : ReactionManipulator.getAllAtomContainers( (IReaction) object)) { wholeModel.add(container); } ShapeSelection container = new RectangleSelection(); for (IAtom atom : wholeModel.atoms()) { container.atoms.add(atom); } for (IBond bond : wholeModel.bonds()) { container.bonds.add(bond); } renderModel.setSelection(container); } else { logger.warn("Cannot select everything in : ", object); } } else if (type.equals(SELECT_REACTION_REACTANTS)) { IChemObject object = getSource(e); if (object instanceof IReaction) { IReaction reaction = (IReaction) object; IAtomContainer wholeModel = jcpPanel.getChemModel().getBuilder().newInstance(IAtomContainer.class); for (IAtomContainer container : MoleculeSetManipulator.getAllAtomContainers( reaction.getReactants())) { wholeModel.add(container); } ShapeSelection container = new RectangleSelection(); for (IAtom atom : wholeModel.atoms()) { container.atoms.add(atom); } for (IBond bond : wholeModel.bonds()) { container.bonds.add(bond); } renderModel.setSelection(container); } else { logger.warn("Cannot select reactants from : ", object); } } else if (type.equals(SELECT_REACTION_PRODUCTS)) { IChemObject object = getSource(e); if (object instanceof IReaction) { IReaction reaction = (IReaction) object; IAtomContainer wholeModel = jcpPanel.getChemModel().getBuilder().newInstance(IAtomContainer.class); for (IAtomContainer container : MoleculeSetManipulator.getAllAtomContainers( reaction.getProducts())) { wholeModel.add(container); } ShapeSelection container = new RectangleSelection(); for (IAtom atom : wholeModel.atoms()) { container.atoms.add(atom); } for (IBond bond : wholeModel.bonds()) { container.bonds.add(bond); } renderModel.setSelection(container); } else { logger.warn("Cannot select reactants from : ", object); } } jcpPanel.get2DHub().updateView(); } private Clipboard getClipboard() { Clipboard clipboard = jcpPanel.getToolkit().getSystemClipboard(); if (clipboardWrapper != null) { try { Constructor<? extends Clipboard> constructor = clipboardWrapper.getConstructor(Clipboard.class); clipboard = constructor.newInstance(clipboard); } catch (NoSuchMethodException | InvocationTargetException | InstantiationException | IllegalAccessException ex) { throw new RuntimeException(ex); } } return clipboard; } /** * Scale the structure to be pasted to the same scale of the current drawing * * @param topaste */ private void scaleStructure(IAtomContainer topaste) { if (topaste.getBondCount() == 0) return; double bondLengthModel = Renderer.calculateBondLength(jcpPanel.get2DHub().getIChemModel().getMoleculeSet()); double bondLengthInsert = GeometryUtil.getBondLengthMedian(topaste); double scale = bondLengthModel / bondLengthInsert; for (IAtom atom : topaste.atoms()) { if (atom.getPoint2d() != null) { atom.setPoint2d(new Point2d(atom.getPoint2d().x * scale, atom.getPoint2d().y * scale)); } } } /** * Inserts a structure into the panel. It adds Hs if needed and highlights the structure after insert. * * @param toPaste The structure to paste. * @param renderModel The current renderer model. */ private void insertStructure(IAtomContainer toPaste, JChemPaintRendererModel renderModel) { //add implicit hs if (jcpPanel.get2DHub().getController2DModel().getAutoUpdateImplicitHydrogens()) { try { AtomContainerManipulator.percieveAtomTypesAndConfigureAtoms(toPaste); CDKHydrogenAdder hAdder = CDKHydrogenAdder.getInstance(toPaste .getBuilder()); hAdder.addImplicitHydrogens(toPaste); } catch (CDKException ex) { ex.printStackTrace(); // do nothing } //valencies are set when doing atom typing, which we don't want in jcp for (int i = 0; i < toPaste.getAtomCount(); i++) { toPaste.getAtom(i).setValency(null); } } //somehow, in case of single atoms, there are no coordinates if (toPaste.getAtomCount() == 1 && toPaste.getAtom(0).getPoint2d() == null) toPaste.getAtom(0).setPoint2d(new Point2d(0, 0)); try { JChemPaint.generateModel(jcpPanel, toPaste, false, true); } catch (CDKException e) { e.printStackTrace(); return; } jcpPanel.get2DHub().fireStructureChangedEvent(); //We select the inserted structure IChemObjectSelection selection = new LogicalSelection(LogicalSelection.Type.ALL); selection.select(ChemModelManipulator.newChemModel(toPaste)); renderModel.setSelection(selection); SelectSquareModule successorModule = new SelectSquareModule(jcpPanel.get2DHub()); successorModule.setID("select"); MoveModule newActiveModule = new MoveModule(jcpPanel.get2DHub(), successorModule); newActiveModule.setID("move"); jcpPanel.get2DHub().setActiveDrawModule(newActiveModule); } private void handleSystemClipboard(Clipboard clipboard) { Transferable clipboardContent = clipboard.getContents(this); DataFlavor flavors[] = clipboardContent.getTransferDataFlavors(); String text = "System.clipoard content"; for (int i = 0; i < flavors.length; ++i) { text += "\n\n Name: " + flavors[i].getHumanPresentableName(); text += "\n MIME Type: " + flavors[i].getMimeType(); text += "\n Class: "; Class<?> cl = flavors[i].getRepresentationClass(); if (cl == null) text += "null"; else text += cl.getName(); } logger.debug(text); } class JcpSelection implements Transferable, ClipboardOwner { private final DataFlavor[] flavors = { SVG_FLAVOR, INKSCAPE_SVG_FLAVOR, PDF_FLAVOR, DataFlavor.imageFlavor, DataFlavor.stringFlavor, DataFlavor.javaFileListFlavor, MOL_FLAVOR, CML_FLAVOR, SMI_FLAVOR }; String mol; Image image; byte[] pdf; String smiles; String svg; String cml; File file; public JcpSelection(IAtomContainer container, RendererModel model) { IAtomContainer tocopy = container.getBuilder() .newInstance(IAtomContainer.class, container); // MDL mol output StringWriter sw = new StringWriter(); try (MDLV2000Writer mdlWriter = new MDLV2000Writer(sw)) { mdlWriter.writeMolecule(tocopy); } catch (Exception ex) { logger.error("Could not write molecule to string: ", ex.getMessage()); logger.debug(ex); } this.mol = sw.toString(); SmilesGenerator sg = SmilesGenerator.isomeric(); try { smiles = sg.create(tocopy); } catch (CDKException ex) { logger.error("Could not create SMILES: ", ex.getMessage()); logger.debug(ex); } Depiction depiction = null; try { depiction = new DepictionGenerator().withParams(model) .withParam(BasicSceneGenerator.Margin.class, DepictionGenerator.AUTOMATIC) .depict(container); image = depiction.toImg(); pdf = depiction.toPdf(); svg = depiction.toSvgStr(); file = File.createTempFile("jcp-selection", ".svg"); try (OutputStream out = Files.newOutputStream(file.toPath())) { out.write(svg.getBytes(StandardCharsets.UTF_8)); } } catch (CDKException e) { logger.error("Could not generate depiction for selection"); image = null; pdf = null; svg = null; file = null; } catch (IOException e) { throw new RuntimeException(e); } // CML output sw = new StringWriter(); Class<?> cmlWriterClass = null; try { cmlWriterClass = this.getClass().getClassLoader().loadClass( "org.openscience.cdk.io.CMLWriter"); if (cmlWriterClass != null) { IChemObjectWriter cow = (IChemObjectWriter) cmlWriterClass.newInstance(); Constructor<? extends IChemObjectWriter> constructor = cow.getClass().getConstructor(new Class[]{Writer.class}); cow = (IChemObjectWriter) constructor.newInstance(new Object[]{sw}); cow.write(tocopy); cow.close(); } cml = sw.toString(); } catch (Exception exception) { logger.error("Could not load CMLWriter: ", exception.getMessage()); logger.debug(exception); } } public synchronized DataFlavor[] getTransferDataFlavors() { return (flavors); } public boolean isDataFlavorSupported(DataFlavor parFlavor) { for (DataFlavor flavor : flavors) { if (flavor.equals(parFlavor)) return true; } return false; } public synchronized Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException { if (flavor.equals(MOL_FLAVOR)) { return mol; } else if (flavor.equals(SMI_FLAVOR)) { return new StringReader(smiles); } else if (flavor.equals(DataFlavor.stringFlavor)) { return smiles; } else if (flavor.equals(CML_FLAVOR)) { return new StringReader(cml); } else if (flavor.equals(SVG_FLAVOR) || flavor.equals(INKSCAPE_SVG_FLAVOR)) { return svg != null ? new ByteArrayInputStream(svg.getBytes(StandardCharsets.UTF_8)) : null; } else if (flavor.equals(DataFlavor.imageFlavor)) { return image; } else if (flavor.equals(PDF_FLAVOR)) { return pdf != null ? new ByteArrayInputStream(pdf) : null; } else if (flavor.equals(DataFlavor.javaFileListFlavor)) { return Collections.singletonList(file); } else { throw new UnsupportedFlavorException(flavor); } } public void lostOwnership(Clipboard parClipboard, Transferable parTransferable) { System.out.println("Lost ownership"); } } class StringContent implements Transferable, ClipboardOwner { String str; public StringContent(String str) throws Exception { this.str = str; } public synchronized DataFlavor[] getTransferDataFlavors() { return new DataFlavor[]{DataFlavor.stringFlavor}; } public boolean isDataFlavorSupported(DataFlavor f) { return f == DataFlavor.stringFlavor; } public synchronized Object getTransferData(DataFlavor f) throws UnsupportedFlavorException { if (f.equals(DataFlavor.stringFlavor)) { return str; } else { throw new UnsupportedFlavorException(f); } } public void lostOwnership(Clipboard parClipboard, Transferable parTransferable) { } } }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/action/ToolBarAction.java
.java
1,748
53
/* * $RCSfile$ * $Author: egonw $ * $Date: 2007-01-04 17:26:00 +0000 (Thu, 04 Jan 2007) $ * $Revision: 7634 $ * * Copyright (C) 1997-2008 Christoph Steinbeck, Stefan Kuhn * * Contact: cdk-jchempaint@lists.sourceforge.net * * 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.jchempaint.action; import java.awt.event.ActionEvent; /** * Opens a new empty JChemPaintFrame. * */ public class ToolBarAction extends JCPAction { private static final long serialVersionUID = -7685519078261241187L; /** * Opens an empty JChemPaint frame. * *@param e Description of the Parameter */ public void actionPerformed(ActionEvent e) { jcpPanel.setShowToolBar(!jcpPanel.getShowToolBar()); } }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/action/InsertStructureAction.java
.java
1,773
51
/* * $RCSfile$ * $Author: egonw $ * $Date: 2007-01-04 17:26:00 +0000 (Thu, 04 Jan 2007) $ * $Revision: 7634 $ * * Copyright (C) 1997-2008 Rajarshi Guha, Stefan Kuhn * * Contact: cdk-jchempaint@lists.sourceforge.net * * 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.jchempaint.action; import java.awt.event.ActionEvent; /** * Opens a new empty JChemPaintFrame. * */ public class InsertStructureAction extends JCPAction { private static final long serialVersionUID = -7685519078261241187L; /** * Hide or show the structure entry text field. * * @param e Description of the Parameter */ public void actionPerformed(ActionEvent e) { jcpPanel.setShowInsertTextField(!jcpPanel.getShowInsertTextField()); } }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/action/ChangeValenceAction.java
.java
3,353
94
/* * $RCSfile$ * $Author: egonw $ * $Date: 2007-01-04 17:26:00 +0000 (Thu, 04 Jan 2007) $ * $Revision: 7634 $ * * Copyright (C) 1997-2008 Egon Willighagen, Stefan Kuhn * * Contact: cdk-jchempaint@lists.sourceforge.net * * 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.jchempaint.action; import java.awt.event.ActionEvent; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.openscience.cdk.interfaces.IAtom; import org.openscience.cdk.interfaces.IChemObject; import org.openscience.jchempaint.controller.ChangeValenceModule; /** * changes the atom symbol */ public class ChangeValenceAction extends JCPAction { private static final long serialVersionUID = -8502905723573311893L; public void actionPerformed(ActionEvent event) { logger.debug("About to change valence of relevant atom!"); IChemObject object = getSource(event); logger.debug("Source of call: ", object); Iterator<IAtom> atomsInRange = null; if (object == null){ //this means the main menu was used if(jcpPanel.getRenderPanel().getRenderer().getRenderer2DModel().getSelection().isFilled()) atomsInRange=jcpPanel.getRenderPanel().getRenderer().getRenderer2DModel().getSelection().elements(IAtom.class).iterator(); }else if (object instanceof IAtom) { List<IAtom> atoms = new ArrayList<IAtom>(); atoms.add((IAtom) object); atomsInRange = atoms.iterator(); } else { List<IAtom> atoms = new ArrayList<IAtom>(); atoms.add(jcpPanel.getRenderPanel().getRenderer().getRenderer2DModel().getHighlightedAtom()); atomsInRange = atoms.iterator(); } if(atomsInRange==null) return; String s = event.getActionCommand(); String symbol = s.substring(s.indexOf("@") + 1); Integer valence=null; if(!symbol.equals("off")) valence = new Integer(symbol); while(atomsInRange.hasNext()){ IAtom atom = atomsInRange.next(); if(symbol.equals("off")){ jcpPanel.get2DHub().setValence(atom,null); }else{ jcpPanel.get2DHub().setValence(atom,valence); } } ChangeValenceModule newActiveModule = new ChangeValenceModule(jcpPanel.get2DHub(), valence==null ? -1 : valence); newActiveModule.setID("valence"); jcpPanel.get2DHub().setActiveDrawModule(newActiveModule); jcpPanel.get2DHub().updateView(); } }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/action/ExitAction.java
.java
1,730
56
/* * $RCSfile$ * $Author: egonw $ * $Date: 2007-01-04 17:26:00 +0000 (Thu, 04 Jan 2007) $ * $Revision: 7634 $ * * Copyright (C) 1997-2008 Stefan Kuhn * * Contact: cdk-jchempaint@lists.sourceforge.net * * 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.jchempaint.action; import java.awt.event.ActionEvent; import org.openscience.jchempaint.JChemPaintPanel; /** * Triggers an exit of the application * */ public class ExitAction extends JCPAction { private static final long serialVersionUID = -7805547937237070627L; /** * Opens an empty JChemPaint frame. * *@param e Description of the Parameter */ public void actionPerformed(ActionEvent e) { JChemPaintPanel.closeAllInstances(); } }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/action/SaveAsAction.java
.java
20,244
473
/* * $RCSfile$ * $Author: egonw $ * $Date: 2007-01-04 17:26:00 +0000 (Thu, 04 Jan 2007) $ * $Revision: 7634 $ * * Copyright (C) 1997-2008 Stefan Kuhn * * Contact: cdk-jchempaint@lists.sourceforge.net * * 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.jchempaint.action; import java.awt.Component; import java.awt.event.ActionEvent; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.Iterator; import javax.swing.JFileChooser; import javax.swing.JOptionPane; import javax.swing.filechooser.FileFilter; import org.openscience.cdk.exception.CDKException; import org.openscience.cdk.interfaces.IAtomContainer; import org.openscience.cdk.interfaces.IChemModel; import org.openscience.cdk.interfaces.IChemObject; import org.openscience.cdk.interfaces.IAtomContainerSet; import org.openscience.cdk.io.CDKSourceCodeWriter; import org.openscience.cdk.io.IChemObjectWriter; import org.openscience.cdk.io.MDLRXNWriter; import org.openscience.cdk.io.MDLV2000Writer; import org.openscience.cdk.io.RGroupQueryWriter; import org.openscience.cdk.io.SMILESWriter; import org.openscience.cdk.io.listener.SwingGUIListener; import org.openscience.cdk.io.setting.IOSetting; import org.openscience.cdk.isomorphism.matchers.IRGroupQuery; import org.openscience.cdk.tools.manipulator.ChemModelManipulator; import org.openscience.jchempaint.AbstractJChemPaintPanel; import org.openscience.jchempaint.GT; import org.openscience.jchempaint.JCPPropertyHandler; import org.openscience.jchempaint.JChemPaintPanel; import org.openscience.jchempaint.inchi.InChI; import org.openscience.jchempaint.inchi.InChITool; import org.openscience.jchempaint.io.IJCPFileFilter; import org.openscience.jchempaint.io.JCPFileView; import org.openscience.jchempaint.io.JCPSaveFileFilter; /** * Opens a "Save as" dialog * */ public class SaveAsAction extends JCPAction { private static final long serialVersionUID = -5138502232232716970L; protected IChemObjectWriter cow; protected static String type = null; protected boolean wasCancelled = false; /** * Constructor for the SaveAsAction object */ public SaveAsAction() { super(); } /** * Constructor for the SaveAsAction object * *@param jcpPanel Description of the Parameter *@param isPopupAction Description of the Parameter */ public SaveAsAction(AbstractJChemPaintPanel jcpPanel, boolean isPopupAction) { super(jcpPanel, "", isPopupAction); } /** * Opens a dialog frame and manages the saving of a file. * *@param event Description of the Parameter */ public void actionPerformed(ActionEvent event) { IChemModel jcpm = jcpPanel.getChemModel(); if (jcpm == null) { String error = GT.get("Nothing to save."); JOptionPane.showMessageDialog(jcpPanel, error,error,JOptionPane.WARNING_MESSAGE); } else { saveAs(event); } } protected void saveAs(ActionEvent event) { int ready=1; while(ready==1){ IChemModel model = jcpPanel.getChemModel(); JFileChooser chooser = new JFileChooser(); chooser.setName("save"); chooser.setCurrentDirectory(jcpPanel.getCurrentWorkDirectory()); chooser.setAcceptAllFileFilterUsed(false); JCPSaveFileFilter.addChoosableFileFilters(chooser); if (jcpPanel.getCurrentSaveFileFilter() != null) { for(int i=0;i<chooser.getChoosableFileFilters().length;i++){ if(chooser.getChoosableFileFilters()[i].getDescription().equals(jcpPanel.getCurrentSaveFileFilter().getDescription())) chooser.setFileFilter(chooser.getChoosableFileFilters()[i]); } } else { chooser.setFileFilter(chooser.getChoosableFileFilters()[0]); } chooser.setFileView(new JCPFileView()); if(jcpPanel.isAlreadyAFile()!=null) chooser.setSelectedFile(jcpPanel.isAlreadyAFile()); int returnVal = chooser.showSaveDialog(jcpPanel); IChemObject object = getSource(event); FileFilter currentFilter = chooser.getFileFilter(); if(returnVal==JFileChooser.CANCEL_OPTION){ ready=0; wasCancelled = true; } if (returnVal == JFileChooser.APPROVE_OPTION) { if(!(currentFilter instanceof IJCPFileFilter)){ JOptionPane.showMessageDialog(jcpPanel, GT.get("Please choose a file type!"), GT.get("No file type chosen"), JOptionPane.INFORMATION_MESSAGE); return; }else{ type = ((IJCPFileFilter) currentFilter).getType(); File outFile = chooser.getSelectedFile(); if(outFile.exists()){ ready=JOptionPane.showConfirmDialog((Component)null, GT.get("File {0} already exists. Do you want to overwrite it?", outFile.getName()), GT.get("File already exists"),JOptionPane.YES_NO_OPTION); }else{ try{ if(new File(outFile.getCanonicalFile()+"."+type).exists()){ ready=JOptionPane.showConfirmDialog((Component)null, GT.get("File {0} already exists. Do you want to overwrite it?", outFile.getName()), GT.get("File already exists"),JOptionPane.YES_NO_OPTION); } }catch(Throwable ex){ jcpPanel.announceError(ex); } ready=0; } if(ready==0){ if (object == null) { // called from main menu, only possibility try { if (type.equals(JCPSaveFileFilter.mol)) { outFile = saveAsMol(model, outFile); } else if (type.equals(JCPSaveFileFilter.inchi)) { outFile = saveAsInChI(model, outFile); } else if (type.equals(JCPSaveFileFilter.cml)) { outFile = saveAsCML2(model, outFile); } else if (type.equals(JCPSaveFileFilter.smiles)) { outFile = saveAsSMILES(model, outFile); } else if (type.equals(JCPSaveFileFilter.cdk)) { outFile = saveAsCDKSourceCode(model, outFile); } else if (type.equals(JCPSaveFileFilter.rxn)) { outFile = saveAsRXN(model, outFile); } else { String error = GT.get("Cannot save file in this format:") + " " + type; logger.error(error); JOptionPane.showMessageDialog(jcpPanel, error); return; } jcpPanel.setModified(false); } catch (Exception exc) { String error = GT.get("Error while writing file")+": " + exc.getMessage(); logger.error(error); logger.debug(exc); JOptionPane.showMessageDialog(jcpPanel, error); } } jcpPanel.setCurrentWorkDirectory(chooser.getCurrentDirectory()); jcpPanel.setCurrentSaveFileFilter(chooser.getFileFilter()); jcpPanel.setIsAlreadyAFile(outFile); if(outFile!=null){ jcpPanel.getChemModel().setID(outFile.getName()); if(jcpPanel instanceof JChemPaintPanel) ((JChemPaintPanel)jcpPanel).setTitle(outFile.getName()); } } } } } } protected File saveAsRXN(IChemModel model, File outFile) throws IOException, CDKException { if(model.getMoleculeSet()!=null && model.getMoleculeSet().getAtomContainerCount()>0){ String error = GT.get("Problems handling data"); String message = GT.get("{0} files cannot contain extra molecules. You painted molecules outside the reaction(s), which will not be in the file. Continue?", "RXN"); int answer = JOptionPane.showConfirmDialog(jcpPanel, message, error, JOptionPane.YES_NO_OPTION); if(answer == JOptionPane.NO_OPTION) return null; } if(model.getReactionSet()==null || model.getReactionSet().getReactionCount()==0){ String error = GT.get("Problems handling data"); String message = GT.get("RXN can only save reactions. You have no reactions painted!"); JOptionPane.showMessageDialog(jcpPanel, message, error, JOptionPane.WARNING_MESSAGE); return null; } logger.info("Saving the contents in an rxn file..."); String fileName = outFile.toString(); if (!fileName.endsWith(".rxn")) { fileName += ".rxn"; outFile = new File(fileName); } outFile=new File(fileName); cow = new MDLRXNWriter(new FileWriter(outFile)); cow.write(model.getReactionSet()); cow.close(); if(jcpPanel instanceof JChemPaintPanel) ((JChemPaintPanel)jcpPanel).setTitle(jcpPanel.getChemModel().getID()); return outFile; } private boolean askIOSettings() { return JCPPropertyHandler.getInstance(true).getJCPProperties() .getProperty("General.askForIOSettings").equals("true"); } protected File saveAsMol(IChemModel model, File outFile) throws Exception { logger.info("Saving the contents in a MDL molfile file..."); if(model.getMoleculeSet()==null || model.getMoleculeSet().getAtomContainerCount()==0){ String error = GT.get("Problems handling data"); String message = GT.get("MDL mol files can only save molecules. You have no molecules painted!"); JOptionPane.showMessageDialog(jcpPanel, message, error, JOptionPane.WARNING_MESSAGE); return null; } if(model.getReactionSet()!=null && model.getReactionSet().getReactionCount()>0){ String error = GT.get("Problems handling data"); String message = GT.get("{0} files cannot contain reactions. Your have reaction(s) painted. The reactants/products of these will be included as separate molecules. Continue?", "MDL mol"); int answer = JOptionPane.showConfirmDialog(jcpPanel, message, error, JOptionPane.YES_NO_OPTION); if(answer == JOptionPane.NO_OPTION) return null; } boolean saveAsRgrpQuery=false; IRGroupQuery rGroupQuery = null; if(jcpPanel.get2DHub().getRGroupHandler()!=null) rGroupQuery= jcpPanel.get2DHub().getRGroupHandler().getrGroupQuery(); if(rGroupQuery!=null){ String error = GT.get("Please choose a file type!"); String message = GT.get("Would you like to save the drawing as an R-group Query File? (RGFile = extended MOLfile)"); int answer = JOptionPane.showConfirmDialog(jcpPanel, message, error, JOptionPane.YES_NO_OPTION); if(answer == JOptionPane.YES_OPTION) saveAsRgrpQuery=true; } String fileName = outFile.toString(); if (!fileName.endsWith(".mol")) { fileName += ".mol"; outFile = new File(fileName); } outFile=new File(fileName); if(saveAsRgrpQuery) { cow = new RGroupQueryWriter(new FileWriter(outFile)); boolean problem=false; String message=""; jcpPanel.get2DHub().getRGroupHandler().cleanUpRGroup(jcpPanel.get2DHub().getChemModel().getMoleculeSet()); if(!rGroupQuery.areRootAtomsDefined()) { message = GT.get("The R-group Query is not valid: there are substitutes that have no corresponding atom in the root structure."); problem=true; } if(!rGroupQuery.areSubstituentsDefined()) { message = GT.get("The R-group Query is not valid: the root structure has R# definitions for which no substitutes are defined."); problem=true; } if (problem) { String error = GT.get("Could not save file"); JOptionPane.showMessageDialog(jcpPanel, message, GT.get(error), JOptionPane.INFORMATION_MESSAGE); return null; } cow.write(rGroupQuery); } else { cow = new MDLV2000Writer(new FileWriter(outFile)); cow.write(model); } cow.close(); if(jcpPanel instanceof JChemPaintPanel) ((JChemPaintPanel)jcpPanel).setTitle(jcpPanel.getChemModel().getID()); return outFile; } protected File saveAsCML2(IChemObject object, File outFile) throws Exception { // if(Float.parseFloat(System.getProperty("java.specification.version"))<1.5){ // JOptionPane.showMessageDialog(null,"For saving as CML you need Java 1.5 or higher!"); // return outFile; // } // logger.info("Saving the contents in a CML 2.0 file..."); // String fileName = outFile.toString(); // if (!fileName.endsWith(".cml")) { // fileName += ".cml"; // outFile = new File(fileName); // } // FileWriter sw = new FileWriter(outFile); // cow = new CMLWriter(sw); // if (cow != null && askIOSettings()) // { // cow.addChemObjectIOListener(new SwingGUIListener(jcpPanel, IOSetting.Importance.HIGH)); // } // cow.write(object); // cow.close(); // sw.close(); // if(jcpPanel instanceof JChemPaintPanel) // ((JChemPaintPanel)jcpPanel).setTitle(jcpPanel.getChemModel().getID()); // return outFile; throw new IllegalStateException(); } protected File saveAsInChI(IChemObject object, File outFile) throws Exception { logger.info("Saving the contents in an InChI textfile..."); String fileName = outFile.toString(); if (!fileName.endsWith(".txt")) { fileName += ".txt"; outFile = new File(fileName); } BufferedWriter out = new BufferedWriter(new FileWriter(outFile)); String eol=System.getProperty("line.separator"); if (object instanceof IChemModel) { IAtomContainerSet mSet = ((IChemModel) object).getMoleculeSet(); for (IAtomContainer atc : mSet.atomContainers()) { InChI inchi = InChITool.generateInchi(atc); out.write(inchi.getInChI()+eol); out.write(inchi.getAuxInfo()+eol); out.write(inchi.getKey()+eol); } } else if (object instanceof IAtomContainer) { IAtomContainer atc = (IAtomContainer) object; InChI inchi = InChITool.generateInchi(atc); out.write(inchi.getInChI()+eol); out.write(inchi.getAuxInfo()+eol); out.write(inchi.getKey()+eol); } out.close(); return outFile; } protected File saveAsSMILES(IChemModel model, File outFile) throws Exception { logger.info("Saving the contents in SMILES format..."); if(model.getReactionSet()!=null && model.getReactionSet().getReactionCount()>0){ String error = GT.get("Problems handling data"); String message = GT.get("{0} files cannot contain reactions. Your have reaction(s) painted. The reactants/products of these will be included as separate molecules. Continue?", "SMILES"); int answer = JOptionPane.showConfirmDialog(jcpPanel, message, error, JOptionPane.YES_NO_OPTION); if(answer == JOptionPane.NO_OPTION) return null; } String fileName = outFile.toString(); if (!fileName.endsWith(".smi") && !fileName.endsWith(".smiles")) { fileName += ".smi"; outFile = new File(fileName); } cow = new SMILESWriter(new FileWriter(outFile)); if (cow != null && askIOSettings()) { cow.addChemObjectIOListener(new SwingGUIListener(jcpPanel, IOSetting.Importance.HIGH)); } Iterator<IAtomContainer> containers = ChemModelManipulator.getAllAtomContainers(model).iterator(); IAtomContainerSet som = model.getBuilder().newInstance(IAtomContainerSet.class); while (containers.hasNext()) { //Clone() is here because the SMILESWriter sets valencies and we don't //want these changes visible som.addAtomContainer((IAtomContainer) containers.next().clone()); } cow.write(som); cow.close(); if(jcpPanel instanceof JChemPaintPanel) ((JChemPaintPanel)jcpPanel).setTitle(jcpPanel.getChemModel().getID()); return outFile; } protected File saveAsCDKSourceCode(IChemModel model, File outFile) throws Exception { logger.info("Saving the contents as a CDK source code file..."); String fileName = outFile.toString(); if (!fileName.endsWith(".cdk")) { fileName += ".cdk"; outFile = new File(fileName); } cow = new CDKSourceCodeWriter(new FileWriter(outFile)); if (cow != null && askIOSettings()) { cow.addChemObjectIOListener(new SwingGUIListener(jcpPanel, IOSetting.Importance.HIGH)); } Iterator<IAtomContainer> containers = ChemModelManipulator.getAllAtomContainers(model).iterator(); while (containers.hasNext()) { IAtomContainer ac = (IAtomContainer)containers.next(); if (ac != null) { cow.write(ac); } else { System.err.println("AC == null!"); } } cow.close(); if(jcpPanel instanceof JChemPaintPanel) ((JChemPaintPanel)jcpPanel).setTitle(jcpPanel.getChemModel().getID()); return outFile; } /** * Tells if the save as has been cancelled. * * @return True if cancel has been used on the save as dialog, false else. */ public boolean getWasCancelled() { return wasCancelled; } }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/action/HelpAction.java
.java
2,670
79
/* * $RCSfile$ * $Author: egonw $ * $Date: 2007-01-04 17:26:00 +0000 (Thu, 04 Jan 2007) $ * $Revision: 7634 $ * * Copyright (C) 1997-2008 Stefan Kuhn, Christoph Steinbeck * * Contact: cdk-jchempaint@lists.sourceforge.net * * 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.jchempaint.action; import java.awt.event.ActionEvent; import java.net.URL; import org.openscience.jchempaint.GT; import org.openscience.jchempaint.dialog.HelpDialog; /** * Pops up the help. * */ public class HelpAction extends JCPAction { private static final long serialVersionUID = -9213900779679488824L; public void actionPerformed(ActionEvent e) { String helpRoot = "org/openscience/jchempaint/resources/userhelp_jcp/"; String language = GT.getLanguage(); URL helpURL = HelpDialog.class.getClassLoader().getResource(helpRoot + language + "/jcp.html"); if (helpURL == null) { language = "en_US"; } if (type.equals("tutorial")) { new HelpDialog(null, helpRoot+language+"/contain/tutorial.html", GT.get("JChemPaint Help")).setVisible(true); } else if (type.equals("rgpTutorial")) { new HelpDialog(null, helpRoot+language+"/contain/rgroup_tutorial.html", GT.get("JChemPaint Help")).setVisible(true); } else if (type.equals("feedback")) { new HelpDialog(null, helpRoot+language+"/contain/feedback.html", GT.get("JChemPaint Help")).setVisible(true); } else if (type.equals("license")) { new HelpDialog(null, helpRoot+language+"/license.html", GT.get("JChemPaint License")).setVisible(true); } else { new HelpDialog(null, helpRoot+language+"/jcp.html", GT.get("JChemPaint Help")).setVisible(true); } } }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/action/MenuBarAction.java
.java
1,747
53
/* * $RCSfile$ * $Author: egonw $ * $Date: 2007-01-04 17:26:00 +0000 (Thu, 04 Jan 2007) $ * $Revision: 7634 $ * * Copyright (C) 1997-2008 Christoph Steinbeck, Stefan Kuhn * * Contact: cdk-jchempaint@lists.sourceforge.net * * 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.jchempaint.action; import java.awt.event.ActionEvent; /** * Opens a new empty JChemPaintFrame. * */ public class MenuBarAction extends JCPAction { private static final long serialVersionUID = 8427001652906942684L; /** * Opens an empty JChemPaint frame. * *@param e Description of the Parameter */ public void actionPerformed(ActionEvent e) { jcpPanel.setShowMenuBar(!jcpPanel.getShowMenuBar()); } }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/action/PrintAction.java
.java
2,719
87
/* * $RCSfile$ * $Author: egonw $ * $Date: 2007-01-04 17:26:00 +0000 (Thu, 04 Jan 2007) $ * $Revision: 7634 $ * * Copyright (C) 1997-2008 Stefan Kuhn * * Contact: cdk-jchempaint@lists.sourceforge.net * * 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.jchempaint.action; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.event.ActionEvent; import java.awt.print.PageFormat; import java.awt.print.Printable; import java.awt.print.PrinterException; import java.awt.print.PrinterJob; /** * Opens a print dialog * * @cdk.module jchempaint */ public class PrintAction extends JCPAction implements Printable { private static final long serialVersionUID = 3944389510342678007L; /** * Opens a dialog frame and manages the printing of a file. * * @param event Description of the Parameter */ public void actionPerformed(ActionEvent event) { PrinterJob printJob = PrinterJob.getPrinterJob(); printJob.setPrintable(this); if (printJob.printDialog()) { try { printJob.print(); } catch (PrinterException pe) { jcpPanel.announceError(pe); } } } /** * Prints the actual drawingPanel * * @param g Graphics object of drawinPanel * @param pageFormat Description of the Parameter * @param pageIndex Description of the Parameter * @return Description of the Return Value */ public int print(Graphics g, PageFormat pageFormat, int pageIndex) { if (pageIndex > 0) { return (NO_SUCH_PAGE); } else { Graphics2D g2d = (Graphics2D) g; g2d.translate(pageFormat.getImageableX(), pageFormat.getImageableY()); jcpPanel.getRenderPanel().takeSnapshot(g2d); return (PAGE_EXISTS); } } }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/action/ChangeSingleElectronAction.java
.java
3,381
85
/* * $RCSfile$ * $Author: egonw $ * $Date: 2007-01-04 17:26:00 +0000 (Thu, 04 Jan 2007) $ * $Revision: 7634 $ * * Copyright (C) 1997-2008 Stefan Kuhn * * Contact: cdk-jchempaint@lists.sourceforge.net * * 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.jchempaint.action; import java.awt.event.ActionEvent; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.openscience.cdk.interfaces.IAtom; import org.openscience.cdk.interfaces.IChemObject; import org.openscience.jchempaint.controller.ChangeSingleElectronModule; /** */ public class ChangeSingleElectronAction extends JCPAction { private static final long serialVersionUID = 1898335761308427006L; public void actionPerformed(ActionEvent event) { logger.debug("Converting to radical: ", type); IChemObject object = getSource(event); Iterator<IAtom> atomsInRange = null; if (object == null){ //this means the main menu was used if(jcpPanel.getRenderPanel().getRenderer().getRenderer2DModel().getSelection().isFilled()) atomsInRange=jcpPanel.getRenderPanel().getRenderer().getRenderer2DModel().getSelection().elements(IAtom.class).iterator(); }else if (object instanceof IAtom) { List<IAtom> atoms = new ArrayList<IAtom>(); atoms.add((IAtom) object); atomsInRange = atoms.iterator(); } else { List<IAtom> atoms = new ArrayList<IAtom>(); atoms.add(jcpPanel.getRenderPanel().getRenderer().getRenderer2DModel().getHighlightedAtom()); atomsInRange = atoms.iterator(); } if(atomsInRange==null) return; ChangeSingleElectronModule newActiveModule = null; while(atomsInRange.hasNext()){ IAtom atom = atomsInRange.next(); if(type.equals("add")){ jcpPanel.get2DHub().addSingleElectron(atom); logger.info("Added single electron to atom"); newActiveModule = new ChangeSingleElectronModule(jcpPanel.get2DHub(), true); }else{ jcpPanel.get2DHub().removeSingleElectron(atom); logger.info("Removed single electron to atom"); newActiveModule = new ChangeSingleElectronModule(jcpPanel.get2DHub(), false); } } jcpPanel.get2DHub().updateView(); newActiveModule.setID(type); jcpPanel.get2DHub().setActiveDrawModule(newActiveModule); } }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/action/FlipAction.java
.java
1,849
52
/* * $RCSfile$ * $Author: egonw $ * $Date: 2007-01-04 17:26:00 +0000 (Thu, 04 Jan 2007) $ * $Revision: 7634 $ * * Copyright (C) 1997-2008 Egon Willighagen, Stefan Kuhn * * Contact: cdk-jchempaint@lists.sourceforge.net * * 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.jchempaint.action; import java.awt.event.ActionEvent; /** * Action to flip selected part of a structure * */ public class FlipAction extends JCPAction { private static final long serialVersionUID = 2360209016030592684L; public void actionPerformed(ActionEvent e) { logger.info(" type ", type); logger.debug(" source ", e.getSource()); boolean horiz = "horizontal".equals(type); jcpPanel.get2DHub().flip(horiz); // fire a change so that the view gets updated jcpPanel.get2DHub().updateView(); } }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/action/ChangeIsotopeAction.java
.java
5,296
120
/* * $RCSfile$ * $Author: egonw $ * $Date: 2007-01-04 17:26:00 +0000 (Thu, 04 Jan 2007) $ * $Revision: 7634 $ * * Copyright (C) 1997-2008 Egon Willighagen, Stefan Kuhn * * Contact: cdk-jchempaint@lists.sourceforge.net * * 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.jchempaint.action; import java.awt.event.ActionEvent; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.openscience.cdk.config.Isotopes; import org.openscience.cdk.interfaces.IAtom; import org.openscience.cdk.interfaces.IBond; import org.openscience.cdk.interfaces.IChemObject; import org.openscience.cdk.interfaces.IIsotope; import org.openscience.jchempaint.controller.AddAtomModule; import org.openscience.jchempaint.controller.AddBondDragModule; /** * Changes the isotope for a selected atom * */ public class ChangeIsotopeAction extends JCPAction { private static final long serialVersionUID = -4692219842740123315L; public void actionPerformed(ActionEvent event) { //first switch draw mode AddAtomModule newActiveModule = new AddAtomModule(jcpPanel.get2DHub(), IBond.Display.Solid); if(jcpPanel.get2DHub().getActiveDrawModule() instanceof AddBondDragModule) newActiveModule=new AddAtomModule(jcpPanel.get2DHub(), ((AddBondDragModule)jcpPanel.get2DHub().getActiveDrawModule()).getStereoForNewBond()); else if(jcpPanel.get2DHub().getActiveDrawModule() instanceof AddAtomModule) newActiveModule=new AddAtomModule(jcpPanel.get2DHub(), ((AddAtomModule)jcpPanel.get2DHub().getActiveDrawModule()).getStereoForNewBond()); logger.debug("About to change atom type of relevant atom!"); IChemObject object = getSource(event); logger.debug("Source of call: ", object); Iterator<IAtom> atomsInRange = null; if (object == null){ //this means the main menu was used if(jcpPanel.getRenderPanel().getRenderer().getRenderer2DModel().getSelection().isFilled()) atomsInRange=jcpPanel.getRenderPanel().getRenderer().getRenderer2DModel().getSelection().elements(IAtom.class).iterator(); }else if (object instanceof IAtom) { List<IAtom> atoms = new ArrayList<IAtom>(); atoms.add((IAtom) object); atomsInRange = atoms.iterator(); } else { List<IAtom> atoms = new ArrayList<IAtom>(); atoms.add(jcpPanel.getRenderPanel().getRenderer().getRenderer2DModel().getHighlightedAtom()); atomsInRange = atoms.iterator(); } if(atomsInRange==null) return; while(atomsInRange.hasNext()){ IAtom atom = atomsInRange.next(); int isotopeNumber = 0; try { IIsotope isotope = Isotopes.getInstance().getMajorIsotope( atom.getSymbol()); isotopeNumber = isotope.getMassNumber(); } catch (Exception exception) { logger.error("Error while configuring atom"); logger.debug(exception); } // adapt for menu chosen if (type.equals("major")) { // that's the default } else if (type.equals("majorPlusOne")) { isotopeNumber += 1; } else if (type.equals("majorPlusTwo")) { isotopeNumber += 2; } else if (type.equals("majorPlusThree")) { isotopeNumber += 3; } else if (type.equals("majorMinusOne")) { isotopeNumber -= 1; } else if (type.equals("majorMinusTwo")) { isotopeNumber -= 2; } else if (type.equals("majorMinusThree")) { isotopeNumber -= 3; } else if (type.indexOf("specific")==0) { isotopeNumber = Integer.parseInt(type.substring(8)); } jcpPanel.get2DHub().setMassNumber(atom,isotopeNumber); jcpPanel.get2DHub().updateView(); newActiveModule.setID(atom.getSymbol()); jcpPanel.get2DHub().getController2DModel().setDrawElement(atom.getSymbol()); jcpPanel.get2DHub().getController2DModel().setDrawIsotopeNumber(isotopeNumber); jcpPanel.get2DHub().getController2DModel().setDrawPseudoAtom(false); } jcpPanel.get2DHub().setActiveDrawModule(newActiveModule); } }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/action/ConvertToPseudoAtomAction.java
.java
4,947
116
/* * $RCSfile$ * $Author: egonw $ * $Date: 2007-01-04 17:26:00 +0000 (Thu, 04 Jan 2007) $ * $Revision: 7634 $ * * Copyright (C) 1997-2008 Stefan Kuhn * * Contact: cdk-jchempaint@lists.sourceforge.net * * 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.jchempaint.action; import java.awt.event.ActionEvent; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import javax.swing.JOptionPane; import org.openscience.cdk.PseudoAtom; import org.openscience.cdk.interfaces.IAtom; import org.openscience.cdk.interfaces.IBond; import org.openscience.cdk.interfaces.IChemObject; import org.openscience.cdk.interfaces.IPseudoAtom; import org.openscience.cdk.isomorphism.matchers.RGroupQuery; import org.openscience.jchempaint.controller.AddAtomModule; import org.openscience.jchempaint.controller.AddBondDragModule; import org.openscience.jchempaint.GT; ; /** * Converts to and from pseudo atoms */ public class ConvertToPseudoAtomAction extends JCPAction { private static final long serialVersionUID = -598284013998335002L; public void actionPerformed(ActionEvent event) { logger.debug("Converting to: ", type); IChemObject object = getSource(event); Iterator<IAtom> atomsInRange = null; if (object == null){ //this means the main menu was used if(jcpPanel.getRenderPanel().getRenderer().getRenderer2DModel().getSelection().isFilled()) atomsInRange=jcpPanel.getRenderPanel().getRenderer().getRenderer2DModel().getSelection().elements(IAtom.class).iterator(); }else if (object instanceof IAtom) { List<IAtom> atoms = new ArrayList<IAtom>(); atoms.add((IAtom) object); atomsInRange = atoms.iterator(); } else { List<IAtom> atoms = new ArrayList<IAtom>(); atoms.add(jcpPanel.getRenderPanel().getRenderer().getRenderer2DModel().getHighlightedAtom()); atomsInRange = atoms.iterator(); } if(atomsInRange==null) return; String label = type; if(type.equals("RX")) { boolean inputOkay=false; do { label = JOptionPane.showInputDialog(GT.get("Enter label"), "R"); if (label == null) return; if(label.startsWith("R") && label.length()>1 && !RGroupQuery.isValidRgroupQueryLabel(label)) JOptionPane.showMessageDialog(null, GT.get("This is not a valid R-group label.\nPlease label in range R1 .. R32")); else inputOkay=true; } while (!inputOkay); } while(atomsInRange.hasNext()){ IAtom atom = atomsInRange.next(); if(type.equals("normal")){ PseudoAtom pseudo = (PseudoAtom)atom; IAtom normal = pseudo.getBuilder().newInstance(IPseudoAtom.class,pseudo); normal.setSymbol("C"); jcpPanel.get2DHub().replaceAtom(normal,pseudo); }else { jcpPanel.get2DHub().convertToPseudoAtom(atom,label); AddAtomModule newActiveModule = new AddAtomModule(jcpPanel.get2DHub(), IBond.Display.Solid); if(jcpPanel.get2DHub().getActiveDrawModule() instanceof AddBondDragModule) newActiveModule=new AddAtomModule(jcpPanel.get2DHub(), ((AddBondDragModule)jcpPanel.get2DHub().getActiveDrawModule()).getStereoForNewBond()); else if(jcpPanel.get2DHub().getActiveDrawModule() instanceof AddAtomModule) newActiveModule=new AddAtomModule(jcpPanel.get2DHub(), ((AddAtomModule)jcpPanel.get2DHub().getActiveDrawModule()).getStereoForNewBond()); newActiveModule.setID(label); jcpPanel.get2DHub().setActiveDrawModule(newActiveModule); jcpPanel.get2DHub().getController2DModel().setDrawPseudoAtom(true); jcpPanel.get2DHub().getController2DModel().setDrawElement(label); jcpPanel.get2DHub().getController2DModel().setDrawIsotopeNumber(0); } } jcpPanel.get2DHub().updateView(); } }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/action/ChargeAction.java
.java
4,060
104
/* * $RCSfile$ * $Author: egonw $ * $Date: 2007-01-04 17:26:00 +0000 (Thu, 04 Jan 2007) $ * $Revision: 7634 $ * * Copyright (C) 2009 Stefan Kuhn * * Contact: cdk-jchempaint@lists.sourceforge.net * * 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.jchempaint.action; import java.awt.event.ActionEvent; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.openscience.cdk.interfaces.IAtom; import org.openscience.cdk.interfaces.IChemObject; import org.openscience.jchempaint.controller.ChangeFormalChargeModule; import org.openscience.jchempaint.renderer.JChemPaintRendererModel; /** * Changes the charge */ public class ChargeAction extends JCPAction { private static final long serialVersionUID = -8502905723573311893L; public void actionPerformed(ActionEvent event) { String s = event.getActionCommand(); String action = s.substring(s.indexOf("@") + 1); int charge = 0; if (action.equals("plus2")) { charge = 2; } else if (action.equals("plus")) { charge = 1; } else if (action.equals("minus")) { charge = -1; } else if (action.equals("minus2")) { charge = -2; } ChangeFormalChargeModule newActiveModule = new ChangeFormalChargeModule(jcpPanel.get2DHub(), charge); newActiveModule.setID(action); jcpPanel.get2DHub().setActiveDrawModule(newActiveModule); logger.debug("About to change atom type of relevant atom!"); Iterator<IAtom> atomsInRange = null; IChemObject object = getSource(event); logger.debug("Source of call: ", object); JChemPaintRendererModel model = jcpPanel.getRenderPanel().getRenderer().getRenderer2DModel(); if (object == null) { // this means the main menu was used List<IAtom> atoms = new ArrayList<IAtom>(); IAtom highlightedAtom = model.getHighlightedAtom(); if (model.getSelection() != null && model.getSelection().isFilled()) atomsInRange = model.getSelection().elements(IAtom.class).iterator(); else if (highlightedAtom != null) { atoms.add(highlightedAtom); atomsInRange = atoms.iterator(); } } else if (object instanceof IAtom) { List<IAtom> atoms = new ArrayList<IAtom>(); atoms.add((IAtom) object); atomsInRange = atoms.iterator(); } else { List<IAtom> atoms = new ArrayList<IAtom>(); atoms.add(model.getHighlightedAtom()); atomsInRange = atoms.iterator(); } if (atomsInRange == null) return; while (atomsInRange.hasNext()) { IAtom atom = atomsInRange.next(); int newCharge = charge; if (atom.getFormalCharge() != null) newCharge += atom.getFormalCharge(); jcpPanel.get2DHub().setCharge(atom, newCharge); } jcpPanel.get2DHub().updateView(); } }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/action/AboutAction.java
.java
1,851
56
/* * $RCSfile$ * $Author: egonw $ * $Date: 2007-01-04 17:26:00 +0000 (Thu, 04 Jan 2007) $ * $Revision: 7634 $ * * Copyright (C) 1997-2008 Stefan Kuhn, Christoph Steinbeck * * Contact: cdk-jchempaint@lists.sourceforge.net * * 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.jchempaint.action; import java.awt.Frame; import java.awt.event.ActionEvent; import javax.swing.JOptionPane; import org.openscience.jchempaint.dialog.AboutDialog; /** * Action to pop-up an About JChemPaint dialog. * */ public class AboutAction extends JCPAction { private static final long serialVersionUID = 1420132959122535398L; public void actionPerformed(ActionEvent e) { Frame frame = JOptionPane.getFrameForComponent(jcpPanel); AboutDialog ad = new AboutDialog(frame, jcpPanel.getGuistring()); ad.pack(); ad.setVisible(true); } }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/action/ModifySettingsAction.java
.java
2,037
57
/* * $RCSfile$ * $Author: egonw $ * $Date: 2007-01-04 17:26:00 +0000 (Thu, 04 Jan 2007) $ * $Revision: 7634 $ * * Copyright (C) 1997-2008 Christoph Steinbeck, Stefan Kuhn * * Contact: cdk-jchempaint@lists.sourceforge.net * * 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.jchempaint.action; import java.awt.event.ActionEvent; import org.openscience.jchempaint.dialog.ModifyRenderOptionsDialog; import org.openscience.jchempaint.renderer.JChemPaintRendererModel; /** * Shows a dialog for editing the Display settings */ public class ModifySettingsAction extends JCPAction { private static final long serialVersionUID = 374787381482528088L; public void actionPerformed(ActionEvent e) { //TODO test if renderer uses settings logger.debug("Modify display settings in mode"); JChemPaintRendererModel renderModel = jcpPanel.get2DHub().getRenderer().getRenderer2DModel(); ModifyRenderOptionsDialog frame = new ModifyRenderOptionsDialog(jcpPanel,renderModel,0); frame.setVisible(true); } }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/action/NewAction.java
.java
2,775
75
/* * $RCSfile$ * $Author: egonw $ * $Date: 2007-01-04 17:26:00 +0000 (Thu, 04 Jan 2007) $ * $Revision: 7634 $ * * Copyright (C) 1997-2008 Stefan Kuhn * * Contact: cdk-jchempaint@lists.sourceforge.net * * 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.jchempaint.action; import java.awt.event.ActionEvent; import javax.swing.JOptionPane; import org.openscience.jchempaint.applet.JChemPaintEditorApplet; import org.openscience.jchempaint.application.JChemPaint; import org.openscience.cdk.renderer.selection.IChemObjectSelection; import org.openscience.jchempaint.renderer.selection.LogicalSelection; /** * Opens a new empty JChemPaintFrame. * */ public class NewAction extends JCPAction { private static final long serialVersionUID = -6710948755122145479L; /** * Opens an empty JChemPaint frame. * *@param e * Description of the Parameter */ public void actionPerformed(ActionEvent e) { if (jcpPanel.getGuistring().equals(JChemPaintEditorApplet.GUI_APPLET)) { int clear = jcpPanel.showWarning(); if (clear == JOptionPane.YES_OPTION) { jcpPanel.get2DHub().unsetRGroupHandler(); jcpPanel.get2DHub().zap(); jcpPanel.get2DHub().updateView(); jcpPanel.getRenderPanel().getRenderer().getRenderer2DModel() .setZoomFactor(1); IChemObjectSelection selection = new LogicalSelection( LogicalSelection.Type.NONE); jcpPanel.getRenderPanel().getRenderer().getRenderer2DModel() .setSelection(selection); } } else { JChemPaint.showEmptyInstance(jcpPanel.isDebug()); } } }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/action/CreateSmilesAction.java
.java
4,253
119
/* * $RCSfile$ * $Author: egonw $ * $Date: 2007-01-04 17:26:00 +0000 (Thu, 04 Jan 2007) $ * $Revision: 7634 $ * * Copyright (C) 1997-2008 Christoph Steinbeck, Stefan Kuhn * * Contact: cdk-jchempaint@lists.sourceforge.net * * 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.jchempaint.action; import java.awt.event.ActionEvent; import java.io.IOException; import java.io.StringWriter; import javax.swing.JFrame; import org.openscience.cdk.exception.CDKException; import org.openscience.cdk.interfaces.IAtomContainer; import org.openscience.cdk.interfaces.IChemModel; import org.openscience.cdk.io.SDFWriter; import org.openscience.cdk.smiles.SmilesGenerator; import org.openscience.cdk.stereo.Projection; import org.openscience.cdk.stereo.StereoElementFactory; import org.openscience.cdk.tools.manipulator.ChemModelManipulator; import org.openscience.jchempaint.GT; import org.openscience.jchempaint.dialog.TextViewDialog; /** * Creates a SMILES from the current model * */ public class CreateSmilesAction extends JCPAction { private static final long serialVersionUID = -4886982931009753342L; TextViewDialog dialog = null; JFrame frame = null; public void actionPerformed(ActionEvent e) { logger.debug("Trying to create smile: ", type); if (dialog == null) { dialog = new TextViewDialog(frame, "SMILES", null, false, 40, 2); dialog.setName("smilestextdialog"); } try { String smiles = getSmiles(jcpPanel.getChemModel()); dialog.setMessage(GT.get("Generated SMILES:"), "SMILES: " + smiles); } catch (Exception exception) { String message = GT.get("Error while creating SMILES:") + " " + exception.getMessage(); logger.error(message); logger.debug(exception); dialog.setMessage(GT.get("Error"), message); } dialog.setVisible(true); } public static String getSmiles(IChemModel model) throws CDKException, ClassNotFoundException, IOException, CloneNotSupportedException{ return getChiralSmiles(model); } public static String getMolfile(IChemModel model) throws CDKException, ClassNotFoundException, IOException, CloneNotSupportedException{ StringWriter sw = new StringWriter(); try (SDFWriter sdfw = new SDFWriter(sw)) { sdfw.write(model); } return sw.toString(); } /** * @deprecated no such thing as chiral SMILES use {@link #getSmiles} for 'a' SMILES. */ @Deprecated public static String getChiralSmiles(IChemModel model) throws CDKException, ClassNotFoundException, IOException, CloneNotSupportedException { SmilesGenerator smigen = SmilesGenerator.isomeric(); StringBuilder sb = new StringBuilder(); for(IAtomContainer container : ChemModelManipulator.getAllAtomContainers(model)) { container.setStereoElements(StereoElementFactory.using2DCoordinates(container) .interpretProjections(Projection.Haworth, Projection.Chair) .createAll()); if (sb.length() > 0) sb.append('.'); sb.append(smigen.create(container)); } return sb.toString(); } }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/action/RedoAction.java
.java
2,111
64
/* * $RCSfile$ * $Author: egonw $ * $Date: 2007-01-04 17:26:00 +0000 (Thu, 04 Jan 2007) $ * $Revision: 7634 $ * * Copyright (C) 1997-2008 Stefan Kuhn * * Contact: cdk-jchempaint@lists.sourceforge.net * * 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.jchempaint.action; import java.awt.event.ActionEvent; import org.openscience.jchempaint.renderer.selection.LogicalSelection; /** * Performce a Redo - a repeat of the last undone action * */ public class RedoAction extends JCPAction { private static final long serialVersionUID = 9219564857373463615L; /** * redoes the last action. * *@param e Description of the Parameter */ public void actionPerformed(ActionEvent e) { logger.debug("Redo triggered"); if (jcpPanel.getRenderPanel().getUndoManager().canRedo()) { jcpPanel.getRenderPanel().getUndoManager().redo(); } jcpPanel.getRenderPanel().getRenderer().getRenderer2DModel() .setSelection(new LogicalSelection(LogicalSelection.Type.NONE)); jcpPanel.updateUndoRedoControls(); jcpPanel.get2DHub().updateView(); } }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/action/JCPAction.java
.java
8,818
346
/* * $RCSfile$ * $Author: egonw $ * $Date: 2007-01-04 17:26:00 +0000 (Thu, 04 Jan 2007) $ * $Revision: 7634 $ * * Copyright (C) 1997-2008 Stefan Kuhn * * Contact: cdk-jchempaint@lists.sourceforge.net * * 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.jchempaint.action; import java.awt.Container; import java.awt.event.ActionEvent; import java.util.Hashtable; import javax.swing.AbstractAction; import javax.swing.JMenuItem; import javax.swing.JPopupMenu; import org.openscience.cdk.interfaces.IChemObject; import org.openscience.cdk.tools.ILoggingTool; import org.openscience.cdk.tools.LoggingToolFactory; import org.openscience.jchempaint.AbstractJChemPaintPanel; import org.openscience.jchempaint.JChemPaintMenuBar; import org.openscience.jchempaint.JChemPaintPopupMenu; /** * Superclass of all JChemPaint GUI actions * */ public class JCPAction extends AbstractAction { private static final long serialVersionUID = -4056416630614934238L; public final static String actionSuffix = "Action"; public final static String imageSuffix = "Image"; public final static String disabled_imageSuffix = "DisabledImage"; /** * Description of the Field */ public final static String TIPSUFFIX = "Tooltip"; /** * Description of the Field */ protected static ILoggingTool logger = LoggingToolFactory.createLoggingTool(JCPAction.class); private Hashtable<String,JCPAction> actions = null; private Hashtable<String,JCPAction> popupActions = null; /** * Description of the Field */ protected String type; /** * Description of the Field */ protected AbstractJChemPaintPanel jcpPanel = null; /** * Is this popup action assiociated with a PopupMenu or not. */ private boolean isPopupAction; /** * Constructor for the JCPAction object * *@param jcpPanel Description of the Parameter *@param type Description of the Parameter *@param isPopupAction Description of the Parameter */ public JCPAction(AbstractJChemPaintPanel jcpPanel, String type, boolean isPopupAction) { super(); if (this.actions == null) { this.actions = new Hashtable<String,JCPAction>(); } if (this.popupActions == null) { this.popupActions = new Hashtable<String,JCPAction>(); } this.type = ""; this.isPopupAction = isPopupAction; this.jcpPanel = jcpPanel; } /** * Constructor for the JCPAction object * *@param jcpPanel Description of the Parameter *@param isPopupAction Description of the Parameter */ public JCPAction(AbstractJChemPaintPanel jcpPanel, boolean isPopupAction) { this(jcpPanel, "", isPopupAction); } /** * Constructor for the JCPAction object * *@param jcpPanel Description of the Parameter */ public JCPAction(AbstractJChemPaintPanel jcpPanel) { this(jcpPanel, false); } /** * Constructor for the JCPAction object */ public JCPAction() { this(null); } /** * Sets the type attribute of the JCPAction object * *@param type The new type value */ public void setType(String type) { this.type = type; } /** * Sets the jChemPaintPanel attribute of the JCPAction object * *@param jcpPanel The new jChemPaintPanel value */ public void setJChemPaintPanel(AbstractJChemPaintPanel jcpPanel) { this.jcpPanel = jcpPanel; } /** * Is this action runnable? * *@return The enabled value */ public boolean isEnabled() { return true; } /** * Gets the popupAction attribute of the JCPAction object * *@return The popupAction value */ public boolean isPopupAction() { return isPopupAction; } /** * Sets the isPopupAction attribute of the JCPAction object * *@param isPopupAction The new isPopupAction value */ public void setIsPopupAction(boolean isPopupAction) { this.isPopupAction = isPopupAction; } /** * Dummy method. * *@param e Description of the Parameter */ public void actionPerformed(ActionEvent e) { } /** * Gets the source attribute of the JCPAction object * *@param event Description of the Parameter *@return The source value */ public IChemObject getSource(ActionEvent event) { Object source = event.getSource(); logger.debug("event source: ", source); if (source instanceof JMenuItem) { Container parent = ((JMenuItem) source).getComponent().getParent(); // logger.debug("event source parent: " + parent); if (parent instanceof JChemPaintPopupMenu) { return ((JChemPaintPopupMenu) parent).getSource(); } else if (parent instanceof JPopupMenu) { // assume that the top menu is indeed a CDKPopupMenu logger.debug("Submenu... need to recurse into CDKPopupMenu..."); while (!(parent instanceof JChemPaintPopupMenu)) { logger.debug(" Parent instanceof ", parent.getClass().getName()); if (parent instanceof JPopupMenu) { parent = ((JPopupMenu) parent).getInvoker().getParent(); } else if (parent instanceof JChemPaintMenuBar) { logger.info(" Source is MenuBar. MenuBar items don't know about the source"); return null; } else { logger.error(" Cannot get parent!"); return null; } } return ((JChemPaintPopupMenu) parent).getSource(); } } return null; } /** * Gets the action attribute of the JCPAction class * *@param jcpPanel Description of the Parameter *@param actionname Description of the Parameter *@param isPopupAction Description of the Parameter *@return The action value */ public JCPAction getAction(AbstractJChemPaintPanel jcpPanel, String actionname, boolean isPopupAction) { // make sure logger and actions are instantiated JCPAction dummy = new JCPAction(jcpPanel); // extract type String type = ""; String classname = ""; int index = actionname.indexOf("@"); if (index >= 0) { classname = actionname.substring(0, index); // FIXME: it should actually properly check wether there are more chars // than just the "@". type = actionname.substring(index + 1); } else { classname = actionname; } logger.debug("Action class: ", classname); logger.debug("Action type: ", type); // now get actual JCPAction class if (!isPopupAction && actions.containsKey(actionname)) { logger.debug("Taking JCPAction from action cache for:", actionname); return (JCPAction) actions.get(actionname); } else if (isPopupAction && popupActions.containsKey(actionname)) { logger.debug("Taking JCPAction from popup cache for:", actionname); return (JCPAction) popupActions.get(actionname); } else { logger.debug("Loading JCPAction class for:", classname); Object o = null; try { // because 'this' is static, it cannot be used to get a classloader, // therefore use logger instead o = dummy.getClass().getClassLoader().loadClass(classname).newInstance(); } catch (Exception exc) { logger.error("Could not find/instantiate class: ", classname); logger.debug(exc); return dummy; } if (o instanceof JCPAction) { JCPAction a = (JCPAction) o; a.setJChemPaintPanel(jcpPanel); if (type.length() > 0) { a.setType(type); } if (isPopupAction) { popupActions.put(actionname, a); } else { actions.put(actionname, a); } return a; } else { logger.error("Action is not a JCPAction!"); } } return dummy; } /** * Gets the action attribute of the JCPAction class * *@param jcpPanel Description of the Parameter *@param actionname Description of the Parameter *@return The action value */ public JCPAction getAction(AbstractJChemPaintPanel jcpPanel, String actionname) { return getAction(jcpPanel, actionname, false); } }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/action/EditChemObjectPropsAction.java
.java
3,094
84
/* * $RCSfile$ * $Author: egonw $ * $Date: 2007-01-04 17:26:00 +0000 (Thu, 04 Jan 2007) $ * $Revision: 7634 $ * * Copyright (C) 1997-2008 Egon Willighagen, Stefan Kuhn * * Contact: cdk-jchempaint@lists.sourceforge.net * * 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.jchempaint.action; import java.awt.event.ActionEvent; import javax.swing.JOptionPane; import org.openscience.cdk.interfaces.IAtom; import org.openscience.cdk.interfaces.IBond; import org.openscience.cdk.interfaces.IChemModel; import org.openscience.cdk.interfaces.IChemObject; import org.openscience.cdk.interfaces.IPseudoAtom; import org.openscience.cdk.interfaces.IReaction; import org.openscience.jchempaint.dialog.editor.AtomEditor; import org.openscience.jchempaint.dialog.editor.BondEditor; import org.openscience.jchempaint.dialog.editor.ChemObjectEditor; import org.openscience.jchempaint.dialog.editor.ChemObjectPropertyDialog; import org.openscience.jchempaint.dialog.editor.PseudoAtomEditor; import org.openscience.jchempaint.dialog.editor.ReactionEditor; /** * Action for triggering an edit of a IChemObject * */ public class EditChemObjectPropsAction extends JCPAction { private static final long serialVersionUID = 7123137508085454087L; public void actionPerformed(ActionEvent event) { IChemObject object = getSource(event); logger.debug("Showing object properties for: ", object); ChemObjectEditor editor = null; if (object instanceof IPseudoAtom) { editor = new PseudoAtomEditor(); } else if (object instanceof IAtom) { editor = new AtomEditor(jcpPanel.get2DHub()); } else if (object instanceof IReaction) { editor = new ReactionEditor(); } else if (object instanceof IBond) { editor = new BondEditor(jcpPanel.get2DHub(), jcpPanel.getBlockedActions()); } if (editor != null) { editor.setChemObject(object); ChemObjectPropertyDialog frame = new ChemObjectPropertyDialog(JOptionPane.getFrameForComponent(editor), jcpPanel.get2DHub(),editor); frame.pack(); frame.setVisible(true); } jcpPanel.get2DHub().updateView(); } }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/action/ExportAction.java
.java
7,683
182
/* * $RCSfile$ * $Author: egonw $ * $Date: 2007-01-04 17:26:00 +0000 (Thu, 04 Jan 2007) $ * $Revision: 7634 $ * * Copyright (C) 1997-2008 Stefan Kuhn * * Contact: cdk-jchempaint@lists.sourceforge.net * * 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.jchempaint.action; import java.awt.event.ActionEvent; import java.awt.image.RenderedImage; import java.io.File; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import javax.imageio.ImageIO; import javax.swing.JFileChooser; import javax.swing.JOptionPane; import javax.swing.filechooser.FileFilter; import org.openscience.jchempaint.GT; import org.openscience.jchempaint.JChemPaintPanel; import org.openscience.jchempaint.io.IJCPFileFilter; import org.openscience.jchempaint.io.JCPExportFileFilter; import org.openscience.jchempaint.io.JCPFileView; /** * Opens a save dialog * */ public class ExportAction extends SaveAsAction { private static final long serialVersionUID = -6748046051686998776L; private FileFilter currentFilter = null; public ExportAction() { super(); } /** * Constructor for the ExportAction object * *@param jcpPanel * the parent Panel *@param isPopupAction * true if this is a popup action */ public ExportAction(JChemPaintPanel jcpPanel, boolean isPopupAction) { super(jcpPanel, isPopupAction); } /** * Exports the canvas as an image. * *@param event * the action event that triggered this action. */ public void actionPerformed(ActionEvent event) { JFileChooser chooser = new JFileChooser(); chooser.setCurrentDirectory(this.jcpPanel.getCurrentWorkDirectory()); chooser.setAcceptAllFileFilterUsed(false); JCPExportFileFilter.addChoosableFileFilters(chooser); if (currentFilter != null) { { for(int i=0;i<chooser.getChoosableFileFilters().length;i++){ if(chooser.getChoosableFileFilters()[i].getDescription().equals(currentFilter.getDescription())) chooser.setFileFilter(chooser.getChoosableFileFilters()[i]); } } } chooser.setFileView(new JCPFileView()); int returnVal = chooser.showSaveDialog(jcpPanel); currentFilter = chooser.getFileFilter(); if (returnVal == JFileChooser.APPROVE_OPTION) { if(!(currentFilter instanceof IJCPFileFilter)){ JOptionPane.showMessageDialog(jcpPanel, GT.get("Please chose a file type!"), GT.get("No file type chosen"), JOptionPane.INFORMATION_MESSAGE); return; }else{ type = ((JCPExportFileFilter) currentFilter).getType(); File outFile = new File( chooser.getSelectedFile().getAbsolutePath()); String fileName = outFile.toString(); if (!fileName.endsWith("."+type)) { fileName += "."+type; outFile = new File(fileName); } if (outFile.exists()) { String message = GT.get("File already exists. Do you want to overwrite it?"); String title = GT.get("File already exists"); int value = JOptionPane.showConfirmDialog(jcpPanel, message, title, JOptionPane.YES_NO_OPTION); if (value == JOptionPane.NO_OPTION) { return; } } if (type.equals(JCPExportFileFilter.svg)) { try (FileWriter writer = new FileWriter(outFile)) { writer.write(this.jcpPanel.getSVGString()); JOptionPane.showMessageDialog(jcpPanel, GT.get("Exported image to {0}", outFile.getName())); return; } catch (IOException e) { String error = GT.get("Problem exporting to SVG"); JOptionPane.showMessageDialog(jcpPanel, error); return; } } else if (type.equals(JCPExportFileFilter.pdf)) { try (FileOutputStream writer = new FileOutputStream(outFile)){ writer.write(this.jcpPanel.getPDF()); JOptionPane.showMessageDialog(jcpPanel, GT.get("Exported image to {0}", outFile.getName())); return; } catch (IOException e) { String error = GT.get("Problem exporting to PDF"); JOptionPane.showMessageDialog(jcpPanel, error); return; } } else { RenderedImage image = (RenderedImage) this.jcpPanel .takeSnapshot(); try { String imageIOType; if (type.equals(JCPExportFileFilter.bmp)) { imageIOType = "BMP"; } else if (type.equals(JCPExportFileFilter.jpg)) { imageIOType = "JPEG"; } else { imageIOType = "PNG"; } boolean succeeded = ImageIO.write(image, imageIOType, outFile); if (succeeded) { JOptionPane.showMessageDialog(jcpPanel, GT.get("Exported image to {0}", outFile.getName())); return; } else { // no writer of type imageIOType found ImageIO.write(image, "PNG", outFile); JOptionPane.showMessageDialog(jcpPanel, GT.get("Exported image to {0} as PNG, since {1} could not be written", new String[]{outFile.getName(), type})); return; } } catch (IOException ioe) { ioe.printStackTrace(); JOptionPane.showMessageDialog(jcpPanel, GT.get("Problem exporting image")); } } } } else if (returnVal == JFileChooser.CANCEL_OPTION) { return; } } }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/controller/UndoAdapter.java
.java
2,029
63
/* $RCSfile$ * $Author: egonw $ * $Date: 2008-09-10 08:13:15 +0200 (Wed, 10 Sep 2008) $ * $Revision: 12257 $ * * Copyright (C) 2005-2007 The Chemistry Development Kit (CDK) project * * Contact: cdk-devel@lists.sourceforge.net * * 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. * * 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.jchempaint.controller; import javax.swing.event.UndoableEditEvent; import javax.swing.event.UndoableEditListener; import javax.swing.undo.UndoManager; import javax.swing.undo.UndoableEdit; /** * An undo adapter for updating the state of the undo components according to * the new state of the undo history list. Is registered as a listener to the * undoSupport which is receiving the undo/redo events. * * @author tohel * @cdk.module control * @cdk.githash */ public class UndoAdapter implements UndoableEditListener { private UndoManager undoManager; /** * @param undoManager * The undoManager handling the undo/redo history list */ public UndoAdapter(UndoManager undoManager) { this.undoManager = undoManager; } /* * (non-Javadoc) * * @see javax.swing.event.UndoableEditListener#undoableEditHappened(javax.swing.event.UndoableEditEvent) */ public void undoableEditHappened(UndoableEditEvent arg0) { UndoableEdit edit = arg0.getEdit(); undoManager.addEdit(edit); } }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/controller/PhantomAtomGenerator.java
.java
2,957
76
/* $Revision: $ $Author: $ $Date$ * * Copyright (C) 2009 Arvid Berg <goglepox@users.sourceforge.net> * * Contact: cdk-devel@lists.sourceforge.net * * 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 I ask is that proper credit is given for my 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.jchempaint.controller; import org.openscience.cdk.interfaces.IAtom; import org.openscience.cdk.interfaces.IAtomContainer; import org.openscience.cdk.interfaces.IBond; import org.openscience.cdk.interfaces.IChemObject; import org.openscience.cdk.interfaces.IElement; import org.openscience.cdk.renderer.RendererModel; import org.openscience.cdk.renderer.elements.ElementGroup; import org.openscience.cdk.renderer.elements.IRenderingElement; import org.openscience.cdk.renderer.generators.BasicAtomGenerator; import org.openscience.cdk.renderer.generators.BasicBondGenerator; import org.openscience.jchempaint.renderer.JChemPaintRendererModel; import java.awt.*; /** * Draws the null-valent phantom atoms in ControllerHub. * * @cdk.module controlbasic */ public class PhantomAtomGenerator extends BasicAtomGenerator { ControllerHub hub; public PhantomAtomGenerator() { } public void setControllerHub(ControllerHub hub) { this.hub = hub; } @Override public IRenderingElement generate(IAtomContainer ac, RendererModel model) { JChemPaintRendererModel jcpModel = (JChemPaintRendererModel) model; if (hub == null || hub.getPhantoms() == null) return new ElementGroup(); final ElementGroup group = new ElementGroup(); // this is really only for showing individual atoms "in hand" for (IAtom atom : hub.getPhantoms().atoms()) { if (atom.getBondCount() > 1 || atom.getBondCount() == 1 && atom.getAtomicNumber() == IElement.C || atom.is(IChemObject.VISITED)) continue; IRenderingElement element = generateElement(atom, 1, jcpModel); group.add(element); } return group; } }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/controller/ChangeSingleElectronModule.java
.java
3,223
98
/* $Revision: 7636 $ $Author: nielsout $ $Date: 2007-01-04 18:46:10 +0100 (Thu, 04 Jan 2007) $ * * Copyright (C) 2007 Niels Out <nielsout@users.sf.net> * Copyright (C) 2008 Stefan Kuhn (undo redo) * Copyright (C) 2008 Arvid Berg <goglepox@users.sf.net> * * Contact: cdk-devel@lists.sourceforge.net * * 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 I ask is that proper credit is given for my 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.jchempaint.controller; import javax.vecmath.Point2d; import org.openscience.cdk.interfaces.IAtom; import org.openscience.jchempaint.AtomBondSet; /** * Changes (Increases or Decreases) single electrons of an atom * * @cdk.svnrev $Revision: 9162 $ * @cdk.module controlbasic */ public class ChangeSingleElectronModule extends ControllerModuleAdapter { private boolean add = true; private String ID; /** * Constructor for the ChangeSingleElectronModule. * * @param chemModelRelay The current chemModelRelay. * @param add true=single electrons get added, * false=single electrons get removed */ public ChangeSingleElectronModule(IChemModelRelay chemModelRelay, boolean add) { super(chemModelRelay); this.add = add; } /* (non-Javadoc) * @see org.openscience.cdk.controller.ControllerModuleAdapter#mouseClickedDown(javax.vecmath.Point2d) */ public void mouseClickedDown(Point2d worldCoord, int modifiers) { AtomBondSet selectedAC = getSelectAtomBondSet(worldCoord); if(selectedAC == null) return; for(IAtom atom:selectedAC.atoms()) { if(add){ chemModelRelay.addSingleElectron(atom); }else{ chemModelRelay.removeSingleElectron(atom); } } } /* (non-Javadoc) * @see org.openscience.cdk.controller.IControllerModule#getDrawModeString() */ public String getDrawModeString() { if (add) return "Add Single Electron"; else return "Remove Single Electron"; } /* (non-Javadoc) * @see org.openscience.cdk.controller.IControllerModule#getID() */ public String getID() { return ID; } /* (non-Javadoc) * @see org.openscience.cdk.controller.IControllerModule#setID(java.lang.String) */ public void setID(String ID) { this.ID=ID; } }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/controller/IChangeModeListener.java
.java
1,665
44
/* $Revision: 7636 $ $Author: egonw $ $Date: 2007-01-04 18:46:10 +0100 (Thu, 04 Jan 2007) $ * * Copyright (C) 2009 Stefan Kuhn <stefan.kuhn@ebi.ac.uk> * * Contact: cdk-devel@lists.sourceforge.net * * 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 I ask is that proper credit is given for my 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.jchempaint.controller; /** * This listener can be registered onto the ControllerHub to get * nofified if the activeDrawModule changes. * * @cdk.svnrev $Revision: 9162 $ * @cdk.module controlbasic */ public interface IChangeModeListener { /** * Called if the activeDrawModule changes. * * @param newActiveModule The new activeDrawModule. */ public void modeChanged(IControllerModule newActiveModule); }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/controller/CDKPopupMenu.java
.java
2,120
64
/* $RCSfile$ * $Author$ * $Date$ * $Revision$ * * Copyright (C) 2003-2007 The Chemistry Development Kit (CDK) project * * Contact: cdk-devel@lists.sourceforge.net * * 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 I ask is that proper credit is given for my 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.jchempaint.controller; import javax.swing.JPopupMenu; import org.openscience.cdk.interfaces.IChemObject; /** * Basically, identical to the JPopupMenu class, except that this menu * can also contain the source for which it was popped up. * * <p>IMPORTANT: The very nature of this design can lead to race conditions. * It would be better that the Event passed to the popup menu would define * the IChemObject source. * * @author Egon Willighagen <egonw@sci.kun.nl> * @cdk.created 2003-07-36 * @cdk.require swing * @cdk.module controlold * @cdk.githash */ public class CDKPopupMenu extends JPopupMenu { private static final long serialVersionUID = -235498895062628065L; private IChemObject source; public void setSource(IChemObject object) { this.source = object; } public IChemObject getSource() { return this.source; } }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/controller/ConjugationTools.java
.java
12,125
351
/* * Copyright (C) 2025 John Mayfield * * 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 I ask is that proper credit is given for my 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.jchempaint.controller; import org.openscience.cdk.interfaces.IAtom; import org.openscience.cdk.interfaces.IAtomContainer; import org.openscience.cdk.interfaces.IBond; import org.openscience.cdk.interfaces.IChemObject; import java.util.List; import static org.openscience.cdk.interfaces.IBond.Order.DOUBLE; import static org.openscience.cdk.interfaces.IBond.Order.SINGLE; /** * Utilities for pushing bond orders around a molecule, for example, * alternating Kekulé/tautomeric forms etc. * * @author john */ public class ConjugationTools { /** * Check if two bonds are alternating, that is one is single and the other * is double. * * @param a first bond * @param b second bond * @return one bond is single, one bond is double */ private static boolean isAlternating(IBond a, IBond b) { return a.getOrder() == SINGLE && b.getOrder() == DOUBLE || a.getOrder() == DOUBLE && b.getOrder() == SINGLE; } /** * A depth-limited depth-first search that find alternating cycle of bonds. * * @param bonds (output) - the path found * @param root the root atom to find a cycle to * @param atom the current atom in the search * @param prev the previous bond * @param limit remaining limit on the search (decrements with each descent) * @return a path was found (result stored in bonds param) or not */ private static boolean searchAlternatingCycle(List<IBond> bonds, IAtom root, IAtom atom, IBond prev, int limit) { if (atom.equals(root) && isAlternating(prev, bonds.get(0))) { return true; } if (limit == 0) return false; for (IBond bond : atom.bonds()) { if (bond.equals(prev)) continue; if (bond.is(IChemObject.VISITED)) continue; if (isAlternating(prev, bond)) { bond.set(IChemObject.VISITED); bonds.add(bond); if (searchAlternatingCycle(bonds, root, bond.getOther(atom), bond, limit - 1)) return true; bonds.remove(bonds.size() - 1); bond.clear(IChemObject.VISITED); } } return false; } /** * Clear all the visit flags. * * @param container the container */ private static void clearBondVisitFlags(IAtomContainer container) { for (IBond b : container.bonds()) b.clear(IChemObject.VISITED); } /** * Find an alternating path of bonds (single,double,single,double,etc) that * starts with the provided bond. If no such path exists (or at least not * one short enough to be considered reasonable) false is returned. * * @param bonds (output) - the path found * @return a path was found (result stored in bonds param) or not found */ public static boolean findAlternating(List<IBond> bonds, IBond bond) { bonds.clear(); clearBondVisitFlags(bond.getContainer()); // iteratively deepening search, most cases will be six member rings // so we check those first bond.set(IChemObject.VISITED); bonds.add(bond); if (searchAlternatingCycle(bonds, bond.getBegin(), bond.getEnd(), bond, 6)) return true; if (searchAlternatingCycle(bonds, bond.getBegin(), bond.getEnd(), bond, 10)) return true; if (searchAlternatingCycle(bonds, bond.getBegin(), bond.getEnd(), bond, 14)) return true; if (searchAlternatingCycle(bonds, bond.getBegin(), bond.getEnd(), bond, 34)) return true; bond.clear(IChemObject.VISITED); return false; } /** * Possible tautomer roles. */ private enum TautRole { CanAcceptH, CanDonateH, Other; /** * Can the opposite role, e.g. Donor opposite is Acceptor, * Acceptor opposite is Donor. Other is Other. * @return the opposite role */ TautRole flip() { switch (this) { case CanDonateH: return CanAcceptH; case CanAcceptH: return CanDonateH; default: return Other; } } } /** * Safely access the atom's implicit hydrogen count. * @param atom the atom * @return the implicit H count (or 0 if null) */ private static int safeImplH(IAtom atom) { return atom.getImplicitHydrogenCount() != null ? atom.getImplicitHydrogenCount() : 0; } /** * Safely access the atom's charge. * @param atom the atom * @return the charge (or 0 if null) */ private static int charge(IAtom atom) { return atom.getFormalCharge() != null ? atom.getFormalCharge() : 0; } private static int packedBondInfo(IAtom atom) { int result = safeImplH(atom); for (IBond bond : atom.bonds()) { switch (bond.getOrder()) { case SINGLE: result += 0x0001; break; case DOUBLE: result += 0x0010; break; case TRIPLE: result += 0x0100; break; default: result += 0x1000; break; } } return result; } /** * Simple but efficient tautomer role determination. * @param atom the atom to type * @return the role */ private static TautRole getType(IAtom atom) { final int h = safeImplH(atom); final int q = charge(atom); switch (atom.getAtomicNumber()) { case IAtom.N: case IAtom.P: case IAtom.As: // *=NH if (h == 1 && q == 0 && packedBondInfo(atom) == 0x11) return TautRole.CanAcceptH; // *-NH2 if (h == 2 && q == 0 && packedBondInfo(atom) == 0x3) return TautRole.CanDonateH; // *-NH-* if (h == 1 && q == 0 && packedBondInfo(atom) == 0x3) return TautRole.CanDonateH; // *-N=* if (h == 0 && q == 0 && packedBondInfo(atom) == 0x11) return TautRole.CanAcceptH; break; case IAtom.O: case IAtom.S: case IAtom.Se: case IAtom.Te: // *-OH if (h == 1 && q == 0 && packedBondInfo(atom) == 0x2) return TautRole.CanDonateH; // *=O if (h == 0 && q == 0 && packedBondInfo(atom) == 0x10) return TautRole.CanAcceptH; break; } return TautRole.Other; } /** * A depth-limited depth-first search that find alternating path to an atom * of a given tautomer role. * * @param bonds (output) - the path found * @param atom the current atom in the search * @param prev the previous bond * @param role the role to find * @param limit remaining limit on the search (decrements with each descent) * @return a path was found (result stored in bonds param) or not */ private static boolean searchForRole(List<IBond> bonds, IAtom atom, IBond prev, TautRole role, int limit) { if (getType(atom) == role && isAlternating(prev, bonds.get(0))) { return true; } if (limit == 0) return false; for (IBond bond : atom.bonds()) { if (bond.equals(prev)) continue; if (bond.is(IChemObject.VISITED)) continue; if (isAlternating(prev, bond)) { bond.set(IChemObject.VISITED); bonds.add(bond); if (searchForRole(bonds, bond.getOther(atom), bond, role, limit - 1)) return true; bonds.remove(bonds.size() - 1); bond.clear(IChemObject.VISITED); } } return false; } /** * Find a tautomeric shift path between hetero atoms. Given a bond of which * one atom is a hydrogen donor or acceptor it attempts to find a path * (1,3-, 1,5-, 1,7, 1,9- or 1,11-) between that atom and a counter role * (e.g. starting at a donor we need to find an acceptor). * * @param bonds the found shift path * @param bond the bond to start from (one end should be a H donor/acceptor) * @return a shift was found */ public static boolean findTautomerShift(List<IBond> bonds, IBond bond) { bonds.clear(); TautRole begType = getType(bond.getBegin()); TautRole endType = getType(bond.getEnd()); // one of them must be a donor or acceptor, if they are both type // 'Other' or neither type 'Other' then we can't do anything if ((begType == TautRole.Other) == (endType == TautRole.Other)) return false; clearBondVisitFlags(bond.getContainer()); // iteratively deepening search, most cases will be six member rings // so we check those first bond.set(IChemObject.VISITED); bonds.add(bond); if (begType != TautRole.Other) { // 1-5, and 1-7 shifts if (searchForRole(bonds, bond.getEnd(), bond, begType.flip(), 7)) { return true; } // 1-9, and 1-11 shifts if (searchForRole(bonds, bond.getEnd(), bond, begType.flip(), 11)) { return true; } } else { // 1-5, and 1-7 shifts if (searchForRole(bonds, bond.getBegin(), bond, endType.flip(), 7)) { return true; } // 1-9, and 1-11 shifts if (searchForRole(bonds, bond.getBegin(), bond, endType.flip(), 11)) { return true; } } bond.clear(IChemObject.VISITED); return false; } }
Java