]> gerrit.simantics Code Review - simantics/platform.git/blob - bundles/org.simantics.modeling.ui/src/org/simantics/modeling/ui/pdf/PDFDiagramExportWizard.java
Merge branch 'feature/funcwrite'
[simantics/platform.git] / bundles / org.simantics.modeling.ui / src / org / simantics / modeling / ui / pdf / PDFDiagramExportWizard.java
1 /*******************************************************************************
2  * Copyright (c) 2007, 2010 Association for Decentralized Information Management
3  * in Industry THTH ry.
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
8  *
9  * Contributors:
10  *     VTT Technical Research Centre of Finland - initial API and implementation
11  *******************************************************************************/
12 package org.simantics.modeling.ui.pdf;
13
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;
23 import java.util.Set;
24 import java.util.TreeSet;
25
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;
62
63 public class PDFDiagramExportWizard extends Wizard implements IExportWizard {
64
65     private static final int    MAX_RECENT_EXPORT_PATHS = 10;
66
67     private static final String TAG_PATH  = "path";
68
69     private static final String ATTR_NAME = "name";
70
71     Deque<String>               recentExportPaths;
72     boolean                     zoomToFit;
73     boolean                                             attachTG, attachWiki;
74
75     PDFExportPlan              exportPlan;
76
77     private boolean readPreferences() {
78         IPreferenceStore store = new ScopedPreferenceStore(InstanceScope.INSTANCE, Activator.PLUGIN_ID);
79
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);
85
86         return true;
87     }
88
89     private void writePreferences() throws IOException {
90         IPersistentPreferenceStore store = new ScopedPreferenceStore(InstanceScope.INSTANCE, Activator.PLUGIN_ID);
91
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));
96
97         if (store.needsSaving())
98             store.save();
99     }
100
101     private Deque<String> decodePaths(String recentPathsPref) {
102         Deque<String> result = new LinkedList<String>();
103         try {
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())
108                     result.add(name);
109             }
110         } catch (IllegalArgumentException e) {
111         }
112         return result;
113     }
114
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);
120         }
121         return sm.toString();
122     }
123
124     public PDFDiagramExportWizard() {
125         setWindowTitle("Export Diagrams to PDF");
126         setNeedsProgressMonitor(true);
127     }
128
129     @Override
130     public void addPages() {
131         super.addPages();
132         if (exportPlan != null) {
133             addPage(new PDFExportPage(exportPlan));
134         } else {
135             addPage(new NoProjectPage("Export Diagrams to PDF"));
136         }
137     }
138
139     private NamedResource toNamedResource(ReadGraph graph, Resource r) throws DatabaseException {
140         String name = graph.syncRequest(new GetName(r));
141         return new NamedResource(name, r);
142     }
143
144     @Override
145     public void init(IWorkbench workbench, IStructuredSelection selection) {
146         readPreferences();
147
148         ISessionContext ctx = SimanticsUI.getSessionContext();
149         if (ctx == null)
150             return;
151         IProject project = ctx.getHint(ProjectKeys.KEY_PROJECT);
152         if (project == null)
153             return;
154
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;
161         
162         // Get all model names
163         try {
164             exportPlan.sessionContext.getSession().syncRequest(new ReadRequest() {
165                 @Override
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);
172                     } else {
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 );
177                             break;
178                         }
179                     }
180
181                     List<NamedResource> models = new ArrayList<NamedResource>();
182                     
183                     Collection<Resource> ontologies = Simantics.applySCL("Simantics/SharedOntologies", "traverseSharedOntologies", graph, graph.getRootLibrary());
184                     for (Resource model : ontologies) {
185                         if (model.equals(selection))
186                             continue;
187                         models.add( toNamedResource(graph, model) );
188                     }
189                     
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))
193                             continue;
194                         models.add( toNamedResource(graph, model) );
195                     }
196                     Collections.sort(models);
197                     exportPlan.selectableModels.addAll(models);
198                     if (selection == null && !exportPlan.selectableModels.isEmpty()) {
199                         exportPlan.selection = exportPlan.selectableModels.get(0);
200                     }
201                 }
202             });
203         } catch (DatabaseException e) {
204             e.printStackTrace();
205         }
206     }
207
208     @Override
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);
212             if (!confirmed)
213                 return false;
214
215             try {
216                 FileUtils.deleteAll(exportPlan.exportLocation);
217             } catch (IOException e) {
218                 ExceptionUtils.logAndShowError(e);
219                 return false;
220             }
221         }
222
223         try {
224             recentExportPaths.addFirst(exportPlan.exportLocation.getAbsolutePath());
225
226             // Remove duplicates
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)) {
231                     it.remove();
232                 }
233             }
234
235             if (recentExportPaths.size() > MAX_RECENT_EXPORT_PATHS)
236                 recentExportPaths.pollLast();
237
238             zoomToFit = exportPlan.fitContentToPageMargins;
239             attachTG = exportPlan.attachTG;
240             attachWiki = exportPlan.attachWiki;
241
242             writePreferences();
243         } catch (IOException e) {
244             ErrorLogger.defaultLogError("Failed to write preferences", e);
245         }
246
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() {
250             @Override
251             public boolean select(Object toTest) {
252                 Node n = (Node) toTest;
253                 return exportPlan.selectedNodeSet.contains(n) && n.getDiagramResource() != null;
254             }
255         }, Node.CASE_INSENSITIVE_COMPARATOR);
256
257         long start = System.currentTimeMillis();
258         try {
259             getContainer().run(true, true, new IRunnableWithProgress() {
260                 @Override
261                 public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
262                     try {
263                         DiagramPrinter.printToPdf(monitor, exportPlan, exportPlan.exportLocation.toString(), exportPlan.selectedNodes);
264                     } catch (PdfException e) {
265                         throw new InvocationTargetException(e);
266                     } finally {
267                         monitor.done();
268                     }
269                 }
270             });
271         } catch (InvocationTargetException e) {
272             Throwable t = e.getTargetException();
273             ExceptionUtils.logAndShowError(t);
274             return false;
275         } catch (InterruptedException e) {
276             return false;
277         }
278         long end = System.currentTimeMillis();
279         System.out.println("PDF export took " + ((end - start) * 1e-3) + " seconds.");
280
281         return true;
282     }
283
284 }