package org.simantics.plant3d.handlers; import org.eclipse.core.commands.AbstractHandler; import org.eclipse.core.commands.ExecutionEvent; import org.eclipse.core.commands.ExecutionException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.jobs.Job; import org.simantics.Simantics; import org.simantics.db.Resource; import org.simantics.db.WriteGraph; import org.simantics.db.common.request.WriteRequest; import org.simantics.db.common.utils.NameUtils; import org.simantics.db.exception.DatabaseException; import org.simantics.db.layer0.adapter.ActionFactory; import org.simantics.layer0.Layer0; import org.simantics.plant3d.Activator; import org.simantics.plant3d.utils.P3DUtil; public class NewPlantHandler extends AbstractHandler implements ActionFactory { // Action factory method @Override public Runnable create(final Object target) { if (!(target instanceof Resource)) return null; return new Runnable() { @Override public void run() { createNewPlantJob((Resource) target); } }; } // Handler method @Override public Object execute(ExecutionEvent event) throws ExecutionException { final Resource library = Simantics.getProject().get(); createNewPlantJob(library); return null; } /** * Create a new plant as a user-triggered job. * * @param library Parent resource for the new plant. */ public static void createNewPlantJob(final Resource library) { Job job = new Job("Create Plant ") { @Override protected IStatus run(IProgressMonitor monitor) { monitor.beginTask("Create Plant" , IProgressMonitor.UNKNOWN); try { Simantics.getSession().syncRequest(new WriteRequest() { @Override public void perform(WriteGraph graph) throws DatabaseException { Layer0 l0 = Layer0.getInstance(graph); String modelName = NameUtils.findFreshName(graph, "Plant", library); Resource model = P3DUtil.createModel(graph, modelName); graph.claim(library, l0.ConsistsOf, model); } }); return Status.OK_STATUS; } catch (DatabaseException e) { return new Status(IStatus.ERROR, Activator.PLUGIN_ID, getName() + " failed.",e); } } }; job.setUser(true); job.schedule(); } }