1 /*******************************************************************************
2 * Copyright (c) 2007, 2010 Association for Decentralized Information Management
4 * All rights reserved. This program and the accompanying materials
5 * are made available under the terms of the Eclipse Public License v1.0
6 * which accompanies this distribution, and is available at
7 * http://www.eclipse.org/legal/epl-v10.html
10 * VTT Technical Research Centre of Finland - initial API and implementation
11 *******************************************************************************/
12 package org.simantics.modeling.ui.pdf;
14 import java.io.IOException;
15 import java.lang.reflect.InvocationTargetException;
16 import java.util.ArrayList;
17 import java.util.Collection;
18 import java.util.Collections;
19 import java.util.Deque;
20 import java.util.Iterator;
21 import java.util.LinkedList;
22 import java.util.List;
24 import java.util.TreeSet;
26 import org.eclipse.core.runtime.IProgressMonitor;
27 import org.eclipse.core.runtime.preferences.InstanceScope;
28 import org.eclipse.jface.dialogs.MessageDialog;
29 import org.eclipse.jface.operation.IRunnableWithProgress;
30 import org.eclipse.jface.preference.IPersistentPreferenceStore;
31 import org.eclipse.jface.preference.IPreferenceStore;
32 import org.eclipse.jface.viewers.IFilter;
33 import org.eclipse.jface.viewers.IStructuredSelection;
34 import org.eclipse.jface.wizard.Wizard;
35 import org.eclipse.ui.IExportWizard;
36 import org.eclipse.ui.IMemento;
37 import org.eclipse.ui.IWorkbench;
38 import org.eclipse.ui.preferences.ScopedPreferenceStore;
39 import org.simantics.Simantics;
40 import org.simantics.browsing.ui.graph.impl.request.GetName;
41 import org.simantics.db.ReadGraph;
42 import org.simantics.db.Resource;
43 import org.simantics.db.common.NamedResource;
44 import org.simantics.db.common.request.ObjectsWithType;
45 import org.simantics.db.common.request.ReadRequest;
46 import org.simantics.db.exception.DatabaseException;
47 import org.simantics.db.layer0.request.ActiveModels;
48 import org.simantics.db.management.ISessionContext;
49 import org.simantics.layer0.Layer0;
50 import org.simantics.modeling.requests.Node;
51 import org.simantics.modeling.ui.Activator;
52 import org.simantics.modeling.ui.utils.NoProjectPage;
53 import org.simantics.project.IProject;
54 import org.simantics.project.ProjectKeys;
55 import org.simantics.simulation.ontology.SimulationResource;
56 import org.simantics.ui.SimanticsUI;
57 import org.simantics.ui.utils.ResourceAdaptionUtils;
58 import org.simantics.utils.FileUtils;
59 import org.simantics.utils.ui.ErrorLogger;
60 import org.simantics.utils.ui.ExceptionUtils;
61 import org.simantics.utils.ui.workbench.StringMemento;
63 public class PDFDiagramExportWizard extends Wizard implements IExportWizard {
65 private static final int MAX_RECENT_EXPORT_PATHS = 10;
67 private static final String TAG_PATH = "path";
69 private static final String ATTR_NAME = "name";
71 Deque<String> recentExportPaths;
73 boolean attachTG, attachWiki;
75 PDFExportPlan exportPlan;
77 private boolean readPreferences() {
78 IPreferenceStore store = new ScopedPreferenceStore(InstanceScope.INSTANCE, Activator.PLUGIN_ID);
80 String recentPathsPref = store.getString(Preferences.DIAGRAM_EXPORT_PDF_PATH);
81 recentExportPaths = decodePaths(recentPathsPref);
82 zoomToFit = store.getBoolean(Preferences.DIAGRAM_EXPORT_PDF_ZOOM_TO_FIT);
83 attachTG = store.getBoolean(Preferences.DIAGRAM_EXPORT_PDF_ATTACH_TG);
84 attachWiki = store.getBoolean(Preferences.DIAGRAM_EXPORT_PDF_ATTACH_WIKI);
89 private void writePreferences() throws IOException {
90 IPersistentPreferenceStore store = new ScopedPreferenceStore(InstanceScope.INSTANCE, Activator.PLUGIN_ID);
92 store.putValue(Preferences.DIAGRAM_EXPORT_PDF_PATH, encodePaths(recentExportPaths));
93 store.putValue(Preferences.DIAGRAM_EXPORT_PDF_ZOOM_TO_FIT, String.valueOf(zoomToFit));
94 store.putValue(Preferences.DIAGRAM_EXPORT_PDF_ATTACH_TG, String.valueOf(attachTG));
95 store.putValue(Preferences.DIAGRAM_EXPORT_PDF_ATTACH_WIKI, String.valueOf(attachWiki));
97 if (store.needsSaving())
101 private Deque<String> decodePaths(String recentPathsPref) {
102 Deque<String> result = new LinkedList<String>();
104 StringMemento sm = new StringMemento(recentPathsPref);
105 for (IMemento m : sm.getChildren(TAG_PATH)) {
106 String name = m.getString(ATTR_NAME);
107 if (name != null && !name.isEmpty())
110 } catch (IllegalArgumentException e) {
115 private String encodePaths(Deque<String> recentPaths) {
116 StringMemento sm = new StringMemento();
117 for (String path : recentPaths) {
118 IMemento m = sm.createChild(TAG_PATH);
119 m.putString(ATTR_NAME, path);
121 return sm.toString();
124 public PDFDiagramExportWizard() {
125 setWindowTitle("Export Diagrams to PDF");
126 setNeedsProgressMonitor(true);
130 public void addPages() {
132 if (exportPlan != null) {
133 addPage(new PDFExportPage(exportPlan));
135 addPage(new NoProjectPage("Export Diagrams to PDF"));
139 private NamedResource toNamedResource(ReadGraph graph, Resource r) throws DatabaseException {
140 String name = graph.syncRequest(new GetName(r));
141 return new NamedResource(name, r);
145 public void init(IWorkbench workbench, IStructuredSelection selection) {
148 ISessionContext ctx = SimanticsUI.getSessionContext();
151 IProject project = ctx.getHint(ProjectKeys.KEY_PROJECT);
155 exportPlan = new PDFExportPlan(ctx, recentExportPaths);
156 exportPlan.project = project;
157 final Object selectedObject = selection.getFirstElement();
158 exportPlan.fitContentToPageMargins = zoomToFit;
159 exportPlan.attachTG = attachTG;
160 exportPlan.attachWiki = attachWiki;
162 // Get all model names
164 exportPlan.sessionContext.getSession().syncRequest(new ReadRequest() {
166 public void run(ReadGraph graph) throws DatabaseException {
167 Resource selection = ResourceAdaptionUtils.toSingleResource(selectedObject);
168 if (selection != null) {
169 //exportModel.selection = new NamedResource(name + " (input selection)", selection);
170 exportPlan.selection = toNamedResource(graph, selection);
171 exportPlan.selectableModels.add(exportPlan.selection);
173 for (Resource activeModel : graph.syncRequest(new ActiveModels(exportPlan.project.get()))) {
174 selection = activeModel;
175 exportPlan.selection = toNamedResource(graph, activeModel);
176 exportPlan.selectableModels.add( exportPlan.selection );
181 List<NamedResource> models = new ArrayList<NamedResource>();
183 Collection<Resource> ontologies = Simantics.applySCL("Simantics/SharedOntologies", "traverseSharedOntologies", graph, graph.getRootLibrary());
184 for (Resource model : ontologies) {
185 if (model.equals(selection))
187 models.add( toNamedResource(graph, model) );
190 for (Resource model : graph.syncRequest(new ObjectsWithType(exportPlan.project.get(),
191 Layer0.getInstance(graph).ConsistsOf, SimulationResource.getInstance(graph).Model))) {
192 if (model.equals(selection))
194 models.add( toNamedResource(graph, model) );
196 Collections.sort(models);
197 exportPlan.selectableModels.addAll(models);
198 if (selection == null && !exportPlan.selectableModels.isEmpty()) {
199 exportPlan.selection = exportPlan.selectableModels.get(0);
203 } catch (DatabaseException e) {
209 public boolean performFinish() {
210 if (exportPlan.exportLocation.exists()) {
211 boolean confirmed = MessageDialog.openConfirm(getShell(), "Overwrite", "Are you sure you want to overwrite " + exportPlan.exportLocation);
216 FileUtils.deleteAll(exportPlan.exportLocation);
217 } catch (IOException e) {
218 ExceptionUtils.logAndShowError(e);
224 recentExportPaths.addFirst(exportPlan.exportLocation.getAbsolutePath());
227 Set<String> dups = new TreeSet<String>(String.CASE_INSENSITIVE_ORDER);
228 for (Iterator<String> it = recentExportPaths.iterator(); it.hasNext();) {
229 String path = it.next();
230 if (!dups.add(path)) {
235 if (recentExportPaths.size() > MAX_RECENT_EXPORT_PATHS)
236 recentExportPaths.pollLast();
238 zoomToFit = exportPlan.fitContentToPageMargins;
239 attachTG = exportPlan.attachTG;
240 attachWiki = exportPlan.attachWiki;
243 } catch (IOException e) {
244 ErrorLogger.defaultLogError("Failed to write preferences", e);
247 // Make sure that the diagrams are printed in the same order as the user
248 // saw them in the wizard.
249 exportPlan.selectedNodes = exportPlan.nodes.depthFirstFlatten(new IFilter() {
251 public boolean select(Object toTest) {
252 Node n = (Node) toTest;
253 return exportPlan.selectedNodeSet.contains(n) && n.getDiagramResource() != null;
255 }, Node.CASE_INSENSITIVE_COMPARATOR);
257 long start = System.currentTimeMillis();
259 getContainer().run(true, true, new IRunnableWithProgress() {
261 public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
263 DiagramPrinter.printToPdf(monitor, exportPlan, exportPlan.exportLocation.toString(), exportPlan.selectedNodes);
264 } catch (PdfException e) {
265 throw new InvocationTargetException(e);
271 } catch (InvocationTargetException e) {
272 Throwable t = e.getTargetException();
273 ExceptionUtils.logAndShowError(t);
275 } catch (InterruptedException e) {
278 long end = System.currentTimeMillis();
279 System.out.println("PDF export took " + ((end - start) * 1e-3) + " seconds.");