private static void checkCoordinates(final IChemModel chemModel)
			throws CDKException {
		for (final IAtomContainer next : ChemModelManipulator
				.getAllAtomContainers(chemModel)) {
			if (!GeometryTools.get2DCoordinateCoverage(next).equals(
					GeometryTools.CoordinateCoverage.FULL)) {
				final String error = GT._("Not all atoms have 2D coordinates."
						+ " JCP can only show full 2D specified structures."
						+ " Shall we lay out the structure?");
				final int answer = JOptionPane.showConfirmDialog(null, error,
						"No 2D coordinates", JOptionPane.YES_NO_OPTION);

				if (answer == JOptionPane.NO_OPTION) {
					throw new CDKException(
							GT._("Cannot display without 2D coordinates"));
				} else {
					// CreateCoordinatesForFileDialog frame =
					// new CreateCoordinatesForFileDialog(chemModel);
					// frame.pack();
					// frame.show();

					WaitDialog.showDialog();
					final 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)
		 */
		final CDKHydrogenAdder hAdder = CDKHydrogenAdder.getInstance(chemModel
				.getBuilder());
		for (final IAtomContainer molecule : ChemModelManipulator
				.getAllAtomContainers(chemModel)) {
			if (molecule != null) {
				try {
					hAdder.addImplicitHydrogens(molecule);
				} catch (final CDKException e) {
					// do nothing
				}
			}
		}
	}
	/**
	 * Clean up chemical model ,removing duplicates empty molecules etc
	 * 
	 * @param chemModel
	 * @param avoidOverlap
	 * @throws CDKException
	 */
	public static void cleanUpChemModel(final IChemModel chemModel,
			final boolean avoidOverlap, final 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.removeDuplicateAtomContainers(chemModel);
		JChemPaint.checkCoordinates(chemModel);
		JChemPaint.removeEmptyAtomContainers(chemModel);

		if (avoidOverlap) {
			try {
				ControllerHub.avoidOverlap(chemModel);
			} catch (final Exception e) {
				JOptionPane.showMessageDialog(panel,
						GT._("Structure could not be generated"));
				throw new CDKException("Cannot depict structure");
			}
		}

		// We update implicit Hs in any case
		final CDKAtomTypeMatcher matcher = CDKAtomTypeMatcher
				.getInstance(chemModel.getBuilder());
		for (final IAtomContainer container : ChemModelManipulator
				.getAllAtomContainers(chemModel)) {
			for (final IAtom atom : container.atoms()) {
				if (!(atom instanceof IPseudoAtom)) {
					try {
						final IAtomType type = matcher.findMatchingAtomType(
								container, atom);
						if (type != null
								&& type.getFormalNeighbourCount() != null) {
							final int connectedAtomCount = container
									.getConnectedAtomsCount(atom);
							atom.setImplicitHydrogenCount(type
									.getFormalNeighbourCount()
									- connectedAtomCount);
						}
					} catch (final CDKException e) {
						e.printStackTrace();
					}
				}
			}
		}
	}
Exemple #3
0
	public void doInit() {
		String version = JCPPropertyHandler.getInstance(true).getVersion();
		String s1 = "JChemPaint " + version + "\n";
		s1 += GT._("An open-source editor for 2D chemical structures.");
		String s2 = GT._("An OpenScience project.")+"\n";
		s2 += GT._("See 'http://jchempaint.github.com' for more information.");

		getContentPane().setLayout(new BorderLayout());
		getContentPane().setBackground(Color.white);

		JLabel label1 = new JLabel();

		try {
			JCPPropertyHandler jcpph = JCPPropertyHandler.getInstance(true);
			URL url = jcpph.getResource("jcplogo" + JCPAction.imageSuffix);
			ImageIcon icon = new ImageIcon(url);
			//ImageIcon icon = new ImageIcon(../resources/);
			label1 = new JLabel(icon);
		} catch (Exception exception) {
			logger.error("Cannot add JCP logo: " + exception.getMessage());
			logger.debug(exception);
		}
		label1.setBackground(Color.white);

		Border lb = BorderFactory.createLineBorder(Color.white, 5);
		JTextArea jtf1 = new JTextArea(s1);
		jtf1.setBorder(lb);
		jtf1.setEditable(false);
		JTextArea jtf2 = new JTextArea(s2);
		jtf2.setEditable(false);
		jtf2.setBorder(lb);
		getContentPane().add("Center", label1);
		getContentPane().add("North", jtf1);
		getContentPane().add("South", jtf2);
		pack();
		setVisible(true);
	}
	public static void showInstance(final File inFile, final String type,
			final AbstractJChemPaintPanel jcpPanel, final boolean debug) {
		try {
			final IChemModel chemModel = JChemPaint.readFromFile(inFile, type,
					jcpPanel);

			final String name = inFile.getName();
			final JChemPaintPanel p = JChemPaint.showInstance(chemModel, name,
					debug);
			p.setCurrentWorkDirectory(inFile.getParentFile());
			p.setLastOpenedFile(inFile);
			p.setIsAlreadyAFile(inFile);
		} catch (final CDKException ex) {
			JOptionPane.showMessageDialog(jcpPanel, ex.getMessage());
			return;
		} catch (final FileNotFoundException e) {
			JOptionPane.showMessageDialog(jcpPanel, GT._("File does not exist")
					+ ": " + inFile.getPath());
			return;
		}
	}
	public static void showEmptyInstance(final boolean debug) {
		final IChemModel chemModel = emptyModel();
		showInstance(chemModel, GT._("Untitled") + " " + instancecounter++,
				debug);
	}
	@SuppressWarnings("static-access")
	public static void main(String[] args) {
		try {
			final String vers = System.getProperty("java.version");
			final String requiredJVM = "1.5.0";
			final Package self = Package
					.getPackage("org.openscience.jchempaint");
			String version = GT._("Could not determine JCP version");
			if (self != null) {
				version = JCPPropertyHandler.getInstance(true).getVersion();
			}
			if (vers.compareTo(requiredJVM) < 0) {
				System.err
						.println(GT
								._("WARNING: JChemPaint {0} must be run with a Java VM version {1} or higher.",
										new String[] { version, requiredJVM }));
				System.err.println(GT._("Your JVM version is {0}", vers));
				System.exit(1);
			}

			final Options options = new Options();
			options.addOption("h", "help", false, GT._("gives this help page"));
			options.addOption("v", "version", false,
					GT._("gives JChemPaints version number"));
			options.addOption("d", "debug", false,
					"switches on various debug options");
			options.addOption(OptionBuilder.withArgName("property=value")
					.hasArg().withValueSeparator()
					.withDescription(GT._("supported options are given below"))
					.create("D"));

			CommandLine line = null;
			try {
				final CommandLineParser parser = new PosixParser();
				line = parser.parse(options, args);
			} catch (final UnrecognizedOptionException exception) {
				System.err.println(exception.getMessage());
				System.exit(-1);
			} catch (final 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");

				final 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
			final Properties props = JCPPropertyHandler.getInstance(true)
					.getJCPProperties();
			try {
				UIManager.setLookAndFeel(props.getProperty("LookAndFeelClass"));
			} catch (final Throwable e) {
				final 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];
				final File file = new File(modelFilename);
				if (!file.exists()) {
					System.err.println(GT._("File does not exist") + ": "
							+ modelFilename);
					System.exit(-1);
				}
				showInstance(file, null, null, debug);
			} else {
				showEmptyInstance(debug);
			}

		} catch (final Throwable t) {
			System.err.println("uncaught exception: " + t);
			t.printStackTrace(System.err);
		}
	}
	/**
	 * 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(
			final AbstractJChemPaintPanel chemPaintPanel,
			IAtomContainer molecule, final boolean generateCoordinates,
			final boolean shiftPasted) throws CDKException {
		if (molecule == null) {
			return;
		}

		final 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 (final IAtomContainer atc : moleculeSet.atomContainers()) {
				// Detect the right border of the current structure..
				for (final IAtom atom : atc.atoms()) {
					if (atom.getPoint2d().x > maxXCurr) {
						maxXCurr = atom.getPoint2d().x;
					}
				}
				// Detect the left border of the pasted structure..
				for (final 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 (final IAtom atom : molecule.atoms()) {
					atom.setPoint2d(new Point2d(atom.getPoint2d().x + MARGIN
							+ SHIFT, atom.getPoint2d().y));
				}
			}
		}

		if (generateCoordinates) {
			// now generate 2D coordinates
			final StructureDiagramGenerator sdg = new StructureDiagramGenerator();
			sdg.setTemplateHandler(new TemplateHandler(moleculeSet.getBuilder()));
			try {
				sdg.setMolecule(molecule);
				sdg.generateCoordinates(new Vector2d(0, 1));
				molecule = sdg.getMolecule();
			} catch (final Exception exc) {
				JOptionPane.showMessageDialog(chemPaintPanel,
						GT._("Structure could not be generated"));
				throw new CDKException("Cannot depict structure");
			}
		}

		if (moleculeSet.getAtomContainer(0).getAtomCount() == 0) {
			moleculeSet.getAtomContainer(0).add(molecule);
		} else {
			moleculeSet.addAtomContainer(molecule);
		}

		final IUndoRedoFactory undoRedoFactory = chemPaintPanel.get2DHub()
				.getUndoRedoFactory();
		final UndoRedoHandler undoRedoHandler = chemPaintPanel.get2DHub()
				.getUndoRedoHandler();

		if (undoRedoFactory != null) {
			final IUndoRedoable undoredo = undoRedoFactory
					.getAddAtomsAndBondsEdit(chemPaintPanel.get2DHub()
							.getIChemModel(), molecule, null, "Paste",
							chemPaintPanel.get2DHub());
			undoRedoHandler.postEdit(undoredo);
		}

		chemPaintPanel.getChemModel().setMoleculeSet(moleculeSet);
		chemPaintPanel.updateUndoRedoControls();
		chemPaintPanel.get2DHub().updateView();
	}