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
core/src/main/java/org/openscience/jchempaint/controller/IViewEventRelay.java
.java
1,358
36
/* $Revision$ $Author$ $Date$ * * Copyright (C) 2007 Egon Willighagen <egonw@users.lists.sf> * * 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; /** * * @cdk.module control */ public interface IViewEventRelay { public abstract void updateView(); }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/controller/IAtomBondEdits.java
.java
3,808
80
/* * 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 java.util.Collection; import javax.vecmath.Point2d; import javax.vecmath.Vector2d; import org.openscience.cdk.interfaces.IAtom; import org.openscience.cdk.interfaces.IAtomContainer; import org.openscience.cdk.interfaces.IBond; import org.openscience.jchempaint.AtomBondSet; import org.openscience.jchempaint.controller.IChemModelRelay.Direction; /** * Interface for edit methods currently used by edit modules but should * be replaced by IEdit commands. * @author Arvid * @cdk.module control */ public interface IAtomBondEdits { /* Editing actions for atoms */ public AtomBondSet removeAtom(IAtom atom); public AtomBondSet removeAtomWithoutUndo(IAtom atom); public IAtom addAtom(String element, Point2d worldcoord, boolean makePseudoAtom); public IAtom addAtomWithoutUndo(String element, Point2d worldcoord, boolean makePseudoAtom); public IAtom addAtom(String element, IAtom atom, boolean makePseudoAtom); public IAtom addAtomWithoutUndo(String element, IAtom atom, boolean makePseudoAtom); public void moveToWithoutUndo(IAtom atom, Point2d point); public void moveTo(IAtom atom, Point2d point); public void moveTo(IAtom atom, Point2d from, Point2d to, boolean undoable); public void moveBy(Collection<IAtom> atoms, Vector2d move, Vector2d totalmove); public void setSymbol(IAtom atom, String symbol); public void setCharge(IAtom atom, int charge); public void setMassNumber(IAtom atom, int charge); public void setImplicitHydrogenCount(IAtom atom, int intValue); public void replaceAtom(IAtom atomnew, IAtom atomold); public void addSingleElectron(IAtom atom); public void removeSingleElectron(IAtom atom); public void updateAtoms(IAtomContainer container, Iterable<IAtom> atoms); public void updateAtom(IAtom atom); public void updateAtoms(IBond bond); public void mergeMolecules(Vector2d movedDistance); /* Editing actions for bonds */ public IBond addBond(IAtom fromAtom, IAtom toAtom); public void removeBondWithoutUndo(IBond bond); public void removeBond(IBond bond); public void moveToWithoutUndo(IBond bond, Point2d point); public void moveTo(IBond bond, Point2d point); public void changeBond(IBond bond, IBond.Order order, IBond.Display stereo); public void addNewBond(Point2d worldCoordinate, boolean makePseudoAtom); public void cycleBondValence(IBond bond); public void cycleBondValence(IBond bond, IBond.Order order); public void makeBondStereo(IBond bond, Direction desiredDirection); public IBond makeNewStereoBond(IAtom atom, Direction desiredDirection); }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/controller/IChemModelEventRelayHandler.java
.java
2,179
59
/* $Revision: 7636 $ $Author: nielsout $ $Date: 2007-09-02 11:46:10 +0100 (su, 02 sep 2007) $ * * Copyright (C) 2009 Egon Willighagen <egonw@users.lists.sf> * * 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; /** * @cdk.module control */ public interface IChemModelEventRelayHandler { /** * Signals that the connectivity table of the structure has changed, for * example, an atom or bond was added or removed. This implies that the * coordinates have changed too. */ public void structureChanged(); /** * Signals that the atom or bond properties have changed, like atom symbol * or bond order. This excludes coordinate changes, for which * {@link #coordinatesChanged()} is used. */ public void structurePropertiesChanged(); /** * Signals that the coordinates of the structure or the coordinates * boundaries of the structure have changed. */ public void coordinatesChanged(); /** * Signals that a selection was added, removed or changed. */ public void selectionChanged(); public void zoomChanged(); }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/controller/IChemModelRelay.java
.java
10,917
302
/* $Revision: 7636 $ $Author: nielsout $ $Date: 2007-09-02 11:46:10 +0100 (su, 02 sep 2007) $ * * Copyright (C) 2007 Egon Willighagen <egonw@users.lists.sf> * * 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 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 License for more details. * * You should have received a copy of the GNU Lesser General 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 java.io.IOException; import java.util.Collection; import java.util.Map; import javax.vecmath.Point2d; import org.openscience.cdk.exception.CDKException; 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.IRing; import org.openscience.cdk.interfaces.IBond.Order; import org.openscience.cdk.interfaces.IBond.Stereo; import org.openscience.jchempaint.AtomBondSet; import org.openscience.jchempaint.controller.undoredo.IUndoRedoFactory; import org.openscience.jchempaint.controller.undoredo.UndoRedoHandler; import org.openscience.jchempaint.renderer.IRenderer; import org.openscience.cdk.renderer.selection.IChemObjectSelection; import org.openscience.jchempaint.renderer.selection.IncrementalSelection; import org.openscience.jchempaint.rgroups.RGroupHandler; /** * @cdk.module control */ public interface IChemModelRelay extends IAtomBondEdits { enum Direction { UP, DOWN, UNDEFINED, EZ_UNDEFINED }; enum Scale { Horizontal, Vertical, Both } enum CursorType { DEFAULT, MOVE, ROTATE, RESIZE_N, RESIZE_NE, RESIZE_E, RESIZE_SE, RESIZE_S, RESIZE_SW, RESIZE_W, RESIZE_NW; boolean isResize() { switch (this) { case RESIZE_N: case RESIZE_NE: case RESIZE_E: case RESIZE_SE: case RESIZE_S: case RESIZE_SW: case RESIZE_W: case RESIZE_NW: return true; default: return false; } } Scale getScaleDirection() { switch (this) { case RESIZE_N: case RESIZE_S: return Scale.Vertical; case RESIZE_E: case RESIZE_W: return Scale.Horizontal; case RESIZE_NE: case RESIZE_SE: case RESIZE_SW: case RESIZE_NW: return Scale.Both; default: throw new IllegalStateException(); } } }; /* Interaction*/ IControllerModel getController2DModel(); IRenderer getRenderer(); IChemModel getIChemModel(); void setChemModel(IChemModel model); IAtom getClosestAtom(Point2d worldCoord); IBond getClosestBond(Point2d worldCoord); /** * Get the closest atom that is in 'range' (highlight distance) of the * atom 'atom', ignoring all the atoms in the collection 'toIgnore'. * * @param toIgnore the atoms to ignore in the search * @param atom the atom to use as the base of the search * @return the closest atom that is in highlight distance */ IAtom getAtomInRange(Collection<IAtom> toIgnore, IAtom atom); /** * Find the atom closest to 'atom', exclusind the atom itself. * * @param atom the atom around which to search * @return the nearest atom other than 'atom' */ IAtom getClosestAtom(IAtom atom); void updateView(); /** * Sets the active controller module. * * @param activeDrawModule The new controller module.^M */ void setActiveDrawModule(IControllerModule activeDrawModule); /** * Fills an IncrementalSelection and sets it as selction in the model. * * @param selection The selection to fill and to set. */ void select(IncrementalSelection selection); /** * Sets a selection as selection in the model. * * @param selection The selection to set. */ void select(IChemObjectSelection selection); /* Event model */ void setEventHandler(IChemModelEventRelayHandler handler); void fireZoomEvent(); void fireStructureChangedEvent(); /** * Adds an temporary atom which might be cleared later, when the final * atom is added. Controllers can use this to draw temporary atoms, for * example while drawing new bonds. * * @param atom atom to add as phantom */ void addPhantomAtom(IAtom atom); /** * Sets a phantom = temporary arrow, e. g. for reaction drawing. * * @param start The start point. * @param end The end point (if startt and end are null, no arrow is drawn). */ void setPhantomArrow(Point2d start, Point2d end); /** * Gets start and end for a phantom arrow. * * @return [0]=start, [1]=end. Can be null, nothing to be done then. */ Point2d[] getPhantomArrow(); /** * Adds an temporary bond which might be cleared later, when the final * bond is added. Controllers can use this to draw temporary bonds, for * example while drawing new bonds. * * @param bond bond to add as phantom */ void addPhantomBond(IBond bond); /** * Replaces the phantom bonds/atoms with this atomcontainer. * * @param phantoms The new phantoms */ void setPhantoms(IAtomContainer phantoms); /** * Sets a text to be rendered as a phantom at a certain position. * * @param text The text. * @param position The position. */ void setPhantomText(String text, Point2d position); /** * Returns an IAtomContainer containing all phantom atoms and bonds. */ IAtomContainer getPhantoms(); /** * Deletes all temporary atoms. */ void clearPhantoms(); /* Editing actions for the complete model */ void updateImplicitHydrogenCounts(); void zap(); IRing addRing(int size, Point2d worldcoord, boolean undoable); /** * Adds a ring to an atom. * * @param atom The atom to attach to. * @param size The size of the new ring. * @param phantom Should this become a phantom bond or real one? * @return The new bond. */ IRing addRing(IAtom atom, int size, boolean phantom); /** * Adds a phenyl ring to an atom. * * @param atom The atom to attach to. * @param phantom Should this become a phantom bond or real one? * @return The new bond. */ IRing addPhenyl(IAtom atom, int ringSize, boolean phantom); IRing addPhenyl(Point2d worldcoord, int ringSize, boolean phantom); /** * Adds a ring to an bond. * * @param bond The bond to attach to. * @param size The size of the new ring. * @param phantom Should this become a phantom bond or real one? * @return The new bond. */ IRing addRing(IBond bond, int size, boolean phantom); /** * Adds a phenyl ring to an atom. * * @param bond The bond to attach to. * @param phantom Should this become a phantom bond or real one? * @return The new bond. */ IRing addPhenyl(IBond bond, int size, boolean phantom); /** * Adds a fragment to the chemmodel. * * @param toPaste The fragment to add. * @param moleculeToAddTo If null, a new molecule in the setOfMolecules will be made, if not null, it will be added to moleculeToAddTo. * @param toRemove If not null, this atomcontainer will be added to moleculeToAddTo as well and removed from chemmodel (this is needed if a merge happens). */ void addFragment(AtomBondSet toPaste, IAtomContainer moleculeToAddTo, IAtomContainer toRemove); AtomBondSet deleteFragment(AtomBondSet toDelete); void cleanup(); void flip(boolean horizontal); void invertStereoInSelection(); /** * Adjusts all bond orders to fit valency */ void adjustBondOrders() throws IOException, ClassNotFoundException, CDKException; /** * Sets all bond order to single */ void resetBondOrders(); void clearValidation(); void makeAllImplicitExplicit(); void makeAllExplicitImplicit(); // void cleanupSelection(Selector sectionIdentifier); IUndoRedoFactory getUndoRedoFactory(); UndoRedoHandler getUndoRedoHandler(); IBond addBond(IAtom fromAtom, IAtom toAtom, IBond.Display display, Order order); IBond addBond(IAtom fromAtom, IAtom toAtom, IBond.Display display); IAtom addAtomWithoutUndo(String drawElement, IAtom newAtom, IBond.Display display, Order order, boolean makePseudoAtom, boolean phantom); IAtom addAtomWithoutUndo(String drawElement, IAtom newAtom, IBond.Display stereo, Order order, boolean makePseudoAtom); void setValence(IAtom atom, Integer newValence); IAtom addAtom(String drawElement, int drawIsotopeNumber, Point2d start, boolean makePseudoAtom); void removeBondAndLoneAtoms(IBond bond); IAtom convertToPseudoAtom(IAtom newAtom, String drawElement); void setCursor(CursorType type); void setCursor(int cursor); int getCursor(); IChemModel getChemModel(); RGroupHandler getRGroupHandler(); void setRGroupHandler(RGroupHandler rGroupHandler); void unsetRGroupHandler(); void rotate(Map<IAtom,Point2d> atoms, Point2d center, double angle); void scale(Map<IAtom,Point2d> atoms, Point2d center, double dist, Scale scale); }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/controller/AddBondDragModule.java
.java
13,269
308
/* * Copyright (C) 2009 Arvid Berg <goglepox@users.sourceforge.net> * Copyright (C) 2025 John Mayfield * * 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 javax.vecmath.Vector2d; import org.openscience.cdk.config.Elements; 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.IChemObjectBuilder; import org.openscience.cdk.interfaces.IPseudoAtom; import org.openscience.cdk.tools.manipulator.ChemModelManipulator; import org.openscience.jchempaint.AtomBondSet; import org.openscience.jchempaint.controller.IChemModelRelay.Direction; import org.openscience.jchempaint.controller.undoredo.IUndoRedoFactory; import org.openscience.jchempaint.controller.undoredo.IUndoRedoable; import org.openscience.jchempaint.controller.undoredo.UndoRedoHandler; import org.openscience.jchempaint.renderer.Renderer; import org.openscience.jchempaint.renderer.selection.SingleSelection; /** * Adds a bond at direction that is dragged. * * @cdk.module controlbasic */ public class AddBondDragModule extends ControllerModuleAdapter { Point2d lastMouseMove; Point2d start; Point2d dest; IAtom source = null;// either atom at mouse down or new atom IAtom merge = null; boolean newSource = false; boolean isBond = false; private double bondLength; private String id; IBond.Display displayForNewBond; IBond.Order orderForNewBond; //if this is true, initally a bond will be drawn, if not, just an atom boolean makeInitialBond; /** * Constructor for the AddBondDragModule. * * @param chemModelRelay The current chemModelRelay. * @param display If a new bond is formed, which stereo specification should it have? * @param makeInitialBond true=click on empty place gives bond, false=gives atom. */ public AddBondDragModule(IChemModelRelay chemModelRelay, IBond.Order order, IBond.Display display, boolean makeInitialBond, String id) { super(chemModelRelay); this.orderForNewBond = order; this.displayForNewBond = display; this.makeInitialBond = makeInitialBond; this.id = id; } public AddBondDragModule(IChemModelRelay chemModelRelay, IBond.Display display, boolean makeInitialBond) { this(chemModelRelay, IBond.Order.SINGLE, display, makeInitialBond, null); } public AddBondDragModule(IChemModelRelay chemModelRelay, IBond.Order order, boolean makeInitialBond, String id) { this(chemModelRelay, order, IBond.Display.Solid, makeInitialBond, id); } public AddBondDragModule(IChemModelRelay chemModelRelay, IBond.Order orderForNewBond, boolean makeInitialBond) { this(chemModelRelay, orderForNewBond, makeInitialBond, null); } private IChemObjectBuilder getBuilder() { return chemModelRelay.getIChemModel().getBuilder(); } @Override public void mouseMove(Point2d worldCoord) { lastMouseMove = worldCoord; IAtom closestAtom = chemModelRelay.getClosestAtom(worldCoord); IBond closestBond = chemModelRelay.getClosestBond(worldCoord); IChemObject singleSelection = getHighlighted(worldCoord, closestAtom, closestBond); chemModelRelay.clearPhantoms(); if (singleSelection instanceof IAtom) { isBond = false; source = (IAtom) singleSelection; chemModelRelay.addAtomWithoutUndo(chemModelRelay.getController2DModel().getDrawElement(), source, displayForNewBond, orderForNewBond, chemModelRelay.getController2DModel().getDrawPseudoAtom(), true); } } @Override public void mouseClickedDown(Point2d worldCoord, int modifiers) { lastMouseMove = null; start = null; dest = null; source = null; merge = null; isBond = false; newSource = false; bondLength = Renderer.calculateBondLength(chemModelRelay.getIChemModel()); // in case we are starting on an empty canvas if (bondLength == 0 || Double.isNaN(bondLength)) bondLength = 1.5; start = new Point2d(worldCoord); IAtom closestAtom = chemModelRelay.getClosestAtom(worldCoord); IBond closestBond = chemModelRelay.getClosestBond(worldCoord); IChemObject singleSelection = getHighlighted(worldCoord, closestAtom, closestBond); if (singleSelection == null || singleSelection instanceof IAtom) { isBond = false; source = (IAtom) getHighlighted(worldCoord, closestAtom); if (source == null) { String symbol = chemModelRelay.getController2DModel().getDrawElement(); if (Elements.ofString(symbol) != Elements.Unknown) source = getBuilder().newInstance(IAtom.class, symbol, start); else source = getBuilder().newInstance(IPseudoAtom.class, symbol, start); newSource = true; } else { // Take the true (x,y) of the atom, not the click point // otherwise it's very hard to draw a regular ring start = closestAtom.getPoint2d(); } } else if (singleSelection instanceof IBond) { if (displayForNewBond == IBond.Display.Solid) { chemModelRelay.cycleBondValence((IBond) singleSelection, orderForNewBond); } else { chemModelRelay.changeBond((IBond) singleSelection, orderForNewBond, displayForNewBond); } setSelection(new SingleSelection<IChemObject>(singleSelection)); isBond = true; } } @Override public void mouseDrag(Point2d worldCoordFrom, Point2d worldCoordTo, int modifiers) { lastMouseMove = null; if (isBond) return; IAtom closestAtom = chemModelRelay.getClosestAtom(worldCoordTo); chemModelRelay.getRenderer().getRenderer2DModel().getMerge().remove(merge); merge = (IAtom) getHighlighted(worldCoordTo, closestAtom); chemModelRelay.clearPhantoms(); if (start.distance(worldCoordTo) < getHighlightDistance()) { // clear phantom merge = null; dest = null; } else if (merge != null) { // set bond chemModelRelay.addPhantomAtom(source); chemModelRelay.addPhantomAtom(merge); chemModelRelay.addPhantomBond(getBuilder().newInstance(IBond.class, source, merge, orderForNewBond, displayForNewBond)); dest = null; //we also remember the merge atom in the merges in the rendererModel, //in case an application uses these. chemModelRelay.getRenderer().getRenderer2DModel().getMerge().put(merge, merge); } else { dest = roundAngle(start, worldCoordTo, bondLength); IAtom atom; String symbol = chemModelRelay.getController2DModel().getDrawElement(); if (Elements.ofString(symbol) != Elements.Unknown) atom = getBuilder().newInstance(IAtom.class, symbol, dest); else atom = getBuilder().newInstance(IPseudoAtom.class, symbol, start); IBond bond = getBuilder().newInstance(IBond.class, source, atom, orderForNewBond, displayForNewBond); chemModelRelay.addPhantomAtom(source); chemModelRelay.addPhantomAtom(atom); chemModelRelay.addPhantomBond(bond); // update phantom } chemModelRelay.updateView(); } public static Point2d roundAngle(Point2d s, Point2d d, double bondLength) { Vector2d v = new Vector2d(); v.sub(d, s); double rad = Math.atan2(v.y, v.x); double deg = Math.toDegrees(rad); deg = Math.round(deg / 15) * 15; rad = Math.toRadians(deg); v.x = bondLength * Math.cos(rad); v.y = bondLength * Math.sin(rad); Point2d result = new Point2d(); result.add(s, v); return result; } @Override public void mouseClickedUp(Point2d worldCoord, int modifiers) { lastMouseMove = null; chemModelRelay.clearPhantoms(); if (isBond) return; IUndoRedoFactory factory = chemModelRelay.getUndoRedoFactory(); UndoRedoHandler handler = chemModelRelay.getUndoRedoHandler(); AtomBondSet containerForUndoRedo = new AtomBondSet(); IAtom newAtom; if (newSource) { newAtom = chemModelRelay.addAtomWithoutUndo(chemModelRelay.getController2DModel().getDrawElement(), start, chemModelRelay.getController2DModel().getDrawPseudoAtom()); containerForUndoRedo.add(newAtom); } else newAtom = source; // if merge is set either form a bond or add and form IAtomContainer removedContainer = null; if (merge != null) { chemModelRelay.getRenderer().getRenderer2DModel().getMerge().remove(merge); removedContainer = ChemModelManipulator.getRelevantAtomContainer(chemModelRelay.getIChemModel(), merge); IBond newBond = chemModelRelay.addBond(newAtom, merge, displayForNewBond, orderForNewBond); containerForUndoRedo.add(newBond); } else { if (start.distance(worldCoord) < getHighlightDistance()) { if (!newSource) { IAtom undoRedoAtom = chemModelRelay.addAtomWithoutUndo(chemModelRelay.getController2DModel().getDrawElement(), newAtom, displayForNewBond, orderForNewBond, chemModelRelay.getController2DModel().getDrawPseudoAtom()); containerForUndoRedo.add(undoRedoAtom); IAtomContainer atomCon = ChemModelManipulator.getRelevantAtomContainer(chemModelRelay.getIChemModel(), undoRedoAtom); containerForUndoRedo.add(atomCon.getConnectedBondsList(undoRedoAtom).get(0)); } else if (makeInitialBond) { IAtom undoRedoAtom = chemModelRelay.addAtomWithoutUndo(chemModelRelay.getController2DModel().getDrawElement(), new Point2d(newAtom.getPoint2d().x + 1.5, newAtom.getPoint2d().y), chemModelRelay.getController2DModel().getDrawPseudoAtom()); containerForUndoRedo.add(undoRedoAtom); containerForUndoRedo.add(chemModelRelay.addBond(newAtom, undoRedoAtom, displayForNewBond, orderForNewBond)); } } else { IAtom atom = chemModelRelay.addAtomWithoutUndo(chemModelRelay.getController2DModel().getDrawElement(), dest, chemModelRelay.getController2DModel().getDrawPseudoAtom()); containerForUndoRedo.add(atom); IBond newBond = chemModelRelay.addBond(newAtom, atom, displayForNewBond, orderForNewBond); containerForUndoRedo.add(newBond); } } if (factory != null && handler != null) { IUndoRedoable undoredo = chemModelRelay.getUndoRedoFactory().getAddAtomsAndBondsEdit(chemModelRelay.getIChemModel(), containerForUndoRedo, removedContainer, "Add Bond", chemModelRelay); handler.postEdit(undoredo); } chemModelRelay.updateView(); } public String getDrawModeString() { if (orderForNewBond == IBond.Order.DOUBLE) return "Draw Double Bond"; else if (orderForNewBond == IBond.Order.TRIPLE) return "Draw Triple Bond"; else return "Draw Bond"; } public String getID() { return id; } public void setID(String ID) { this.id = ID; } /** * Tells which stereo info new bonds will get. * * @return The stereo which new bonds will have. */ public IBond.Display getStereoForNewBond() { return displayForNewBond; } @Override public void updateView() { if (lastMouseMove != null) mouseMove(lastMouseMove); } }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/controller/PhantomTextGenerator.java
.java
2,356
63
/* $Revision: $ $Author: $ $Date$ * * Copyright (C) 2010 Conni Wagner <conn75@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 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 java.awt.Color; import java.util.List; import org.openscience.cdk.interfaces.IAtomContainer; import org.openscience.cdk.renderer.RendererModel; import org.openscience.cdk.renderer.elements.ElementGroup; import org.openscience.cdk.renderer.elements.IRenderingElement; import org.openscience.jchempaint.renderer.elements.TextElement; import org.openscience.cdk.renderer.generators.IGenerator; import org.openscience.cdk.renderer.generators.IGeneratorParameter; public class PhantomTextGenerator implements IGenerator<IAtomContainer> { ControllerHub hub; public PhantomTextGenerator(){ } public void setControllerHub(ControllerHub hub) { this.hub = hub; } public IRenderingElement generate(IAtomContainer ac, RendererModel model) { if(hub.getPhantomText()==null) return new ElementGroup(); else return new TextElement(hub.getPhantomTextPosition().x, hub.getPhantomTextPosition().y, hub.getPhantomText(), Color.GRAY); } public List<IGeneratorParameter<?>> getParameters() { // TODO Auto-generated method stub return null; } }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/controller/SelectLassoModule.java
.java
1,365
40
/* $Revision$ $Author$ $Date$ * * Copyright (C) 2008 Gilleain Torrance <gilleain.torrance@gmail.com> * * Contact: cdk-devel@list.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 org.openscience.jchempaint.renderer.selection.LassoSelection; /** * @cdk.module controlbasic */ public class SelectLassoModule extends AbstractSelectModule { public SelectLassoModule(IChemModelRelay chemModelRelay) { super(chemModelRelay); selection = new LassoSelection(); } public String getDrawModeString() { return "Select in Free Form"; } }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/controller/CycleSymbolModule.java
.java
3,309
97
/* $Revision: 7636 $ $Author: nielsout $ $Date: 2007-01-04 18:46:10 +0100 (Thu, 04 Jan 2007) $ * * Copyright (C) 2007 Stefan Kuhn * Copyright (C) 2009 Arvid Berg * * 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.cdk.interfaces.IChemObject; import org.openscience.cdk.renderer.selection.AbstractSelection; import org.openscience.jchempaint.renderer.selection.SingleSelection; /** * Adds an atom on the given location on mouseclick * * @author Stefan Kuhn * @cdk.svnrev $Revision: 9162 $ * @cdk.module controlbasic */ public class CycleSymbolModule extends ControllerModuleAdapter { private String ID; public CycleSymbolModule(IChemModelRelay chemModelRelay) { super(chemModelRelay); } public void mouseClickedDown(Point2d worldCoord, int modifiers) { IChemObject singleSelected = getHighlighted( worldCoord, chemModelRelay.getClosestAtom(worldCoord) ); IAtom closestAtom; if(singleSelected instanceof IAtom) { closestAtom = (IAtom) singleSelected; }else { setSelection( AbstractSelection.EMPTY_SELECTION ); return; } String symbol = closestAtom.getSymbol(); boolean changed = false; String[] elements = chemModelRelay.getController2DModel().getCommonElements(); for (int i = 0; i < elements.length; i++) { if (elements[i].equals(symbol)) { if (i < elements.length - 2) { chemModelRelay.setSymbol( closestAtom,elements[i + 1]); } else { chemModelRelay.setSymbol( closestAtom, elements[0]); } changed = true; break; } } if (!changed) closestAtom.setSymbol("C"); setSelection( new SingleSelection<IAtom>(closestAtom) ); chemModelRelay.updateView(); } public String getDrawModeString() { return "Cycle Symbol"; } public String getID() { return ID; } public void setID(String ID) { this.ID=ID; } }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/controller/PhantomArrowGenerator.java
.java
2,746
73
/* $Revision: $ $Author: $ $Date$ * * 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 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 java.awt.Color; import java.util.List; import org.openscience.cdk.interfaces.IAtomContainer; import org.openscience.cdk.renderer.RendererModel; import org.openscience.jchempaint.renderer.JChemPaintRendererModel; import org.openscience.cdk.renderer.elements.ArrowElement; import org.openscience.cdk.renderer.elements.ElementGroup; import org.openscience.cdk.renderer.elements.IRenderingElement; import org.openscience.cdk.renderer.generators.IGenerator; import org.openscience.cdk.renderer.generators.IGeneratorParameter; /** * Draws a phantom arrow in ControllerHub */ public class PhantomArrowGenerator implements IGenerator<IAtomContainer> { ControllerHub hub; public PhantomArrowGenerator(){ } public void setControllerHub(ControllerHub hub) { this.hub = hub; } public IRenderingElement generate(IAtomContainer ac, RendererModel model) { JChemPaintRendererModel jcpModel = (JChemPaintRendererModel) model; if(hub.getPhantomArrow()[0]==null || hub.getPhantomArrow()[1]==null) return new ElementGroup(); else return new ArrowElement(hub.getPhantomArrow()[0].x, hub.getPhantomArrow()[0].y, hub.getPhantomArrow()[1].x, hub.getPhantomArrow()[1].y, 1 / jcpModel.getScale(),true, Color.GRAY); } public List<IGeneratorParameter<?>> getParameters() { // TODO Auto-generated method stub return null; } }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/controller/AtomAtomMappingModule.java
.java
3,499
96
/* * Copyright (C) 2009 Stefan Kuhn * * 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.cdk.interfaces.IMapping; import org.openscience.cdk.interfaces.IReaction; import org.openscience.cdk.tools.manipulator.ChemModelManipulator; import org.openscience.jchempaint.renderer.JChemPaintRendererModel; /** * Adds an atom on the given location on mouseclick * * @author shk3 * @cdk.module controlextra */ public class AtomAtomMappingModule extends ControllerModuleAdapter { private IAtom startAtom; private String ID; public AtomAtomMappingModule(IChemModelRelay chemModelRelay) { super(chemModelRelay); } public void mouseClickedDown(Point2d worldCoord, int modifiers) { JChemPaintRendererModel model = chemModelRelay.getRenderer().getRenderer2DModel(); double dH = model.getHighlightDistance() / model.getScale(); IAtom closestAtom = chemModelRelay.getClosestAtom(worldCoord); if(closestAtom == null || closestAtom.getPoint2d().distance(worldCoord) > dH) startAtom = null; else startAtom = chemModelRelay.getClosestAtom(worldCoord); } public void mouseClickedUp(Point2d worldCoord, int modifiers){ JChemPaintRendererModel model = chemModelRelay.getRenderer().getRenderer2DModel(); double dH = model.getHighlightDistance() / model.getScale(); IAtom closestAtom = chemModelRelay.getClosestAtom(worldCoord); IAtom endAtom = null; if(closestAtom != null && closestAtom.getPoint2d().distance(worldCoord) < dH) endAtom = chemModelRelay.getClosestAtom(worldCoord); if(endAtom!=null && startAtom!=null){ IMapping mapping = startAtom.getBuilder().newInstance(IMapping.class,startAtom, endAtom); // ok, now figure out if they are in one reaction IReaction reaction1 = ChemModelManipulator.getRelevantReaction(chemModelRelay.getIChemModel(), startAtom); IReaction reaction2 = ChemModelManipulator.getRelevantReaction(chemModelRelay.getIChemModel(), endAtom); if (reaction1 != null && reaction2 != null && reaction1 == reaction2) { ((IReaction)reaction1).addMapping(mapping); }else{ //TODO what to do? message box? that would be a swing component } } startAtom = null; } public String getDrawModeString() { return "Do Atom-Atom Mapping"; } public String getID() { return ID; } public void setID(String ID) { this.ID=ID; } }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/controller/ControllerModuleAdapter.java
.java
8,103
227
package org.openscience.jchempaint.controller; import javax.vecmath.Point2d; 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.jchempaint.AtomBondSet; import org.openscience.jchempaint.renderer.JChemPaintRendererModel; import org.openscience.cdk.renderer.selection.AbstractSelection; import org.openscience.cdk.renderer.selection.IChemObjectSelection; import org.openscience.jchempaint.renderer.selection.SingleSelection; /** * @cdk.module control */ public abstract class ControllerModuleAdapter implements IControllerModule { protected IChemModelRelay chemModelRelay; protected IChemObjectSelection selection; protected boolean wasEscaped; public ControllerModuleAdapter(IChemModelRelay chemModelRelay) { this.chemModelRelay = chemModelRelay; this.wasEscaped = false; } public double getHighlightDistance() { JChemPaintRendererModel model = chemModelRelay.getRenderer().getRenderer2DModel(); return model.getHighlightDistance() / model.getScale(); } public static double distanceToAtom(IAtom atom, Point2d p) { if (atom == null) { return Double.MAX_VALUE; } else { return atom.getPoint2d().distance(p); } } public static double distanceToBond(IBond bond, Point2d p) { if (bond == null) { return Double.MAX_VALUE; } else { return bond.get2DCenter().distance(p); } } public boolean isBondOnlyInHighlightDistance(double dA, double dB, double dH) { return dA > dH && dB < dH; } public boolean isAtomOnlyInHighlightDistance(double dA, double dB, double dH) { return dA < dH && dB > dH; } public boolean noSelection(double dA, double dB, double dH) { return (dH == Double.POSITIVE_INFINITY) || (dA > dH && dB > dH); } public void mouseWheelMovedBackward(int modifiers, int clicks) { } public void mouseWheelMovedForward(int modifiers, int clicks) { } public void mouseClickedDouble(Point2d worldCoord) { } public final void mouseClickedDown(Point2d worldCoord) { mouseClickedDown(worldCoord, 0); } public final void mouseClickedUp(Point2d worldCoord) { mouseClickedUp(worldCoord, 0); } public void mouseClickedDown(Point2d worldCoord, int modifiers) { } public void mouseClickedUp(Point2d worldCoord, int modifiers) { } public void mouseClickedDownRight(Point2d worldCoord) { } public void mouseClickedUpRight(Point2d worldCoord) { } public final void mouseDrag(Point2d worldCoordFrom, Point2d worldCoordTo) { mouseDrag(worldCoordFrom, worldCoordTo, 0); } public void mouseDrag(Point2d worldCoordFrom, Point2d worldCoordTo, int modifiers) { } public void mouseEnter(Point2d worldCoord) { } public void mouseExit(Point2d worldCoord) { } public void mouseMove(Point2d worldCoord) { } public void setChemModelRelay(IChemModelRelay relay) { this.chemModelRelay = relay; } protected IChemObject getHighlighted(Point2d worldCoord, IChemObject... objects) { IChemObject closest = null; double minDistance = Double.POSITIVE_INFINITY; for (IChemObject obj : objects) { double distance = Double.POSITIVE_INFINITY; if (obj instanceof IAtom) distance = distanceToAtom((IAtom) obj, worldCoord); else if (obj instanceof IBond) distance = distanceToBond((IBond) obj, worldCoord); if (distance < minDistance) { closest = obj; minDistance = distance; } } if (minDistance <= getHighlightDistance()) return closest; return null; } /** * Handles selection behavior. When nothing is within the highlight radius, * null is returned and the selection is cleared. If an atom or bond is * selected that is part of the current selection, the returned atom * container contains the selection. If the atom or bond is not part of the * selection, the selection is updated to contain only the atom or bond * and is returned in the atom container. * * @param worldCoord * @return a AtomBondSet containing the atoms/bond that should be affected * by this action. Otherwise <code>null</code>. */ protected AtomBondSet getSelectAtomBondSet(Point2d worldCoord) { JChemPaintRendererModel rModel = chemModelRelay.getRenderer().getRenderer2DModel(); IAtom atom = chemModelRelay.getClosestAtom(worldCoord); IBond bond = chemModelRelay.getClosestBond(worldCoord); IChemObjectSelection localSelection = rModel.getSelection(); IChemObject chemObject = getHighlighted(worldCoord, atom, bond); if (localSelection == null || !localSelection.contains(chemObject)) { if (chemObject != null) { localSelection = new SingleSelection<IChemObject>(chemObject); } else { //if clicked inside a square comprising the selection, keep it, otherwise void it Double upperX = null, lowerX = null, upperY = null, lowerY = null; IAtomContainer selectedAtoms = null; if (localSelection != null) selectedAtoms = localSelection.getConnectedAtomContainer(); if (selectedAtoms != null) { for (int i = 0; i < selectedAtoms.getAtomCount(); i++) { if (upperX == null) { upperX = lowerX = selectedAtoms.getAtom(i).getPoint2d().x; upperY = lowerY = selectedAtoms.getAtom(i).getPoint2d().y; } else { double currX = selectedAtoms.getAtom(i).getPoint2d().x; if (currX > upperX) upperX = currX; if (currX < lowerX) lowerX = currX; double currY = selectedAtoms.getAtom(i).getPoint2d().y; if (currY > upperY) upperY = currY; if (currY < lowerY) lowerY = currY; } } } if (upperX != null && upperY != null) { if (!(worldCoord.x >= lowerX && worldCoord.y >= lowerY && worldCoord.x <= upperX && worldCoord.y <= upperY) ) localSelection = AbstractSelection.EMPTY_SELECTION; } else localSelection = AbstractSelection.EMPTY_SELECTION; } } setSelection(localSelection); AtomBondSet atomBondSet = new AtomBondSet(); for (IAtom a : localSelection.elements(IAtom.class)) atomBondSet.add(a); for (IBond b : localSelection.elements(IBond.class)) atomBondSet.add(b); return atomBondSet; } protected void setSelection(IChemObjectSelection selection) { this.selection = selection; if (chemModelRelay.getController2DModel().isHightlighLastSelected()) { chemModelRelay.getRenderer().getRenderer2DModel().setSelection(selection); chemModelRelay.select(null); /*FIXME setSelection on IChemModelRelay the selection should probably be in the ControllerHub and not in the RendererModel*/ chemModelRelay.updateView(); } } public void escapeTheMode() { this.wasEscaped = true; } public boolean wasEscaped() { return this.wasEscaped; } public void updateView() {} }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/controller/ControllerModel.java
.java
9,853
349
/* $RCSfile$ * $Author$ * $Date$ * $Revision$ * * Copyright (C) 1997-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 java.io.Serializable; import java.util.HashMap; import org.openscience.cdk.interfaces.IBond; /** * @cdk.module controlbasic * @cdk.svnrev $Revision$ */ public class ControllerModel implements Serializable, Cloneable, IControllerModel { private static final long serialVersionUID = 9007159812273128989L; private ControllerParameters parameters; private HashMap<Object, Object> merge = new HashMap<Object, Object>(); public ControllerModel() { this.parameters = new ControllerParameters(); } /** * This is the central facility for handling "merges" of atoms. A merge * occures if during moving atoms an atom is in Range of another atom. These * atoms are then put into the merge map as a key-value pair. During the * move, the atoms are then marked by a circle and on releasing the mouse * they get actually merged, meaning one atom is removed and bonds pointing * to this atom are made to point to the atom it has been marged with. * * @return Returns the merge.map * * FIXME: this belongs in the controller model... this is not about * rendering, it's about editing (aka controlling) */ public HashMap<Object, Object> getMerge() { return merge; } public IBond.Order getMaxOrder() { return this.parameters.getMaxOrder(); } public void setMaxOrder(IBond.Order maxOrder) { this.parameters.setMaxOrder(maxOrder); } /* * (non-Javadoc) * * @see * org.openscience.cdk.controller.IController2DModel#getSnapToGridAngle() */ public boolean getSnapToGridAngle() { return this.parameters.isSnapToGridAngle(); } /* * (non-Javadoc) * * @seeorg.openscience.cdk.controller.IController2DModel# * getAutoUpdateImplicitHydrogens() */ public boolean getAutoUpdateImplicitHydrogens() { return this.parameters.isAutoUpdateImplicitHydrogens(); } /* * (non-Javadoc) * * @seeorg.openscience.cdk.controller.IController2DModel# * setAutoUpdateImplicitHydrogens(boolean) */ public void setAutoUpdateImplicitHydrogens(boolean update) { this.parameters.setAutoUpdateImplicitHydrogens(update); } /* * (non-Javadoc) * * @see * org.openscience.cdk.controller.IController2DModel#setSnapToGridAngle( * boolean) */ public void setSnapToGridAngle(boolean snapToGridAngle) { this.parameters.setSnapToGridAngle(snapToGridAngle); } /* * (non-Javadoc) * * @see org.openscience.cdk.controller.IController2DModel#getSnapAngle() */ public int getSnapAngle() { return this.parameters.getSnapAngle(); } /* * (non-Javadoc) * * @see org.openscience.cdk.controller.IController2DModel#setSnapAngle(int) */ public void setSnapAngle(int snapAngle) { this.parameters.setSnapAngle(snapAngle); } /* * (non-Javadoc) * * @see * org.openscience.cdk.controller.IController2DModel#getSnapToGridCartesian * () */ public boolean getSnapToGridCartesian() { return this.parameters.isSnapToGridCartesian(); } /* * (non-Javadoc) * * @see * org.openscience.cdk.controller.IController2DModel#setSnapToGridCartesian * (boolean) */ public void setSnapToGridCartesian(boolean snapToGridCartesian) { this.parameters.setSnapToGridCartesian(snapToGridCartesian); } /* * (non-Javadoc) * * @see org.openscience.cdk.controller.IController2DModel#getSnapCartesian() */ public int getSnapCartesian() { return this.parameters.getSnapCartesian(); } /* * (non-Javadoc) * * @see * org.openscience.cdk.controller.IController2DModel#setSnapCartesian(int) */ public void setSnapCartesian(int snapCartesian) { this.parameters.setSnapCartesian(snapCartesian); } /* * (non-Javadoc) * * @see * org.openscience.cdk.controller.IController2DModel#getDefaultElementSymbol * () */ public String getDefaultElementSymbol() { return this.parameters.getDefaultElementSymbol(); } /* * (non-Javadoc) * * @see * org.openscience.cdk.controller.IController2DModel#setDefaultElementSymbol * (java.lang.String) */ public void setDefaultElementSymbol(String defaultElementSymbol) { this.parameters.setDefaultElementSymbol(defaultElementSymbol); } /* * (non-Javadoc) * * @see * org.openscience.cdk.controller.IController2DModel#getBondPointerLength() */ public double getBondPointerLength() { return this.parameters.getBondPointerLength(); } /* * (non-Javadoc) * * @see * org.openscience.cdk.controller.IController2DModel#setBondPointerLength * (double) */ public void setBondPointerLength(double bondPointerLength) { this.parameters.setBondPointerLength(bondPointerLength); } /* * (non-Javadoc) * * @see * org.openscience.cdk.controller.IController2DModel#getRingPointerLength() */ public double getRingPointerLength() { return this.parameters.getRingPointerLength(); } /* * (non-Javadoc) * * @see * org.openscience.cdk.controller.IController2DModel#setRingPointerLength * (double) */ public void setRingPointerLength(double ringPointerLength) { this.parameters.setRingPointerLength(ringPointerLength); } /* * (non-Javadoc) * * @see * org.openscience.cdk.controller.IController2DModel#setCommonElements(java * .lang.String[]) */ public void setCommonElements(String[] elements) { this.parameters.setCommonElements(elements); } /* * (non-Javadoc) * * @see * org.openscience.cdk.controller.IController2DModel#getCommonElements() */ public String[] getCommonElements() { return this.parameters.getCommonElements(); } /* (non-Javadoc) * @see org.openscience.cdk.controller.IControllerModel#setDrawPseudoAtom(boolean) */ public void setDrawPseudoAtom(boolean drawPseudoAtom){ this.parameters.setDrawPseudoAtom(drawPseudoAtom); } /* (non-Javadoc) * @see org.openscience.cdk.controller.IControllerModel#getDrawPseudoAtom() */ public boolean getDrawPseudoAtom(){ return this.parameters.getDrawPseudoAtom(); } /* * (non-Javadoc) * * @see * org.openscience.cdk.controller.IController2DModel#setDrawElement(java * .lang.String) */ public void setDrawElement(String element) { this.parameters.setDrawElement(element); } /* * (non-Javadoc) * * @see org.openscience.cdk.controller.IController2DModel#getDrawElement() */ public String getDrawElement() { return this.parameters.getDrawElement(); } /* * (non-Javadoc) * * @see org.openscience.cdk.controller.IController2DModel#isMovingAllowed() */ public boolean isMovingAllowed() { return this.parameters.isMovingAllowed(); } /* * (non-Javadoc) * * @see * org.openscience.cdk.controller.IController2DModel#setMovingAllowed(boolean * ) */ public void setMovingAllowed(boolean isMovingAllowed) { this.parameters.setMovingAllowed(isMovingAllowed); } /* (non-Javadoc) * @see org.openscience.cdk.controller.IControllerModel#getDrawIsotopeNumber() */ public int getDrawIsotopeNumber() { return this.parameters.getDrawIsotope(); } /* (non-Javadoc) * @see org.openscience.cdk.controller.IControllerModel#setDrawIsotopeNumber(int) */ public void setDrawIsotopeNumber(int isotope) { this.parameters.setDrawIsotope(isotope); } /** * @return Tells if after a structure change the affected part should be selected. */ public boolean isHightlighLastSelected() { return this.parameters.isHightlighLastSelected(); } /** * Determines if after a structure change the affected part should be selected. * * @param hightlighLastSelected True=will be selected, false=will not be selected. */ public void setHightlighLastSelected(boolean hightlighLastSelected) { this.parameters.setHightlighLastSelected(hightlighLastSelected); } }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/controller/ControllerHub.java
.java
131,775
3,852
/* $Revision: 7636 $ $Author: egonw $ $Date: 2007-01-04 18:46:10 +0100 (Thu, 04 Jan 2007) $ * * Copyright (C) 2007-2008 Egon Willighagen <egonw@users.sf.net> * 2005-2007 Christoph Steinbeck <steinbeck@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 org.openscience.cdk.CDKConstants; import org.openscience.cdk.atomtype.CDKAtomTypeMatcher; import org.openscience.cdk.config.Elements; import org.openscience.cdk.config.Isotopes; import org.openscience.cdk.exception.CDKException; import org.openscience.cdk.geometry.GeometryUtil; import org.openscience.cdk.graph.ConnectivityChecker; import org.openscience.cdk.graph.Cycles; import org.openscience.cdk.interfaces.IAtom; import org.openscience.cdk.interfaces.IAtomContainer; import org.openscience.cdk.interfaces.IAtomContainerSet; import org.openscience.cdk.interfaces.IAtomType; import org.openscience.cdk.interfaces.IBond; import org.openscience.cdk.interfaces.IBond.Display; import org.openscience.cdk.interfaces.IBond.Order; import org.openscience.cdk.interfaces.IBond.Stereo; import org.openscience.cdk.interfaces.IChemModel; import org.openscience.cdk.interfaces.IChemObject; import org.openscience.cdk.interfaces.IElement; import org.openscience.cdk.interfaces.IMolecularFormula; import org.openscience.cdk.interfaces.IPseudoAtom; import org.openscience.cdk.interfaces.IReaction; import org.openscience.cdk.interfaces.IReactionSet; import org.openscience.cdk.interfaces.IRing; import org.openscience.cdk.interfaces.ISingleElectron; import org.openscience.cdk.layout.AtomPlacer; import org.openscience.cdk.layout.RingPlacer; import org.openscience.cdk.layout.StructureDiagramGenerator; import org.openscience.cdk.renderer.selection.IChemObjectSelection; import org.openscience.cdk.stereo.Projection; import org.openscience.cdk.stereo.StereoElementFactory; import org.openscience.cdk.tools.ILoggingTool; import org.openscience.cdk.tools.LoggingToolFactory; import org.openscience.cdk.tools.SaturationChecker; import org.openscience.cdk.tools.manipulator.AtomContainerManipulator; import org.openscience.cdk.tools.manipulator.AtomContainerSetManipulator; import org.openscience.cdk.tools.manipulator.ChemModelManipulator; import org.openscience.cdk.tools.manipulator.MolecularFormulaManipulator; import org.openscience.cdk.tools.manipulator.ReactionManipulator; import org.openscience.cdk.validate.ProblemMarker; import org.openscience.jchempaint.AtomBondSet; import org.openscience.jchempaint.RenderPanel; import org.openscience.jchempaint.applet.JChemPaintAbstractApplet; import org.openscience.jchempaint.controller.undoredo.AddAtomsAndBondsEdit; import org.openscience.jchempaint.controller.undoredo.AdjustBondOrdersEdit; import org.openscience.jchempaint.controller.undoredo.ChangeAtomSymbolEdit; import org.openscience.jchempaint.controller.undoredo.ChangeHydrogenCountEdit; import org.openscience.jchempaint.controller.undoredo.ChangeIsotopeEdit; import org.openscience.jchempaint.controller.undoredo.CompoundEdit; import org.openscience.jchempaint.controller.undoredo.IUndoRedoFactory; import org.openscience.jchempaint.controller.undoredo.IUndoRedoable; import org.openscience.jchempaint.controller.undoredo.ReplaceAtomEdit; import org.openscience.jchempaint.controller.undoredo.UndoRedoHandler; import org.openscience.jchempaint.renderer.BoundsCalculator; import org.openscience.jchempaint.renderer.IRenderer; import org.openscience.jchempaint.renderer.JChemPaintRendererModel; import org.openscience.jchempaint.renderer.Renderer; import org.openscience.jchempaint.renderer.selection.IncrementalSelection; import org.openscience.jchempaint.renderer.selection.LogicalSelection; import org.openscience.jchempaint.rgroups.RGroupHandler; import javax.vecmath.Point2d; import javax.vecmath.Tuple2d; import javax.vecmath.Vector2d; import java.awt.Cursor; import java.awt.Image; import java.awt.Point; import java.awt.Toolkit; import java.awt.geom.Rectangle2D; import java.io.IOException; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Deque; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.TimeUnit; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Class that will central interaction point between a mouse event throwing * widget (SWT or Swing) and the Controller2D modules. IMPORTANT: All actions in * this class must adhere to the following rules: - They keep any fragments in * separate Molecules in the SetOfMolecules, i. e. if splits or merges are done, * they must handle this (precondition and postcondition: Each Molecule in * SetOfMolecules is a linked graph). - The chemModel always contains a * SetOfMolecules with at least one Molecule, this can be empty. No other * containers are allowed to be empty (precondition and postcondition: * SetOfMolecules.getAtomContainerCount>0, atomCount>0 for all Molecules in * SetOfMolecules where index>0). * * @cdk.svnrev $Revision: 9162 $ * @cdk.module controlbasic * @author Niels Out * @author egonw */ public class ControllerHub implements IMouseEventRelay, IChemModelRelay { private static final ILoggingTool log = LoggingToolFactory.createLoggingTool(ControllerHub.class); private IChemModel chemModel; private IControllerModel controllerModel; private IRenderer renderer; private RenderPanel eventRelay; private List<IControllerModule> generalModules; private List<IChangeModeListener> changeModeListeners = new ArrayList<IChangeModeListener>(); private static StructureDiagramGenerator diagramGenerator; private IControllerModule activeDrawModule; private IControllerModule fallbackModule; private final static RingPlacer ringPlacer = new RingPlacer(); private IAtomContainer phantoms; private IChemModelEventRelayHandler changeHandler; private IUndoRedoFactory undoredofactory; private UndoRedoHandler undoredohandler; private CDKAtomTypeMatcher matcher; private static RGroupHandler rGroupHandler; int oldMouseCursor = Cursor.DEFAULT_CURSOR; private Point2d phantomArrowStart = null; private Point2d phantomArrowEnd = null; private Point2d phantomTextPosition = null; private String phantomText = null; /** Alternative input mode allow different actions when alt is held. */ private boolean altMode = false; private Cursor rotateCursor; public ControllerHub(IControllerModel controllerModel, IRenderer renderer, IChemModel chemModel, RenderPanel eventRelay, UndoRedoHandler undoredohandler, IUndoRedoFactory undoredofactory, boolean isViewer, JChemPaintAbstractApplet applet) { this.controllerModel = controllerModel; this.renderer = renderer; this.chemModel = chemModel; this.eventRelay = eventRelay; this.phantoms = chemModel.getBuilder().newInstance(IAtomContainer.class); this.undoredofactory = undoredofactory; this.undoredohandler = undoredohandler; generalModules = new ArrayList<IControllerModule>(); if (!isViewer) { registerGeneralControllerModule(new ZoomModule(this)); } registerGeneralControllerModule(new HighlightModule(this, applet)); matcher = CDKAtomTypeMatcher.getInstance(chemModel.getBuilder()); Toolkit toolkit = Toolkit.getDefaultToolkit(); rotateCursor = toolkit.createCustomCursor(toolkit.getImage(getClass().getResource("cursors/rotate.png")) .getScaledInstance(16, 16, Image.SCALE_SMOOTH), new Point(8, 8), "rotate"); } public IControllerModel getController2DModel() { return controllerModel; } public IRenderer getRenderer() { return renderer; } public IChemModel getIChemModel() { return chemModel; } public void setChemModel(IChemModel model) { this.chemModel = model; structureChanged(); } /** * Unregister all general IController2DModules. */ public void unRegisterAllControllerModule() { generalModules.clear(); } /** * Adds a general IController2DModule which will catch all mouse events. */ public void registerGeneralControllerModule(IControllerModule module) { module.setChemModelRelay(this); generalModules.add(module); } public void mouseWheelMovedBackward(int modifiers, int clicks) { for (IControllerModule module : generalModules) { module.mouseWheelMovedBackward(modifiers, clicks); } IControllerModule activeModule = getActiveDrawModule(); if (activeModule != null) activeModule.mouseWheelMovedBackward(modifiers, clicks); } public void mouseWheelMovedForward(int modifiers, int clicks) { for (IControllerModule module : generalModules) { module.mouseWheelMovedForward(modifiers, clicks); } IControllerModule activeModule = getActiveDrawModule(); if (activeModule != null) activeModule.mouseWheelMovedForward(modifiers, clicks); } public void mouseClickedDouble(int screenCoordX, int screenCoordY) { Point2d worldCoord = renderer.toModelCoordinates(screenCoordX, screenCoordY); // Relay the mouse event to the general handlers for (IControllerModule module : generalModules) { module.mouseClickedDouble(worldCoord); } // Relay the mouse event to the active IControllerModule activeModule = getActiveDrawModule(); if (activeModule != null) activeModule.mouseClickedDouble(worldCoord); } public void mouseClickedDownRight(int screenX, int screenY) { Point2d modelCoord = renderer.toModelCoordinates(screenX, screenY); // Relay the mouse event to the active IControllerModule activeModule = getActiveDrawModule(); if (activeModule != null) activeModule.mouseClickedDownRight(modelCoord); if (activeModule.wasEscaped()) { setActiveDrawModule(null); return; } // Relay the mouse event to the general handlers for (IControllerModule module : generalModules) { module.mouseClickedDownRight(modelCoord); } } public void mouseClickedUpRight(int screenX, int screenY) { Point2d modelCoord = renderer.toModelCoordinates(screenX, screenY); // Relay the mouse event to the general handlers for (IControllerModule module : generalModules) { module.mouseClickedUpRight(modelCoord); } // Relay the mouse event to the active IControllerModule activeModule = getActiveDrawModule(); if (activeModule != null) activeModule.mouseClickedUpRight(modelCoord); } public void mouseClickedDown(int screenX, int screenY, int modifiers) { Point2d modelCoord = renderer.toModelCoordinates(screenX, screenY); // Relay the mouse event to the general handlers for (IControllerModule module : generalModules) { module.mouseClickedDown(modelCoord, modifiers); } // Relay the mouse event to the active IControllerModule activeModule = getActiveDrawModule(); if (activeModule != null) { activeModule.mouseClickedDown(modelCoord, modifiers); } if (getCursor() == Cursor.HAND_CURSOR) { setCursor(Cursor.MOVE_CURSOR); oldMouseCursor = Cursor.HAND_CURSOR; } else if (getCursor() != Cursor.DEFAULT_CURSOR) { oldMouseCursor = Cursor.DEFAULT_CURSOR; } } public void mouseClickedDown(int screenX, int screenY) { mouseClickedDown(screenX, screenY, 0); } public void mouseClickedUp(int screenX, int screenY, int modifiers) { Point2d modelCoord = renderer.toModelCoordinates(screenX, screenY); // Relay the mouse event to the general handlers for (IControllerModule module : generalModules) { module.mouseClickedUp(modelCoord, modifiers); } // Relay the mouse event to the active IControllerModule activeModule = getActiveDrawModule(); if (activeModule != null) { activeModule.mouseClickedUp(modelCoord, modifiers); } setCursor(oldMouseCursor); } public void mouseClickedUp(int screenX, int screenY) { mouseClickedUp(screenX, screenY, 0); } public void mouseDrag(int screenXFrom, int screenYFrom, int screenXTo, int screenYTo, int modifiers) { Point2d modelCoordFrom = renderer.toModelCoordinates(screenXFrom, screenYFrom); Point2d modelCoordTo = renderer .toModelCoordinates(screenXTo, screenYTo); // Relay the mouse event to the general handlers for (IControllerModule module : generalModules) { module.mouseDrag(modelCoordFrom, modelCoordTo, modifiers); } // Relay the mouse event to the active IControllerModule activeModule = getActiveDrawModule(); if (activeModule != null) { activeModule.mouseDrag(modelCoordFrom, modelCoordTo, modifiers); } } public void mouseEnter(int screenX, int screenY) { Point2d worldCoord = renderer.toModelCoordinates(screenX, screenY); // Relay the mouse event to the general handlers for (IControllerModule module : generalModules) { module.mouseEnter(worldCoord); } // Relay the mouse event to the active IControllerModule activeModule = getActiveDrawModule(); if (activeModule != null) activeModule.mouseEnter(worldCoord); } public void mouseExit(int screenX, int screenY) { Point2d worldCoord = renderer.toModelCoordinates(screenX, screenY); // Relay the mouse event to the general handlers for (IControllerModule module : generalModules) { module.mouseExit(worldCoord); } // Relay the mouse event to the active IControllerModule activeModule = getActiveDrawModule(); if (activeModule != null) activeModule.mouseExit(worldCoord); } public void mouseMove(int screenX, int screenY) { Point2d worldCoord = renderer.toModelCoordinates(screenX, screenY); // Relay the mouse event to the general handlers for (IControllerModule module : generalModules) { module.mouseMove(worldCoord); } // Relay the mouse event to the active IControllerModule activeModule = getActiveDrawModule(); if (activeModule != null) activeModule.mouseMove(worldCoord); } public void updateView() { // call the eventRelay method here to update the view.. eventRelay.updateView(); } public IControllerModule getActiveDrawModule() { return activeDrawModule; } public void setActiveDrawModule(IControllerModule activeDrawModule) { clearPhantoms(); if (activeDrawModule == null) activeDrawModule = this.fallbackModule; this.activeDrawModule = activeDrawModule; for (int i = 0; i < changeModeListeners.size(); i++) changeModeListeners.get(i).modeChanged(this.activeDrawModule); } // OK public IAtom getClosestAtom(Point2d worldCoord) { IAtom closestAtom = null; double closestDistanceSQ = Double.MAX_VALUE; for (IAtomContainer atomContainer : ChemModelManipulator .getAllAtomContainers(chemModel)) { for (IAtom atom : atomContainer.atoms()) { if (atom.getPoint2d() != null) { double distanceSQ = atom.getPoint2d().distanceSquared( worldCoord); if (distanceSQ < closestDistanceSQ) { closestAtom = atom; closestDistanceSQ = distanceSQ; } } } } return closestAtom; } // OK public IBond getClosestBond(Point2d worldCoord) { IBond closestBond = null; double closestDistanceSQ = Double.MAX_VALUE; for (IAtomContainer atomContainer : ChemModelManipulator .getAllAtomContainers(chemModel)) { for (IBond bond : atomContainer.bonds()) { boolean hasCenter = true; for (IAtom atom : bond.atoms()) hasCenter = hasCenter && (atom.getPoint2d() != null); if (hasCenter) { double distanceSQ = bond.get2DCenter().distanceSquared( worldCoord); if (distanceSQ < closestDistanceSQ) { closestBond = bond; closestDistanceSQ = distanceSQ; } } } } return closestBond; } // OK public AtomBondSet removeAtomWithoutUndo(IAtom atom) { AtomBondSet undoRedoSet = new AtomBondSet(); if(rGroupHandler!=null && !rGroupHandler.checkRGroupOkayForDelete(atom, this)) return undoRedoSet; undoRedoSet.add(atom); Iterator<IBond> connbonds = ChemModelManipulator .getRelevantAtomContainer(chemModel, atom) .getConnectedBondsList(atom).iterator(); while (connbonds.hasNext()) { IBond connBond = connbonds.next(); undoRedoSet.add(connBond); } ChemModelManipulator.removeAtomAndConnectedElectronContainers( chemModel, atom); for (IBond bond : undoRedoSet.bonds()) { updateAtom(bond.getOther(atom)); } structureChanged(); adjustRgroup(); return undoRedoSet; } /* * (non-Javadoc) * * @see * org.openscience.cdk.controller.IChemModelRelay#addAtom(java.lang.String, * javax.vecmath.Point2d) */ public IAtom addAtom(String atomType, Point2d worldCoord, boolean makePseudoAtom) { return addAtom(atomType, 0, worldCoord, makePseudoAtom); } //OK TODO this could do with less partitioning public AtomBondSet removeAtom(IAtom atom) { AtomBondSet undoRedoSet = removeAtomWithoutUndo(atom); removeEmptyContainers(chemModel); if(getUndoRedoFactory()!=null && getUndoRedoHandler()!=null){ IUndoRedoable undoredo = getUndoRedoFactory().getRemoveAtomsAndBondsEdit(getIChemModel(), undoRedoSet, "Remove Atom",this); getUndoRedoHandler().postEdit(undoredo); } return undoRedoSet; } // OK /* * (non-Javadoc) * * @see * org.openscience.cdk.controller.IChemModelRelay#addAtom(java.lang.String, * int, javax.vecmath.Point2d) */ public IAtom addAtom(String atomType, int isotopeNumber, Point2d worldCoord, boolean makePseudoAtom) { AtomBondSet undoRedoSet = new AtomBondSet(); undoRedoSet.add(addAtomWithoutUndo(atomType, isotopeNumber, worldCoord, makePseudoAtom)); if (getUndoRedoFactory() != null && getUndoRedoHandler() != null) { IUndoRedoable undoredo = getUndoRedoFactory() .getAddAtomsAndBondsEdit(chemModel, undoRedoSet, null, "Add Atom", this); getUndoRedoHandler().postEdit(undoredo); } return undoRedoSet.getSingleAtom(); } // OK /* * (non-Javadoc) * * @see * org.openscience.cdk.controller.IChemModelRelay#addAtomWithoutUndo(java * .lang.String, javax.vecmath.Point2d) */ public IAtom addAtomWithoutUndo(String atomType, Point2d worldCoord, boolean makePseudoAtom) { return addAtomWithoutUndo(atomType, 0, worldCoord, makePseudoAtom); } // OK /* * (non-Javadoc) * * @see * org.openscience.cdk.controller.IChemModelRelay#addAtomWithoutUndo(java * .lang.String, int, javax.vecmath.Point2d) */ public IAtom addAtomWithoutUndo(String atomType, int isotopeNumber, Point2d worldCoord, boolean makePseudoAtom) { IAtom newAtom; if (makePseudoAtom) { newAtom = makePseudoAtom(atomType, worldCoord); } else { newAtom = chemModel.getBuilder().newInstance(IAtom.class,atomType, worldCoord); } if (isotopeNumber != 0) newAtom.setMassNumber(isotopeNumber); // FIXME : there should be an initial hierarchy? IAtomContainerSet molSet = chemModel.getMoleculeSet(); if (molSet == null) { molSet = chemModel.getBuilder().newInstance(IAtomContainerSet.class); IAtomContainer ac = chemModel.getBuilder().newInstance(IAtomContainer.class); ac.addAtom(newAtom); molSet.addAtomContainer(ac); chemModel.setMoleculeSet(molSet); } IAtomContainer newAtomContainer = chemModel.getBuilder().newInstance(IAtomContainer.class); if (chemModel.getMoleculeSet().getAtomContainer(0).getAtomCount() == 0) newAtomContainer = (IAtomContainer) chemModel.getMoleculeSet() .getAtomContainer(0); else molSet.addAtomContainer(newAtomContainer); newAtomContainer.addAtom(newAtom); updateAtom(newAtom); JChemPaintRendererModel model = this.getRenderer().getRenderer2DModel(); double nudgeDistance = model.getHighlightDistance() / model.getScale(); if (getClosestAtom(newAtom) != null) newAtom.getPoint2d().x += nudgeDistance; structureChanged(); return newAtom; } // OK public IAtom addAtom(String atomType, IAtom atom, boolean makePseudoAtom) { AtomBondSet undoRedoSet = new AtomBondSet(); undoRedoSet.add(addAtomWithoutUndo(atomType, atom, makePseudoAtom)); IAtomContainer atomContainer = ChemModelManipulator .getRelevantAtomContainer(getIChemModel(), undoRedoSet.getSingleAtom()); IBond newBond = atomContainer.getBond(atom, undoRedoSet.getSingleAtom()); undoRedoSet.add(newBond); if (getUndoRedoFactory() != null && getUndoRedoHandler() != null) { IUndoRedoable undoredo = getUndoRedoFactory() .getAddAtomsAndBondsEdit(chemModel, undoRedoSet, null, "Add Atom", this); getUndoRedoHandler().postEdit(undoredo); } return undoRedoSet.getSingleAtom(); } // OK /* * (non-Javadoc) * * @see * org.openscience.cdk.controller.IChemModelRelay#addAtomWithoutUndo(java * .lang.String, org.openscience.cdk.interfaces.IAtom) */ public IAtom addAtomWithoutUndo(String atomType, IAtom atom, boolean makePseudoAtom) { return addAtomWithoutUndo(atomType, atom, Display.Solid, makePseudoAtom); } public IAtom addAtomWithoutUndo(String atomType, IAtom atom, IBond.Display display, Order order, boolean makePseudoAtom) { return addAtomWithoutUndo(atomType, atom, display, order, makePseudoAtom, false); } private static boolean isLeft(Point2d a, Point2d b, Point2d c) { return (b.x - a.x)*(c.y - a.y) - (b.y - a.y)*(c.x - a.x) > 0; } private static boolean isLeft(IAtom a, IAtom b, IAtom c) { return isLeft(a.getPoint2d(), b.getPoint2d(), c.getPoint2d()); } private static void reflect(Tuple2d p, Tuple2d base, double a, double b) { double x = a * (p.x - base.x) + b * (p.y - base.y) + base.x; double y = b * (p.x - base.x) - a * (p.y - base.y) + base.y; p.x = x; p.y = y; } private void reflect(Point2d p, Tuple2d begP, Tuple2d endP) { double dx = endP.x - begP.x; double dy = endP.y - begP.y; double a = (dx * dx - dy * dy) / (dx * dx + dy * dy); double b = 2 * dx * dy / (dx * dx + dy * dy); reflect(p, begP, a, b); } public IAtom addAtomWithoutUndo(String atomType, IAtom atom, IBond.Display display, Order order, boolean makePseudoAtom, boolean phantom) { return addAtomWithoutUndo(atomType, atom, display, order, makePseudoAtom, phantom, altMode); } /* * @param cyclicMode sprouts the bond in cyclic mode (as opposed to linear) */ public IAtom addAtomWithoutUndo(String atomType, IAtom atom, IBond.Display display, Order order, boolean makePseudoAtom, boolean phantom, boolean cyclicMode) { IAtomContainer atomCon = ChemModelManipulator.getRelevantAtomContainer(chemModel, atom); IAtom newAtom; if (makePseudoAtom) { newAtom = makePseudoAtom(atomType, null); } else { newAtom = chemModel.getBuilder().newInstance(IAtom.class,atomType); } IBond newBond = chemModel.getBuilder().newInstance(IBond.class,atom, newAtom, order); newBond.setDisplay(display); if (atomCon == null) { atomCon = chemModel.getBuilder().newInstance(IAtomContainer.class); IAtomContainerSet moleculeSet = chemModel.getMoleculeSet(); if (moleculeSet == null) { moleculeSet = chemModel.getBuilder().newInstance(IAtomContainerSet.class); chemModel.setMoleculeSet(moleculeSet); } moleculeSet.addAtomContainer(atomCon); } // The AtomPlacer generates coordinates for the new atom AtomPlacer atomPlacer = new AtomPlacer(); // need a temporary container for AtomPlacer to work correctly IAtomContainer tmp = atomCon.getBuilder().newAtomContainer(); tmp.add(atomCon); tmp.addAtom(newAtom); tmp.newBond(atom, newAtom); atomPlacer.setMolecule(tmp); double bondLength; if (atomCon.getBondCount() >= 1) { bondLength = Renderer.calculateBondLength(atomCon); } else { bondLength = Renderer.calculateBondLength(chemModel.getMoleculeSet()); } // determine the atoms which define where the // new atom should not be placed List<IAtom> connectedAtoms = atomCon.getConnectedAtomsList(atom); if (connectedAtoms.isEmpty()) { Point2d newAtomPoint = new Point2d(atom.getPoint2d()); double angle = Math.toRadians(-30); Vector2d vec1 = new Vector2d(Math.cos(angle), Math.sin(angle)); vec1.scale(bondLength); newAtomPoint.add(vec1); newAtom.setPoint2d(newAtomPoint); } else if (connectedAtoms.size() == 1) { IAtomContainer ac = atomCon.getBuilder().newInstance(IAtomContainer.class); ac.addAtom(atom); ac.addAtom(newAtom); Point2d distanceMeasure = new Point2d(0, 0); // XXX not sure about // this? IAtom connectedAtom = connectedAtoms.get(0); Vector2d v = atomPlacer.getNextBondVector(atom, connectedAtom, distanceMeasure, true); v.normalize(); v.scale(bondLength); Point2d p = new Point2d(atom.getPoint2d().x + v.x, atom.getPoint2d().y + v.y); newAtom.setPoint2d(p); // if we place the bond flipped before and it was undo/redone // (there is only a single atom connected) then we do the opposite boolean flip = false; if (atom.getProperty("placeFlipped") != null) { flip = !atom.<Boolean>getProperty("placeFlipped"); } // no previous default, first place should be a zig-zag else if (flipChainAngle(connectedAtom, atom, newAtom)) { flip = true; } // alt-mode switches from whatever has been decided if (cyclicMode) flip = !flip; if (flip) reflect(newAtom.getPoint2d(), atom.getPoint2d(), connectedAtom.getPoint2d()); if (!phantom) { atom.setProperty("placeFlipped", flip); } } else { IAtomContainer placedAtoms = atomCon.getBuilder().newAtomContainer(); for (IAtom conAtom : connectedAtoms) placedAtoms.addAtom(conAtom); Point2d center2D = GeometryUtil.get2DCenter(placedAtoms); IAtomContainer unplacedAtoms = atomCon.getBuilder() .newInstance(IAtomContainer.class); unplacedAtoms.addAtom(newAtom); atomPlacer.distributePartners(atom, placedAtoms, center2D, unplacedAtoms, bondLength); } if (phantom) { phantoms.addAtom(atom); phantoms.addAtom(newAtom); phantoms.addBond(newBond); } else { atomCon.addAtom(newAtom); atomCon.addBond(newBond); updateAtom(newBond.getAtom(0)); updateAtom(newBond.getAtom(1)); newAtom = atomCon.getAtom(atomCon.getAtomCount()-1); } // shift the new atom a bit if it is in range of another atom JChemPaintRendererModel model = this.getRenderer().getRenderer2DModel(); double nudgeDistance = model.getHighlightDistance() / model.getScale(); if (getClosestAtom(newAtom) != null) newAtom.getPoint2d().x += nudgeDistance; structureChanged(); return newAtom; } private static boolean flipChainAngle(IAtom prevAtom, IAtom atom, IAtom newAtom) { IAtom reference = null; if (prevAtom.getBondCount() == 2) { for (IBond bond : prevAtom.bonds()) { IAtom nbor = bond.getOther(prevAtom); if (!nbor.equals(atom)) reference = nbor; } } else if (prevAtom.getBondCount() > 2) { for (IBond bond : prevAtom.bonds()) { IAtom nbor = bond.getOther(prevAtom); if (!nbor.equals(atom) && nbor.getBondCount() != 1) { if (reference != null) { reference = null; break; } reference = nbor; } } if (reference == null) { // no reference, avoid sprouting directly up/down if (Math.abs(atom.getPoint2d().x - newAtom.getPoint2d().x) <= 0.01) return true; } } if (reference != null && isLeft(atom, prevAtom, reference) == isLeft(atom, prevAtom, newAtom)) { return true; // on same side so flip! } return false; } public IAtom addAtomWithoutUndo(String atomType, IAtom atom, IBond.Display display, boolean makePseudoAtom) { return addAtomWithoutUndo(atomType, atom, display, IBond.Order.SINGLE, makePseudoAtom); } // OK public void addNewBond(Point2d worldCoordinate, boolean makePseudoAtom) { AtomBondSet undoRedoSet = new AtomBondSet(); // add the first atom in the new bond String atomType = getController2DModel().getDrawElement(); IAtom atom = addAtomWithoutUndo(atomType, worldCoordinate, makePseudoAtom); undoRedoSet.add(atom); // add the second atom to this IAtom newAtom = addAtomWithoutUndo(atomType, atom, makePseudoAtom); undoRedoSet.add(newAtom); IAtomContainer atomContainer = ChemModelManipulator .getRelevantAtomContainer(getIChemModel(), newAtom); IBond newBond = atomContainer.getBond(atom, newAtom); undoRedoSet.add(newBond); updateAtom(newBond.getAtom(0)); updateAtom(newBond.getAtom(1)); structureChanged(); if (undoredofactory != null && undoredohandler != null) { IUndoRedoable undoredo = undoredofactory.getAddAtomsAndBondsEdit( getIChemModel(), undoRedoSet, null, "Add Bond", this); undoredohandler.postEdit(undoredo); } } /** * Alternative input mode allow different actions when alt is held. * @param value activate/deactivate * @return mode was changed or not */ public boolean setAltInputMode(boolean value) { if (altMode != value) { altMode = value; return true; } else { return false; } } public void addAtom(IAtom atom, int atno, boolean cyclicMode) { addAtom(atom, atno, Order.SINGLE, cyclicMode); } public void addAtom(IAtom atom, int atno, IBond.Order order, boolean cyclicMode) { addAtom(atom, atno, order, Display.Solid, cyclicMode); } /** * Sprout a single atom * * @param atom the atom * @param atno the atomic number * @param cyclicMode the cyclicMode mode, false = zig/zag chain. */ public void addAtom(IAtom atom, int atno, IBond.Order order, IBond.Display stereo, boolean cyclicMode) { atom.removeProperty("placeFlipped"); IAtom newAtom = addAtomWithoutUndo(Elements.ofNumber(atno).symbol(), atom, stereo, order, false, false, cyclicMode); renderer.getRenderer2DModel().setHighlightedAtom(newAtom); if (getUndoRedoHandler() != null) { IAtomContainer container = ChemModelManipulator .getRelevantAtomContainer(getIChemModel(), newAtom); AtomBondSet atomBondSet = new AtomBondSet(); atomBondSet.add(newAtom); atomBondSet.add(container.getConnectedBondsList(newAtom).get(0)); IUndoRedoable undoredo = new AddAtomsAndBondsEdit(this.getIChemModel(), atomBondSet, container, "Add Bond", this); getUndoRedoHandler().postEdit(undoredo); } } public void addAcetyl(IAtom atom) { AtomBondSet undoRedoSet = new AtomBondSet(); int freeValence = atom.getImplicitHydrogenCount(); IAtomContainer container = ChemModelManipulator.getRelevantAtomContainer(getChemModel(), atom); if (freeValence == 1) { clearPhantoms(); IAtom c1 = addAtomWithoutUndo("C", atom, Display.Solid, Order.SINGLE, false, false, false); IAtom c2 = addAtomWithoutUndo("C", c1, Display.Solid, Order.SINGLE, false, false, false); IAtom o = addAtomWithoutUndo("O", c1, Display.Solid, Order.DOUBLE, false, false, false); undoRedoSet.add(c1); undoRedoSet.add(c2); undoRedoSet.add(o); for (IBond bond : container.getConnectedBondsList(c1)) undoRedoSet.add(bond); getRenderer().getRenderer2DModel().setHighlightedAtom(c2); } else if (freeValence == 2) { clearPhantoms(); IAtom o = addAtomWithoutUndo("O", atom, Display.Solid, Order.DOUBLE, false, false, false); undoRedoSet.add(o); for (IBond bond : container.getConnectedBondsList(o)) undoRedoSet.add(bond); } else if (freeValence > 2) { clearPhantoms(); IAtom c = addAtomWithoutUndo("C", atom, Display.Solid, Order.SINGLE, false, false, false); IAtom o = addAtomWithoutUndo("O", atom, Display.Solid, Order.DOUBLE, false, false, false); undoRedoSet.add(c); undoRedoSet.add(o); for (IBond bond : container.getConnectedBondsList(c)) undoRedoSet.add(bond); for (IBond bond : container.getConnectedBondsList(o)) undoRedoSet.add(bond); getRenderer().getRenderer2DModel().setHighlightedAtom(c); } if (getUndoRedoHandler() != null) { getUndoRedoHandler().postEdit(new AddAtomsAndBondsEdit(getIChemModel(), undoRedoSet, null, "Acetyl", this)); } } public void addDimethyl(IAtom atom, IBond.Display display) { AtomBondSet undoRedoSet = new AtomBondSet(); int freeValence = atom.getImplicitHydrogenCount(); IAtomContainer container = ChemModelManipulator.getRelevantAtomContainer(getChemModel(), atom); if (freeValence == 1) { if (display == Display.Solid) { clearPhantoms(); IAtom c = addAtomWithoutUndo("C", atom, Display.Solid, Order.SINGLE, false, false, false); IAtom me1 = addAtomWithoutUndo("C", c, Display.Solid, Order.SINGLE, false, false, false); IAtom me2 = addAtomWithoutUndo("C", c, Display.Solid, Order.SINGLE, false, false, false); undoRedoSet.add(c); undoRedoSet.add(me1); undoRedoSet.add(me2); for (IBond bond : container.getConnectedBondsList(c)) undoRedoSet.add(bond); getRenderer().getRenderer2DModel().setHighlightedAtom(me1); } else { addAtom(atom, IAtom.C, Order.SINGLE, display, false); } } else if (freeValence >= 2) { clearPhantoms(); IAtom me1 = addAtomWithoutUndo("C", atom, Display.Solid, Order.SINGLE, false, false, false); IAtom me2 = addAtomWithoutUndo("C", atom, display, Order.SINGLE, false, false, false); undoRedoSet.add(me1); undoRedoSet.add(me2); for (IBond bond : container.getConnectedBondsList(me1)) undoRedoSet.add(bond); for (IBond bond : container.getConnectedBondsList(me2)) undoRedoSet.add(bond); getRenderer().getRenderer2DModel().setHighlightedAtom(me1); } if (getUndoRedoHandler() != null) { getUndoRedoHandler().postEdit(new AddAtomsAndBondsEdit(getIChemModel(), undoRedoSet, null, "Dimethyl", this)); } } /** * Select all atoms which are in the same container as the provided root * atom. In altMode the fragment is flood-filled based on weather the * provided atom is acyclic/acyclic. * * @param root an atom to select from */ public void selectFragment(IAtom root) { LogicalSelection selection = new LogicalSelection(LogicalSelection.Type.ALL); IAtomContainer container = ChemModelManipulator.getRelevantAtomContainer(getChemModel(), root); if (container != null) { if (altMode) { // flood fill atoms/bonds which are cyclic/acyclic Cycles.markRingAtomsAndBonds(container); Set<IChemObject> set = new HashSet<>(); Deque<IAtom> queue = new ArrayDeque<>(); queue.add(root); while (!queue.isEmpty()) { IAtom atom = queue.poll(); set.add(atom); for (IBond bond : atom.bonds()) { if (bond.isInRing() == root.isInRing()) { set.add(bond); IAtom nbor = bond.getOther(atom); if (!set.contains(nbor)) queue.add(nbor); } } } for (IChemObject obj : set) selection.select(obj); } else { selection.select(container); } } select(selection); } /** * Select all bonds which are in the same container as the provided bond. * In altMode the fragment is flood-filled based on weather the * provided bond is acyclic/acyclic. * * @param root the bond to select from */ public void selectFragment(IBond root) { LogicalSelection selection = new LogicalSelection(LogicalSelection.Type.ALL); IAtomContainer container = ChemModelManipulator.getRelevantAtomContainer(getChemModel(), root); if (container != null) { if (altMode) { // flood fill atoms/bonds which are cyclic/acyclic Cycles.markRingAtomsAndBonds(container); Set<IChemObject> set = new HashSet<>(); Deque<IAtom> queue = new ArrayDeque<>(); queue.add(root.getBegin()); queue.add(root.getEnd()); while (!queue.isEmpty()) { IAtom atom = queue.poll(); set.add(atom); for (IBond bond : atom.bonds()) { if (bond.isInRing() == root.isInRing()) { set.add(bond); IAtom nbor = bond.getOther(atom); if (!set.contains(nbor)) queue.add(nbor); } } } for (IChemObject obj : set) selection.select(obj); } else { selection.select(container); } } select(selection); } /** * Class tracks when a bond order is increased and when. */ private static final class CycledBond { IBond bond; long time; private CycledBond(IBond bond) { this.bond = bond; this.time = System.nanoTime(); } boolean expired(IBond bond) { long deltaT = System.nanoTime() - time; return this.bond == null || !bond.equals(this.bond) || TimeUnit.NANOSECONDS.toMillis(deltaT) > 2500; } } private void flipBonds(List<IBond> path, boolean tautomer) { Map<IBond,Order[]> changedBonds = new LinkedHashMap<>(); Map<IAtom,Integer[]> changedAtoms = new LinkedHashMap<>(); for (IBond b : path) { if (b.getOrder() == Order.SINGLE) changedBonds.put(b, new Order[]{Order.DOUBLE, Order.SINGLE}); else if (b.getOrder() == Order.DOUBLE) changedBonds.put(b, new Order[]{Order.SINGLE, Order.DOUBLE}); } String description = tautomer ? "Tautomer 1," + (path.size() + 1) + "-shift" : "Alternative Kekule From"; AdjustBondOrdersEdit adjustBondOrders = new AdjustBondOrdersEdit(changedBonds, Collections.emptyMap(), "Change Bond Orders", this); CompoundEdit edit = new CompoundEdit(description); if (tautomer) { // tautomers need their hydrogen count changed, note update atoms // can get in the way here but seems to work okay on O,S,N,P int last = path.size()-1; IBond begBond = path.get(0); IBond endBond = path.get(last); IAtom begAtom = begBond.getOther(begBond.getConnectedAtom(path.get(1))); IAtom endAtom = endBond.getOther(endBond.getConnectedAtom(path.get(last - 1))); if (begBond.getOrder() == Order.DOUBLE) { changedAtoms.put(begAtom, new Integer[]{begAtom.getImplicitHydrogenCount()+1, begAtom.getImplicitHydrogenCount()}); changedAtoms.put(endAtom, new Integer[]{endAtom.getImplicitHydrogenCount()-1, endAtom.getImplicitHydrogenCount()}); } else { changedAtoms.put(begAtom, new Integer[]{begAtom.getImplicitHydrogenCount()-1, begAtom.getImplicitHydrogenCount()}); changedAtoms.put(endAtom, new Integer[]{endAtom.getImplicitHydrogenCount()+1, endAtom.getImplicitHydrogenCount()}); } // we need to set the hydrogen counts forward/backwards because // otherwise the automatic CDK atom typing messes things up edit.add(new ChangeHydrogenCountEdit(changedAtoms, "Change Hydrogen Counts")); edit.add(adjustBondOrders); edit.add(new ChangeHydrogenCountEdit(changedAtoms, "Change Hydrogen Counts")); } else { edit.add(adjustBondOrders); } edit.redo(); // fire the changes if (undoredofactory != null && undoredohandler != null) { undoredohandler.postEdit(edit); } } /** * Cycle to an alternative Kekulé form. * * @param bond a bond in the alternating path * @return the kekulé form was alternated */ private boolean cycleKekuleForm(IBond bond) { List<IBond> path = new ArrayList<>(6); if (ConjugationTools.findAlternating(path, bond)) { flipBonds(path, false); // atom update shouldn't be needed since we shifted the bonds // but the hybridisation didn't change updateView(); return true; } if (ConjugationTools.findTautomerShift(path, bond)) { flipBonds(path, true); updateView(); return true; } return false; } CycledBond cycledBond = new CycledBond(null); // OK public void cycleBondValence(IBond bond) { cycleBondValence(bond, IBond.Order.SINGLE); } public void cycleBondValence(IBond bond, IBond.Order order) { IBond.Order[] orders = new IBond.Order[2]; IBond.Display[] stereos = new IBond.Display[2]; orders[1] = bond.getOrder(); stereos[1] = bond.getDisplay(); if (altMode) { cycleKekuleForm(bond); return; } // special case : reset stereo bonds if (bond.getDisplay() != Display.Solid ) { bond.setDisplay(Display.Solid); bond.setOrder(order); } else { if (order == IBond.Order.SINGLE) { switch (bond.getOrder()) { case SINGLE: bond.setOrder(Order.DOUBLE); cycledBond = new CycledBond(bond); break; case DOUBLE: if (cycledBond.expired(bond)) { bond.setOrder(Order.SINGLE); } else { bond.setOrder(Order.TRIPLE); } break; case TRIPLE: bond.setOrder(Order.SINGLE); break; } } else { if (bond.getOrder() != order) { bond.setOrder(order); } else { bond.setOrder(IBond.Order.SINGLE); } } } orders[0] = bond.getOrder(); stereos[0] = bond.getDisplay(); Map<IBond, IBond.Order[]> changedBonds = new HashMap<IBond, IBond.Order[]>(); Map<IBond, IBond.Display[]> changedBondsStereo = new HashMap<IBond, IBond.Display[]>(); changedBonds.put(bond, orders); changedBondsStereo.put(bond, stereos); // set hybridization from bond order bond.getAtom(0).setHybridization(null); bond.getAtom(1).setHybridization(null); updateAtom(bond.getAtom(0)); updateAtom(bond.getAtom(1)); structureChanged(); if (undoredofactory != null && undoredohandler != null) { IUndoRedoable undoredo = undoredofactory .getAdjustBondOrdersEdit(changedBonds, changedBondsStereo, "Adjust Bond Order", this); undoredohandler.postEdit(undoredo); } } // OK public IBond makeNewStereoBond(IAtom atom, Direction desiredDirection) { String atomType = getController2DModel().getDrawElement(); IAtom newAtom = addAtomWithoutUndo(atomType, atom, controllerModel .getDrawPseudoAtom()); AtomBondSet undoRedoSet = new AtomBondSet(); // XXX these calls would not be necessary if addAtom returned a bond IAtomContainer atomContainer = ChemModelManipulator .getRelevantAtomContainer(getIChemModel(), newAtom); IBond newBond = atomContainer.getBond(atom, newAtom); if (desiredDirection == Direction.UP) { newBond.setDisplay(IBond.Display.Up); } else if (desiredDirection == Direction.DOWN) { newBond.setDisplay(IBond.Display.Down); } else if (desiredDirection == Direction.UNDEFINED) { newBond.setDisplay(IBond.Display.Wavy); } else { newBond.setDisplay(IBond.Display.Crossed); } undoRedoSet.add(newAtom); undoRedoSet.add(newBond); if (getUndoRedoFactory() != null && getUndoRedoHandler() != null) { IUndoRedoable undoredo = getUndoRedoFactory() .getAddAtomsAndBondsEdit(getIChemModel(), undoRedoSet, null, "Add Stereo Bond", this); getUndoRedoHandler().postEdit(undoredo); } return newBond; } // OK public void moveToWithoutUndo(IAtom atom, Point2d worldCoords) { if (atom != null) { Point2d atomCoord = new Point2d(worldCoords); atom.setPoint2d(atomCoord); } coordinatesChanged(); } // OK public void moveTo(IAtom atom, Point2d worldCoords) { if (atom != null) { if (getUndoRedoFactory() != null && getUndoRedoHandler() != null) { IAtomContainer undoRedoSet = chemModel.getBuilder() .newInstance(IAtomContainer.class); undoRedoSet.addAtom(atom); Vector2d end = new Vector2d(); end.sub(worldCoords, atom.getPoint2d()); IUndoRedoable undoredo = getUndoRedoFactory().getMoveAtomEdit( undoRedoSet, end, "Move atom"); getUndoRedoHandler().postEdit(undoredo); } moveToWithoutUndo(atom, worldCoords); } } // OK public void moveToWithoutUndo(IBond bond, Point2d point) { if (bond != null) { Point2d center = bond.get2DCenter(); for (IAtom atom : bond.atoms()) { Vector2d offset = new Vector2d(); offset.sub(atom.getPoint2d(), center); Point2d result = new Point2d(); result.add(point, offset); atom.setPoint2d(result); } } coordinatesChanged(); } // OK public void moveTo(IBond bond, Point2d point) { if (bond != null) { if (getUndoRedoFactory() != null && getUndoRedoHandler() != null) { IAtomContainer undoRedoSet = chemModel.getBuilder() .newInstance(IAtomContainer.class); undoRedoSet.addAtom(bond.getAtom(0)); undoRedoSet.addAtom(bond.getAtom(1)); Vector2d end = new Vector2d(); end.sub(point, bond.getAtom(0).getPoint2d()); IUndoRedoable undoredo = getUndoRedoFactory().getMoveAtomEdit( undoRedoSet, end, "Move atom"); getUndoRedoHandler().postEdit(undoredo); } moveToWithoutUndo(bond, point); } } /* * (non-Javadoc) * * @see * org.openscience.cdk.controller.IChemModelRelay#addBond(org.openscience * .cdk.interfaces.IAtom, org.openscience.cdk.interfaces.IAtom, int) */ public IBond addBond(IAtom fromAtom, IAtom toAtom, IBond.Display display, IBond.Order order) { IBond newBond = chemModel.getBuilder().newInstance(IBond.class,fromAtom, toAtom, order); newBond.setDisplay(display); IAtomContainer fromContainer = ChemModelManipulator .getRelevantAtomContainer(chemModel, fromAtom); IAtomContainer toContainer = ChemModelManipulator .getRelevantAtomContainer(chemModel, toAtom); // we need to check if this merges two atom containers or not if (fromContainer != toContainer) { fromContainer.add(toContainer); chemModel.getMoleculeSet().removeAtomContainer(toContainer); } fromContainer.addBond(newBond); updateAtom(newBond.getAtom(0)); updateAtom(newBond.getAtom(1)); structureChanged(); return newBond; } public IBond addBond(IAtom fromAtom, IAtom toAtom, IBond.Display stereo) { return addBond(fromAtom, toAtom, stereo, IBond.Order.SINGLE); } // OK /* * (non-Javadoc) * * @see * org.openscience.cdk.controller.IChemModelRelay#addBond(org.openscience * .cdk.interfaces.IAtom, org.openscience.cdk.interfaces.IAtom) */ public IBond addBond(IAtom fromAtom, IAtom toAtom) { return addBond(fromAtom, toAtom, Display.Solid, IBond.Order.SINGLE); } // OK public void setCharge(IAtom atom, int charge) { if (getUndoRedoFactory() != null && getUndoRedoHandler() != null) { IUndoRedoable undoredo = getUndoRedoFactory().getChangeChargeEdit( atom, atom.getFormalCharge(), charge, "Change charge to " + charge, this); getUndoRedoHandler().postEdit(undoredo); } atom.setFormalCharge(charge); updateAtom(atom); structurePropertiesChanged(); } // OK public void setMassNumber(IAtom atom, int massNumber) { if (getUndoRedoFactory() != null && getUndoRedoHandler() != null) { IUndoRedoable undoredo = getUndoRedoFactory().getChangeIsotopeEdit( atom, atom.getMassNumber(), massNumber, "Change Atomic Mass to " + massNumber); getUndoRedoHandler().postEdit(undoredo); } atom.setMassNumber(massNumber); structurePropertiesChanged(); } public void changeBond(IBond bond, Order order, Display display) { changeBonds(Collections.singletonList(bond), order, display); } private static boolean atWideEndOfAnotherWedge(IAtom atom) { for (IBond bond : atom.bonds()) { switch (bond.getDisplay()) { case Bold: case Hash: return true; case WedgeBegin: case WedgedHashBegin: return bond.getEnd().equals(atom); case WedgeEnd: case WedgedHashEnd: return bond.getBegin().equals(atom); } } return false; } public void changeBonds(Collection<IBond> bonds, Order order, Display display) { Map<IBond, Order[]> orderChanges = new LinkedHashMap<>(); Map<IBond, Stereo[]> stereoChanges = new LinkedHashMap<>(); Map<IBond, Display[]> displayChanges = new LinkedHashMap<>(); for (IBond bond : bonds) { if (bond.getOrder() != order) orderChanges.put(bond, new Order[]{order, bond.getOrder()}); // flip wedges: if the bond is already wedged, and it is wedged the same // wedge direction, the intention is to flip the ordering // C < O (WedgeBegin) => C > O (WedgeEnd) if (display == bond.getDisplay() && display.flip() != display) { displayChanges.put(bond, new Display[]{display.flip(), bond.getDisplay()}); } else if (display != bond.getDisplay()) { if (display != Display.Solid && bond.getDisplay() == Display.Solid) { IAtom begin = bond.getBegin(); IAtom end = bond.getEnd(); // end has more bonds => more likely tetrahedral, or // we already have a wide of a wedge next to us if (end.getBondCount() > begin.getBondCount() || end.getBondCount() == begin.getBondCount() && atWideEndOfAnotherWedge(begin)) display = display.flip(); } displayChanges.put(bond, new Display[]{display, bond.getDisplay()}); } } AdjustBondOrdersEdit edit = new AdjustBondOrdersEdit(orderChanges, stereoChanges, displayChanges, "Set bond order/stereo", this); edit.redo(); // make the changes structureChanged(); if (getUndoRedoFactory() != null && getUndoRedoHandler() != null) { getUndoRedoHandler().postEdit(edit); } } public void setSymbol(IAtom atom, String symbol) { setSymbol(atom, symbol, null); } /** * Change the Atom Symbol to the given element symbol, setting also its massNumber. * If an exception happens, the massNumber is set to null. * @see org.openscience.jchempaint.controller.IAtomBondEdits#setSymbol(org.openscience.cdk.interfaces.IAtom, java.lang.String) */ public void setSymbol(IAtom atom, String symbol, Integer massNumber) { CompoundEdit edit = new CompoundEdit("Change atom to " + symbol); boolean newIsPseudo = Elements.ofString(symbol) == Elements.Unknown; boolean swap = atom instanceof IPseudoAtom || newIsPseudo; if (swap) { IAtom newAtom; if (newIsPseudo) { newAtom = makePseudoAtom(symbol, null); } else { newAtom = atom.getBuilder().newInstance(IAtom.class, symbol); } newAtom.setPoint2d(atom.getPoint2d()); edit.add(new ReplaceAtomEdit(this.getIChemModel(), atom, newAtom, "Change atom to " + symbol)); } else { edit.add(new ChangeAtomSymbolEdit(atom, atom.getSymbol(), symbol, this)); } edit.add(new ChangeIsotopeEdit(atom, atom.getMassNumber(), massNumber, "Change Mass Number to " + massNumber)); edit.redo(); structurePropertiesChanged(); if (getUndoRedoHandler() != null) { getUndoRedoHandler().postEdit(edit); } } // OK public void updateImplicitHydrogenCounts() { Map<IAtom, Integer[]> atomHydrogenCountsMap = new HashMap<IAtom, Integer[]>(); for (IAtomContainer container : ChemModelManipulator .getAllAtomContainers(chemModel)) { for (IAtom atom : container.atoms()) { if (!(atom instanceof IPseudoAtom)) { try { IAtomType type = matcher.findMatchingAtomType(container, atom); if (type != null && !type.getAtomTypeName().equals("X") && type.getFormalNeighbourCount() != null) { int connectedAtomCount = container .getConnectedAtomsCount(atom); atomHydrogenCountsMap.put(atom, new Integer[]{ type.getFormalNeighbourCount() - connectedAtomCount, atom.getImplicitHydrogenCount()}); atom.setImplicitHydrogenCount(type.getFormalNeighbourCount() - connectedAtomCount); } else { atom.setImplicitHydrogenCount(0); } } catch (CDKException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } if (getUndoRedoFactory() != null && getUndoRedoHandler() != null) { IUndoRedoable undoredo = getUndoRedoFactory() .getChangeHydrogenCountEdit(atomHydrogenCountsMap, "Update implicit hydrogen count"); getUndoRedoHandler().postEdit(undoredo); } structurePropertiesChanged(); } public void zap() { if (getUndoRedoFactory() != null && getUndoRedoHandler() != null) { IUndoRedoable undoredo = getUndoRedoFactory().getClearAllEdit( chemModel, chemModel.getMoleculeSet(), chemModel.getReactionSet(), "Clear Panel"); getUndoRedoHandler().postEdit(undoredo); } if (chemModel.getMoleculeSet() != null) { IAtomContainerSet molSet = chemModel.getBuilder().newInstance(IAtomContainerSet.class); IAtomContainer ac = chemModel.getBuilder().newInstance(IAtomContainer.class); molSet.addAtomContainer(ac); chemModel.setMoleculeSet(molSet); } if (chemModel.getReactionSet() != null) chemModel.setReactionSet(chemModel.getBuilder().newInstance(IReactionSet.class)); structureChanged(); } // OK public void makeBondStereo(IBond bond, Direction desiredDirection) { IBond.Display stereo = bond.getDisplay(); boolean isUp = isUp(stereo); boolean isDown = isDown(stereo); boolean isUndefined = isUndefined(stereo); if (isUp && desiredDirection == Direction.UP) { flipDirection(bond, stereo); } else if (isDown && desiredDirection == Direction.DOWN) { flipDirection(bond, stereo); } else if (isUndefined && desiredDirection == Direction.UNDEFINED) { flipDirection(bond, stereo); } else if (desiredDirection == Direction.EZ_UNDEFINED) { bond.setDisplay(Display.Crossed); } else if (desiredDirection == Direction.UNDEFINED) { bond.setDisplay(Display.Wavy); } else if (desiredDirection == Direction.UP) { bond.setDisplay(Display.Up); } else if (desiredDirection == Direction.DOWN) { bond.setDisplay(Display.Down); } IBond.Display[] displays = new IBond.Display[2]; displays[1] = stereo; displays[0] = bond.getDisplay(); Map<IBond, IBond.Order[]> changedBonds = new HashMap<IBond, IBond.Order[]>(); Map<IBond, IBond.Display[]> changedBondsStereo = new HashMap<IBond, IBond.Display[]>(); changedBondsStereo.put(bond, displays); updateAtom(bond.getAtom(0)); updateAtom(bond.getAtom(1)); structureChanged(); if (getUndoRedoFactory() != null && getUndoRedoHandler() != null) { IUndoRedoable undoredo = getUndoRedoFactory() .getAdjustBondOrdersEdit(changedBonds, changedBondsStereo, "Adjust Bond Stereo", this); getUndoRedoHandler().postEdit(undoredo); } } /** * Change the stereo bond from start->end to start<-end. * * @param bond * the bond to change * @param stereo * the current stereo of that bond */ private void flipDirection(IBond bond, IBond.Display stereo) { bond.setDisplay(stereo.flip()); } private boolean isUp(IBond.Display stereo) { return stereo == Display.WedgeBegin || stereo == Display.WedgeEnd || stereo == Display.HollowWedgeBegin || stereo == Display.HollowWedgeEnd; } private boolean isDown(IBond.Display stereo) { return stereo == Display.WedgedHashBegin || stereo == Display.WedgedHashEnd; } private boolean isUndefined(IBond.Display stereo) { return stereo == Display.Wavy; } public static void avoidOverlap(IChemModel chemModel){ //we avoid overlaps //first we shift down the reactions Rectangle2D usedReactionbounds=null; if(chemModel.getReactionSet()!=null){ for(IReaction reaction : chemModel.getReactionSet().reactions()){ // now move it so that they don't overlap Rectangle2D reactionbounds = BoundsCalculator.calculateBounds(reaction); if(usedReactionbounds!=null){ double bondLength = Renderer.calculateBondLength(reaction); Rectangle2D shiftedBounds = toRect(GeometryUtil.shiftReactionVertical( reaction, toArray(reactionbounds), toArray(usedReactionbounds), bondLength)); usedReactionbounds = usedReactionbounds.createUnion(shiftedBounds); } else { usedReactionbounds = reactionbounds; } } } //then we shift the molecules not to overlap Rectangle2D usedBounds = null; if(chemModel.getMoleculeSet()!=null){ List<IAtomContainer> containers = AtomContainerSetManipulator.getAllAtomContainers(chemModel.getMoleculeSet()); for (IAtomContainer container : containers) { // now move it so that they don't overlap Rectangle2D bounds = BoundsCalculator.calculateBounds(container); if (usedBounds != null) { double bondLength = Renderer.calculateBondLength(container); Rectangle2D shiftedBounds = toRect(GeometryUtil.shiftContainer(container, toArray(bounds), toArray(usedBounds), bondLength)); usedBounds = usedBounds.createUnion(shiftedBounds); } else { usedBounds = bounds; } } if (usedBounds != null) { double BOND_LENGTH = 1.5; for (IAtomContainer container : containers) { GeometryUtil.translate2D(container, -(usedBounds.getX() - BOND_LENGTH), -usedBounds.getY() - usedBounds.getHeight() - BOND_LENGTH); } } } //and the products/reactants in every reaction if(chemModel.getReactionSet()!=null){ for(IReaction reaction : chemModel.getReactionSet().reactions()){ usedBounds = null; double gap=0; double centerY=0; for (IAtomContainer container : ReactionManipulator.getAllAtomContainers(reaction)) { // now move it so that they don't overlap Rectangle2D bounds = BoundsCalculator.calculateBounds(container); if (usedBounds != null) { if(gap==0){ gap = Renderer.calculateBondLength(container); if(Double.isNaN(gap)) gap = 1.5; } Rectangle2D shiftedBounds = toRect(GeometryUtil.shiftContainer( container, toArray(bounds), toArray(usedBounds), gap*2)); double yshift=centerY - bounds.getCenterY(); Vector2d shift = new Vector2d(0.0, yshift); GeometryUtil.translate2D(container, shift); usedBounds = usedBounds.createUnion(shiftedBounds); } else { usedBounds = bounds; centerY = bounds.getCenterY(); } } //we shift the products an extra bit to make a larget gap between products and reactants for(IAtomContainer container : reaction.getProducts().atomContainers()){ Vector2d shift = new Vector2d(gap*2, 0.0); GeometryUtil.translate2D(container, shift); } } } //TODO overlaps of molecules in molecule set and reactions (ok, not too common, but still...) } private static double[] toArray(Rectangle2D rect) { return new double[]{rect.getMinX(), rect.getMinY(), rect.getMaxX(), rect.getMaxY()}; } private static Rectangle2D toRect(double[] bounds) { return new Rectangle2D.Double(bounds[0], bounds[1], bounds[2]-bounds[0], bounds[3]-bounds[1]); } // OK public void cleanup() { Map<IAtom, Point2d[]> coords = new HashMap<IAtom, Point2d[]>(); Map<IBond, IBond.Stereo> stereo = new HashMap<>(); // if there is a selection we clean up in-place IChemObjectSelection selection = getRenderer().getRenderer2DModel().getSelection(); IAtomContainer selected = selection.getConnectedAtomContainer(); if (selection.isFilled() && ConnectivityChecker.isConnected(selected)) { Set<IAtom> selectedAtoms = new HashSet<>(); for (IBond bond : selection.elements(IBond.class)) { selectedAtoms.add(bond.getBegin()); selectedAtoms.add(bond.getEnd()); } selectedAtoms.addAll(selection.elements(IAtom.class)); // crossing atoms/bonds Set<IAtom> xatoms = new HashSet<>(); Set<IBond> xbonds = new HashSet<>(); for (IAtomContainer container : ChemModelManipulator.getAllAtomContainers(chemModel)) { for (IBond bond : container.bonds()) { if (selectedAtoms.contains(bond.getBegin()) != selectedAtoms.contains(bond.getEnd())) xbonds.add(bond); } } for (IBond xbond : xbonds) { for (IAtom a : xbond.atoms()) { if (selectedAtoms.contains(a)) xatoms.add(a); } } if (xbonds.size() > 1) { // if we have two "leaving" bonds, check if there is a common atom, // we then move the anchor to that bond. if (xatoms.size() == 1) { xbonds.clear(); IAtom anchorAtom = xatoms.iterator().next(); for (IBond bond : ChemModelManipulator.getRelevantAtomContainer(getChemModel(), anchorAtom) .getConnectedBondsList(anchorAtom)) { if (selection.contains(bond)) xbonds.add(bond); } } } if (xatoms.size() > 1) return; Point2d oldCenter = GeometryUtil.get2DCenter(selected); for (IAtom atom : selected.atoms()) { coords.put(atom, new Point2d[]{ null, atom.getPoint2d()}); atom.setPoint2d(null); } for (IBond bond : selected.bonds()) { stereo.put(bond, bond.getStereo()); bond.setStereo(Stereo.NONE); } generateNewCoordinates(selected, xatoms, xbonds); // put the molecule back where it was Point2d newCenter = GeometryUtil.get2DCenter(selected); GeometryUtil.translate2D(selected, oldCenter.x - newCenter.x, oldCenter.y - newCenter.y); coordinatesChanged(); if (getUndoRedoFactory() != null && getUndoRedoHandler() != null) { IUndoRedoable undoredo = getUndoRedoFactory().getChangeCoordsEdit( coords, stereo,"Clean Up Selection"); getUndoRedoHandler().postEdit(undoredo); } return; } for (IAtomContainer container : ChemModelManipulator.getAllAtomContainers(chemModel)) { // ensure current stereo from 2D is set container.setStereoElements(StereoElementFactory.using2DCoordinates(container) .interpretProjections(Projection.Haworth, Projection.Chair) .createAll()); for (IAtom atom : container.atoms()) { coords.put(atom, new Point2d[]{ null, atom.getPoint2d()}); atom.setPoint2d(null); } for (IBond bond : container.bonds()) { stereo.put(bond, bond.getStereo()); bond.setStereo(Stereo.NONE); } generateNewCoordinates(container); for (IAtom atom : container.atoms()) { Point2d[] coordsforatom = coords.get(atom); coordsforatom[0] = atom.getPoint2d(); } } avoidOverlap(chemModel); if (rGroupHandler != null) { try { rGroupHandler.layoutRgroup(); } catch (CDKException ignore) { } } coordinatesChanged(); if (getUndoRedoFactory() != null && getUndoRedoHandler() != null) { IUndoRedoable undoredo = getUndoRedoFactory().getChangeCoordsEdit( coords, stereo,"Clean Up"); getUndoRedoHandler().postEdit(undoredo); } } public static void generateNewCoordinates(IAtomContainer container) { generateNewCoordinates(container, Collections.emptySet(), Collections.emptySet()); } public static void generateNewCoordinates(IAtomContainer container, Set<IAtom> afix, Set<IBond> bifx) { if (diagramGenerator == null) { diagramGenerator = new StructureDiagramGenerator(); } try { diagramGenerator.setMolecule(container, false, afix, bifx); diagramGenerator.generateCoordinates(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } public IRing addRing(int ringSize, Point2d worldcoord, boolean phantom) { IRing ring = chemModel.getBuilder().newInstance(IRing.class, ringSize, "C"); double bondLength = Renderer.calculateBondLength(chemModel.getMoleculeSet()); ringPlacer.placeRing(ring, worldcoord, bondLength, RingPlacer.jcpAngles); if (altMode) { GeometryUtil.rotate(ring, GeometryUtil.get2DCenter(ring), Math.toRadians(360d/(2*ringSize))); } if (phantom) { phantoms.add(ring); //and look if it would merge somewhere getRenderer().getRenderer2DModel().getMerge().clear(); for(IAtom atom : ring.atoms()){ IAtom closestAtomInRing = this.getClosestAtom(atom); if( closestAtomInRing != null) { getRenderer().getRenderer2DModel().getMerge().put(closestAtomInRing, atom); } } } else { IAtomContainerSet set = chemModel.getMoleculeSet(); // the molecule set should not be null, but just in case... if (set == null) { set = chemModel.getBuilder().newInstance(IAtomContainerSet.class); chemModel.setMoleculeSet(set); } IAtomContainer newAtomContainer = chemModel.getBuilder().newInstance(IAtomContainer.class); if (chemModel.getMoleculeSet().getAtomContainer(0).isEmpty()) newAtomContainer = (IAtomContainer) chemModel.getMoleculeSet().getAtomContainer(0); else chemModel.getMoleculeSet().addAtomContainer(newAtomContainer); newAtomContainer.add(ring); updateAtoms(ring, ring.atoms()); AtomBondSet abset = handleMerge(ring); structureChanged(); if (getUndoRedoFactory() != null && getUndoRedoHandler() != null) { IUndoRedoable undoredo = getUndoRedoFactory() .getAddAtomsAndBondsEdit(getIChemModel(), abset, null, "Ring" + " " + ringSize, this); getUndoRedoHandler().postEdit(undoredo); } renderer.getRenderer2DModel() .setHighlightedAtom(newAtomContainer.getAtom(ring.indexOf(ring.getAtom((ringSize/2)-1)))); clearPhantoms(); } return ring; } // OK public IRing addPhenyl(Point2d worldcoord, int ringSize, boolean phantom) { IRing ring = chemModel.getBuilder().newInstance(IRing.class, ringSize, "C"); if (ringSize == 5) { if (altMode) { ring.getBond(1).setOrder(IBond.Order.DOUBLE); ring.getBond(4).setOrder(IBond.Order.DOUBLE); } else { ring.getBond(1).setOrder(IBond.Order.DOUBLE); ring.getBond(3).setOrder(IBond.Order.DOUBLE); } } else if (ringSize == 6) { ring.getBond(0).setOrder(IBond.Order.DOUBLE); ring.getBond(2).setOrder(IBond.Order.DOUBLE); ring.getBond(4).setOrder(IBond.Order.DOUBLE); } double bondLength = Renderer.calculateBondLength(chemModel .getMoleculeSet()); ringPlacer.placeRing(ring, worldcoord, bondLength, RingPlacer.jcpAngles); if (altMode) { GeometryUtil.rotate(ring, GeometryUtil.get2DCenter(ring), Math.PI/ringSize); } if (phantom) { phantoms.add(ring); //and look if it would merge somewhere getRenderer().getRenderer2DModel().getMerge().clear(); for(IAtom atom : ring.atoms()){ IAtom closestAtomInRing = this.getClosestAtom(atom); if( closestAtomInRing != null) { getRenderer().getRenderer2DModel().getMerge().put(closestAtomInRing, atom); } } } else { IAtomContainerSet set = chemModel.getMoleculeSet(); // the molecule set should not be null, but just in case... if (set == null) { set = chemModel.getBuilder().newInstance(IAtomContainerSet.class); chemModel.setMoleculeSet(set); } IAtomContainer newAtomContainer = chemModel.getBuilder().newInstance(IAtomContainer.class); if (chemModel.getMoleculeSet().getAtomContainer(0).getAtomCount() == 0) newAtomContainer = (IAtomContainer) chemModel.getMoleculeSet() .getAtomContainer(0); else chemModel.getMoleculeSet().addAtomContainer(newAtomContainer); newAtomContainer.add(ring); updateAtoms(ring, ring.atoms()); AtomBondSet abset = handleMerge(ring); structureChanged(); if (getUndoRedoFactory() != null && getUndoRedoHandler() != null) { IUndoRedoable undoredo = getUndoRedoFactory() .getAddAtomsAndBondsEdit(getIChemModel(), abset, null, "Benzene", this); getUndoRedoHandler().postEdit(undoredo); } renderer.getRenderer2DModel() .setHighlightedAtom(newAtomContainer.getAtom(ring.indexOf(ring.getAtom(2)))); clearPhantoms(); } return ring; } private AtomBondSet handleMerge(IRing ring) { Map<IAtom, IAtom> mergeSet = getRenderer().getRenderer2DModel().getMerge(); mergeSet.clear(); //we look if it would merge for (IAtom atom : ring.atoms()) { IAtom closestAtomInRing = getClosestAtom(atom); if (closestAtomInRing != null) { mergeSet.put(atom, closestAtomInRing); } } // if we need to merge, we first move the ring so that the merge atoms // are exactly on top of each other - if not doing this, rings get distorted. for (Map.Entry<IAtom, IAtom> e : mergeSet.entrySet()) { IAtom atomOut = e.getKey(); IAtom atomRep = e.getValue(); atomOut.getPoint2d().sub(atomRep.getPoint2d()); Point2d pointSub = new Point2d(atomOut.getPoint2d().x, atomOut.getPoint2d().y); for (IAtom atom : ring.atoms()) { atom.getPoint2d().sub(pointSub); } } AtomBondSet abset = new AtomBondSet(ring); for (IAtom atom : mergeSet.keySet()) { abset.remove(atom); for (IBond bond : ring.getConnectedBondsList(atom)) { if (mergeSet.containsKey(bond.getOther(atom))) abset.remove(bond); } } //and perform the merge mergeMolecules(null); getRenderer().getRenderer2DModel().getMerge().clear(); return abset; } // OK /* * (non-Javadoc) * * @see * org.openscience.cdk.controller.IChemModelRelay#addRing(org.openscience * .cdk.interfaces.IAtom, int, boolean) */ public IRing addRing(IAtom atom, int ringSize, boolean phantom) { IAtomContainer sourceContainer = ChemModelManipulator.getRelevantAtomContainer(chemModel, atom); IAtomContainer sharedAtoms = atom.getBuilder().newAtomContainer(); IRing newRing; if (sourceContainer.getConnectedBondsCount(atom) > 1 && !altMode) { Point2d conAtomsCenter = getConnectedAtomsCenter(atom); Point2d sharedAtomsCenter = atom.getPoint2d(); Vector2d ringCenterVector = new Vector2d(sharedAtomsCenter); ringCenterVector.sub(conAtomsCenter); ringCenterVector.normalize(); ringCenterVector.scale(1.5); newRing = chemModel.getBuilder().newInstance(IRing.class, ringSize, "C"); IAtom root = newRing.getAtom(0); root.setPoint2d(new Point2d(atom.getPoint2d().x + ringCenterVector.x, atom.getPoint2d().y + ringCenterVector.y)); IAtomContainer tmp = chemModel.getBuilder().newAtomContainer(); tmp.addAtom(atom); tmp.addAtom(root); tmp.newBond(tmp.getAtom(0), tmp.getAtom(1)); sharedAtoms.addAtom(root); conAtomsCenter = getConnectedAtomsCenter(tmp.getAtom(tmp.indexOf(root))); sharedAtomsCenter = root.getPoint2d(); ringCenterVector = new Vector2d(sharedAtomsCenter); ringCenterVector.sub(conAtomsCenter); double bondLength = GeometryUtil.getBondLengthMedian(sourceContainer); ringPlacer.setMolecule(tmp); ringPlacer.placeSpiroRing(newRing, sharedAtoms, sharedAtomsCenter, ringCenterVector, bondLength); newRing.addAtom(atom); newRing.addBond(tmp.getBond(0)); // normally the undo/redo is created by createAttached if (!phantom && getUndoRedoFactory() != null && getUndoRedoHandler() != null) { AtomBondSet undoRedoSet = new AtomBondSet(newRing); undoRedoSet.remove(atom); IUndoRedoable undoredo = getUndoRedoFactory() .getAddAtomsAndBondsEdit(getIChemModel(), undoRedoSet, null, "Add Ring", this); getUndoRedoHandler().postEdit(undoredo); } } else { sharedAtoms.addAtom(atom); newRing = createAttachRing(sharedAtoms, ringSize, IElement.C, phantom); double bondLength = Renderer.calculateBondLength(sourceContainer); Point2d conAtomsCenter = getConnectedAtomsCenter(sharedAtoms, chemModel); Point2d sharedAtomsCenter = atom.getPoint2d(); Vector2d ringCenterVector = new Vector2d(sharedAtomsCenter); ringCenterVector.sub(conAtomsCenter); if ((ringCenterVector.x == 0 && ringCenterVector.y == 0)) { // Rare bug case: // the spiro ring can not be attached, it will lead // to NaN values deeper down and serious picture distortion. // Instead, return empty ring, let user try otherwise.. return chemModel.getBuilder().newInstance(IRing.class); } else { ringPlacer.setMolecule(sourceContainer); ringPlacer.placeSpiroRing(newRing, sharedAtoms, sharedAtomsCenter, ringCenterVector, bondLength); } } for (IAtom ringAtom : newRing.atoms()) { if (phantom) this.addPhantomAtom(ringAtom); else if (!ringAtom.equals(atom)) sourceContainer.addAtom(ringAtom); } for (IBond ringBond : newRing.bonds()) { if (phantom) this.addPhantomBond(ringBond); else sourceContainer.addBond(ringBond); } if (!phantom) { updateAtoms(sourceContainer, newRing.atoms()); int atomToHighlight = newRing.getAtomCount() / 2; IAtom hgAtom = sourceContainer.getAtom(sourceContainer.indexOf(newRing.getAtom(atomToHighlight))); renderer.getRenderer2DModel().setHighlightedAtom(hgAtom); } JChemPaintRendererModel rModel = this.getRenderer().getRenderer2DModel(); double d = rModel.getHighlightDistance() / rModel.getScale(); for (IAtom newatom : newRing.atoms()) { if (!atom.equals(newatom) && getClosestAtom(atom) != null) { atom.getPoint2d().x += d; } } structureChanged(); return newRing; } // OK /* * (non-Javadoc) * * @see * org.openscience.cdk.controller.IChemModelRelay#addPhenyl(org.openscience * .cdk.interfaces.IAtom, boolean) */ public IRing addPhenyl(IAtom atom, int ringSize, boolean phantom) { IAtomContainer sourceContainer = ChemModelManipulator.getRelevantAtomContainer(chemModel, atom); IAtomContainer sharedAtoms = atom.getBuilder().newInstance(IAtomContainer.class); IRing newRing; if (atom.getBondCount() > 1 && !altMode) { Point2d conAtomsCenter = getConnectedAtomsCenter(atom); Point2d sharedAtomsCenter = atom.getPoint2d(); Vector2d ringCenterVector = new Vector2d(sharedAtomsCenter); ringCenterVector.sub(conAtomsCenter); ringCenterVector.normalize(); ringCenterVector.scale(1.5); newRing = chemModel.getBuilder().newInstance(IRing.class, ringSize, "C"); if (ringSize == 5) { newRing.getBond(1).setOrder(IBond.Order.DOUBLE); newRing.getBond(3).setOrder(IBond.Order.DOUBLE); } else if (ringSize == 6) { newRing.getBond(0).setOrder(IBond.Order.DOUBLE); newRing.getBond(2).setOrder(IBond.Order.DOUBLE); newRing.getBond(4).setOrder(IBond.Order.DOUBLE); } IAtom root = newRing.getAtom(0); root.setPoint2d(new Point2d(atom.getPoint2d().x + ringCenterVector.x, atom.getPoint2d().y + ringCenterVector.y)); IAtomContainer tmp = chemModel.getBuilder().newAtomContainer(); tmp.addAtom(atom); tmp.addAtom(root); tmp.newBond(tmp.getAtom(0), tmp.getAtom(1)); sharedAtoms.addAtom(root); conAtomsCenter = getConnectedAtomsCenter(tmp.getAtom(tmp.indexOf(root))); sharedAtomsCenter = root.getPoint2d(); ringCenterVector = new Vector2d(sharedAtomsCenter); ringCenterVector.sub(conAtomsCenter); double bondLength = GeometryUtil.getBondLengthMedian(sourceContainer); ringPlacer.setMolecule(tmp); ringPlacer.placeSpiroRing(newRing, sharedAtoms, sharedAtomsCenter, ringCenterVector, bondLength); newRing.addAtom(atom); newRing.addBond(tmp.getBond(0)); // normally the undo/redo is created by createAttached if (!phantom && getUndoRedoFactory() != null && getUndoRedoHandler() != null) { AtomBondSet undoRedoSet = new AtomBondSet(newRing); undoRedoSet.remove(atom); IUndoRedoable undoredo = getUndoRedoFactory() .getAddAtomsAndBondsEdit(getIChemModel(), undoRedoSet, null, "Benzene", this); getUndoRedoHandler().postEdit(undoredo); } } else { sharedAtoms.addAtom(atom); // make a benzene ring newRing = createAttachRing(sharedAtoms, ringSize, IElement.C, phantom); if (ringSize == 5) { newRing.getBond(1).setOrder(IBond.Order.DOUBLE); newRing.getBond(3).setOrder(IBond.Order.DOUBLE); } else if (ringSize == 6) { newRing.getBond(0).setOrder(IBond.Order.DOUBLE); newRing.getBond(2).setOrder(IBond.Order.DOUBLE); newRing.getBond(4).setOrder(IBond.Order.DOUBLE); } double bondLength; if (sourceContainer.getBondCount() == 0) { /* * Special case of adding a ring to a single, unconnected atom - * places the ring centered on the place where the atom was. */ bondLength = Renderer.calculateBondLength(chemModel.getMoleculeSet()); Point2d ringCenter = new Point2d(atom.getPoint2d()); ringPlacer.setMolecule(sourceContainer); ringPlacer.placeRing(newRing, ringCenter, bondLength, RingPlacer.jcpAngles); } else { bondLength = GeometryUtil.getBondLengthMedian(sourceContainer); Point2d conAtomsCenter = getConnectedAtomsCenter(sharedAtoms, chemModel); Point2d sharedAtomsCenter = atom.getPoint2d(); Vector2d ringCenterVector = new Vector2d(sharedAtomsCenter); ringCenterVector.sub(conAtomsCenter); if ((ringCenterVector.x == 0 && ringCenterVector.y == 0)) { return chemModel.getBuilder().newInstance(IRing.class); } else { ringPlacer.setMolecule(sourceContainer); ringPlacer.placeSpiroRing(newRing, sharedAtoms, sharedAtomsCenter, ringCenterVector, bondLength); } } } // add the ring to the source container/phantoms for (IAtom ringAtom : newRing.atoms()) { if (phantom) this.addPhantomAtom(ringAtom); else sourceContainer.addAtom(ringAtom); } for (IBond ringBond : newRing.bonds()) { if (phantom) this.addPhantomBond(ringBond); else sourceContainer.addBond(ringBond); } if (!phantom) { updateAtoms(sourceContainer, newRing.atoms()); int atomToHighlight = newRing.getAtomCount() / 2; IAtom hgAtom = sourceContainer.getAtom(sourceContainer.indexOf(newRing.getAtom(atomToHighlight))); renderer.getRenderer2DModel().setHighlightedAtom(hgAtom); } for (IAtom newatom : newRing.atoms()) { if (!atom.equals(newatom) && getClosestAtom(atom) != null) { JChemPaintRendererModel rModel = this.getRenderer().getRenderer2DModel(); double d = rModel.getHighlightDistance() / rModel.getScale(); atom.getPoint2d().x += d; } } structureChanged(); return newRing; } // OK /** * Constructs a new Ring of a certain size that contains all the atoms and * bonds of the given AtomContainer and is filled up with new Atoms and * Bonds. * * @param sharedAtoms * The AtomContainer containing the Atoms and bonds for the new * Ring * @param ringSize * The size (number of Atoms) the Ring will have * @param atomicNum * The element number the new atoms will have * @param phantom * If true we assume this is a phantom ring and do not put it * into undo. * @return The constructed Ring */ private IRing createAttachRing(IAtomContainer sharedAtoms, int ringSize, int atomicNum, boolean phantom) { IRing newRing = sharedAtoms.getBuilder().newInstance(IRing.class,ringSize); for (int i = 0; i < sharedAtoms.getAtomCount(); i++) { newRing.addAtom(sharedAtoms.getAtom(i)); } for (int i = sharedAtoms.getAtomCount(); i < ringSize; i++) { newRing.newAtom(atomicNum); } for (IBond bond : sharedAtoms.bonds()) newRing.addBond(bond); for (int i = sharedAtoms.getBondCount(); i < ringSize - 1; i++) { newRing.newBond(newRing.getAtom(i),newRing.getAtom(i + 1)); } newRing.newBond(newRing.getAtom(ringSize-1),newRing.getAtom(0)); if (!phantom && getUndoRedoFactory() != null && getUndoRedoHandler() != null) { AtomBondSet undoRedoSet = new AtomBondSet(newRing); for (IAtom atom : sharedAtoms.atoms()) undoRedoSet.remove(atom); for (IBond bond : sharedAtoms.bonds()) undoRedoSet.remove(bond); IUndoRedoable undoredo = getUndoRedoFactory() .getAddAtomsAndBondsEdit(getIChemModel(), undoRedoSet, null, "Ring" + " " + ringSize, this); getUndoRedoHandler().postEdit(undoredo); } return newRing; } // OK /** * Searches all the atoms attached to the Atoms in the given AtomContainer * and calculates the center point of them. * * @param sharedAtoms * The Atoms the attached partners are searched of * @return The Center Point of all the atoms found */ private Point2d getConnectedAtomsCenter(IAtomContainer sharedAtoms, IChemModel chemModel) { IAtomContainer conAtoms = sharedAtoms.getBuilder().newInstance(IAtomContainer.class); for (IAtom sharedAtom : sharedAtoms.atoms()) { conAtoms.addAtom(sharedAtom); IAtomContainer atomCon = ChemModelManipulator .getRelevantAtomContainer(chemModel, sharedAtom); for (IAtom atom : atomCon.getConnectedAtomsList(sharedAtom)) { conAtoms.addAtom(atom); } } return GeometryUtil.get2DCenter(conAtoms); } private Point2d getConnectedAtomsCenter(IAtom atom) { IAtomContainer conAtoms = atom.getBuilder().newInstance(IAtomContainer.class); conAtoms.addAtom(atom); for (IBond bond : atom.bonds()) { conAtoms.addAtom(bond.getOther(atom)); } return GeometryUtil.get2DCenter(conAtoms); } // OK /* * (non-Javadoc) * * @see * org.openscience.cdk.controller.IChemModelRelay#addRing(org.openscience * .cdk.interfaces.IBond, int, boolean) */ public IRing addRing(IBond bond, int size, boolean phantom) { IAtomContainer sharedAtoms = bond.getBuilder().newInstance(IAtomContainer.class); IAtom firstAtom = bond.getAtom(0); // Assumes two-atom bonds only IAtom secondAtom = bond.getAtom(1); sharedAtoms.addAtom(firstAtom); sharedAtoms.addAtom(secondAtom); sharedAtoms.addBond(bond); IAtomContainer sourceContainer = ChemModelManipulator .getRelevantAtomContainer(chemModel, firstAtom); Point2d sharedAtomsCenter = GeometryUtil.get2DCenter(sharedAtoms); // calculate two points that are perpendicular to the highlighted bond // and have a certain distance from the bond center Point2d firstPoint = firstAtom.getPoint2d(); Point2d secondPoint = secondAtom.getPoint2d(); Vector2d diff = new Vector2d(secondPoint); diff.sub(firstPoint); double bondLength = firstPoint.distance(secondPoint); double angle = GeometryUtil.getAngle(diff.x, diff.y); Point2d newPoint1 = new Point2d( // FIXME: what is this point?? (Math.cos(angle + (Math.PI / 2)) * bondLength / 4) + sharedAtomsCenter.x, (Math.sin(angle + (Math.PI / 2)) * bondLength / 4) + sharedAtomsCenter.y); Point2d newPoint2 = new Point2d( // FIXME: what is this point?? (Math.cos(angle - (Math.PI / 2)) * bondLength / 4) + sharedAtomsCenter.x, (Math.sin(angle - (Math.PI / 2)) * bondLength / 4) + sharedAtomsCenter.y); // decide on which side to draw the ring?? IAtomContainer connectedAtoms = bond.getBuilder().newInstance(IAtomContainer.class); for (IAtom atom : sourceContainer.getConnectedAtomsList(firstAtom)) { if (!atom.equals(secondAtom)) connectedAtoms.addAtom(atom); } for (IAtom atom : sourceContainer.getConnectedAtomsList(secondAtom)) { if (!atom.equals(firstAtom)) connectedAtoms.addAtom(atom); } Point2d conAtomsCenter = GeometryUtil.get2DCenter(connectedAtoms); double distance1 = newPoint1.distance(conAtomsCenter); double distance2 = newPoint2.distance(conAtomsCenter); Vector2d ringCenterVector = new Vector2d(sharedAtomsCenter); if (distance1 < distance2) { ringCenterVector.sub(newPoint1); } else { // distance2 <= distance1 ringCenterVector.sub(newPoint2); } // construct a new Ring that contains the highlighted bond an its two // atoms IRing newRing = createAttachRing(sharedAtoms, size, IElement.C, phantom); ringPlacer.setMolecule(sourceContainer); ringPlacer.placeFusedRing(newRing, sharedAtoms, ringCenterVector, bondLength); // add the new atoms and bonds for (IAtom ringAtom : newRing.atoms()) { if (phantom) addPhantomAtom(ringAtom); else if (!ringAtom.equals(firstAtom) && !ringAtom.equals(secondAtom)) sourceContainer.addAtom(ringAtom); } for (IBond ringBond : newRing.bonds()) { if (phantom) addPhantomBond(ringBond); else if (!ringBond.equals(bond)) sourceContainer.addBond(ringBond); } if (!phantom) { renderer.getRenderer2DModel().setHighlightedBond(newRing.getBond(size/2)); updateAtoms(sourceContainer, newRing.atoms()); } JChemPaintRendererModel rModel = this.getRenderer().getRenderer2DModel(); double d = rModel.getHighlightDistance() / rModel.getScale(); for (IAtom atom : newRing.atoms()) { if (!atom.equals(firstAtom) && !atom.equals(secondAtom) && getClosestAtom(atom) != null) { atom.getPoint2d().x += d; } } structureChanged(); return newRing; } // OK public IAtom getClosestAtom(IAtom atom) { return getAtomInRange(null, atom); } // OK public IAtom getAtomInRange(Collection<IAtom> toIgnore, IAtom atom) { Point2d atomPosition = atom.getPoint2d(); JChemPaintRendererModel rModel = this.getRenderer().getRenderer2DModel(); double highlight = rModel.getHighlightDistance() / rModel.getScale(); IAtom bestClosestAtom = null; double bestDistance = -1; for (IAtomContainer atomContainer : ChemModelManipulator .getAllAtomContainers(getIChemModel())) { IAtom closestAtom = GeometryUtil.getClosestAtom(atomContainer, atom); if (closestAtom != null) { double distance = closestAtom.getPoint2d().distance( atomPosition); if ((distance > highlight) || (toIgnore != null && toIgnore.contains(closestAtom))) { continue; } else { if (bestClosestAtom == null || distance < bestDistance) { bestClosestAtom = closestAtom; bestDistance = distance; } } } } return bestClosestAtom; } // OK /* * (non-Javadoc) * * @see * org.openscience.cdk.controller.IChemModelRelay#addPhenyl(org.openscience * .cdk.interfaces.IBond, boolean) */ public IRing addPhenyl(IBond bond, int ringSize, boolean phantom) { IAtomContainer sharedAtoms = bond.getBuilder().newInstance(IAtomContainer.class); IAtom firstAtom = bond.getAtom(0); // Assumes two-atom bonds only IAtom secondAtom = bond.getAtom(1); sharedAtoms.addAtom(firstAtom); sharedAtoms.addAtom(secondAtom); sharedAtoms.addBond(bond); IAtomContainer sourceContainer = ChemModelManipulator .getRelevantAtomContainer(chemModel, firstAtom); Point2d sharedAtomsCenter = GeometryUtil.get2DCenter(sharedAtoms); // calculate two points that are perpendicular to the highlighted bond // and have a certain distance from the bond center Point2d firstPoint = firstAtom.getPoint2d(); Point2d secondPoint = secondAtom.getPoint2d(); Vector2d diff = new Vector2d(secondPoint); diff.sub(firstPoint); double bondLength = firstPoint.distance(secondPoint); double angle = GeometryUtil.getAngle(diff.x, diff.y); Point2d newPoint1 = new Point2d( // FIXME: what is this point?? (Math.cos(angle + (Math.PI / 2)) * bondLength / 4) + sharedAtomsCenter.x, (Math.sin(angle + (Math.PI / 2)) * bondLength / 4) + sharedAtomsCenter.y); Point2d newPoint2 = new Point2d( // FIXME: what is this point?? (Math.cos(angle - (Math.PI / 2)) * bondLength / 4) + sharedAtomsCenter.x, (Math.sin(angle - (Math.PI / 2)) * bondLength / 4) + sharedAtomsCenter.y); // decide on which side to draw the ring?? IAtomContainer connectedAtoms = bond.getBuilder().newInstance(IAtomContainer.class); for (IAtom atom : sourceContainer.getConnectedAtomsList(firstAtom)) { if (!atom.equals(secondAtom)) connectedAtoms.addAtom(atom); } for (IAtom atom : sourceContainer.getConnectedAtomsList(secondAtom)) { if (!atom.equals(firstAtom)) connectedAtoms.addAtom(atom); } Point2d conAtomsCenter = GeometryUtil.get2DCenter(connectedAtoms); double distance1 = newPoint1.distance(conAtomsCenter); double distance2 = newPoint2.distance(conAtomsCenter); Vector2d ringCenterVector = new Vector2d(sharedAtomsCenter); if (distance1 < distance2) { ringCenterVector.sub(newPoint1); } else { // distance2 <= distance1 ringCenterVector.sub(newPoint2); } // construct a new Ring that contains the highlighted bond an its two // atoms IRing newRing = createAttachRing(sharedAtoms, ringSize, IElement.C, phantom); ringPlacer.setMolecule(sourceContainer); ringPlacer.placeFusedRing(newRing, sharedAtoms, ringCenterVector, bondLength); if (sourceContainer.getMaximumBondOrder(bond.getAtom(0)) == IBond.Order.SINGLE && sourceContainer.getMaximumBondOrder(bond.getAtom(1)) == IBond.Order.SINGLE) { if (ringSize == 5) { if (altMode) { newRing.getBond(1).setOrder(IBond.Order.DOUBLE); newRing.getBond(4).setOrder(IBond.Order.DOUBLE); } else { newRing.getBond(1).setOrder(IBond.Order.DOUBLE); newRing.getBond(3).setOrder(IBond.Order.DOUBLE); } } else if (ringSize == 6) { if (altMode) { newRing.getBond(2).setOrder(IBond.Order.DOUBLE); newRing.getBond(4).setOrder(IBond.Order.DOUBLE); } else { newRing.getBond(1).setOrder(IBond.Order.DOUBLE); newRing.getBond(3).setOrder(IBond.Order.DOUBLE); newRing.getBond(5).setOrder(IBond.Order.DOUBLE); } } } else { // assume Order.DOUBLE, so only need to add 2 double bonds if (ringSize == 5) { if (altMode) newRing.getBond(3).setOrder(IBond.Order.DOUBLE); else newRing.getBond(2).setOrder(IBond.Order.DOUBLE); } else if (ringSize == 6) { newRing.getBond(2).setOrder(IBond.Order.DOUBLE); newRing.getBond(4).setOrder(IBond.Order.DOUBLE); } } // add the new atoms and bonds for (IAtom ringAtom : newRing.atoms()) { if (phantom) this.addPhantomAtom(ringAtom); else sourceContainer.addAtom(ringAtom); } for (IBond ringBond : newRing.bonds()) { if (!ringBond.equals(bond)) { if (phantom) this.addPhantomBond(ringBond); else sourceContainer.addBond(ringBond); } } if (!phantom) { renderer.getRenderer2DModel().setHighlightedBond(newRing.getBond(3)); updateAtoms(sourceContainer, newRing.atoms()); } JChemPaintRendererModel rModel = this.getRenderer().getRenderer2DModel(); double d = rModel.getHighlightDistance() / rModel.getScale(); for (IAtom atom : newRing.atoms()) { if (!atom.equals(firstAtom) && !atom.equals(secondAtom) && getClosestAtom(atom) != null) { atom.getPoint2d().x += d; } } structureChanged(); return newRing; } // OK public void removeBondWithoutUndo(IBond bond) { ChemModelManipulator.removeElectronContainer(chemModel, bond); // set hybridization from bond order bond.getAtom(0).setHybridization(null); bond.getAtom(1).setHybridization(null); updateAtom(bond.getAtom(0)); updateAtom(bond.getAtom(1)); adjustRgroup(); structureChanged(); } // OK TODO this could do with less partitioning public void removeBond(IBond bond) { removeBondWithoutUndo(bond); AtomBondSet undAtomContainer = new AtomBondSet(); undAtomContainer.add(bond); if (getUndoRedoFactory() != null && getUndoRedoHandler() != null) { IUndoRedoable undoredo = getUndoRedoFactory() .getRemoveAtomsAndBondsEdit(getIChemModel(), undAtomContainer, "Remove Bond", this); getUndoRedoHandler().postEdit(undoredo); } } public void addPhantomAtom(IAtom atom) { this.phantoms.addAtom(atom); } public void addPhantomBond(IBond bond) { this.phantoms.addBond(bond); } public void clearPhantoms() { getRenderer().getRenderer2DModel().getMerge().clear(); this.phantoms.removeAllElements(); } @Override public void setPhantoms(IAtomContainer phantoms) { this.phantoms = phantoms; } public IAtomContainer getPhantoms() { return this.phantoms; } public void adjustBondOrders() throws IOException, ClassNotFoundException, CDKException { // TODO also work on reactions ?!? SaturationChecker satChecker = new SaturationChecker(); List<IAtomContainer> containersList = ChemModelManipulator .getAllAtomContainers(chemModel); Iterator<IAtomContainer> iterator = containersList.iterator(); Map<IBond, IBond.Order[]> changedBonds = new HashMap<IBond, IBond.Order[]>(); while (iterator.hasNext()) { IAtomContainer ac = (IAtomContainer) iterator.next(); for (IBond bond : ac.bonds()) { IBond.Order[] orders = new IBond.Order[2]; orders[1] = bond.getOrder(); changedBonds.put(bond, orders); } satChecker.saturate(ac); for (IBond bond : ac.bonds()) { IBond.Order[] orders = changedBonds.get(bond); orders[0] = bond.getOrder(); changedBonds.put(bond, orders); } } if (this.getController2DModel().getAutoUpdateImplicitHydrogens()) updateImplicitHydrogenCounts(); if (undoredofactory != null && undoredohandler != null) { IUndoRedoable undoredo = undoredofactory.getAdjustBondOrdersEdit( changedBonds, Collections.emptyMap(), "Adjust Bond Order of Molecules", this); undoredohandler.postEdit(undoredo); } } // OK public void resetBondOrders() { List<IAtomContainer> containersList = ChemModelManipulator .getAllAtomContainers(chemModel); Iterator<IAtomContainer> iterator = containersList.iterator(); Map<IBond, IBond.Order[]> changedBonds = new HashMap<IBond, IBond.Order[]>(); while (iterator.hasNext()) { IAtomContainer ac = iterator.next(); for (IBond bond : ac.bonds()) { IBond.Order[] orders = new IBond.Order[2]; orders[1] = bond.getOrder(); orders[0] = Order.SINGLE; changedBonds.put(bond, orders); bond.setOrder(Order.SINGLE); } } if (this.getController2DModel().getAutoUpdateImplicitHydrogens()) updateImplicitHydrogenCounts(); if (undoredofactory != null && undoredohandler != null) { IUndoRedoable undoredo = undoredofactory.getAdjustBondOrdersEdit( changedBonds, Collections.emptyMap(), "Reset Bond Order of Molecules", this); undoredohandler.postEdit(undoredo); } } // OK public void replaceAtom(IAtom atomnew, IAtom atomold) { IAtomContainer relevantContainer = ChemModelManipulator .getRelevantAtomContainer(chemModel, atomold); AtomContainerManipulator.replaceAtomByAtom(relevantContainer, atomold, atomnew); updateAtom(atomnew); structureChanged(); if (undoredofactory != null && undoredohandler != null) { IUndoRedoable undoredo = undoredofactory.getReplaceAtomEdit( chemModel, atomold, atomnew, "Replace Atom"); undoredohandler.postEdit(undoredo); } } /* * (non-Javadoc) * * @seeorg.openscience.cdk.controller.IAtomBondEdits#addSingleElectron(org. * openscience.cdk.interfaces.IAtom) */ public void addSingleElectron(IAtom atom) { IAtomContainer relevantContainer = ChemModelManipulator .getRelevantAtomContainer(chemModel, atom); ISingleElectron singleElectron = atom.getBuilder().newInstance(ISingleElectron.class,atom); relevantContainer.addSingleElectron(singleElectron); updateAtom(atom); if (undoredofactory != null && undoredohandler != null) { IUndoRedoable undoredo = undoredofactory.getSingleElectronEdit( relevantContainer, singleElectron, true, this, atom, "Add Single Electron"); undoredohandler.postEdit(undoredo); } } // OK /* * (non-Javadoc) * * @see * org.openscience.cdk.controller.IAtomBondEdits#removeSingleElectron(org * .openscience.cdk.interfaces.IAtom) */ public void removeSingleElectron(IAtom atom) { IAtomContainer relevantContainer = ChemModelManipulator .getRelevantAtomContainer(chemModel, atom); if (relevantContainer.getConnectedSingleElectronsCount(atom) > 0) { ISingleElectron removedElectron = relevantContainer .removeSingleElectron(relevantContainer .getConnectedSingleElectronsCount(atom) - 1); updateAtom(atom); if (undoredofactory != null && undoredohandler != null) { IUndoRedoable undoredo = undoredofactory.getSingleElectronEdit( relevantContainer, removedElectron, false, this, atom, "Remove Single Electron"); undoredohandler.postEdit(undoredo); } } } public void clearValidation() { Iterator<IAtomContainer> containers = ChemModelManipulator .getAllAtomContainers(chemModel).iterator(); while (containers.hasNext()) { IAtomContainer atoms = containers.next(); for (int i = 0; i < atoms.getAtomCount(); i++) { ProblemMarker.unmark(atoms.getAtom(i)); } } } // OK public void flip(boolean horizontal) { HashMap<IAtom, Point2d[]> atomCoordsMap = new HashMap<IAtom, Point2d[]>(); Map<IBond, IBond.Stereo> bondStereo = new HashMap<IBond, IBond.Stereo>(); JChemPaintRendererModel renderModel = renderer.getRenderer2DModel(); Set<IBond> anchors = new HashSet<>(); IAtomContainer toflip; IChemObjectSelection select = renderModel.getSelection(); if (select.isFilled()) { for (IAtomContainer container : getChemModel().getMoleculeSet()) { for (IBond bond : container.bonds()) { if (select.contains(bond.getBegin()) && !select.contains(bond.getEnd())) { anchors.add(bond); } else if (select.contains(bond.getEnd()) && !select.contains(bond.getBegin())) { anchors.add(bond); } } } toflip = select.getConnectedAtomContainer(); } else { List<IAtomContainer> toflipall = ChemModelManipulator .getAllAtomContainers(chemModel); toflip = toflipall.get(0).getBuilder().newInstance(IAtomContainer.class); for (IAtomContainer atomContainer : toflipall) { toflip.add(atomContainer); } } // if we have two "leaving" bonds, check if there is a common atom, // we then move the anchor to that bond. if (anchors.size() > 1) { Set<IAtom> anchorAtoms = new HashSet<>(); for (IBond anchor : anchors) { for (IAtom a : anchor.atoms()) { if (select.contains(a)) anchorAtoms.add(a); } } if (anchorAtoms.size() == 1) { anchors.clear(); IAtom anchorAtom = anchorAtoms.iterator().next(); for (IBond bond : ChemModelManipulator.getRelevantAtomContainer(getChemModel(), anchorAtom) .getConnectedBondsList(anchorAtom)) { if (select.contains(bond)) anchors.add(bond); } } } if (anchors.size() == 1 && !altMode) { IBond bond = anchors.iterator().next(); for (IAtom atom : toflip.atoms()) { Point2d p = atom.getPoint2d(); Point2d backup = new Point2d(p); reflect(p, bond.getBegin().getPoint2d(), bond.getEnd().getPoint2d()); atomCoordsMap.put(atom, new Point2d[]{new Point2d(p), backup}); } } else { Point2d center = GeometryUtil.get2DCenter(toflip); for (IAtom atom : toflip.atoms()) { Point2d p2d = atom.getPoint2d(); Point2d oldCoord = new Point2d(p2d.x, p2d.y); if (horizontal) { p2d.y = 2.0 * center.y - p2d.y; } else { p2d.x = 2.0 * center.x - p2d.x; } Point2d newCoord = p2d; if (!oldCoord.equals(newCoord)) { Point2d[] coords = new Point2d[2]; coords[0] = newCoord; coords[1] = oldCoord; atomCoordsMap.put(atom, coords); } } } // Stereo bonds must be flipped as well to keep the structure for (IBond bond : toflip.bonds()) { bondStereo.put(bond, bond.getStereo()); if (bond.getStereo() == IBond.Stereo.UP) bond.setStereo(IBond.Stereo.DOWN); else if (bond.getStereo() == IBond.Stereo.DOWN) bond.setStereo(IBond.Stereo.UP); else if (bond.getStereo() == IBond.Stereo.UP_INVERTED) bond.setStereo(IBond.Stereo.DOWN_INVERTED); else if (bond.getStereo() == IBond.Stereo.DOWN_INVERTED) bond.setStereo(IBond.Stereo.UP_INVERTED); } coordinatesChanged(); if (getUndoRedoFactory() != null && getUndoRedoHandler() != null) { IUndoRedoable undoredo = getUndoRedoFactory().getChangeCoordsEdit( atomCoordsMap, bondStereo, "Clean Up"); getUndoRedoHandler().postEdit(undoredo); } } public void invertStereoInSelection() { IAtomContainer toflip; JChemPaintRendererModel renderModel = renderer.getRenderer2DModel(); if (renderModel.getSelection().getConnectedAtomContainer() != null && renderModel.getSelection().getConnectedAtomContainer() .getAtomCount() != 0) { toflip = renderModel.getSelection().getConnectedAtomContainer(); } else return; for (IBond bond : toflip.bonds()) { if (bond.getStereo() == IBond.Stereo.UP) bond.setStereo(IBond.Stereo.DOWN); else if (bond.getStereo() == IBond.Stereo.DOWN) bond.setStereo(IBond.Stereo.UP); else if (bond.getStereo() == IBond.Stereo.UP_INVERTED) bond.setStereo(IBond.Stereo.DOWN_INVERTED); else if (bond.getStereo() == IBond.Stereo.DOWN_INVERTED) bond.setStereo(IBond.Stereo.UP_INVERTED); } } public void setEventHandler(IChemModelEventRelayHandler handler) { this.changeHandler = handler; } protected void structureChanged() { if (renderer.getRenderer2DModel().getSelection() instanceof IncrementalSelection) select((IncrementalSelection) renderer.getRenderer2DModel() .getSelection()); if (changeHandler != null) changeHandler.structureChanged(); } public void fireZoomEvent() { changeHandler.zoomChanged(); } public void fireStructureChangedEvent() { changeHandler.structureChanged(); } private void structurePropertiesChanged() { if (changeHandler != null) changeHandler.structurePropertiesChanged(); } private void coordinatesChanged() { if (changeHandler != null) changeHandler.coordinatesChanged(); } public IUndoRedoFactory getUndoRedoFactory() { return undoredofactory; } public UndoRedoHandler getUndoRedoHandler() { return undoredohandler; } private void selectionChanged() { if (changeHandler != null) changeHandler.selectionChanged(); } /* * (non-Javadoc) * * @see * org.openscience.cdk.controller.IChemModelRelay#select(org.openscience * .cdk.renderer.selection.IncrementalSelection) */ public void select(IncrementalSelection selection) { if (selection != null) selection.select(this.chemModel); selectionChanged(); } /* * (non-Javadoc) * * @see * org.openscience.cdk.controller.IChemModelRelay#select(org.openscience * .cdk.renderer.selection.IChemObjectSelection) */ public void select(IChemObjectSelection selection) { getRenderer().getRenderer2DModel().setSelection(selection); selectionChanged(); } // OK public void addFragment(AtomBondSet toPaste, IAtomContainer moleculeToAddTo, IAtomContainer toRemove) { IAtomContainerSet newMoleculeSet = chemModel.getMoleculeSet(); if (newMoleculeSet == null) { newMoleculeSet = chemModel.getBuilder().newInstance(IAtomContainerSet.class); } IAtomContainerSet oldMoleculeSet = chemModel.getBuilder().newInstance(IAtomContainerSet.class); if (moleculeToAddTo == null) { moleculeToAddTo = chemModel.getBuilder().newAtomContainer(); for (IAtom atom : toPaste.atoms()) moleculeToAddTo.addAtom(atom); for (IBond bond : toPaste.bonds()) moleculeToAddTo.addBond(bond); newMoleculeSet.addAtomContainer(moleculeToAddTo); } else { IAtomContainer mol = chemModel.getBuilder().newInstance(IAtomContainer.class); for (IAtom atom: moleculeToAddTo.atoms()) mol.addAtom(atom); for (IBond bond: moleculeToAddTo.bonds()) mol.addBond(bond); oldMoleculeSet.addAtomContainer(mol); for (IAtom atom : toPaste.atoms()) moleculeToAddTo.addAtom(atom); for (IBond bond : toPaste.bonds()) moleculeToAddTo.addBond(bond); } if (toRemove != null) { oldMoleculeSet.addAtomContainer(toRemove); moleculeToAddTo.add(toRemove); updateAtoms(toRemove, toRemove.atoms()); newMoleculeSet.removeAtomContainer(toRemove); } for (IAtomContainer ac: newMoleculeSet.atomContainers()) updateAtoms(ac, ac.atoms()); if (undoredofactory != null && undoredohandler != null) { IUndoRedoable undoredo = undoredofactory.getLoadNewModelEdit( getIChemModel(), this, oldMoleculeSet, null, newMoleculeSet, null, "Add Chain Fragment"); undoredohandler.postEdit(undoredo); } chemModel.setMoleculeSet(newMoleculeSet); structureChanged(); } // OK public AtomBondSet deleteFragment(AtomBondSet selected) { AtomBondSet undoRedoSet = new AtomBondSet(); if (rGroupHandler != null && !rGroupHandler.checkRGroupOkayForDelete(selected, this)) return undoRedoSet; Set<IAtom> adjacentAtoms = new HashSet<>(); for (IAtom atom : selected.atoms()) { undoRedoSet.add(atom); } for (IAtom atom : undoRedoSet.atoms()) { IAtomContainer container = ChemModelManipulator.getRelevantAtomContainer(chemModel, atom); for (IBond bond : container.getConnectedBondsList(atom)) { if (!undoRedoSet.contains(bond)) { undoRedoSet.add(bond); adjacentAtoms.add(bond.getOther(atom)); } } } for (IBond bond : selected.bonds()) { if (!undoRedoSet.contains(bond)) undoRedoSet.add(bond); } for (IBond bond : undoRedoSet.bonds()) { ChemModelManipulator.removeElectronContainer(chemModel, bond); } for (IAtom atom : undoRedoSet.atoms()) { ChemModelManipulator.removeAtomAndConnectedElectronContainers(chemModel, atom); } for (IAtom atom : adjacentAtoms) { if (!undoRedoSet.contains(atom)) updateAtom(atom); } removeEmptyContainers(chemModel); if (undoredofactory != null && undoredohandler != null) { IUndoRedoable undoredo = undoredofactory .getRemoveAtomsAndBondsEdit(chemModel, undoRedoSet, "Cut", this); undoredohandler.postEdit(undoredo); } adjustRgroup(); structureChanged(); return undoRedoSet; } public static void removeEmptyContainers(IChemModel chemModel) { Iterator<IAtomContainer> it = ChemModelManipulator .getAllAtomContainers(chemModel).iterator(); while (it.hasNext()) { IAtomContainer ac = it.next(); if (ac.getAtomCount() == 0) { chemModel.getMoleculeSet().removeAtomContainer(ac); } } if (chemModel.getMoleculeSet().getAtomContainerCount() == 0) chemModel.getMoleculeSet().addAtomContainer( chemModel.getBuilder().newInstance(IAtomContainer.class)); } // OK /** * Updates an array of atoms with respect to its hydrogen count * *@param container * The AtomContainer to work on *@param atoms * The Atoms to update */ public void updateAtoms(IAtomContainer container, Iterable<IAtom> atoms) { for (IAtom atom : atoms) { updateAtom(container, atom); } } // OK /** * Updates an atom with respect to its hydrogen count * *@param atom * The Atom to update */ public void updateAtom(IAtom atom) { IAtomContainer container = ChemModelManipulator .getRelevantAtomContainer(chemModel, atom); if (container != null) { updateAtom(container, atom); } } public void updateAtoms(IBond bond) { IAtomContainer container = ChemModelManipulator .getRelevantAtomContainer(chemModel, bond); if (container != null) { updateAtom(container, bond.getBegin()); updateAtom(container, bond.getEnd()); } } // OK /** * Updates an atom with respect to its hydrogen count * *@param container * The AtomContainer to work on *@param atom * The Atom to update */ private void updateAtom(IAtomContainer container, IAtom atom) { if (this.getController2DModel().getAutoUpdateImplicitHydrogens()) { atom.setImplicitHydrogenCount(0); try { IAtomType type = matcher.findMatchingAtomType(container, atom); if (type != null && !type.getAtomTypeName().equals("X")) { Integer neighbourCount = type.getFormalNeighbourCount(); if (neighbourCount != null) { atom.setImplicitHydrogenCount(neighbourCount - container.getConnectedAtomsCount(atom)); } // for some reason, the neighbour count takes into account // only // one single electron if (container.getConnectedSingleElectronsCount(atom) > 1 && atom.getImplicitHydrogenCount() - container .getConnectedSingleElectronsCount(atom) + 1 > -1) atom.setImplicitHydrogenCount(atom.getImplicitHydrogenCount() - container .getConnectedSingleElectronsCount(atom) + 1); atom.setFlag(CDKConstants.IS_TYPEABLE, false); } else { atom.setFlag(CDKConstants.IS_TYPEABLE, true); } } catch (CDKException e) { e.printStackTrace(); } } } // OK public void makeAllExplicitImplicit() { IAtomContainer undoRedoSet = chemModel.getBuilder() .newInstance(IAtomContainer.class); List<IAtomContainer> containers = ChemModelManipulator .getAllAtomContainers(chemModel); for (int i = 0; i < containers.size(); i++) { IAtomContainer removeatoms = chemModel.getBuilder() .newInstance(IAtomContainer.class); for (IAtom atom : containers.get(i).atoms()) { if (atom.getSymbol().equals("H")) { removeatoms.addAtom(atom); removeatoms.addBond(containers.get(i) .getConnectedBondsList(atom).get(0)); containers .get(i) .getConnectedAtomsList(atom) .get(0) .setImplicitHydrogenCount( containers.get(i).getConnectedAtomsList( atom).get(0).getImplicitHydrogenCount() + 1); } } containers.get(i).remove(removeatoms); undoRedoSet.add(removeatoms); } if (getUndoRedoFactory() != null && getUndoRedoHandler() != null) { IUndoRedoable undoredo = getUndoRedoFactory() .getRemoveAtomsAndBondsEdit(chemModel, new AtomBondSet(undoRedoSet), "Make explicit Hs implicit", this); getUndoRedoHandler().postEdit(undoredo); } structureChanged(); } // OK public void makeAllImplicitExplicit() { AtomBondSet undoRedoSet = new AtomBondSet(); List<IAtomContainer> containers = ChemModelManipulator .getAllAtomContainers(chemModel); for (int i = 0; i < containers.size(); i++) { for (IAtom atom : containers.get(i).atoms()) { int hcount = atom.getImplicitHydrogenCount(); for (int k = 0; k < hcount; k++) { IAtom newAtom = this.addAtomWithoutUndo("H", atom, false); IAtomContainer atomContainer = ChemModelManipulator .getRelevantAtomContainer(getIChemModel(), newAtom); IBond newBond = atomContainer.getBond(atom, newAtom); undoRedoSet.add(newAtom); undoRedoSet.add(newBond); } } } if (getUndoRedoFactory() != null && getUndoRedoHandler() != null) { IUndoRedoable undoredo = getUndoRedoFactory() .getAddAtomsAndBondsEdit(chemModel, undoRedoSet, null, "Make implicit Hs explicit", this); getUndoRedoHandler().postEdit(undoredo); } structureChanged(); } // OK public void setImplicitHydrogenCount(IAtom atom, int intValue) { if (getUndoRedoFactory() != null && getUndoRedoHandler() != null) { HashMap<IAtom, Integer[]> atomhydrogenmap = new HashMap<IAtom, Integer[]>(); atomhydrogenmap.put(atom, new Integer[] { intValue, atom.getImplicitHydrogenCount() }); IUndoRedoable undoredo = getUndoRedoFactory() .getChangeHydrogenCountEdit(atomhydrogenmap, "Change hydrogen count to " + intValue); getUndoRedoHandler().postEdit(undoredo); } atom.setImplicitHydrogenCount(intValue); structureChanged(); } // OK /** * Merge molecules when a selection is moved onto another part of the * molecule set * */ public void mergeMolecules(Vector2d movedDistance) { JChemPaintRendererModel model = getRenderer().getRenderer2DModel(); if (rGroupHandler != null) { if (!rGroupHandler.isMergeAllowed(this)) { model.getMerge().clear(); updateView(); throw new RuntimeException("Merge not allowed by RGroupHandler"); } } // First try to shift the selection to be exactly on top of // the target of the merge. This makes the end results visually // more attractive and avoid tilted rings // Map<IAtom, IAtom> mergeMap = model.getMerge(); for (Map.Entry<IAtom,IAtom> e : mergeMap.entrySet()) { IAtomContainer movedAtomContainer = renderer.getRenderer2DModel() .getSelection().getConnectedAtomContainer(); if (movedAtomContainer != null) { IAtom atomA = e.getKey(); IAtom atomB = e.getValue(); Vector2d shift = new Vector2d(); shift.sub(atomB.getPoint2d(), atomA.getPoint2d()); for (IAtom shiftAtom : movedAtomContainer.atoms()) { shiftAtom.getPoint2d().add(shift); } } } List<IAtom> mergedAtoms = new ArrayList<IAtom>(); List<IAtomContainer> containers = new ArrayList<IAtomContainer>(); List<IAtomContainer> droppedContainers = new ArrayList<IAtomContainer>(); List<List<IBond>> removedBondss = new ArrayList<List<IBond>>(); List<Map<IBond, Integer>> bondsWithReplacedAtoms = new ArrayList<Map<IBond, Integer>>(); List<IAtom> mergedPartnerAtoms = new ArrayList<IAtom>(); List<IAtom> atomsToUpdate = new ArrayList<>(); if (mergeMap.isEmpty()) return; // Done shifting, now the actual merging for (Map.Entry<IAtom,IAtom> e : mergeMap.entrySet()) { List<IBond> removedBonds = new ArrayList<IBond>(); Map<IBond, Integer> bondsWithReplacedAtom = new HashMap<IBond, Integer>(); IAtom atomRemoved = e.getKey(); IAtom atomMerged = e.getValue(); mergedAtoms.add(atomRemoved); mergedPartnerAtoms.add(atomMerged); IAtomContainer container1 = ChemModelManipulator .getRelevantAtomContainer(chemModel, atomRemoved); containers.add(container1); IAtomContainer container2 = ChemModelManipulator .getRelevantAtomContainer(chemModel, atomMerged); // If the atoms are in different atom containers till now, we merge // the atom containers first. if (container1 != container2) { container1.add(container2); chemModel.getMoleculeSet().removeAtomContainer(container2); droppedContainers.add(container2); } else { droppedContainers.add(null); } // Handle the case of a bond between mergedAtom and mergedPartnerAtom. // This bond should be removed. IBond rb = container1.getBond(atomRemoved, atomMerged); if (rb != null) { container1.removeBond(rb); removedBonds.add(rb); } // In the next loop we remove bonds that are redundant, that is // to say bonds that exist on both sides of the parts to be merged // and would cause duplicate bonding in the end result. for (IAtom atom : container1.atoms()) { if (!atom.equals(atomRemoved)) { if (container1.getBond(atomRemoved, atom) != null) { if (model.getMerge().containsKey(atom)) { for (IAtom atom2 : container2.atoms()) { if (!atom2.equals(atomMerged)) { if (container1.getBond(atomMerged, atom2) != null) { if (model.getMerge().get(atom).equals( atom2)) { IBond redundantBond = container1 .getBond(atom, atomRemoved); container1 .removeBond(redundantBond); removedBonds.add(redundantBond); } } } } } } } } // remove multi-edges if (container1.equals(container2)) { for (IBond bond : atomRemoved.bonds()) { IAtom nbor = bond.getOther(atomRemoved); for (IBond bond2 : bond.getOther(atomRemoved).bonds()) { if (bond2.getOther(nbor).equals(atomMerged)) { container2.removeBond(bond2); removedBonds.add(bond2); atomsToUpdate.add(nbor); break; } } } } removedBondss.add(removedBonds); // After the removal of redundant bonds, the actual merge is done. // One half of atoms in the merge map are removed and their bonds // are mapped to their replacement atoms. for (IBond bond : container1.getConnectedBondsList(atomRemoved)) { if (bond.getBegin().equals(atomRemoved)) { bond.setAtom(atomMerged, 0); bondsWithReplacedAtom.put(bond, 0); } else if (bond.getEnd().equals(atomRemoved)) { bond.setAtom(atomMerged, 1); bondsWithReplacedAtom.put(bond, 1); } else { ControllerHub.log.warn("Bond did not contain the atom it was adjacent to?"); } } container1.removeAtom(atomRemoved); updateAtom(atomMerged); bondsWithReplacedAtoms.add(bondsWithReplacedAtom); } for (IAtom atom : atomsToUpdate) { updateAtom(atom); } Map<Integer, Map<Integer, Integer>> oldRGroupHash = null; Map<Integer, Map<Integer, Integer>> newRGroupHash = null; if (rGroupHandler != null) { try { oldRGroupHash = rGroupHandler.makeHash(); rGroupHandler.adjustAtomContainers(chemModel.getMoleculeSet()); newRGroupHash = rGroupHandler.makeHash(); } catch (CDKException e) { unsetRGroupHandler(); for (IAtomContainer atc : droppedContainers) { atc.setProperty(CDKConstants.TITLE, null); } } } // Undo section to undo/redo the merge IUndoRedoFactory factory = getUndoRedoFactory(); UndoRedoHandler handler = getUndoRedoHandler(); if (movedDistance != null && factory != null && handler != null) { // we look if anything has been moved which was not merged IAtomContainer undoRedoSet = getIChemModel().getBuilder() .newInstance(IAtomContainer.class); if (renderer.getRenderer2DModel().getSelection() .getConnectedAtomContainer() != null) { undoRedoSet.add(renderer.getRenderer2DModel() .getSelection().getConnectedAtomContainer()); } Iterator<IAtom> it2 = mergeMap.keySet().iterator(); while (it2.hasNext()) { IAtom remove = it2.next(); undoRedoSet.removeAtom(remove); } IUndoRedoable moveundoredo = getUndoRedoFactory().getMoveAtomEdit( undoRedoSet, movedDistance, "Move atom"); IUndoRedoable undoredo = factory.getMergeMoleculesEdit(mergedAtoms, containers, droppedContainers, removedBondss, bondsWithReplacedAtoms, movedDistance, mergedPartnerAtoms, moveundoredo, oldRGroupHash, newRGroupHash, "Move and merge atoms", this); handler.postEdit(undoredo); } model.getMerge().clear(); structureChanged(); updateView(); } // OK public void setValence(IAtom atom, Integer newValence) { if (getUndoRedoFactory() != null && getUndoRedoHandler() != null) { IUndoRedoable undoredo = getUndoRedoFactory().getChangeValenceEdit( atom, atom.getValency(), newValence, "Change valence to " + newValence, this); getUndoRedoHandler().postEdit(undoredo); } if (!(atom instanceof IPseudoAtom)) { atom.setValency(newValence); } updateAtom(atom); structurePropertiesChanged(); } public void addChangeModeListener(IChangeModeListener listener) { changeModeListeners.add(listener); } public void removeChangeModeListener(IChangeModeListener listener) { changeModeListeners.remove(listener); } public void setFallbackModule (IControllerModule m) { this.fallbackModule = m; } /* * (non-Javadoc) * * @see * org.openscience.cdk.controller.IChemModelRelay#removeBondAndLoneAtoms * (org.openscience.cdk.interfaces.IBond) */ public void removeBondAndLoneAtoms(IBond bondToRemove) { IAtomContainer container = ChemModelManipulator .getRelevantAtomContainer(chemModel, bondToRemove.getAtom(0)); AtomBondSet undoRedoSet = new AtomBondSet(); undoRedoSet.add(bondToRemove); removeBondWithoutUndo(bondToRemove); if (container != null) { for (int i = 0; i < 2; i++) { if (container.getConnectedBondsCount(bondToRemove.getAtom(i)) == 0) { removeAtomWithoutUndo(bondToRemove.getAtom(i)); undoRedoSet.add(bondToRemove.getAtom(i)); } } } removeEmptyContainers(chemModel); IUndoRedoable undoredo = getUndoRedoFactory() .getRemoveAtomsAndBondsEdit(chemModel, undoRedoSet, "Delete Bond", this); getUndoRedoHandler().postEdit(undoredo); if(rGroupHandler!=null && !rGroupHandler.checkRGroupOkayForDelete(undoRedoSet, this)) { undoredo.undo(); return; } } private static final Pattern ATTACH_POINT_REGEX = Pattern.compile("_AP([1-9])"); // OK /* * (non-Javadoc) * * @see * org.openscience.cdk.controller.IChemModelRelay#convertToPseudoAtom(org * .openscience.cdk.interfaces.IAtom, java.lang.String) */ public IPseudoAtom convertToPseudoAtom(IAtom atom, String label) { IPseudoAtom pseudo = makePseudoAtom(label, atom.getPoint2d()); // attachment points only replace atoms if they have a single // bond attached, else we sprout off a new atom if (pseudo.getAttachPointNum() != 0 && atom.getBondCount() != 1) { addAtom(label, atom, true); } else { replaceAtom(pseudo, atom); } return pseudo; } private IPseudoAtom makePseudoAtom(String label, Point2d p) { IPseudoAtom pseudo = chemModel.getBuilder() .newInstance(IPseudoAtom.class); pseudo.setAtomicNumber(IAtom.Wildcard); pseudo.setImplicitHydrogenCount(0); Matcher matcher = ATTACH_POINT_REGEX.matcher(label); if (matcher.matches()) { pseudo.setAttachPointNum(Integer.parseInt(matcher.group(1))); } else { pseudo.setLabel(label); } pseudo.setPoint2d(p); return pseudo; } public void moveTo(IAtom atom, Point2d from, Point2d to, boolean finished) { if (!altMode && atom.getBondCount() == 1) { IBond bond = atom.bonds().iterator().next(); IAtom nbor = bond.getOther(atom); Vector2d a = new Vector2d(from.x - nbor.getPoint2d().x, from.y - nbor.getPoint2d().y); Vector2d b = new Vector2d(to.x - nbor.getPoint2d().x, to.y - nbor.getPoint2d().y); double angle = Math.atan2(a.x*b.y - a.y*b.x, a.x*b.x + a.y*b.y); double snapAngle = (Math.PI/12) * Math.round(angle / (Math.PI/12)); double cos = Math.cos(snapAngle); double sin = Math.sin(snapAngle); double x = a.x * cos - a.y * sin; double y = a.x * sin + a.y * cos; Vector2d c = new Vector2d(x, y); to.x = nbor.getPoint2d().x + c.x; to.y = nbor.getPoint2d().y + c.y; } moveToWithoutUndo(atom, to); if (finished) { IAtomContainer undoRedoSet = chemModel.getBuilder().newInstance(IAtomContainer.class); undoRedoSet.addAtom(atom); IUndoRedoable undoredo = getUndoRedoFactory().getMoveAtomEdit( undoRedoSet, new Vector2d(to.x - from.x, to.y - from.y), "Move atom(s)"); getUndoRedoHandler().postEdit(undoredo); } } // OK public void moveBy(Collection<IAtom> atoms, Vector2d move, Vector2d totalmove) { if (totalmove != null && getUndoRedoFactory() != null && getUndoRedoHandler() != null) { IAtomContainer undoRedoSet = chemModel.getBuilder() .newInstance(IAtomContainer.class); for (IAtom atom : atoms) { undoRedoSet.addAtom(atom); } IUndoRedoable undoredo = getUndoRedoFactory().getMoveAtomEdit( undoRedoSet, totalmove, "Move atom"); getUndoRedoHandler().postEdit(undoredo); } if (move != null) { for (IAtom atom : atoms) { Point2d newpoint = new Point2d(atom.getPoint2d()); newpoint.add(move); moveToWithoutUndo(atom, newpoint); } } } public IChemModel getChemModel() { return chemModel; } /** * Sets the mouse cursor shown on the renderPanel. * * @param cursor One of the constants from java.awt.Cursor. */ public void setCursor(int cursor) { eventRelay.setCursor(new Cursor(cursor)); } public void setCursor(CursorType type) { switch (type) { case DEFAULT: setCursor(Cursor.DEFAULT_CURSOR); break; case MOVE: setCursor(Cursor.HAND_CURSOR); break; case ROTATE: eventRelay.setCursor(rotateCursor); break; case RESIZE_N: setCursor(Cursor.N_RESIZE_CURSOR); break; case RESIZE_NE: setCursor(Cursor.NE_RESIZE_CURSOR); break; case RESIZE_E: setCursor(Cursor.E_RESIZE_CURSOR); break; case RESIZE_SE: setCursor(Cursor.SE_RESIZE_CURSOR); break; case RESIZE_S: setCursor(Cursor.S_RESIZE_CURSOR); break; case RESIZE_SW: setCursor(Cursor.SW_RESIZE_CURSOR); break; case RESIZE_W: setCursor(Cursor.W_RESIZE_CURSOR); break; case RESIZE_NW: setCursor(Cursor.NW_RESIZE_CURSOR); break; } } /** * Tells the mouse cursor shown on the renderPanel. * * @return One of the constants from java.awt.Cursor. */ public int getCursor() { return eventRelay.getCursor().getType(); } /** * 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 getFormula() { IMolecularFormula wholeModel = getIChemModel().getBuilder() .newInstance(IMolecularFormula.class); Iterator<IAtomContainer> containers = ChemModelManipulator .getAllAtomContainers(chemModel).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.getHTML(wholeModel, true, false); } public RGroupHandler getRGroupHandler() { return rGroupHandler; } /** * See unsetRGroupHandler() to nullify the R-group aspects. */ public void setRGroupHandler(RGroupHandler rGroupHandler) { ControllerHub.rGroupHandler = rGroupHandler; } public void unsetRGroupHandler() { ControllerHub.rGroupHandler = null; if (chemModel.getMoleculeSet()!=null) for (IAtomContainer atc : chemModel.getMoleculeSet().atomContainers()) { atc.removeProperty(CDKConstants.TITLE); } } private void adjustRgroup() { if (rGroupHandler != null) { try { rGroupHandler.adjustAtomContainers(chemModel.getMoleculeSet()); } catch (CDKException e) { unsetRGroupHandler(); //e.printStackTrace(); } } } public void setPhantomArrow(Point2d start, Point2d end) { this.phantomArrowStart=start; this.phantomArrowEnd=end; } public Point2d[] getPhantomArrow() { return new Point2d[]{phantomArrowStart, phantomArrowEnd}; } @Override public void setPhantomText(String text, Point2d position) { this.phantomText = text; this.phantomTextPosition = position; } public Point2d getPhantomTextPosition() { return phantomTextPosition; } public String getPhantomText() { return phantomText; } @Override public void rotate(Map<IAtom,Point2d> atoms, Point2d center, double angle) { // by default snap to 10 degrees (PI/18 radians) // in alt mode we allow free rotation if (!altMode) angle = (Math.PI/18) * Math.round(angle / (Math.PI/18)); /* For more info on the mathematics, see Wiki at * http://en.wikipedia.org/wiki/Coordinate_rotation */ double cosine = java.lang.Math.cos(angle); double sine = java.lang.Math.sin(angle); for (Map.Entry<IAtom,Point2d> e : atoms.entrySet()) { Point2d refPoint = e.getValue(); double newX = (refPoint.x * cosine) - (refPoint.y * sine); double newY = (refPoint.x * sine) + (refPoint.y * cosine); Point2d newCoords = new Point2d(newX + center.x, newY + center.y); e.getKey().setPoint2d(newCoords); } } @Override public void scale(Map<IAtom,Point2d> atoms, Point2d center, double amount, Scale direction) { // in alt mode snap to 1.5 increments if (altMode) amount = Math.round(2 * amount) / 2d; for (Map.Entry<IAtom,Point2d> e : atoms.entrySet()) { Point2d refPoint = e.getValue(); double newX = direction != Scale.Vertical ? (refPoint.x * amount) : refPoint.x; double newY = direction != Scale.Horizontal ? (refPoint.y * amount) : refPoint.y; Point2d newCoords = new Point2d(newX + center.x, newY + center.y); e.getKey().setPoint2d(newCoords); } } }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/controller/SelectSquareModule.java
.java
1,364
39
/* $Revision$ $Author$ $Date$ * * Copyright (C) 2008 Gilleain Torrance <gilleain.torrance@gmail.com> * * Contact: cdk-devel@list.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 org.openscience.jchempaint.renderer.selection.RectangleSelection; /** * @cdk.module controlbasic */ public class SelectSquareModule extends AbstractSelectModule { public SelectSquareModule(IChemModelRelay chemModelRelay) { super(chemModelRelay); selection = new RectangleSelection(); } public String getDrawModeString() { return "Select Square"; } }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/controller/IMouseEventRelay.java
.java
2,739
94
/* $Revision$ $Author$ $Date$ * * Copyright (C) 2007 Niels Out <nielsout@users.sf.net> * * Contact: cdk-devel@lists.sourceforge.net or nout@science.uva.nl * * 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; /** * * @cdk.module control */ public interface IMouseEventRelay { void mouseWheelMovedBackward(int modifiers, int clicks); void mouseWheelMovedForward(int modifiers, int clicks); void mouseClickedUp(int screenCoordX, int screenCoordY); void mouseClickedDown(int screenCoordX, int screenCoordY); void mouseClickedUp(int screenCoordX, int screenCoordY, int modifiers); void mouseClickedDown(int screenCoordX, int screenCoordY, int modifiers); void mouseClickedUpRight(int screenCoordX, int screenCoordY); /** * * @param screenCoordX * @param screenCoordY */ void mouseClickedDownRight(int screenCoordX, int screenCoordY); /** * * @param screenCoordX * @param screenCoordY */ void mouseClickedDouble(int screenCoordX, int screenCoordY); /** * * @param screenCoordX * @param screenCoordY */ void mouseMove(int screenCoordX, int screenCoordY); /** * * @param screenCoordX * @param screenCoordY */ void mouseEnter(int screenCoordX, int screenCoordY); /** * * @param screenCoordX * @param screenCoordY */ void mouseExit(int screenCoordX, int screenCoordY); /** * * @param screenCoordXFrom * @param screenCoordYFrom * @param screenCoordXTo * @param screenCoordYTo */ void mouseDrag(int screenCoordXFrom, int screenCoordYFrom, int screenCoordXTo, int screenCoordYTo, int modifiers); }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/controller/AddRingModule.java
.java
7,915
214
/* $Revision: $ $Author: $ $Date: $ * * Copyright (C) 2007 Gilleain Torrance * * 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.IBond; import org.openscience.cdk.interfaces.IChemObject; import org.openscience.cdk.interfaces.IRing; import org.openscience.cdk.layout.RingPlacer; import org.openscience.cdk.renderer.selection.AbstractSelection; import org.openscience.jchempaint.AtomBondSet; import org.openscience.jchempaint.renderer.selection.SingleSelection; import javax.vecmath.Point2d; import java.util.Map; /** * Adds an atom on the given location on mouseclick * * @author maclean * @cdk.module controlbasic */ public class AddRingModule extends ControllerModuleAdapter { private int ringSize; private boolean unsaturated = false; private String id; private RingPlacer ringPlacer = new RingPlacer(); private static long drawTime = 0; private Point2d mouseLastMoved = null; public AddRingModule(IChemModelRelay chemModelRelay, int ringSize, boolean unsaturated, String id) { super(chemModelRelay); this.ringSize = ringSize; this.unsaturated = unsaturated; this.id = id; } public AddRingModule(IChemModelRelay chemModelRelay, int ringSize, boolean unsaturated) { this(chemModelRelay, ringSize, unsaturated, null); } private IRing addRingToEmptyCanvas(Point2d p, boolean phantom) { if (unsaturated) { return chemModelRelay.addPhenyl(p, ringSize, phantom); } else { return chemModelRelay.addRing(ringSize, p, phantom); } } private IRing addRingToAtom(IAtom closestAtom, boolean phantom) { IRing newring; if (unsaturated) { newring = chemModelRelay.addPhenyl(closestAtom, ringSize, phantom); } else { newring = chemModelRelay.addRing(closestAtom, ringSize, phantom); } newring.removeAtom(closestAtom); return newring; } private IRing addRingToBond(IBond bond, boolean phantom) { IRing newring; if (unsaturated) { newring = chemModelRelay.addPhenyl(bond, ringSize, phantom); } else { newring = chemModelRelay.addRing(bond, ringSize, phantom); } newring.removeAtom(bond.getAtom(0)); newring.removeAtom(bond.getAtom(1)); newring.removeBond(bond); return newring; } public void mouseClickedDown(Point2d worldCoord, int modifiers) { mouseLastMoved = null; IAtom closestAtom = chemModelRelay.getClosestAtom(worldCoord); IBond closestBond = chemModelRelay.getClosestBond(worldCoord); IChemObject singleSelection = getHighlighted(worldCoord, closestAtom, closestBond); if (singleSelection == null) { //we add the ring IRing newRing = this.addRingToEmptyCanvas(worldCoord, false); Map<IAtom, IAtom> mergeSet = chemModelRelay.getRenderer().getRenderer2DModel().getMerge(); mergeSet.clear(); //we look if it would merge for (IAtom atom : newRing.atoms()) { IAtom closestAtomInRing = this.chemModelRelay.getClosestAtom(atom); if (closestAtomInRing != null) { mergeSet.put(atom, closestAtomInRing); } } // if we need to merge, we first move the ring so that the merge atoms // are exactly on top of each other - if not doing this, rings get distorted. for (Map.Entry<IAtom, IAtom> e : mergeSet.entrySet()) { IAtom atomOut = e.getKey(); IAtom atomRep = e.getValue(); atomOut.getPoint2d().sub(atomRep.getPoint2d()); Point2d pointSub = new Point2d(atomOut.getPoint2d().x, atomOut.getPoint2d().y); for (IAtom atom : newRing.atoms()) { atom.getPoint2d().sub(pointSub); } } AtomBondSet abset = new AtomBondSet(newRing); for (IAtom atom : mergeSet.keySet()) { abset.remove(atom); for (IBond bond : newRing.getConnectedBondsList(atom)) { if (mergeSet.containsKey(bond.getOther(atom))) abset.remove(bond); } } //and perform the merge chemModelRelay.mergeMolecules(null); chemModelRelay.getRenderer().getRenderer2DModel().getMerge().clear(); } else if (singleSelection instanceof IAtom) { this.addRingToAtom((IAtom) singleSelection, false); } else if (singleSelection instanceof IBond) { this.addRingToBond((IBond) singleSelection, false); } if (singleSelection == null) setSelection(AbstractSelection.EMPTY_SELECTION); else setSelection(new SingleSelection<IChemObject>(singleSelection)); chemModelRelay.updateView(); } public void mouseClickedDownRight(Point2d worldCoord) { this.chemModelRelay.clearPhantoms(); this.setSelection(AbstractSelection.EMPTY_SELECTION); chemModelRelay.getRenderer().getRenderer2DModel().getMerge().clear(); this.chemModelRelay.updateView(); this.escapeTheMode(); } public void mouseMove(Point2d worldCoord) { if ((System.nanoTime() - drawTime) < 4000000) { return; } this.mouseLastMoved = worldCoord; this.chemModelRelay.clearPhantoms(); IAtom closestAtom = chemModelRelay.getClosestAtom(worldCoord); IBond closestBond = chemModelRelay.getClosestBond(worldCoord); IChemObject singleSelection = getHighlighted(worldCoord, closestAtom, closestBond); if (singleSelection == null) { this.addRingToEmptyCanvas(worldCoord, true); } else if (singleSelection instanceof IAtom) { this.addRingToAtom((IAtom) singleSelection, true); } else if (singleSelection instanceof IBond) { this.addRingToBond((IBond) singleSelection, true); } drawTime = System.nanoTime(); this.chemModelRelay.updateView(); } @Override public void updateView() { if (mouseLastMoved != null) mouseMove(mouseLastMoved); } public String getDrawModeString() { if (unsaturated) { return "Benzene"; } else { return "Ring" + " " + ringSize; } } public String getID() { return id; } public void setID(String ID) { this.id = ID; } }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/controller/ChangeFormalChargeModule.java
.java
2,917
87
/* $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 java.util.HashSet; import java.util.Set; import javax.vecmath.Point2d; import org.openscience.cdk.interfaces.IAtom; import org.openscience.jchempaint.AtomBondSet; import org.openscience.jchempaint.renderer.selection.MultiSelection; /** * Changes (Increases or Decreases) Formal Charge of an atom * * @author Niels Out * @cdk.svnrev $Revision: 9162 $ * @cdk.module controlbasic */ public class ChangeFormalChargeModule extends ControllerModuleAdapter { private int change = 0; private String ID; public ChangeFormalChargeModule(IChemModelRelay chemModelRelay, int change) { super(chemModelRelay); this.change = change; } public void mouseClickedDown(Point2d worldCoord, int modifiers) { AtomBondSet selectedAC = getSelectAtomBondSet(worldCoord); if(selectedAC == null) return; Set<IAtom> newSelection = new HashSet<IAtom>(); for(IAtom atom:selectedAC.atoms()) { newSelection.add( atom ); int newCharge = change; if( atom.getFormalCharge() != null) newCharge += atom.getFormalCharge(); chemModelRelay.setCharge(atom, newCharge); } setSelection( new MultiSelection<IAtom>(newSelection) ); chemModelRelay.updateView();// FIXME do you really need to call it here? } public String getDrawModeString() { if (change < 0) return "Decrease Charge"; else return "Increase Charge"; } public String getID() { return ID; } public void setID(String ID) { this.ID=ID; } }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/controller/RotateModule.java
.java
10,404
277
/* * Copyright (C) 2008 Gilleain Torrance <gilleain.torrance@gmail.com> * 2009 Mark Rijnbeek <mark_rynbeek@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 java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import javax.vecmath.Point2d; import org.openscience.cdk.interfaces.IAtom; import org.openscience.cdk.interfaces.IBond; import org.openscience.cdk.renderer.selection.AbstractSelection; import org.openscience.cdk.tools.ILoggingTool; import org.openscience.cdk.tools.LoggingToolFactory; import org.openscience.jchempaint.controller.undoredo.IUndoRedoFactory; import org.openscience.jchempaint.controller.undoredo.IUndoRedoable; import org.openscience.jchempaint.controller.undoredo.UndoRedoHandler; import org.openscience.cdk.renderer.selection.IChemObjectSelection; /** * Module to rotate a selection of atoms (and their bonds). * * @cdk.module controlbasic */ public class RotateModule extends ControllerModuleAdapter { protected static ILoggingTool logger = LoggingToolFactory.createLoggingTool(RotateModule.class); private static final double SNAP_ANGLE = (Math.PI / 6); private double rotationAngle; protected boolean selectionMade = false; protected IChemObjectSelection selection; protected Point2d rotationCenter; protected Map<IAtom, Point2d> startCoordsRelativeToRotationCenter; protected Map<IAtom, Point2d[]> atomCoordsMap; protected boolean rotationPerformed; protected String ID; /** * Constructor * * @param chemModelRelay */ public RotateModule(IChemModelRelay chemModelRelay) { super(chemModelRelay); logger.debug("constructor"); } /** * Initializes possible rotation. Determines rotation center and stores * coordinates of atoms to be rotated. These stored coordinates are relative * to the rotation center. */ public void mouseClickedDown(Point2d worldCoord, int modifiers) { logger.debug("rotate mouseClickedDown, initializing rotation"); rotationCenter = null; selection = super.chemModelRelay.getRenderer().getRenderer2DModel() .getSelection(); if (selection == null || !selection.isFilled() || selection.getConnectedAtomContainer() == null || selection.getConnectedAtomContainer().getAtomCount() == 0) { /* * Nothing selected- return. Dragging the mouse will not result in * any rotation logic. */ logger.debug("Nothing selected for rotation"); selectionMade = false; return; } else { rotationPerformed = false; rotationAngle = 0.0; selectionMade = true; chemModelRelay.getRenderer().getRenderer2DModel().setRotating(true); Collection<IAtom> selectedAtoms = selection.elements(IAtom.class); rotationCenter = getRotationCenter(selection); logger.debug("rotationCenter " + rotationCenter.x + " " + rotationCenter.y); /* Keep original coordinates for possible undo/redo */ atomCoordsMap = new HashMap<>(); /* Store the original coordinates relative to the rotation center. * These are necessary to rotate around the center of the * selection rather than the draw center. */ startCoordsRelativeToRotationCenter = new HashMap<>(); for (IAtom atom : selectedAtoms) { Point2d relPoint = new Point2d(); relPoint.x = atom.getPoint2d().x - rotationCenter.x; relPoint.y = atom.getPoint2d().y - rotationCenter.y; startCoordsRelativeToRotationCenter.put(atom, relPoint); atomCoordsMap.put(atom, new Point2d[]{null, atom.getPoint2d()}); } } } static Point2d getRotationCenter(IChemObjectSelection selection) { /* * Determine rotationCenter as the middle of a region defined by * min(x,y) and max(x,y) of coordinates of the selected atoms. */ Set<IAtom> anchors = new HashSet<>(); Double upperX = null, lowerX = null, upperY = null, lowerY = null; for (IAtom atom : selection.elements(IAtom.class)) { if (upperX == null) { upperX = atom.getPoint2d().x; lowerX = upperX; upperY = atom.getPoint2d().y; lowerY = atom.getPoint2d().y; } else { double currX = atom.getPoint2d().x; if (currX > upperX) upperX = currX; if (currX < lowerX) lowerX = currX; double currY = atom.getPoint2d().y; if (currY > upperY) upperY = currY; if (currY < lowerY) lowerY = currY; } for (IBond bond : atom.bonds()) { if (!selection.contains(bond.getOther(atom))) anchors.add(atom); } } if (anchors.size() == 1) { return new Point2d(anchors.iterator().next().getPoint2d()); } else { return new Point2d((upperX + lowerX) / 2, (upperY + lowerY) / 2); } } /** * On mouse drag, actual rotation around the center is done */ public void mouseDrag(Point2d worldCoordFrom, Point2d worldCoordTo, int modifiers) { if (selectionMade) { rotationPerformed = true; rotationAngle += getRotationAmount(rotationCenter, worldCoordFrom, worldCoordTo); chemModelRelay.rotate(startCoordsRelativeToRotationCenter, rotationCenter, rotationAngle); } chemModelRelay.updateView(); } static double getRotationAmount(Point2d rotationCenter, Point2d from, Point2d to) { /* * Determine the quadrant the user is currently in, relative to the * rotation center. */ int quadrant = 0; if ((from.x >= rotationCenter.x)) if ((from.y <= rotationCenter.y)) quadrant = 1; // 12 to 3 o'clock else quadrant = 2; // 3 to 6 o'clock else if ((from.y <= rotationCenter.y)) quadrant = 4; // 9 to 12 o'clock else quadrant = 3; // 6 to 9 o'clock /* * The quadrant and the drag combined determine in which direction * the rotation will be done. For example, dragging in direction * left/down in quadrant 4 means rotating counter clockwise. */ final int SLOW_DOWN_FACTOR = 4; switch (quadrant) { case 1: return (to.x - from.x) / SLOW_DOWN_FACTOR + (to.y - from.y) / SLOW_DOWN_FACTOR; case 2: return (from.x - to.x) / SLOW_DOWN_FACTOR + (to.y - from.y) / SLOW_DOWN_FACTOR; case 3: return (from.x - to.x) / SLOW_DOWN_FACTOR + (from.y - to.y) / SLOW_DOWN_FACTOR; case 4: return (to.x - from.x) / SLOW_DOWN_FACTOR + (from.y - to.y) / SLOW_DOWN_FACTOR; } return 0; } /** * After the rotation (=mouse up after drag), post the undo/redo information * with the old and the new coordinates */ public void mouseClickedUp(Point2d worldCoord, int modifiers) { if (rotationPerformed && atomCoordsMap != null && selection.isFilled()) { logger.debug("posting undo/redo for rotation"); /* Keep new coordinates for the sake of possible undo/redo */ for (IAtom atom : selection.getConnectedAtomContainer().atoms()) { Point2d[] coords = atomCoordsMap.get(atom); coords[0] = atom.getPoint2d(); } /* Post the rotation */ IUndoRedoFactory factory = chemModelRelay.getUndoRedoFactory(); UndoRedoHandler handler = chemModelRelay.getUndoRedoHandler(); if (factory != null && handler != null) { IUndoRedoable undoredo = factory.getChangeCoordsEdit( atomCoordsMap, new HashMap<IBond, IBond.Stereo>(), "Rotation"); handler.postEdit(undoredo); } chemModelRelay.getRenderer().getRenderer2DModel().setRotating(false); chemModelRelay.updateView(); } else { chemModelRelay.select(AbstractSelection.EMPTY_SELECTION); chemModelRelay.getRenderer().getRenderer2DModel().setRotating(false); chemModelRelay.updateView(); } } public void setChemModelRelay(IChemModelRelay relay) { this.chemModelRelay = relay; } public String getDrawModeString() { return "Rotate"; } public String getID() { return ID; } public void setID(String ID) { this.ID = ID; } }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/controller/MoveModule.java
.java
16,580
420
/* * Copyright (C) 2007 Niels Out <nielsout@users.sf.net> * Copyright (C) 2008-2009 Arvid Berg <goglepox@users.sf.net> * Copyright (C) 2008 Stefan Kuhn (undo redo) * Copyright (C) 2009 Mark Rijnbeek (markr@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; 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.IBond; import org.openscience.cdk.interfaces.IChemObject; import org.openscience.cdk.renderer.selection.AbstractSelection; import org.openscience.cdk.renderer.selection.IChemObjectSelection; import org.openscience.cdk.tools.ILoggingTool; import org.openscience.cdk.tools.LoggingToolFactory; import org.openscience.cdk.tools.manipulator.ChemModelManipulator; import org.openscience.jchempaint.AtomBondSet; import org.openscience.jchempaint.controller.undoredo.IUndoRedoFactory; import org.openscience.jchempaint.controller.undoredo.UndoRedoHandler; import org.openscience.jchempaint.renderer.JChemPaintRendererModel; import org.openscience.jchempaint.renderer.selection.LogicalSelection; import org.openscience.jchempaint.renderer.selection.SingleSelection; import javax.vecmath.Point2d; import javax.vecmath.Vector2d; import java.awt.Cursor; import java.util.ArrayList; 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.Set; import static org.openscience.jchempaint.controller.AbstractSelectModule.getSelectionControlType; /** * Module to move around a selection of atoms and bonds. * Handles merging of atoms. * * @author Niels Out * @cdk.svnrev $Revision: 9162 $ * @cdk.module controlbasic */ public class MoveModule extends ControllerModuleAdapter { private static ILoggingTool logger = LoggingToolFactory.createLoggingTool(MoveModule.class); private Vector2d offset; private Set<IAtom> atomsToMove; private Point2d start2DCenter; private Point2d end2DCenter; private String ID; private ControllerModuleAdapter switchtowhenoutside; private enum Transform { Move, Rotate, Scale } private Transform transform = Transform.Move; private double transformAmmount; protected Point2d transformOrigin; protected IChemModelRelay.Scale scaleDir = IChemModelRelay.Scale.Both; protected Map<IAtom, Point2d> relativeAtomCoords; protected Map<IAtom, Point2d[]> atomCoordsMap; protected boolean transformMade; /** * Constructor for the MoveModule. Gets passed an instance of another module * to which mode switches if clicked outside the selection. * * @param chemObjectRelay The current ChemObjectRelay. * @param switchtowhenoutside The module to switch to if clicked outside selection. */ public MoveModule(IChemModelRelay chemObjectRelay, ControllerModuleAdapter switchtowhenoutside) { super(chemObjectRelay); this.switchtowhenoutside = switchtowhenoutside; } // if anything is selected, set offset, start2DCenter, and atomsToMove. // if not, switch to other mode and reset mouse cursor. public void mouseClickedDown(Point2d worldCoord, int modifiers) { JChemPaintRendererModel jcpModel = chemModelRelay.getRenderer().getRenderer2DModel(); // move/rotate/scales works on atom coords, a bond may be selected // without its end points so we expand the selection to include // those atoms selection = getExpandedSelection(jcpModel.getSelection()); IChemModelRelay.CursorType cursor = getSelectionControlType(worldCoord, chemModelRelay); if (cursor == IChemModelRelay.CursorType.ROTATE) { transformMade = false; transformAmmount = 0; transformOrigin = RotateModule.getRotationCenter(selection); /* Keep original coordinates for possible undo/redo */ atomCoordsMap = new HashMap<>(); /* Store the original coordinates relative to the rotation center. * These are necessary to rotate around the center of the * selection rather than the draw center. */ relativeAtomCoords = new HashMap<>(); for (IAtom atom : selection.elements(IAtom.class)) { Point2d relPoint = new Point2d(); relPoint.x = atom.getPoint2d().x - transformOrigin.x; relPoint.y = atom.getPoint2d().y - transformOrigin.y; relativeAtomCoords.put(atom, relPoint); atomCoordsMap.put(atom, new Point2d[]{null, atom.getPoint2d()}); } transform = Transform.Rotate; jcpModel.setRotating(true); return; } else if (cursor.isResize()) { transformMade = false; transformOrigin = RotateModule.getRotationCenter(selection); transformAmmount = worldCoord.distance(transformOrigin); /* Keep original coordinates for possible undo/redo */ atomCoordsMap = new HashMap<>(); /* Store the original coordinates relative to the rotation center. * These are necessary to rotate around the center of the * selection rather than the draw center. */ relativeAtomCoords = new HashMap<>(); for (IAtom atom : selection.elements(IAtom.class)) { Point2d relPoint = new Point2d(); relPoint.x = atom.getPoint2d().x - transformOrigin.x; relPoint.y = atom.getPoint2d().y - transformOrigin.y; relativeAtomCoords.put(atom, relPoint); atomCoordsMap.put(atom, new Point2d[]{null, atom.getPoint2d()}); } transform = Transform.Scale; scaleDir = cursor.getScaleDirection(); return; } else { transform = Transform.Move; } // if we are outside bounding box, we deselect, else // we actually start a move. AtomBondSet selectedAC = getSelectAtomBondSet(worldCoord); if (selectedAC != null && !selectedAC.isEmpty()) { // It could be that only a selected bond is going to be moved. // So make sure that the attached atoms are included, otherwise // the undo will fail to place the atoms back where they were atomsToMove = new HashSet<IAtom>(); for (IAtom atom : selectedAC.atoms()) { atomsToMove.add(atom); } for (IBond bond : selectedAC.bonds()) { for (IAtom atom : bond.atoms()){ atomsToMove.add(atom); selectedAC.add(atom); } } Point2d current = GeometryUtil.get2DCenter(selectedAC.atoms()); start2DCenter = current; offset = new Vector2d(); offset.sub(current, worldCoord); } else if(switchtowhenoutside!=null){ jcpModel .setSelection(AbstractSelection.EMPTY_SELECTION); this.chemModelRelay .setActiveDrawModule(switchtowhenoutside); chemModelRelay.updateView(); endMove(); switchtowhenoutside.mouseClickedDown(worldCoord); chemModelRelay.setCursor(Cursor.DEFAULT_CURSOR); } } private IChemObjectSelection getExpandedSelection(IChemObjectSelection selection) { LogicalSelection expandSelection = new LogicalSelection(LogicalSelection.Type.ALL); for (IAtom atom : selection.elements(IAtom.class)) { expandSelection.select(atom); } for (IBond bond : selection.elements(IBond.class)) { expandSelection.select(bond.getBegin()); expandSelection.select(bond.getEnd()); } return expandSelection; } public void mouseMove(Point2d p){ AbstractSelectModule.showMouseCursor(p, this.chemModelRelay); } public void mouseClickedUp(Point2d worldCoord, int modifiers) { if (transform == Transform.Rotate || transform == Transform.Scale) { if (transformMade && atomCoordsMap != null && selection.isFilled()) { /* Keep new coordinates for the sake of possible undo/redo */ for (IAtom atom : selection.getConnectedAtomContainer().atoms()) { atomCoordsMap.get(atom)[0] = atom.getPoint2d(); } /* Post the rotation/scale */ IUndoRedoFactory factory = chemModelRelay.getUndoRedoFactory(); UndoRedoHandler handler = chemModelRelay.getUndoRedoHandler(); if (factory != null && handler != null) { handler.postEdit(factory.getChangeCoordsEdit(atomCoordsMap, new HashMap<>(), transform.name())); } } chemModelRelay.setCursor(Cursor.DEFAULT_CURSOR); chemModelRelay.getRenderer().getRenderer2DModel().setRotating(false); chemModelRelay.updateView(); return; } if (start2DCenter != null) { // take 2d center of end point to ensure correct positional undo Vector2d total = new Vector2d(); Point2d end2DCenter = GeometryUtil.get2DCenter(atomsToMove); total.sub(end2DCenter, start2DCenter); Map<IAtom, IAtom> mergeMap = calculateMerge(atomsToMove); JChemPaintRendererModel model = chemModelRelay.getRenderer().getRenderer2DModel(); model.getMerge().clear(); model.getMerge().putAll(mergeMap); // Do the merge of atoms if (!mergeMap.isEmpty()) { try { chemModelRelay.mergeMolecules(total); } catch (RuntimeException e) { //move things back, merge is not allowed Vector2d d = new Vector2d(); d.sub(start2DCenter,end2DCenter); chemModelRelay.moveBy(atomsToMove, d, total); chemModelRelay.updateView(); } } else { // single atom will snap to sensible angles (moveTo(atom,from,to) if (atomsToMove.size() == 1) { chemModelRelay.moveTo(atomsToMove.iterator().next(), start2DCenter, end2DCenter, true); } else { chemModelRelay.moveBy(atomsToMove, null, total); } } } IControllerModule newActiveModule = new SelectSquareModule(this.chemModelRelay); newActiveModule.setID("select"); this.chemModelRelay.setActiveDrawModule(newActiveModule); endMove(); } private void endMove() { start2DCenter = null; selection = null; offset = null; } /** * Most move mode calculations are done in this routine. */ public void mouseDrag(Point2d worldCoordFrom, Point2d worldCoordTo, int modifiers) { if (transform == Transform.Rotate) { transformMade = true; transformAmmount += RotateModule.getRotationAmount(transformOrigin, worldCoordFrom, worldCoordTo); chemModelRelay.rotate(relativeAtomCoords, transformOrigin, transformAmmount); chemModelRelay.updateView(); return; } else if (transform == Transform.Scale) { transformMade = true; double dist = worldCoordTo.distance(transformOrigin) / transformAmmount; chemModelRelay.scale(relativeAtomCoords, transformOrigin, dist, scaleDir); chemModelRelay.updateView(); return; } end2DCenter = worldCoordTo; Vector2d d = new Vector2d(); d.sub(worldCoordTo, worldCoordFrom); // single atom will snap to sensible angles (moveTo(atom,from,to) if (atomsToMove.size() == 1) { chemModelRelay.moveTo(atomsToMove.iterator().next(), start2DCenter, worldCoordTo, false); } else { chemModelRelay.moveBy(atomsToMove, d, null); } chemModelRelay.updateView(); } public static class DistAtom implements Comparable<DistAtom>{ IAtom atom; double distSquared; public DistAtom(IAtom atom, double distSquared) { this.atom = atom; this.distSquared = distSquared; } public int compareTo( DistAtom o ) { if(this.distSquared < o.distSquared) return -1; if(this.distSquared > o.distSquared) return 1; return 0; } } private Map<IAtom, IAtom> calculateMerge( Set<IAtom> mergeAtoms ) { JChemPaintRendererModel rModel = chemModelRelay.getRenderer().getRenderer2DModel(); double maxDistance = rModel.getHighlightDistance()/ rModel.getScale(); maxDistance *= maxDistance; // maxDistance squared Map<IAtom,IAtom> mergers = new HashMap<IAtom, IAtom>(); Iterator<IAtomContainer> containers = ChemModelManipulator.getAllAtomContainers(chemModelRelay.getIChemModel()).iterator(); while (containers.hasNext()) { IAtomContainer ac = (IAtomContainer)containers.next(); for(IAtom atom:mergeAtoms) { List<DistAtom> candidates = findMergeCandidates(ac,atom); Collections.sort( candidates); for(DistAtom candidate:candidates) { if(candidate.distSquared>maxDistance) break; if(mergeAtoms.contains( candidate.atom )) continue; mergers.put( atom, candidate.atom ); } } } return mergers; } /* (non-Javadoc) * @see org.openscience.cdk.controller.ControllerModuleAdapter#mouseClickedDouble(javax.vecmath.Point2d) */ public void mouseClickedDouble(Point2d p){ IAtom closestAtom = chemModelRelay.getClosestAtom(p); IBond closestBond = chemModelRelay.getClosestBond(p); IChemObject singleSelection = getHighlighted( p, closestAtom, closestBond ); if(singleSelection!=null){ for (IAtomContainer isolatedSystem : ConnectivityChecker.partitionIntoMolecules(this.chemModelRelay.getIChemModel().getMoleculeSet().getAtomContainer(0)).atomContainers()) { if(isolatedSystem.contains(closestAtom) || isolatedSystem.contains(closestBond)){ this.chemModelRelay.select(new SingleSelection<IAtomContainer>(isolatedSystem)); } } } chemModelRelay.updateView(); } private List<DistAtom> findMergeCandidates(IAtomContainer set, IAtom atom ) { List<DistAtom> candidates = new ArrayList<DistAtom>(); for(IAtom candidate:set.atoms()) { double disSquare = candidate.getPoint2d().distanceSquared( atom.getPoint2d() ); candidates.add(new DistAtom(candidate,disSquare)); } return candidates; } public String getDrawModeString() { return "Move"; } public String getID() { return ID; } public void setID(String ID) { this.ID=ID; } }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/controller/ZoomModule.java
.java
2,307
84
package org.openscience.jchempaint.controller; import javax.vecmath.Point2d; import javax.vecmath.Vector2d; import org.openscience.jchempaint.renderer.IRenderer; import org.openscience.jchempaint.renderer.JChemPaintRendererModel; import java.awt.event.InputEvent; import java.awt.event.KeyEvent; /** * @cdk.module controlbasic */ public class ZoomModule extends ControllerModuleAdapter { public static final int MAX_ZOOM_AMOUNT = 10; public static final double MIN_ZOOM_AMOUNT = .1; private Point2d worldCoord = null; private String ID; public ZoomModule(IChemModelRelay chemModelRelay) { super(chemModelRelay); } public void mouseWheelMovedForward(int modifiers, int clicks) { // shift scroll to zoom if ((modifiers & InputEvent.META_DOWN_MASK) == 0) return; doZoom( .9 ); chemModelRelay.fireZoomEvent(); chemModelRelay.updateView(); } public void mouseWheelMovedBackward(int modifiers, int clicks) { // shift scroll to zoom if ((modifiers & InputEvent.META_DOWN_MASK) == 0) return; doZoom( 1.1 ); chemModelRelay.fireZoomEvent(); chemModelRelay.updateView(); } private void doZoom(double z) { IRenderer renderer = chemModelRelay.getRenderer(); double currentZoom = renderer.getRenderer2DModel().getZoomFactor(); if (currentZoom * z <= MIN_ZOOM_AMOUNT) return; if (currentZoom * z >= MAX_ZOOM_AMOUNT) return; zoom(z); } private void zoom(double zoomFactor) { JChemPaintRendererModel model = chemModelRelay.getRenderer().getRenderer2DModel(); double zoom = model.getZoomFactor(); if (zoom <= MIN_ZOOM_AMOUNT || zoom >= MAX_ZOOM_AMOUNT) return; zoom = zoom * zoomFactor; // clamp zoom = Math.max(MIN_ZOOM_AMOUNT, Math.min(zoom, MAX_ZOOM_AMOUNT)); chemModelRelay.getRenderer().setZoom( zoom ); } @Override public void mouseMove( Point2d worldCoord ) { this.worldCoord = worldCoord; } public String getDrawModeString() { return "Zoom"; } public String getID() { return ID; } public void setID(String ID) { this.ID=ID; } }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/controller/ReactionArrowModule.java
.java
8,018
200
/* * Copyright (C) 2009 Stefan Kuhn <shk3@users.sourceforge.net> * * 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 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 javax.vecmath.Vector2d; import org.openscience.cdk.interfaces.IAtom; import org.openscience.cdk.interfaces.IAtomContainer; import org.openscience.cdk.interfaces.IAtomContainerSet; import org.openscience.cdk.interfaces.IReaction; import org.openscience.cdk.interfaces.IReactionSet; import org.openscience.cdk.tools.ILoggingTool; import org.openscience.cdk.tools.LoggingToolFactory; import java.util.ArrayList; import java.util.List; public class ReactionArrowModule extends ControllerModuleAdapter { protected static ILoggingTool logger = LoggingToolFactory.createLoggingTool(ReactionArrowModule.class); Point2d startPoint = null; protected String ID; /** * Constructor * @param chemModelRelay */ public ReactionArrowModule(IChemModelRelay chemModelRelay) { super(chemModelRelay); logger.debug("constructor"); } @Override public void mouseClickedDown(Point2d worldCoordFrom, int modifiers) { startPoint = worldCoordFrom; } @Override public void mouseClickedUp(Point2d endPoint, int modifiers) { //first, we get rid of the phantom arrow chemModelRelay.setPhantomArrow(null, null); chemModelRelay.updateView(); //for each molecule, we need to look if the majority of // its atoms are to the left or right or on the arrow IAtomContainerSet moleculeSet = super.chemModelRelay.getChemModel().getMoleculeSet(); if (moleculeSet.getAtomContainerCount() == 0 || (moleculeSet.getAtomContainerCount() == 1 && moleculeSet.getAtomContainer(0).getAtomCount() == 0)) { return; } final Vector2d unit = newUnitVector(startPoint, endPoint); final Vector2d perp = new Vector2d(unit.y, -unit.x); List<IAtomContainer> reactants = new ArrayList<IAtomContainer>(2); List<IAtomContainer> products = new ArrayList<IAtomContainer>(2); // determine the reactants and products of a reaction we do this by // taking the perpendicular vector and testing where atoms lie with // respect to the start and end of the arrow. The following diagram // may help visualise what the startPos and endPos values are. // // startPos < 0 startPos > 0 // endPost < 0 endPost > 0 // ^ ^ // | | // ---------------------> // for (IAtomContainer container : moleculeSet.atomContainers()) { // count the number of atoms before and after the arrow for this molecule int beforeStart = 0; int afterEnd = 0; for (final IAtom atom : container.atoms()){ final Point2d p = atom.getPoint2d(); // sign( (Bx-Ax)*(Y-Ay) - (By-Ay)*(X-Ax) ) final double endPos = (perp.x) * (p.y - endPoint.y) - (perp.y) * (p.x - endPoint.x); final double startPos = (perp.x) * (p.y - startPoint.y) - (perp.y) * (p.x - startPoint.x); if (endPos > 0) afterEnd++; if (startPos < 0) beforeStart++; } if (beforeStart > afterEnd) { reactants.add(container); } else if (beforeStart < afterEnd) { products.add(container); } else { //TODO catalysts in general } } // don't create a new reaction if (reactants.isEmpty() && products.isEmpty()) return; // do reaction creation // JWM: This used to use 'ReactionChain' but there is a much better way // of doing this and support branching - it involves ditching the ChemModel // are just storing everything in one container, this a big change but // will be done in future IReactionSet reactionSet = super.chemModelRelay.getChemModel().getReactionSet(); if (reactionSet == null) { reactionSet = super.chemModelRelay.getChemModel().getBuilder().newInstance(IReactionSet.class); super.chemModelRelay.getChemModel().setReactionSet(reactionSet); } IReaction reaction = moleculeSet.getBuilder().newInstance(IReaction.class); reactionSet.addReaction(reaction); reaction.setID(ReactionHub.newReactionId(chemModelRelay)); for (IAtomContainer reactant : reactants) { ReactionHub.makeReactantInExistingReaction((ControllerHub) super.chemModelRelay, reaction.getID(), cloneReactionParticipant(reactant), reactant); } for (IAtomContainer product : products) { ReactionHub.makeProductInExistingReaction((ControllerHub) super.chemModelRelay, reaction.getID(), cloneReactionParticipant(product), product); } } static Vector2d newUnitVector(Point2d a, Point2d b) { Vector2d v = new Vector2d(b.x - a.x, b.y - a.y); v.normalize(); return v; } IAtomContainer cloneReactionParticipant(IAtomContainer org) { try { IAtomContainer cpy = (IAtomContainer) org.clone(); if (org.getID() != null) { cpy.setID(org.getID()); } else { cpy.setID("ac" + System.currentTimeMillis()); } return cpy; } catch (CloneNotSupportedException e) { // never going to happen (should be suppressed) logger.error("Could not clone IAtomContainer: ", e.getMessage()); logger.debug(e); throw new InternalError("Could not clone IAtomContainer: " + e.getMessage()); } } /** * On mouse drag, quasi-3D rotation around the center is done * (It isn't real 3D rotation because of truncation of transformation * matrix to 2x2) */ @Override public void mouseDrag(Point2d worldCoordFrom, Point2d worldCoordTo, int modifiers) { chemModelRelay.setPhantomArrow(startPoint, worldCoordTo); chemModelRelay.updateView(); } public String getDrawModeString() { return "Draw a reaction Arrow"; } public String getID() { return ID; } public void setID(String ID) { this.ID = ID; } }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/controller/Rotate3DModule.java
.java
4,056
110
/* * Copyright (C) 2009 Konstantin Tokarev <annulen@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 javax.vecmath.Point2d; import org.openscience.cdk.interfaces.IAtom; import org.openscience.cdk.interfaces.IAtomContainer; import java.util.Map; public class Rotate3DModule extends RotateModule { private double rotationAnglePhi; private double rotationAnglePsi; private boolean horizontalFlip; private boolean verticalFlip; /** * Constructor * @param chemModelRelay */ public Rotate3DModule(IChemModelRelay chemModelRelay) { super(chemModelRelay); logger.debug("constructor"); horizontalFlip = false; verticalFlip = false; } /** * On mouse drag, quasi-3D rotation around the center is done * (It isn't real 3D rotation because of truncation of transformation * matrix to 2x2) */ @Override public void mouseDrag(Point2d worldCoordFrom, Point2d worldCoordTo, int modifiers) { if (selectionMade) { rotationPerformed=true; final int SLOW_DOWN_FACTOR=1; rotationAnglePhi += (worldCoordTo.x - worldCoordFrom.x)/SLOW_DOWN_FACTOR; rotationAnglePsi += (worldCoordTo.y - worldCoordFrom.y)/SLOW_DOWN_FACTOR; /* For more info on the mathematics, see Wiki at * http://en.wikipedia.org/wiki/Rotation_matrix */ double cosinePhi = java.lang.Math.cos(rotationAnglePhi); double sinePhi = java.lang.Math.sin(rotationAnglePhi); double cosinePsi = java.lang.Math.cos(rotationAnglePsi); double sinePsi = java.lang.Math.sin(rotationAnglePsi); for (Map.Entry<IAtom,Point2d> e : startCoordsRelativeToRotationCenter.entrySet()) { Point2d p = e.getValue(); double newX = p.x*cosinePhi + p.y*sinePhi*sinePsi; double newY = p.y*cosinePsi; Point2d newCoords = new Point2d(newX + rotationCenter.x, newY + rotationCenter.y); e.getKey().setPoint2d(newCoords); } if ((cosinePhi < 0) && (!horizontalFlip)) { horizontalFlip = true; chemModelRelay.invertStereoInSelection(); } if ((cosinePhi >= 0) && (horizontalFlip)) { horizontalFlip = false; chemModelRelay.invertStereoInSelection(); } if ((cosinePsi < 0) && (!verticalFlip)) { verticalFlip = true; chemModelRelay.invertStereoInSelection(); } if ((cosinePsi >= 0) && (verticalFlip)) { verticalFlip = false; chemModelRelay.invertStereoInSelection(); } } chemModelRelay.updateView(); } public String getDrawModeString() { return "Rotate in space"; } }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/controller/HighlightModule.java
.java
7,041
185
/* $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> * * 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 java.applet.Applet; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import javax.vecmath.Point2d; import org.openscience.cdk.interfaces.IAtom; import org.openscience.cdk.interfaces.IBond; import org.openscience.cdk.interfaces.IChemObject; import org.openscience.jchempaint.applet.JChemPaintAbstractApplet; import org.openscience.jchempaint.renderer.JChemPaintRendererModel; /** * This should highlight the atom/bond when moving over with the mouse * * @author Niels Out * @cdk.svnrev $Revision: 9162 $ * @cdk.module controlbasic */ public class HighlightModule extends ControllerModuleAdapter { public HighlightModule(IChemModelRelay chemObjectRelay, JChemPaintAbstractApplet applet) { super(chemObjectRelay); assert(chemObjectRelay!=null); this.jcpApplet = applet; } private IAtom prevHighlightAtom; private IBond prevHighlightBond; private String ID; private JChemPaintAbstractApplet jcpApplet; private Applet spectrumApplet; int oldnumber=-1; private void update(IChemObject obj, JChemPaintRendererModel model) { if(obj instanceof IAtom) updateAtom((IAtom)obj,model); else if(obj instanceof IBond) updateBond((IBond)obj,model); } private void updateAtom(IAtom atom, JChemPaintRendererModel model) { if (!atom.equals(prevHighlightAtom)) { model.setHighlightedAtom(atom); prevHighlightAtom = atom; prevHighlightBond = null; model.setHighlightedBond(null); try { if(chemModelRelay.getIChemModel().getMoleculeSet()!=null && chemModelRelay.getIChemModel().getMoleculeSet().getAtomContainerCount()>0) highlightPeakInTable(chemModelRelay.getIChemModel().getMoleculeSet().getAtomContainer(0).indexOf(atom)); } catch (Exception e) { e.printStackTrace(); } highlightPeakInSpectrumApplet(atom); chemModelRelay.updateView(); } } private void highlightPeakInSpectrumApplet(IAtom atom) { if(jcpApplet==null || jcpApplet.getParameter("spectrumRenderer")==null) return; try{ Method highlightMethod = getSpectrumApplet().getClass().getMethod("highlightPeakInSpectrum", new Class[] { Integer.TYPE }); highlightMethod.invoke(getSpectrumApplet(), new Object[] { new Integer(chemModelRelay.getIChemModel().getMoleculeSet().getAtomContainer(0).indexOf(atom)) }); spectrumApplet.repaint(); }catch(Exception ex){ ex.printStackTrace(); } } private Applet getSpectrumApplet() { if (spectrumApplet == null) { String s = jcpApplet.getParameter("spectrumRenderer"); if ((s != null) && (s.length() > 0)) { spectrumApplet = jcpApplet.getAppletContext().getApplet(s); } } return spectrumApplet; } private void updateBond(IBond bond, JChemPaintRendererModel model) { if (!bond.equals(prevHighlightBond)) { model.setHighlightedBond(bond); prevHighlightBond = bond; prevHighlightAtom = null; model.setHighlightedAtom(null); chemModelRelay.updateView(); } } private void unsetHighlights(JChemPaintRendererModel model) { if (prevHighlightAtom != null || prevHighlightBond != null) { model.setHighlightedAtom(null); model.setHighlightedBond(null); prevHighlightAtom = null; prevHighlightBond = null; chemModelRelay.updateView(); } } public void mouseMove(Point2d worldCoord) { IAtom atom = chemModelRelay.getClosestAtom(worldCoord); IBond bond = chemModelRelay.getClosestBond(worldCoord); JChemPaintRendererModel model = chemModelRelay.getRenderer().getRenderer2DModel(); IChemObject obj = getHighlighted( worldCoord, atom,bond ); if(obj == null) unsetHighlights( model ); else update(obj,model); } public String getDrawModeString() { return "Highlighting"; } public String getID() { return ID; } public void setID(String ID) { this.ID=ID; } /** * 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(jcpApplet==null || jcpApplet.getParameter("highlightTable")==null) 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[] {jcpApplet}); 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/controller/SwingEventRelay.java
.java
1,589
44
/* $Revision$ $Author$ $Date$ * * Copyright (C) 2007 Niels Out <nielsout@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.swing.JComponent; /** * @cdk.module controlawt */ public class SwingEventRelay implements IViewEventRelay { private JComponent component; public SwingEventRelay(JComponent painter) { component = painter; } public void updateView() { System.out.println("updateView in SwingEventRelay"); component.repaint(); } }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/controller/ReactionHub.java
.java
7,344
132
package org.openscience.jchempaint.controller; import org.openscience.cdk.interfaces.IAtomContainer; import org.openscience.cdk.interfaces.IChemModel; import org.openscience.cdk.interfaces.IReaction; import org.openscience.cdk.interfaces.IReactionSet; import org.openscience.cdk.tools.manipulator.ReactionSetManipulator; import org.openscience.jchempaint.controller.undoredo.IUndoRedoable; import java.util.HashSet; import java.util.Set; public class ReactionHub { public static void makeReactantInNewReaction(ControllerHub controllerhub, IAtomContainer newContainer, IAtomContainer oldcontainer) { IChemModel chemModel = controllerhub.getChemModel(); IReaction reaction = newContainer.getBuilder().newInstance(IReaction.class); reaction.setID(newReactionId(controllerhub)); IAtomContainer mol=newContainer.getBuilder().newInstance(IAtomContainer.class,newContainer); mol.setID(newContainer.getID()); reaction.addReactant(mol); IReactionSet reactionSet = chemModel.getReactionSet(); if (reactionSet == null) { reactionSet = chemModel.getBuilder().newInstance(IReactionSet.class); } reactionSet.addReaction(reaction); chemModel.setReactionSet(reactionSet); chemModel.getMoleculeSet().removeAtomContainer(oldcontainer); if(chemModel.getMoleculeSet().getAtomContainerCount()==0) chemModel.getMoleculeSet().addAtomContainer(chemModel.getBuilder().newInstance(IAtomContainer.class)); if(controllerhub.getUndoRedoFactory()!=null && controllerhub.getUndoRedoHandler()!=null){ IUndoRedoable undoredo = controllerhub.getUndoRedoFactory().getMakeReactantOrProductInNewReactionEdit(chemModel, newContainer, oldcontainer, true, "Make Reactant in new Reaction"); controllerhub.getUndoRedoHandler().postEdit(undoredo); } controllerhub.structureChanged(); } /* (non-Javadoc) * @see org.openscience.cdk.controller.IChemModelRelay#makeReactantInExistingReaction(java.lang.String, org.openscience.cdk.interfaces.IAtomContainer, org.openscience.cdk.interfaces.IAtomContainer) */ public static void makeReactantInExistingReaction(ControllerHub controllerhub, String reactionId, IAtomContainer newContainer, IAtomContainer oldcontainer) { IChemModel chemModel = controllerhub.getChemModel(); IReaction reaction = ReactionSetManipulator.getReactionByReactionID(chemModel.getReactionSet(), reactionId); IAtomContainer mol=newContainer.getBuilder().newInstance(IAtomContainer.class,newContainer); mol.setID(newContainer.getID()); reaction.addReactant(mol); chemModel.getMoleculeSet().removeAtomContainer(oldcontainer); if(chemModel.getMoleculeSet().getAtomContainerCount()==0) chemModel.getMoleculeSet().addAtomContainer(chemModel.getBuilder().newInstance(IAtomContainer.class)); if(controllerhub.getUndoRedoFactory()!=null && controllerhub.getUndoRedoHandler()!=null){ IUndoRedoable undoredo = controllerhub.getUndoRedoFactory().getMakeReactantOrProductInExistingReactionEdit(chemModel, newContainer, oldcontainer, reactionId, true, "Make Reactant in "+reactionId); controllerhub.getUndoRedoHandler().postEdit(undoredo); } controllerhub.structureChanged(); } public static void makeProductInNewReaction(ControllerHub controllerhub, IAtomContainer newContainer, IAtomContainer oldcontainer) { IChemModel chemModel = controllerhub.getChemModel(); IReaction reaction = newContainer.getBuilder().newInstance(IReaction.class); reaction.setID(newReactionId(controllerhub)); IAtomContainer mol=newContainer.getBuilder().newInstance(IAtomContainer.class,newContainer); mol.setID(newContainer.getID()); reaction.addProduct(mol); IReactionSet reactionSet = chemModel.getReactionSet(); if (reactionSet == null) { reactionSet = chemModel.getBuilder().newInstance(IReactionSet.class); } reactionSet.addReaction(reaction); chemModel.setReactionSet(reactionSet); chemModel.getMoleculeSet().removeAtomContainer(oldcontainer); if(chemModel.getMoleculeSet().getAtomContainerCount()==0) chemModel.getMoleculeSet().addAtomContainer(chemModel.getBuilder().newInstance(IAtomContainer.class)); if(controllerhub.getUndoRedoFactory()!=null && controllerhub.getUndoRedoHandler()!=null){ IUndoRedoable undoredo = controllerhub.getUndoRedoFactory().getMakeReactantOrProductInNewReactionEdit(chemModel, newContainer, oldcontainer, false, "Make Reactant in new Reaction"); controllerhub.getUndoRedoHandler().postEdit(undoredo); } controllerhub.structureChanged(); } /* (non-Javadoc) * @see org.openscience.cdk.controller.IChemModelRelay#makeProductInExistingReaction(java.lang.String, org.openscience.cdk.interfaces.IAtomContainer, org.openscience.cdk.interfaces.IAtomContainer) */ public static void makeProductInExistingReaction(ControllerHub controllerhub, String reactionId, IAtomContainer newContainer, IAtomContainer oldcontainer) { IChemModel chemModel = controllerhub.getChemModel(); IReaction reaction = ReactionSetManipulator.getReactionByReactionID(chemModel.getReactionSet(), reactionId); IAtomContainer mol=newContainer.getBuilder().newInstance(IAtomContainer.class,newContainer); mol.setID(newContainer.getID()); reaction.addProduct(mol); chemModel.getMoleculeSet().removeAtomContainer(oldcontainer); if(chemModel.getMoleculeSet().getAtomContainerCount()==0) chemModel.getMoleculeSet().addAtomContainer(chemModel.getBuilder().newInstance(IAtomContainer.class)); if(controllerhub.getUndoRedoFactory()!=null && controllerhub.getUndoRedoHandler()!=null){ IUndoRedoable undoredo = controllerhub.getUndoRedoFactory().getMakeReactantOrProductInExistingReactionEdit(chemModel, newContainer, oldcontainer, reactionId, false, "Make Reactant in "+reactionId); controllerhub.getUndoRedoHandler().postEdit(undoredo); } controllerhub.structureChanged(); } public static String newReactionId(IChemModelRelay hub) { final String name = "untitled reaction"; if (hub.getChemModel().getReactionSet() == null) return name; return newReactionId(hub.getChemModel().getReactionSet(), name); } public static String newReactionId(IReactionSet reactionSet, String startName) { final Set<String> ids = currentIds(reactionSet); if (!ids.contains(startName)) return startName; for (int i = 2; i < reactionSet.getReactionCount() + 1; i++) { String potentialName = startName + " (" + i + ")"; if (!ids.contains(potentialName)) return potentialName; } return "reaction-" + System.currentTimeMillis(); } public static Set<String> currentIds(IReactionSet reactionSet) { Set<String> ids = new HashSet<String>(); for (IReaction reaction : reactionSet.reactions()) { ids.add(reaction.getID()); } return ids; } }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/controller/ControllerParameters.java
.java
5,185
190
/* $Revision$ $Author$ $Date$ * * Copyright (C) 2008 Gilleain Torrance <gilleain.torrance@gmail.com> * * Contact: cdk-devel@list.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 org.openscience.cdk.interfaces.IBond; /** * @cdk.module controlbasic */ public class ControllerParameters { private String drawElement = "C"; private boolean drawPseudoAtom=false; private int drawIsotope = 0; private String[] commonElements = { "C", "O", "N", "P", "S", "Br", "Cl", "F", "I" }; private boolean snapToGridAngle = true; private int snapAngle = 15; private boolean snapToGridCartesian = true; private int snapCartesian = 10; private double bondPointerLength = 20; private double ringPointerLength = 20; private boolean autoUpdateImplicitHydrogens = true; private String defaultElementSymbol = "C"; private IBond.Order maxOrder = IBond.Order.QUADRUPLE; private boolean hightlighLastSelected = false; public IBond.Order getMaxOrder() { return this.maxOrder; } public void setMaxOrder(IBond.Order maxOrder) { this.maxOrder = maxOrder; } // for controlling, if the structure or substructural parts might be moved private boolean isMovingAllowed = true; public boolean isMovingAllowed() { return isMovingAllowed; } public void setMovingAllowed(boolean isMovingAllowed) { this.isMovingAllowed = isMovingAllowed; } public boolean isSnapToGridAngle() { return snapToGridAngle; } public void setSnapToGridAngle(boolean snapToGridAngle) { this.snapToGridAngle = snapToGridAngle; } public int getSnapAngle() { return snapAngle; } public void setSnapAngle(int snapAngle) { this.snapAngle = snapAngle; } public boolean isSnapToGridCartesian() { return snapToGridCartesian; } public void setSnapToGridCartesian(boolean snapToGridCartesian) { this.snapToGridCartesian = snapToGridCartesian; } public int getSnapCartesian() { return snapCartesian; } public void setSnapCartesian(int snapCartesian) { this.snapCartesian = snapCartesian; } public double getBondPointerLength() { return bondPointerLength; } public void setBondPointerLength(double bondPointerLength) { this.bondPointerLength = bondPointerLength; } public double getRingPointerLength() { return ringPointerLength; } public void setRingPointerLength(double ringPointerLength) { this.ringPointerLength = ringPointerLength; } public boolean isAutoUpdateImplicitHydrogens() { return autoUpdateImplicitHydrogens; } public void setAutoUpdateImplicitHydrogens(boolean autoUpdateImplicitHydrogens) { this.autoUpdateImplicitHydrogens = autoUpdateImplicitHydrogens; } public String getDefaultElementSymbol() { return defaultElementSymbol; } public void setDefaultElementSymbol(String defaultElementSymbol) { this.defaultElementSymbol = defaultElementSymbol; } public String getDrawElement() { return drawElement; } public void setDrawElement(String drawElement) { this.drawElement = drawElement; } public void setDrawPseudoAtom(boolean drawPseudoAtom){ this.drawPseudoAtom=drawPseudoAtom; } public boolean getDrawPseudoAtom(){ return drawPseudoAtom; } public String[] getCommonElements() { return commonElements; } public void setCommonElements(String[] commonElements) { this.commonElements = commonElements; } public int getDrawIsotope() { return drawIsotope; } public void setDrawIsotope(int isotope) { this.drawIsotope = isotope; } /** * @return Tells if after a structure change the affected part should be selected. */ public boolean isHightlighLastSelected() { return hightlighLastSelected; } /** * Determines if after a structure change the affected part should be selected. * * @param hightlighLastSelected True=will be selected, false=will not be selected. */ public void setHightlighLastSelected(boolean hightlighLastSelected) { this.hightlighLastSelected = hightlighLastSelected; } }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/controller/SwingMouseEventRelay.java
.java
4,312
123
/* $Revision$ $Author$ $Date$ * * Copyright (C) 2007 Niels Out <nielsout@users.sf.net> * * Contact: cdk-devel@lists.sourceforge.net or nout@science.uva.nl * * 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 java.awt.event.InputEvent; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import java.awt.event.MouseWheelEvent; import java.awt.event.MouseWheelListener; /** * @cdk.module controlbasic */ public class SwingMouseEventRelay implements MouseMotionListener, MouseListener, MouseWheelListener { private IMouseEventRelay relay; /** Position of mouse press for dragging. */ private int dragFromX = 0; private int dragFromY = 0; /** true means mouse was pressed in ball and still in panel. */ private boolean _canDrag = false; private boolean isPopupTrigger=false; public SwingMouseEventRelay(IMouseEventRelay relay) { this.relay = relay; } public void mouseMoved(MouseEvent event) { relay.mouseMove(event.getX(), event.getY()); } public void updateView() { System.out.println("updating View now in SwingMouseEventRelay"); } public void mouseDragged(MouseEvent event) { // check // http://www.leepoint.net/notes-java/examples/mouse/020dragdemo.html // for implementation relay.mouseDrag(dragFromX, dragFromY, event.getX(), event.getY(), event.getModifiersEx()); dragFromX = event.getX(); dragFromY = event.getY(); } public void mouseClicked(MouseEvent event) { // normal mouseClicked is the same as mousePressed and mouseReleased // after that // Double click is a special case if (event.getClickCount() > 1) relay.mouseClickedDouble(event.getX(), event.getY()); } public void mouseEntered(MouseEvent event) { relay.mouseEnter(event.getX(), event.getY()); } public void mouseExited(MouseEvent event) { relay.mouseExit(event.getX(), event.getY()); } public void mousePressed(MouseEvent event) { String osType= System.getProperty("os.name"); if (event.isPopupTrigger() || (osType.indexOf("Windows")>-1 && event.getButton()==MouseEvent.BUTTON3)) { relay.mouseClickedDownRight(event.getX(), event.getY()); isPopupTrigger = true; } else { relay.mouseClickedDown(event.getX(), event.getY(), event.getModifiersEx()); isPopupTrigger = false; } dragFromX = event.getX(); dragFromY = event.getY(); } public void mouseReleased(MouseEvent event) { if (isPopupTrigger){ relay.mouseClickedUpRight(event.getX(), event.getY()); isPopupTrigger=false; } else { relay.mouseClickedUp(event.getX(), event.getY(), event.getModifiersEx()); } } public void mouseWheelMoved(MouseWheelEvent e) { int rotation = e.getWheelRotation(); int modifiers = e.getModifiersEx(); if (rotation > 0) { relay.mouseWheelMovedForward(modifiers, e.getClickCount()); } else if (rotation < 0) { relay.mouseWheelMovedBackward(modifiers, e.getClickCount()); } } }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/controller/Changed.java
.java
1,387
38
/* * 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; /** * Defines different changes that an <code>IEdit</code> can do. * @author Arvid * @cdk.module control */ public enum Changed { Structure, Properties, Coordinates, Selection, Zoom }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/controller/PhantomBondGenerator.java
.java
2,505
68
/* $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 java.awt.Color; import org.openscience.cdk.interfaces.IAtomContainer; import org.openscience.cdk.interfaces.IBond; import org.openscience.cdk.renderer.RendererModel; import org.openscience.jchempaint.renderer.JChemPaintRendererModel; import org.openscience.cdk.renderer.elements.ElementGroup; import org.openscience.cdk.renderer.elements.IRenderingElement; import org.openscience.cdk.renderer.generators.BasicBondGenerator; /** * Draws the phantoms in ControllerHub * * @cdk.module controlbasic */ public class PhantomBondGenerator extends BasicBondGenerator { ControllerHub hub; public PhantomBondGenerator() { } 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(); for(IBond bond:hub.getPhantoms().bonds()) { this.setOverrideColor(Color.GRAY); IRenderingElement element = generateBond( bond, jcpModel); group.add(element); } return group; } }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/controller/AbstractSelectModule.java
.java
14,480
333
/* $Revision$ $Author$ $Date$ * * Copyright (C) 2008 Gilleain Torrance <gilleain.torrance@gmail.com> * * Contact: cdk-devel@list.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 java.awt.*; import java.awt.event.MouseEvent; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.util.HashSet; import java.util.Set; import javax.vecmath.Point2d; import org.openscience.cdk.interfaces.IAtom; import org.openscience.cdk.interfaces.IBond; import org.openscience.cdk.interfaces.IChemObject; import org.openscience.cdk.renderer.elements.RectangleElement; import org.openscience.cdk.renderer.selection.AbstractSelection; import org.openscience.jchempaint.renderer.BoundsCalculator; import org.openscience.jchempaint.renderer.JChemPaintRendererModel; import org.openscience.cdk.renderer.selection.IChemObjectSelection; import org.openscience.jchempaint.renderer.selection.LogicalSelection; import org.openscience.jchempaint.renderer.selection.ShapeSelection; import org.openscience.jchempaint.renderer.selection.SingleSelection; /** * An abstract base class for select modules. Classes extending this must * implement getDrawModeString and set selection to the appropriate type in * their constructor. * * @cdk.module controlbasic */ public abstract class AbstractSelectModule extends ControllerModuleAdapter { protected ShapeSelection selection; private Point2d startPoint; private boolean init; // ensure initialization only happens once private IChemObjectSelection currentSelection; private String ID; public AbstractSelectModule(IChemModelRelay chemModelRelay) { super(chemModelRelay); } private IAtom getClosestSelAtom(Point2d worldCoord) { IAtom closestAtom = null; IChemObjectSelection sel = chemModelRelay.getRenderer().getRenderer2DModel().getSelection(); double closestDistanceSQ = Double.MAX_VALUE; for (IAtom atom : sel.elements(IAtom.class)) { if (atom.getPoint2d() != null) { double distanceSQ = atom.getPoint2d().distanceSquared( worldCoord); if (distanceSQ < closestDistanceSQ) { closestAtom = atom; closestDistanceSQ = distanceSQ; } } } return closestAtom; } private IBond getClosestSelBond(Point2d worldCoord) { IBond closestBond = null; IChemObjectSelection sel = chemModelRelay.getRenderer().getRenderer2DModel().getSelection(); double closestDistanceSQ = Double.MAX_VALUE; for (IBond bond : sel.elements(IBond.class)) { if (bond.get2DCenter() != null) { double distanceSQ = bond.get2DCenter().distanceSquared( worldCoord); if (distanceSQ < closestDistanceSQ) { closestBond = bond; closestDistanceSQ = distanceSQ; } } } return closestBond; } public void mouseDrag(Point2d from, Point2d to, int modifiers) { boolean shiftPressed = (modifiers & MouseEvent.SHIFT_DOWN_MASK) != 0; Rectangle2D bounds = null; boolean inSelectionCircle = false; JChemPaintRendererModel model = chemModelRelay.getRenderer().getRenderer2DModel(); IChemObjectSelection sel = model.getSelection(); if (sel == null) return; double d = model.getSelectionRadius() / model.getScale(); IAtom closestAtom = null; IBond closestBond = null; // start of the drag if (init && from.equals(startPoint)) { init = false; LogicalSelection lsel = null; boolean isAllSelected = false; if (sel.getClass().isAssignableFrom(LogicalSelection.class)) { lsel = (LogicalSelection) sel; isAllSelected = lsel.getType() == LogicalSelection.Type.ALL && sel.isFilled(); } if (!isAllSelected && sel != null && sel.isFilled()) { bounds = BoundsCalculator.calculateBounds(sel.getConnectedAtomContainer()); closestAtom = getClosestSelAtom(startPoint); closestBond = getClosestSelBond(startPoint); } inSelectionCircle = (closestAtom != null && closestAtom.getPoint2d().distance(startPoint) < 4 * d) || (closestBond != null && closestBond.get2DCenter().distance(startPoint) < 4 * d); //in case the user either starts dragging inside the current selection //rectangle or in a selection circle, we switch to move mode, //else we start a new selection if ((inSelectionCircle || isAllSelected || (bounds != null && bounds.contains(new Point2D.Double(startPoint.x, startPoint.y))))) { IControllerModule newActiveModule = new MoveModule(this.chemModelRelay, this); newActiveModule.setID("move"); chemModelRelay.setActiveDrawModule(newActiveModule); Point2d sf = chemModelRelay.getRenderer().toScreenCoordinates(startPoint.x, startPoint.y); ((IMouseEventRelay) this.chemModelRelay).mouseClickedDown((int) sf.x, (int) sf.y); Point2d st = chemModelRelay.getRenderer().toScreenCoordinates(to.x, to.y); ((IMouseEventRelay) this.chemModelRelay).mouseDrag((int) sf.x, (int) sf.y, (int) st.x, (int) st.y, modifiers); return; } } this.selection.addPoint(to); this.selection.select(chemModelRelay.getIChemModel()); if (shiftPressed) this.selection.difference(currentSelection); this.chemModelRelay.select((IChemObjectSelection) selection); this.chemModelRelay.updateView(); } public void mouseMove(Point2d p) { showMouseCursor(p, this.chemModelRelay); } public static void showMouseCursor(Point2d p, IChemModelRelay chemModelRelay) { IChemModelRelay.CursorType cursor = getSelectionControlType(p, chemModelRelay); if (cursor != IChemModelRelay.CursorType.DEFAULT) { chemModelRelay.setCursor(cursor); return; } //We look if we the user would move when clicking and show arrows then Rectangle2D bounds = null; if (chemModelRelay.getRenderer().getRenderer2DModel().getSelection() != null && chemModelRelay.getRenderer().getRenderer2DModel() .getSelection().isFilled()) try { bounds = BoundsCalculator.calculateBounds(chemModelRelay .getRenderer().getRenderer2DModel().getSelection() .getConnectedAtomContainer()); } catch (NullPointerException e) { bounds = null; } IChemObject highlightedAtom = chemModelRelay.getRenderer().getRenderer2DModel().getHighlightedAtom(); IChemObject highlightedBond = chemModelRelay.getRenderer().getRenderer2DModel().getHighlightedBond(); if ((bounds != null && bounds.contains(new Point2D.Double(p.x, p.y))) || highlightedAtom != null || highlightedBond != null) { chemModelRelay.setCursor(Cursor.HAND_CURSOR); } else { chemModelRelay.setCursor(Cursor.DEFAULT_CURSOR); } } @Override public void mouseClickedDown(Point2d p, int modifiers) { if (getSelectionControlType(p, chemModelRelay) != IChemModelRelay.CursorType.DEFAULT) { IControllerModule newActiveModule = new MoveModule(this.chemModelRelay, this); newActiveModule.setID("Move"); chemModelRelay.setActiveDrawModule(newActiveModule); Point2d sf = chemModelRelay.getRenderer().toScreenCoordinates(p.x, p.y); ((IMouseEventRelay) this.chemModelRelay).mouseClickedDown((int) sf.x, (int) sf.y, modifiers); return; } init = true; startPoint = p; IChemObjectSelection chemObjSelection = chemModelRelay.getRenderer().getRenderer2DModel().getSelection(); currentSelection = chemObjSelection != null ? new LogicalSelection(chemObjSelection) : null; } protected static IChemModelRelay.CursorType getSelectionControlType(Point2d p, IChemModelRelay relay) { JChemPaintRendererModel jcpModel = relay.getRenderer().getRenderer2DModel(); RectangleElement rect = jcpModel.getSelectionBounds(); if (rect == null) return IChemModelRelay.CursorType.DEFAULT; if (rect.width <= 0.001 || rect.height >= -0.001 || jcpModel.getSelection().elements(IAtom.class).size() == 1) return IChemModelRelay.CursorType.DEFAULT; double hgDist = (jcpModel.getHighlightDistance() / jcpModel.getScale() / jcpModel.getZoomFactor()); Point2d rotateControl = jcpModel.getSelectionRotateControl(); if (rotateControl != null && rotateControl.distance(p) <= hgDist) return IChemModelRelay.CursorType.ROTATE; // do the point testing towards the outside of the rect, basically we // expand by half the highlight distance, this allows single bonds to // still be controlled rect = new RectangleElement(rect.xCoord - hgDist / 2, rect.yCoord + hgDist / 2, rect.width + hgDist, rect.height - hgDist, false, rect.color); Point2d nw = new Point2d(rect.xCoord, rect.yCoord); Point2d ne = new Point2d(rect.xCoord + rect.width, rect.yCoord); Point2d sw = new Point2d(rect.xCoord, rect.yCoord + rect.height); Point2d se = new Point2d(rect.xCoord + rect.width, rect.yCoord + rect.height); if (p.distance(sw) <= hgDist) return IChemModelRelay.CursorType.RESIZE_SW; if (p.distance(se) <= hgDist) return IChemModelRelay.CursorType.RESIZE_SE; if (p.distance(ne) <= hgDist) return IChemModelRelay.CursorType.RESIZE_NE; if (p.distance(nw) <= hgDist) return IChemModelRelay.CursorType.RESIZE_NW; Point2d n = new Point2d(rect.xCoord + (rect.width / 2), rect.yCoord); Point2d e = new Point2d(rect.xCoord + rect.width, rect.yCoord + (rect.height / 2)); Point2d s = new Point2d(rect.xCoord + (rect.width / 2), rect.yCoord + rect.height); Point2d w = new Point2d(rect.xCoord, rect.yCoord + (rect.height / 2)); if (p.distance(n) <= hgDist) return IChemModelRelay.CursorType.RESIZE_N; if (p.distance(e) <= hgDist) return IChemModelRelay.CursorType.RESIZE_E; if (p.distance(s) <= hgDist) return IChemModelRelay.CursorType.RESIZE_S; if (p.distance(w) <= hgDist) return IChemModelRelay.CursorType.RESIZE_W; return IChemModelRelay.CursorType.DEFAULT; } @Override public void mouseClickedUp(Point2d p, int modifiers) { boolean shiftPressed = (modifiers & MouseEvent.SHIFT_DOWN_MASK) != 0; if (p.equals(startPoint)) { // there was no mouse drag so we need to do the selection logic here IAtom closestAtom = chemModelRelay.getClosestAtom(p); IBond closestBond = chemModelRelay.getClosestBond(p); IChemObject singleSelection = getHighlighted(p, closestAtom, closestBond); IChemObjectSelection currentSelection = chemModelRelay.getRenderer().getRenderer2DModel().getSelection(); IChemObjectSelection sel = null; if (shiftPressed && currentSelection != null && currentSelection.isFilled()) { Set<IChemObject> chemObjSet = new HashSet<>(currentSelection.elements(IChemObject.class)); if (!chemObjSet.contains(singleSelection)) chemObjSet.add(singleSelection); else chemObjSet.remove(singleSelection); LogicalSelection logSel = new LogicalSelection(LogicalSelection.Type.ALL); logSel.select(chemObjSet); sel = logSel; } else { if (singleSelection == null) { selection.clear(); sel = AbstractSelection.EMPTY_SELECTION; } else if (singleSelection instanceof IAtom) { sel = new SingleSelection<>((IAtom) singleSelection); } else if (singleSelection instanceof IBond) { sel = new SingleSelection<>((IBond) singleSelection); } } this.chemModelRelay.select(sel); } else { this.selection.select(chemModelRelay.getIChemModel()); if (shiftPressed) this.selection.difference(currentSelection); this.chemModelRelay.select((IChemObjectSelection) selection); selection.reset(); } this.chemModelRelay.updateView(); } public String getID() { return ID; } public void setID(String ID) { this.ID = ID; } @Override protected void setSelection(IChemObjectSelection selection) { super.setSelection(selection); startPoint = null; init = false; } }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/controller/IControllerModel.java
.java
5,268
199
/* $Revision: 10179 $ $Author: egonw $ $Date: 2008-02-18 17:05:56 +0100 (Mon, 18 Feb 2008) $ * * Copyright (C) 2008 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 org.openscience.cdk.interfaces.IBond; /** * @cdk.module control */ public interface IControllerModel { public abstract IBond.Order getMaxOrder(); public abstract void setMaxOrder(IBond.Order maxOrder); /** * Returns the snapToGridAngle mode * * @return the snapToGridAngle mode */ public abstract boolean getSnapToGridAngle(); /** * Returns true if the number of implicit hydrogens is updated * when an Atom is edited. */ public abstract boolean getAutoUpdateImplicitHydrogens(); /** * Sets whether the number of implicit hydrogens is update when an * Atom is edited. */ public abstract void setAutoUpdateImplicitHydrogens(boolean update); /** * Sets the snapToGridAngle mode * * @param snapToGridAngle */ public abstract void setSnapToGridAngle(boolean snapToGridAngle); /** * Returns the snapAngle mode * * @return the snapAngle mode */ public abstract int getSnapAngle(); /** * Sets the snapAngle mode * * @param snapAngle */ public abstract void setSnapAngle(int snapAngle); /** * Returns the snapToGridCartesian mode * * @return the snapToGridCartesian mode */ public abstract boolean getSnapToGridCartesian(); /** * Sets the snapToGridCartesian mode * * @param snapToGridCartesian */ public abstract void setSnapToGridCartesian(boolean snapToGridCartesian); /** * Returns the snapCartesian value * * @return the snapCartesian value */ public abstract int getSnapCartesian(); /** * Sets the snapCartesian value * * @param snapCartesian */ public abstract void setSnapCartesian(int snapCartesian); public abstract String getDefaultElementSymbol(); /** * Sets the default element symbol * * @param defaultElementSymbol */ public abstract void setDefaultElementSymbol(String defaultElementSymbol); /** * Returns the bond pointer length * * @return the length */ public abstract double getBondPointerLength(); /** * Sets the pointer length * * @param bondPointerLength */ public abstract void setBondPointerLength(double bondPointerLength); /** * Returns the ring pointer length * * @return the length */ public abstract double getRingPointerLength(); /** * Sets the pointer length * * @param ringPointerLength */ public abstract void setRingPointerLength(double ringPointerLength); public abstract void setCommonElements(String[] elements); public abstract String[] getCommonElements(); public abstract void setDrawElement(String element); /** * Sets the isotope number which new atoms will get by default. * 0 means new elements will be created with major isotope. * * @param isotope The isotope number */ public abstract void setDrawIsotopeNumber(int isotope); /** * Sets if newly created atoms are supposed to become pseudo atoms or not. * * @param drawPseudoAtom true=new atoms will be pseudo atoms, false=they will * be regular atoms. */ public void setDrawPseudoAtom(boolean drawPseudoAtom); /** * Tells if newly created atoms are supposed to become pseudo atoms or not. * * @return true=new atoms will be pseudo atoms, false=they will * be regular atoms. */ public boolean getDrawPseudoAtom(); /** * Element symbol that <b>new</b> atoms get by default. */ public abstract String getDrawElement(); /** * Isotope number that <b>new</b> atoms get by default. */ public abstract int getDrawIsotopeNumber(); /** * To retrieve the value of the isMovingAllowed flag * @return boolean isMovingAllowed */ public abstract boolean isMovingAllowed(); /** * Lets you set the siMovingAllowed flag * @param isMovingAllowed */ public abstract void setMovingAllowed(boolean isMovingAllowed); public boolean isHightlighLastSelected(); public void setHightlighLastSelected(boolean hightlighLastSelected); }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/controller/AddAtomModule.java
.java
11,514
262
/* $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) 2009 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.config.Elements; 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.jchempaint.AtomBondSet; import org.openscience.jchempaint.controller.IChemModelRelay.Direction; import org.openscience.jchempaint.controller.undoredo.IUndoRedoFactory; 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.selection.SingleSelection; import org.openscience.jchempaint.GT; import java.util.concurrent.TimeUnit; /** * Adds an atom on the given location on mouseclick * * @author Niels Out * @cdk.svnrev $Revision: 9162 $ * @cdk.module controlbasic */ public class AddAtomModule extends ControllerModuleAdapter { Point2d start; Point2d dest; IAtom source = null;// either atom at mouse down or new atom IAtom merge = null; boolean newSource = false; private String ID; boolean isBond = false; private double bondLength; private IBond.Display displayForNewBond; long drawTime = 0; public AddAtomModule(IChemModelRelay chemModelRelay, IBond.Display stereoForNewBond) { super(chemModelRelay); this.displayForNewBond = stereoForNewBond; } public void mouseClickedDown(Point2d worldCoord, int modifiers) { start = null; dest = null; source = null; merge = null; isBond = false; newSource = false; bondLength = Renderer.calculateBondLength(chemModelRelay.getIChemModel()); // in case we are starting on an empty canvas if(bondLength==0 || Double.isNaN(bondLength)) bondLength=1.5; start = new Point2d(worldCoord); IAtom closestAtom = chemModelRelay.getClosestAtom(worldCoord); IBond closestBond = chemModelRelay.getClosestBond( worldCoord ); IChemObject singleSelection = getHighlighted( worldCoord, closestAtom, closestBond ); if(singleSelection == null || singleSelection instanceof IAtom ) { isBond = false; source = (IAtom) getHighlighted(worldCoord, closestAtom); if(source == null) { String symbol = chemModelRelay.getController2DModel().getDrawElement(); if (Elements.ofString(symbol) != Elements.Unknown) source = chemModelRelay.getIChemModel().getBuilder().newInstance(IAtom.class, symbol, start); else source = chemModelRelay.getIChemModel().getBuilder().newInstance(IPseudoAtom.class, symbol, start); if(chemModelRelay.getController2DModel().getDrawIsotopeNumber()!=0) source.setMassNumber(chemModelRelay.getController2DModel().getDrawIsotopeNumber()); newSource = true; } } else if (singleSelection instanceof IBond) { if (displayForNewBond == IBond.Display.Solid) { chemModelRelay.cycleBondValence((IBond) singleSelection); } else { IChemModelRelay.Direction direction = Direction.DOWN; if (displayForNewBond == IBond.Display.Up) direction = Direction.UP; else if (displayForNewBond == IBond.Display.Wavy) direction = Direction.UNDEFINED; else if (displayForNewBond == IBond.Display.Crossed) direction = Direction.EZ_UNDEFINED; chemModelRelay.makeBondStereo((IBond) singleSelection, direction); } setSelection(new SingleSelection<IChemObject>(singleSelection)); isBond = true; } } @Override public void mouseMove(Point2d worldCoord) { if ((System.nanoTime() - drawTime) < TimeUnit.MILLISECONDS.toNanos(5)) { return; } chemModelRelay.clearPhantoms(); IAtom atom = chemModelRelay.getChemModel().getBuilder().newAtom(); atom.setSymbol(chemModelRelay.getController2DModel().getDrawElement()); atom.setMassNumber(chemModelRelay.getController2DModel().getDrawIsotopeNumber()); atom.setPoint2d(new Point2d(worldCoord)); chemModelRelay.addPhantomAtom(atom); chemModelRelay.updateView(); drawTime = System.nanoTime(); } public void mouseDrag(Point2d worldCoordFrom, Point2d worldCoordTo, int modifiers) { if(isBond) return; IAtom closestAtom = chemModelRelay.getClosestAtom(worldCoordTo); merge = (IAtom) getHighlighted(worldCoordTo, closestAtom); chemModelRelay.clearPhantoms(); if (start == null || start.distance(worldCoordTo) < getHighlightDistance()) { // clear phantom merge = null; dest = null; }else if (merge != null) { // set bond chemModelRelay.addPhantomBond( chemModelRelay.getIChemModel() .getBuilder().newInstance(IBond.class,source,merge) ); dest = null; }else { dest = AddBondDragModule.roundAngle(start, worldCoordTo, bondLength ); IAtom atom; String symbol = chemModelRelay.getController2DModel().getDrawElement(); if (Elements.ofString(symbol) != Elements.Unknown) atom = chemModelRelay.getIChemModel().getBuilder().newInstance(IAtom.class, symbol, dest); else atom = chemModelRelay.getIChemModel().getBuilder().newInstance(IPseudoAtom.class, symbol, dest); IBond bond = chemModelRelay.getIChemModel().getBuilder(). newInstance(IBond.class, source, atom, IBond.Order.SINGLE, displayForNewBond); chemModelRelay.addPhantomAtom( source ); chemModelRelay.addPhantomAtom( atom ); chemModelRelay.addPhantomBond( bond ); // update phantom } chemModelRelay.updateView(); } public void mouseClickedUp(Point2d worldCoord, int modifiers){ chemModelRelay.clearPhantoms(); if(isBond) return; //There are four cases we handle //-Clicked on an existing atom and not dragged more than highligt distance: // Change element //-Clicked on an existing atom and dragged more than hightligh distance: // Make a bond of DrawBondType from the atom to a new atom of DrawElement //-Clicked in empty and not dragged more than highligt distance: // Make new atom //-Clicked in empty and dragged more than hightligh distance: // Make a bond of DrawBondType with two new atoms of DrawElement IAtom closestAtom = chemModelRelay.getClosestAtom(worldCoord); JChemPaintRendererModel model = chemModelRelay.getRenderer().getRenderer2DModel(); double dH = model.getHighlightDistance() / model.getScale(); IAtom newAtom; if(newSource){ newAtom = chemModelRelay.addAtom( chemModelRelay.getController2DModel().getDrawElement(), chemModelRelay.getController2DModel().getDrawIsotopeNumber(), start, chemModelRelay.getController2DModel().getDrawPseudoAtom() ); }else{ newAtom = source; } if(start.distance(worldCoord)>dH){ if(dest==null) dest=worldCoord; IAtom atom = chemModelRelay.addAtom( chemModelRelay.getController2DModel().getDrawElement(), chemModelRelay.getController2DModel().getDrawIsotopeNumber(), dest, chemModelRelay.getController2DModel().getDrawPseudoAtom() ); if(chemModelRelay.getController2DModel().getDrawIsotopeNumber()!=0) atom.setMassNumber(chemModelRelay.getController2DModel().getDrawIsotopeNumber()); IUndoRedoFactory factory = chemModelRelay.getUndoRedoFactory(); UndoRedoHandler handler = chemModelRelay.getUndoRedoHandler(); AtomBondSet containerForUndoRedo = new AtomBondSet(); IBond bond = chemModelRelay.addBond(newAtom, atom, displayForNewBond); containerForUndoRedo.add(bond); if (factory != null && handler != null) { IUndoRedoable undoredo = chemModelRelay.getUndoRedoFactory().getAddAtomsAndBondsEdit (chemModelRelay.getIChemModel(), containerForUndoRedo, null, "Add Bond",chemModelRelay); handler.postEdit(undoredo); } }else{ if(!newSource){ if(chemModelRelay.getController2DModel().getDrawPseudoAtom()){ chemModelRelay.convertToPseudoAtom(closestAtom, chemModelRelay.getController2DModel().getDrawElement()); }else{ chemModelRelay.setSymbol(closestAtom, chemModelRelay.getController2DModel().getDrawElement()); if(chemModelRelay.getController2DModel().getDrawIsotopeNumber()!=0) chemModelRelay.setMassNumber(closestAtom, chemModelRelay.getController2DModel().getDrawIsotopeNumber()); } } } chemModelRelay.updateView(); } public void setChemModelRelay(IChemModelRelay relay) { this.chemModelRelay = relay; } public String getDrawModeString() { return GT.get("Add Atom Or Change Element") +" ("+ (chemModelRelay.getController2DModel().getDrawIsotopeNumber()==0 ? "" : chemModelRelay.getController2DModel().getDrawIsotopeNumber())+ chemModelRelay.getController2DModel().getDrawElement()+")"; } public String getID() { return ID; } public void setID(String ID) { this.ID=ID; } /** * Tells which stereo info new bonds will get. * * @return The stereo which new bonds will have. */ public IBond.Display getStereoForNewBond() { return displayForNewBond; } }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/controller/RemoveModule.java
.java
2,522
78
/* $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) 2009 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.cdk.interfaces.IBond; import org.openscience.cdk.renderer.selection.AbstractSelection; import org.openscience.jchempaint.AtomBondSet; /** * Deletes closest atom on click * * @author Niels Out * @cdk.svnrev $Revision: 9162 $ * @cdk.module controlbasic */ public class RemoveModule extends ControllerModuleAdapter { private String ID; public RemoveModule(IChemModelRelay chemObjectRelay) { super(chemObjectRelay); } public void mouseClickedDown(Point2d worldCoordinate, int modifiers) { AtomBondSet selectedAC = getSelectAtomBondSet(worldCoordinate); if(selectedAC == null) return; for(IAtom atom:selectedAC.atoms()) { chemModelRelay.removeAtom(atom); } for(IBond bond:selectedAC.bonds()) { chemModelRelay.removeBondAndLoneAtoms( bond ); } setSelection( AbstractSelection.EMPTY_SELECTION ); } public String getDrawModeString() { return "Delete"; } public String getID() { return ID; } public void setID(String ID) { this.ID=ID; } }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/controller/IControllerModule.java
.java
3,371
134
/* $Revision: 7636 $ $Author: egonw $ $Date: 2007-01-04 18:46:10 +0100 (Thu, 04 Jan 2007) $ * * Copyright (C) 2007 Egon Willighagen <egonw@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; /** * Interface that Controller2D modules must implement. Each module is * associated with an editing mode (DRAWMODE_*), as given in * Controller2DModel. * * @author egonw * @cdk.svnrev $Revision: 9162 $ * @cdk.module control * * @see ControllerModel */ public interface IControllerModule { void setChemModelRelay(IChemModelRelay relay); void mouseWheelMovedBackward(int modifiers, int clicks); void mouseWheelMovedForward(int modifiers, int clicks); /** * @param Point2d worldCoord */ void mouseClickedUp(Point2d worldCoord); public void mouseClickedUp(Point2d worldCoord, int modifies); public void mouseClickedDown(Point2d worldCoord, int modifies); /** * @param Point2d worldCoord */ void mouseClickedDown(Point2d worldCoord); /** * @param Point2d worldCoord */ void mouseClickedUpRight(Point2d worldCoord); /** * @param Point2d worldCoord */ void mouseClickedDownRight(Point2d worldCoord); /** * @param Point2d worldCoord */ void mouseClickedDouble(Point2d worldCoord); /** * @param Point2d worldCoord */ void mouseMove(Point2d worldCoord); /** * @param Point2d worldCoord */ void mouseEnter(Point2d worldCoord); /** * @param Point2d worldCoord */ void mouseExit(Point2d worldCoord); /** * @param Point2d worldCoordFrom * @param Point2d worldCoordTo */ void mouseDrag(Point2d worldCoordFrom, Point2d worldCoordTo); void mouseDrag(Point2d worldCoordFrom, Point2d worldCoordTo, int modifiers); /** * @return A string describing this module e. g. for the status bar */ String getDrawModeString(); /** * @return Returns the ID attribute */ String getID(); /** * Sets the ID attribute * * @param ID The ID attribute */ void setID(String ID); /** * Set wasEscaped flag to true */ void escapeTheMode(); /** * Returns wasEscaped attribute */ boolean wasEscaped(); /** * Update the module view, this is useful if alt mode is turned on/off * and we want to change what the phantom atoms are doing. */ void updateView(); }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/controller/ChangeValenceModule.java
.java
3,482
104
/* $Revision: 7636 $ $Author: nielsout $ $Date: 2007-01-04 18:46:10 +0100 (Thu, 04 Jan 2007) $ * * Copyright (C) 2009 Stefan Kuhn (undo redo) * * 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 java.util.HashSet; import java.util.Set; import javax.vecmath.Point2d; import org.openscience.cdk.interfaces.IAtom; import org.openscience.jchempaint.AtomBondSet; import org.openscience.jchempaint.renderer.selection.MultiSelection; /** * Changes valence of atoms. * * @author Niels Out * @cdk.svnrev $Revision: 9162 $ * @cdk.module controlbasic */ public class ChangeValenceModule extends ControllerModuleAdapter { private int valence = 0; private String ID; /** * Constructor for the ChangeValenceModule. * * @param chemModelRelay The current implmentation of IChemModelRelay. * @param valence The valence to set */ public ChangeValenceModule(IChemModelRelay chemModelRelay, int valence) { super(chemModelRelay); this.valence = valence; } /* (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; Set<IAtom> newSelection = new HashSet<IAtom>(); for(IAtom atom:selectedAC.atoms()) { newSelection.add( atom ); chemModelRelay.setValence(atom, valence==-1 ? null : valence); } setSelection( new MultiSelection<IAtom>(newSelection) ); chemModelRelay.updateView();// FIXME do you really need to call it here? } /* (non-Javadoc) * @see org.openscience.cdk.controller.ControllerModuleAdapter#setChemModelRelay(org.openscience.cdk.controller.IChemModelRelay) */ public void setChemModelRelay(IChemModelRelay relay) { this.chemModelRelay = relay; } /* (non-Javadoc) * @see org.openscience.cdk.controller.IControllerModule#getDrawModeString() */ public String getDrawModeString() { return "Valence "+valence; } /* (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/ChainModule.java
.java
9,458
221
/* * Copyright (C) 2010 Conni Wagner <conni75@users.sourceforge.net> * 2012 Ralf Stephan <ralf@ark.in-berlin.de> * * 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.config.Elements; 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.IChemObjectBuilder; import org.openscience.cdk.tools.manipulator.ChemModelManipulator; import org.openscience.jchempaint.AtomBondSet; import org.openscience.jchempaint.renderer.JChemPaintRendererModel; import org.openscience.jchempaint.renderer.Renderer; import javax.vecmath.Point2d; /** * Adds a bond at direction that is dragged. * */ public class ChainModule extends ControllerModuleAdapter { Point2d start; Point2d dest; IAtom source = null;// either atom at mouse down or new atom IAtom merge = null; private double bondLength; private String ID; /** * Constructor for the ChainModule. * * @param chemModelRelay The current chemModelRelay. */ public ChainModule(IChemModelRelay chemModelRelay) { super( chemModelRelay ); } private IChemObjectBuilder getBuilder() { return chemModelRelay.getIChemModel().getBuilder(); } @Override public void mouseClickedDown( Point2d worldCoord, int modifiers) { start = null; dest = null; source = null; bondLength = Renderer.calculateBondLength(chemModelRelay.getIChemModel()); // in case we are starting on an empty canvas if (bondLength == 0 || Double.isNaN(bondLength)) bondLength = 1.5; start = new Point2d(worldCoord); IAtom closestAtom = chemModelRelay.getClosestAtom(worldCoord); IBond closestBond = chemModelRelay.getClosestBond( worldCoord ); IChemObject singleSelection = getHighlighted( worldCoord, closestAtom, closestBond ); if(singleSelection instanceof IAtom ) { source = (IAtom) getHighlighted(worldCoord, closestAtom); if(source == null) { source = getBuilder().newInstance(IAtom.class, chemModelRelay.getController2DModel().getDrawElement(), start ); } else { // Take the true (x,y) of the atom, not the click point // otherwise it's very hard to draw a regular ring start = closestAtom.getPoint2d(); } } } @Override public void mouseDrag( Point2d worldCoordFrom, Point2d worldCoordTo, int modifiers) { chemModelRelay.clearPhantoms(); //how many bonds do we want? double distance = start.distance(worldCoordTo); int numberofbonds = (int)(distance / (bondLength*.8660254)); // constant is sqrt(3)/4 if(numberofbonds>0){ //add start atom IAtomContainer phantoms = getBuilder().newInstance(IAtomContainer.class); IAtom startAtom; if (source == null) { if (Elements.ofString(chemModelRelay.getController2DModel().getDrawElement()) == Elements.Unknown) startAtom = getBuilder().newInstance(IAtom.class, "C", start); else startAtom = getBuilder().newInstance(IAtom.class, chemModelRelay.getController2DModel().getDrawElement(), start); } else { startAtom = source; } phantoms.addAtom(startAtom); //make atoms and bonds as needed for(int i=0;i<numberofbonds;i++){ IAtom nextAtom; if (Elements.ofString(chemModelRelay.getController2DModel().getDrawElement()) == Elements.Unknown) nextAtom = getBuilder().newInstance(IAtom.class, "C", new Point2d(startAtom.getPoint2d().x+bondLength, startAtom.getPoint2d().y)); else nextAtom = getBuilder().newInstance(IAtom.class, chemModelRelay.getController2DModel().getDrawElement(), new Point2d(startAtom.getPoint2d().x+bondLength, startAtom.getPoint2d().y)); phantoms.addAtom(nextAtom); phantoms.addBond(getBuilder().newInstance(IBond.class, startAtom, nextAtom, IBond.Order.SINGLE)); startAtom = nextAtom; } // The algorithm is 1. calc point a bondlength away in the mouse direction // 2. calc point rotating the above 30° down, then the same 30° up // 3. chain the points alternatively Point2d point = new Point2d(worldCoordTo); Point2d center = new Point2d(start); double dx = (point.x - center.x)/numberofbonds; double dy = (point.y - center.y)/numberofbonds; double angle = Math.PI / 6; double cosangle = Math.cos(angle); double sinangle = Math.sin(angle); double firstx = dx*cosangle - dy*sinangle; double firsty = dx*sinangle + dy*cosangle; double secx = dx*cosangle + dy*sinangle; double secy = -dx*sinangle + dy*cosangle; Point2d p1 = new Point2d(start); phantoms.getAtom(0).setPoint2d(p1); double currx = p1.x; double curry = p1.y; for(int i=1; i<phantoms.getAtomCount(); i++){ Point2d p = new Point2d(currx,curry); if(i % 2 == 1){ p.x += firstx; p.y += firsty; }else{ p.x += secx; p.y += secy; } currx = p.x; curry = p.y; phantoms.getAtom(i).setPoint2d(p); } chemModelRelay.setPhantoms(phantoms); chemModelRelay.setPhantomText(""+phantoms.getAtomCount(), worldCoordTo); IAtom closestAtom = chemModelRelay.getClosestAtom(phantoms.getAtom(phantoms.getAtomCount()-1)); chemModelRelay.getRenderer().getRenderer2DModel().getMerge().remove(merge); merge = (IAtom) getHighlighted(phantoms.getAtom(phantoms.getAtomCount()-1).getPoint2d(), closestAtom); if(merge!=null){ chemModelRelay.getRenderer().getRenderer2DModel().getMerge().put(merge,phantoms.getAtom(phantoms.getAtomCount()-1)); chemModelRelay.getPhantoms().getConnectedBondsList(phantoms.getAtom(phantoms.getAtomCount()-1)).get(0).setAtom(merge,1); phantoms.removeAtomOnly(phantoms.getAtomCount()-1); } } chemModelRelay.updateView(); } @Override public void mouseClickedUp( Point2d worldCoord, int modifiers) { JChemPaintRendererModel model = chemModelRelay.getRenderer().getRenderer2DModel(); double d = model.getSelectionRadius() / model.getScale(); if (start.distance(worldCoord) < 4*d) return; IAtomContainer fromContainer = null, toContainer = null; IChemModel chemModel = chemModelRelay.getChemModel(); if(source != null){ fromContainer = ChemModelManipulator.getRelevantAtomContainer(chemModel, source); if (chemModelRelay.getPhantoms().getAtomCount() > 0) chemModelRelay.getPhantoms().removeAtomOnly(0); if (merge != null) toContainer = ChemModelManipulator.getRelevantAtomContainer(chemModel, merge); AtomBondSet fragment = new AtomBondSet(chemModelRelay.getPhantoms()); chemModelRelay.addFragment(fragment, fromContainer, toContainer==fromContainer ? null : toContainer); } else { if (merge != null) toContainer = ChemModelManipulator.getRelevantAtomContainer(chemModel, merge); chemModelRelay.addFragment(new AtomBondSet(chemModelRelay.getPhantoms()), null, toContainer); } if (merge != null) chemModelRelay.updateAtom(merge); if (source != null) chemModelRelay.updateAtom(source); chemModelRelay.clearPhantoms(); chemModelRelay.setPhantomText(null, null); chemModelRelay.getRenderer().getRenderer2DModel().getMerge().clear(); } public String getDrawModeString() { return "Draw Bond Chain"; } public String getID() { return ID; } public void setID(String ID) { this.ID=ID; } }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/controller/undoredo/CompoundEdit.java
.java
3,029
99
/* * 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.undoredo; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * A composite edit is made up of multiple sub-edits combined. The order is * important, the edits should be added in the order they were done, they will * then be undone in reverse. This allows multiple changed to be made at once * and then combined. * * @author John Mayfield */ public class CompoundEdit implements IUndoRedoable { private final List<IUndoRedoable> edits; private String description = "Structure changes"; public CompoundEdit(String description) { this.description = description; this.edits = new ArrayList<>(); } public CompoundEdit(String description, List<IUndoRedoable> edits) { this.description = description; this.edits = new ArrayList<>(edits); } public CompoundEdit(String description, IUndoRedoable first, IUndoRedoable second) { this.description = description; this.edits = Arrays.asList(first, second); } public void add(IUndoRedoable edit) { this.edits.add(edit); } public String description() { return description; } @Override public void redo() { for (IUndoRedoable child : edits) { child.redo(); } } @Override public void undo() { for (int i = edits.size() - 1; i >= 0; i--) { edits.get(i).undo(); } } @Override public boolean canRedo() { for (IUndoRedoable child : edits) { if (!child.canRedo()) return false; } return !edits.isEmpty(); } @Override public boolean canUndo() { for (IUndoRedoable child : edits) { if (!child.canUndo()) return false; } return !edits.isEmpty(); } }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/controller/undoredo/ReplaceAtomEdit.java
.java
2,552
85
/* $RCSfile$ * $Author: gilleain $ * $Date: 2008-11-26 16:01:05 +0000 (Wed, 26 Nov 2008) $ * $Revision: 13311 $ * * Copyright (C) 2005-2008 Tobias Helmus, Stefan Kuhn * * 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.undoredo; import org.openscience.cdk.interfaces.IAtom; import org.openscience.cdk.interfaces.IAtomContainer; import org.openscience.cdk.interfaces.IChemModel; import org.openscience.cdk.tools.manipulator.AtomContainerManipulator; import org.openscience.cdk.tools.manipulator.ChemModelManipulator; /** * @cdk.module controlbasic * @cdk.svnrev $Revision: 13311 $ */ public class ReplaceAtomEdit implements IUndoRedoable { private static final long serialVersionUID = -7667903450980188402L; private IChemModel chemModel; private IAtom oldAtom; private IAtom newAtom; private String type; /** * @param chemModel * @param undoRedoSet * @param c2dm The controller model; if none, set to null */ public ReplaceAtomEdit(IChemModel chemModel, IAtom oldAtom, IAtom newAtom, String type) { this.chemModel = chemModel; this.oldAtom = oldAtom; this.newAtom = newAtom; this.type = type; } public void redo() { IAtomContainer relevantContainer = ChemModelManipulator.getRelevantAtomContainer(chemModel, oldAtom); AtomContainerManipulator.replaceAtomByAtom(relevantContainer, oldAtom, newAtom); } public void undo() { IAtomContainer relevantContainer = ChemModelManipulator.getRelevantAtomContainer(chemModel, newAtom); AtomContainerManipulator.replaceAtomByAtom(relevantContainer, newAtom, oldAtom); } public boolean canRedo() { return true; } public boolean canUndo() { return true; } public String description() { return type; } }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/controller/undoredo/ChangeCoordsEdit.java
.java
3,450
107
/* $RCSfile$ * $Author: egonw $ * $Date: 2008-05-12 07:29:49 +0100 (Mon, 12 May 2008) $ * $Revision: 10979 $ * * 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.undoredo; import java.util.Iterator; import java.util.Map; import java.util.Set; import javax.vecmath.Point2d; import org.openscience.cdk.interfaces.IAtom; import org.openscience.cdk.interfaces.IBond; /** * Undo/Redo Edit superclass for all edit classes for coordinate changing * actions, containing the methods for undoing and redoing the regarding changes * * @cdk.module controlbasic * @cdk.svnrev $Revision: 10979 $ */ public class ChangeCoordsEdit implements IUndoRedoable { private static final long serialVersionUID = -8964120764568614909L; private Map<IAtom, Point2d[]> atomCoordsMap; private Map<IBond, IBond.Stereo> bondStereo; private String type; /** * @param atomCoordsMap * A HashMap containing the changed atoms as key and an Array * with the former and the changed coordinates as Point2ds */ public ChangeCoordsEdit(Map<IAtom, Point2d[]> atomCoordsMap, Map<IBond, IBond.Stereo> bondStereo, String type) { this.atomCoordsMap = atomCoordsMap; this.bondStereo = bondStereo; this.type=type; } public void redo() { Set<IAtom> keys = atomCoordsMap.keySet(); Iterator<IAtom> it = keys.iterator(); while (it.hasNext()) { IAtom atom = it.next(); Point2d[] coords = atomCoordsMap.get(atom); atom.setNotification(false); atom.setPoint2d(coords[0]); atom.setNotification(true); } for (Map.Entry<IBond, IBond.Stereo> e : bondStereo.entrySet()) { IBond.Stereo prev = e.getKey().getStereo(); e.getKey().setStereo(e.getValue()); e.setValue(prev); } } public void undo() { Set<IAtom> keys = atomCoordsMap.keySet(); Iterator<IAtom> it = keys.iterator(); while (it.hasNext()) { IAtom atom = (IAtom) it.next(); Point2d[] coords = atomCoordsMap.get(atom); atom.setPoint2d(coords[1]); } for (Map.Entry<IBond, IBond.Stereo> e : bondStereo.entrySet()) { IBond.Stereo prev = e.getKey().getStereo(); e.getKey().setStereo(e.getValue()); e.setValue(prev); } } public boolean canRedo() { return true; } public boolean canUndo() { return true; } public String description() { return type; } }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/controller/undoredo/ChangeAtomSymbolEdit.java
.java
3,214
125
/* $RCSfile$ * $Author: gilleain $ * $Date: 2008-11-26 16:01:05 +0000 (Wed, 26 Nov 2008) $ * $Revision: 13311 $ * * Copyright (C) 2005-2008 Tobias Helmus, Stefan Kuhn * * 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.undoredo; import org.openscience.cdk.interfaces.IAtom; import org.openscience.jchempaint.controller.IChemModelRelay; import javax.swing.undo.CannotRedoException; import javax.swing.undo.CannotUndoException; /** * Undo/Redo Edit class for the ChangeAtomSymbolAction, containing the methods * for undoing and redoing the regarding changes * * @author tohel * @cdk.module controlbasic */ public class ChangeAtomSymbolEdit implements IUndoRedoable { private static final long serialVersionUID = 779682083223003185L; private IAtom atom; private String formerSymbol; private String symbol; private String type; private IChemModelRelay chemModelRelay=null; /** * @param atomInRange * The atom been changed * @param formerSymbol * The atom symbol before change * @param symbol * The atom symbol past change */ public ChangeAtomSymbolEdit(IAtom atomInRange, String formerSymbol, String symbol, String type, IChemModelRelay chemModelRelay) { this.atom = atomInRange; this.formerSymbol = formerSymbol; this.symbol = symbol; this.type=type; this.chemModelRelay=chemModelRelay; } public ChangeAtomSymbolEdit(IAtom atomInRange, String formerSymbol, String symbol, IChemModelRelay chemModelRelay) { this(atomInRange, formerSymbol, symbol, "Change atom to " + symbol, chemModelRelay); } /* * (non-Javadoc) * * @see javax.swing.undo.UndoableEdit#redo() */ public void redo() throws CannotRedoException { this.atom.setSymbol(symbol); chemModelRelay.updateAtom(atom); } /* * (non-Javadoc) * * @see javax.swing.undo.UndoableEdit#undo() */ public void undo() throws CannotUndoException { this.atom.setSymbol(formerSymbol); chemModelRelay.updateAtom(atom); } /* * (non-Javadoc) * * @see javax.swing.undo.UndoableEdit#canRedo() */ public boolean canRedo() { return true; } /* * (non-Javadoc) * * @see javax.swing.undo.UndoableEdit#canUndo() */ public boolean canUndo() { return true; } /* * (non-Javadoc) * * @see javax.swing.undo.UndoableEdit#getPresentationName() */ public String description() { return type; } }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/controller/undoredo/MakeReactantOrProductInExistingReactionEdit.java
.java
4,575
130
/* $RCSfile$ * $Author: gilleain $ * $Date: 2008-11-26 16:01:05 +0000 (Wed, 26 Nov 2008) $ * $Revision: 13311 $ * * Copyright (C) 2005-2008 Tobias Helmus, Stefan Kuhn * * 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.undoredo; import org.openscience.cdk.interfaces.IAtomContainer; import org.openscience.cdk.interfaces.IChemModel; import org.openscience.cdk.interfaces.IAtomContainerSet; import org.openscience.cdk.interfaces.IReaction; import org.openscience.cdk.interfaces.IReactionSet; import org.openscience.cdk.tools.manipulator.ReactionSetManipulator; /** * @cdk.module controlextra * @cdk.svnrev $Revision: 13311 $ */ public class MakeReactantOrProductInExistingReactionEdit implements IUndoRedoable { private static final long serialVersionUID = -7667903450980188402L; private IAtomContainer movedContainer; private IAtomContainer oldContainer; private String type; private IChemModel chemModel; private String reactionID; private boolean reactantOrProduct; /** * @param chemModel * @param undoRedoSet * @param c2dm The controller model; if none, set to null */ public MakeReactantOrProductInExistingReactionEdit(IChemModel chemModel, IAtomContainer ac, IAtomContainer oldcontainer, String s, boolean reactantOrProduct, String type) { this.type = type; this.movedContainer = ac; this.oldContainer = oldcontainer; this.chemModel = chemModel; this.reactionID = s; this.reactantOrProduct = reactantOrProduct; } public void redo() { chemModel.getMoleculeSet().removeAtomContainer(movedContainer); if(chemModel.getReactionSet()==null) chemModel.setReactionSet(chemModel.getBuilder().newInstance(IReactionSet.class)); IReaction reaction = ReactionSetManipulator.getReactionByReactionID(chemModel.getReactionSet(), reactionID); if(reaction==null){ reaction = chemModel.getBuilder().newInstance(IReaction.class); reaction.setID(reactionID); chemModel.getReactionSet().addReaction(reaction); } IAtomContainer mol=chemModel.getBuilder().newInstance(IAtomContainer.class,movedContainer); mol.setID(movedContainer.getID()); if(reactantOrProduct) reaction.addReactant(mol); else reaction.addProduct(mol); chemModel.getMoleculeSet().removeAtomContainer(oldContainer); if(chemModel.getMoleculeSet().getAtomContainerCount()==0) chemModel.getMoleculeSet().addAtomContainer(chemModel.getBuilder().newInstance(IAtomContainer.class)); } public void undo() { if(chemModel.getMoleculeSet()==null) chemModel.setMoleculeSet(chemModel.getBuilder().newInstance(IAtomContainerSet.class)); chemModel.getMoleculeSet().addAtomContainer(oldContainer); IAtomContainerSet reactantsorproducts; if(reactantOrProduct) reactantsorproducts = ReactionSetManipulator.getReactionByReactionID(chemModel.getReactionSet(), reactionID).getReactants(); else reactantsorproducts = ReactionSetManipulator.getReactionByReactionID(chemModel.getReactionSet(), reactionID).getProducts(); IReaction reaction = ReactionSetManipulator.getReactionByReactionID(chemModel.getReactionSet(), reactionID); int count=0; for(IAtomContainer mol : reactantsorproducts.atomContainers()){ if(mol.getID().equals(movedContainer.getID())){ reactantsorproducts.removeAtomContainer(count); break; } count++; } if(reaction.getReactantCount()==0 && reaction.getProductCount()==0) chemModel.getReactionSet().removeReaction(reaction); if(chemModel.getReactionSet().getReactionCount()==0) chemModel.setReactionSet(null); } public boolean canRedo() { return true; } public boolean canUndo() { return true; } /* * (non-Javadoc) * * @see javax.swing.undo.UndoableEdit#getPresentationName() */ public String description() { return type; } }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/controller/undoredo/IUndoRedoFactory.java
.java
5,731
98
/* * $RCSfile$ * $Author: egonw $ * $Date: 2007-01-04 17:26:00 +0000 (Thu, 04 Jan 2007) $ * $Revision: 7634 $ * * Copyright (C) 1997-2008 Stefan Kuhn * Copyright (C) 2009 Arvid Berg * * 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.undoredo; import java.util.List; import java.util.Map; import javax.vecmath.Point2d; import javax.vecmath.Vector2d; 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.IElectronContainer; import org.openscience.cdk.interfaces.IAtomContainerSet; import org.openscience.cdk.interfaces.IReactionSet; import org.openscience.cdk.isomorphism.matchers.RGroup; import org.openscience.cdk.isomorphism.matchers.RGroupList; import org.openscience.jchempaint.AtomBondSet; import org.openscience.jchempaint.controller.IChemModelRelay; import org.openscience.jchempaint.rgroups.RGroupHandler; /** * This interface needs to be implemented in an application to return instances of classes * extending the implementations of IUndoRedoable suitable for the respective gui framework * (e. g. swing or swt). * * @cdk.module control */ public interface IUndoRedoFactory { public IUndoRedoable getAddAtomsAndBondsEdit(IChemModel chemModel, AtomBondSet undoRedoSet, IAtomContainer removedAtomContainer, String type, IChemModelRelay c2dm); public IUndoRedoable getAdjustBondOrdersEdit(Map<IBond, IBond.Order[]> changedBonds, Map<IBond, IBond.Display[]> changedBondDisplay, String type, IChemModelRelay chemModelRelay ); public IUndoRedoable getChangeAtomSymbolEdit(IAtom atom, String formerSymbol, String symbol, String type, IChemModelRelay chemModelRelay); public IUndoRedoable getChangeChargeEdit(IAtom atomInRange, int formerCharge, int newCharge, String type, IChemModelRelay chemModelRelay); public IUndoRedoable getMoveAtomEdit(IAtomContainer undoRedoSet, Vector2d offset, String type); public IUndoRedoable getRemoveAtomsAndBondsEdit(IChemModel chemModel, AtomBondSet undoRedoSet, String type, IChemModelRelay chemModelRelay); public IUndoRedoable getReplaceAtomEdit(IChemModel chemModel, IAtom oldAtom, IAtom newAtom, String type); public IUndoRedoable getSingleElectronEdit(IAtomContainer relevantContainer, IElectronContainer electronContainer, boolean add, IChemModelRelay chemModelRelay, IAtom atom, String type); public IUndoRedoable getChangeIsotopeEdit(IAtom atom, Integer formerIsotopeNumber, Integer newIstopeNumber, String type); public IUndoRedoable getClearAllEdit(IChemModel chemModel, IAtomContainerSet som, IReactionSet sor, String type); public IUndoRedoable getChangeCoordsEdit(Map<IAtom, Point2d[]> atomCoordsMap, Map<IBond, IBond.Stereo> bondStereo, String type); public IUndoRedoable getMakeReactantOrProductInNewReactionEdit(IChemModel chemModel, IAtomContainer ac, IAtomContainer oldcontainer, boolean reactantOrProduct, String type); public IUndoRedoable getMakeReactantOrProductInExistingReactionEdit( IChemModel chemModel, IAtomContainer newContainer, IAtomContainer oldcontainer, String s, boolean reactantOrProduct, String string); public IUndoRedoable getMergeMoleculesEdit(List<IAtom> deletedAtom, List<IAtomContainer> containers, List<IAtomContainer> droppedContainers, List<List<IBond>> deletedBonds, List<Map<IBond, Integer>> bondsWithReplacedAtom, Vector2d offset, List<IAtom> atomwhichwasmoved, IUndoRedoable moveundoredo, Map<Integer,Map<Integer,Integer>> oldRgrpHash, Map<Integer,Map<Integer,Integer>> newGrgpHash, String type, IChemModelRelay c2dm); public IUndoRedoable getChangeHydrogenCountEdit(Map<IAtom, Integer[]> atomHydrogenCountsMap, String type); public IUndoRedoable getLoadNewModelEdit(IChemModel chemModel, IChemModelRelay relay, IAtomContainerSet oldsom, IReactionSet oldsor, IAtomContainerSet newsom, IReactionSet newsor, String type); public IUndoRedoable getChangeValenceEdit(IAtom atomInRange, Integer formerValence, Integer valence, String text, IChemModelRelay chemModelRelay); public IUndoRedoable getRGroupEdit(String type, boolean isNewRGroup,IChemModelRelay hub,RGroupHandler rgrpHandler , Map<IAtom,IAtomContainer> existingAtomDistr, Map<IBond,IAtomContainer> existingBondDistr , IAtomContainer existingRoot, Map<IAtom, Map<Integer, IBond>> existingRootAttachmentPoints, Map<IAtom, Map<Integer, IBond>> newRootAttachmentPoints, Map<RGroup, Map<Integer,IAtom>> existingRGroupApo , Map<Integer,RGroupList> rgroupLists,IAtomContainer userSelection); }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/controller/undoredo/MergeMoleculesEdit.java
.java
8,593
224
/* $RCSfile$ * $Author: gilleain $ * $Date: 2008-11-26 16:01:05 +0000 (Wed, 26 Nov 2008) $ * $Revision: 13311 $ * * Copyright (C) 2005-2008 Tobias Helmus, Stefan Kuhn * * 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.undoredo; import java.util.List; import java.util.Map; import javax.swing.undo.CannotRedoException; import javax.swing.undo.CannotUndoException; import javax.vecmath.Vector2d; import org.openscience.cdk.AtomContainer; import org.openscience.cdk.interfaces.IAtom; import org.openscience.cdk.interfaces.IAtomContainer; import org.openscience.cdk.interfaces.IBond; import org.openscience.cdk.tools.manipulator.AtomContainerManipulator; import org.openscience.jchempaint.controller.IChemModelRelay; /** * @cdk.module controlextra * @cdk.svnrev $Revision: 10979 $ */ public class MergeMoleculesEdit implements IUndoRedoable{ private static final long serialVersionUID = -4093867960954400453L; private List<IAtom> deletedAtoms; private List<List<IBond>> deletedBondss; private List<Map<IBond, Integer>> bondsWithReplacedAtoms; private IChemModelRelay chemModelRelay; private String type; private List<IAtomContainer> containers; private List<IAtomContainer> droppedContainers; private Vector2d offset; private List<IAtom> mergedPartnerAtoms; private IUndoRedoable moveundoredo; Map<Integer,Map<Integer,Integer>> oldRgrpHash; Map<Integer,Map<Integer,Integer>> newRgrpHash; /** * @param deletedAtoms The atoms which were deleted during the merge. * @param containers containers participating in the merge * @param droppedContainers containers dropped on merge of 2 separate containers * @param deletedBondss The bonds which were deleted to merge each individual atom. * @param bondsWithReplacedAtoms For each atom merge, for each bond in deletedBondss, which of the atoms (0 or 1) in that bond was deletedAtom. * @param offset The distance by which the atoms where shifted in merge. * @param mergedPartnerAtoms The atoms which replace deletedAtoms. * @param moveundoredo If atoms where moved, but not merged, they go in here, maybe null. * @param type The string returned as presentation name. * @param chemModelRelay The current chemModelRelay. */ public MergeMoleculesEdit(List<IAtom> deletedAtoms, List<IAtomContainer> containers, List<IAtomContainer> droppedContainers, List<List<IBond>> deletedBondss, List<Map<IBond, Integer>> bondsWithReplacedAtoms, Vector2d offset, List<IAtom> mergedPartnerAtoms, IUndoRedoable moveundoredo, Map<Integer,Map<Integer,Integer>> oldRgrpHash, Map<Integer,Map<Integer,Integer>> newRgrpHash, String type, IChemModelRelay chemModelRelay) { this.deletedAtoms = deletedAtoms; this.deletedBondss = deletedBondss; this.bondsWithReplacedAtoms = bondsWithReplacedAtoms; this.chemModelRelay = chemModelRelay; this.mergedPartnerAtoms = mergedPartnerAtoms; this.type = type; this.containers= containers; this.droppedContainers= droppedContainers; this.offset = offset; this.moveundoredo = moveundoredo; this.oldRgrpHash=oldRgrpHash; this.newRgrpHash=newRgrpHash; } public void redo() throws CannotRedoException { // put everything back together for(int i=0;i<deletedAtoms.size();i++){ IAtomContainer containerWithMerge =containers.get(i); IAtomContainer droppedContainer = droppedContainers.get(i); // can be null if (droppedContainer!=null) { for (IAtom mAt : droppedContainer.atoms()) { if (!containerWithMerge.contains(mAt)) { containerWithMerge.addAtom(mAt); } } for (IBond mBond : droppedContainer.bonds()) { if (!containerWithMerge.contains(mBond)) { containerWithMerge.addBond(mBond); } } chemModelRelay.getChemModel().getMoleculeSet().removeAtomContainer(droppedContainer); } } // delete/update bonds as needed for(int i=0;i<deletedAtoms.size();i++){ IAtomContainer containerWithMerge =containers.get(i); IAtomContainer droppedContainer = droppedContainers.get(i); // can be null for(IBond bond : bondsWithReplacedAtoms.get(i).keySet()){ bond.setAtom(mergedPartnerAtoms.get(i), bondsWithReplacedAtoms.get(i).get(bond)); } for(IBond bond : deletedBondss.get(i)){ containerWithMerge.removeBond(bond); } deletedAtoms.get(i).getPoint2d().x+=offset.x; deletedAtoms.get(i).getPoint2d().y+=offset.y; chemModelRelay.updateAtom(mergedPartnerAtoms.get(i)); if (droppedContainer!=null) { for (IAtom mAt : droppedContainer.atoms()) { if (!containerWithMerge.contains(mAt)) { containerWithMerge.addAtom(mAt); } } for (IBond mBond : droppedContainer.bonds()) { if (!containerWithMerge.contains(mBond)) { containerWithMerge.addBond(mBond); } } chemModelRelay.getChemModel().getMoleculeSet().removeAtomContainer(droppedContainer); } } // now delete the atoms for(int i=0;i<deletedAtoms.size();i++) { IAtomContainer containerWithMerge = containers.get(i); containerWithMerge.removeAtomOnly(deletedAtoms.get(i)); } if(moveundoredo!=null) moveundoredo.redo(); if (chemModelRelay.getRGroupHandler()!=null) { chemModelRelay.getRGroupHandler().restoreFromHash(newRgrpHash, chemModelRelay.getChemModel().getMoleculeSet()); } } public void undo() throws CannotUndoException { assert deletedAtoms.size() == mergedPartnerAtoms.size(); // add all atoms back on first for (int i=0; i<deletedAtoms.size(); i++) { IAtomContainer containerWithMerge = containers.get(i); containerWithMerge.addAtom(deletedAtoms.get(i)); } for (int i=0; i<deletedAtoms.size(); i++){ IAtomContainer containerWithMerge = containers.get(i); IAtomContainer droppedContainer = droppedContainers.get(i); // can be null //Put dropped atom and bond back into atc1 for (Map.Entry<IBond,Integer> e : bondsWithReplacedAtoms.get(i).entrySet()) { IBond bond = e.getKey(); int idx = e.getValue(); bond.setAtom(deletedAtoms.get(i), idx); } System.err.println(deletedBondss.get(i).size()); for (IBond bond : deletedBondss.get(i)){ containerWithMerge.addBond(bond); } deletedAtoms.get(i).getPoint2d().x-=offset.x; deletedAtoms.get(i).getPoint2d().y-=offset.y; chemModelRelay.updateAtom(deletedAtoms.get(i)); chemModelRelay.updateAtom(mergedPartnerAtoms.get(i)); if (droppedContainer!=null) { //remove from atc1 what was merged in from atc2 for (IAtom mAt : droppedContainer.atoms()) { if (containerWithMerge.contains(mAt)) { containerWithMerge.removeAtomOnly(mAt); } } for (IBond mBond : droppedContainer.bonds()) { if (containerWithMerge.contains(mBond)) { containerWithMerge.removeBond(mBond); } } //restore removed container atc2 chemModelRelay.getChemModel().getMoleculeSet().addAtomContainer(droppedContainer); } } if(moveundoredo!=null) moveundoredo.undo(); if (chemModelRelay.getRGroupHandler()!=null) { chemModelRelay.getRGroupHandler().restoreFromHash(oldRgrpHash, chemModelRelay.getChemModel().getMoleculeSet()); } } public boolean canRedo() { return true; } public boolean canUndo() { return true; } public String description() { return type; } }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/controller/undoredo/IUndoListener.java
.java
1,600
44
/* * $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-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.undoredo; /** * This interface is implemented by applications and registered onto UndoRedoHandler. * The events then get passed onto the actual undo/redo implementation of the gui * framework. * * @cdk.module control */ public interface IUndoListener { public void doUndo(IUndoRedoable undoredo); }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/controller/undoredo/ChangeHydrogenCountEdit.java
.java
2,853
94
/* $RCSfile$ * $Author: gilleain $ * $Date: 2008-11-26 16:01:05 +0000 (Wed, 26 Nov 2008) $ * $Revision: 13311 $ * * Copyright (C) 2005-2008 Tobias Helmus, Stefan Kuhn * * 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.undoredo; import java.util.Iterator; import java.util.Map; import java.util.Set; import org.openscience.cdk.interfaces.IAtom; /** * Undo/Redo Edit class for the ChangeCharge actions in AbstarctController2D, * containing the methods for undoing and redoing the regarding changes * * @cdk.module controlbasic * @cdk.svnrev $Revision: 10979 $ */ public class ChangeHydrogenCountEdit implements IUndoRedoable { private static final long serialVersionUID = 1237756549190508501L; private Map<IAtom, Integer[]> atomHydrogenCountsMap; private String type; /** * @param atomInRange * The atom been changed * @param formerCharge * The former charge of this atom * @param newCharge * The new charge of this atom */ public ChangeHydrogenCountEdit(Map<IAtom, Integer[]> atomHydrogenCountsMap, String type) { this.atomHydrogenCountsMap = atomHydrogenCountsMap; this.type = type; } public void redo() { Set<IAtom> keys = atomHydrogenCountsMap.keySet(); Iterator<IAtom> it = keys.iterator(); while (it.hasNext()) { IAtom atom = it.next(); Integer[] counts = atomHydrogenCountsMap.get(atom); atom.setNotification(false); atom.setImplicitHydrogenCount(counts[0]); atom.setNotification(true); } } public void undo() { Set<IAtom> keys = atomHydrogenCountsMap.keySet(); Iterator<IAtom> it = keys.iterator(); while (it.hasNext()) { IAtom atom = (IAtom) it.next(); Integer[] counts = atomHydrogenCountsMap.get(atom); atom.setImplicitHydrogenCount(counts[1]); } } public boolean canRedo() { return true; } public boolean canUndo() { return true; } public String description() { return type; } }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/controller/undoredo/ClearAllEdit.java
.java
2,161
75
/* $RCSfile$ * $Author: gilleain $ * $Date: 2008-11-26 16:01:05 +0000 (Wed, 26 Nov 2008) $ * $Revision: 13311 $ * * Copyright (C) 2005-2008 Stefan Kuhn * * 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.undoredo; import org.openscience.cdk.interfaces.IChemModel; import org.openscience.cdk.interfaces.IAtomContainerSet; import org.openscience.cdk.interfaces.IReactionSet; /** * @cdk.module controlbasic * @cdk.svnrev $Revision: 10979 $ */ public class ClearAllEdit implements IUndoRedoable { private static final long serialVersionUID = -9022673628051651034L; private IChemModel chemModel; private IAtomContainerSet som; private IReactionSet sor; private String type; public ClearAllEdit(IChemModel chemModel, IAtomContainerSet som, IReactionSet sor, String type) { this.chemModel = chemModel; this.som=som; this.sor=sor; this.type=type; } public void redo() { if(chemModel.getMoleculeSet()!=null) chemModel.getMoleculeSet().removeAllAtomContainers(); if(chemModel.getReactionSet()!=null) chemModel.getReactionSet().removeAllReactions(); } public void undo() { if(som!=null) chemModel.setMoleculeSet(som); if(sor!=null) chemModel.setReactionSet(sor); } public boolean canRedo() { return true; } public boolean canUndo() { return true; } public String description() { return type; } }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/controller/undoredo/AdjustBondOrdersEdit.java
.java
4,636
140
/* $RCSfile$ * $Author: gilleain $ * $Date: 2008-11-26 16:01:05 +0000 (Wed, 26 Nov 2008) $ * $Revision: 13311 $ * * Copyright (C) 2005-2008 Tobias Helmus, Stefan Kuhn * * 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.undoredo; import java.util.Collections; import java.util.Iterator; import java.util.Map; import java.util.Set; import javax.swing.undo.CannotUndoException; import org.openscience.cdk.interfaces.IBond; import org.openscience.jchempaint.controller.IChemModelRelay; /** * Undo/Redo Edit class for the AdjustBondOrdesAction, containing the methods * for undoing and redoing the regarding changes * * @cdk.module controlbasic * @cdk.svnrev $Revision: 10979 $ */ public class AdjustBondOrdersEdit implements IUndoRedoable { private static final long serialVersionUID = 1513012471000333600L; private Map<IBond, IBond.Order[]> changedBondOrders; private Map<IBond, IBond.Stereo[]> changedBondsStereo; private Map<IBond, IBond.Display[]> changedBondsDisplay; private String type; private IChemModelRelay chemModelRelay=null; /** * @param changedBonds * A HashMap containing the changed atoms as key and an Array * with the former and the changed bondOrder */ public AdjustBondOrdersEdit( Map<IBond, IBond.Order[]> changedBondsOrder, Map<IBond, IBond.Stereo[]> changedBondsStereo, Map<IBond, IBond.Display[]> changedBondsDisplay, String type, IChemModelRelay chemModelRelay) { this.changedBondOrders = changedBondsOrder; this.changedBondsStereo = changedBondsStereo; this.changedBondsDisplay = changedBondsDisplay; this.type=type; this.chemModelRelay=chemModelRelay; } public AdjustBondOrdersEdit( Map<IBond, IBond.Order[]> changedBondsOrder, Map<IBond, IBond.Stereo[]> changedBondsStereo, String type, IChemModelRelay chemModelRelay) { this(changedBondsOrder, changedBondsStereo, Collections.emptyMap(), type, chemModelRelay); } public void redo() { for (Map.Entry<IBond, IBond.Order[]> e : changedBondOrders.entrySet()) { IBond bond = e.getKey(); IBond.Order[] bondOrders = e.getValue(); bond.setOrder(bondOrders[0]); } for (Map.Entry<IBond, IBond.Stereo[]> e : changedBondsStereo.entrySet()) { IBond bond = e.getKey(); IBond.Stereo[] bondStereos = e.getValue(); bond.setStereo(bondStereos[0]); } for (Map.Entry<IBond, IBond.Display[]> e : changedBondsDisplay.entrySet()) { IBond bond = e.getKey(); IBond.Display[] bondStereos = e.getValue(); bond.setDisplay(bondStereos[0]); } // update once everything has changed for (IBond bond : changedBondOrders.keySet()) { chemModelRelay.updateAtoms(bond); } } public void undo() throws CannotUndoException { for (Map.Entry<IBond, IBond.Order[]> e : changedBondOrders.entrySet()) { IBond bond = e.getKey(); IBond.Order[] bondOrders = e.getValue(); bond.setOrder(bondOrders[1]); } for (Map.Entry<IBond, IBond.Stereo[]> e : changedBondsStereo.entrySet()) { IBond bond = e.getKey(); IBond.Stereo[] bondStereos = e.getValue(); bond.setStereo(bondStereos[1]); if (bondStereos[1] == IBond.Stereo.NONE) bond.setDisplay(IBond.Display.Solid); } for (Map.Entry<IBond, IBond.Display[]> e : changedBondsDisplay.entrySet()) { IBond bond = e.getKey(); IBond.Display[] bondStereos = e.getValue(); bond.setDisplay(bondStereos[1]); } // update once everything has changed for (IBond bond : changedBondOrders.keySet()) { chemModelRelay.updateAtoms(bond); } } public boolean canRedo() { return true; } public boolean canUndo() { return true; } public String description() { return type; } }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/controller/undoredo/ChangeValenceEdit.java
.java
3,056
114
/* $RCSfile$ * $Author: gilleain $ * $Date: 2008-11-26 16:01:05 +0000 (Wed, 26 Nov 2008) $ * $Revision: 13311 $ * * Copyright (C) 2009 Stefan Kuhn * * 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.undoredo; import javax.swing.undo.CannotRedoException; import javax.swing.undo.CannotUndoException; import org.openscience.cdk.interfaces.IAtom; import org.openscience.jchempaint.controller.IChemModelRelay; /** * Undo/Redo Edit class for the ChangeValenceAction, containing the methods * for undoing and redoing the regarding changes * * @cdk.module controlbasic */ public class ChangeValenceEdit implements IUndoRedoable { private static final long serialVersionUID = 779682083223003185L; private IAtom atom; private Integer formerValence; private Integer valence; private String text; private IChemModelRelay chemModelRelay=null; /** * @param atomInRange The atom which has been changed. * @param formerValence The atom valence before change. * @param valence The atom valence past change. * @param text The text to display for this undo/redo action.. * @param chemModelRelay The current instance implementing IChemModelRelay. */ public ChangeValenceEdit(IAtom atomInRange, Integer formerValence, Integer valence, String text, IChemModelRelay chemModelRelay) { this.atom = atomInRange; this.formerValence = formerValence; this.valence = valence; this.text=text; this.chemModelRelay=chemModelRelay; } /* * (non-Javadoc) * * @see javax.swing.undo.UndoableEdit#redo() */ public void redo() throws CannotRedoException { this.atom.setValency(valence); chemModelRelay.updateAtom(atom); } /* * (non-Javadoc) * * @see javax.swing.undo.UndoableEdit#undo() */ public void undo() throws CannotUndoException { this.atom.setValency(formerValence); chemModelRelay.updateAtom(atom); } /* * (non-Javadoc) * * @see javax.swing.undo.UndoableEdit#canRedo() */ public boolean canRedo() { return true; } /* * (non-Javadoc) * * @see javax.swing.undo.UndoableEdit#canUndo() */ public boolean canUndo() { return true; } /* * (non-Javadoc) * * @see javax.swing.undo.UndoableEdit#getPresentationName() */ public String description() { return text; } }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/controller/undoredo/AddAtomsAndBondsEdit.java
.java
7,453
215
/* $RCSfile$ * $Author: gilleain $ * $Date: 2008-11-26 16:01:05 +0000 (Wed, 26 Nov 2008) $ * $Revision: 13311 $ * * Copyright (C) 2005-2008 Tobias Helmus, Stefan Kuhn * * 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.undoredo; import org.openscience.cdk.DefaultChemObjectBuilder; 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.tools.manipulator.ChemModelManipulator; import org.openscience.jchempaint.AtomBondSet; import org.openscience.jchempaint.controller.ControllerHub; import org.openscience.jchempaint.controller.IChemModelRelay; import org.openscience.jchempaint.renderer.JChemPaintRendererModel; import java.util.ArrayList; import java.util.Comparator; import java.util.HashSet; import java.util.List; import java.util.Set; /** * @cdk.module controlbasic @cdk.svnrev $Revision: 13311 $ */ public class AddAtomsAndBondsEdit implements IUndoRedoable { private static final long serialVersionUID = -7667903450980188402L; private IChemModel chemModel; private AtomBondSet undoRedoSet; private String type; private IChemModelRelay chemModelRelay = null; private IAtomContainer containerToAddTo; private IAtomContainer removedAtomContainer; // TODO - remove this, also from constructor. see markr's comments /** * @param chemModel * @param undoRedoSet * @param removedAtomContainer atomContainer which has been removed from * setOfAtomContainers as part of the edit, if none, null. * @param chemModelRelay */ public AddAtomsAndBondsEdit(IChemModel chemModel, AtomBondSet undoRedoSet, IAtomContainer removedAtomContainer, String type, IChemModelRelay chemModelRelay) { this.chemModel = chemModel; this.undoRedoSet = undoRedoSet; this.type = type; this.chemModelRelay = chemModelRelay; this.removedAtomContainer = removedAtomContainer; } public void redo() { IAtomContainer connectedContainer = isConnectedToExistingFragment(undoRedoSet); if (connectedContainer == null && containerToAddTo != null && chemModel.getMoleculeSet().getMultiplier(containerToAddTo) == -1) { chemModel.getMoleculeSet().addAtomContainer(containerToAddTo); connectedContainer = containerToAddTo; } if (connectedContainer == null) { connectedContainer = DefaultChemObjectBuilder.getInstance() .newAtomContainer(); chemModel.getMoleculeSet().addAtomContainer(connectedContainer); } //markr: this code creates problems when dragging a bond across a structure, so that it merges with itself.. //if(removedAtomContainer!=null){ // containerToAddTo.add(removedAtomContainer); // chemModel.getMoleculeSet().removeAtomContainer(removedAtomContainer); //} for (IAtom atom : undoRedoSet.atoms()) { connectedContainer.addAtom(atom); } for (IBond bond : undoRedoSet.bonds()) { connectedContainer.addBond(bond); } for (IBond bond : undoRedoSet.bonds()) { chemModelRelay.updateAtoms(bond); } for (IAtom atom : undoRedoSet.atoms()) { chemModelRelay.updateAtom(atom); } } // JWM: this is really dodgey, we need to ditch ChemModel! private IAtomContainer isConnectedToExistingFragment(AtomBondSet undoRedoSet) { for (IBond bond : undoRedoSet.bonds()) { if (!undoRedoSet.contains(bond.getBegin())) return ChemModelManipulator.getRelevantAtomContainer(chemModel, bond.getBegin()); if (!undoRedoSet.contains(bond.getEnd())) return ChemModelManipulator.getRelevantAtomContainer(chemModel, bond.getEnd()); } return null; } public void undo() { //markr: this code creates problems when dragging a bond across a structure, so that it merges with itself.. //if(removedAtomContainer!=null){ // ChemModelManipulator.getRelevantAtomContainer(chemModel, removedAtomContainer.getAtom(0)).remove(removedAtomContainer); // chemModel.getMoleculeSet().addAtomContainer(removedAtomContainer); //} IBond[] bonds = new IBond[undoRedoSet.getBondCount()]; int idx = 0; for (IBond bond : undoRedoSet.bonds()) { bonds[idx++] = bond; } List<IAtom> leftOver = new ArrayList<>(); for (IBond bond : bonds) { containerToAddTo = ChemModelManipulator.getRelevantAtomContainer(chemModel, bond); if (containerToAddTo != null) { containerToAddTo.removeBond(bond); if (undoRedoSet.contains(bond.getBegin()) && !undoRedoSet.contains(bond.getEnd())) { leftOver.add(bond.getEnd()); } else if (undoRedoSet.contains(bond.getEnd()) && !undoRedoSet.contains(bond.getBegin())) { leftOver.add(bond.getBegin()); } } } IAtom[] atoms = new IAtom[undoRedoSet.getAtomCount()]; idx = 0; for (IAtom atom : undoRedoSet.atoms()) { atoms[idx++] = atom; } for (IAtom atom : atoms) { containerToAddTo = ChemModelManipulator.getRelevantAtomContainer(chemModel, atom); if (containerToAddTo != null) { containerToAddTo.removeAtom(atom); } } if (chemModelRelay.getIChemModel().getMoleculeSet().getAtomContainerCount() > 1) { ControllerHub.removeEmptyContainers(chemModelRelay.getIChemModel()); } for (IAtomContainer container : ChemModelManipulator.getAllAtomContainers(chemModel)) { chemModelRelay.updateAtoms(container, container.atoms()); } // select the last atom if the hotspot was deleted by this undo JChemPaintRendererModel model = chemModelRelay.getRenderer().getRenderer2DModel(); if (!leftOver.isEmpty()) { leftOver.sort(Comparator.comparing(IAtom::getIndex)); IAtom hgAtom = leftOver.get(leftOver.size() - 1); containerToAddTo = ChemModelManipulator.getRelevantAtomContainer(chemModel, hgAtom); model.setHighlightedAtom(containerToAddTo.getAtom(containerToAddTo.indexOf(hgAtom))); } else { if (undoRedoSet.contains(model.getHighlightedAtom())) { for (IAtomContainer container : ChemModelManipulator.getAllAtomContainers(chemModelRelay.getIChemModel())) { if (!container.isEmpty()) { chemModelRelay.getRenderer().getRenderer2DModel() .setHighlightedAtom(container.getAtom(container.getAtomCount() - 1)); } } } } } public boolean canRedo() { return true; } public boolean canUndo() { return true; } /* * (non-Javadoc) * * @see javax.swing.undo.UndoableEdit#getPresentationName() */ public String description() { return type; } }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/controller/undoredo/IUndoRedoable.java
.java
1,666
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-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.undoredo; /** * This interface is implemented by all the actual edit events. * * @cdk.module control */ public interface IUndoRedoable { default String description() { return "Structure changed"; } void redo(); void undo(); default boolean canRedo() { return true; } default boolean canUndo() { return true; } }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/controller/undoredo/ChangeChargeEdit.java
.java
2,468
89
/* $RCSfile$ * $Author: gilleain $ * $Date: 2008-11-26 16:01:05 +0000 (Wed, 26 Nov 2008) $ * $Revision: 13311 $ * * Copyright (C) 2005-2008 Tobias Helmus, Stefan Kuhn * * 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.undoredo; import org.openscience.cdk.interfaces.IAtom; import org.openscience.jchempaint.controller.IChemModelRelay; /** * Undo/Redo Edit class for the ChangeCharge actions in AbstarctController2D, * containing the methods for undoing and redoing the regarding changes * * @cdk.module controlbasic * @cdk.svnrev $Revision: 10979 $ */ public class ChangeChargeEdit implements IUndoRedoable { private static final long serialVersionUID = 1237756549190508501L; private IAtom atom; private int formerCharge; private int newCharge; private String type; private IChemModelRelay chemModelRelay=null; /** * @param atomInRange * The atom been changed * @param formerCharge * The former charge of this atom * @param newCharge * The new charge of this atom */ public ChangeChargeEdit(IAtom atomInRange, int formerCharge, int newCharge, String type, IChemModelRelay chemModelRelay) { this.atom = atomInRange; this.formerCharge = formerCharge; this.newCharge = newCharge; this.type = type; this.chemModelRelay=chemModelRelay; } public void redo() { this.atom.setFormalCharge(newCharge); chemModelRelay.updateAtom(atom); } public void undo() { this.atom.setFormalCharge(formerCharge); chemModelRelay.updateAtom(atom); } public boolean canRedo() { return true; } public boolean canUndo() { return true; } public String description() { return type; } }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/controller/undoredo/MakeReactantOrProductInNewReactionEdit.java
.java
3,613
108
/* $RCSfile$ * $Author: gilleain $ * $Date: 2008-11-26 16:01:05 +0000 (Wed, 26 Nov 2008) $ * $Revision: 13311 $ * * Copyright (C) 2005-2008 Tobias Helmus, Stefan Kuhn * * 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.undoredo; import org.openscience.cdk.interfaces.IAtomContainer; import org.openscience.cdk.interfaces.IChemModel; import org.openscience.cdk.interfaces.IAtomContainerSet; import org.openscience.cdk.interfaces.IReaction; import org.openscience.cdk.interfaces.IReactionSet; import org.openscience.cdk.tools.manipulator.ReactionSetManipulator; /** * @cdk.module controlextra * @cdk.svnrev $Revision: 13311 $ */ public class MakeReactantOrProductInNewReactionEdit implements IUndoRedoable { private static final long serialVersionUID = -7667903450980188402L; private IAtomContainer movedContainer; private IAtomContainer oldContainer; private String type; private IChemModel chemModel; private String reactionID; private boolean reactantOrProduct; /** * @param chemModel * @param undoRedoSet * @param c2dm The controller model; if none, set to null */ public MakeReactantOrProductInNewReactionEdit(IChemModel chemModel, IAtomContainer ac, IAtomContainer oldcontainer, boolean reactantOrProduct, String type) { this.type = type; this.movedContainer = ac; this.oldContainer = oldcontainer; this.chemModel = chemModel; this.reactionID = ReactionSetManipulator.getReactionByAtomContainerID(chemModel.getReactionSet(), movedContainer.getID()).getID(); this.reactantOrProduct = reactantOrProduct; } public void redo() { chemModel.getMoleculeSet().removeAtomContainer(movedContainer); IReaction reaction = chemModel.getBuilder().newInstance(IReaction.class); reaction.setID(reactionID); IAtomContainer mol=chemModel.getBuilder().newInstance(IAtomContainer.class,movedContainer); mol.setID(movedContainer.getID()); if(reactantOrProduct) reaction.addReactant(mol); else reaction.addProduct(mol); if(chemModel.getReactionSet()==null) chemModel.setReactionSet(chemModel.getBuilder().newInstance(IReactionSet.class)); chemModel.getReactionSet().addReaction(reaction); chemModel.getMoleculeSet().removeAtomContainer(oldContainer); } public void undo() { if(chemModel.getMoleculeSet()==null) chemModel.setMoleculeSet(chemModel.getBuilder().newInstance(IAtomContainerSet.class)); chemModel.getMoleculeSet().addAtomContainer(oldContainer); chemModel.getReactionSet().removeReaction(ReactionSetManipulator.getReactionByAtomContainerID(chemModel.getReactionSet(), movedContainer.getID())); } public boolean canRedo() { return true; } public boolean canUndo() { return true; } /* * (non-Javadoc) * * @see javax.swing.undo.UndoableEdit#getPresentationName() */ public String description() { return type; } }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/controller/undoredo/LoadNewModelEdit.java
.java
2,701
90
/* $RCSfile$ * $Author: gilleain $ * $Date: 2008-11-26 16:01:05 +0000 (Wed, 26 Nov 2008) $ * $Revision: 13311 $ * * Copyright (C) 2005-2008 Stefan Kuhn * * 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.undoredo; import org.openscience.cdk.interfaces.IAtomContainer; import org.openscience.cdk.interfaces.IChemModel; import org.openscience.cdk.interfaces.IAtomContainerSet; import org.openscience.cdk.interfaces.IReactionSet; import org.openscience.jchempaint.controller.IChemModelRelay; /** * @cdk.module controlextra * @cdk.svnrev $Revision: 10979 $ */ public class LoadNewModelEdit implements IUndoRedoable { private static final long serialVersionUID = -9022673628051651034L; private IChemModel chemModel; private IAtomContainerSet oldsom; private IReactionSet oldsor; private IAtomContainerSet newsom; private IReactionSet newsor; private String type; private IChemModelRelay chemModelRelay = null; public LoadNewModelEdit(IChemModel chemModel, IChemModelRelay relay, IAtomContainerSet oldsom, IReactionSet oldsor, IAtomContainerSet newsom, IReactionSet newsor, String type) { this.chemModel = chemModel; this.newsom=newsom; this.newsor=newsor; this.oldsom=oldsom; this.oldsor=oldsor; this.type=type; this.chemModelRelay = relay; } public void redo() { if (chemModelRelay != null) { for (IAtomContainer ac : newsom.atomContainers()) { chemModelRelay.updateAtoms(ac, ac.atoms()); } } chemModel.setMoleculeSet(newsom); chemModel.setReactionSet(newsor); } public void undo() { if (chemModelRelay != null) { for (IAtomContainer ac : oldsom.atomContainers()) { chemModelRelay.updateAtoms(ac, ac.atoms()); } } chemModel.setMoleculeSet(oldsom); chemModel.setReactionSet(oldsor); } public boolean canRedo() { return true; } public boolean canUndo() { return true; } public String description() { return type; } }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/controller/undoredo/ChangeIsotopeEdit.java
.java
2,237
85
/* $RCSfile$ * $Author: gilleain $ * $Date: 2008-11-26 16:01:05 +0000 (Wed, 26 Nov 2008) $ * $Revision: 13311 $ * * Copyright (C) 2005-2008 Tobias Helmus, Stefan Kuhn * * 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.undoredo; import org.openscience.cdk.interfaces.IAtom; /** * Undo/Redo Edit class for the ChangeIsotopeAction, containing the methods for * undoing and redoing the regarding changes * * @cdk.module controlextra * @cdk.svnrev $Revision: 10979 $ */ public class ChangeIsotopeEdit implements IUndoRedoable { private static final long serialVersionUID = -8177452346351978213L; private IAtom atom; private Integer formerIsotopeNumber; private Integer isotopeNumber; private String type; /** * @param atom * The atom been changed * @param formerIsotopeNumber * The former mass number * @param isotopeNumber * The new mass number */ public ChangeIsotopeEdit(IAtom atom, Integer formerIsotopeNumber, Integer isotopeNumber, String type) { this.atom = atom; this.formerIsotopeNumber = formerIsotopeNumber; this.isotopeNumber = isotopeNumber; this.type=type; } public void redo() { this.atom.setMassNumber(isotopeNumber); } public void undo() { this.atom.setMassNumber(formerIsotopeNumber); } public boolean canRedo() { return true; } public boolean canUndo() { return true; } public String description() { return type; } }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/controller/undoredo/UndoRedoHandler.java
.java
2,122
67
/* * $RCSfile$ * $Author: egonw $ * $Date: 2007-01-04 17:26:00 +0000 (Thu, 04 Jan 2007) $ * $Revision: 7634 $ * * Copyright (C) 1997-2008 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.undoredo; import java.util.ArrayList; import java.util.List; /** * This class needs to be passed to all controller modules, who want to/need to post * undo/redoable events. Applications register an IUndoListener on this and pass the edits * to the actual undo/redo implementation (provided e. g. by swing or swt). * * @cdk.module control */ public class UndoRedoHandler { List<IUndoListener> undoListeners=new ArrayList<IUndoListener>(); /** * Only constructor * * @param c2dm The Controller2dModel of the current application */ public UndoRedoHandler() { } public void addIUndoListener(IUndoListener listener){ undoListeners.add(listener); } public void postEdit(IUndoRedoable edit) { for(IUndoListener listener:undoListeners){ listener.doUndo(edit); } } }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/controller/undoredo/AddSingleElectronEdit.java
.java
3,779
122
/* $RCSfile$ * $Author: gilleain $ * $Date: 2008-11-26 16:01:05 +0000 (Wed, 26 Nov 2008) $ * $Revision: 13311 $ * * Copyright (C) 2005-2008 Tobias Helmus, Stefan Kuhn * * 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.undoredo; import org.openscience.cdk.interfaces.IAtom; import org.openscience.cdk.interfaces.IAtomContainer; import org.openscience.cdk.interfaces.IElectronContainer; import org.openscience.jchempaint.controller.IChemModelRelay; /** * Undo/Redo Edit class for change single electrons, containing the methods * for undoing and redoing the regarding changes. * * @cdk.module controlbasic * @cdk.svnrev $Revision: 10979 $ */ public class AddSingleElectronEdit implements IUndoRedoable { private static final long serialVersionUID = 2348438340238651134L; private IAtomContainer container; private IElectronContainer electronContainer; private String type; private boolean addSingleElectron; private IChemModelRelay chemModelRelay; private IAtom atom; /** * @param relevantContainer - * The container the changes were made * @param electronContainer - * AtomContainer containing the SingleElectron * @param addSingleElectron true=single electron was added, false=was removed. * @param chemModelRelay The current chemModelRelay. * @param atom The atom the change was done on. * @param type A string representing this edit, to be displayed * in GUI. */ public AddSingleElectronEdit(IAtomContainer relevantContainer, IElectronContainer electronContainer, boolean addSingleElectron, IChemModelRelay chemModelRelay, IAtom atom, String type) { this.container = relevantContainer; this.electronContainer = electronContainer; this.addSingleElectron = addSingleElectron; this.type = type; this.atom = atom; this.chemModelRelay = chemModelRelay; } /* (non-Javadoc) * @see org.openscience.cdk.controller.undoredo.IUndoRedoable#redo() */ public void redo(){ if(addSingleElectron) container.addElectronContainer(electronContainer); else container.removeElectronContainer(electronContainer); chemModelRelay.updateAtom(atom); } /* (non-Javadoc) * @see org.openscience.cdk.controller.undoredo.IUndoRedoable#undo() */ public void undo(){ if(addSingleElectron) container.removeElectronContainer(electronContainer); else container.addElectronContainer(electronContainer); chemModelRelay.updateAtom(atom); } /* (non-Javadoc) * @see org.openscience.cdk.controller.undoredo.IUndoRedoable#canRedo() */ public boolean canRedo() { return true; } /* (non-Javadoc) * @see org.openscience.cdk.controller.undoredo.IUndoRedoable#canUndo() */ public boolean canUndo() { return true; } /** * A string representing this edit, to be displayed in GUI. * * @return The presentation string. */ public String description() { return type; } }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/controller/undoredo/MoveAtomEdit.java
.java
2,147
80
/* $RCSfile$ * $Author: egonw $ * $Date: 2008-05-12 07:29:49 +0100 (Mon, 12 May 2008) $ * $Revision: 10979 $ * * 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.undoredo; import javax.vecmath.Vector2d; import org.openscience.cdk.interfaces.IAtom; import org.openscience.cdk.interfaces.IAtomContainer; /** * @cdk.module controlbasic * @cdk.svnrev $Revision: 10979 $ */ public class MoveAtomEdit implements IUndoRedoable { private static final long serialVersionUID = -2277790465507859547L; private IAtomContainer undoRedoSet; private Vector2d offset; private String type; public MoveAtomEdit(IAtomContainer undoRedoSet, Vector2d offset, String type) { this.undoRedoSet = undoRedoSet; this.offset=offset; this.type=type; } public void redo() { for (int i = 0; i < undoRedoSet.getAtomCount(); i++) { IAtom atom=undoRedoSet.getAtom(i); atom.getPoint2d().x+=offset.x; atom.getPoint2d().y+=offset.y; } } public void undo() { for (int i = 0; i < undoRedoSet.getAtomCount(); i++) { IAtom atom=undoRedoSet.getAtom(i); atom.getPoint2d().x-=offset.x; atom.getPoint2d().y-=offset.y; } } public boolean canRedo() { return true; } public boolean canUndo() { return true; } public String description() { return type; } }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/controller/undoredo/RemoveAtomsAndBondsEdit.java
.java
5,449
158
/* $RCSfile$ * $Author: egonw $ * $Date: 2008-05-12 07:29:49 +0100 (Mon, 12 May 2008) $ * $Revision: 10979 $ * * 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.undoredo; import java.util.ArrayList; import java.util.Comparator; import java.util.Iterator; import java.util.List; import org.openscience.cdk.exception.CDKException; import org.openscience.cdk.graph.ConnectivityChecker; 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.tools.manipulator.ChemModelManipulator; import org.openscience.jchempaint.AtomBondSet; import org.openscience.jchempaint.controller.IChemModelRelay; import org.openscience.jchempaint.renderer.JChemPaintRendererModel; /** * @cdk.module controlbasic * @cdk.svnrev $Revision: 10979 $ */ public class RemoveAtomsAndBondsEdit implements IUndoRedoable { private static final long serialVersionUID = -143712173063846054L; private String type; private AtomBondSet undoRedoSet; private IChemModel chemModel; private IAtomContainer container; private IChemModelRelay chemModelRelay=null; public RemoveAtomsAndBondsEdit(IChemModel chemModel, AtomBondSet undoRedoSet, String type, IChemModelRelay chemModelRelay) { this.chemModel = chemModel; this.undoRedoSet = undoRedoSet; this.container = chemModel.getBuilder().newInstance(IAtomContainer.class); Iterator<IAtomContainer> containers = ChemModelManipulator.getAllAtomContainers(chemModel).iterator(); while (containers.hasNext()) { container.add((IAtomContainer)containers.next()); } this.type = type; this.chemModelRelay=chemModelRelay; } public void redo() { List<IAtom> leftOver = new ArrayList<>(); for (IBond bond : undoRedoSet.bonds()) { container.removeBond(bond); if (undoRedoSet.contains(bond.getBegin()) && !undoRedoSet.contains(bond.getEnd())) { leftOver.add(bond.getEnd()); } else if (undoRedoSet.contains(bond.getEnd()) && !undoRedoSet.contains(bond.getBegin())) { leftOver.add(bond.getBegin()); } } for (IAtom atom : undoRedoSet.atoms()) { container.removeAtom(atom); } chemModelRelay.updateAtoms(container, container.atoms()); IAtomContainer molecule = container.getBuilder().newInstance(IAtomContainer.class,container); IAtomContainerSet moleculeSet = ConnectivityChecker.partitionIntoMolecules(molecule); chemModel.setMoleculeSet(moleculeSet); if (chemModelRelay.getRGroupHandler() != null) { try { chemModelRelay.getRGroupHandler().adjustAtomContainers(moleculeSet); } catch (CDKException e) { chemModelRelay.unsetRGroupHandler(); } } JChemPaintRendererModel model = chemModelRelay.getRenderer().getRenderer2DModel(); if (undoRedoSet.contains(model.getHighlightedAtom())) { // select the last atom if the hotspot was deleted by this redo if (!leftOver.isEmpty()) { leftOver.sort(Comparator.comparing(IAtom::getIndex)); IAtom hgAtom = leftOver.get(leftOver.size() - 1); IAtomContainer containerToAddTo = ChemModelManipulator.getRelevantAtomContainer(chemModel, hgAtom); model.setHighlightedAtom(containerToAddTo.getAtom(containerToAddTo.indexOf(hgAtom))); } else { for (IAtomContainer container : ChemModelManipulator.getAllAtomContainers(chemModelRelay.getIChemModel())) { if (!container.isEmpty()) { chemModelRelay.getRenderer().getRenderer2DModel() .setHighlightedAtom(container.getAtom(container.getAtomCount() - 1)); } } } } } public void undo() { for (IAtom atom : undoRedoSet.atoms()) { container.addAtom(atom); } for (IBond bond : undoRedoSet.bonds()) { container.addBond(bond); } chemModelRelay.updateAtoms(container, container.atoms()); IAtomContainer molecule = container.getBuilder().newInstance(IAtomContainer.class,container); IAtomContainerSet moleculeSet = ConnectivityChecker .partitionIntoMolecules(molecule); chemModel.setMoleculeSet(moleculeSet); if (chemModelRelay.getRGroupHandler()!=null) { try { chemModelRelay.getRGroupHandler().adjustAtomContainers(moleculeSet); } catch (CDKException e) { chemModelRelay.unsetRGroupHandler(); e.printStackTrace(); } } } public boolean canRedo() { return true; } public boolean canUndo() { return true; } public String description() { return type; } }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/controller/undoredo/RGroupEdit.java
.java
8,791
238
/* * 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.controller.undoredo; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import org.openscience.cdk.CDKConstants; import org.openscience.cdk.interfaces.IAtom; import org.openscience.cdk.interfaces.IAtomContainer; import org.openscience.cdk.interfaces.IBond; import org.openscience.cdk.isomorphism.matchers.IRGroup; import org.openscience.cdk.isomorphism.matchers.IRGroupQuery; import org.openscience.cdk.isomorphism.matchers.RGroup; import org.openscience.cdk.isomorphism.matchers.RGroupList; import org.openscience.jchempaint.controller.IChemModelRelay; import org.openscience.jchempaint.rgroups.RGroupHandler; /** * Undo-redo class for clicking together an R-Group query in JCP. * @author markr */ public class RGroupEdit implements IUndoRedoable { private String type; private boolean isNewRgrp; private IChemModelRelay hub; private RGroupHandler rgrpHandler; private Map<IAtom,IAtomContainer> existingAtomDistr; private Map<IBond,IAtomContainer> existingBondDistr; private IAtomContainer existingRoot; private Map<IAtom, Map<Integer, IBond>> oldRootAttachmentPoints; private Map<IAtom, Map<Integer, IBond>> newRootAttachmentPoints; private Map<Integer,RGroupList> existingRgroupLists =null; private Map<RGroup, Map<Integer,IAtom>> existingRGroupApo; private IAtomContainer redoRootStructure; private Map<IAtom, Map<Integer, IBond>> redoRootAttachmentPoints; private Map<Integer,RGroupList> redoRgroupLists =null; private Map<RGroup, Map<Integer,IAtom>> redoRGroupApo=null; private IAtomContainer userSelection; public RGroupEdit(String _type , boolean _isNewRgrp , IChemModelRelay _hub , RGroupHandler _rgrpHandler , Map<IAtom,IAtomContainer> _existingAtomDistr , Map<IBond,IAtomContainer> _existingBondDistr , IAtomContainer _existingRoot , Map<IAtom, Map<Integer, IBond>> oldBondApos , Map<IAtom, Map<Integer, IBond>> newBondApos , Map<RGroup, Map<Integer,IAtom>> _existingRGroupApo , Map<Integer,RGroupList> _existingRgroupLists , IAtomContainer _userSelection ) { this.type=_type; this.isNewRgrp=_isNewRgrp; this.hub=_hub; this.rgrpHandler=_rgrpHandler; this.existingRoot=_existingRoot; this.oldRootAttachmentPoints =oldBondApos; this.newRootAttachmentPoints =newBondApos; this.existingRGroupApo=_existingRGroupApo; this.existingAtomDistr=_existingAtomDistr; this.existingBondDistr=_existingBondDistr; this.existingRgroupLists=_existingRgroupLists; this.redoRootStructure=rgrpHandler.getrGroupQuery().getRootStructure(); this.userSelection=(IAtomContainer)_userSelection; if (_existingRgroupLists!=null) { redoRgroupLists = new HashMap<Integer,RGroupList>(); for (Iterator<Integer> itr=rgrpHandler.getrGroupQuery().getRGroupDefinitions().keySet().iterator(); itr.hasNext();) { int rNum=itr.next(); redoRgroupLists.put(rNum, (RGroupList) rgrpHandler.getrGroupQuery().getRGroupDefinitions().get(rNum)); } } if(existingRGroupApo!=null) { RGroup undoRGroup=existingRGroupApo.keySet().iterator().next(); for (Iterator<Integer> rnumItr= hub.getRGroupHandler().getrGroupQuery().getRGroupDefinitions().keySet().iterator(); rnumItr.hasNext();) { for (IRGroup irgrp : hub.getRGroupHandler().getrGroupQuery().getRGroupDefinitions().get(rnumItr.next()).getRGroups()) { RGroup rgrp = (RGroup) irgrp; if(rgrp.equals(undoRGroup)) { redoRGroupApo= new HashMap <RGroup,Map<Integer,IAtom>>(); HashMap<Integer,IAtom> map = new HashMap<Integer,IAtom>(); map.put(1, rgrp.getFirstAttachmentPoint()); map.put(2, rgrp.getSecondAttachmentPoint()); redoRGroupApo.put(rgrp,map); } } } } } /** * Undo actions */ public void undo() { IRGroupQuery rgrpQ = rgrpHandler.getrGroupQuery(); if (type.equals("setSubstitute")||type.equals("setRoot")) { this.redoRootAttachmentPoints=rgrpHandler.getrGroupQuery().getRootAttachmentPoints(); for (Iterator<IAtom> atItr = existingAtomDistr.keySet().iterator(); atItr.hasNext();) { IAtom atom = atItr.next(); existingAtomDistr.get(atom).addAtom(atom); } for (Iterator<IBond> bndItr = existingBondDistr.keySet().iterator(); bndItr.hasNext();) { IBond bond = bndItr.next(); existingBondDistr.get(bond).addBond(bond); } hub.getChemModel().getMoleculeSet().removeAtomContainer(userSelection); if (type.equals("setRoot")) { if (isNewRgrp) { rgrpQ.setRootStructure(null); rgrpQ.setRootAttachmentPoints(null); for (IAtomContainer atc: hub.getIChemModel().getMoleculeSet().atomContainers()) { atc.removeProperty(CDKConstants.TITLE); } hub.unsetRGroupHandler(); } else { existingRoot.setProperty(CDKConstants.TITLE,RGroup.ROOT_LABEL); rgrpQ.setRootStructure(existingRoot); rgrpQ.setRootAttachmentPoints(oldRootAttachmentPoints); } } else if (type.equals("setSubstitute")) { if (existingRgroupLists !=null) { for(Iterator<Integer> rNums=existingRgroupLists.keySet().iterator(); rNums.hasNext();){ int rNum= rNums.next(); rgrpQ.getRGroupDefinitions().put(rNum, existingRgroupLists.get(rNum)); } } } } else if (type.startsWith("setBondApoAction")) { rgrpQ.setRootAttachmentPoints(oldRootAttachmentPoints); } else if (type.equals("clearRgroup")) { hub.setRGroupHandler(rgrpHandler); rgrpQ.getRootStructure().setProperty(CDKConstants.TITLE, RGroup.ROOT_LABEL); for (Iterator<Integer> rnumItr= hub.getRGroupHandler().getrGroupQuery().getRGroupDefinitions().keySet().iterator(); rnumItr.hasNext();) { int rNum=rnumItr.next(); for (IRGroup rgrp: hub.getRGroupHandler().getrGroupQuery().getRGroupDefinitions().get(rNum).getRGroups()) { rgrp.getGroup().setProperty(CDKConstants.TITLE,RGroup.makeLabel(rNum)); } } } } /** * Redo actions */ public void redo() { if(type.equals("setRoot")||type.equals("setSubstitute")) { if (isNewRgrp) { hub.setRGroupHandler(rgrpHandler); } IRGroupQuery rgrpQ= rgrpHandler.getrGroupQuery(); for (Iterator<IAtom> atItr = existingAtomDistr.keySet().iterator(); atItr.hasNext();) { IAtom atom = atItr.next(); existingAtomDistr.get(atom).removeAtom(atom); } for (Iterator<IBond> bndItr = existingBondDistr.keySet().iterator(); bndItr.hasNext();) { IBond bond = bndItr.next(); existingBondDistr.get(bond).removeBond(bond); } hub.getChemModel().getMoleculeSet().addAtomContainer(userSelection); if (type.equals("setRoot")) { rgrpQ.setRootStructure(redoRootStructure); rgrpQ.getRootStructure().setProperty(CDKConstants.TITLE,RGroup.ROOT_LABEL); rgrpQ.setRootAttachmentPoints(redoRootAttachmentPoints); } else if (type.equals("setSubstitute")) { if (redoRgroupLists !=null) { for(Iterator<Integer> rNums=redoRgroupLists.keySet().iterator(); rNums.hasNext();){ int rNum= rNums.next(); rgrpQ.getRGroupDefinitions().put(rNum, redoRgroupLists.get(rNum)); } } } } else if (type.startsWith("setBondApoAction")) { IRGroupQuery rgrpQ = rgrpHandler.getrGroupQuery(); rgrpQ.setRootAttachmentPoints(newRootAttachmentPoints); } else if (type.equals("clearRgroup")) { hub.unsetRGroupHandler(); } } public boolean canRedo() { return true; } public boolean canUndo() { return true; } public String description() { return type; } }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/renderer/JCPAction2D.java
.java
9,119
353
/* * $RCSfile$ * $Author: egonw $ * $Date: 2007-01-04 18:26:00 +0100 (do, 04 jan 2007) $ * $Revision: 7634 $ * * Copyright (C) 1997-2007 The JChemPaint project * * 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.renderer; import java.awt.Container; import java.awt.event.ActionEvent; import java.util.Hashtable; import javax.swing.AbstractAction; import javax.swing.JFrame; 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.controller.CDKPopupMenu; /** * Superclass of all JChemPaint GUI actions * * @cdk.module jchempaint * @cdk.githash * @author steinbeck */ public class JCPAction2D extends AbstractAction { private static final long serialVersionUID = -4056416630614934238L; /** * Description of the Field */ public final static String actionSuffix = "Action"; /** * Description of the Field */ public final static String imageSuffix = "Image"; /** * Description of the Field */ public final static String labelSuffix = "Label"; /** * Description of the Field */ private static ILoggingTool logger = LoggingToolFactory.createLoggingTool(JCPAction2D.class); private Hashtable<String, JCPAction2D> actions = null; private Hashtable<String, JCPAction2D> popupActions = null; /** * Description of the Field */ protected String type; /** * Description of the Field */ //protected JChemPaintPanel jcpPanel = null; protected JFrame 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 JCPAction2D(JFrame jcpPanel, String type, boolean isPopupAction) { super(); if (this.actions == null) { this.actions = new Hashtable<String, JCPAction2D>(); } if (this.popupActions == null) { this.popupActions = new Hashtable<String, JCPAction2D>(); } 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 JCPAction2D(JFrame jcpPanel, boolean isPopupAction) { this(jcpPanel, "", isPopupAction); } /** * Constructor for the JCPAction object * *@param jcpPanel Description of the Parameter */ public JCPAction2D(JFrame jcpPanel) { this(jcpPanel, false); } /** * Constructor for the JCPAction object */ public JCPAction2D() { 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(JFrame 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 CDKPopupMenu) { return ((CDKPopupMenu) 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 CDKPopupMenu)) { logger.debug(" Parent instanceof ", parent.getClass().getName()); if (parent instanceof JPopupMenu) { parent = ((JPopupMenu) parent).getInvoker().getParent(); } /*else if (parent instanceof JChemPaintMenuBar) { logger.warn(" Source is MenuBar. MenuBar items don't know about the source"); return null; }*/ else { logger.error(" Cannot get parent!"); return null; } } return ((CDKPopupMenu) 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 JCPAction2D getAction(JFrame jcpPanel, String actionname, boolean isPopupAction) { // make sure logger and actions are instantiated JCPAction2D dummy = new JCPAction2D(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 whether 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 (JCPAction2D) actions.get(actionname); } else if (isPopupAction && popupActions.containsKey(actionname)) { logger.debug("Taking JCPAction from popup cache for:", actionname); return (JCPAction2D) 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 JCPAction2D) { JCPAction2D a = (JCPAction2D) 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 JCPAction2D getAction(JFrame jcpPanel, String actionname) { return getAction(jcpPanel, actionname, false); } }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/undoredo/SwingUndoableEdit.java
.java
2,824
106
/* * Copyright (C) 2025 John Mayfield * * 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.undoredo; import org.openscience.jchempaint.controller.undoredo.IUndoRedoable; import javax.swing.undo.CannotRedoException; import javax.swing.undo.CannotUndoException; import javax.swing.undo.UndoableEdit; /** * This adapter allows us to wrap anu IUndoRedoable for usage in Java Swing * with sensible defaults. * * @author John Mayfield */ public class SwingUndoableEdit implements UndoableEdit, IUndoRedoable { private final IUndoRedoable undoRedoable; public SwingUndoableEdit(IUndoRedoable undoRedoable) { this.undoRedoable = undoRedoable; } @Override public void undo() throws CannotUndoException { undoRedoable.undo(); } @Override public boolean canUndo() { return undoRedoable.canUndo(); } @Override public void redo() throws CannotRedoException { undoRedoable.redo(); } @Override public boolean canRedo() { return undoRedoable.canRedo(); } @Override public void die() { } @Override public boolean addEdit(UndoableEdit anEdit) { return false; } @Override public boolean replaceEdit(UndoableEdit anEdit) { return false; } @Override public boolean isSignificant() { return true; } @Override public String description() { return undoRedoable.description(); } @Override public String getUndoPresentationName() { return description(); } @Override public String getRedoPresentationName() { return description(); } @Override public String getPresentationName() { return description(); } }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/undoredo/SwingUndoRedoFactory.java
.java
9,330
166
/* * $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.undoredo; import java.util.Collections; import java.util.List; import java.util.Map; import javax.vecmath.Point2d; import javax.vecmath.Vector2d; 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.IElectronContainer; import org.openscience.cdk.interfaces.IAtomContainerSet; import org.openscience.cdk.interfaces.IReactionSet; import org.openscience.cdk.isomorphism.matchers.RGroup; import org.openscience.cdk.isomorphism.matchers.RGroupList; import org.openscience.jchempaint.AtomBondSet; import org.openscience.jchempaint.controller.IChemModelRelay; import org.openscience.jchempaint.controller.undoredo.*; import org.openscience.jchempaint.rgroups.RGroupHandler; /** * A class returning Swing-Implementations of all the undo-redo edits */ public class SwingUndoRedoFactory implements IUndoRedoFactory { public IUndoRedoable getAddAtomsAndBondsEdit(IChemModel chemModel, AtomBondSet undoRedoSet, IAtomContainer removedAtomContainer, String type, IChemModelRelay c2dm) { return new SwingUndoableEdit(new AddAtomsAndBondsEdit(chemModel, undoRedoSet, removedAtomContainer, type, c2dm)); } public IUndoRedoable getAdjustBondOrdersEdit(Map<IBond, IBond.Order[]> orderChanges, Map<IBond, IBond.Display[]> displayChanges, String type, IChemModelRelay chemModelRelay) { return new SwingUndoableEdit(new AdjustBondOrdersEdit(orderChanges, Collections.emptyMap(), displayChanges, type, chemModelRelay)); } public IUndoRedoable getChangeAtomSymbolEdit(IAtom atom, String formerSymbol, String symbol, String type, IChemModelRelay chemModelRelay) { return new SwingUndoableEdit(new ChangeAtomSymbolEdit(atom, formerSymbol, symbol, type, chemModelRelay)); } public IUndoRedoable getChangeChargeEdit(IAtom atomInRange, int formerCharge, int newCharge, String type, IChemModelRelay chemModelRelay) { return new SwingUndoableEdit(new ChangeChargeEdit(atomInRange, formerCharge, newCharge, type, chemModelRelay)); } public IUndoRedoable getMoveAtomEdit(IAtomContainer undoRedoSet, Vector2d offset, String type) { return new SwingUndoableEdit(new MoveAtomEdit(undoRedoSet, offset, type)); } public IUndoRedoable getRemoveAtomsAndBondsEdit(IChemModel chemModel, AtomBondSet undoRedoSet, String type, IChemModelRelay chemModelRelay) { return new SwingUndoableEdit(new RemoveAtomsAndBondsEdit(chemModel, undoRedoSet, type, chemModelRelay)); } public IUndoRedoable getReplaceAtomEdit(IChemModel chemModel, IAtom oldAtom, IAtom newAtom, String type) { return new SwingUndoableEdit(new ReplaceAtomEdit(chemModel, oldAtom, newAtom, type)); } public IUndoRedoable getSingleElectronEdit( IAtomContainer relevantContainer, IElectronContainer electronContainer, boolean addSingleElectron, IChemModelRelay chemModelRelay, IAtom atom, String type) { return new SwingUndoableEdit(new AddSingleElectronEdit(relevantContainer, electronContainer, addSingleElectron, chemModelRelay, atom, type)); } public IUndoRedoable getChangeIsotopeEdit(IAtom atom, Integer formerIsotopeNumber, Integer newIstopeNumber, String type) { return new SwingUndoableEdit(new ChangeIsotopeEdit(atom, formerIsotopeNumber, newIstopeNumber, type)); } public IUndoRedoable getClearAllEdit(IChemModel chemModel, IAtomContainerSet som, IReactionSet sor, String type) { return new SwingUndoableEdit(new ClearAllEdit(chemModel, som, sor, type)); } public IUndoRedoable getChangeCoordsEdit(Map<IAtom, Point2d[]> atomCoordsMap, Map<IBond, IBond.Stereo> bondStereo, String type) { return new SwingUndoableEdit(new ChangeCoordsEdit(atomCoordsMap, bondStereo, type)); } public IUndoRedoable getMakeReactantOrProductInNewReactionEdit(IChemModel chemModel, IAtomContainer ac, IAtomContainer oldcontainer, boolean reactantOrProduct, String type) { return new SwingUndoableEdit(new MakeReactantOrProductInNewReactionEdit(chemModel, ac, oldcontainer, reactantOrProduct, type)); } public IUndoRedoable getMakeReactantOrProductInExistingReactionEdit( IChemModel chemModel, IAtomContainer newContainer, IAtomContainer oldcontainer, String s, boolean reactantOrProduct, String type) { return new SwingUndoableEdit(new MakeReactantOrProductInExistingReactionEdit(chemModel, newContainer, oldcontainer, s, reactantOrProduct, type)); } public IUndoRedoable getMergeMoleculesEdit(List<IAtom> deletedAtom, List<IAtomContainer> containers, List<IAtomContainer> droppedContainers, List<List<IBond>> deletedBonds, List<Map<IBond, Integer>> bondsWithReplacedAtom, Vector2d offset, List<IAtom> atomwhichwasmoved, IUndoRedoable moveundoredo, Map<Integer, Map<Integer, Integer>> oldRgrpHash, Map<Integer, Map<Integer, Integer>> newRgrpHash, String type, IChemModelRelay c2dm) { return new SwingUndoableEdit(new MergeMoleculesEdit(deletedAtom, containers, droppedContainers, deletedBonds, bondsWithReplacedAtom, offset, atomwhichwasmoved, moveundoredo, oldRgrpHash, newRgrpHash, type, c2dm)); } public IUndoRedoable getChangeHydrogenCountEdit( Map<IAtom, Integer[]> atomHydrogenCountsMap, String type) { return new SwingUndoableEdit(new ChangeHydrogenCountEdit(atomHydrogenCountsMap, type)); } public IUndoRedoable getLoadNewModelEdit(IChemModel chemModel, IChemModelRelay relay, IAtomContainerSet oldsom, IReactionSet oldsor, IAtomContainerSet newsom, IReactionSet newsor, String type) { return new SwingUndoableEdit(new LoadNewModelEdit(chemModel, relay, oldsom, oldsor, newsom, newsor, type)); } public IUndoRedoable getChangeValenceEdit(IAtom atomInRange, Integer formerValence, Integer valence, String text, IChemModelRelay chemModelRelay) { return new SwingUndoableEdit(new ChangeValenceEdit(atomInRange, formerValence, valence, text, chemModelRelay)); } public IUndoRedoable getRGroupEdit(String type, boolean isNewRGroup, IChemModelRelay hub, RGroupHandler rgrpHandler , Map<IAtom, IAtomContainer> existingAtomDistr, Map<IBond, IAtomContainer> existingBondDistr , IAtomContainer existingRoot, Map<IAtom, Map<Integer, IBond>> oldRootApos, Map<IAtom, Map<Integer, IBond>> newRootApos, Map<RGroup, Map<Integer, IAtom>> existingRGroupApo, Map<Integer, RGroupList> rgroupLists, IAtomContainer userSelection) { return new SwingUndoableEdit(new RGroupEdit(type, isNewRGroup, hub, rgrpHandler , existingAtomDistr, existingBondDistr, existingRoot, oldRootApos, newRootApos , existingRGroupApo, rgroupLists, userSelection)); } }
Java
2D
JChemPaint/jchempaint
core/src/main/java/org/openscience/jchempaint/application/JChemPaint.java
.java
31,572
770
/* * $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.application; import com.formdev.flatlaf.util.SystemInfo; import com.formdev.flatlaf.util.UIScale; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.OptionBuilder; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.apache.commons.cli.PosixParser; import org.apache.commons.cli.UnrecognizedOptionException; import org.openscience.cdk.AtomContainer; import org.openscience.cdk.AtomContainerSet; import org.openscience.cdk.ChemFile; import org.openscience.cdk.ChemModel; import org.openscience.cdk.DefaultChemObjectBuilder; import org.openscience.cdk.atomtype.CDKAtomTypeMatcher; 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.IAtomContainerSet; import org.openscience.cdk.interfaces.IAtomType; import org.openscience.cdk.interfaces.IChemFile; 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.cdk.interfaces.IReactionSet; import org.openscience.cdk.io.CMLReader; import org.openscience.cdk.io.ISimpleChemObjectReader; import org.openscience.cdk.io.RGroupQueryReader; import org.openscience.cdk.io.SMILESReader; import org.openscience.cdk.isomorphism.matchers.IRGroupQuery; import org.openscience.cdk.isomorphism.matchers.RGroupQuery; import org.openscience.cdk.layout.StructureDiagramGenerator; import org.openscience.cdk.tools.CDKHydrogenAdder; import org.openscience.cdk.tools.manipulator.ChemModelManipulator; import org.openscience.cdk.tools.manipulator.ReactionSetManipulator; import org.openscience.jchempaint.AbstractJChemPaintPanel; import org.openscience.jchempaint.AtomBondSet; import org.openscience.jchempaint.GT; import org.openscience.jchempaint.JCPPropertyHandler; import org.openscience.jchempaint.JChemPaintPanel; import org.openscience.jchempaint.controller.ControllerHub; import org.openscience.jchempaint.controller.undoredo.IUndoRedoFactory; import org.openscience.jchempaint.controller.undoredo.IUndoRedoable; import org.openscience.jchempaint.controller.undoredo.UndoRedoHandler; import org.openscience.jchempaint.dialog.WaitDialog; import org.openscience.jchempaint.inchi.InChITool; import org.openscience.jchempaint.io.FileHandler; import org.openscience.jchempaint.rgroups.RGroupHandler; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.UIManager; import javax.vecmath.Point2d; import java.awt.Dimension; import java.awt.GraphicsDevice; import java.awt.GraphicsEnvironment; import java.awt.Point; import java.awt.Rectangle; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileReader; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Properties; public class JChemPaint { public static int instancecounter = 1; public static List<JFrame> frameList = new ArrayList<JFrame>(); public final static String GUI_APPLICATION="application"; @SuppressWarnings("static-access") public static void main(String[] args) { try { String vers = System.getProperty("java.version"); String requiredJVM = "1.5.0"; Package self = Package.getPackage("org.openscience.jchempaint"); String version = GT.get("Could not determine JCP version"); if (self != null) version = JCPPropertyHandler.getInstance(true).getVersion(); if (vers.compareTo(requiredJVM) < 0) { System.err.println(GT.get("WARNING: JChemPaint {0} must be run with a Java VM version {1} or higher.", new String[]{version, requiredJVM})); System.err.println(GT.get("Your JVM version is {0}", vers)); System.exit(1); } Options options = new Options(); options.addOption("h", "help", false, GT.get("gives this help page")); options.addOption("v", "version", false, GT .get("gives JChemPaints version number")); options.addOption("d", "debug", false, "switches on various debug options"); options.addOption(OptionBuilder.withArgName("property=value") .hasArg().withValueSeparator().withDescription( GT.get("supported options are given below")).create( "D")); CommandLine line = null; try { CommandLineParser parser = new PosixParser(); line = parser.parse(options, args); } catch (UnrecognizedOptionException exception) { System.err.println(exception.getMessage()); System.exit(-1); } catch (ParseException exception) { System.err.println("Unexpected exception: " + exception.toString()); } if (line.hasOption("v")) { System.out.println("JChemPaint v." + version + "\n"); System.exit(0); } if (line.hasOption("h")) { System.out.println("JChemPaint v." + version + "\n"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("JChemPaint", options); // now report on the -D options System.out.println(); System.out .println("The -D options are as follows (defaults in parathesis):"); System.out.println(" cdk.debugging [true|false] (false)"); System.out.println(" cdk.debug.stdout [true|false] (false)"); System.out.println(" user.language [ar|ca|cs|de|en|es|hu|nb|nl|pl|pt|ru|th] (en)"); System.out.println(" user.language [ar|ca|cs|de|hu|nb|nl|pl|pt_BR|ru|th] (EN)"); System.exit(0); } boolean debug = false; if (line.hasOption("d")) { debug = true; } // Set Look&Feel Properties props = JCPPropertyHandler.getInstance(true).getJCPProperties(); try { UIManager.setLookAndFeel(props.getProperty("LookAndFeelClass")); } catch (Throwable e) { String sys = UIManager.getSystemLookAndFeelClassName(); UIManager.setLookAndFeel(sys); props.setProperty("LookAndFeelClass", sys); } // Language props.setProperty("General.language", System.getProperty("user.language", "en")); // Process command line arguments String modelFilename = ""; args = line.getArgs(); if (args.length > 0) { modelFilename = args[0]; File file = new File(modelFilename); if (!file.exists()) { System.err.println(GT.get("File does not exist") + ": " + modelFilename); System.exit(-1); } showInstance(file, null, null, debug); } else { showEmptyInstance(debug); } } catch (Throwable t) { System.err.println("uncaught exception: " + t); t.printStackTrace(System.err); } } public static void showEmptyInstance(boolean debug) { IChemModel chemModel = emptyModel(); showInstance(chemModel, GT.get("Untitled") + " " + (instancecounter++), debug); } public static IChemModel emptyModel() { IChemModel chemModel = DefaultChemObjectBuilder.getInstance().newInstance(IChemModel.class); chemModel.setMoleculeSet(chemModel.getBuilder().newInstance(IAtomContainerSet.class)); chemModel.getMoleculeSet().addAtomContainer( chemModel.getBuilder().newInstance(IAtomContainer.class)); return chemModel; } public static void showInstance(File inFile, String type, AbstractJChemPaintPanel jcpPanel, boolean debug) { try { IChemModel chemModel = JChemPaint.readFromFile(inFile, type, jcpPanel); String name = inFile.getName(); JChemPaintPanel p = JChemPaint.showInstance(chemModel, name, debug); p.setCurrentWorkDirectory(inFile.getParentFile()); p.setLastOpenedFile(inFile); p.setIsAlreadyAFile(inFile); } catch (CDKException ex) { JOptionPane.showMessageDialog(jcpPanel, ex.getMessage()); return; } catch (FileNotFoundException e) { JOptionPane.showMessageDialog(jcpPanel, GT.get("File does not exist") + ": " + inFile.getPath()); return; } } public static JChemPaintPanel showInstance(JFrame f, IChemModel chemModel, String title, boolean debug) { JChemPaintPanel p = new JChemPaintPanel(chemModel, GUI_APPLICATION, debug, null, new HashSet<>()); p.setName("JChemPaintPanel"); GraphicsDevice gd = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice(); Rectangle bounds = gd.getDefaultConfiguration().getBounds(); float height = UIScale.scale((float)bounds.getHeight()) / 1.2f; f.setPreferredSize(new Dimension((int)Math.floor(height / 1.2f), (int)Math.floor(height))); f.setJMenuBar(p.getJMenuBar()); f.add(p); f.pack(); Point point = GraphicsEnvironment.getLocalGraphicsEnvironment() .getCenterPoint(); int w2 = (f.getWidth() / 2); int h2 = (f.getHeight() / 2); f.setLocation(point.x - w2, point.y - h2); f.setVisible(true); frameList.add(f); return p; } public static JChemPaintPanel showInstance(IChemModel chemModel, String title, boolean debug) { JFrame f = new JFrame(title + " - JChemPaint"); f.setName("JChemPaint"); chemModel.setID(title); f.addWindowListener(new JChemPaintPanel.AppCloser()); f.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); if (SystemInfo.isMacFullWindowContentSupported) { f.getRootPane().putClientProperty("apple.awt.transparentTitleBar", true); } else if (SystemInfo.isWindows) { f.getRootPane().putClientProperty("JRootPane.menuBarEmbedded", false); } return showInstance(f, chemModel, title, debug); } public static IChemModel readFromFileReader(URL fileURL, String url, String type, AbstractJChemPaintPanel panel) throws CDKException { IChemModel chemModel = null; WaitDialog.showDialog(); // InChI workaround - guessing for InChI results into an INChIReader // (this does not work, we'd need an INChIPlainTextReader..) // Instead here we use STDInChIReader, to be consistent throughout JCP // using the nestedVm based classes. try { ISimpleChemObjectReader cor=null; if(url.endsWith("txt")) { chemModel = InChITool.readInChI(fileURL); } else { cor = FileHandler.createReader(fileURL, url,type); chemModel = JChemPaint.getChemModelFromReader(cor,panel); } boolean avoidOverlap=true; if (cor instanceof RGroupQueryReader) avoidOverlap=false; JChemPaint.cleanUpChemModel(chemModel, avoidOverlap, panel); } finally { WaitDialog.hideDialog(); } return chemModel; } /** * Read an IChemModel from a given file. * @param file * @param type * @param panel * @return * @throws CDKException * @throws FileNotFoundException */ public static IChemModel readFromFile(File file, String type, AbstractJChemPaintPanel panel) throws CDKException, FileNotFoundException { String url = file.toURI().toString(); ISimpleChemObjectReader cor = null; try { cor = FileHandler.createReader(file.toURI().toURL(), url, type); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (cor instanceof CMLReader) cor.setReader(new FileInputStream(file)); // hack else cor.setReader(new FileReader(file)); // hack IChemModel chemModel = JChemPaint.getChemModelFromReader(cor,panel); boolean avoidOverlap=true; if (cor instanceof RGroupQueryReader) avoidOverlap=false; JChemPaint.cleanUpChemModel(chemModel, avoidOverlap, panel); return chemModel; } /** * Clean up chemical model ,removing duplicates empty molecules etc * @param chemModel * @param avoidOverlap * @throws CDKException */ public static void cleanUpChemModel(IChemModel chemModel, boolean avoidOverlap, AbstractJChemPaintPanel panel) throws CDKException { JChemPaint.setReactionIDs(chemModel); JChemPaint.replaceReferencesWithClones(chemModel); // check the model is not completely empty if (ChemModelManipulator.getBondCount(chemModel) == 0 && ChemModelManipulator.getAtomCount(chemModel) == 0) { throw new CDKException( "Structure does not have bonds or atoms. Cannot depict structure."); } JChemPaint.removeDuplicateMolecules(chemModel); JChemPaint.checkCoordinates(chemModel); JChemPaint.removeEmptyMolecules(chemModel); if (avoidOverlap) { try { ControllerHub.avoidOverlap(chemModel); } catch (Exception e) { JOptionPane.showMessageDialog(panel, GT.get("Structure could not be generated")); throw new CDKException( "Cannot depict structure"); } } //We update implicit Hs in any case CDKAtomTypeMatcher matcher = CDKAtomTypeMatcher.getInstance(chemModel.getBuilder()); for (IAtomContainer container : ChemModelManipulator.getAllAtomContainers(chemModel)) { for (IAtom atom : container.atoms()) { if (!(atom instanceof IPseudoAtom)) { try { IAtomType type = matcher.findMatchingAtomType( container, atom ); if (type != null && type.getFormalNeighbourCount() != null) { int connectedAtomCount = container.getConnectedAtomsCount(atom); atom.setImplicitHydrogenCount( type.getFormalNeighbourCount() - connectedAtomCount ); } } catch ( CDKException e ) { e.printStackTrace(); } } } } } /** * Returns an IChemModel, using the reader provided (picked). * @param cor * @param panel * @return * @throws CDKException */ public static IChemModel getChemModelFromReader(ISimpleChemObjectReader cor,AbstractJChemPaintPanel panel) throws CDKException { panel.get2DHub().setRGroupHandler(null); String error = null; ChemModel chemModel = null; IChemFile chemFile = null; if (cor.accepts(IChemFile.class) && chemModel==null) { // try to read a ChemFile try { chemFile = (IChemFile) cor.read((IChemObject) new ChemFile()); if (chemFile == null) { error = "The object chemFile was empty unexpectedly!"; } } catch (Exception exception) { error = "Error while reading file: " + exception.getMessage(); exception.printStackTrace(); } } if (error != null) { throw new CDKException(error); } if (chemModel == null && chemFile != null) { chemModel = (ChemModel) chemFile.getChemSequence(0).getChemModel(0); } if (cor.accepts(ChemModel.class) && chemModel==null) { // try to read a ChemModel try { chemModel = (ChemModel) cor.read((IChemObject) new ChemModel()); if (chemModel == null) { error = "The object chemModel was empty unexpectedly!"; } } catch (Exception exception) { error = "Error while reading file: " + exception.getMessage(); exception.printStackTrace(); } } // Smiles reading if (cor.accepts(IAtomContainerSet.class) && chemModel==null) { // try to read a Molecule set try { IAtomContainerSet som = (AtomContainerSet) cor.read(new AtomContainerSet()); chemModel = new ChemModel(); chemModel.setMoleculeSet(som); } catch (Exception exception) { error = "Error while reading file: " + exception.getMessage(); exception.printStackTrace(); } } // MDLV3000 reading if (cor.accepts(IAtomContainer.class) && chemModel==null) { // try to read a Molecule IAtomContainer mol = (AtomContainer) cor.read(new AtomContainer()); if(mol!=null ) try{ IAtomContainerSet newSet = new AtomContainerSet(); newSet.addAtomContainer(mol); chemModel = new ChemModel(); chemModel.setMoleculeSet(newSet); } catch (Exception exception) { error = "Error while reading file: " + exception.getMessage(); exception.printStackTrace(); } } // RGroupQuery reading if (cor.accepts(RGroupQuery.class) && chemModel==null) { IRGroupQuery rgroupQuery = (RGroupQuery) cor.read(new RGroupQuery(DefaultChemObjectBuilder.getInstance())); if(rgroupQuery!=null ) try{ chemModel = new ChemModel(); RGroupHandler rgHandler = new RGroupHandler(rgroupQuery, panel); panel.get2DHub().setRGroupHandler(rgHandler); chemModel.setMoleculeSet(rgHandler.getMoleculeSet(chemModel)); rgHandler.layoutRgroup(); } catch (Exception exception) { error = "Error while reading file: " + exception.getMessage(); exception.printStackTrace(); } } if (error != null) { throw new CDKException(error); } if (chemModel == null && chemFile != null) { chemModel = (ChemModel) chemFile.getChemSequence(0).getChemModel(0); } //SmilesParser sets valencies, switch off by default. if(cor instanceof SMILESReader){ IAtomContainer allinone = JChemPaintPanel.getAllAtomContainersInOne(chemModel); for(int k=0;k<allinone.getAtomCount();k++){ allinone.getAtom(k).setValency(null); } } return chemModel; } private static void positionStructure(IAtomContainer mol) { double minX = Double.MAX_VALUE; double maxY = -Double.MAX_VALUE; for (IAtom atom : mol.atoms()) { minX = Math.min(atom.getPoint2d().x, minX); maxY = Math.max(atom.getPoint2d().y, maxY); } int MARGIN = 1; for (IAtom atom : mol.atoms()) { atom.getPoint2d().x -= minX - MARGIN; atom.getPoint2d().y -= maxY + MARGIN; } } /** * Inserts a molecule into the current set, usually from Combobox or Insert field, with possible * shifting of the existing set. * @param chemPaintPanel * @param molecule * @param generateCoordinates * @param shiftPanel * @throws CDKException */ public static void generateModel(AbstractJChemPaintPanel chemPaintPanel, IAtomContainer molecule, boolean generateCoordinates, boolean shiftPasted) throws CDKException { if (molecule == null) return; if (generateCoordinates) { // now generate 2D coordinates StructureDiagramGenerator sdg = new StructureDiagramGenerator(); try { sdg.setMolecule(molecule); sdg.generateCoordinates(); molecule = sdg.getMolecule(); } catch (Exception exc) { JOptionPane.showMessageDialog(chemPaintPanel, GT.get("Structure could not be generated")); throw new CDKException( "Cannot depict structure"); } } positionStructure(molecule); IChemModel chemModel = chemPaintPanel.getChemModel(); IAtomContainerSet moleculeSet = chemModel.getMoleculeSet(); if (moleculeSet == null) { moleculeSet = new AtomContainerSet(); } // On copy & paste on top of an existing drawn structure, prevent the // pasted section to be drawn exactly on top or to far away from the // original by shifting it to a fixed position next to it. if (shiftPasted) { double maxXCurr = Double.NEGATIVE_INFINITY; double minXPaste = Double.POSITIVE_INFINITY; for (IAtomContainer atc : moleculeSet.atomContainers()) { // Detect the right border of the current structure.. for (IAtom atom : atc.atoms()) { if(atom.getPoint2d().x>maxXCurr) maxXCurr = atom.getPoint2d().x; } // Detect the left border of the pasted structure.. for (IAtom atom : molecule.atoms()) { if(atom.getPoint2d().x<minXPaste) minXPaste = atom.getPoint2d().x; } } if (maxXCurr != Double.NEGATIVE_INFINITY && minXPaste != Double.POSITIVE_INFINITY) { // Shift the pasted structure to be nicely next to the existing one. final int MARGIN=1; final double SHIFT = maxXCurr - minXPaste; for (IAtom atom : molecule.atoms()) { atom.setPoint2d(new Point2d (atom.getPoint2d().x+MARGIN+SHIFT, atom.getPoint2d().y )); } } } if (moleculeSet.getAtomContainer(0).getAtomCount() == 0) { moleculeSet.getAtomContainer(0).add(molecule); moleculeSet.getAtomContainer(0).setTitle(molecule.getTitle()); } else { moleculeSet.addAtomContainer(molecule); } IUndoRedoFactory undoRedoFactory= chemPaintPanel.get2DHub().getUndoRedoFactory(); UndoRedoHandler undoRedoHandler= chemPaintPanel.get2DHub().getUndoRedoHandler(); if (undoRedoFactory!=null) { IUndoRedoable undoredo = undoRedoFactory.getAddAtomsAndBondsEdit(chemPaintPanel.get2DHub().getIChemModel(), new AtomBondSet(molecule), null, "Paste", chemPaintPanel.get2DHub()); undoRedoHandler.postEdit(undoredo); } chemPaintPanel.getChemModel().setMoleculeSet(moleculeSet); chemPaintPanel.updateUndoRedoControls(); chemPaintPanel.get2DHub().updateView(); } private static void setReactionIDs(IChemModel chemModel) { // we give all reactions an ID, in case they have none // IDs are needed for handling in JCP IReactionSet reactionSet = chemModel.getReactionSet(); if (reactionSet != null) { int i = 0; for (IReaction reaction : reactionSet.reactions()) { if (reaction.getID() == null) reaction.setID("Reaction " + (++i)); } } } private static void replaceReferencesWithClones(IChemModel chemModel) throws CDKException { // we make references in products/reactants clones, since same compounds // in different reactions need separate layout (different positions etc) if (chemModel.getReactionSet() != null) { for (IReaction reaction : chemModel.getReactionSet().reactions()) { int i = 0; IAtomContainerSet products = reaction.getProducts(); for (IAtomContainer product : products.atomContainers()) { try { products.replaceAtomContainer(i, (IAtomContainer) product.clone()); } catch (CloneNotSupportedException e) { } i++; } i = 0; IAtomContainerSet reactants = reaction.getReactants(); for (IAtomContainer reactant : reactants.atomContainers()) { try { reactants.replaceAtomContainer(i, (IAtomContainer) reactant.clone()); } catch (CloneNotSupportedException e) { } i++; } } } } private static void removeDuplicateMolecules(IChemModel chemModel) { // we remove molecules which are in MoleculeSet as well as in a reaction IReactionSet reactionSet = chemModel.getReactionSet(); IAtomContainerSet moleculeSet = chemModel.getMoleculeSet(); if (reactionSet != null && moleculeSet != null) { List<IAtomContainer> aclist = ReactionSetManipulator .getAllAtomContainers(reactionSet); for (int i = moleculeSet.getAtomContainerCount() - 1; i >= 0; i--) { for (int k = 0; k < aclist.size(); k++) { String label = moleculeSet.getAtomContainer(i).getID(); if (aclist.get(k).getID().equals(label)) { chemModel.getMoleculeSet().removeAtomContainer(i); break; } } } } } private static void removeEmptyMolecules(IChemModel chemModel) { IAtomContainerSet moleculeSet = chemModel.getMoleculeSet(); if (moleculeSet != null && moleculeSet.getAtomContainerCount() == 0) { chemModel.setMoleculeSet(null); } } private static void checkCoordinates(IChemModel chemModel) throws CDKException { for (IAtomContainer next : ChemModelManipulator .getAllAtomContainers(chemModel)) { if (!GeometryUtil.has2DCoordinates(next)) { String error = GT.get("Not all atoms have 2D coordinates." + " JCP can only show full 2D specified structures." + " Shall we lay out the structure?"); int answer = JOptionPane.showConfirmDialog(null, error, "No 2D coordinates", JOptionPane.YES_NO_OPTION); if (answer == JOptionPane.NO_OPTION) { throw new CDKException(GT .get("Cannot display without 2D coordinates")); } else { // CreateCoordinatesForFileDialog frame = // new CreateCoordinatesForFileDialog(chemModel); // frame.pack(); // frame.show(); WaitDialog.showDialog(); List<IAtomContainer> acs=ChemModelManipulator.getAllAtomContainers(chemModel); generate2dCoordinates(acs); WaitDialog.hideDialog(); return; } } } /* * Add implicit hydrogens (in ControllerParameters, * autoUpdateImplicitHydrogens is true by default, so we need to do that * anyway) */ CDKHydrogenAdder hAdder = CDKHydrogenAdder.getInstance(chemModel .getBuilder()); for (IAtomContainer molecule : ChemModelManipulator .getAllAtomContainers(chemModel)) { if (molecule != null) { try { hAdder.addImplicitHydrogens(molecule); } catch (CDKException e) { // do nothing } } } } /** * Helper method to generate 2d coordinates when JChempaint loads a molecule * without 2D coordinates. Typically happens for SMILES strings. * * @param molecules * @throws Exception */ private static void generate2dCoordinates(List<IAtomContainer> molecules) { StructureDiagramGenerator sdg = new StructureDiagramGenerator(); for (int atIdx = 0; atIdx < molecules.size(); atIdx++) { IAtomContainer mol = molecules.get(atIdx); sdg.setMolecule(mol.getBuilder().newInstance(IAtomContainer.class,mol)); try { sdg.generateCoordinates(); } catch (Exception e) { e.printStackTrace(); } IAtomContainer ac = sdg.getMolecule(); for(int i=0;i<ac.getAtomCount();i++){ mol.getAtom(i).setPoint2d(ac.getAtom(i).getPoint2d()); } } } }
Java
2D
JChemPaint/jchempaint
core/src/test/java/org/openscience/cdk/CDKTestCase.java
.java
11,139
304
/* $Revision: 8050 $ $Author: egonw $ $Date: 2007-03-08 13:03:42 +0100 (Thu, 08 Mar 2007) $ * * 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.cdk; import org.junit.Assert; import org.junit.Test; import org.openscience.cdk.atomtype.CDKAtomTypeMatcher; import org.openscience.cdk.interfaces.IAtom; import org.openscience.cdk.interfaces.IAtomContainer; import org.openscience.cdk.interfaces.IAtomType; import org.openscience.cdk.interfaces.IBond; import org.openscience.cdk.tools.CDKHydrogenAdder; import org.openscience.cdk.tools.manipulator.AtomContainerManipulator; import org.openscience.cdk.tools.manipulator.AtomTypeManipulator; import javax.vecmath.Point2d; import javax.vecmath.Point3d; import javax.vecmath.Vector3d; import java.util.Iterator; /** * Super class for <b>all</b> CDK TestCase implementations that ensures that * the LoggingTool is configured. This is the JUnit4 version of CDKTestCase. * * @cdk.module test * * @see CDKTestCase */ public class CDKTestCase { /** * Determines if slow JUnit tests are to be run. You can set this * from the command line when running Ant: * <pre> * ant -f build.xml -DrunSlowTests=false test-all * </pre> * * @return */ public boolean runSlowTests() { if (System.getProperty("runSlowTests", "true").equals("false")) return false; // else return true; } /** * Determines if JUnit tests for known and unfixed bugs are to be run. * This is to aid the 'Open Source JVM Test Suite', so that all bugs that * show up in the report are caused by the JVM or the Java library is * uses (mostly a Classpath version). * * <p>You can set this from the command line when running Ant: * <pre> * ant -f build.xml -DrunKnownBugs=false test-all * </pre> * * <p><b>This method may only be used in JUnit classes, if the bug is reported * on SourceForge, and both the test <i>and</i> the affected Class are marked * with a JavaDoc @cdk.bug taglet!</b> * * @return a boolean indicating whether known bugs should be tested */ public boolean runKnownBugs() { if (System.getProperty("runKnownBugs", "true").equals("false")) return false; // else return true; } /** * Compares two Point2d objects, and asserts that the XY coordinates * are identical within the given error. * * @param p1 first Point2d * @param p2 second Point2d * @param error maximal allowed error */ public void assertEquals(Point2d p1, Point2d p2, double error) { Assert.assertNotNull("The expected Point2d is null", p1); Assert.assertNotNull("The tested Point2d is null", p2); Assert.assertEquals(p1.x, p2.x, error); Assert.assertEquals(p1.y, p2.y, error); } /** * Compares two Point3d objects, and asserts that the XY coordinates * are identical within the given error. * * @param p1 first Point3d * @param p2 second Point3d * @param error maximal allowed error */ public void assertEquals(Point3d p1, Point3d p2, double error) { Assert.assertNotNull("The expected Point3d is null", p1); Assert.assertNotNull("The tested Point3d is null", p2); Assert.assertEquals(p1.x, p2.x, error); Assert.assertEquals(p1.y, p2.y, error); Assert.assertEquals(p1.z, p2.z, error); } /** * Compares two Vector3d objects, and asserts that the XYZ coordinates * are identical within the given error. * * @param v1 first Point3d * @param v2 second Point3d * @param error maximal allowed error */ public void assertEquals(Vector3d v1, Vector3d v2, double error) { Assert.assertNotNull("The expected Vector3d is null", v1); Assert.assertNotNull("The tested Vector3d is null", v2); Assert.assertEquals(v1.x, v2.x, error); Assert.assertEquals(v1.y, v2.y, error); Assert.assertEquals(v1.z, v2.z, error); } /** * Tests method that asserts that for all atoms an reasonable CDK atom * type can be perceived. * * @param container IAtomContainer to test atom types of */ public void assertAtomTypesPerceived(IAtomContainer container) throws Exception { CDKAtomTypeMatcher matcher = CDKAtomTypeMatcher.getInstance(container.getBuilder()); Iterator<IAtom> atoms = container.atoms().iterator(); while (atoms.hasNext()) { IAtom atom = atoms.next(); IAtomType type = matcher.findMatchingAtomType(container, atom); Assert.assertNotNull( "Could not perceive atom type for: " + atom, type ); } } /** * Convenience method that perceives atom types (CDK scheme) and * adds explicit hydrogens accordingly. It does not create 2D or 3D * coordinates for the new hydrogens. * * @param container to which explicit hydrogens are added. */ protected void addExplicitHydrogens(IAtomContainer container) throws Exception { addImplicitHydrogens(container); AtomContainerManipulator.convertImplicitToExplicitHydrogens(container); } /** * Convenience method that perceives atom types (CDK scheme) and * adds implicit hydrogens accordingly. It does not create 2D or 3D * coordinates for the new hydrogens. * * @param container to which implicit hydrogens are added. */ protected void addImplicitHydrogens(IAtomContainer container) throws Exception { CDKAtomTypeMatcher matcher = CDKAtomTypeMatcher.getInstance(container.getBuilder()); for (IAtom atom : container.atoms()) { IAtomType type = matcher.findMatchingAtomType(container, atom); AtomTypeManipulator.configure(atom, type); } CDKHydrogenAdder hAdder = CDKHydrogenAdder.getInstance(container.getBuilder()); hAdder.addImplicitHydrogens(container); } /** * Convenience method to check that all bond orders are single * and all heavy atoms are aromatic (and that all explicit * hydrogens are not aromatic). * * @param container the atom container to check */ protected void assertAllSingleAndAromatic(IAtomContainer container) throws Exception { for (Iterator<IBond> bonds = container.bonds().iterator(); bonds.hasNext();) Assert.assertEquals(IBond.Order.SINGLE, bonds.next().getOrder()); for (Iterator<IAtom> atoms = container.atoms().iterator(); atoms.hasNext();) { IAtom atom = atoms.next(); if (atom.getSymbol().equals("H")) Assert.assertFalse(atom.getFlag(CDKConstants.ISAROMATIC)); else Assert.assertTrue(atom.getFlag(CDKConstants.ISAROMATIC)); } } /** * Convenience method to check the atom symbols * of a molecule. * * @param symbols an array of the expected atom symbols * @param container the atom container to check */ protected void assertAtomSymbols(String[] symbols, IAtomContainer container) throws Exception { int i = 0; for (Iterator<IAtom> atoms = container.atoms().iterator(); atoms.hasNext(); i++) Assert.assertEquals(symbols[i], atoms.next().getSymbol()); } /** * Convenience method to check the hybridization states * of a molecule. * * @param hybridizations an array of the expected hybridization states * @param container the atom container to check */ protected void assertHybridizations(IAtomType.Hybridization[] hybridizations, IAtomContainer container) throws Exception { int i = 0; for (Iterator<IAtom> atoms = container.atoms().iterator(); atoms.hasNext(); i++) Assert.assertEquals(hybridizations[i], atoms.next().getHybridization()); } /** * Convenience method to check the hydrogen counts * of a molecule. * * @param hydrogenCounts an array of the expected hydrogenCounts * @param container the atom container to check */ protected void assertHydrogenCounts(int[] hydrogenCounts, IAtomContainer container) throws Exception { int i = 0; for (Iterator<IAtom> atoms = container.atoms().iterator(); atoms.hasNext(); i++) Assert.assertEquals(hydrogenCounts[i], atoms.next().getImplicitHydrogenCount().intValue()); } /** * Asserts that the given String has zero length. * * @param String String to test the length of. */ public void assertZeroLength(String testString) { Assert.assertNotNull("Expected a non-null String.", testString); Assert.assertEquals( "Expected a zero-length String, but found '" + testString + "'", 0, testString.length() ); } /** * Asserts that the given String consists of a single line, and thus * does not contain any '\r' and/or '\n' characters. * * @param String String to test. */ public void assertOneLiner(String testString) { Assert.assertNotNull("Expected a non-null String.", testString); for (int i=0; i<testString.length(); i++) { char c = testString.charAt(i); Assert.assertNotSame("The String must not contain newline characters", '\n', c); Assert.assertNotSame("The String must not contain newline characters", '\r', c); } } /** * This test allows people to use the {@link TestMethod} annotation for * methods that are testing in other classes than identified with {@link TestClass}. * Bit of a workaround for the current set up, but useful in situations where * a methods is rather untestable, such as SAXHandler's endElement() methods. * * <p>Should be used only in these rare cases. */ @Test public void testedByOtherClass() { // several methods, like endElement() are not directly tested Assert.assertTrue(true); } /** * Asserts that the given subString is present in the fullString. * * @param fullString String which should contain the subString * @param subString String that must be present in the fullString */ public void assertContains(String fullString, String subString) { Assert.assertNotNull("Expected a non-null String to test contains against.", fullString); Assert.assertNotNull("Expected a non-null substring in contains test.", subString); Assert.assertTrue( "Expected the full string '" + fullString + "' to contain '" + subString + "'.", fullString.contains(subString) ); } }
Java
2D
JChemPaint/jchempaint
core/src/test/java/org/openscience/jchempaint/Issue129Test.java
.java
2,432
67
package org.openscience.jchempaint; import javax.vecmath.Point2d; import org.fest.swing.fixture.JPanelFixture; import org.junit.Assert; import org.junit.Test; import org.openscience.cdk.interfaces.IAtom; import org.openscience.cdk.interfaces.IAtomContainer; import org.openscience.jchempaint.renderer.Renderer; /** * @author Ralf Stephan <ralf@ark.in-berlin.de> * * 129: Input SMILES C=C (ethylene); (with single bond active) click on * double bond: NOT ethyne; click on triple bond; click on quadruple * bond: H2C-CH2, should be H3C-CH3 */ public class Issue129Test extends AbstractAppletTest { @Test public void testIssue129() { JPanelFixture jcppanel=applet.panel("appletframe"); JChemPaintPanel panel = (JChemPaintPanel)jcppanel.target; try { jcpApplet.setSmiles("C=C"); panel.get2DHub().updateView(); } catch (Exception e) { Assert.fail(); } int atomCount=0, bondCount=0, implicitHCount=0; for(IAtomContainer atc : panel.getChemModel().getMoleculeSet().atomContainers()) { for (IAtom a : atc.atoms()) implicitHCount += a.getImplicitHydrogenCount(); atomCount+=atc.getAtomCount(); bondCount+=atc.getBondCount(); } Assert.assertEquals(2, atomCount); Assert.assertEquals(1, bondCount); Assert.assertEquals(4, implicitHCount); IAtomContainer ethylene = panel.getChemModel().getMoleculeSet().getAtomContainer(0); Renderer r = panel.getRenderPanel().getRenderer(); Point2d atompos0=ethylene.getAtom(0).getPoint2d(); Point2d atompos1=ethylene.getAtom(1).getPoint2d(); Point2d bondpos = r.toScreenCoordinates((atompos0.x + atompos1.x)/2, (atompos0.y + atompos1.y)/2); panel.get2DHub().mouseClickedDown((int)bondpos.x, (int)bondpos.y); panel.get2DHub().updateView(); applet.panel("renderpanel").robot.waitForIdle(); panel.get2DHub().mouseClickedUp((int)bondpos.x, (int)bondpos.y); panel.get2DHub().updateView(); applet.panel("renderpanel").robot.waitForIdle(); atomCount=0; bondCount=0; implicitHCount=0; for(IAtomContainer atc : panel.getChemModel().getMoleculeSet().atomContainers()) { for (IAtom a : atc.atoms()) implicitHCount += a.getImplicitHydrogenCount(); atomCount+=atc.getAtomCount(); bondCount+=atc.getBondCount(); } Assert.assertEquals(2, atomCount); Assert.assertEquals(1, bondCount); Assert.assertEquals(2, implicitHCount); } }
Java
2D
JChemPaint/jchempaint
core/src/test/java/org/openscience/jchempaint/Issue73Test.java
.java
892
29
package org.openscience.jchempaint; import javax.vecmath.Point2d; import org.fest.swing.fixture.JPanelFixture; import org.junit.Assert; import org.junit.Test; /** * @author Ralf Stephan <ralf@ark.in-berlin.de> */ public class Issue73Test extends AbstractAppletTest { @Test public void testIssue73() { JPanelFixture jcppanel=applet.panel("appletframe"); JChemPaintPanel panel = (JChemPaintPanel)jcppanel.target; applet.button("C").target.doClick(); applet.button("chain").target.doClick(); panel.get2DHub().mouseClickedDown(100, 100); panel.get2DHub().mouseDrag(100, 100, 300, 100, 0); panel.get2DHub().mouseClickedUp(300, 100); panel.get2DHub().updateView(); applet.panel("renderpanel").robot.waitForIdle(); Point2d p = getAtomPoint(panel,0,1); Assert.assertEquals(new Point2d(100,100), p); } }
Java
2D
JChemPaint/jchempaint
core/src/test/java/org/openscience/jchempaint/Issue58Test.java
.java
2,237
51
package org.openscience.jchempaint; import java.awt.AWTException; import java.awt.Point; import javax.vecmath.Point2d; import org.fest.swing.fixture.JPanelFixture; import org.junit.Assert; import org.junit.Test; import org.openscience.cdk.interfaces.IAtomContainer; import org.openscience.cdk.renderer.selection.IChemObjectSelection; /** * @author Ralf Stephan <ralf@ark.in-berlin.de> */ public class Issue58Test extends AbstractAppletTest { @Test public void testIssue58() throws AWTException { JPanelFixture jcppanel=applet.panel("appletframe"); JChemPaintPanel panel = (JChemPaintPanel)jcppanel.target; applet.button("C").target.doClick(); applet.button("bondTool").target.doClick(); applet.panel("renderpanel").robot.click(applet.panel("renderpanel").component(),new Point(100,100)); applet.button("select").target.doClick(); IAtomContainer ethane = panel.getChemModel().getMoleculeSet().getAtomContainer(0); Point2d p1 = ethane.getAtom(0).getPoint2d(); p1 = panel.getRenderPanel().getRenderer().toScreenCoordinates(p1.x, p1.y); panel.get2DHub().mouseClickedDown((int)p1.x, (int)p1.y); applet.panel("renderpanel").robot.waitForIdle(); panel.get2DHub().mouseClickedUp((int)p1.x, (int)p1.y); panel.get2DHub().updateView(); applet.panel("renderpanel").robot.waitForIdle(); IChemObjectSelection sel = panel.getRenderPanel().getRenderer().getRenderer2DModel().getSelection(); Assert.assertEquals(true, sel.contains(ethane.getAtom(0))); applet.menuItem("formalCharge").requireEnabled(); Point2d p2 = ethane.getAtom(1).getPoint2d(); p2 = panel.getRenderPanel().getRenderer().toScreenCoordinates(p2.x, p2.y); panel.get2DHub().mouseClickedDown((int)p2.x, (int)p2.y); applet.panel("renderpanel").robot.waitForIdle(); panel.get2DHub().mouseClickedUp((int)p2.x, (int)p2.y); panel.get2DHub().updateView(); applet.panel("renderpanel").robot.waitForIdle(); sel = panel.getRenderPanel().getRenderer().getRenderer2DModel().getSelection(); Assert.assertEquals(true, sel.contains(ethane.getAtom(1))); applet.menuItem("formalCharge").requireEnabled(); } }
Java
2D
JChemPaint/jchempaint
core/src/test/java/org/openscience/jchempaint/Issue71Test.java
.java
2,334
53
package org.openscience.jchempaint; import java.awt.AWTException; import java.awt.Point; import javax.vecmath.Point2d; import org.fest.swing.fixture.JPanelFixture; import org.junit.Assert; import org.junit.Test; import org.openscience.cdk.interfaces.IAtomContainer; import org.openscience.jchempaint.renderer.Renderer; import org.openscience.cdk.renderer.selection.IChemObjectSelection; /** * @author Ralf Stephan <ralf@ark.in-berlin.de> */ public class Issue71Test extends AbstractAppletTest { @Test public void testIssue71() throws AWTException { JPanelFixture jcppanel=applet.panel("appletframe"); JChemPaintPanel panel = (JChemPaintPanel)jcppanel.target; applet.button("C").target.doClick(); applet.button("bondTool").target.doClick(); applet.panel("renderpanel").robot.click(applet.panel("renderpanel").component(),new Point(100,100)); applet.button("select").target.doClick(); IAtomContainer ethane = panel.getChemModel().getMoleculeSet().getAtomContainer(0); Point2d p1 = ethane.getAtom(0).getPoint2d(); Renderer r = panel.getRenderPanel().getRenderer(); p1 = r.toScreenCoordinates(p1.x, p1.y); panel.get2DHub().mouseClickedDown((int)(p1.x), (int)(p1.y)); applet.panel("renderpanel").robot.waitForIdle(); panel.get2DHub().mouseClickedUp((int)p1.x, (int)p1.y); panel.get2DHub().updateView(); applet.panel("renderpanel").robot.waitForIdle(); IChemObjectSelection sel = r.getRenderer2DModel().getSelection(); Assert.assertEquals(true, sel.contains(ethane.getAtom(0))); double d = r.getRenderer2DModel().getSelectionRadius() / r.getRenderer2DModel().getScale(); panel.get2DHub().mouseClickedDown((int)(p1.x+d/2), (int)(p1.y+d/2)); applet.panel("renderpanel").robot.waitForIdle(); panel.get2DHub().mouseDrag((int)(p1.x+d/2), (int)(p1.y+d/2),(int)p1.x+100, (int)p1.y+100, 0); panel.get2DHub().mouseClickedUp((int)p1.x+100, (int)p1.y+100); panel.get2DHub().updateView(); applet.panel("renderpanel").robot.waitForIdle(); sel = panel.getRenderPanel().getRenderer().getRenderer2DModel().getSelection(); Point2d p2 = ethane.getAtom(0).getPoint2d(); p2 = r.toScreenCoordinates(p2.x, p2.y); Assert.assertEquals((int)(p1.x+100), (int)p2.x); } }
Java
2D
JChemPaint/jchempaint
core/src/test/java/org/openscience/jchempaint/Issue137Test.java
.java
2,936
70
package org.openscience.jchempaint; import javax.vecmath.Point2d; import org.fest.swing.fixture.JPanelFixture; import org.junit.Assert; import org.junit.Test; import org.openscience.cdk.interfaces.IAtom; import org.openscience.cdk.interfaces.IAtomContainer; import org.openscience.jchempaint.action.JCPAction; import org.openscience.jchempaint.renderer.Renderer; /** * @author Ralf Stephan <ralf@ark.in-berlin.de> * * #137: move C in ethane over the other gives CH3 * #153: merging ethane internally does not delete bond from model */ public class Issue137Test extends AbstractAppletTest { @Test public void testIssue137() { JPanelFixture jcppanel=applet.panel("appletframe"); JChemPaintPanel panel = (JChemPaintPanel)jcppanel.target; panel.get2DHub().mouseClickedDown(100, 100); panel.get2DHub().mouseClickedUp(100, 100); panel.get2DHub().updateView(); applet.panel("renderpanel").robot.waitForIdle(); // For some reason this does not work // applet.button("select").target.doClick(); // panel.get2DHub().updateView(); // so we crank the lever manually JCPAction act = new JCPAction().getAction(panel, "org.openscience.jchempaint.action.ChangeModeAction@select"); act.actionPerformed(null); applet.panel("renderpanel").robot.waitForIdle(); IAtomContainer ethane = panel.getChemModel().getMoleculeSet().getAtomContainer(0); Renderer r = panel.getRenderPanel().getRenderer(); Point2d atompos0=ethane.getAtom(0).getPoint2d(); Point2d atompos1=ethane.getAtom(1).getPoint2d(); atompos0 = r.toScreenCoordinates(atompos0.x, atompos0.y); atompos1 = r.toScreenCoordinates(atompos1.x, atompos1.y); panel.get2DHub().mouseClickedDown((int)atompos0.x, (int)atompos0.y); panel.get2DHub().updateView(); applet.panel("renderpanel").robot.waitForIdle(); panel.get2DHub().mouseClickedUp((int)atompos0.x, (int)atompos0.y); panel.get2DHub().updateView(); applet.panel("renderpanel").robot.waitForIdle(); panel.get2DHub().mouseClickedDown((int)atompos0.x, (int)atompos0.y); panel.get2DHub().updateView(); applet.panel("renderpanel").robot.waitForIdle(); panel.get2DHub().mouseDrag((int)atompos0.x, (int)atompos0.y, (int)atompos1.x, (int)atompos1.y, 0); panel.get2DHub().updateView(); applet.panel("renderpanel").robot.waitForIdle(); panel.get2DHub().mouseClickedUp((int)atompos1.x, (int)atompos1.y); panel.get2DHub().updateView(); applet.panel("renderpanel").robot.waitForIdle(); int atomCount=0, bondCount=0, implicitHCount=0; for(IAtomContainer atc : panel.getChemModel().getMoleculeSet().atomContainers()) { for (IAtom a : atc.atoms()) implicitHCount += a.getImplicitHydrogenCount(); atomCount+=atc.getAtomCount(); bondCount+=atc.getBondCount(); } Assert.assertEquals(1, atomCount); Assert.assertEquals(0, bondCount); Assert.assertEquals(4, implicitHCount); } }
Java
2D
JChemPaint/jchempaint
core/src/test/java/org/openscience/jchempaint/Issue82Test.java
.java
3,230
95
/* */ package org.openscience.jchempaint; import org.fest.swing.fixture.JPanelFixture; import org.junit.Assert; import org.junit.Test; import org.openscience.cdk.interfaces.IAtom; import org.openscience.cdk.interfaces.IAtomContainer; /** * 1. place a C-C bond; 2. click draw chain; 3. start dragging from C and * notice one H too much in status bar; notice also the * explicit C of the merged methyl stays explicit, unexpectedly, see #103); * 4. clean mol will bomb with NullPointerException * @author <ralf@ark.in-berlin.de> */ public class Issue82Test extends AbstractAppletTest { @Test public void testIssue82() { JPanelFixture jcppanel=applet.panel("appletframe"); JChemPaintPanel pane = (JChemPaintPanel)jcppanel.target; applet.button("C").target.doClick(); applet.button("bondTool").target.doClick(); pane.get2DHub().mouseClickedDown(300, 100); pane.get2DHub().updateView(); applet.panel("renderpanel").robot.waitForIdle(); pane.get2DHub().mouseClickedUp(300, 100); pane.get2DHub().updateView(); applet.panel("renderpanel").robot.waitForIdle(); try { applet.panel("renderpanel").robot.wait(100);} catch (Exception e) {} applet.button("chain").target.doClick(); pane.get2DHub().updateView(); applet.panel("renderpanel").robot.waitForIdle(); pane.get2DHub().mouseClickedDown(200, 100); pane.get2DHub().updateView(); applet.panel("renderpanel").robot.waitForIdle(); pane.get2DHub().mouseDrag(200, 100, 300, 100, 0); pane.get2DHub().updateView(); applet.panel("renderpanel").robot.waitForIdle(); try { pane.get2DHub().mouseClickedUp(300, 100); pane.get2DHub().updateView(); applet.panel("renderpanel").robot.waitForIdle(); } catch (Exception e) { Assert.fail(); } int atomCount=0, bondCount=0, implicitHCount=0; for(IAtomContainer atc : pane.getChemModel().getMoleculeSet().atomContainers()) { for (IAtom a : atc.atoms()) implicitHCount += a.getImplicitHydrogenCount(); atomCount+=atc.getAtomCount(); bondCount+=atc.getBondCount(); } Assert.assertEquals(4, atomCount); Assert.assertEquals(3, bondCount); Assert.assertEquals(10, implicitHCount); applet.button("undo").target.doClick(); pane.get2DHub().updateView(); applet.panel("renderpanel").robot.waitForIdle(); atomCount=0; bondCount=0; implicitHCount=0; for(IAtomContainer atc : pane.getChemModel().getMoleculeSet().atomContainers()) { for (IAtom a : atc.atoms()) implicitHCount += a.getImplicitHydrogenCount(); atomCount+=atc.getAtomCount(); bondCount+=atc.getBondCount(); } Assert.assertEquals(2, atomCount); Assert.assertEquals(1, bondCount); Assert.assertEquals(6, implicitHCount); try { applet.button("undo").target.doClick(); pane.get2DHub().updateView(); applet.panel("renderpanel").robot.waitForIdle(); } catch (Exception e) { Assert.fail(); } atomCount=0; bondCount=0; implicitHCount=0; for(IAtomContainer atc : pane.getChemModel().getMoleculeSet().atomContainers()) { for (IAtom a : atc.atoms()) implicitHCount += a.getImplicitHydrogenCount(); atomCount+=atc.getAtomCount(); bondCount+=atc.getBondCount(); } Assert.assertEquals(0, atomCount); Assert.assertEquals(0, bondCount); } }
Java
2D
JChemPaint/jchempaint
core/src/test/java/org/openscience/jchempaint/AbstractAppletTest.java
.java
5,370
119
package org.openscience.jchempaint; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.Map; import javax.vecmath.Point2d; import org.fest.swing.applet.AppletViewer; import org.fest.swing.fixture.FrameFixture; import org.fest.swing.fixture.JPanelFixture; import org.fest.swing.launcher.AppletLauncher; import org.junit.AfterClass; import org.junit.BeforeClass; 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.IBond; import org.openscience.cdk.interfaces.IChemModel; import org.openscience.cdk.interfaces.IAtomContainerSet; import org.openscience.cdk.io.MDLV2000Reader; import org.openscience.cdk.tools.CDKHydrogenAdder; import org.openscience.cdk.tools.manipulator.AtomContainerManipulator; import org.openscience.jchempaint.applet.JChemPaintEditorApplet; /** * An abstract base class for applet tests. It sets up and tears down * and offers some convenience methods. */ public class AbstractAppletTest { private static AppletViewer viewer; protected static FrameFixture applet; protected static JChemPaintEditorApplet jcpApplet; protected static JChemPaintPanel panel; @BeforeClass public static void setUp() { jcpApplet = new JChemPaintEditorApplet(); Map<String, String> parameters = new HashMap<String, String>(); viewer = AppletLauncher.applet(jcpApplet) .withParameters(parameters) .start(); applet = new FrameFixture(viewer); applet.show(); JPanelFixture jcppanel=applet.panel("appletframe"); panel = (JChemPaintPanel)jcppanel.target; viewer.setSize(700,700); } protected Point2d getBondPoint(JChemPaintPanel panel, int bondnumber) { IBond bond = panel.getChemModel().getMoleculeSet().getAtomContainer(0).getBond(bondnumber); return panel.getRenderPanel().getRenderer().toScreenCoordinates((bond.getAtom(0).getPoint2d().x+bond.getAtom(1).getPoint2d().x)/2,(bond.getAtom(0).getPoint2d().y+bond.getAtom(1).getPoint2d().y)/2); } protected Point2d getAtomPoint(JChemPaintPanel panel, int atomnumber){ IAtom atom = panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(atomnumber); return panel.getRenderPanel().getRenderer().toScreenCoordinates(atom.getPoint2d().x,atom.getPoint2d().y); } protected Point2d getAtomPoint(JChemPaintPanel panel, int atomnumber, int acnumber){ IAtom atom = panel.getChemModel().getMoleculeSet().getAtomContainer(acnumber).getAtom(atomnumber); return panel.getRenderPanel().getRenderer().toScreenCoordinates(atom.getPoint2d().x,atom.getPoint2d().y); } protected void restoreModelToEmpty(){ JPanelFixture jcppanel=applet.panel("appletframe"); JChemPaintPanel panel = (JChemPaintPanel)jcppanel.target; IChemModel basic = DefaultChemObjectBuilder.getInstance().newInstance(IChemModel.class); basic.setMoleculeSet(basic.getBuilder().newInstance(IAtomContainerSet.class)); basic.getMoleculeSet().addAtomContainer( basic.getBuilder().newInstance(IAtomContainer.class)); panel.setChemModel(basic); panel.getRenderPanel().getRenderer().getRenderer2DModel().setZoomFactor(1); panel.getRenderPanel().getRenderer().getRenderer2DModel().setBondLength(10.4); panel.get2DHub().updateView(); } protected void restoreModelWithBasicmol(){ JPanelFixture jcppanel=applet.panel("appletframe"); JChemPaintPanel panel = (JChemPaintPanel)jcppanel.target; panel.get2DHub().getController2DModel().setAutoUpdateImplicitHydrogens(true); String filename = "data/basic.mol"; InputStream ins = this.getClass().getClassLoader().getResourceAsStream(filename); MDLV2000Reader reader = new MDLV2000Reader(ins); IChemModel basic; try { basic = (IChemModel) reader.read(DefaultChemObjectBuilder.getInstance().newInstance(IChemModel.class)); AtomContainerManipulator.percieveAtomTypesAndConfigureAtoms(basic.getMoleculeSet().getAtomContainer(0)); CDKHydrogenAdder hAdder = CDKHydrogenAdder.getInstance(basic.getMoleculeSet().getAtomContainer(0) .getBuilder()); hAdder.addImplicitHydrogens(basic.getMoleculeSet().getAtomContainer(0)); //valencies are set when doing atom typing, which we don't want in jcp for(int i=0;i<basic.getMoleculeSet().getAtomContainer(0).getAtomCount();i++){ basic.getMoleculeSet().getAtomContainer(0).getAtom(i).setValency(null); } panel.setChemModel(basic); panel.getRenderPanel().getRenderer().getRenderer2DModel().setZoomFactor(1); panel.get2DHub().updateView(); reader.close(); } catch (CDKException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } @AfterClass public static void tearDown() { viewer.unloadApplet(); applet.cleanUp(); } }
Java
2D
JChemPaint/jchempaint
core/src/test/java/org/openscience/jchempaint/Issue81Test.java
.java
930
35
package org.openscience.jchempaint; import org.fest.swing.fixture.JPanelFixture; import org.junit.Assert; import org.junit.Test; import org.openscience.cdk.interfaces.IAtomContainer; /** * @author Ralf Stephan <ralf@ark.in-berlin.de> * * Tests SMILES input in general. */ public class Issue81Test extends AbstractAppletTest { @Test public void testIssue81() { JPanelFixture jcppanel=applet.panel("appletframe"); JChemPaintPanel panel = (JChemPaintPanel)jcppanel.target; try { jcpApplet.setSmiles("CCCC"); panel.get2DHub().updateView(); } catch (Exception e) { Assert.fail(); } int atomCount=0, bondCount=0; for(IAtomContainer atc : panel.getChemModel().getMoleculeSet().atomContainers()) { atomCount+=atc.getAtomCount(); bondCount+=atc.getBondCount(); } Assert.assertEquals(4, atomCount); Assert.assertEquals(3, bondCount); } }
Java
2D
JChemPaint/jchempaint
core/src/test/java/org/openscience/jchempaint/JCPEditorAppletUndoRedoTest.java
.java
5,815
132
package org.openscience.jchempaint; import java.awt.Point; import java.util.ArrayList; import java.util.List; import javax.vecmath.Point2d; import org.fest.swing.core.MouseButton; import org.fest.swing.fixture.DialogFixture; import org.fest.swing.fixture.JButtonFixture; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import org.openscience.cdk.interfaces.IAtomContainer; import org.openscience.cdk.interfaces.IChemModel; import org.openscience.jchempaint.matchers.ButtonTextComponentMatcher; public class JCPEditorAppletUndoRedoTest extends AbstractAppletTest { private static List<IChemModel> models = new ArrayList<IChemModel>(); @BeforeClass public static void setUp() { AbstractAppletTest.setUp(); } @Test public void testUndo() throws CloneNotSupportedException{ //These should be models.add((IChemModel)panel.getChemModel().clone()); //but due to a bug in cdk, clone changes the model //without the clone, the test is not of much use, since it tests //(for my understanding) the model against itself. models.add((IChemModel)panel.getChemModel()); drawRing(100,100); applet.panel("renderpanel").robot.click(applet.panel("renderpanel").component(), new Point(0,0), MouseButton.RIGHT_BUTTON,1); models.add((IChemModel)panel.getChemModel()); attachRing(); applet.panel("renderpanel").robot.click(applet.panel("renderpanel").component(), new Point(0,0), MouseButton.RIGHT_BUTTON,1); models.add((IChemModel)panel.getChemModel()); panel.get2DHub().getRenderer().getRenderer2DModel().setHighlightedBond(null); deleteAtom(); models.add((IChemModel)panel.getChemModel()); drawRing(300,200); applet.panel("renderpanel").robot.click(applet.panel("renderpanel").component(), new Point(0,0), MouseButton.RIGHT_BUTTON,1); models.add((IChemModel)panel.getChemModel()); applet.button("undo").target.doClick(); compare(3); applet.button("undo").target.doClick(); compare(2); applet.button("undo").target.doClick(); compare(1); applet.button("undo").target.doClick(); compare(0); } private void deleteAtom() { applet.button("eraser").target.doClick(); Point2d moveto=getAtomPoint(panel, 0); applet.panel("renderpanel").robot.click(applet.panel("renderpanel").component(), new Point((int)moveto.x, (int)moveto.y), MouseButton.LEFT_BUTTON,1); } @Test public void testRedo(){ try { applet.button("redo").target.doClick(); compare(1); applet.button("redo").target.doClick(); compare(2); applet.button("redo").target.doClick(); compare(3); applet.button("redo").target.doClick(); compare(4); } catch (IllegalStateException e) { Assert.fail("Redo button disabled"); } } private void attachRing() { applet.button("hexagon").target.doClick(); Point2d moveto=getBondPoint(panel, 0); applet.panel("renderpanel").robot.click(applet.panel("renderpanel").component(), new Point((int)moveto.x, (int)moveto.y), MouseButton.LEFT_BUTTON,1); } public void drawRing(int x, int y){ applet.button("hexagon").target.doClick(); Point2d moveto=new Point2d(x, y); applet.panel("renderpanel").robot.click(applet.panel("renderpanel").component(), new Point((int)moveto.x, (int)moveto.y), MouseButton.LEFT_BUTTON,1); } private void compare(int whichmodel) { Assert.assertEquals(models.get(whichmodel).getMoleculeSet().getAtomContainerCount(), panel.getChemModel().getMoleculeSet().getAtomContainerCount()); for(int i=0;i<models.get(whichmodel).getMoleculeSet().getAtomContainerCount();i++){ Assert.assertEquals(models.get(whichmodel).getMoleculeSet().getAtomContainer(i).getAtomCount(), panel.getChemModel().getMoleculeSet().getAtomContainer(i).getAtomCount()); Assert.assertEquals(models.get(whichmodel).getMoleculeSet().getAtomContainer(i).getBondCount(), panel.getChemModel().getMoleculeSet().getAtomContainer(i).getBondCount()); } } /** * Tests bug fixed for JChempaint trac Ticket #79 (new defect): * Undo/redo when pasting templates works partly. */ @Test public void testUndoTemplates() throws CloneNotSupportedException{ applet.menuItem("new").click(); models.add((IChemModel)panel.getChemModel()); applet.menuItem("pasteTemplate").click(); DialogFixture dialog = applet.dialog("templates"); JButtonFixture templateButton = new JButtonFixture(dialog.robot, dialog.robot.finder().find(new ButtonTextComponentMatcher("Cysteine"))); templateButton.click(); Assert.assertEquals(7,totalAtomCount()); Assert.assertEquals(1,panel.getChemModel().getMoleculeSet().getAtomContainerCount()); applet.menuItem("pasteTemplate").click(); dialog = applet.dialog("templates"); templateButton = new JButtonFixture(dialog.robot, dialog.robot.finder().find(new ButtonTextComponentMatcher("Leucine"))); templateButton.click(); Assert.assertEquals(16,totalAtomCount()); Assert.assertEquals(2,panel.getChemModel().getMoleculeSet().getAtomContainerCount()); applet.button("undo").target.doClick(); Assert.assertEquals(7,totalAtomCount()); Assert.assertEquals(1,panel.getChemModel().getMoleculeSet().getAtomContainerCount()); } private int totalAtomCount () { int totalAtomCount=0; for(IAtomContainer atc: panel.getChemModel().getMoleculeSet().atomContainers()) { totalAtomCount+=atc.getAtomCount(); } return totalAtomCount; } }
Java
2D
JChemPaint/jchempaint
core/src/test/java/org/openscience/jchempaint/BugSF75Test.java
.java
2,164
40
package org.openscience.jchempaint; import java.awt.Point; import java.io.IOException; import javax.vecmath.Point2d; import org.fest.swing.core.MouseButton; import org.fest.swing.fixture.JPanelFixture; import org.junit.Assert; import org.junit.Test; import org.openscience.cdk.exception.CDKException; public class BugSF75Test extends AbstractAppletTest { @Test public void testBug75() throws CDKException, ClassNotFoundException, IOException, CloneNotSupportedException{ JPanelFixture jcppanel=applet.panel("appletframe"); JChemPaintPanel panel = (JChemPaintPanel)jcppanel.target; applet.button("hexagon").target.doClick(); applet.click(); applet.panel("renderpanel").robot.click(applet.panel("renderpanel").component(), new Point(100,100), MouseButton.LEFT_BUTTON,1); applet.button("eraser").target.doClick(); Point2d moveto=getAtomPoint(panel,0,1); applet.panel("renderpanel").robot.click(applet.panel("renderpanel").component(), new Point((int)moveto.x, (int)moveto.y), MouseButton.LEFT_BUTTON,1); moveto=getAtomPoint(panel,0,1); applet.panel("renderpanel").robot.click(applet.panel("renderpanel").component(), new Point((int)moveto.x, (int)moveto.y), MouseButton.LEFT_BUTTON,1); moveto=getAtomPoint(panel,0,1); applet.panel("renderpanel").robot.click(applet.panel("renderpanel").component(), new Point((int)moveto.x, (int)moveto.y), MouseButton.LEFT_BUTTON,1); moveto=getAtomPoint(panel,0,1); applet.panel("renderpanel").robot.click(applet.panel("renderpanel").component(), new Point((int)moveto.x, (int)moveto.y), MouseButton.LEFT_BUTTON,1); moveto=getAtomPoint(panel,0,1); applet.panel("renderpanel").robot.click(applet.panel("renderpanel").component(), new Point((int)moveto.x, (int)moveto.y), MouseButton.LEFT_BUTTON,1); moveto=getAtomPoint(panel,0,1); applet.panel("renderpanel").robot.click(applet.panel("renderpanel").component(), new Point((int)moveto.x, (int)moveto.y), MouseButton.LEFT_BUTTON,1); Assert.assertEquals("C1CCCCC1", panel.getSmiles()); restoreModelToEmpty(); } }
Java
2D
JChemPaint/jchempaint
core/src/test/java/org/openscience/jchempaint/MenuIsotopeTest.java
.java
3,252
66
package org.openscience.jchempaint; import java.awt.Point; import java.io.IOException; import org.junit.Assert; import org.junit.Test; import org.openscience.cdk.exception.CDKException; import org.openscience.cdk.interfaces.IAtom; import org.openscience.jchempaint.renderer.selection.SingleSelection; public class MenuIsotopeTest extends AbstractAppletTest { @Test public void testMenuIsotopeMajorPlusThree() throws CDKException, ClassNotFoundException, IOException, CloneNotSupportedException { genericIsotopeTest(15); } @Test public void testMenuIsotopeMajorPlusTwo() throws CDKException, ClassNotFoundException, IOException, CloneNotSupportedException { genericIsotopeTest(14); } @Test public void testMenuIsotopeMajorPlusOne() throws CDKException, ClassNotFoundException, IOException, CloneNotSupportedException { genericIsotopeTest(13); } @Test public void testMenuIsotopeMajor() throws CDKException, ClassNotFoundException, IOException, CloneNotSupportedException { genericIsotopeTest(12); } @Test public void testMenuIsotopeMajorMinusOne() throws CDKException, ClassNotFoundException, IOException, CloneNotSupportedException { genericIsotopeTest(11); } private void genericIsotopeTest(int isotopeNumber){ //we go to select mode restoreModelWithBasicmol(); applet.button("select").target.doClick(); panel.getRenderPanel().getRenderer().getRenderer2DModel().setSelection(new SingleSelection<IAtom>(panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(0))); panel.selectionChanged(); int oldAtomCount=panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtomCount(); applet.menuItem("isotopeChange").click(); applet.menuItem("C"+isotopeNumber).click(); Assert.assertEquals(isotopeNumber, panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(0).getMassNumber().intValue()); //the mode should have changed now Assert.assertEquals("C", panel.get2DHub().getActiveDrawModule().getID()); Assert.assertEquals(isotopeNumber, panel.get2DHub().getController2DModel().getDrawIsotopeNumber()); //if we click somewhere, we should get a new atom with specified properties applet.panel("renderpanel").robot.click(applet.panel("renderpanel").component(), new Point(100,100)); Assert.assertEquals(oldAtomCount+1, panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtomCount()+panel.getChemModel().getMoleculeSet().getAtomContainer(1).getAtomCount()); Assert.assertEquals("C", panel.getChemModel().getMoleculeSet().getAtomContainer(1).getAtom(0).getSymbol()); Assert.assertEquals(isotopeNumber, panel.getChemModel().getMoleculeSet().getAtomContainer(1).getAtom(0).getMassNumber().intValue()); panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(0).setMassNumber(12); } @Test public void testMenuIsotopeMajorMinusTwo() throws CDKException, ClassNotFoundException, IOException, CloneNotSupportedException { genericIsotopeTest(10); } @Test public void testMenuIsotopeMajorMinusThree() throws CDKException, ClassNotFoundException, IOException, CloneNotSupportedException { genericIsotopeTest(9); } }
Java
2D
JChemPaint/jchempaint
core/src/test/java/org/openscience/jchempaint/JCPEditorAppletBugsTest.java
.java
21,805
473
package org.openscience.jchempaint; import java.awt.Point; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import javax.swing.JComboBox; import javax.vecmath.Point2d; import org.fest.swing.core.ComponentDragAndDrop; import org.fest.swing.core.MouseButton; import org.fest.swing.fixture.DialogFixture; import org.fest.swing.fixture.JButtonFixture; import org.fest.swing.fixture.JPanelFixture; import org.fest.swing.fixture.JTextComponentFixture; import org.junit.Assert; import org.junit.Test; import org.openscience.cdk.DefaultChemObjectBuilder; import org.openscience.cdk.exception.CDKException; import org.openscience.cdk.interfaces.IAtomContainer; import org.openscience.cdk.interfaces.IBond; import org.openscience.cdk.io.MDLV2000Reader; import org.openscience.jchempaint.matchers.ButtonTextComponentMatcher; import org.openscience.jchempaint.matchers.ComboBoxTextComponentMatcher; public class JCPEditorAppletBugsTest extends AbstractAppletTest { private static int SAVE_AS_MOL_COMBOBOX_POS=6; @Test public void testSquareSelectSingleAtom() { JPanelFixture jcppanel = applet.panel("appletframe"); JChemPaintPanel panel = (JChemPaintPanel) jcppanel.target; applet.button("C").target.doClick(); Point movetopint = new Point(100, 100); applet.panel("renderpanel").robot.click(applet.panel("renderpanel") .component(), movetopint, MouseButton.LEFT_BUTTON, 1); Assert.assertEquals(1, panel.getChemModel().getMoleculeSet() .getAtomContainer(0).getAtomCount()); applet.button("select").target.doClick(); movetopint = new Point(80, 80); applet.panel("renderpanel").robot.moveMouse(applet.panel("renderpanel") .component(), movetopint); applet.panel("renderpanel").robot.pressMouse(MouseButton.LEFT_BUTTON); movetopint = new Point(85, 85); // little fix by MR, do small initial // drag first applet.panel("renderpanel").robot.moveMouse(applet.panel("renderpanel") .component(), movetopint); movetopint = new Point(120, 120); applet.panel("renderpanel").robot.moveMouse(applet.panel("renderpanel") .component(), movetopint); applet.panel("renderpanel").robot.releaseMouse(MouseButton.LEFT_BUTTON); Assert.assertEquals(1, panel.getRenderPanel().getRenderer() .getRenderer2DModel().getSelection() .getConnectedAtomContainer().getAtomCount()); restoreModelToEmpty(); } @Test public void testMove() throws InterruptedException { JPanelFixture jcppanel = applet.panel("appletframe"); JChemPaintPanel panel = (JChemPaintPanel) jcppanel.target; // we draw a hexagon applet.button("hexagon").target.doClick(); applet.panel("renderpanel").robot.click(applet.panel("renderpanel") .component(), new Point(100, 100), MouseButton.LEFT_BUTTON, 1); // select this applet.button("select").target.doClick(); Point movetopint = new Point(50, 50); ComponentDragAndDrop dandd = new ComponentDragAndDrop(applet .panel("renderpanel").robot); dandd.drag(applet.panel("renderpanel").component(), movetopint); movetopint = new Point(300, 300); dandd.drop(applet.panel("renderpanel").component(), movetopint); Point2d oldcoord = new Point2d(panel.getChemModel().getMoleculeSet() .getAtomContainer(0).getAtom(0).getPoint2d().x, panel .getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(0) .getPoint2d().y); // switch to move mode should happen automatically applet.panel("renderpanel").robot.moveMouse( applet.panel("renderpanel").target, new Point(100, 100)); applet.panel("renderpanel").robot.pressMouse(MouseButton.LEFT_BUTTON); applet.panel("renderpanel").robot.moveMouse( applet.panel("renderpanel").target, new Point(150, 150)); applet.panel("renderpanel").robot.releaseMouseButtons(); Assert.assertFalse(oldcoord.equals(panel.getChemModel() .getMoleculeSet().getAtomContainer(0).getAtom(0).getPoint2d())); } @Test public void testSetMolFile() throws CDKException { JPanelFixture jcppanel = applet.panel("appletframe"); JChemPaintPanel panel = (JChemPaintPanel) jcppanel.target; jcpApplet .setMolFile("\n CDK 1/19/07,10:3\n\n 2 1 0 0 0 0 0 0 0 0999 V2000 \n 2.520000 10.220000 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0\n 2.270000 10.470000 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0\n 2 1 1 0 0 0 0 \nM END"); Assert.assertEquals(2, panel.getChemModel().getMoleculeSet() .getAtomContainer(0).getAtomCount()); restoreModelToEmpty(); } @Test public void testGetMolFile() throws CDKException { applet.button("hexagon").target.doClick(); Point movetopint = new Point(100, 100); applet.panel("renderpanel").robot.click(applet.panel("renderpanel") .component(), movetopint, MouseButton.LEFT_BUTTON, 1); Assert.assertTrue(jcpApplet.getMolFile().indexOf( "6 6 0 0 0 0 0 0 0 0999 V2000") > 0); restoreModelToEmpty(); } @Test public void testBug2858663() { JPanelFixture jcppanel = applet.panel("appletframe"); JChemPaintPanel panel = (JChemPaintPanel) jcppanel.target; applet.button("bondTool").target.doClick(); applet.click(); Assert.assertEquals(2, panel.getChemModel().getMoleculeSet() .getAtomContainer(0).getAtomCount()); Assert.assertEquals(1, panel.getChemModel().getMoleculeSet() .getAtomContainer(0).getBondCount()); restoreModelToEmpty(); } // @cdk.bug 2859344 /6 @Test public void overwriteStereo() { JPanelFixture jcppanel = applet.panel("appletframe"); JChemPaintPanel panel = (JChemPaintPanel) jcppanel.target; // we draw a hexagon applet.button("hexagon").target.doClick(); applet.click(); // one of its bonds becomes an up bond applet.button("up_bond").target.doClick(); Point2d moveto = panel .getRenderPanel() .getRenderer() .toScreenCoordinates( (panel.getChemModel().getMoleculeSet() .getAtomContainer(0).getAtom(2).getPoint2d().x + panel .getChemModel().getMoleculeSet() .getAtomContainer(0).getAtom(3).getPoint2d().x) / 2, (panel.getChemModel().getMoleculeSet() .getAtomContainer(0).getAtom(2).getPoint2d().y + panel .getChemModel().getMoleculeSet() .getAtomContainer(0).getAtom(3).getPoint2d().y) / 2); applet.panel("renderpanel").robot.click(applet.panel("renderpanel") .component(), new Point((int) moveto.x, (int) moveto.y), MouseButton.LEFT_BUTTON, 1); Assert.assertEquals(IBond.Stereo.UP, panel.getChemModel() .getMoleculeSet().getAtomContainer(0).getBond(2).getStereo()); // if we make that down, it must be down (and not donw_inv) applet.button("down_bond").target.doClick(); moveto = panel.getRenderPanel().getRenderer().toScreenCoordinates( (panel.getChemModel().getMoleculeSet().getAtomContainer(0) .getAtom(2).getPoint2d().x + panel.getChemModel() .getMoleculeSet().getAtomContainer(0).getAtom(3) .getPoint2d().x) / 2, (panel.getChemModel().getMoleculeSet().getAtomContainer(0) .getAtom(2).getPoint2d().y + panel.getChemModel() .getMoleculeSet().getAtomContainer(0).getAtom(3) .getPoint2d().y) / 2); applet.panel("renderpanel").robot.click(applet.panel("renderpanel") .component(), new Point((int) moveto.x, (int) moveto.y), MouseButton.LEFT_BUTTON, 1); Assert.assertEquals(IBond.Stereo.DOWN, panel.getChemModel() .getMoleculeSet().getAtomContainer(0).getBond(2).getStereo()); // and up again applet.button("up_bond").target.doClick(); moveto = panel.getRenderPanel().getRenderer().toScreenCoordinates( (panel.getChemModel().getMoleculeSet().getAtomContainer(0) .getAtom(2).getPoint2d().x + panel.getChemModel() .getMoleculeSet().getAtomContainer(0).getAtom(3) .getPoint2d().x) / 2, (panel.getChemModel().getMoleculeSet().getAtomContainer(0) .getAtom(2).getPoint2d().y + panel.getChemModel() .getMoleculeSet().getAtomContainer(0).getAtom(3) .getPoint2d().y) / 2); applet.panel("renderpanel").robot.click(applet.panel("renderpanel") .component(), new Point((int) moveto.x, (int) moveto.y), MouseButton.LEFT_BUTTON, 1); Assert.assertEquals(IBond.Stereo.UP, panel.getChemModel() .getMoleculeSet().getAtomContainer(0).getBond(2).getStereo()); restoreModelToEmpty(); } @Test public void testUpBond() { genericStereoBondTest(IBond.Stereo.UP); } @Test public void testDownBond() { genericStereoBondTest(IBond.Stereo.DOWN); } @Test public void testUndefinedBond() { genericStereoBondTest(IBond.Stereo.UP_OR_DOWN); } // @cdk.bug 2859344 /7 @Test public void testUndefinedEzBond() { genericStereoBondTest(IBond.Stereo.E_OR_Z); } @Test public void testNoneBond() { genericStereoBondTest(IBond.Stereo.NONE); } // @cdk.bug 2860015 @Test public void testBug2860015() { JPanelFixture jcppanel = applet.panel("appletframe"); JChemPaintPanel panel = (JChemPaintPanel) jcppanel.target; applet.button("bondTool").target.doClick(); applet.click(); applet.click(); applet.click(); applet.click(); Point2d moveto = panel.getRenderPanel().getRenderer() .toScreenCoordinates( panel.getChemModel().getMoleculeSet().getAtomContainer( 0).getAtom(3).getPoint2d().x, panel.getChemModel().getMoleculeSet().getAtomContainer( 0).getAtom(3).getPoint2d().y); applet.panel("renderpanel").robot.click(applet.panel("renderpanel") .component(), new Point((int) moveto.x, (int) moveto.y), MouseButton.LEFT_BUTTON, 1); Assert.assertEquals(6, panel.getChemModel().getMoleculeSet() .getAtomContainer(0).getAtomCount()); Assert.assertEquals(5, panel.getChemModel().getMoleculeSet() .getAtomContainer(0).getBondCount()); moveto = getBondPoint(panel, 0); panel.getRenderPanel().getRenderer().getRenderer2DModel() .setHighlightedAtom(null); applet.moveTo(new Point(100, 100)); applet.button("eraser").target.doClick(); applet.panel("renderpanel").robot.click(applet.panel("renderpanel") .component(), new Point((int) moveto.x, (int) moveto.y), MouseButton.LEFT_BUTTON, 1); Assert.assertEquals(5, panel.getChemModel().getMoleculeSet() .getAtomContainer(0).getAtomCount()); Assert.assertEquals(4, panel.getChemModel().getMoleculeSet() .getAtomContainer(0).getBondCount()); moveto = getBondPoint(panel, 1); applet.panel("renderpanel").robot.click(applet.panel("renderpanel") .component(), new Point((int) moveto.x, (int) moveto.y), MouseButton.LEFT_BUTTON, 1); Assert.assertEquals(2, panel.getChemModel().getMoleculeSet() .getAtomContainerCount()); Assert.assertEquals(3, panel.getChemModel().getMoleculeSet() .getAtomContainer(0).getAtomCount()); Assert.assertEquals(2, panel.getChemModel().getMoleculeSet() .getAtomContainer(0).getBondCount()); Assert.assertEquals(2, panel.getChemModel().getMoleculeSet() .getAtomContainer(1).getAtomCount()); Assert.assertEquals(1, panel.getChemModel().getMoleculeSet() .getAtomContainer(1).getBondCount()); restoreModelToEmpty(); } // This is a test for overwriting of stereo bonds. Any stereo bond // must overwrite all others and flip itself. private void genericStereoBondTest(IBond.Stereo directionToTest) { JPanelFixture jcppanel = applet.panel("appletframe"); JChemPaintPanel panel = (JChemPaintPanel) jcppanel.target; // we draw a hexagon applet.button("hexagon").target.doClick(); applet.click(); // we make all bond types in there applet.button("up_bond").target.doClick(); Point2d moveto = getBondPoint(panel, 1); applet.panel("renderpanel").robot.click(applet.panel("renderpanel") .component(), new Point((int) moveto.x, (int) moveto.y), MouseButton.LEFT_BUTTON, 1); Assert.assertEquals(IBond.Stereo.UP, panel.getChemModel() .getMoleculeSet().getAtomContainer(0).getBond(1).getStereo()); applet.button("down_bond").target.doClick(); moveto = getBondPoint(panel, 2); applet.panel("renderpanel").robot.click(applet.panel("renderpanel") .component(), new Point((int) moveto.x, (int) moveto.y), MouseButton.LEFT_BUTTON, 1); Assert.assertEquals(IBond.Stereo.DOWN, panel.getChemModel() .getMoleculeSet().getAtomContainer(0).getBond(2).getStereo()); applet.button("undefined_bond").target.doClick(); moveto = getBondPoint(panel, 3); applet.panel("renderpanel").robot.click(applet.panel("renderpanel") .component(), new Point((int) moveto.x, (int) moveto.y), MouseButton.LEFT_BUTTON, 1); Assert.assertEquals(IBond.Stereo.UP_OR_DOWN, panel.getChemModel() .getMoleculeSet().getAtomContainer(0).getBond(3).getStereo()); applet.button("undefined_stereo_bond").target.doClick(); moveto = getBondPoint(panel, 4); applet.panel("renderpanel").robot.click(applet.panel("renderpanel") .component(), new Point((int) moveto.x, (int) moveto.y), MouseButton.LEFT_BUTTON, 1); Assert.assertEquals(IBond.Stereo.E_OR_Z, panel.getChemModel() .getMoleculeSet().getAtomContainer(0).getBond(4).getStereo()); // now we click on all of them with disired bond if (directionToTest == IBond.Stereo.UP) applet.button("up_bond").target.doClick(); if (directionToTest == IBond.Stereo.DOWN) applet.button("down_bond").target.doClick(); if (directionToTest == IBond.Stereo.UP_OR_DOWN) applet.button("undefined_bond").target.doClick(); if (directionToTest == IBond.Stereo.E_OR_Z) applet.button("undefined_stereo_bond").target.doClick(); if (directionToTest == IBond.Stereo.NONE) applet.button("bondTool").target.doClick(); for (int i = 0; i < 5; i++) { boolean self = false; if (panel.getChemModel().getMoleculeSet().getAtomContainer(0) .getBond(i).getStereo() == directionToTest) self = true; moveto = getBondPoint(panel, i); applet.panel("renderpanel").robot.click(applet.panel("renderpanel") .component(), new Point((int) moveto.x, (int) moveto.y), MouseButton.LEFT_BUTTON, 1); if (self) { IBond.Stereo desiredDirection = null; if (directionToTest == IBond.Stereo.E_OR_Z) desiredDirection = IBond.Stereo.E_OR_Z; else if (directionToTest == IBond.Stereo.NONE) desiredDirection = IBond.Stereo.NONE; else if (directionToTest == IBond.Stereo.DOWN) desiredDirection = IBond.Stereo.DOWN_INVERTED; else if (directionToTest == IBond.Stereo.UP) desiredDirection = IBond.Stereo.UP_INVERTED; else if (directionToTest == IBond.Stereo.UP_OR_DOWN) desiredDirection = IBond.Stereo.UP_OR_DOWN_INVERTED; Assert.assertEquals(desiredDirection, panel.getChemModel() .getMoleculeSet().getAtomContainer(0).getBond(i) .getStereo()); } else { Assert.assertEquals(directionToTest, panel.getChemModel() .getMoleculeSet().getAtomContainer(0).getBond(i) .getStereo()); } } restoreModelToEmpty(); } @Test public void testFlipWithStereo() { JPanelFixture jcppanel = applet.panel("appletframe"); JChemPaintPanel panel = (JChemPaintPanel) jcppanel.target; applet.button("hexagon").target.doClick(); applet.click(); applet.button("up_bond").target.doClick(); Point2d moveto = getAtomPoint(panel, 0); applet.panel("renderpanel").robot.click(applet.panel("renderpanel") .component(), new Point((int) moveto.x, (int) moveto.y), MouseButton.LEFT_BUTTON, 1); moveto = getAtomPoint(panel, 1); applet.panel("renderpanel").robot.click(applet.panel("renderpanel") .component(), new Point((int) moveto.x, (int) moveto.y), MouseButton.LEFT_BUTTON, 1); applet.button("down_bond").target.doClick(); moveto = getAtomPoint(panel, 2); applet.panel("renderpanel").robot.click(applet.panel("renderpanel") .component(), new Point((int) moveto.x, (int) moveto.y), MouseButton.LEFT_BUTTON, 1); applet.button("flipHorizontal").target.doClick(); Assert.assertEquals(IBond.Stereo.DOWN, panel.getChemModel() .getMoleculeSet().getAtomContainer(0).getBond(6).getStereo()); Assert.assertEquals(IBond.Stereo.DOWN, panel.getChemModel() .getMoleculeSet().getAtomContainer(0).getBond(7).getStereo()); Assert.assertEquals(IBond.Stereo.UP, panel.getChemModel() .getMoleculeSet().getAtomContainer(0).getBond(8).getStereo()); applet.button("flipVertical").target.doClick(); Assert.assertEquals(IBond.Stereo.UP, panel.getChemModel() .getMoleculeSet().getAtomContainer(0).getBond(6).getStereo()); Assert.assertEquals(IBond.Stereo.UP, panel.getChemModel() .getMoleculeSet().getAtomContainer(0).getBond(7).getStereo()); Assert.assertEquals(IBond.Stereo.DOWN, panel.getChemModel() .getMoleculeSet().getAtomContainer(0).getBond(8).getStereo()); restoreModelToEmpty(); } @Test public void testBug77() throws CDKException, IOException{ JPanelFixture jcppanel=applet.panel("appletframe"); JChemPaintPanel panel = (JChemPaintPanel)jcppanel.target; applet.button("hexagon").target.doClick(); applet.click(); applet.menuItem("saveAs").click(); File file=new File(System.getProperty("java.io.tmpdir")+File.separator+"test1.mol"); if(file.exists()) file.delete(); DialogFixture dialog = applet.dialog(); JComboBox<?> combobox = dialog.robot.finder().find(new ComboBoxTextComponentMatcher("org.openscience.jchempaint.io.JCPFileFilter")); combobox.setSelectedItem(combobox.getItemAt(SAVE_AS_MOL_COMBOBOX_POS)); JTextComponentFixture text = dialog.textBox(); text.setText(file.toString()); JButtonFixture okbutton = new JButtonFixture(dialog.robot, dialog.robot.finder().find(new ButtonTextComponentMatcher("Save"))); okbutton.click(); //not the bug, but still worth testing MDLV2000Reader reader = new MDLV2000Reader(new FileInputStream(file)); IAtomContainer mol = (IAtomContainer)reader.read(DefaultChemObjectBuilder.getInstance().newInstance(IAtomContainer.class)); Assert.assertEquals(panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtomCount(), mol.getAtomCount()); Assert.assertEquals(panel.getChemModel().getMoleculeSet().getAtomContainer(0).getBondCount(), mol.getBondCount()); applet.menuItem("new").click(); applet.button("hexagon").target.doClick(); applet.click(); applet.button("bondTool").target.doClick(); Point2d moveto=getAtomPoint(panel,0); applet.panel("renderpanel").robot.click(applet.panel("renderpanel").component(), new Point((int)moveto.x,(int)moveto.y), MouseButton.LEFT_BUTTON,1); applet.menuItem("saveAs").click(); dialog = applet.dialog(); combobox = dialog.robot.finder().find(new ComboBoxTextComponentMatcher("org.openscience.jchempaint.io.JCPFileFilter")); combobox.setSelectedItem(combobox.getItemAt(SAVE_AS_MOL_COMBOBOX_POS)); text = dialog.textBox(); file=new File(System.getProperty("java.io.tmpdir")+File.separator+"test2.mol"); if(file.exists()) file.delete(); text.setText(file.toString()); okbutton = new JButtonFixture(dialog.robot, dialog.robot.finder().find(new ButtonTextComponentMatcher("Save"))); okbutton.click(); reader.close(); //not the bug, but still worth testing reader = new MDLV2000Reader(new FileInputStream(file)); mol = (IAtomContainer)reader.read(DefaultChemObjectBuilder.getInstance().newInstance(IAtomContainer.class)); Assert.assertEquals(panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtomCount(), mol.getAtomCount()); Assert.assertEquals(panel.getChemModel().getMoleculeSet().getAtomContainer(0).getBondCount(), mol.getBondCount()); //ok, now the critical bits - open mol1 file=new File(System.getProperty("java.io.tmpdir")+File.separator+"test1.mol"); applet.menuItem("open").click(); dialog = applet.dialog(); text = dialog.textBox(); text.setText(file.toString()); okbutton = new JButtonFixture(dialog.robot, dialog.robot.finder().find(new ButtonTextComponentMatcher("Open"))); okbutton.click(); //"save as" mol1 file.delete(); applet.menuItem("saveAs").click(); dialog = applet.dialog(); combobox = dialog.robot.finder().find(new ComboBoxTextComponentMatcher("org.openscience.jchempaint.io.JCPFileFilter")); combobox.setSelectedItem(combobox.getItemAt(SAVE_AS_MOL_COMBOBOX_POS)); text = dialog.textBox(); text.setText(file.toString()); okbutton = new JButtonFixture(dialog.robot, dialog.robot.finder().find(new ButtonTextComponentMatcher("Save"))); okbutton.click(); reader.close(); //open mol2 file=new File(System.getProperty("java.io.tmpdir")+File.separator+"test2.mol"); applet.menuItem("open").click(); dialog = applet.dialog(); text = dialog.textBox(); text.setText(file.toString()); okbutton = new JButtonFixture(dialog.robot, dialog.robot.finder().find(new ButtonTextComponentMatcher("Open"))); okbutton.click(); //save should write to mol2, ie mol1=6 atoms, mol2=7atoms applet.menuItem("save").click(); file=new File(System.getProperty("java.io.tmpdir")+File.separator+"test1.mol"); reader = new MDLV2000Reader(new FileInputStream(file)); mol = (IAtomContainer)reader.read(DefaultChemObjectBuilder.getInstance().newInstance(IAtomContainer.class)); Assert.assertEquals(6, mol.getAtomCount()); reader.close(); file=new File(System.getProperty("java.io.tmpdir")+File.separator+"test2.mol"); reader = new MDLV2000Reader(new FileInputStream(file)); mol = (IAtomContainer)reader.read(DefaultChemObjectBuilder.getInstance().newInstance(IAtomContainer.class)); Assert.assertEquals(7, mol.getAtomCount()); restoreModelToEmpty(); reader.close(); } }
Java
2D
JChemPaint/jchempaint
core/src/test/java/org/openscience/jchempaint/SetSmilesTest.java
.java
613
21
package org.openscience.jchempaint; import org.fest.swing.fixture.JPanelFixture; import org.junit.Assert; import org.junit.Test; import org.openscience.cdk.exception.CDKException; public class SetSmilesTest extends AbstractAppletTest { @Test public void testSetSmiles() throws CDKException { JPanelFixture jcppanel = applet.panel("appletframe"); JChemPaintPanel panel = (JChemPaintPanel) jcppanel.target; jcpApplet.setSmiles("CCCC"); panel.get2DHub().updateView(); Assert.assertEquals(4, panel.getChemModel().getMoleculeSet() .getAtomContainer(0).getAtomCount()); restoreModelToEmpty(); } }
Java
2D
JChemPaint/jchempaint
core/src/test/java/org/openscience/jchempaint/Issue139Test.java
.java
2,613
76
package org.openscience.jchempaint; import org.fest.swing.fixture.JPanelFixture; import org.junit.Assert; import org.junit.Test; import org.openscience.cdk.interfaces.IAtom; import org.openscience.cdk.interfaces.IAtomContainer; import org.openscience.jchempaint.renderer.selection.RectangleSelection; /** * @author Ralf Stephan <ralf@ark.in-berlin.de> */ public class Issue139Test extends AbstractAppletTest { @Test public void testIssue139() { JPanelFixture jcppanel=applet.panel("appletframe"); JChemPaintPanel panel = (JChemPaintPanel)jcppanel.target; panel.get2DHub().mouseClickedDown(100, 100); panel.get2DHub().updateView(); applet.panel("renderpanel").robot.waitForIdle(); panel.get2DHub().mouseClickedUp(100, 100); panel.get2DHub().updateView(); applet.panel("renderpanel").robot.waitForIdle(); applet.button("select").target.doClick(); panel.get2DHub().updateView(); applet.panel("renderpanel").robot.waitForIdle(); IAtomContainer ethane = panel.getChemModel().getMoleculeSet().getAtomContainer(0); RectangleSelection sel = new RectangleSelection(); sel.addAtom (ethane.getAtom(0)); sel.addBond(ethane.getBond(0)); panel.getRenderPanel().getRenderer().getRenderer2DModel().setSelection(sel); panel.selectionChanged(); try { applet.button("cut").target.doClick(); panel.get2DHub().updateView(); applet.panel("renderpanel").robot.waitForIdle(); } catch (Exception e) { Assert.fail(); } int atomCount=0, bondCount=0, implicitHCount=0; for(IAtomContainer atc : panel.getChemModel().getMoleculeSet().atomContainers()) { for (IAtom a : atc.atoms()) implicitHCount += a.getImplicitHydrogenCount(); atomCount+=atc.getAtomCount(); bondCount+=atc.getBondCount(); } Assert.assertEquals(1, atomCount); Assert.assertEquals(0, bondCount); Assert.assertEquals(4, implicitHCount); try { applet.button("paste").target.doClick(); } catch (Exception e) { Assert.fail(); } panel.get2DHub().updateView(); applet.panel("renderpanel").robot.waitForIdle(); atomCount=0; bondCount=0; implicitHCount=0; for(IAtomContainer atc : panel.getChemModel().getMoleculeSet().atomContainers()) { for (IAtom a : atc.atoms()) implicitHCount += a.getImplicitHydrogenCount(); atomCount+=atc.getAtomCount(); bondCount+=atc.getBondCount(); } Assert.assertEquals(2, atomCount); Assert.assertEquals(0, bondCount); Assert.assertEquals(8, implicitHCount); } }
Java
2D
JChemPaint/jchempaint
core/src/test/java/org/openscience/jchempaint/AllJCPTests.java
.java
1,121
43
package org.openscience.jchempaint; import org.junit.runner.RunWith; import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; @RunWith(value=Suite.class) @SuiteClasses( value = { JCPEditorAppletMenuTest.class, JCPEditorAppletDrawingTest.class, JCPEditorAppletBugsTest.class, JCPEditorAppletUndoRedoTest.class, BugSF65Test.class, BugSF70Test.class, BugSF75Test.class, BugSF80Test.class, Issue4Test.class, Issue8Test.class, Issue10Test.class, //inclusion of this test depends on #11 or #138 //Issue11Test.class, Issue19Test.class, Issue32Test.class, Issue40Test.class, Issue58Test.class, Issue71Test.class, Issue73Test.class, Issue76Test.class, Issue81Test.class, Issue82Test.class, Issue116Test.class, Issue129Test.class, Issue137Test.class, Issue139Test.class, MenuCutTest.class, MenuIsotopeTest.class, SetSmilesTest.class } ) public class AllJCPTests { }
Java
2D
JChemPaint/jchempaint
core/src/test/java/org/openscience/jchempaint/Issue8Test.java
.java
2,025
58
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.openscience.jchempaint; import org.fest.swing.fixture.JPanelFixture; import org.junit.Assert; import org.junit.Test; import org.openscience.jchempaint.action.JCPAction; /** * Draw chain, replace middle atom with H, clean up. * Should not throw anything. * @author <ralf@ark.in-berlin.de> */ public class Issue8Test extends AbstractAppletTest { @Test public void testIssue8() { JPanelFixture jcppanel=applet.panel("appletframe"); JChemPaintPanel pane = (JChemPaintPanel)jcppanel.target; applet.button("chain").target.doClick(); pane.get2DHub().updateView(); applet.panel("renderpanel").robot.waitForIdle(); pane.get2DHub().mouseClickedDown(100, 100); pane.get2DHub().updateView(); applet.panel("renderpanel").robot.waitForIdle(); pane.get2DHub().mouseDrag(100, 100, 300, 100, 0); pane.get2DHub().updateView(); applet.panel("renderpanel").robot.waitForIdle(); pane.get2DHub().mouseClickedUp(300, 100); pane.get2DHub().updateView(); applet.panel("renderpanel").robot.waitForIdle(); applet.button("H").target.doClick(); pane.get2DHub().updateView(); applet.panel("renderpanel").robot.waitForIdle(); pane.get2DHub().mouseClickedDown(180, 100); pane.get2DHub().updateView(); applet.panel("renderpanel").robot.waitForIdle(); pane.get2DHub().mouseClickedUp(180, 100); pane.get2DHub().updateView(); applet.panel("renderpanel").robot.waitForIdle(); try { // For some reason this does not work // applet.button("cleanup").target.doClick(); // panel.get2DHub().updateView(); // so we crank the lever manually JCPAction act = new JCPAction().getAction(panel, "org.openscience.jchempaint.action.CleanupAction"); act.actionPerformed(null); } catch (Exception e) { Assert.fail(); } panel.get2DHub().updateView(); applet.panel("renderpanel").robot.waitForIdle(); } }
Java
2D
JChemPaint/jchempaint
core/src/test/java/org/openscience/jchempaint/Issue116Test.java
.java
3,184
85
package org.openscience.jchempaint; import org.fest.swing.fixture.JPanelFixture; import org.junit.Assert; import org.junit.Test; import org.openscience.cdk.interfaces.IAtom; import org.openscience.cdk.interfaces.IAtomContainer; import org.openscience.jchempaint.action.JCPAction; /** * @author Ralf Stephan <ralf@ark.in-berlin.de> */ public class Issue116Test extends AbstractAppletTest { @Test public void testIssue116() { JPanelFixture jcppanel=applet.panel("appletframe"); JChemPaintPanel panel = (JChemPaintPanel)jcppanel.target; applet.button("H").target.doClick(); panel.get2DHub().updateView(); applet.panel("renderpanel").robot.waitForIdle(); panel.get2DHub().mouseClickedDown(100, 100); panel.get2DHub().updateView(); applet.panel("renderpanel").robot.waitForIdle(); panel.get2DHub().mouseClickedUp(100, 100); panel.get2DHub().updateView(); applet.panel("renderpanel").robot.waitForIdle(); int atomCount=0, bondCount=0, implicitHCount=0; for(IAtomContainer atc : panel.getChemModel().getMoleculeSet().atomContainers()) { for (IAtom a : atc.atoms()) implicitHCount += a.getImplicitHydrogenCount(); atomCount+=atc.getAtomCount(); bondCount+=atc.getBondCount(); } Assert.assertEquals(1, atomCount); Assert.assertEquals(0, bondCount); Assert.assertEquals(1, implicitHCount); applet.button("O").target.doClick(); panel.get2DHub().updateView(); applet.panel("renderpanel").robot.waitForIdle(); panel.get2DHub().mouseClickedDown(100, 100); panel.get2DHub().updateView(); applet.panel("renderpanel").robot.waitForIdle(); panel.get2DHub().mouseClickedUp(100, 100); panel.get2DHub().updateView(); applet.panel("renderpanel").robot.waitForIdle(); atomCount=0; bondCount=0; implicitHCount=0; for(IAtomContainer atc : panel.getChemModel().getMoleculeSet().atomContainers()) { for (IAtom a : atc.atoms()) implicitHCount += a.getImplicitHydrogenCount(); atomCount+=atc.getAtomCount(); bondCount+=atc.getBondCount(); } Assert.assertEquals(1, atomCount); Assert.assertEquals(0, bondCount); Assert.assertEquals(2, implicitHCount); try { // For some reason this does not work // applet.button("undo").target.doClick(); // panel.get2DHub().updateView(); // so we crank the lever manually JCPAction act = new JCPAction().getAction(panel, "org.openscience.jchempaint.action.UndoAction"); act.actionPerformed(null); } catch (Exception e) { Assert.fail(); } panel.get2DHub().updateView(); applet.panel("renderpanel").robot.waitForIdle(); atomCount=0; bondCount=0; implicitHCount=0; for(IAtomContainer atc : panel.getChemModel().getMoleculeSet().atomContainers()) { for (IAtom a : atc.atoms()) implicitHCount += a.getImplicitHydrogenCount(); atomCount+=atc.getAtomCount(); bondCount+=atc.getBondCount(); } Assert.assertEquals(1, atomCount); Assert.assertEquals(0, bondCount); Assert.assertEquals(1, implicitHCount); } }
Java
2D
JChemPaint/jchempaint
core/src/test/java/org/openscience/jchempaint/Issue4Test.java
.java
2,100
46
package org.openscience.jchempaint; import java.awt.Point; import org.junit.Assert; import org.junit.Test; public class Issue4Test extends AbstractAppletTest { @Test public void testIssue4() { applet.button("C").target.doClick(); applet.button("C").target.doClick(); applet.panel("renderpanel").robot.click(applet.panel("renderpanel").component(),new Point(100,100)); applet.button("select").target.doClick(); applet.panel("renderpanel").robot.click(applet.panel("renderpanel").component(),new Point(100,100)); applet.panel("renderpanel").robot.waitForIdle(); try { applet.button("H").target.doClick(); applet.panel("renderpanel").robot.waitForIdle(); applet.button("select").target.doClick(); applet.panel("renderpanel").robot.click(applet.panel("renderpanel").component(),new Point(100,100)); applet.panel("renderpanel").robot.waitForIdle(); applet.button("N").target.doClick(); applet.panel("renderpanel").robot.waitForIdle(); applet.button("select").target.doClick(); applet.panel("renderpanel").robot.click(applet.panel("renderpanel").component(),new Point(100,100)); applet.panel("renderpanel").robot.waitForIdle(); applet.button("I").target.doClick(); applet.panel("renderpanel").robot.waitForIdle(); applet.button("select").target.doClick(); applet.panel("renderpanel").robot.click(applet.panel("renderpanel").component(),new Point(100,100)); applet.panel("renderpanel").robot.waitForIdle(); applet.button("S").target.doClick(); applet.panel("renderpanel").robot.waitForIdle(); applet.button("select").target.doClick(); applet.panel("renderpanel").robot.click(applet.panel("renderpanel").component(),new Point(100,100)); applet.panel("renderpanel").robot.waitForIdle(); applet.button("C").target.doClick(); applet.panel("renderpanel").robot.waitForIdle(); } catch(Exception e) { Assert.fail(); } } }
Java
2D
JChemPaint/jchempaint
core/src/test/java/org/openscience/jchempaint/Issue10Test.java
.java
1,447
52
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.openscience.jchempaint; import org.fest.swing.fixture.JPanelFixture; import org.junit.Assert; import org.junit.Test; import org.openscience.cdk.interfaces.IAtomContainer; /** * @author Ralf Stephan <ralf@ark.in-berlin.de> * * Tests Undo after SMILES input. See also Issue81Test */ public class Issue10Test extends AbstractAppletTest { @Test public void testIssue10() { JPanelFixture jcppanel=applet.panel("appletframe"); JChemPaintPanel pane = (JChemPaintPanel)jcppanel.target; try { jcpApplet.setSmiles("CCCC"); pane.get2DHub().updateView(); } catch (Exception e) { Assert.fail(); } applet.button("undo").target.doClick(); pane.get2DHub().updateView(); int atomCount=0, bondCount=0; for(IAtomContainer atc : pane.getChemModel().getMoleculeSet().atomContainers()) { atomCount+=atc.getAtomCount(); bondCount+=atc.getBondCount(); } Assert.assertEquals(0, atomCount); Assert.assertEquals(0, bondCount); applet.button("redo").target.doClick(); pane.get2DHub().updateView(); atomCount=0; bondCount=0; for(IAtomContainer atc : pane.getChemModel().getMoleculeSet().atomContainers()) { atomCount+=atc.getAtomCount(); bondCount+=atc.getBondCount(); } Assert.assertEquals(4, atomCount); Assert.assertEquals(3, bondCount); } }
Java
2D
JChemPaint/jchempaint
core/src/test/java/org/openscience/jchempaint/Issue40Test.java
.java
2,092
62
package org.openscience.jchempaint; import javax.vecmath.Point2d; import org.fest.swing.fixture.JPanelFixture; import org.junit.Assert; import org.junit.Test; import org.openscience.cdk.interfaces.IAtom; import org.openscience.cdk.interfaces.IAtomContainer; import org.openscience.jchempaint.action.JCPAction; /** * @author Ralf Stephan <ralf@ark.in-berlin.de> */ public class Issue40Test extends AbstractAppletTest { @Test public void testIssue40() { JPanelFixture jcppanel=applet.panel("appletframe"); JChemPaintPanel panel = (JChemPaintPanel)jcppanel.target; applet.button("C").target.doClick(); applet.button("chain").target.doClick(); panel.get2DHub().mouseClickedDown(100, 100); panel.get2DHub().mouseDrag(100, 100, 300, 100, 0); panel.get2DHub().mouseClickedUp(300, 100); panel.get2DHub().updateView(); applet.panel("renderpanel").robot.waitForIdle(); Point2d p = getAtomPoint(panel,0,1); try { panel.get2DHub().mouseClickedDown((int)p.x, (int)p.y); panel.get2DHub().mouseClickedUp((int)p.x, (int)p.y); } catch(Exception e) { Assert.fail(); } int atomCount=0, bondCount=0, implicitHCount=0; for(IAtomContainer atc : panel.getChemModel().getMoleculeSet().atomContainers()) { for (IAtom a : atc.atoms()) implicitHCount += a.getImplicitHydrogenCount(); atomCount+=atc.getAtomCount(); bondCount+=atc.getBondCount(); } Assert.assertEquals(6, atomCount); Assert.assertEquals(5, bondCount); Assert.assertEquals(14, implicitHCount); try { JCPAction act = new JCPAction().getAction(panel, "org.openscience.jchempaint.action.UndoAction"); act.actionPerformed(null); } catch (NullPointerException e) { Assert.fail(); } atomCount=0; bondCount=0; for(IAtomContainer atc : panel.getChemModel().getMoleculeSet().atomContainers()) { atomCount+=atc.getAtomCount(); bondCount+=atc.getBondCount(); } Assert.assertEquals(0, atomCount); Assert.assertEquals(0, bondCount); } }
Java
2D
JChemPaint/jchempaint
core/src/test/java/org/openscience/jchempaint/BugSF65Test.java
.java
1,336
37
package org.openscience.jchempaint; import java.awt.Point; import javax.vecmath.Point2d; import org.fest.swing.core.MouseButton; import org.fest.swing.fixture.JPanelFixture; import org.junit.Assert; import org.junit.Test; import org.openscience.cdk.interfaces.IAtomContainer; public class BugSF65Test extends AbstractAppletTest { @Test public void testBug65() { JPanelFixture jcppanel=applet.panel("appletframe"); JChemPaintPanel panel = (JChemPaintPanel)jcppanel.target; applet.button("hexagon").target.doClick(); applet.click(); applet.button("eraser").target.doClick(); Point2d point = getBondPoint(panel,0); applet.panel("renderpanel").robot.click(applet.panel("renderpanel").component(), new Point((int)point.x, (int)point.y), MouseButton.LEFT_BUTTON,1); point = getBondPoint(panel,2); applet.panel("renderpanel").robot.click(applet.panel("renderpanel").component(), new Point((int)point.x, (int)point.y), MouseButton.LEFT_BUTTON,1); int atomCount=0, bondCount=0; for(IAtomContainer atc : panel.getChemModel().getMoleculeSet().atomContainers()) { atomCount+=atc.getAtomCount(); bondCount+=atc.getBondCount(); } Assert.assertEquals(6, atomCount); Assert.assertEquals(4, bondCount); restoreModelToEmpty(); } }
Java
2D
JChemPaint/jchempaint
core/src/test/java/org/openscience/jchempaint/Issue76Test.java
.java
3,301
91
/* */ package org.openscience.jchempaint; import javax.vecmath.Point2d; import org.fest.swing.fixture.JPanelFixture; import org.junit.Assert; import org.junit.Test; import org.openscience.cdk.interfaces.IAtom; import org.openscience.cdk.interfaces.IAtomContainer; /** * #76: synopsis: place a benzene; draw chain from a benzene C-atom * should not change this atom's position; first undo should give unaltered * benzene; second back to zero, without NullPointerException * #154: merging with chain garbles implicit Hs * #158: with chain, single click on atom creates undo slot, should do nothing * @author Ralf Stephan <ralf@ark.in-berlin.de> */ public class Issue76Test extends AbstractAppletTest { @Test public void testIssue76() { JPanelFixture jcppanel=applet.panel("appletframe"); JChemPaintPanel pane = (JChemPaintPanel)jcppanel.target; applet.button("benzene").target.doClick(); pane.get2DHub().mouseClickedDown(100, 100); pane.get2DHub().mouseClickedUp(100, 100); pane.get2DHub().updateView(); applet.panel("renderpanel").robot.waitForIdle(); Point2d atompos=pane.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(3).getPoint2d(); atompos = pane.getRenderPanel().getRenderer().toScreenCoordinates(atompos.x, atompos.y); int x = (int) atompos.x; int y = (int) atompos.y; applet.button("C").target.doClick(); applet.button("chain").target.doClick(); pane.get2DHub().mouseClickedDown(x, y); pane.get2DHub().updateView(); applet.panel("renderpanel").robot.waitForIdle(); pane.get2DHub().mouseClickedUp(x, y); pane.get2DHub().updateView(); applet.panel("renderpanel").robot.waitForIdle(); pane.get2DHub().mouseClickedDown(x, y); pane.get2DHub().updateView(); applet.panel("renderpanel").robot.waitForIdle(); pane.get2DHub().mouseDrag(x, y, x+200, y, 0); pane.get2DHub().updateView(); applet.panel("renderpanel").robot.waitForIdle(); pane.get2DHub().mouseClickedUp(x+200, y); pane.get2DHub().updateView(); applet.panel("renderpanel").robot.waitForIdle(); int atomCount=0, bondCount=0, implicitHCount=0; for(IAtomContainer atc : panel.getChemModel().getMoleculeSet().atomContainers()) { for (IAtom a : atc.atoms()) implicitHCount += a.getImplicitHydrogenCount(); atomCount+=atc.getAtomCount(); bondCount+=atc.getBondCount(); } Assert.assertEquals(11, atomCount); Assert.assertEquals(11, bondCount); Assert.assertEquals(16, implicitHCount); applet.button("undo").target.doClick(); pane.get2DHub().updateView(); atomCount=0; bondCount=0; for(IAtomContainer atc : pane.getChemModel().getMoleculeSet().atomContainers()) { atomCount+=atc.getAtomCount(); bondCount+=atc.getBondCount(); } Assert.assertEquals(6, atomCount); Assert.assertEquals(6, bondCount); try { applet.button("undo").target.doClick(); pane.get2DHub().updateView(); } catch (Exception e) { Assert.fail(); } atomCount=0; bondCount=0; for(IAtomContainer atc : pane.getChemModel().getMoleculeSet().atomContainers()) { atomCount+=atc.getAtomCount(); bondCount+=atc.getBondCount(); } Assert.assertEquals(0, atomCount); Assert.assertEquals(0, bondCount); } }
Java
2D
JChemPaint/jchempaint
core/src/test/java/org/openscience/jchempaint/Issue19Test.java
.java
1,167
39
package org.openscience.jchempaint; import java.awt.AWTException; import java.awt.Point; import java.awt.Robot; import java.awt.event.KeyEvent; import org.junit.Assert; import org.junit.Test; /** * @author Ralf Stephan <ralf@ark.in-berlin.de> */ public class Issue19Test extends AbstractAppletTest { @Test public void testIssue19() throws AWTException { Robot robot = new Robot(); applet.button("C").target.doClick(); applet.panel("renderpanel").robot.click(applet.panel("renderpanel").component(),new Point(100,100)); applet.button("select").target.doClick(); applet.panel("renderpanel").robot.click(applet.panel("renderpanel").component(),new Point(100,100)); applet.panel("renderpanel").robot.moveMouse(100,100); try { robot.keyPress(KeyEvent.VK_DELETE); robot.delay(500); robot.keyRelease(KeyEvent.VK_DELETE); robot.delay(500); robot.keyPress(KeyEvent.VK_DELETE); robot.delay(500); robot.keyRelease(KeyEvent.VK_DELETE); robot.delay(500); } catch (Exception e) { Assert.fail(); } } }
Java
2D
JChemPaint/jchempaint
core/src/test/java/org/openscience/jchempaint/MenuCutTest.java
.java
2,238
38
package org.openscience.jchempaint; import java.awt.Point; import javax.vecmath.Point2d; import org.fest.swing.fixture.JPopupMenuFixture; import org.junit.Assert; import org.junit.Test; import org.openscience.cdk.interfaces.IAtom; import org.openscience.jchempaint.renderer.selection.SingleSelection; public class MenuCutTest extends AbstractAppletTest { @Test public void testMenuCut(){ restoreModelWithBasicmol(); panel.getRenderPanel().getRenderer().getRenderer2DModel().setSelection(new SingleSelection<IAtom>(panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(0))); panel.selectionChanged(); Assert.assertEquals(8,panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtomCount()); applet.menuItem("cut").click(); Assert.assertEquals(7,panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtomCount()); applet.menuItem("paste").click(); Assert.assertEquals(2,panel.getChemModel().getMoleculeSet().getAtomContainerCount()); Assert.assertEquals(7,panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtomCount()); Assert.assertEquals(1,panel.getChemModel().getMoleculeSet().getAtomContainer(1).getAtomCount()); Point2d moveto=panel.getRenderPanel().getRenderer().toScreenCoordinates(panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(4).getPoint2d().x,panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(4).getPoint2d().y); JPopupMenuFixture popup = applet.panel("renderpanel").showPopupMenuAt(new Point((int)moveto.x,(int)moveto.y)); //try {Thread.sleep(5000);} catch (InterruptedException e) {e.printStackTrace();} popup.menuItem("cut").click(); Assert.assertEquals(3,panel.getChemModel().getMoleculeSet().getAtomContainerCount()); //try {Thread.sleep(5000);} catch (InterruptedException e) {e.printStackTrace();} Assert.assertEquals(1,panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtomCount()); Assert.assertEquals(4,panel.getChemModel().getMoleculeSet().getAtomContainer(1).getAtomCount()); Assert.assertEquals(2,panel.getChemModel().getMoleculeSet().getAtomContainer(2).getAtomCount()); } }
Java
2D
JChemPaint/jchempaint
core/src/test/java/org/openscience/jchempaint/JCPEditorAppletDrawingTest.java
.java
34,171
356
package org.openscience.jchempaint; import java.awt.Point; import java.io.IOException; import javax.vecmath.Point2d; import org.fest.swing.core.ComponentDragAndDrop; import org.fest.swing.core.MouseButton; import org.fest.swing.fixture.DialogFixture; import org.fest.swing.fixture.JPanelFixture; import org.junit.Assert; import org.junit.Test; import org.openscience.cdk.exception.CDKException; import org.openscience.cdk.interfaces.IBond; import org.openscience.jchempaint.renderer.selection.SingleSelection; public class JCPEditorAppletDrawingTest extends AbstractAppletTest{ @Test public void testAddBond() throws CDKException, ClassNotFoundException, IOException, CloneNotSupportedException { restoreModelWithBasicmol(); JPanelFixture jcppanel=applet.panel("appletframe"); JChemPaintPanel panel = (JChemPaintPanel)jcppanel.target; int oldAtomCount=panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtomCount(); //using bond button applet.button("bondTool").target.doClick(); //can we add a new bond? Point2d moveto=panel.getRenderPanel().getRenderer().toScreenCoordinates(panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(0).getPoint2d().x,panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(1).getPoint2d().y); applet.panel("renderpanel").robot.click(applet.panel("renderpanel").component(), new Point((int)moveto.x, (int)moveto.y), MouseButton.LEFT_BUTTON,1); Assert.assertEquals(oldAtomCount+1, panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtomCount()); //can we convert bond order? int oldhydrogencount0 = panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(2).getImplicitHydrogenCount().intValue(); int oldhydrogencount1 = panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(3).getImplicitHydrogenCount().intValue(); moveto=panel.getRenderPanel().getRenderer().toScreenCoordinates((panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(2).getPoint2d().x+panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(3).getPoint2d().x)/2,(panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(2).getPoint2d().y+panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(3).getPoint2d().y)/2); applet.panel("renderpanel").robot.click(applet.panel("renderpanel").component(), new Point((int)moveto.x, (int)moveto.y), MouseButton.LEFT_BUTTON,1); Assert.assertEquals(IBond.Order.DOUBLE, panel.getChemModel().getMoleculeSet().getAtomContainer(0).getBond(2).getOrder()); Assert.assertEquals(oldhydrogencount0-1, panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(2).getImplicitHydrogenCount().intValue()); Assert.assertEquals(oldhydrogencount1-1, panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(3).getImplicitHydrogenCount().intValue()); //using up bond button, panel.getRenderPanel().getRenderer().getRenderer2DModel().setSelection(new SingleSelection<IBond>(panel.getChemModel().getMoleculeSet().getAtomContainer(0).getBond(4))); applet.button("up_bond").target.doClick(); //was the selected bond changed Assert.assertEquals(IBond.Stereo.UP, panel.getChemModel().getMoleculeSet().getAtomContainer(0).getBond(4).getStereo()); //can we add a new bond? moveto=panel.getRenderPanel().getRenderer().toScreenCoordinates(panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(0).getPoint2d().x,panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(1).getPoint2d().y); applet.panel("renderpanel").robot.click(applet.panel("renderpanel").component(), new Point((int)moveto.x, (int)moveto.y), MouseButton.LEFT_BUTTON,1); Assert.assertEquals(oldAtomCount+2, panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtomCount()); Assert.assertEquals(IBond.Stereo.UP, panel.getChemModel().getMoleculeSet().getAtomContainer(0).getBond(panel.getChemModel().getMoleculeSet().getAtomContainer(0).getBondCount()-1).getStereo()); //can we convert an existing one? moveto=panel.getRenderPanel().getRenderer().toScreenCoordinates((panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(2).getPoint2d().x+panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(3).getPoint2d().x)/2,(panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(2).getPoint2d().y+panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(3).getPoint2d().y)/2); applet.panel("renderpanel").robot.click(applet.panel("renderpanel").component(), new Point((int)moveto.x, (int)moveto.y), MouseButton.LEFT_BUTTON,1); Assert.assertEquals(IBond.Stereo.UP, panel.getChemModel().getMoleculeSet().getAtomContainer(0).getBond(2).getStereo()); //using down bond button, panel.getRenderPanel().getRenderer().getRenderer2DModel().setSelection(new SingleSelection<IBond>(panel.getChemModel().getMoleculeSet().getAtomContainer(0).getBond(4))); applet.button("down_bond").target.doClick(); //was the selected bond changed Assert.assertEquals(IBond.Stereo.DOWN, panel.getChemModel().getMoleculeSet().getAtomContainer(0).getBond(4).getStereo()); //can we add a new bond? moveto=panel.getRenderPanel().getRenderer().toScreenCoordinates(panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(0).getPoint2d().x,panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(1).getPoint2d().y); applet.panel("renderpanel").robot.click(applet.panel("renderpanel").component(), new Point((int)moveto.x, (int)moveto.y), MouseButton.LEFT_BUTTON,1); Assert.assertEquals(oldAtomCount+3, panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtomCount()); Assert.assertEquals(IBond.Stereo.DOWN, panel.getChemModel().getMoleculeSet().getAtomContainer(0).getBond(panel.getChemModel().getMoleculeSet().getAtomContainer(0).getBondCount()-1).getStereo()); //can we convert an existing one? moveto=panel.getRenderPanel().getRenderer().toScreenCoordinates((panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(2).getPoint2d().x+panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(3).getPoint2d().x)/2,(panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(2).getPoint2d().y+panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(3).getPoint2d().y)/2); applet.panel("renderpanel").robot.click(applet.panel("renderpanel").component(), new Point((int)moveto.x, (int)moveto.y), MouseButton.LEFT_BUTTON,1); Assert.assertEquals(IBond.Stereo.DOWN, panel.getChemModel().getMoleculeSet().getAtomContainer(0).getBond(2).getStereo()); //using undefined bond button, panel.getRenderPanel().getRenderer().getRenderer2DModel().setSelection(new SingleSelection<IBond>(panel.getChemModel().getMoleculeSet().getAtomContainer(0).getBond(4))); applet.button("undefined_bond").target.doClick(); //was the selected bond changed Assert.assertEquals(IBond.Stereo.UP_OR_DOWN, panel.getChemModel().getMoleculeSet().getAtomContainer(0).getBond(4).getStereo()); //can we add a new bond? moveto=panel.getRenderPanel().getRenderer().toScreenCoordinates(panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(0).getPoint2d().x,panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(1).getPoint2d().y); applet.panel("renderpanel").robot.click(applet.panel("renderpanel").component(), new Point((int)moveto.x, (int)moveto.y), MouseButton.LEFT_BUTTON,1); Assert.assertEquals(oldAtomCount+4, panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtomCount()); Assert.assertEquals(IBond.Stereo.UP_OR_DOWN, panel.getChemModel().getMoleculeSet().getAtomContainer(0).getBond(panel.getChemModel().getMoleculeSet().getAtomContainer(0).getBondCount()-1).getStereo()); //can we convert an existing one? moveto=panel.getRenderPanel().getRenderer().toScreenCoordinates((panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(2).getPoint2d().x+panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(3).getPoint2d().x)/2,(panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(2).getPoint2d().y+panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(3).getPoint2d().y)/2); applet.panel("renderpanel").robot.click(applet.panel("renderpanel").component(), new Point((int)moveto.x, (int)moveto.y), MouseButton.LEFT_BUTTON,1); Assert.assertEquals(IBond.Stereo.UP_OR_DOWN, panel.getChemModel().getMoleculeSet().getAtomContainer(0).getBond(2).getStereo()); //using undefined stereo button, panel.getRenderPanel().getRenderer().getRenderer2DModel().setSelection(new SingleSelection<IBond>(panel.getChemModel().getMoleculeSet().getAtomContainer(0).getBond(4))); applet.button("undefined_stereo_bond").target.doClick(); //was the selected bond changed Assert.assertEquals(IBond.Stereo.E_OR_Z, panel.getChemModel().getMoleculeSet().getAtomContainer(0).getBond(4).getStereo()); //can we add a new bond? moveto=panel.getRenderPanel().getRenderer().toScreenCoordinates(panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(0).getPoint2d().x,panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(1).getPoint2d().y); applet.panel("renderpanel").robot.click(applet.panel("renderpanel").component(), new Point((int)moveto.x, (int)moveto.y), MouseButton.LEFT_BUTTON,1); Assert.assertEquals(oldAtomCount+5, panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtomCount()); Assert.assertEquals(IBond.Stereo.E_OR_Z, panel.getChemModel().getMoleculeSet().getAtomContainer(0).getBond(panel.getChemModel().getMoleculeSet().getAtomContainer(0).getBondCount()-1).getStereo()); //can we convert an existing one? moveto=panel.getRenderPanel().getRenderer().toScreenCoordinates((panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(2).getPoint2d().x+panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(3).getPoint2d().x)/2,(panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(2).getPoint2d().y+panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(3).getPoint2d().y)/2); applet.panel("renderpanel").robot.click(applet.panel("renderpanel").component(), new Point((int)moveto.x, (int)moveto.y), MouseButton.LEFT_BUTTON,1); Assert.assertEquals(IBond.Stereo.E_OR_Z, panel.getChemModel().getMoleculeSet().getAtomContainer(0).getBond(2).getStereo()); } @Test public void testElement() throws CDKException, ClassNotFoundException, IOException, CloneNotSupportedException { //we go into bond_down mode to see that hitting O button actually changes activeDrawModule restoreModelWithBasicmol(); applet.button("down_bond").target.doClick(); JPanelFixture jcppanel=applet.panel("appletframe"); JChemPaintPanel panel = (JChemPaintPanel)jcppanel.target; int oldAtomCount=panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtomCount(); applet.button("O").target.doClick(); Assert.assertEquals("O",panel.get2DHub().getActiveDrawModule().getID()); Point2d moveto=panel.getRenderPanel().getRenderer().toScreenCoordinates(panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(0).getPoint2d().x,panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(0).getPoint2d().y); applet.panel("renderpanel").robot.click(applet.panel("renderpanel").component(), new Point((int)moveto.x, (int)moveto.y), MouseButton.LEFT_BUTTON,1); Assert.assertEquals("O",panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(0).getSymbol()); applet.button("bondTool").target.doClick(); moveto=panel.getRenderPanel().getRenderer().toScreenCoordinates(panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(0).getPoint2d().x,panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(0).getPoint2d().y); applet.panel("renderpanel").robot.click(applet.panel("renderpanel").component(), new Point((int)moveto.x, (int)moveto.y), MouseButton.LEFT_BUTTON,1); Assert.assertEquals(oldAtomCount+1, panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtomCount()); Assert.assertEquals("O",panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtomCount()-1).getSymbol()); Assert.assertEquals("O",panel.get2DHub().getController2DModel().getDrawElement()); } @Test public void testPeriodictable() throws CDKException, ClassNotFoundException, IOException, CloneNotSupportedException { restoreModelWithBasicmol(); JPanelFixture jcppanel=applet.panel("appletframe"); JChemPaintPanel panel = (JChemPaintPanel)jcppanel.target; int oldAtomCount=panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtomCount(); applet.button("periodictable").target.doClick(); DialogFixture dialog = applet.dialog(); dialog.button("Li").target.doClick(); Point2d moveto=panel.getRenderPanel().getRenderer().toScreenCoordinates(panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(0).getPoint2d().x,panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(0).getPoint2d().y); applet.panel("renderpanel").robot.click(applet.panel("renderpanel").component(), new Point((int)moveto.x, (int)moveto.y), MouseButton.LEFT_BUTTON,1); Assert.assertEquals("Li",panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(0).getSymbol()); applet.button("bondTool").target.doClick(); moveto=panel.getRenderPanel().getRenderer().toScreenCoordinates(panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(0).getPoint2d().x,panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(0).getPoint2d().y); applet.panel("renderpanel").robot.click(applet.panel("renderpanel").component(), new Point((int)moveto.x, (int)moveto.y), MouseButton.LEFT_BUTTON,1); Assert.assertEquals(oldAtomCount+1, panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtomCount()); Assert.assertEquals("Li",panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtomCount()-1).getSymbol()); } @Test public void testEnterelement() throws CDKException, ClassNotFoundException, IOException, CloneNotSupportedException { restoreModelWithBasicmol(); JPanelFixture jcppanel=applet.panel("appletframe"); JChemPaintPanel panel = (JChemPaintPanel)jcppanel.target; int oldAtomCount=panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtomCount(); applet.button("enterelement").target.doClick(); Point2d moveto=panel.getRenderPanel().getRenderer().toScreenCoordinates(panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(0).getPoint2d().x,panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(0).getPoint2d().y); applet.panel("renderpanel").robot.click(applet.panel("renderpanel").component(), new Point((int)moveto.x, (int)moveto.y), MouseButton.LEFT_BUTTON,1); DialogFixture dialog = applet.dialog(); dialog.textBox().setText("U"); dialog.button("ok").target.doClick(); Assert.assertEquals("U",panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(0).getSymbol()); applet.button("bondTool").target.doClick(); moveto=panel.getRenderPanel().getRenderer().toScreenCoordinates(panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(0).getPoint2d().x,panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(0).getPoint2d().y); applet.panel("renderpanel").robot.click(applet.panel("renderpanel").component(), new Point((int)moveto.x, (int)moveto.y), MouseButton.LEFT_BUTTON,1); Assert.assertEquals(oldAtomCount+1, panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtomCount()); Assert.assertEquals("U",panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtomCount()-1).getSymbol()); } @Test public void testTriangle() throws CDKException, ClassNotFoundException, IOException, CloneNotSupportedException { restoreModelWithBasicmol(); JPanelFixture jcppanel=applet.panel("appletframe"); JChemPaintPanel panel = (JChemPaintPanel)jcppanel.target; int oldAtomCount=panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtomCount(); //we add a triangle to an atom applet.button("triangle").target.doClick(); Point2d moveto=panel.getRenderPanel().getRenderer().toScreenCoordinates(panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(3).getPoint2d().x,panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(3).getPoint2d().y); applet.panel("renderpanel").robot.click(applet.panel("renderpanel").component(), new Point((int)moveto.x, (int)moveto.y), MouseButton.LEFT_BUTTON,1); Assert.assertEquals(oldAtomCount+2, panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtomCount()); //and a bond moveto=panel.getRenderPanel().getRenderer().toScreenCoordinates((panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(2).getPoint2d().x+panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(3).getPoint2d().x)/2,(panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(2).getPoint2d().y+panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(3).getPoint2d().y)/2); applet.panel("renderpanel").robot.click(applet.panel("renderpanel").component(), new Point((int)moveto.x, (int)moveto.y), MouseButton.LEFT_BUTTON,1); Assert.assertEquals(oldAtomCount+3, panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtomCount()); restoreModelWithBasicmol(); } @Test public void testPentagon() throws CDKException, ClassNotFoundException, IOException, CloneNotSupportedException { restoreModelWithBasicmol(); JPanelFixture jcppanel=applet.panel("appletframe"); JChemPaintPanel panel = (JChemPaintPanel)jcppanel.target; int oldAtomCount=panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtomCount(); //we add a pentagon to an atom applet.button("pentagon").target.doClick(); Point2d moveto=panel.getRenderPanel().getRenderer().toScreenCoordinates(panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(3).getPoint2d().x,panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(3).getPoint2d().y); applet.panel("renderpanel").robot.click(applet.panel("renderpanel").component(), new Point((int)moveto.x, (int)moveto.y), MouseButton.LEFT_BUTTON,1); Assert.assertEquals(oldAtomCount+4, panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtomCount()); //and a bond moveto=panel.getRenderPanel().getRenderer().toScreenCoordinates((panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(2).getPoint2d().x+panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(3).getPoint2d().x)/2,(panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(2).getPoint2d().y+panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(3).getPoint2d().y)/2); applet.panel("renderpanel").robot.click(applet.panel("renderpanel").component(), new Point((int)moveto.x, (int)moveto.y), MouseButton.LEFT_BUTTON,1); Assert.assertEquals(oldAtomCount+7, panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtomCount()); restoreModelWithBasicmol(); } @Test public void testHexagon() throws CDKException, ClassNotFoundException, IOException, CloneNotSupportedException { restoreModelWithBasicmol(); JPanelFixture jcppanel=applet.panel("appletframe"); JChemPaintPanel panel = (JChemPaintPanel)jcppanel.target; int oldAtomCount=panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtomCount(); //we add a hexagon to an atom applet.button("hexagon").target.doClick(); Point2d moveto=panel.getRenderPanel().getRenderer().toScreenCoordinates(panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(3).getPoint2d().x,panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(3).getPoint2d().y); applet.panel("renderpanel").robot.click(applet.panel("renderpanel").component(), new Point((int)moveto.x, (int)moveto.y), MouseButton.LEFT_BUTTON,1); Assert.assertEquals(oldAtomCount+5, panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtomCount()); //and a bond moveto=panel.getRenderPanel().getRenderer().toScreenCoordinates((panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(2).getPoint2d().x+panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(3).getPoint2d().x)/2,(panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(2).getPoint2d().y+panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(3).getPoint2d().y)/2); applet.panel("renderpanel").robot.click(applet.panel("renderpanel").component(), new Point((int)moveto.x, (int)moveto.y), MouseButton.LEFT_BUTTON,1); Assert.assertEquals(oldAtomCount+9, panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtomCount()); restoreModelWithBasicmol(); } @Test public void testOctagon() throws CDKException, ClassNotFoundException, IOException, CloneNotSupportedException { restoreModelWithBasicmol(); JPanelFixture jcppanel=applet.panel("appletframe"); JChemPaintPanel panel = (JChemPaintPanel)jcppanel.target; int oldAtomCount=panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtomCount(); //we add a octagon to an atom applet.button("octagon").target.doClick(); Point2d moveto=panel.getRenderPanel().getRenderer().toScreenCoordinates(panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(3).getPoint2d().x,panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(3).getPoint2d().y); applet.panel("renderpanel").robot.click(applet.panel("renderpanel").component(), new Point((int)moveto.x, (int)moveto.y), MouseButton.LEFT_BUTTON,1); Assert.assertEquals(oldAtomCount+7, panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtomCount()); //and a bond moveto=panel.getRenderPanel().getRenderer().toScreenCoordinates((panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(2).getPoint2d().x+panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(3).getPoint2d().x)/2,(panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(2).getPoint2d().y+panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(3).getPoint2d().y)/2); applet.panel("renderpanel").robot.click(applet.panel("renderpanel").component(), new Point((int)moveto.x, (int)moveto.y), MouseButton.LEFT_BUTTON,1); Assert.assertEquals(oldAtomCount+13, panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtomCount()); restoreModelWithBasicmol(); } @Test public void testBenzene() throws CDKException, ClassNotFoundException, IOException, CloneNotSupportedException { restoreModelWithBasicmol(); JPanelFixture jcppanel=applet.panel("appletframe"); JChemPaintPanel panel = (JChemPaintPanel)jcppanel.target; int oldAtomCount=panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtomCount(); //we add a benzene to an atom applet.button("benzene").target.doClick(); Point2d moveto=panel.getRenderPanel().getRenderer().toScreenCoordinates(panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(3).getPoint2d().x,panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(3).getPoint2d().y); applet.panel("renderpanel").robot.click(applet.panel("renderpanel").component(), new Point((int)moveto.x, (int)moveto.y), MouseButton.LEFT_BUTTON,1); Assert.assertEquals(oldAtomCount+5, panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtomCount()); //and a bond moveto=panel.getRenderPanel().getRenderer().toScreenCoordinates((panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(2).getPoint2d().x+panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(3).getPoint2d().x)/2,(panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(2).getPoint2d().y+panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(3).getPoint2d().y)/2); applet.panel("renderpanel").robot.click(applet.panel("renderpanel").component(), new Point((int)moveto.x, (int)moveto.y), MouseButton.LEFT_BUTTON,1); Assert.assertEquals(oldAtomCount+9, panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtomCount()); restoreModelWithBasicmol(); } @Test public void testSquare() throws CDKException, ClassNotFoundException, IOException, CloneNotSupportedException { restoreModelWithBasicmol(); JPanelFixture jcppanel=applet.panel("appletframe"); JChemPaintPanel panel = (JChemPaintPanel)jcppanel.target; int oldAtomCount=panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtomCount(); //we add a square to an atom applet.button("square").target.doClick(); Point2d moveto=panel.getRenderPanel().getRenderer().toScreenCoordinates(panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(3).getPoint2d().x,panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(3).getPoint2d().y); applet.panel("renderpanel").robot.click(applet.panel("renderpanel").component(), new Point((int)moveto.x, (int)moveto.y), MouseButton.LEFT_BUTTON,1); Assert.assertEquals(oldAtomCount+3, panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtomCount()); //and a bond moveto=panel.getRenderPanel().getRenderer().toScreenCoordinates((panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(2).getPoint2d().x+panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(3).getPoint2d().x)/2,(panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(2).getPoint2d().y+panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(3).getPoint2d().y)/2); applet.panel("renderpanel").robot.click(applet.panel("renderpanel").component(), new Point((int)moveto.x, (int)moveto.y), MouseButton.LEFT_BUTTON,1); Assert.assertEquals(oldAtomCount+5, panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtomCount()); restoreModelWithBasicmol(); } @Test public void testDelete() throws CDKException, ClassNotFoundException, IOException, CloneNotSupportedException { restoreModelWithBasicmol(); JPanelFixture jcppanel=applet.panel("appletframe"); JChemPaintPanel panel = (JChemPaintPanel)jcppanel.target; int oldAtomCount=panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtomCount(); int oldBondCount=panel.getChemModel().getMoleculeSet().getAtomContainer(0).getBondCount(); //we delete an atom applet.button("eraser").target.doClick(); Point2d moveto=getAtomPoint(panel, 0); applet.panel("renderpanel").robot.click(applet.panel("renderpanel").component(), new Point((int)moveto.x, (int)moveto.y), MouseButton.LEFT_BUTTON,1); Assert.assertEquals(oldAtomCount-1, panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtomCount()); Assert.assertEquals(oldBondCount-1, panel.getChemModel().getMoleculeSet().getAtomContainer(0).getBondCount()); //and a (terminal) bond moveto=panel.getRenderPanel().getRenderer().toScreenCoordinates((panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(1).getPoint2d().x+panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(2).getPoint2d().x)/2,(panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(1).getPoint2d().y+panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(2).getPoint2d().y)/2); applet.panel("renderpanel").robot.click(applet.panel("renderpanel").component(), new Point((int)moveto.x, (int)moveto.y), MouseButton.LEFT_BUTTON,1); Assert.assertEquals(2, panel.getChemModel().getMoleculeSet().getAtomContainerCount()); Assert.assertEquals(oldAtomCount-1, panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtomCount()+panel.getChemModel().getMoleculeSet().getAtomContainer(1).getAtomCount()); Assert.assertEquals(oldBondCount-2, panel.getChemModel().getMoleculeSet().getAtomContainer(0).getBondCount()+panel.getChemModel().getMoleculeSet().getAtomContainer(1).getBondCount()); restoreModelWithBasicmol(); } // The double-click functionality was removed. Commented out /* @Test public void selectByDoubleClick(){ restoreModelWithBasicmol(); JPanelFixture jcppanel=applet.panel("appletframe"); JChemPaintPanel panel = (JChemPaintPanel)jcppanel.target; int oldAtomCount=panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtomCount(); //we add a hexagon applet.button("hexagon").target.doClick(); Point2d moveto=new Point2d(200,100); applet.panel("renderpanel").robot.click(applet.panel("renderpanel").component(), new Point((int)moveto.x, (int)moveto.y), MouseButton.LEFT_BUTTON,1); Assert.assertEquals(oldAtomCount+6, panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtomCount()+panel.getChemModel().getMoleculeSet().getAtomContainer(1).getAtomCount()); applet.button("select").target.doClick(); //double click on atom moveto=panel.getRenderPanel().getRenderer().toScreenCoordinates(panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(0).getPoint2d().x,panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(0).getPoint2d().y); applet.panel("renderpanel").robot.click(applet.panel("renderpanel").component(), new Point((int)moveto.x, (int)moveto.y), MouseButton.LEFT_BUTTON,2); Assert.assertEquals(oldAtomCount, panel.getRenderPanel().getRenderer().getRenderer2DModel().getSelection().getConnectedAtomContainer().getAtomCount()); }*/ @Test public void mergeAndUndoRedo(){ restoreModelWithBasicmol(); JPanelFixture jcppanel=applet.panel("appletframe"); JChemPaintPanel panel = (JChemPaintPanel)jcppanel.target; int oldAtomCount=panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtomCount(); applet.button("select").target.doClick(); Point2d startpoint=getAtomPoint(panel,0); applet.panel("renderpanel").robot.click(applet.panel("renderpanel").component(), new Point((int)startpoint.x, (int)startpoint.y), MouseButton.LEFT_BUTTON,1); ComponentDragAndDrop dandd = new ComponentDragAndDrop(applet.panel("renderpanel").robot); dandd.drag(applet.panel("renderpanel").component(), new Point((int)startpoint.x, (int)startpoint.y)); Point2d movetopoint=getAtomPoint(panel,1); dandd.drop(applet.panel("renderpanel").component(), new Point((int)movetopoint.x, (int)movetopoint.y)); Assert.assertEquals(oldAtomCount-1, panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtomCount()); movetopoint=getAtomPoint(panel,2); applet.panel("renderpanel").robot.moveMouse(applet.panel("renderpanel").component(),new Point((int)movetopoint.x, (int)movetopoint.y)); applet.button("undo").target.doClick(); Assert.assertEquals(oldAtomCount, panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtomCount()); applet.button("redo").target.doClick(); Assert.assertEquals(oldAtomCount-1, panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtomCount()); } @Test public void drawReactions(){ restoreModelToEmpty(); JPanelFixture jcppanel=applet.panel("appletframe"); JChemPaintPanel panel = (JChemPaintPanel)jcppanel.target; applet.button("hexagon").target.doClick(); applet.panel("renderpanel").robot.click(applet.panel("renderpanel").component(), new Point(100,50), MouseButton.LEFT_BUTTON,1); applet.panel("renderpanel").robot.click(applet.panel("renderpanel").component(), new Point(400,50), MouseButton.LEFT_BUTTON,1); applet.panel("renderpanel").robot.click(applet.panel("renderpanel").component(), new Point(0,0), MouseButton.RIGHT_BUTTON,1); applet.button("reactionArrow").target.doClick(); ComponentDragAndDrop dandd = new ComponentDragAndDrop(applet.panel("renderpanel").robot); dandd.drag(applet.panel("renderpanel").component(), new Point(150,50)); dandd.drop(applet.panel("renderpanel").component(), new Point(350,50)); Assert.assertEquals(1, panel.getChemModel().getReactionSet().getReactionCount()); Assert.assertEquals(1, panel.getChemModel().getReactionSet().getReaction(0).getReactantCount()); Assert.assertEquals(1, panel.getChemModel().getReactionSet().getReaction(0).getProductCount()); applet.button("hexagon").target.doClick(); applet.panel("renderpanel").robot.click(applet.panel("renderpanel").component(), new Point(500,50), MouseButton.LEFT_BUTTON,1); applet.panel("renderpanel").robot.click(applet.panel("renderpanel").component(), new Point(0,0), MouseButton.RIGHT_BUTTON,1); Point2d point = getAtomPoint(panel,0); applet.panel("renderpanel").robot.click(applet.panel("renderpanel").component(), new Point((int)point.x, (int)point.y), MouseButton.RIGHT_BUTTON,1); applet.menuItem("addProductToExistingReaction").click(); Assert.assertEquals(1, panel.getChemModel().getReactionSet().getReactionCount()); Assert.assertEquals(1, panel.getChemModel().getReactionSet().getReaction(0).getReactantCount()); Assert.assertEquals(2, panel.getChemModel().getReactionSet().getReaction(0).getProductCount()); applet.panel("renderpanel").robot.click(applet.panel("renderpanel").component(), new Point(100,300), MouseButton.LEFT_BUTTON,1); applet.panel("renderpanel").robot.click(applet.panel("renderpanel").component(), new Point(400,300), MouseButton.LEFT_BUTTON,1); applet.button("reactionArrow").target.doClick(); dandd.drag(applet.panel("renderpanel").component(), new Point(150,300)); dandd.drop(applet.panel("renderpanel").component(), new Point(350,300)); Assert.assertEquals(2, panel.getChemModel().getReactionSet().getReactionCount()); Assert.assertEquals(1, panel.getChemModel().getReactionSet().getReaction(1).getReactantCount()); Assert.assertEquals(1, panel.getChemModel().getReactionSet().getReaction(1).getProductCount()); } }
Java
2D
JChemPaint/jchempaint
core/src/test/java/org/openscience/jchempaint/BugSF70Test.java
.java
3,120
64
package org.openscience.jchempaint; import java.awt.Point; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import javax.swing.JComboBox; import javax.swing.text.JTextComponent; import javax.vecmath.Point2d; import org.fest.swing.core.MouseButton; import org.fest.swing.core.matcher.JTextComponentMatcher; import org.fest.swing.fixture.DialogFixture; import org.fest.swing.fixture.JButtonFixture; import org.fest.swing.fixture.JPanelFixture; import org.fest.swing.fixture.JTextComponentFixture; import org.junit.Assert; import org.junit.Test; import org.openscience.cdk.CDKConstants; import org.openscience.cdk.DefaultChemObjectBuilder; import org.openscience.cdk.exception.CDKException; import org.openscience.cdk.interfaces.IAtomContainer; import org.openscience.cdk.io.MDLV2000Reader; import org.openscience.jchempaint.matchers.ButtonTextComponentMatcher; import org.openscience.jchempaint.matchers.ComboBoxTextComponentMatcher; public class BugSF70Test extends AbstractAppletTest { private static int SAVE_AS_MOL_COMBOBOX_POS=6; @Test public void testBug70() throws CDKException, IOException{ JPanelFixture jcppanel=applet.panel("appletframe"); JChemPaintPanel panel = (JChemPaintPanel)jcppanel.target; applet.button("hexagon").target.doClick(); applet.click(); Point2d point = getAtomPoint(panel,0); applet.panel("renderpanel").robot.click(applet.panel("renderpanel").component(), new Point((int)point.x, (int)point.y), MouseButton.RIGHT_BUTTON,1); applet.panel("renderpanel").robot.click(applet.panel("renderpanel").component(), new Point((int)point.x, (int)point.y), MouseButton.RIGHT_BUTTON,1); applet.menuItem("showACProperties").click(); DialogFixture dialog = applet.dialog(); JTextComponent textfield = dialog.robot.finder().find(JTextComponentMatcher.withName("Title")); textfield.setText("aaa"); JButtonFixture okbutton = new JButtonFixture(dialog.robot, dialog.robot.finder().find(new ButtonTextComponentMatcher("OK"))); okbutton.click(); applet.menuItem("save").click(); dialog = applet.dialog(); File file=new File(System.getProperty("java.io.tmpdir")+File.separator+"test.mol"); if(file.exists()) file.delete(); JComboBox<?> combobox = dialog.robot.finder().find(new ComboBoxTextComponentMatcher("org.openscience.jchempaint.io.JCPFileFilter")); combobox.setSelectedItem(combobox.getItemAt(SAVE_AS_MOL_COMBOBOX_POS)); JTextComponentFixture text = dialog.textBox(); text.setText(file.toString()); JButtonFixture savebutton = new JButtonFixture(dialog.robot, dialog.robot.finder().find(new ButtonTextComponentMatcher("Save"))); savebutton.click(); MDLV2000Reader reader = new MDLV2000Reader(new FileInputStream(file)); IAtomContainer mol = (IAtomContainer)reader.read(DefaultChemObjectBuilder.getInstance().newInstance(IAtomContainer.class)); Assert.assertEquals("aaa",(String)mol.getProperty(CDKConstants.TITLE)); reader.close(); } }
Java
2D
JChemPaint/jchempaint
core/src/test/java/org/openscience/jchempaint/Issue11Test.java
.java
1,032
36
package org.openscience.jchempaint; import org.fest.swing.fixture.JPanelFixture; import org.junit.Assert; import org.junit.Test; import org.openscience.cdk.interfaces.IAtomContainer; /** * @author Ralf Stephan <ralf@ark.in-berlin.de> * * Tests SMILES input of a salt, the correct model and * error handling (#11). Depends on cdk SF#3531612. */ public class Issue11Test extends AbstractAppletTest { @Test public void testIssue11() { JPanelFixture jcppanel=applet.panel("appletframe"); JChemPaintPanel panel = (JChemPaintPanel)jcppanel.target; try { jcpApplet.setSmiles("[NH4+].CP(=O)(O)CCC(N)C(=O)[O-]"); panel.get2DHub().updateView(); } catch (Exception e) { Assert.fail(); } int atomCount=0, bondCount=0; for(IAtomContainer atc : panel.getChemModel().getMoleculeSet().atomContainers()) { atomCount+=atc.getAtomCount(); bondCount+=atc.getBondCount(); } Assert.assertEquals(16, atomCount); Assert.assertEquals(14, bondCount); } }
Java
2D
JChemPaint/jchempaint
core/src/test/java/org/openscience/jchempaint/JCPEditorAppletMenuTest.java
.java
37,619
603
package org.openscience.jchempaint; import org.fest.swing.core.MouseButton; import org.fest.swing.core.NameMatcher; import org.fest.swing.fixture.DialogFixture; import org.fest.swing.fixture.JButtonFixture; import org.fest.swing.fixture.JFileChooserFixture; import org.fest.swing.fixture.JPanelFixture; import org.fest.swing.fixture.JTabbedPaneFixture; import org.fest.swing.fixture.JTextComponentFixture; import org.junit.Assert; import org.junit.Ignore; import org.junit.Test; import org.openscience.cdk.ChemFile; import org.openscience.cdk.ChemObject; 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.IBond; import org.openscience.cdk.interfaces.IPseudoAtom; import org.openscience.cdk.io.IChemObjectReader.Mode; import org.openscience.cdk.io.MDLV2000Reader; import org.openscience.cdk.io.SMILESReader; import org.openscience.cdk.tools.manipulator.ChemFileManipulator; import org.openscience.jchempaint.io.JCPFileFilter; import org.openscience.jchempaint.matchers.ButtonTextComponentMatcher; import org.openscience.jchempaint.matchers.ComboBoxTextComponentMatcher; import org.openscience.jchempaint.matchers.DialogTitleComponentMatcher; import org.openscience.jchempaint.renderer.selection.SingleSelection; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JTabbedPane; import javax.swing.SwingUtilities; import javax.vecmath.Point2d; import java.awt.Point; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.InvocationTargetException; import java.nio.file.Files; import java.util.List; public class JCPEditorAppletMenuTest extends AbstractAppletTest { // Exporting does work. The testcases are not useful, since they fail for // sputrious reasons and test nothing. Commented out.# /* @Test public void testMenuExportBmp() throws CDKException, ClassNotFoundException, IOException, CloneNotSupportedException { restoreModelWithBasicmol(); File file=new File(System.getProperty("java.io.tmpdir")+File.separator+"test.bmp"); if(file.exists()) file.delete(); applet.menuItem("export").target.doClick(); DialogFixture dialog = applet.dialog(); //JComboBox combobox = dialog.robot.finder().find(new ComboBoxTextComponentMatcher("org.openscience.jchempaint.io.JCPExportFileFilter")); //combobox.setSelectedItem(combobox.getItemAt(1)); JTextComponentFixture text = dialog.textBox(); text.setText(file.toString().substring(0, file.toString().length()-4)); JButtonFixture okbutton = new JButtonFixture(dialog.robot, dialog.robot.finder().find(new ButtonTextComponentMatcher("Save"))); okbutton.target.doClick(); dialog = applet.dialog(); okbutton = new JButtonFixture(dialog.robot, dialog.robot.finder().find(new ButtonTextComponentMatcher("OK"))); okbutton.target.doClick(); //we only check the existence of file for now Assert.assertTrue(file.exists()); } @Test public void testMenuExportJpg() throws CDKException, ClassNotFoundException, IOException, CloneNotSupportedException { File file=new File(System.getProperty("java.io.tmpdir")+File.separator+"test.jpg"); if(file.exists()) file.delete(); applet.menuItem("export").target.doClick(); DialogFixture dialog = applet.dialog(); //JComboBox combobox = dialog.robot.finder().find(new ComboBoxTextComponentMatcher("org.openscience.jchempaint.io.JCPExportFileFilter")); //combobox.setSelectedItem(combobox.getItemAt(2)); JTextComponentFixture text = dialog.textBox(); text.setText(file.toString().substring(0, file.toString().length()-4)); JButtonFixture okbutton = new JButtonFixture(dialog.robot, dialog.robot.finder().find(new ButtonTextComponentMatcher("Save"))); okbutton.target.doClick(); dialog = applet.dialog(); okbutton = new JButtonFixture(dialog.robot, dialog.robot.finder().find(new ButtonTextComponentMatcher("OK"))); okbutton.target.doClick(); //we only check the existence of file for now Assert.assertTrue(file.exists()); } @Test public void testMenuExportPng() throws CDKException, ClassNotFoundException, IOException, CloneNotSupportedException { File file=new File(System.getProperty("java.io.tmpdir")+File.separator+"test.png"); if(file.exists()) file.delete(); applet.menuItem("export").target.doClick(); DialogFixture dialog = applet.dialog(); JComboBox combobox = dialog.robot.finder().find(new ComboBoxTextComponentMatcher("org.openscience.jchempaint.io.JCPExportFileFilter")); combobox.setSelectedItem(combobox.getItemAt(3)); JTextComponentFixture text = dialog.textBox(); text.setText(file.toString().substring(0, file.toString().length()-4)); JButtonFixture okbutton = new JButtonFixture(dialog.robot, dialog.robot.finder().find(new ButtonTextComponentMatcher("Save"))); okbutton.target.doClick(); dialog = applet.dialog(); okbutton = new JButtonFixture(dialog.robot, dialog.robot.finder().find(new ButtonTextComponentMatcher("OK"))); okbutton.target.doClick(); //we only check the existence of file for now Assert.assertTrue(file.exists()); }*/ // Not very meaningful test. Outcommented because of fest complications /* @Test public void testMenuExportSvg() throws CDKException, ClassNotFoundException, IOException, CloneNotSupportedException { restoreModelWithBasicmol(); File file=new File(System.getProperty("java.io.tmpdir")+File.separator+"test.svg"); if(file.exists()) file.delete(); applet.menuItem("export").target.doClick(); DialogFixture dialog = applet.dialog(); //JComboBox combobox = dialog.robot.finder().find(new ComboBoxTextComponentMatcher("org.openscience.jchempaint.io.JCPExportFileFilter")); //combobox.setSelectedItem(combobox.getItemAt(4)); JTextComponentFixture text = dialog.textBox(); text.setText(file.toString().substring(0, file.toString().length()-4)); JButtonFixture okbutton = new JButtonFixture(dialog.robot, dialog.robot.finder().find(new ButtonTextComponentMatcher("Save"))); okbutton.target.doClick(); //dialog = applet.dialog(); //okbutton = new JButtonFixture(dialog.robot, dialog.robot.finder().find(new ButtonTextComponentMatcher("OK"))); //okbutton.target.doClick(); //we only check the existence of file for now Assert.assertTrue(file.exists()); } @Test public void testMenuPrint() throws CDKException, ClassNotFoundException, IOException, CloneNotSupportedException { //Printing only works from signed applet. We cannot test this. }*/ @Test public void testMenuChargePlus1() throws CDKException, ClassNotFoundException, IOException, CloneNotSupportedException { restoreModelWithBasicmol(); panel.getRenderPanel().getRenderer().getRenderer2DModel().setSelection(new SingleSelection<IAtom>(panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(0))); panel.selectionChanged(); int oldhcount = panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(0).getImplicitHydrogenCount().intValue(); int oldcharge = panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(0).getFormalCharge().intValue(); applet.menuItem("plus").target.doClick(); Assert.assertEquals(oldcharge + 1, panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(0).getFormalCharge().intValue()); Assert.assertEquals(oldhcount - 1, panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(0).getImplicitHydrogenCount().intValue()); panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(0).setFormalCharge(0); Assert.assertEquals("plus", panel.get2DHub().getActiveDrawModule().getID()); Point2d moveto = panel.getRenderPanel().getRenderer().toScreenCoordinates(panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(1).getPoint2d().x, panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(1).getPoint2d().y); oldhcount = panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(1).getImplicitHydrogenCount().intValue(); oldcharge = panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(1).getFormalCharge().intValue(); panel.get2DHub().mouseClickedDown((int) moveto.x, (int) moveto.y); Assert.assertEquals(oldhcount, panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(0).getImplicitHydrogenCount().intValue()); Assert.assertEquals(oldcharge + 1, panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(1).getFormalCharge().intValue()); oldhcount = panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(1).getImplicitHydrogenCount().intValue(); oldcharge = panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(1).getFormalCharge().intValue(); panel.get2DHub().mouseClickedDown((int) moveto.x, (int) moveto.y); Assert.assertEquals(oldhcount - 1, panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(1).getImplicitHydrogenCount().intValue()); Assert.assertEquals(oldcharge + 1, panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(1).getFormalCharge().intValue()); panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(0).setFormalCharge(0); panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(1).setFormalCharge(0); } @Test public void testMenuChargeMinus1() throws CDKException, ClassNotFoundException, IOException, CloneNotSupportedException { restoreModelWithBasicmol(); panel.getRenderPanel().getRenderer().getRenderer2DModel().setSelection(new SingleSelection<IAtom>(panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(0))); panel.selectionChanged(); int oldhcount = panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(0).getImplicitHydrogenCount().intValue(); int oldcharge = panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(0).getFormalCharge().intValue(); applet.menuItem("minus").target.doClick(); Assert.assertEquals(oldcharge - 1, panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(0).getFormalCharge().intValue()); Assert.assertEquals(oldhcount - 1, panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(0).getImplicitHydrogenCount().intValue()); panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(0).setFormalCharge(0); Assert.assertEquals("minus", panel.get2DHub().getActiveDrawModule().getID()); Point2d moveto = panel.getRenderPanel().getRenderer().toScreenCoordinates(panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(1).getPoint2d().x, panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(1).getPoint2d().y); oldhcount = panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(1).getImplicitHydrogenCount().intValue(); oldcharge = panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(1).getFormalCharge().intValue(); panel.get2DHub().mouseClickedDown((int) moveto.x, (int) moveto.y); Assert.assertEquals(oldcharge - 1, panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(1).getFormalCharge().intValue()); Assert.assertEquals(oldhcount - 1 , panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(1).getImplicitHydrogenCount().intValue()); oldhcount = panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(1).getImplicitHydrogenCount().intValue(); oldcharge = panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(1).getFormalCharge().intValue(); panel.get2DHub().mouseClickedDown((int) moveto.x, (int) moveto.y); Assert.assertEquals(oldcharge - 1, panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(1).getFormalCharge().intValue()); Assert.assertEquals(oldhcount - 1, panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(1).getImplicitHydrogenCount().intValue()); panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(0).setFormalCharge(0); panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(1).setFormalCharge(0); } @Ignore public void testMenuValenceOne() throws CDKException, ClassNotFoundException, IOException, CloneNotSupportedException { genericValenceTest(1); } @Ignore public void testMenuValenceTwo() throws CDKException, ClassNotFoundException, IOException, CloneNotSupportedException { genericValenceTest(2); } @Ignore public void testMenuValenceThree() throws CDKException, ClassNotFoundException, IOException, CloneNotSupportedException { genericValenceTest(3); } @Ignore public void testMenuValenceFour() throws CDKException, ClassNotFoundException, IOException, CloneNotSupportedException { genericValenceTest(4); } @Ignore public void testMenuValenceFive() throws CDKException, ClassNotFoundException, IOException, CloneNotSupportedException { genericValenceTest(5); } @Ignore public void testMenuValenceSix() throws CDKException, ClassNotFoundException, IOException, CloneNotSupportedException { genericValenceTest(6); } @Ignore public void testMenuValenceSeven() throws CDKException, ClassNotFoundException, IOException, CloneNotSupportedException { genericValenceTest(7); } @Ignore public void testMenuValenceEight() throws CDKException, ClassNotFoundException, IOException, CloneNotSupportedException { genericValenceTest(8); } @Ignore public void testMenuValenceOff() throws CDKException, ClassNotFoundException, IOException, CloneNotSupportedException { JPanelFixture jcppanel = applet.panel("appletframe"); JChemPaintPanel panel = (JChemPaintPanel) jcppanel.target; panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(0).setValency(1); panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(2).setValency(2); genericValenceTest(-1); } private void genericValenceTest(int valence) { //we go to select mode restoreModelWithBasicmol(); applet.button("select").target.doClick(); panel.getRenderPanel().getRenderer().getRenderer2DModel().setSelection(new SingleSelection<IAtom>(panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(0))); panel.selectionChanged(); applet.menuItem("isotopeChange").target.doClick(); applet.menuItem("valence" + (valence == -1 ? "Off" : valence)).target.doClick(); if (valence == -1) Assert.assertNull(panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(0).getValency()); else Assert.assertEquals(valence, panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(0).getValency().intValue()); //the mode should have changed now Assert.assertEquals("valence", panel.get2DHub().getActiveDrawModule().getID()); //if we click somewhere, we should get a new atom with specified properties Point2d moveto = panel.getRenderPanel().getRenderer().toScreenCoordinates(panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(2).getPoint2d().x, panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(2).getPoint2d().y); applet.panel("renderpanel").robot.click(applet.panel("renderpanel").component(), new Point((int) moveto.x, (int) moveto.y), MouseButton.LEFT_BUTTON, 1); if (valence == -1) Assert.assertNull(panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(2).getValency()); else Assert.assertEquals(valence, panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(2).getValency().intValue()); panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(0).setValency(null); panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(2).setValency(null); } @Test public void testMenuConvertToRadical() throws CDKException, ClassNotFoundException, IOException, CloneNotSupportedException { restoreModelWithBasicmol(); panel.getRenderPanel().getRenderer().getRenderer2DModel().setSelection(new SingleSelection<IAtom>(panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(0))); panel.selectionChanged(); //applet.menuItem("convertToRadical").target.doClick(); //TODO miguel needs to look at this //Assert... //reset to non-radical } @Test public void testMenuPseudoStar() throws CDKException, ClassNotFoundException, IOException, CloneNotSupportedException { restoreModelWithBasicmol(); panel.getRenderPanel().getRenderer().getRenderer2DModel().setSelection(new SingleSelection<IAtom>(panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(0))); panel.selectionChanged(); applet.menuItem("pseudoStar").target.doClick(); Assert.assertEquals("*", ((IPseudoAtom) panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(0)).getLabel()); //the mode should have changed now Assert.assertEquals("*", panel.get2DHub().getActiveDrawModule().getID()); Assert.assertTrue(panel.get2DHub().getController2DModel().getDrawPseudoAtom()); Assert.assertEquals("*", panel.get2DHub().getActiveDrawModule().getID()); IAtom normal = panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(0).getBuilder().newInstance(IAtom.class, panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(0)); normal.setSymbol("C"); panel.get2DHub().replaceAtom(normal, panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(0)); } @Test public void testMenuPseudoR() throws CDKException, ClassNotFoundException, IOException, CloneNotSupportedException { restoreModelWithBasicmol(); panel.getRenderPanel().getRenderer().getRenderer2DModel().setSelection(new SingleSelection<IAtom>(panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(0))); panel.selectionChanged(); applet.menuItem("pseudoR").target.doClick(); Assert.assertEquals("R", ((IPseudoAtom) panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(0)).getLabel()); //the mode should have changed now Assert.assertEquals("R", panel.get2DHub().getActiveDrawModule().getID()); Assert.assertTrue(panel.get2DHub().getController2DModel().getDrawPseudoAtom()); Assert.assertEquals("R", panel.get2DHub().getActiveDrawModule().getID()); IAtom normal = panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(0).getBuilder().newInstance(IAtom.class, panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(0)); normal.setSymbol("C"); panel.get2DHub().replaceAtom(normal, panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(0)); } @Test public void testMenuPeriodictable() throws CDKException, ClassNotFoundException, IOException, CloneNotSupportedException, InterruptedException, InvocationTargetException { restoreModelWithBasicmol(); panel.getRenderPanel().getRenderer().getRenderer2DModel().setSelection(new SingleSelection<IAtom>(panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(0))); panel.selectionChanged(); SwingUtilities.invokeLater(applet.menuItem("periodictable").target::doClick); DialogFixture dialog = applet.dialog(); dialog.button("Li").target.doClick(); dialog.target.setVisible(false); applet.robot.waitForIdle(); Assert.assertEquals("Li", panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(0).getSymbol()); panel.get2DHub().setSymbol(panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(0), "C"); Assert.assertEquals("periodictable", panel.get2DHub().getActiveDrawModule().getID()); } @Test public void testMenuBondSingle() throws CDKException, ClassNotFoundException, IOException, CloneNotSupportedException { restoreModelWithBasicmol(); JPanelFixture jcppanel = applet.panel("appletframe"); JChemPaintPanel panel = (JChemPaintPanel) jcppanel.target; panel.getChemModel().getMoleculeSet().getAtomContainer(0).getBond(0).setOrder(IBond.Order.DOUBLE); panel.getRenderPanel().getRenderer().getRenderer2DModel().setSelection(new SingleSelection<IBond>(panel.getChemModel().getMoleculeSet().getAtomContainer(0).getBond(0))); panel.selectionChanged(); applet.menuItem("bond").target.doClick(); Assert.assertEquals(IBond.Order.SINGLE, panel.getChemModel().getMoleculeSet().getAtomContainer(0).getBond(0).getOrder()); panel.getChemModel().getMoleculeSet().getAtomContainer(0).getBond(0).setOrder(IBond.Order.SINGLE); Assert.assertEquals("bond", panel.get2DHub().getActiveDrawModule().getID()); } @Test public void testMenuBondStereoDown() throws CDKException, ClassNotFoundException, IOException, CloneNotSupportedException { restoreModelWithBasicmol(); JPanelFixture jcppanel = applet.panel("appletframe"); JChemPaintPanel panel = (JChemPaintPanel) jcppanel.target; panel.getChemModel().getMoleculeSet().getAtomContainer(0).getBond(0).setStereo(IBond.Stereo.NONE); panel.getRenderPanel().getRenderer().getRenderer2DModel().setSelection(new SingleSelection<IBond>(panel.getChemModel().getMoleculeSet().getAtomContainer(0).getBond(0))); panel.selectionChanged(); applet.menuItem("down_bond").target.doClick(); Assert.assertEquals(IBond.Stereo.DOWN, panel.getChemModel().getMoleculeSet().getAtomContainer(0).getBond(0).getStereo()); panel.getChemModel().getMoleculeSet().getAtomContainer(0).getBond(0).setStereo(IBond.Stereo.NONE); Assert.assertEquals("down_bond", panel.get2DHub().getActiveDrawModule().getID()); } @Test public void testMenuBondStereoUp() throws CDKException, ClassNotFoundException, IOException, CloneNotSupportedException { restoreModelWithBasicmol(); JPanelFixture jcppanel = applet.panel("appletframe"); JChemPaintPanel panel = (JChemPaintPanel) jcppanel.target; panel.getChemModel().getMoleculeSet().getAtomContainer(0).getBond(0).setStereo(IBond.Stereo.NONE); panel.getRenderPanel().getRenderer().getRenderer2DModel().setSelection(new SingleSelection<IBond>(panel.getChemModel().getMoleculeSet().getAtomContainer(0).getBond(0))); panel.selectionChanged(); applet.menuItem("up_bond").target.doClick(); Assert.assertEquals(IBond.Stereo.UP, panel.getChemModel().getMoleculeSet().getAtomContainer(0).getBond(0).getStereo()); panel.getChemModel().getMoleculeSet().getAtomContainer(0).getBond(0).setStereo(IBond.Stereo.NONE); Assert.assertEquals("up_bond", panel.get2DHub().getActiveDrawModule().getID()); } @Test public void testMenuBondUndefinedStereo() throws CDKException, ClassNotFoundException, IOException, CloneNotSupportedException { restoreModelWithBasicmol(); JPanelFixture jcppanel = applet.panel("appletframe"); JChemPaintPanel panel = (JChemPaintPanel) jcppanel.target; panel.getChemModel().getMoleculeSet().getAtomContainer(0).getBond(0).setStereo(IBond.Stereo.NONE); panel.getRenderPanel().getRenderer().getRenderer2DModel().setSelection(new SingleSelection<IBond>(panel.getChemModel().getMoleculeSet().getAtomContainer(0).getBond(0))); panel.selectionChanged(); applet.menuItem("undefined_bond").target.doClick(); Assert.assertEquals(IBond.Stereo.UP_OR_DOWN, panel.getChemModel().getMoleculeSet().getAtomContainer(0).getBond(0).getStereo()); panel.getChemModel().getMoleculeSet().getAtomContainer(0).getBond(0).setStereo(IBond.Stereo.NONE); Assert.assertEquals("undefined_bond", panel.get2DHub().getActiveDrawModule().getID()); } @Test public void testMenuBondUndefinedEZ() throws CDKException, ClassNotFoundException, IOException, CloneNotSupportedException { restoreModelWithBasicmol(); JPanelFixture jcppanel = applet.panel("appletframe"); JChemPaintPanel panel = (JChemPaintPanel) jcppanel.target; panel.getChemModel().getMoleculeSet().getAtomContainer(0).getBond(0).setStereo(IBond.Stereo.NONE); panel.getRenderPanel().getRenderer().getRenderer2DModel().setSelection(new SingleSelection<IBond>(panel.getChemModel().getMoleculeSet().getAtomContainer(0).getBond(0))); panel.selectionChanged(); applet.menuItem("undefined_stereo_bond").target.doClick(); Assert.assertEquals(IBond.Stereo.E_OR_Z, panel.getChemModel().getMoleculeSet().getAtomContainer(0).getBond(0).getStereo()); panel.getChemModel().getMoleculeSet().getAtomContainer(0).getBond(0).setStereo(IBond.Stereo.NONE); Assert.assertEquals("undefined_stereo_bond", panel.get2DHub().getActiveDrawModule().getID()); } @Test public void testMenuReportSmiles() { restoreModelWithBasicmol(); SwingUtilities.invokeLater(applet.menuItem("createSMILES").target::doClick); DialogFixture dialog = applet.dialog("smilestextdialog"); String text = dialog.textBox("textviewdialogtextarea").text(); Assert.assertTrue(text.contains("CCCCCCCC")); dialog.target.setVisible(false); } @Test public void testMenuNew() throws CDKException, ClassNotFoundException, IOException, CloneNotSupportedException { applet.menuItem("new").target.doClick(); JPanelFixture jcppanel = applet.panel("appletframe"); JChemPaintPanel panel = (JChemPaintPanel) jcppanel.target; Assert.assertEquals("", panel.getSmiles()); restoreModelWithBasicmol(); } @Test public void testMenuSaveAsMol() throws CDKException, ClassNotFoundException, IOException, CloneNotSupportedException { restoreModelWithBasicmol(); SwingUtilities.invokeLater(applet.menuItem("save").target::doClick); applet.robot.waitForIdle(); JFileChooserFixture dialog = applet.fileChooser("save"); File file = File.createTempFile("jcptest", ".mol"); file.delete(); JComboBox<?> combobox = dialog.robot.finder().find(new ComboBoxTextComponentMatcher("org.openscience.jchempaint.io.JCPFileFilter")); int index = -1; for (int i = 0; i < combobox.getModel().getSize(); i++) if (((JCPFileFilter) combobox.getModel().getElementAt(i)).getType() == JCPFileFilter.mol) index = i; Assert.assertFalse(index < 0); combobox.setSelectedIndex(index); JTextComponentFixture text = dialog.fileNameTextBox(); text.setText(file.toString()); JButtonFixture okbutton = new JButtonFixture(dialog.robot, dialog.robot.finder().find(new ButtonTextComponentMatcher("Save"))); okbutton.target.doClick(); dialog.target.setVisible(false); applet.robot.waitForIdle(); MDLV2000Reader reader = null; try { reader = new MDLV2000Reader(Files.newInputStream(file.toPath())); } catch (Exception e) { // TODO Auto-generated catch block Assert.fail("File not found."); return; } IAtomContainer mol = (IAtomContainer) reader.read(DefaultChemObjectBuilder.getInstance().newInstance(IAtomContainer.class)); JPanelFixture jcppanel = applet.panel("appletframe"); JChemPaintPanel panel = (JChemPaintPanel) jcppanel.target; Assert.assertEquals(panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtomCount(), mol.getAtomCount()); Assert.assertEquals(panel.getChemModel().getMoleculeSet().getAtomContainer(0).getBondCount(), mol.getBondCount()); reader.close(); } //TODO do this for all formats @Test public void testMenuOpenMol() throws CDKException, ClassNotFoundException, IOException, CloneNotSupportedException { if (System.getProperty("os.name").indexOf("Mac") == -1) { String filename = "data/chebi/ChEBI_26120.mol"; InputStream ins = this.getClass().getClassLoader().getResourceAsStream(filename); File file = new File(System.getProperty("java.io.tmpdir") + File.separator + "test.mol"); if (file.exists()) file.delete(); FileOutputStream fos = new FileOutputStream(file); while (ins.available() > 0) fos.write(ins.read()); fos.close(); applet.menuItem("open").target.doClick(); DialogFixture dialog = applet.dialog(); JTextComponentFixture text = dialog.textBox(); text.setText(file.toString()); JButtonFixture okbutton = new JButtonFixture(dialog.robot, dialog.robot.finder().find(new ButtonTextComponentMatcher("Open"))); okbutton.target.doClick(); ins = this.getClass().getClassLoader().getResourceAsStream(filename); MDLV2000Reader reader = new MDLV2000Reader(ins, Mode.STRICT); ChemFile chemFile = (ChemFile) reader.read((ChemObject) new ChemFile()); reader.close(); Assert.assertNotNull(chemFile); List<IAtomContainer> containersList = ChemFileManipulator.getAllAtomContainers(chemFile); JPanelFixture jcppanel = applet.panel("appletframe"); JChemPaintPanel panel = (JChemPaintPanel) jcppanel.target; Assert.assertEquals(1, containersList.size()); Assert.assertEquals((containersList.get(0)).getAtomCount(), panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtomCount()); Assert.assertEquals((containersList.get(0)).getBondCount(), panel.getChemModel().getMoleculeSet().getAtomContainer(0).getBondCount()); restoreModelWithBasicmol(); } } // CML i/o was disabled, buggy test commented out /* @Test public void testMenuOpenCml() throws CDKException, ClassNotFoundException, IOException, CloneNotSupportedException { if(System.getProperty("os.name").indexOf("Mac")==-1){ String filename = "data/a-pinen.cml"; InputStream ins = this.getClass().getClassLoader().getResourceAsStream(filename); File file=new File(System.getProperty("java.io.tmpdir")+File.separator+"test.cml"); if(file.exists()) file.delete(); FileOutputStream fos = new FileOutputStream(file); while(ins.available()>0) fos.write(ins.read()); applet.menuItem("open").target.doClick(); DialogFixture dialog = applet.dialog(); //JComboBox combobox = dialog.robot.finder().find(new ComboBoxTextComponentMatcher("org.openscience.jchempaint.io.JCPFileFilter")); //combobox.setSelectedItem(combobox.getItemAt(1)); JTextComponentFixture text = dialog.textBox(); text.setText(file.toString()); JButtonFixture okbutton = new JButtonFixture(dialog.robot, dialog.robot.finder().find(new ButtonTextComponentMatcher("Open"))); okbutton.target.doClick(); ins = this.getClass().getClassLoader().getResourceAsStream(filename); CMLReader reader = new CMLReader(ins); ChemFile chemFile = (ChemFile)reader.read((ChemObject)new ChemFile()); Assert.assertNotNull(chemFile); List<IAtomContainer> containersList = ChemFileManipulator.getAllAtomContainers(chemFile); JPanelFixture jcppanel=applet.panel("appletframe"); JChemPaintPanel panel = (JChemPaintPanel)jcppanel.target; Assert.assertEquals(containersList.size(), containersList.size()); Assert.assertEquals((containersList.get(0)).getAtomCount(),panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtomCount()); Assert.assertEquals((containersList.get(0)).getBondCount(),panel.getChemModel().getMoleculeSet().getAtomContainer(0).getBondCount()); restoreModelWithBasicmol(); } }*/ @Test public void testMenuOpenSmiles() throws CDKException, ClassNotFoundException, IOException, CloneNotSupportedException { if (System.getProperty("os.name").indexOf("Mac") == -1) { String filename = "data/smiles.smi"; InputStream ins = this.getClass().getClassLoader().getResourceAsStream(filename); File file = new File(System.getProperty("java.io.tmpdir") + File.separator + "test.smi"); if (file.exists()) file.delete(); FileOutputStream fos = new FileOutputStream(file); while (ins.available() > 0) fos.write(ins.read()); fos.close(); applet.menuItem("open").target.doClick(); DialogFixture dialog = applet.dialog(); //it seems the Combo selection depends on if you run test as single test or all in class, no idea why //JComboBox combobox = dialog.robot.finder().find(new ComboBoxTextComponentMatcher("org.openscience.jchempaint.io.JCPFileFilter","org.openscience.jchempaint.io.JCPSaveFileFilter")); //combobox.setSelectedItem(combobox.getItemAt(2)); JTextComponentFixture text = dialog.textBox(); text.setText(file.toString()); JButtonFixture okbutton = new JButtonFixture(dialog.robot, dialog.robot.finder().find(new ButtonTextComponentMatcher("Open"))); okbutton.target.doClick(); DialogFixture coordsdialog = new DialogFixture(applet.robot, applet.robot.finder().find(new DialogTitleComponentMatcher("No 2D coordinates"))); JButtonFixture okbuttoncoordsdialog = new JButtonFixture(coordsdialog.robot, coordsdialog.robot.finder().find(new ButtonTextComponentMatcher("Yes"))); okbuttoncoordsdialog.target.doClick(); ins = this.getClass().getClassLoader().getResourceAsStream(filename); SMILESReader reader = new SMILESReader(ins); ChemFile chemFile = (ChemFile) reader.read((ChemObject) new ChemFile()); Assert.assertNotNull(chemFile); reader.close(); List<IAtomContainer> containersList = ChemFileManipulator.getAllAtomContainers(chemFile); JPanelFixture jcppanel = applet.panel("appletframe"); JChemPaintPanel panel = (JChemPaintPanel) jcppanel.target; Assert.assertEquals(containersList.size(), containersList.size()); Assert.assertEquals((containersList.get(0)).getAtomCount(), panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtomCount()); Assert.assertEquals((containersList.get(0)).getBondCount(), panel.getChemModel().getMoleculeSet().getAtomContainer(0).getBondCount()); restoreModelWithBasicmol(); } } //TODO do this for all formats @Test public void testMenuTemplatesAll() throws CDKException, ClassNotFoundException, IOException, CloneNotSupportedException { restoreModelToEmpty(); SwingUtilities.invokeLater(applet.menuItem("pasteTemplate").target::doClick); DialogFixture dialog = applet.dialog("templates"); JButtonFixture morphineButton = new JButtonFixture(dialog.robot, dialog.robot.finder().find(new ButtonTextComponentMatcher("Morphine"))); morphineButton.target.doClick(); dialog.target.setVisible(false); applet.robot.waitForIdle(); Assert.assertEquals(1, panel.getChemModel().getMoleculeSet().getAtomContainerCount()); Assert.assertEquals(22, panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtomCount()); } // This test seems to be problematic, the preferences are non-modal and // doesn't get closed - likely an issue with dialog being redisplayed @Test public void testSwitchLanguage() { applet.menuItem("options").target.doClick(); DialogFixture dialog = applet.dialog(); JTabbedPaneFixture tabs = new JTabbedPaneFixture(dialog.robot, (JTabbedPane) dialog.robot.finder().findByName("tabs")); tabs.selectTab(1); JComboBox<?> combobox = (JComboBox<?>) dialog.robot.finder().find(new NameMatcher("language")); for (int i = 0; i < combobox.getItemCount(); i++) { if (((String) combobox.getItemAt(i)).equals("German")) { combobox.setSelectedIndex(i); break; } } JButtonFixture applybutton = new JButtonFixture(dialog.robot, (JButton) dialog.robot.finder().find(new NameMatcher("apply", true))); applybutton.target.doClick(); Assert.assertEquals("Neu", applet.menuItem("new").component().getText()); // setting the language resets the whole tree so we do some for (int i = 0; i < combobox.getItemCount(); i++) { if (((String) combobox.getItemAt(i)).equals("American English")) { combobox.setSelectedIndex(i); break; } } applybutton.target.doClick(); dialog.target.setVisible(false); applet.robot.waitForIdle(); Assert.assertEquals("New", applet.menuItem("new").component().getText()); } }
Java
2D
JChemPaint/jchempaint
core/src/test/java/org/openscience/jchempaint/Issue32Test.java
.java
2,437
58
package org.openscience.jchempaint; import java.awt.AWTException; import java.awt.Point; import org.fest.swing.fixture.JPanelFixture; import org.junit.Assert; import org.junit.Test; import org.openscience.cdk.interfaces.IAtomContainer; import org.openscience.jchempaint.AbstractAppletTest; import org.openscience.jchempaint.JChemPaintPanel; /** * @author Ralf Stephan <ralf@ark.in-berlin.de> */ public class Issue32Test extends AbstractAppletTest { @Test public void testIssue32() throws AWTException { JPanelFixture jcppanel=applet.panel("appletframe"); JChemPaintPanel panel = (JChemPaintPanel)jcppanel.target; applet.button("C").click(); applet.button("bondTool").click(); applet.panel("renderpanel").robot.click(applet.panel("renderpanel").component(),new Point(100,100)); IAtomContainer ethane = panel.getChemModel().getMoleculeSet().getAtomContainer(0); IAtomContainer selected = ethane.getBuilder().newInstance(IAtomContainer.class); selected.addAtom(ethane.getAtom(0)); panel.getRenderPanel().getHub().deleteFragment(new AtomBondSet(selected)); /* applet.button("C").click(); applet.button("bondTool").click(); applet.panel("renderpanel").robot.click(applet.panel("renderpanel").component(),new Point(100,100)); applet.button("select").click(); Point2d p1 = panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(0).getPoint2d(); Point2d p2 = panel.getChemModel().getMoleculeSet().getAtomContainer(0).getAtom(0).getPoint2d(); double d = p2.x - p1.x; Point2d moveto=panel.getRenderPanel().getRenderer().toScreenCoordinates((p1.x+p2.x)/2, p1.y+d); applet.panel("renderpanel").robot.moveMouse((int)moveto.x, (int)moveto.y); applet.panel("renderpanel").robot.pressMouse(MouseButton.LEFT_BUTTON); robot.delay(1000); moveto=panel.getRenderPanel().getRenderer().toScreenCoordinates(p1.x-d/2, p1.y-d); applet.panel("renderpanel").robot.moveMouse((int)moveto.x, (int)moveto.y); robot.delay(1000); applet.panel("renderpanel").robot.releaseMouseButtons(); */ int atomCount=0, hCount=0; for(IAtomContainer atc : panel.getChemModel().getMoleculeSet().atomContainers()) { atomCount+=atc.getAtomCount(); hCount+=atc.getAtom(0).getImplicitHydrogenCount().intValue(); } Assert.assertEquals(1, atomCount); Assert.assertEquals(4, hCount); } }
Java
2D
JChemPaint/jchempaint
core/src/test/java/org/openscience/jchempaint/BugSF80Test.java
.java
2,884
68
package org.openscience.jchempaint; import java.awt.Point; import java.io.IOException; import javax.vecmath.Point2d; import org.fest.swing.core.MouseButton; import org.fest.swing.fixture.JPanelFixture; import org.junit.Assert; import org.junit.Test; import org.openscience.cdk.exception.CDKException; import org.openscience.cdk.interfaces.IAtom; import org.openscience.cdk.interfaces.IAtomContainer; import org.openscience.cdk.interfaces.IBond; public class BugSF80Test extends AbstractAppletTest { //Test for Trac ticket # 80 : deletion of the double bonds that bind the oxygens in caffeine led to // incorrect cascading removal of the bound carbons too. @Test public void testRemoveBond() throws CDKException, ClassNotFoundException, IOException, CloneNotSupportedException { // Clean the panel: JPanelFixture jcppanel=applet.panel("appletframe"); JChemPaintPanel panel = (JChemPaintPanel)jcppanel.target; jcpApplet.setSmiles("Cn1cnc2c1c(=O)n(C)c(=O)n2C"); /* // Paste caffeine template: applet.menuItem("pasteTemplate").click(); DialogFixture dialog = applet.dialog("templates"); JButtonFixture templateButton = new JButtonFixture(dialog.robot, dialog.robot.finder().find( new ButtonTextComponentMatcher("Caffeine"))); templateButton.click(); applet.button("select").target.doClick(); applet.panel("renderpanel").robot.click(applet.panel("renderpanel").component(), new Point(0,0), MouseButton.LEFT_BUTTON,1); */ //Delete the double bonds connecting the two oxygen atoms: applet.button("eraser").target.doClick(); for (IBond bond : panel.getChemModel().getMoleculeSet().getAtomContainer(0).bonds()) if (bond.getOrder().equals(IBond.Order.DOUBLE) && (bond.getAtom(0).getSymbol().equals("O")||bond.getAtom(1).getSymbol().equals("O"))) { double xAvg= (bond.getAtom(0).getPoint2d().x +bond.getAtom(1).getPoint2d().x)/2; double yAvg= (bond.getAtom(0).getPoint2d().y +bond.getAtom(1).getPoint2d().y)/2; Point2d moveTo=panel.getRenderPanel().getRenderer().toScreenCoordinates(xAvg,yAvg); Point p = new Point((int)moveTo.x, (int)moveTo.y); applet.panel("renderpanel").robot.click(applet.panel("renderpanel").component(), p, MouseButton.LEFT_BUTTON,1); } //Establish that only the double bonds plus the oxygens are gone, rest is still in place: //Issue 1, 129: make sure implicit Hs are added int atomCount=0, bondCount=0, implicitHCount=0; for(IAtomContainer atc : panel.getChemModel().getMoleculeSet().atomContainers()) { for (IAtom a : atc.atoms()) implicitHCount += a.getImplicitHydrogenCount(); atomCount+=atc.getAtomCount(); bondCount+=atc.getBondCount(); } Assert.assertEquals(12, atomCount); Assert.assertEquals(13, bondCount); Assert.assertEquals(14, implicitHCount); } }
Java
2D
JChemPaint/jchempaint
core/src/test/java/org/openscience/jchempaint/matchers/ComboBoxTextComponentMatcher.java
.java
923
35
package org.openscience.jchempaint.matchers; import javax.swing.JComboBox; import org.fest.swing.core.GenericTypeMatcher; public class ComboBoxTextComponentMatcher extends GenericTypeMatcher<JComboBox> { private String text; private String altText; public ComboBoxTextComponentMatcher(String text){ super(JComboBox.class); this.text=text; } public ComboBoxTextComponentMatcher(String text, String altText) { super(JComboBox.class); this.text = text; this.altText = altText; } @Override protected boolean isMatching(JComboBox arg0) { if(!arg0.isShowing()) return false; if(arg0.getSelectedItem()!=null && arg0.getSelectedItem().toString().indexOf(text)==0) return true; else if(arg0.getSelectedItem()!=null && altText!=null && arg0.getSelectedItem().toString().indexOf(altText)==0) return true; else return false; } }
Java
2D
JChemPaint/jchempaint
core/src/test/java/org/openscience/jchempaint/matchers/DialogTitleComponentMatcher.java
.java
585
26
package org.openscience.jchempaint.matchers; import javax.swing.JDialog; import org.fest.swing.core.GenericTypeMatcher; public class DialogTitleComponentMatcher extends GenericTypeMatcher<JDialog> { private String text; public DialogTitleComponentMatcher(String text){ super(JDialog.class); this.text=text; } @Override protected boolean isMatching(JDialog arg0) { System.err.println(arg0.getTitle()+" "+text); System.err.println(arg0.getTitle().equals(text)); if(arg0.getTitle()!=null && arg0.getTitle().equals(text)) return true; else return false; } }
Java
2D
JChemPaint/jchempaint
core/src/test/java/org/openscience/jchempaint/matchers/ButtonTextComponentMatcher.java
.java
501
24
package org.openscience.jchempaint.matchers; import javax.swing.JButton; import org.fest.swing.core.GenericTypeMatcher; public class ButtonTextComponentMatcher extends GenericTypeMatcher<JButton> { private String text; public ButtonTextComponentMatcher(String text){ super(JButton.class); this.text=text; } @Override protected boolean isMatching(JButton arg0) { if(arg0.getText()!=null && arg0.isShowing() && arg0.getText().equals(text)) return true; else return false; } }
Java
2D
JChemPaint/jchempaint
core/src/test/java/org/openscience/jchempaint/controller/ConjugationToolsTest.java
.java
6,269
150
package org.openscience.jchempaint.controller; import org.junit.Assert; import org.junit.Test; import org.openscience.cdk.DefaultChemObjectBuilder; import org.openscience.cdk.exception.InvalidSmilesException; import org.openscience.cdk.interfaces.IAtomContainer; import org.openscience.cdk.interfaces.IBond; import org.openscience.cdk.smiles.SmilesParser; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import static org.openscience.cdk.interfaces.IBond.Order.DOUBLE; import static org.openscience.cdk.interfaces.IBond.Order.SINGLE; public class ConjugationToolsTest { private static void assertBondOrders(IAtomContainer mol, IBond.Order ... orders) { List<IBond.Order> actual = new ArrayList<>(); List<IBond.Order> expected = Arrays.asList(orders); for (IBond bond : mol.bonds()) { actual.add(bond.getOrder()); } Assert.assertEquals(expected, actual); } private static void flip(IBond bond) { if (bond.getOrder() == SINGLE) bond.setOrder(DOUBLE); else if (bond.getOrder() == DOUBLE) bond.setOrder(SINGLE); else throw new IllegalArgumentException("Not single or double!"); } private static void flip(List<IBond> bonds) { for (IBond bond : bonds) flip(bond); } @Test public void testBenzeneStartWithDouble() throws InvalidSmilesException { SmilesParser sp = new SmilesParser(DefaultChemObjectBuilder.getInstance()); IAtomContainer mol = sp.parseSmiles("C1=CC=CC=C1"); assertBondOrders(mol, DOUBLE, SINGLE, DOUBLE, SINGLE, DOUBLE, SINGLE); List<IBond> path = new ArrayList<>(); Assert.assertTrue(ConjugationTools.findAlternating(path, mol.getBond(0))); flip(path); assertBondOrders(mol, SINGLE, DOUBLE, SINGLE, DOUBLE, SINGLE, DOUBLE); } @Test public void testBenzeneStartWithSingle() throws InvalidSmilesException { SmilesParser sp = new SmilesParser(DefaultChemObjectBuilder.getInstance()); IAtomContainer mol = sp.parseSmiles("C1=CC=CC=C1"); assertBondOrders(mol, DOUBLE, SINGLE, DOUBLE, SINGLE, DOUBLE, SINGLE); List<IBond> path = new ArrayList<>(); Assert.assertTrue(ConjugationTools.findAlternating(path, mol.getBond(1))); flip(path); assertBondOrders(mol, SINGLE, DOUBLE, SINGLE, DOUBLE, SINGLE, DOUBLE); } @Test public void testLargeRing() throws InvalidSmilesException { SmilesParser sp = new SmilesParser(DefaultChemObjectBuilder.getInstance()); IAtomContainer mol = sp.parseSmiles("C1=CC=CC=CC=CC=CC=C1"); assertBondOrders(mol, DOUBLE, SINGLE, DOUBLE, SINGLE, DOUBLE, SINGLE, DOUBLE, SINGLE, DOUBLE, SINGLE, DOUBLE, SINGLE); List<IBond> path = new ArrayList<>(); Assert.assertTrue(ConjugationTools.findAlternating(path, mol.getBond(0))); flip(path); assertBondOrders(mol, SINGLE, DOUBLE, SINGLE, DOUBLE, SINGLE, DOUBLE, SINGLE, DOUBLE, SINGLE, DOUBLE, SINGLE, DOUBLE); } @Test public void testNotPossible() throws InvalidSmilesException { SmilesParser sp = new SmilesParser(DefaultChemObjectBuilder.getInstance()); IAtomContainer mol = sp.parseSmiles("C1=CCCC=C1"); assertBondOrders(mol, DOUBLE, SINGLE, SINGLE, SINGLE, DOUBLE, SINGLE); List<IBond> path = new ArrayList<>(); Assert.assertFalse(ConjugationTools.findAlternating(path, mol.getBond(0))); } @Test public void testNotPossible2() throws InvalidSmilesException { // alternating path but the start and end are both double so not okay SmilesParser sp = new SmilesParser(DefaultChemObjectBuilder.getInstance()); IAtomContainer mol = sp.parseSmiles("C1=CC=CC=CC=1"); assertBondOrders(mol, DOUBLE, SINGLE, DOUBLE, SINGLE, DOUBLE, SINGLE, DOUBLE); List<IBond> path = new ArrayList<>(); Assert.assertFalse(ConjugationTools.findAlternating(path, mol.getBond(0))); } @Test public void test15Tautomer() throws InvalidSmilesException { SmilesParser sp = new SmilesParser(DefaultChemObjectBuilder.getInstance()); IAtomContainer mol = sp.parseSmiles("OC1=CC=NC=C1"); assertBondOrders(mol, SINGLE, DOUBLE, SINGLE, DOUBLE, SINGLE, DOUBLE, SINGLE); List<IBond> path = new ArrayList<>(); Assert.assertFalse(ConjugationTools.findAlternating(path, mol.getBond(0))); Assert.assertTrue(ConjugationTools.findTautomerShift(path, mol.getBond(0))); flip(path); assertBondOrders(mol, DOUBLE, SINGLE, DOUBLE, SINGLE, SINGLE, DOUBLE, SINGLE); } @Test public void test15Tautomer2() throws InvalidSmilesException { SmilesParser sp = new SmilesParser(DefaultChemObjectBuilder.getInstance()); IAtomContainer mol = sp.parseSmiles("O=C1C=CNC=C1"); assertBondOrders(mol, DOUBLE, SINGLE, DOUBLE, SINGLE, SINGLE, DOUBLE, SINGLE); List<IBond> path = new ArrayList<>(); Assert.assertFalse(ConjugationTools.findAlternating(path, mol.getBond(0))); Assert.assertTrue(ConjugationTools.findTautomerShift(path, mol.getBond(0))); flip(path); assertBondOrders(mol, SINGLE, DOUBLE, SINGLE, DOUBLE, SINGLE, DOUBLE, SINGLE); } @Test public void testNonTautomerShift() throws InvalidSmilesException { // alternating path but the start and end are both single so not okay SmilesParser sp = new SmilesParser(DefaultChemObjectBuilder.getInstance()); IAtomContainer mol = sp.parseSmiles("OC1=CC=CN=C1"); assertBondOrders(mol, SINGLE, DOUBLE, SINGLE, DOUBLE, SINGLE, DOUBLE, SINGLE); List<IBond> path = new ArrayList<>(); Assert.assertFalse(ConjugationTools.findAlternating(path, mol.getBond(0))); Assert.assertFalse(ConjugationTools.findTautomerShift(path, mol.getBond(0))); flip(path); } }
Java
2D
JChemPaint/jchempaint
inchi/src/main/java/org/openscience/jchempaint/inchi/InChI.java
.java
1,891
62
/* * 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; /** * Bean to capture InChI information * @author markr * */ public class InChI { private String inChI; private String auxInfo; private String key; public String getInChI() { return inChI; } public void setInChI(String inChI) { this.inChI = inChI; } public String getAuxInfo() { return auxInfo; } public void setAuxInfo(String auxInfo) { this.auxInfo = auxInfo; } public String getKey() { return key; } public void setKey(String key) { this.key = key; } public static InChI create(String str) { InChI inchi = new InChI(); inchi.setInChI(str); return inchi; } }
Java
2D
JChemPaint/jchempaint
inchi/src/main/java/org/openscience/jchempaint/inchi/InChITool.java
.java
2,694
86
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; import java.util.ArrayList; import java.util.List; import java.util.ServiceLoader; /** * Entry point for InChI generation. The tool finds an available {@link * org.openscience.jchempaint.inchi.InChIHandler} instance to utilise. * * @author John May */ public final class InChITool { static List<InChIHandler> handlers = new ArrayList<InChIHandler>(); static { for (InChIHandler handler : ServiceLoader.load(InChIHandler.class)) { handlers.add(handler); } } /** * Parse an InChI string and create a CDK structure representation. * * @param inchi InChI string * @return structure representation * @throws CDKException InChI could not be parsed */ public static IAtomContainer parseInChI(String inchi) throws CDKException { assert !handlers.isEmpty(); return handlers.get(0).parse(InChI.create(inchi)); } /** * Generate an InChI string from a CDK structure representation. * * @param container structure representation * @return InChI instance * @throws CDKException InChI could not be generated */ public static InChI generateInchi(IAtomContainer container) throws CDKException { assert !handlers.isEmpty(); return handlers.get(0).generate(container); } /** * Load an IChemModel from an InChI. * * @param url location * @return InChI instance * @throws CDKException InChI could not be generated */ public static IChemModel readInChI(URL url) throws CDKException { IChemModel chemModel = new ChemModel(); try { IAtomContainerSet moleculeSet = new AtomContainerSet(); chemModel.setMoleculeSet(moleculeSet); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String line; while ((line = in.readLine()) != null) { if (line.toLowerCase().startsWith("inchi=")) { moleculeSet.addAtomContainer(parseInChI(line)); } } in.close(); } catch (Exception e) { e.printStackTrace(); throw new CDKException(e.getMessage()); } return chemModel; } }
Java