4a4d97a18a2b254f0be58c2a928483dcecd234c6
[simantics/platform.git] / bundles / org.simantics.modeling / src / org / simantics / modeling / ModelingUtils.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;
13
14 import java.io.File;
15 import java.io.IOException;
16 import java.text.DateFormat;
17 import java.util.ArrayList;
18 import java.util.Collection;
19 import java.util.Collections;
20 import java.util.Date;
21 import java.util.HashMap;
22 import java.util.HashSet;
23 import java.util.List;
24 import java.util.Map;
25 import java.util.Set;
26 import java.util.TreeMap;
27
28 import org.eclipse.core.runtime.CoreException;
29 import org.eclipse.core.runtime.IProgressMonitor;
30 import org.eclipse.core.runtime.NullProgressMonitor;
31 import org.eclipse.core.runtime.Path;
32 import org.eclipse.jface.dialogs.Dialog;
33 import org.eclipse.jface.dialogs.IDialogConstants;
34 import org.eclipse.jface.dialogs.MessageDialog;
35 import org.eclipse.jface.layout.GridDataFactory;
36 import org.eclipse.jface.layout.GridLayoutFactory;
37 import org.eclipse.jface.resource.ImageDescriptor;
38 import org.eclipse.jface.viewers.IStructuredSelection;
39 import org.eclipse.jface.viewers.StructuredSelection;
40 import org.eclipse.jface.window.Window;
41 import org.eclipse.jface.wizard.WizardDialog;
42 import org.eclipse.swt.SWT;
43 import org.eclipse.swt.widgets.Composite;
44 import org.eclipse.swt.widgets.Control;
45 import org.eclipse.swt.widgets.Display;
46 import org.eclipse.swt.widgets.FileDialog;
47 import org.eclipse.swt.widgets.Shell;
48 import org.eclipse.ui.IWorkbenchWizard;
49 import org.eclipse.ui.PlatformUI;
50 import org.eclipse.ui.wizards.IWizardDescriptor;
51 import org.simantics.Simantics;
52 import org.simantics.annotation.ontology.AnnotationResource;
53 import org.simantics.databoard.Bindings;
54 import org.simantics.databoard.binding.Binding;
55 import org.simantics.databoard.binding.mutable.Variant;
56 import org.simantics.databoard.container.DataContainer;
57 import org.simantics.databoard.container.DataContainers;
58 import org.simantics.databoard.container.DataFormatException;
59 import org.simantics.databoard.container.FormatHandler;
60 import org.simantics.databoard.serialization.SerializationException;
61 import org.simantics.databoard.type.Datatype;
62 import org.simantics.databoard.util.URIStringUtils;
63 import org.simantics.datatypes.literal.GUID;
64 import org.simantics.db.MetadataI;
65 import org.simantics.db.ReadGraph;
66 import org.simantics.db.RequestProcessor;
67 import org.simantics.db.Resource;
68 import org.simantics.db.Session;
69 import org.simantics.db.Statement;
70 import org.simantics.db.VirtualGraph;
71 import org.simantics.db.WriteGraph;
72 import org.simantics.db.common.Indexing;
73 import org.simantics.db.common.NamedResource;
74 import org.simantics.db.common.QueryMemoryWatcher;
75 import org.simantics.db.common.changeset.GenericChangeListener;
76 import org.simantics.db.common.primitiverequest.IsInstanceOf;
77 import org.simantics.db.common.procedure.adapter.TransientCacheAsyncListener;
78 import org.simantics.db.common.procedure.adapter.TransientCacheListener;
79 import org.simantics.db.common.request.IndexRoot;
80 import org.simantics.db.common.request.ObjectsWithType;
81 import org.simantics.db.common.request.PossibleIndexRoot;
82 import org.simantics.db.common.request.ReadRequest;
83 import org.simantics.db.common.request.ResourceRead2;
84 import org.simantics.db.common.request.WriteRequest;
85 import org.simantics.db.common.request.WriteResultRequest;
86 import org.simantics.db.common.utils.ListUtils;
87 import org.simantics.db.common.utils.Logger;
88 import org.simantics.db.common.utils.NameUtils;
89 import org.simantics.db.common.utils.OrderedSetUtils;
90 import org.simantics.db.common.utils.VersionInfo;
91 import org.simantics.db.common.utils.VersionInfoRequest;
92 import org.simantics.db.common.utils.Versions;
93 import org.simantics.db.exception.DatabaseException;
94 import org.simantics.db.layer0.QueryIndexUtils;
95 import org.simantics.db.layer0.SelectionHints;
96 import org.simantics.db.layer0.adapter.CopyHandler;
97 import org.simantics.db.layer0.adapter.GenericRelationIndex;
98 import org.simantics.db.layer0.adapter.Instances;
99 import org.simantics.db.layer0.adapter.impl.DefaultPasteImportAdvisor;
100 import org.simantics.db.layer0.adapter.impl.ImportAdvisorFactory;
101 import org.simantics.db.layer0.genericrelation.DependenciesRelation.DependencyChangesRequest;
102 import org.simantics.db.layer0.genericrelation.DependencyChanges;
103 import org.simantics.db.layer0.genericrelation.IndexedRelations;
104 import org.simantics.db.layer0.migration.MigratedImportResult;
105 import org.simantics.db.layer0.migration.MigrationUtils;
106 import org.simantics.db.layer0.request.ActivateModel;
107 import org.simantics.db.layer0.request.ActiveModels;
108 import org.simantics.db.layer0.request.Configuration;
109 import org.simantics.db.layer0.request.IsLinkedTo;
110 import org.simantics.db.layer0.request.PossibleModel;
111 import org.simantics.db.layer0.util.ClipboardUtils;
112 import org.simantics.db.layer0.util.DraftStatusBean;
113 import org.simantics.db.layer0.util.ExternalDownloadBean;
114 import org.simantics.db.layer0.util.Layer0Utils;
115 import org.simantics.db.layer0.util.ModelTransferableGraphSourceRequest;
116 import org.simantics.db.layer0.util.PasteEventHandler;
117 import org.simantics.db.layer0.util.RemoverUtil;
118 import org.simantics.db.layer0.util.SimanticsClipboard;
119 import org.simantics.db.layer0.util.SimanticsClipboard.Representation;
120 import org.simantics.db.layer0.util.SimanticsClipboardImpl;
121 import org.simantics.db.layer0.util.SimanticsKeys;
122 import org.simantics.db.layer0.util.TransferableGraphConfiguration2;
123 import org.simantics.db.layer0.variable.Variable;
124 import org.simantics.db.layer0.variable.Variables;
125 import org.simantics.db.request.Read;
126 import org.simantics.db.service.ClusterControl;
127 import org.simantics.db.service.CollectionSupport;
128 import org.simantics.db.service.GraphChangeListenerSupport;
129 import org.simantics.db.service.QueryControl;
130 import org.simantics.db.service.VirtualGraphSupport;
131 import org.simantics.diagram.stubs.DiagramResource;
132 import org.simantics.diagram.stubs.G2DResource;
133 import org.simantics.diagram.synchronization.graph.AddElement;
134 import org.simantics.diagram.synchronization.graph.DiagramGraphUtil;
135 import org.simantics.graph.db.IImportAdvisor2;
136 import org.simantics.graph.db.ImportAdvisors;
137 import org.simantics.graph.db.MissingDependencyException;
138 import org.simantics.graph.db.StreamingTransferableGraphFileReader;
139 import org.simantics.graph.db.TransferableGraphException;
140 import org.simantics.graph.db.TransferableGraphSource;
141 import org.simantics.graph.db.TransferableGraphs;
142 import org.simantics.graph.representation.Identity;
143 import org.simantics.graph.representation.Root;
144 import org.simantics.graph.representation.TransferableGraph1;
145 import org.simantics.graph.representation.TransferableGraphUtils;
146 import org.simantics.issues.common.IssueSourceUtils;
147 import org.simantics.issues.ontology.IssueResource;
148 import org.simantics.layer0.Layer0;
149 import org.simantics.layer0.utils.direct.GraphUtils;
150 import org.simantics.modeling.adapters.ChangeInformation;
151 import org.simantics.modeling.template2d.ontology.Template2dResource;
152 import org.simantics.modeling.utils.OntologicalRequirementTracker;
153 import org.simantics.operation.Layer0X;
154 import org.simantics.project.ontology.ProjectResource;
155 import org.simantics.scenegraph.profile.ProfileUtils;
156 import org.simantics.scl.runtime.function.Function1;
157 import org.simantics.scl.runtime.tuple.Tuple;
158 import org.simantics.simulation.ontology.SimulationResource;
159 import org.simantics.structural.stubs.StructuralResource2;
160 import org.simantics.structural2.modelingRules.IModelingRules;
161 import org.simantics.structural2.scl.StructuralComponent;
162 import org.simantics.structural2.utils.StructuralUtils;
163 import org.simantics.utils.ObjectUtils;
164 import org.simantics.utils.datastructures.Pair;
165 import org.simantics.utils.datastructures.Triple;
166 import org.simantics.utils.datastructures.hints.HintContext;
167 import org.simantics.utils.ui.dialogs.ListDialog;
168
169 /**
170  * @author Hannu Niemistö
171  */
172 public class ModelingUtils {
173
174         private ReadGraph g;
175         private WriteGraph wg;
176         public Layer0 b;
177         private StructuralResource2 sr;
178         private DiagramResource dr;
179         public ModelingResources mr;
180         public SimulationResource SIMU;
181
182         public ModelingUtils(WriteGraph g) {
183                 wg = g;
184                 this.g = g;
185                 b = Layer0.getInstance(g);
186                 sr = StructuralResource2.getInstance(g);
187                 dr = DiagramResource.getInstance(g);
188                 mr = ModelingResources.getInstance(g);
189                 SIMU = SimulationResource.getInstance(g);
190         }
191
192         @Deprecated
193         public Resource createSymbol2(String name) throws DatabaseException {
194                 return createSymbol2(name, dr.Composite);
195         }
196
197         @Deprecated
198         public Resource createSymbol2(String name, Resource diagramType) throws DatabaseException {
199             return createSymbol2(name, diagramType, dr.DefinedElement);
200         }
201         @Deprecated
202         public Resource createSymbol2(String name, Resource diagramType, Resource symbolType) throws DatabaseException {
203                 G2DResource g2d = G2DResource.getInstance(g);
204
205 //              Resource visibleTag = wg.newResource();
206 //              wg.claim(visibleTag, b.SubrelationOf, null, dr.IsVisible);
207 //              Resource focusableTag = wg.newResource();
208 //              wg.claim(focusableTag, b.SubrelationOf, null, dr.IsFocusable);
209
210                 Double boxDimension = 6.0;
211                 Collection<Statement> grid = g.getAssertedStatements(diagramType, dr.HasGridSize);
212                 if(grid.size() == 1) {
213                         Double d = g.getPossibleValue(grid.iterator().next().getObject(), Bindings.DOUBLE);
214                         if(d != null) boxDimension = 2*d;
215                 }
216
217
218                 Resource element  = GraphUtils.create(wg,
219                                 b.InstanceOf, dr.SVGElement,
220                                 g2d.HasSVGDocument,
221                                 "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>" +
222                                                 // REMOVED by Tuukka, because This will cause
223                                                 // parsers to get on the net and get the doctype
224                                                 // definitions which can stall the UI for a long time.
225                                                 // Besides, we're not using the validation for anything
226                                                 // so it's useless to us.
227                                                 //"<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\" \"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\">" +
228                                                 "<svg xmlns=\"http://www.w3.org/2000/svg\" overflow=\"visible\" version=\"1.1\">" +
229                                                 "<rect x=\"-" + boxDimension + "\" y=\"-" + boxDimension + "\" width=\"" + (2*boxDimension) + "\" height=\"" + (2*boxDimension) + "\" fill=\"none\" stroke=\"rgb(0,0,0)\" stroke-width=\"0.1\"/>" +
230                                                 "</svg>"
231                                 );
232
233 //              wg.claim(element, visibleTag, element);
234 //              wg.claim(element, focusableTag, element);
235
236                 Resource orderedSet = OrderedSetUtils.create(wg, diagramType, element);
237
238 //              wg.claim(orderedSet, dr.HasLayer, GraphUtils.create2(wg, dr.Layer,
239 //                              b.HasName, "Default",
240 //                              dr.IsActive, Boolean.TRUE,
241 //                              dr.HasVisibleTag, visibleTag,
242 //                              dr.HasFocusableTag, focusableTag));
243
244                 Resource result = GraphUtils.create(wg,
245                                 b.HasName, name,
246                                 b.HasLabel, "",
247                                 sr.IsDefinedBy, orderedSet);
248
249                 wg.claim(result, b.ConsistsOf, orderedSet);
250                 wg.claimLiteral(orderedSet, b.HasName, "__DIAGRAM__", Bindings.STRING);
251                 AddElement.claimFreshElementName(wg, orderedSet, element);
252                 wg.claim(orderedSet, b.ConsistsOf, element);
253
254                 wg.claim(result, b.Inherits, null, symbolType);
255                 return result;
256         }
257
258         public static Collection<Resource> getElementCorrespondendences(ReadGraph g, Resource element) throws DatabaseException {
259                 DiagramResource dr = DiagramResource.getInstance(g);
260                 ModelingResources mr = ModelingResources.getInstance(g);
261                 if(g.isInstanceOf(element, dr.Connection)) {
262                         Resource mappedComponent = g.getPossibleObject(element, mr.ElementToComponent);
263                         if(mappedComponent != null) return Collections.singletonList(mappedComponent);
264                         Resource mappedConnection = g.getPossibleObject(element, mr.DiagramConnectionToConnection);
265                         if(mappedConnection == null)
266                                 return Collections.emptyList();
267                         ArrayList<Resource> result = new ArrayList<Resource>();
268                         Collection<Resource> relatedMappedConnections = StructuralUtils.getRelatedConnections(g, mappedConnection);
269                         for(Resource relatedMappedConnection : relatedMappedConnections)
270                                 for(Resource relatedConnection : g.getObjects(relatedMappedConnection, mr.ConnectionToDiagramConnection))
271                                         result.addAll(g.getObjects(relatedConnection, mr.ElementToComponent));
272                         return result;
273                 }
274                 else
275                         return g.getObjects(element, mr.ElementToComponent);
276         }
277
278         public static Resource getPossibleElement(ReadGraph g, Resource component) throws DatabaseException {
279                 ModelingResources mr = ModelingResources.getInstance(g);
280                 return g.getPossibleObject(component, mr.ComponentToElement);
281         }
282
283         public static Resource getPossibleElementCorrespondendence(ReadGraph g, Resource element) throws DatabaseException {
284                 Collection<Resource> corrs = getElementCorrespondendences(g, element);
285                 if(corrs.size() != 1) return null;
286                 else return corrs.iterator().next();
287         }
288
289         public static Resource getSingleElementCorrespondendence(ReadGraph g, Resource element) throws DatabaseException {
290                 Collection<Resource> corrs = getElementCorrespondendences(g, element);
291                 if(corrs.size() != 1) throw new DatabaseException("Expected 1 element correspondence, got " + corrs.size());
292                 else return corrs.iterator().next();
293         }
294
295         public static Resource createExperiment(WriteGraph graph, Resource model) throws DatabaseException {
296
297                 Layer0 L0 = Layer0.getInstance(graph);
298                 SimulationResource SIMU = SimulationResource.getInstance(graph);
299                 Resource experiment = graph.newResource();
300                 graph.claim(experiment, L0.InstanceOf, SIMU.Experiment);
301                 graph.claimLiteral(experiment, L0.HasName, "Experiment");
302                 graph.claim(model, L0.ConsistsOf, experiment);
303                 return experiment;
304
305         }
306
307         public static Resource createModel(WriteGraph graph, Resource type) throws DatabaseException {
308                 return createModel(graph, type, Simantics.getProjectResource(), null);
309         }
310                 
311         public static Resource createModel(WriteGraph graph, Resource type, String name) throws DatabaseException {
312                 return createModel(graph, type, Simantics.getProjectResource(), name);
313         }
314
315         public static Resource createModel(WriteGraph graph, Resource type, final Resource target, String name) throws DatabaseException {
316
317                 Layer0 L0 = Layer0.getInstance(graph);
318                 SimulationResource SIMU = SimulationResource.getInstance(graph);
319                 StructuralResource2 STR = StructuralResource2.getInstance(graph);
320                 ModelingResources MOD = ModelingResources.getInstance(graph);
321
322                 if(name == null)
323                         name = NameUtils.findFreshName(graph, "Model", target, L0.ConsistsOf, "%s%d");
324
325                 final Resource model = graph.newResource();
326                 graph.newClusterSet(model);
327                 graph.claim(model, L0.InstanceOf, null, type);
328                 graph.claimLiteral(model, L0.HasName, name);
329
330                 graph.claim(target, L0.ConsistsOf, model);
331
332                 Resource configurationType = graph.getPossibleObject(model, MOD.StructuralModel_HasConfigurationType);
333                 if(configurationType == null) configurationType = STR.Composite;
334
335                 Resource configuration = graph.newResource();
336                 graph.claimLiteral(configuration, L0.HasName, "Configuration", Bindings.STRING);
337                 graph.claim(configuration, L0.InstanceOf, null, configurationType);
338                 graph.claim(model, L0.ConsistsOf, configuration);
339                 graph.claim(model, SIMU.HasConfiguration, configuration);
340
341                 Resource joinClusterSet = graph.newResource();
342                 graph.newClusterSet(joinClusterSet);
343                 graph.claim(joinClusterSet, L0.InstanceOf, L0.ClusterSet);
344                 graph.claim(model, STR.HasJoinClusterSet, joinClusterSet);
345
346                 linkOntologyDependenciesToModel(graph, model, target);
347                 
348                 Resource ontology = graph.syncRequest(new PossibleIndexRoot(type));
349                 if(ontology != null) {
350                         graph.claim(model, L0.IsLinkedTo, ontology);
351                 }
352
353                 VirtualGraphSupport support = graph.getService(VirtualGraphSupport.class);
354                 graph.asyncRequest(new WriteRequest(support.getWorkspacePersistent("activations")) {
355
356                         @Override
357                         public void perform(WriteGraph graph) throws DatabaseException {
358                                 Layer0X L0X = Layer0X.getInstance(graph);
359                                 Collection<Resource> actives = graph.syncRequest(new ActiveModels(target));
360                                 if(actives.isEmpty()) {
361                                         graph.claim(model,  L0X.IsActivatedBy, target);
362                                 }
363                         }
364
365                 });
366
367                 return model;
368
369         }
370         
371         public static void linkOntologyDependenciesToModel(WriteGraph graph, Resource model, Resource target) 
372                         throws DatabaseException {
373                 Layer0 L0 = Layer0.getInstance(graph);
374                 ProjectResource PROJ = ProjectResource.getInstance(graph);
375                 for(Resource dep : graph.getObjects(target, L0.IsLinkedTo)) {
376                         if(graph.isInstanceOf(dep, PROJ.NamespaceRequirement)) {
377                                 for(Resource req : graph.getObjects(dep, PROJ.RequiresNamespace)) {
378                                         String uri = graph.getPossibleValue(req, Bindings.STRING);
379                                         if(uri != null) {
380                                                 Resource ns = graph.getResource(uri);
381                                                 if(ns != null) {
382                                                         graph.claim(model, L0.IsLinkedTo, null, ns);
383                                                 }
384                                         }
385                                 }
386                         }
387                 }
388         }
389         
390         public static void addSCLMainToModel(WriteGraph graph, Resource model) 
391                         throws DatabaseException {
392                 addSCLMainToModel(graph, model, "SCLMain", "include \"Simantics/All\"\n");
393         }
394         
395         public static void addSCLMainToModel(WriteGraph graph, Resource model, String name, String contents) 
396                         throws DatabaseException {
397                 Layer0 L0 = Layer0.getInstance(graph);
398         Resource sclmain = GraphUtils.create2(graph, L0.SCLModule, L0.PartOf, model, L0.HasName, name);
399         graph.claimLiteral(sclmain, L0.SCLModule_definition, contents, Bindings.STRING);
400         }
401
402     public static Resource createLocalLibrary(WriteGraph graph, Resource container, String name) throws DatabaseException {
403         Layer0 L0 = Layer0.getInstance(graph);
404         ModelingResources MOD = ModelingResources.getInstance(graph);
405         Resource library = graph.newResource();
406         graph.claim(library, L0.InstanceOf, null, L0.Library);
407         graph.addLiteral(library, L0.HasName, L0.NameOf, "Library", Bindings.STRING);
408         if (container != null) {
409             graph.claim(container, L0.ConsistsOf, L0.PartOf, library);
410             graph.claim(container, MOD.HasLocalLibrary, MOD.IsLocalLibraryOf, library);
411         }
412         return library;
413     }
414
415         public static void importModel(String fileName) {
416
417                 Resource project = Simantics.getProject().get();
418
419                 try (StreamingTransferableGraphFileReader importer = new StreamingTransferableGraphFileReader(new File(fileName))) {
420                         TransferableGraphSource tg = importer.readTG();
421
422                         final DefaultPasteImportAdvisor advisor = new DefaultPasteImportAdvisor(project) {
423                                 @Override
424                                 public void analyzeType(ReadGraph graph, Root root) throws DatabaseException {
425                                 }
426                                 @Override
427                                 public Resource analyzeRoot(ReadGraph graph, Root root) throws DatabaseException {
428                                         library = Simantics.getProjectResource();
429                                         String newName = newName(graph, library, root.name);
430                                         nameMappings.put(root.name, newName);
431                                         return null;
432                                 }
433                         };
434                         TransferableGraphs.importGraph1(Simantics.getSession(), tg, advisor);
435
436                 } catch (MissingDependencyException e) {
437
438                         final Set<String> missingURIs = e.getMissingURIs();
439
440                         class ErrorMessageDialog extends MessageDialog {
441
442                                 public ErrorMessageDialog(Shell shell) {
443                                         super(shell, 
444                                                         "Unsatisfied dependencies", null, 
445                                                         "The following dependencies were missing. Please import the dependencies and try again.", 
446                                                         MessageDialog.ERROR, new String[] { "Continue" }, 0);
447                                 }
448
449                                 @Override
450                                 protected Control createCustomArea(Composite composite) {
451                                         GridLayoutFactory.fillDefaults().applyTo(composite);
452                                         
453                                         org.eclipse.swt.widgets.List list = new org.eclipse.swt.widgets.List(composite, SWT.BORDER | SWT.READ_ONLY);
454                                         GridDataFactory.fillDefaults().grab(true, true).applyTo(list);
455                                         for(String s : missingURIs) list.add(s);
456                                         return composite;
457                                 }
458
459                         }
460
461                         Display display = Display.getCurrent();
462                         if(display != null) {
463                                 ErrorMessageDialog md = new ErrorMessageDialog(display.getActiveShell());
464                                 md.open();
465                         } else {
466                                 Display.getDefault().asyncExec(new Runnable() {
467
468                                         @Override
469                                         public void run() {
470                                                 Shell shell = Display.getCurrent().getActiveShell();
471                                                 ErrorMessageDialog md = new ErrorMessageDialog(shell);
472                                                 md.open();
473                                         }
474                                         
475                                 });
476                         }
477                         
478
479                 } catch (Exception e) {
480                         Logger.defaultLogError(e);
481                 }
482
483         }
484
485         public static void primeVirtualGraphs() {
486                 VirtualGraphSupport support = Simantics.getSession().getService(VirtualGraphSupport.class);
487                 support.getWorkspacePersistent("activations");
488                 support.getWorkspacePersistent("experiments");
489                 support.getWorkspacePersistent("issues");
490                 support.getWorkspacePersistent("preferences");
491         }
492
493         public static Resource createProfileEntry(WriteGraph graph, String name, Resource style, Resource group) throws DatabaseException {
494
495                 Layer0 L0 = Layer0.getInstance(graph);
496                 DiagramResource DIA = DiagramResource.getInstance(graph);
497
498                 Resource entry = graph.newResource();
499                 graph.claim(entry, L0.InstanceOf, null, DIA.GroupStyleProfileEntry);
500                 graph.claimLiteral(entry, L0.HasName, name);
501                 graph.claimLiteral(entry, L0.HasLabel, name);
502                 graph.claim(entry, DIA.ProfileEntry_HasStyle, style);
503                 graph.claim(entry, DIA.ProfileEntry_HasGroup, group);
504
505                 return entry;
506
507         }
508
509         public static Resource createProfile(WriteGraph graph, String profileName, Resource... entries) throws DatabaseException {
510
511                 Layer0 L0 = Layer0.getInstance(graph);
512                 DiagramResource DIA = DiagramResource.getInstance(graph);
513
514                 Resource list = ListUtils.create(graph, DIA.Profile, entries);
515
516                 Resource profile = graph.newResource();
517                 graph.claim(profile, L0.InstanceOf, null, DIA.Profile);
518                 graph.claimLiteral(profile, L0.HasName, profileName);
519                 graph.claim(profile, DIA.HasEntries, null, list);
520
521                 return profile;
522
523         }
524         
525         public static Resource createProfile(WriteGraph graph, String profileName, Collection<Resource> entries) throws DatabaseException {
526             return createProfile(graph, profileName, entries.toArray(new Resource[entries.size()]));
527         }
528
529         public static Resource createToplevelProfile(WriteGraph graph, Resource model, String name, Resource ... profiles) throws DatabaseException {
530
531                 Resource work = createProfile(graph, name, profiles);
532
533                 Layer0 L0 = Layer0.getInstance(graph);
534                 DiagramResource DIA = DiagramResource.getInstance(graph);
535
536                 graph.deny(model, DIA.HasActiveProfile);
537                 graph.claim(model, DIA.HasActiveProfile, work);
538                 graph.claim(model, L0.ConsistsOf, L0.PartOf, work);
539
540                 return work;
541
542         }
543         
544         public static Resource createToplevelProfile(WriteGraph graph, Resource model, String name, Collection<Resource> profiles) throws DatabaseException {
545             return createToplevelProfile(graph, model, name, profiles.toArray(new Resource[profiles.size()]));
546         }
547
548         public static void activateProfileEntries(WriteGraph graph, final Resource profile, final Resource ... entries) {
549
550                 VirtualGraphSupport support = graph.getService(VirtualGraphSupport.class);
551                 graph.asyncRequest(new WriteRequest(support.getWorkspacePersistent("profiles")) {
552
553                         @Override
554                         public void perform(WriteGraph graph) throws DatabaseException {
555                                 SimulationResource SIMU = SimulationResource.getInstance(graph);
556                                 for(Resource entry : entries)
557                                         graph.claim(profile, SIMU.IsActive, entry);
558                         }
559
560                 });
561
562         }
563         
564         public static void activateProfileEntries(WriteGraph graph, Resource profile, Collection<Resource> entries) {
565             activateProfileEntries(graph, profile, entries.toArray(new Resource[entries.size()]));
566         }
567         
568         public static void toggleProfileGroup(WriteGraph graph, Resource runtimeProfile, String groupName, boolean enabled) throws DatabaseException {
569                 Layer0 L0 = Layer0.getInstance(graph);
570                 for (Resource group : ProfileUtils.getProfileChildren(graph, runtimeProfile)) {
571                         String name = graph.getRelatedValue2(group, L0.HasName);
572                         if (name.equals(groupName)) {
573                                 toggleProfileGroup(graph, runtimeProfile, group, enabled);
574                                 return;
575                         }
576                 }
577         }
578         
579         public static void toggleProfileGroup(WriteGraph graph, Resource runtimeProfile, Resource group, boolean enabled) throws DatabaseException {
580         DiagramResource DIA = DiagramResource.getInstance(graph);
581                 
582         if(graph.isInstanceOf(group, DIA.Profile)) {
583                 
584                 for(Resource child : ProfileUtils.getProfileChildren(graph, group)) {
585                         toggleProfileGroup(graph, runtimeProfile, child, enabled);
586                 }
587                 
588         } else if(graph.isInstanceOf(group, DIA.ProfileEntry)) {
589
590             if(enabled) {
591                 graph.claim(runtimeProfile, SimulationResource.getInstance(graph).IsActive, null, group);
592             } else {
593                 graph.denyStatement(runtimeProfile, SimulationResource.getInstance(graph).IsActive, group);
594             }
595
596                 }
597         }
598
599     public static void untrackDependencies() {
600         untrackDependencies(Simantics.getSession());
601     }
602
603         public static void untrackDependencies(RequestProcessor processor) {
604         
605         try {
606             processor.syncRequest(new ReadRequest() {
607
608                 @Override
609                 public void run(ReadGraph graph) throws DatabaseException {
610                     Layer0X L0X = Layer0X.getInstance(graph);
611                     GenericRelationIndex index = graph.adapt(L0X.DependenciesRelation, GenericRelationIndex.class);
612                     index.untrack(graph.getSession(), graph.getRootLibrary());
613                 }
614                 
615             });
616         } catch (DatabaseException e) {
617             Logger.defaultLogError(e);
618         }
619
620     }
621
622     public static void trackDependencies() {
623         trackDependencies(Simantics.getSession());
624     }
625
626         public static void trackDependencies(RequestProcessor processor) {
627             
628             try {
629             processor.syncRequest(new ReadRequest() {
630
631                 @Override
632                 public void run(ReadGraph graph) throws DatabaseException {
633                     Layer0X L0X = Layer0X.getInstance(graph);
634                     GenericRelationIndex index = graph.adapt(L0X.DependenciesRelation, GenericRelationIndex.class);
635                     index.trackAndIndex(graph.getSession(), graph.getRootLibrary());
636                 }
637                 
638             });
639         } catch (DatabaseException e) {
640             Logger.defaultLogError(e);
641         }
642
643         }
644
645     public static void trackOntologicalRequirements() {
646         Session session = Simantics.getSession();
647         GraphChangeListenerSupport changeListenerSupport = session.getService(GraphChangeListenerSupport.class);
648         changeListenerSupport.addMetadataListener( OntologicalRequirementListener.getInstance() );
649     }
650
651     public static void untrackOntologicalRequirements() {
652         Session session = Simantics.getSession();
653         GraphChangeListenerSupport changeListenerSupport = session.getService(GraphChangeListenerSupport.class);
654         changeListenerSupport.removeMetadataListener( OntologicalRequirementListener.getInstance() );
655     }
656
657     public static class OntologicalRequirementListener extends GenericChangeListener<DependencyChangesRequest, DependencyChanges> {
658
659         private static OntologicalRequirementListener INSTANCE;
660
661         public static OntologicalRequirementListener getInstance() {
662             if(INSTANCE == null) {
663                 INSTANCE = new OntologicalRequirementListener();
664             }
665             return INSTANCE;
666         }
667
668         private OntologicalRequirementListener() {
669         }
670
671         private OntologicalRequirementTracker changeInformationUpdater = new OntologicalRequirementTracker();
672
673         @Override
674         public boolean preEventRequest() {
675             return !Indexing.isDependenciesIndexingDisabled();
676         }
677
678         @Override
679         public void onEvent(ReadGraph graph, MetadataI metadata, DependencyChanges event) throws DatabaseException {
680             changeInformationUpdater.update(graph, metadata, event);
681         }
682
683     }
684
685     public static void removeIndex(WriteGraph graph, Resource model) throws DatabaseException {
686         Layer0X L0X = Layer0X.getInstance(graph);
687         IndexedRelations ir = graph.getService(IndexedRelations.class);
688         // Deletes index files
689         ir.reset(null, graph, L0X.DependenciesRelation, model);
690     }
691     
692     public static void resetIssueSources(WriteGraph graph, Resource model) throws DatabaseException {
693         Layer0 L0 = Layer0.getInstance(graph);
694         IssueResource ISSUE = IssueResource.getInstance(graph);
695         for(Resource source : graph.sync(new ObjectsWithType(model, L0.ConsistsOf, ISSUE.ContinuousIssueSource))) {
696             IssueSourceUtils.update(graph, source);
697         }
698     }
699     
700     public static void copyAnnotationTypes(WriteGraph graph, Resource sourceModel, Resource targetModel) throws DatabaseException {
701
702         Layer0 L0 = Layer0.getInstance(graph);
703         AnnotationResource ANNO = AnnotationResource.getInstance(graph);
704
705         Instances query = graph.adapt(ANNO.AnnotationType, Instances.class);
706
707         Resource library = graph.getPossibleObject(targetModel, ANNO.HasAnnotationTypeRoot);
708         // HAXX:
709         if(library == null) {
710             library = graph.newResource();
711             graph.claim(library, L0.InstanceOf, null, ANNO.AnnotationTypeLibrary);
712             graph.claimLiteral(library, L0.HasName, L0.NameOf, L0.String, "Annotation types", Bindings.STRING);
713             graph.claim(library, L0.PartOf, L0.ConsistsOf, targetModel);
714             graph.claim(targetModel, ANNO.HasAnnotationTypeRoot, library);
715         }
716
717         for(Resource type : query.find(graph, sourceModel)) {
718             String name = graph.getRelatedValue(type, L0.HasName);
719             Resource existing = Layer0Utils.getPossibleChild(graph, library, name);
720             if(existing != null) {
721                 RemoverUtil.remove(graph, existing);
722             }
723             Layer0Utils.copyTo(graph, library, type);
724         }
725
726     }
727     
728         public static void deleteIndex(WriteGraph graph, Resource model) throws DatabaseException {
729                 Layer0X L0X = Layer0X.getInstance(graph);
730                 IndexedRelations ir = graph.getService(IndexedRelations.class);
731                 // Deletes index files
732                 ir.reset(null, graph, L0X.DependenciesRelation, model);
733         }
734     
735         public static void disableDependencies(WriteGraph graph, Resource dummy) {
736                 Layer0Utils.setDependenciesIndexingDisabled(graph, true);               
737         }
738
739     public static void releaseMemory(WriteGraph graph) {
740         
741                 QueryControl qc = graph.getService(QueryControl.class);
742                 ClusterControl cc = graph.getService(ClusterControl.class);
743                 cc.flushClusters();
744                 qc.flush(graph);
745         
746     }
747
748     public static List<Resource> filterByIndexRoot(ReadGraph graph, Resource indexRoot, List<Resource> resources) throws DatabaseException {
749         ArrayList<Resource> result =  new ArrayList<Resource>(resources.size());
750         for (Resource r : resources) {
751             Resource root = graph.syncRequest(new PossibleIndexRoot(r));
752             if (indexRoot.equals(root))
753                 result.add(r);
754         }
755         return result;
756     }
757
758     @Deprecated
759     public static List<Resource> searchByTypeShallow(ReadGraph graph, Resource model, Resource type) throws DatabaseException {
760         return QueryIndexUtils.searchByTypeShallow(graph, model, type);
761     }
762
763     @Deprecated
764     public static List<Resource> searchByType(ReadGraph graph, Resource model, Resource type) throws DatabaseException {
765         return QueryIndexUtils.searchByType(graph, model, type);
766     }
767
768     @Deprecated
769     public static List<Resource> searchByGUID(ReadGraph graph, Resource indexRoot, GUID guid) throws DatabaseException {
770         return QueryIndexUtils.searchByGUID(graph, indexRoot, guid);
771     }
772     
773     @Deprecated
774     public static List<Resource> searchByGUID(ReadGraph graph, Resource indexRoot, String indexString) throws DatabaseException {
775         return QueryIndexUtils.searchByGUID(graph, indexRoot, indexString);
776     }
777
778     @Deprecated
779     public static List<Resource> searchByQueryShallow(ReadGraph graph, Resource model, String query) throws DatabaseException {
780         return QueryIndexUtils.searchByQueryShallow(graph, model, query);
781     }
782
783     @Deprecated
784     public static List<Resource> searchByQuery(ReadGraph graph, Resource model, String query) throws DatabaseException {
785         return QueryIndexUtils.searchByQuery(graph, model, query);
786     }
787
788     @Deprecated
789     public static List<Resource> searchByTypeAndFilter(ReadGraph graph, Resource model, Resource type, Function1<Resource,Boolean> filter) throws DatabaseException {
790         return QueryIndexUtils.searchByTypeAndFilter(graph, model, type, filter);
791     }
792
793     @Deprecated
794     public static List<Triple<Resource, Resource, String>> getIndexEntries(ReadGraph graph, Resource model, String filter) throws DatabaseException {
795         return QueryIndexUtils.getIndexEntries(graph, model, filter);
796     }
797
798     @Deprecated
799     public static String listIndexEntries(ReadGraph graph, Resource model, String filter) throws DatabaseException {
800         return QueryIndexUtils.listIndexEntries(graph, model, filter);
801     }
802
803     @Deprecated
804     public static List<Resource> searchByTypeAndName(ReadGraph graph, Resource model, Resource type, String name) throws DatabaseException {
805         return QueryIndexUtils.searchByTypeAndName(graph, model, type, name);
806     }
807
808     @Deprecated
809     public static List<Resource> searchByTypeAndNameShallow(ReadGraph graph, Resource model, Resource type, String name) throws DatabaseException {
810         return QueryIndexUtils.searchByTypeAndNameShallow(graph, model, type, name);
811     }
812
813         /**
814          * @param graph
815          *            database write access
816          * @param sourceContainer
817          *            the source container to look for annotationProperty from to be
818          *            used as the copy source
819          * @param targetContainer
820          *            the target container for the copied annotationProperty
821          *            annotation
822          * @param annotationProperty
823          *            the annotation property relation
824          * @return created copy of the original annotation or <code>null</code> if
825          *         there was nothing to copy
826          * @throws DatabaseException
827          */
828         public static Resource copyPossibleAnnotation(WriteGraph graph, Resource sourceContainer, Resource targetContainer, Resource annotationProperty) throws DatabaseException {
829                 return copyPossibleAnnotation2(graph, sourceContainer, targetContainer, annotationProperty, null);
830         }
831
832         public static List<String> getPossibleNamePath(ReadGraph graph, Resource resource) throws DatabaseException {
833                 return getPossibleNamePath(graph, resource, null);
834         }
835          
836         private static List<String> getPossibleNamePath(ReadGraph graph, Resource resource, List<String> result) throws DatabaseException {
837                 
838                 Layer0 L0 = Layer0.getInstance(graph);
839                 String name = graph.getPossibleRelatedValue(resource, L0.HasName, Bindings.STRING);
840                 if(name == null) return null;
841
842                 if(result == null) result = new ArrayList<String>();
843                 
844                 SimulationResource SIMU = SimulationResource.getInstance(graph);
845                 if(graph.isInstanceOf(resource, SIMU.Model)) return result;
846                 
847                 Resource parent = graph.getPossibleObject(resource, L0.PartOf);
848                 if(parent != null) {
849                         getPossibleNamePath(graph, parent, result);
850                 } else {
851                         return null;
852                 }
853
854                 result.add(name);
855                 
856                 return result;
857
858         }
859         
860         public static Resource claimLibraryPath(WriteGraph graph, Resource resource, List<String> path) throws DatabaseException {
861                 Layer0 L0 = Layer0.getInstance(graph);
862                 for(int i=0;i<path.size()-1;i++) {
863                         String p = path.get(i);
864                         Resource child = Layer0Utils.getPossibleChild(graph, resource, p);
865                         if(child == null) {
866                                 child = graph.newResource();
867                                 graph.claim(child, L0.InstanceOf, L0.Library);
868                                 graph.addLiteral(child, L0.HasName, L0.NameOf, L0.String, p, Bindings.STRING);
869                                 graph.claim(resource, L0.ConsistsOf, L0.PartOf, child);
870                         }
871                         resource = child;
872                 }
873                 return resource;
874         }
875         
876         /**
877          * @param graph
878          *            database write access
879          * @param sourceContainer
880          *            the source container to look for annotationProperty from to be
881          *            used as the copy source
882          * @param targetContainer
883          *            the target container for the copied annotationProperty
884          *            annotation
885          * @param annotationProperty
886          *            the annotation property relation
887          * @param annotationProperty
888          *            the 2nd level annotation property relation or
889          *            <code>null</code> if no 2nd level annotation exists
890          * @return created copy of the original annotation or <code>null</code> if
891          *         there was nothing to copy
892          * @throws DatabaseException
893          */
894         public static Resource copyPossibleAnnotation2(WriteGraph graph,
895                         Resource sourceContainer, Resource targetContainer,
896                         Resource annotationProperty, Resource entryType) throws DatabaseException {
897
898                 // Delete existing target value first
899                 Layer0 L0 = Layer0.getInstance(graph);
900                 Resource targetValue = graph.getPossibleObject(targetContainer, annotationProperty);
901                 if (targetValue != null) {
902                         if(!graph.hasStatement(targetValue, L0.PartOf))
903                                 RemoverUtil.remove(graph, targetValue);
904                         graph.deny(targetContainer, annotationProperty);
905                 }
906
907                 Resource sourceValue = graph.getPossibleObject(sourceContainer, annotationProperty);
908                 if (sourceValue == null)
909                         return null;
910                 
911                 List<String> sourceValuePath = getPossibleNamePath(graph, sourceValue);
912                 if(sourceValuePath != null) {
913                         Resource targetModel = graph.sync(new PossibleModel(targetContainer));
914                         if(targetModel == null) throw new DatabaseException("No target model found for " + targetContainer);
915                         Resource library = claimLibraryPath(graph, targetModel, sourceValuePath);
916                         Resource existing = Layer0Utils.getPossibleChild(graph, library, sourceValuePath.get(sourceValuePath.size()-1));
917                         if(existing == null) {
918                                 existing = doCopyPossibleAnnotation2(graph, sourceContainer, targetContainer, annotationProperty, entryType);
919                                 graph.claim(library, L0.ConsistsOf, L0.PartOf, existing);
920                         }
921                         graph.claim(targetContainer, annotationProperty, existing);
922                         return existing;
923                 } else {
924                         return doCopyPossibleAnnotation2(graph, sourceContainer, targetContainer, annotationProperty, entryType);
925                 }
926
927         }
928
929         private static Resource doCopyPossibleAnnotation2(WriteGraph graph,
930                         Resource sourceContainer, Resource targetContainer,
931                         Resource annotationProperty, Resource entryType) throws DatabaseException {
932
933                 Resource sourceValue = graph.getPossibleObject(sourceContainer, annotationProperty);
934                 if (sourceValue == null)
935                         return null;
936                 
937                 // Copy 1st level annotation
938                 Resource targetValue = createAnnotation(graph, targetContainer, annotationProperty, sourceValue);
939
940                 // Copy possible 2nd level annotations and attach to 1st if entry
941                 // property is defined.
942                 Layer0 L0 = Layer0.getInstance(graph);
943                 if (entryType != null) {
944                         
945                         AnnotationResource ANNO = AnnotationResource.getInstance(graph);
946                         for (Resource entry : graph.getObjects(sourceValue, ANNO.Annotation_HasEntry)) {
947
948                                 String name = graph.getRelatedValue(entry, L0.HasName, Bindings.STRING);
949
950                                 List<String> entryPath = getPossibleNamePath(graph, entry);
951                                 if(entryPath != null) {
952                                         Resource targetModel = graph.sync(new PossibleModel(targetContainer));
953                                         if(targetModel == null) throw new DatabaseException("No target model found for " + targetContainer);
954                                         Resource library = claimLibraryPath(graph, targetModel, entryPath);
955                                         Resource existing = Layer0Utils.getPossibleChild(graph, library, entryPath.get(entryPath.size()-1));
956                                         if(existing == null) {
957                                                 existing = createTypedAnnotation(graph, null, null, entry, entryType, name);
958                                                 graph.claim(library, L0.ConsistsOf, L0.PartOf, existing);
959                                         }
960                                         graph.claim(targetValue, ANNO.Annotation_HasEntry, existing);
961                                 } else {
962                                         Resource result = createTypedAnnotation(graph, null, null, entry, entryType, name);
963                                         graph.claim(targetValue, ANNO.Annotation_HasEntry, result);
964                                 }
965                                 
966                         }
967                 }
968
969                 return targetValue;
970
971         }
972
973         /**
974          * @param graph
975          *            database write access
976          * @param container
977          *            the container resource to attach the new annotation to
978          * @param property
979          *            the annotation property relation. The type of the created
980          *            annotation is decided from this property relation's range
981          * @param sourceAnnotation
982          *            the annotation to copy data from or <code>null</code> if
983          *            nothing shall be copied
984          * @return the newly created annotation resource or <code>null</code> if the
985          *         annotation property relation didn't have a single range type
986          * @throws DatabaseException
987          */
988         public static Resource createAnnotation(WriteGraph graph, Resource container, Resource property, Resource sourceAnnotation) throws DatabaseException {
989                 return createAnnotation(graph, container, property, sourceAnnotation, null);
990         }
991
992         /**
993          * @param graph
994          *            database write access
995          * @param container
996          *            the container resource to attach the new annotation to
997          * @param property
998          *            the annotation property relation. The type of the created
999          *            annotation is decided from this property relation's range
1000          * @param sourceAnnotation
1001          *            the annotation to copy data from or <code>null</code> if
1002          *            nothing shall be copied
1003          * @param name
1004          *            name for newly created annotation or <code>null</code> to copy
1005          *            name from source if available
1006          * @return the newly created annotation resource or <code>null</code> if the
1007          *         annotation property relation didn't have a single range type
1008          * @throws DatabaseException
1009          */
1010         public static Resource createAnnotation(WriteGraph graph, Resource container, Resource property, Resource sourceAnnotation, String name) throws DatabaseException {
1011
1012                 Layer0 L0 = Layer0.getInstance(graph);
1013                 Resource annotationType = graph.getSingleObject(property, L0.HasRange);
1014                 if (annotationType == null)
1015                         return null;
1016
1017                 return createTypedAnnotation(graph, container, property, sourceAnnotation, annotationType, name);
1018
1019         }
1020
1021         /**
1022          * @param graph
1023          *            database write access
1024          * @param container
1025          *            the container resource to attach the new annotation to
1026          * @param property
1027          *            the annotation property relation
1028          * @param sourceAnnotation
1029          *            the annotation to copy data from or <code>null</code> if
1030          *            nothing shall be copied
1031          * @param annotationType
1032          *            the type of the new annotation
1033          * @return the newly created annotation resource
1034          * @throws DatabaseException
1035          */
1036         public static Resource createTypedAnnotation(WriteGraph graph, Resource container, Resource property, Resource sourceAnnotation, Resource annotationType) throws DatabaseException {
1037                 return createTypedAnnotation(graph, container, property, sourceAnnotation, annotationType, null);
1038         }
1039
1040         /**
1041          * @param graph
1042          *            database write access
1043          * @param container
1044          *            the container resource to attach the new annotation to
1045          * @param property
1046          *            the annotation property relation
1047          * @param sourceAnnotation
1048          *            the annotation to copy data from or <code>null</code> if
1049          *            nothing shall be copied
1050          * @param annotationType
1051          *            the type of the new annotation
1052          * @param name
1053          *            name for newly created annotation or <code>null</code> to copy
1054          *            name from source if available
1055          * @return the newly created annotation resource
1056          * @throws DatabaseException
1057          */
1058         public static Resource createTypedAnnotation(WriteGraph graph, Resource container, Resource property, Resource sourceAnnotation, Resource annotationType, String name) throws DatabaseException {
1059
1060                 Layer0 L0 = Layer0.getInstance(graph);
1061
1062                 Resource anno = graph.newResource();
1063
1064                 graph.claim(anno, L0.InstanceOf, null, annotationType);
1065
1066                 if (name != null)
1067                         graph.addLiteral(anno, L0.HasName, L0.NameOf, L0.String, name, Bindings.STRING);
1068
1069                 if (sourceAnnotation != null) {
1070
1071                         if (name == null) {
1072                                 String sourceName = graph.getPossibleRelatedValue(sourceAnnotation, L0.HasName, Bindings.STRING);
1073                                 if(sourceName != null) graph.addLiteral(anno, L0.HasName, L0.NameOf, L0.String, sourceName, Bindings.STRING);
1074                         }
1075
1076                         Resource sourceType = graph.getSingleType(sourceAnnotation);
1077                         List<AnnotationMap> am = getAnnotationMap(graph, annotationType, sourceType);
1078                         for (AnnotationMap a : am) {
1079                                 Resource object = graph.getSingleObject(sourceAnnotation, a.sourcePredicate);
1080                                 Collection<Resource> objectTypes = graph.getTypes(object);
1081                                 if (objectTypes.contains(L0.Literal)) {
1082                                         Object value = graph.getValue(object, a.defaultValueBinding);
1083                                         if (!ObjectUtils.objectEquals(value, a.defaultValue)) {
1084                                                 graph.addLiteral(anno, a.annotationPredicate, a.annotationPredicateInverse, a.defaultValueType, value, a.defaultValueBinding);
1085                                         }
1086                                 }
1087                         }
1088                 }
1089
1090                 if (container != null && property != null) {
1091                         graph.claim(container, property, anno);
1092                 }
1093
1094                 return anno;
1095
1096         }
1097
1098         private static class AnnotationMap {
1099
1100                 final public Resource sourcePredicate;
1101                 final public Resource sourcePredicateInverse;
1102
1103                 final public Resource annotationPredicate;
1104                 final public Resource annotationPredicateInverse;
1105
1106                 final public Resource defaultValueType;
1107                 final public Object defaultValue;
1108                 final public Binding defaultValueBinding;
1109
1110                 public AnnotationMap(Resource sp, Resource spi, Resource tp, Resource tpi, Resource defaultValueType, Object defaultValue, Binding defaultValueBinding) {
1111                         sourcePredicate = sp;
1112                         sourcePredicateInverse = spi;
1113                         annotationPredicate = tp;
1114                         annotationPredicateInverse = tpi;
1115                         this.defaultValueType = defaultValueType;
1116                         this.defaultValue = defaultValue;
1117                         this.defaultValueBinding = defaultValueBinding;
1118                 }
1119
1120         }
1121
1122         public static List<AnnotationMap> getAnnotationMap(ReadGraph graph, Resource annotationType, Resource sourceType) throws DatabaseException {
1123                 return graph.syncRequest(new AnnotationMapRequest(annotationType, sourceType), TransientCacheListener.<List<AnnotationMap>>instance());
1124         }
1125
1126         static class AnnotationMapRequest extends ResourceRead2<List<AnnotationMap>> {
1127
1128                 public AnnotationMapRequest(Resource annotationType, Resource sourceType) {
1129                         super(annotationType, sourceType);
1130                 }
1131
1132                 @Override
1133                 public List<AnnotationMap> perform(ReadGraph graph) throws DatabaseException {
1134
1135                         Layer0 L0 = Layer0.getInstance(graph);
1136
1137                         ArrayList<AnnotationMap> result = new ArrayList<AnnotationMap>(); 
1138
1139                         Map<String, Resource> annotationPredicates = new HashMap<String, Resource>();
1140                         for(Resource predicate : graph.getObjects(resource, L0.DomainOf)) {
1141                                 String name = graph.getRelatedValue(predicate, L0.HasName, Bindings.STRING);
1142                                 annotationPredicates.put(name, predicate);
1143                         }
1144                         Map<String, Resource> sourcePredicates = new HashMap<String, Resource>();
1145                         for(Resource predicate : graph.getObjects(resource2, L0.DomainOf)) {
1146                                 String name = graph.getRelatedValue(predicate, L0.HasName, Bindings.STRING);
1147                                 sourcePredicates.put(name, predicate);
1148                         }
1149
1150                         for(String key : sourcePredicates.keySet()) {
1151                                 Resource sourcePredicate = sourcePredicates.get(key);
1152                                 Resource anno = annotationPredicates.get(key);
1153                                 if(sourcePredicate != null && anno != null) {
1154                                         Resource defaultValueType = graph.getSingleObject(anno, L0.HasRange);
1155                                         Binding defaultValueBinding = null;
1156                                         Object defaultValue = null;
1157                                         Resource assertion = graph.getPossibleObject(anno, L0.HasPredicateInverse);
1158                                         if (assertion != null) {
1159                                                 Resource object = graph.getPossibleObject(assertion, L0.HasObject);
1160                                                 if (object != null) {
1161                                                         if(graph.isInstanceOf(object, L0.Literal)) {
1162                                                                 Datatype dt = graph.getDataType(object);
1163                                                                 defaultValueBinding = Bindings.getBeanBinding(dt);
1164                                                                 defaultValue = graph.getPossibleValue(object);
1165                                                         }
1166                                                 }
1167                                         }
1168                                         result.add(new AnnotationMap(
1169                                                         sourcePredicate, graph.getInverse(sourcePredicate),
1170                                                         anno, graph.getInverse(anno),
1171                                                         defaultValueType, defaultValue, defaultValueBinding));
1172                                 }
1173                         }
1174
1175                         return result;
1176
1177                 }
1178
1179         }
1180
1181         public static final String DRAWING_TEMPLATE_FORMAT    = "drawingTemplate";
1182     public static final String DRAWING_TEMPLATE_FORMAT_V1 = DRAWING_TEMPLATE_FORMAT + ":1";
1183     public static final String DRAWING_TEMPLATE_FORMAT_V2 = DRAWING_TEMPLATE_FORMAT + ":2";
1184
1185     public static Resource importDrawingTemplate(final Resource model, final File file) throws IOException, SerializationException, DatabaseException, TransferableGraphException {
1186
1187                 try {
1188
1189                         final Resource library = Simantics.sync(new WriteResultRequest<Resource>() {
1190
1191                                 @Override
1192                                 public Resource perform(WriteGraph graph) throws DatabaseException {
1193                                         
1194                                         Layer0 L0 = Layer0.getInstance(graph);
1195                                         Template2dResource TEMPLATE = Template2dResource.getInstance(graph);
1196                                         Resource root = graph.getPossibleObject(model, TEMPLATE.HasDrawingTemplateRoot);
1197                                         if(root == null) {
1198                                                 Template2dResource TEMPLATE2D = Template2dResource.getInstance(graph);
1199                                                 root = graph.newResource();
1200                                                 graph.claim(root, L0.InstanceOf, null, TEMPLATE2D.DrawingTemplateLibrary);
1201                                                 graph.claim(root, L0.InstanceOf, null, TEMPLATE2D.DrawingTemplateLibraryUI);
1202                                                 graph.claimLiteral(root, L0.HasName, L0.NameOf, L0.String, "Diagram Templates", Bindings.STRING);
1203                                                 graph.claim(root, L0.PartOf, L0.ConsistsOf, model);
1204                                                 graph.claim(model, TEMPLATE2D.HasDrawingTemplateRoot, root);
1205                                         }
1206                                         
1207                                         String name = new Path(file.getAbsolutePath()).removeFileExtension().lastSegment();
1208                                         if(name != null) {
1209                                                 Resource existing = Layer0Utils.getPossibleChild(graph, root, name);
1210                                                 if(existing != null)
1211                                                         graph.deny(root, L0.ConsistsOf, existing);
1212                                         }
1213                                         
1214                                         return root;
1215                                         
1216                                 }
1217
1218                         });
1219
1220                         final DefaultPasteImportAdvisor advisor = new DefaultPasteImportAdvisor(library);
1221
1222                         try {
1223                                 HashMap<String, FormatHandler<Object>> handlers = new HashMap<String, FormatHandler<Object>>();
1224                                 FormatHandler<Object> handler = new FormatHandler<Object>() {
1225                                         @Override
1226                                         public Binding getBinding() {
1227                                                 return TransferableGraph1.BINDING;
1228                                         }
1229
1230                                         @Override
1231                                         public Object process(DataContainer container) throws Exception {
1232                                                 TransferableGraphs.importGraph1(Simantics.getSession(), (TransferableGraph1)container.content.getValue(), 
1233                                                                 advisor, null);
1234                                                 return null;
1235                                         }
1236                                 };
1237                                 handlers.put(DRAWING_TEMPLATE_FORMAT_V1, handler);
1238                                 handlers.put(DRAWING_TEMPLATE_FORMAT_V2, handler);
1239                                 try {
1240                                         DataContainers.readFile(file, handlers);
1241                                 } catch(DataFormatException e) {
1242                                         throw new IOException(e);
1243                                 } catch(IOException e) {
1244                                         throw e;
1245                                 } catch(Exception e) {
1246                                         if(e instanceof RuntimeException)
1247                                                 throw (RuntimeException)e;
1248                                         else
1249                                                 throw new RuntimeException(e);
1250                                 }
1251
1252                         } catch(IOException e) {
1253                         }
1254
1255                         return advisor.getRoot();
1256
1257                 } catch (Throwable t) {
1258                         Logger.defaultLogError("Unexpected exception while importing diagram template.", t);
1259                 } finally {
1260                 }
1261
1262                 return null;
1263
1264         }
1265     
1266     public static Collection<Variable> getMappedVariables(ReadGraph graph, Variable source) throws DatabaseException {
1267         
1268         ArrayList<Variable> result = new ArrayList<Variable>();
1269         Resource represents = source.getPossibleRepresents(graph);
1270         if(represents == null) return Collections.emptyList();
1271         ModelingResources MOD = ModelingResources.getInstance(graph);
1272         for(Resource r : getElementCorrespondendences(graph, represents)) {
1273             result.add(Variables.getVariable(graph, r));
1274         }
1275         for(Resource r : graph.getObjects(represents, MOD.ComponentToElement)) {
1276             result.add(Variables.getVariable(graph, r));
1277         }
1278         for(Resource r : graph.getObjects(represents, MOD.DiagramToComposite)) {
1279             result.add(Variables.getVariable(graph, r));
1280         }
1281         for(Resource r : graph.getObjects(represents, MOD.CompositeToDiagram)) {
1282             result.add(Variables.getVariable(graph, r));
1283         }
1284         return result;
1285         
1286     }
1287     
1288     public static Resource getPossibleModel(ReadGraph graph, Resource resource) throws DatabaseException {
1289         
1290         PossibleModel pm = new PossibleModel(resource);
1291         Resource model = pm.perform(graph);
1292         return model;
1293     }
1294     
1295     public static Resource possibleIndexRoot(ReadGraph graph, Resource resource) throws DatabaseException {
1296         return graph.syncRequest(new PossibleIndexRoot(resource));
1297     }
1298
1299     public static Object getMonitorValue(StructuralComponent _variable, ReadGraph graph, String path) throws DatabaseException {
1300         Variable variable = ((VariableStructuralContext)_variable).variable;
1301         Variable var = variable.browse(graph, path);
1302         return var.getValue(graph);
1303     }
1304     
1305     public static void createSharedOntologyWithUI(ReadGraph graph, Variable variable, Resource baseType) throws DatabaseException {
1306         createSharedOntologyWithUI(graph, baseType);
1307     }
1308
1309     public static void createSharedOntologyWithUI(ReadGraph graph, Resource baseType) throws DatabaseException {
1310         
1311 //      Resource indexRoot_ = variable.getPossibleRepresents(graph);
1312 //      if(indexRoot_ == null) return;
1313
1314             final Map<Resource, Pair<String,ImageDescriptor>> map = new HashMap<Resource, Pair<String,ImageDescriptor>>();
1315
1316         Layer0 L0 = Layer0.getInstance(graph);
1317         SimulationResource SIMU = SimulationResource.getInstance(graph);
1318         Instances query = graph.adapt(L0.IndexRootType, Instances.class);
1319         for(Resource ontology : Layer0Utils.listOntologies(graph)) {
1320                 for(Resource type : query.find(graph, ontology)) {
1321                         if(graph.isInheritedFrom(type, SIMU.Model)) continue;
1322                         if(graph.hasStatement(type, L0.Abstract)) continue;
1323                         if(!graph.isInheritedFrom(type, baseType)) continue;
1324                         String name = graph.getPossibleRelatedValue(type, L0.HasLabel, Bindings.STRING);
1325                         if(name == null) name = graph.getRelatedValue(type, L0.HasName, Bindings.STRING);
1326                         map.put(type, new Pair<String,ImageDescriptor>(name, null));
1327                 }
1328         }
1329         
1330         Display.getDefault().asyncExec(new Runnable() {
1331                         @Override
1332                         public void run() {
1333                                 Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();
1334                                 CreateSharedOntologyDialog page = new CreateSharedOntologyDialog(shell, map, "Select type and name of new shared library");
1335                                 if (page.open() == Window.OK) {
1336                                         Object[] result = page.getResult();
1337                                         if (result != null && result.length == 1) {
1338                                                 final Resource res = (Resource)result[0];
1339                                                 final String name = "http://" + page.getName();
1340                                                 Simantics.getSession().asyncRequest(new WriteRequest() {
1341
1342                                                         @Override
1343                                                         public void perform(WriteGraph graph) throws DatabaseException {
1344                                                                 graph.markUndoPoint();
1345                                                                 Resource target = Simantics.applySCL("Simantics/SharedOntologies", "createSharedOntology", graph, name+"@A", res);
1346                                                                 
1347                                                                 ProjectResource PROJ = ProjectResource.getInstance(graph);
1348                                                                 Layer0 L0 = Layer0.getInstance(graph);
1349                                                                 for(Resource dep : graph.getObjects(Simantics.getProjectResource(), L0.IsLinkedTo)) {
1350                                                                         if(graph.isInstanceOf(dep, PROJ.NamespaceRequirement)) {
1351                                                                                 for(Resource req : graph.getObjects(dep, PROJ.RequiresNamespace)) {
1352                                                                                         String uri = graph.getPossibleValue(req, Bindings.STRING);
1353                                                                                         if(uri != null) {
1354                                                                                                 Resource ns = graph.getResource(uri);
1355                                                                                                 if(ns != null) {
1356                                                                                                         graph.claim(target, L0.IsLinkedTo, null, ns);
1357                                                                                                 }
1358                                                                                         }
1359                                                                                 }
1360                                                                         }
1361                                                                 }
1362                                                                 
1363                                                         }
1364                                                         
1365                                                 });
1366                                         }
1367                                 }
1368                         }
1369                 });
1370         
1371     }
1372
1373     public static void unlinkSharedOntologyWithUI(ReadGraph graph, Variable variable, final List<Resource> libraries) throws DatabaseException {
1374         
1375         final Resource indexRoot = variable.getPossibleRepresents(graph);
1376         if(indexRoot == null) return;
1377         
1378         StructuralResource2 STR = StructuralResource2.getInstance(graph);
1379
1380         final List<String> instances = new ArrayList<String>();
1381         
1382         DiagramResource DIA = DiagramResource.getInstance(graph);
1383         
1384         for(Resource library : libraries) {
1385                 for(Resource type : ModelingUtils.searchByTypeShallow(graph, library, STR.ComponentType)) {
1386                         for(Resource instance : ModelingUtils.searchByTypeShallow(graph, indexRoot, type)) {
1387                                 // TODO: haxx
1388                                 if(graph.isInstanceOf(instance, DIA.Element)) continue;
1389                                 String name = Versions.getStandardPathNameString(graph, instance);
1390                                 instances.add(name);
1391                         }
1392                 }
1393         }
1394         
1395         if(instances.isEmpty()) {
1396                 graph.getSession().asyncRequest(new WriteRequest() {
1397                         
1398                                 @Override
1399                                 public void perform(WriteGraph graph) throws DatabaseException {
1400                                 Layer0 L0 = Layer0.getInstance(graph);
1401                                 for(Resource library : libraries)
1402                                         graph.deny(indexRoot, L0.IsLinkedTo, library);
1403                                 }
1404                         
1405                 });
1406                 return;
1407         }
1408         
1409         PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
1410             @Override
1411             public void run() {
1412                 
1413                 if (!PlatformUI.isWorkbenchRunning())
1414                     return;
1415
1416                 Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();
1417                 ListDialog<String> dialog = new ListDialog<String>(
1418                         shell,
1419                         instances,
1420                         "Cannot unlink selected libraries",
1421                         "Libraries cannot be unlinked since the following instances are referring to them.") {
1422
1423                         protected void createButtonsForButtonBar(Composite parent) {
1424                                 createButton(parent, IDialogConstants.OK_ID, IDialogConstants.OK_LABEL,true);
1425                         }
1426                         
1427                 };
1428                 int result = dialog.open();
1429                 if (result != Dialog.OK)
1430                     return;
1431
1432             }
1433         });
1434         
1435     }
1436     
1437     public static MigratedImportResult importSharedOntologyWithResult(String fileName) throws Exception {
1438         try {
1439                 DataContainer dc = DataContainers.readFile(new File(fileName));
1440                 TransferableGraph1 tg = (TransferableGraph1)dc.content.getValue(TransferableGraph1.BINDING);
1441                 Variant draftStatus = dc.metadata.get(DraftStatusBean.EXTENSION_KEY);
1442                 return MigrationUtils.importSharedOntology(Simantics.getSession(), tg, draftStatus == null);
1443         } catch (Exception e) {
1444                 Logger.defaultLogError(e);
1445                 throw e;
1446         }
1447     }
1448     
1449     public static void importSharedOntology(String fileName) throws Exception {
1450         importSharedOntologyWithResult(fileName);
1451     }
1452
1453     public static List<Resource> importSharedOntology2(String fileName) throws Exception {
1454         MigratedImportResult result = importSharedOntologyWithResult(fileName);
1455         return new ArrayList<Resource>(result.roots);
1456     }
1457     
1458     public static void importSharedOntologyWithUI(ReadGraph graph, final Variable variable) throws DatabaseException {
1459         
1460         Display.getDefault().asyncExec(new Runnable() {
1461
1462                         @Override
1463                         public void run() {
1464                                 IStructuredSelection sel = new StructuredSelection(variable);
1465                         openWizard(Display.getCurrent(), sel, "org.simantics.modeling.ui.sharedOntologyImportWizard");
1466                         }
1467                         
1468                 });
1469         
1470     }
1471     
1472         public static class LibraryInfo implements Comparable<LibraryInfo> {
1473                 public NamedResource library;
1474                 public DraftStatusBean draft;
1475                 public LibraryInfo(String name, Resource r, DraftStatusBean draft) {
1476                         library = new NamedResource(name, r);
1477                         this.draft = draft;
1478                 }
1479                 @Override
1480                 public int compareTo(LibraryInfo o) {
1481                         return library.compareTo(o.library);
1482                 }
1483                 @Override
1484                 public int hashCode() {
1485                         return library.hashCode();
1486                 }
1487                 @Override
1488                 public boolean equals(Object object) {
1489                 if (this == object)
1490                     return true;
1491                 else if (object == null)
1492                     return false;
1493                 else if (!(object instanceof LibraryInfo))
1494                     return false;
1495                 LibraryInfo info = (LibraryInfo)object;
1496                 return info.library.equals(library);
1497                 }
1498                 
1499         }
1500         
1501     public static void exportSharedOntologyWithUI(final Resource sharedOntology) {
1502
1503         Display.getDefault().asyncExec(new Runnable() {
1504
1505                 @Override
1506                 public void run() {
1507                         HintContext hc = new HintContext();
1508                         hc.setHint(SelectionHints.KEY_MAIN, sharedOntology);
1509                         IStructuredSelection sel = new StructuredSelection(hc);
1510                 openWizard(Display.getCurrent(), sel, "org.simantics.modeling.ui.sharedOntologyExportWizard");
1511                 }
1512                 
1513         });
1514         
1515     }
1516         
1517     public static TransferableGraph1 exportSharedOntology(IProgressMonitor monitor, RequestProcessor processor, File location, String format, int version, final LibraryInfo info) throws DatabaseException, IOException {
1518         
1519         if(monitor == null) monitor = new NullProgressMonitor();
1520         final IProgressMonitor finalMonitor = monitor;
1521         // TODO: figure out a way to make the TG go directly into a file
1522         // instead of having it all in memory at once.
1523
1524         monitor.beginTask("Exporting shared library...", 100);
1525         SimanticsClipboard clipboard = processor.syncRequest(new Read<SimanticsClipboard>() {
1526             @Override
1527             public SimanticsClipboard perform(ReadGraph graph) throws DatabaseException {
1528                 CopyHandler ch = graph.adapt(info.library.getResource(), CopyHandler.class);
1529                 SimanticsClipboardImpl clipboard = new SimanticsClipboardImpl();
1530                 ch.copyToClipboard(graph, clipboard, finalMonitor);
1531                 return clipboard;
1532             }
1533         });
1534         
1535         TreeMap<String,Variant> metadata = getExportMetadata();
1536         DraftStatusBean draft = info.draft;
1537         if(draft != null) {
1538                 metadata.put(DraftStatusBean.EXTENSION_KEY, new Variant(DraftStatusBean.BINDING ,draft));
1539         }
1540         
1541         for (Set<Representation> object : clipboard.getContents()) {
1542                 
1543             TransferableGraph1 tg = ClipboardUtils.accept(processor, object, SimanticsKeys.KEY_TRANSFERABLE_GRAPH);
1544             monitor.worked(95);
1545             
1546             Variant edb = tg.extensions.get(ExternalDownloadBean.EXTENSION_KEY);
1547             if(edb != null) {
1548                 metadata.put(ExternalDownloadBean.EXTENSION_KEY, edb);
1549             }
1550
1551             if(location != null) {
1552                     monitor.setTaskName("Writing transferable graph...");
1553                     DataContainers.writeFile(location, new DataContainer(
1554                             format, version,
1555                             metadata, new Variant(TransferableGraph1.BINDING, tg)));
1556                     monitor.worked(5);
1557             }
1558             
1559             return tg;
1560             
1561         }
1562         
1563         throw new DatabaseException("Failed to export");
1564         
1565     }
1566
1567     public static TreeMap<String, Variant> getExportMetadata() {
1568
1569         TreeMap<String,Variant> metadata = new TreeMap<String,Variant>();
1570         metadata.put("date", Variant.ofInstance(DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL).format(new Date())));
1571         metadata.put("author", Variant.ofInstance(System.getProperty("user.name", "")));
1572
1573         return metadata;
1574         
1575     }
1576     
1577     public static void createNewVersionWithoutUI(WriteGraph graph, Resource resource) throws DatabaseException {
1578         VersionInfo info = graph.syncRequest(new VersionInfoRequest(resource));
1579         int currentVersion = Integer.parseInt(info.version);
1580         String result = Integer.toString(currentVersion + 1);
1581         createNewVersion(graph, resource, info, result);
1582     }
1583     
1584     public static void createNewVersionWithUI(ReadGraph graph, final Resource resource) throws DatabaseException {
1585         
1586         final VersionInfo info = graph.syncRequest(new VersionInfoRequest(resource));
1587         
1588         Display.getDefault().asyncExec(new Runnable() {
1589                         @Override
1590                         public void run() {
1591                                 Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();
1592                                 CreateVersionDialog dialog = new CreateVersionDialog(shell, info);
1593                                 if (dialog.open() == Window.OK) {
1594                                         final String result = dialog.getResult();
1595                                         Simantics.getSession().asyncRequest(new WriteRequest() {
1596                                                 @Override
1597                                                 public void perform(WriteGraph graph) throws DatabaseException {
1598                                                     createNewVersion(graph, resource, info, result);
1599                                                 }
1600                                         });
1601                                 }
1602                         }
1603                 });
1604         
1605     }
1606     
1607     public static void createNewVersion(WriteGraph graph, Resource resource, final VersionInfo info, final String result) throws DatabaseException {
1608         graph.markUndoPoint();
1609         Layer0 L0 = Layer0.getInstance(graph);
1610         Resource parent = graph.getPossibleObject(resource, L0.PartOf);
1611         if(parent == null) return;
1612         final String parentURI = graph.getPossibleURI(parent);
1613         if(parentURI == null) return;
1614         Layer0Utils.copyTo(graph, parent, resource, new PasteEventHandler() {
1615
1616             @Override
1617             public void postProcess(WriteGraph graph, Resource root) throws DatabaseException {
1618                 Layer0 L0 = Layer0.getInstance(graph);
1619                 graph.deny(root, L0.Entity_published);
1620             }
1621             
1622             @Override
1623             public IImportAdvisor2 createAdvisor(ReadGraph graph, ImportAdvisorFactory factory, Resource target) throws DatabaseException {
1624                 Map<String,Object> context = new HashMap<String,Object>();
1625                 String base = parentURI + "/" + URIStringUtils.escape( info.baseName ) + "@";
1626                 Map<String,String> renameMap = new HashMap<String,String>();
1627                 renameMap.put(base + info.version, base + result);
1628                 renameMap.put(info.baseName + "@" + info.version, info.baseName + "@" + result);
1629                 context.put(ImportAdvisors.RENAME_MAP, renameMap);
1630                 return factory.create(graph, target, context);
1631             }
1632             
1633         });
1634         Layer0Utils.addCommentMetadata(graph, "Created new version of " + info.baseName);
1635     }
1636     
1637     public static boolean isUserComponent(ReadGraph graph, Resource type) throws DatabaseException {
1638         StructuralResource2 STR = StructuralResource2.getInstance(graph);
1639         if(graph.isInstanceOf(type, STR.ProceduralComponentType)) return true;
1640         else if (graph.hasStatement(type, STR.IsDefinedBy)) return true;
1641         return false;
1642     }
1643     
1644     public static void publishComponentTypeWithUI(WriteGraph graph, final Resource componentType) throws DatabaseException {
1645
1646         Layer0 L0 = Layer0.getInstance(graph);
1647         StructuralResource2 STR = StructuralResource2.getInstance(graph);
1648         Resource composite = graph.getPossibleObject(componentType, STR.IsDefinedBy);
1649         final List<String> instances = new ArrayList<String>();
1650         if(composite != null) {
1651                 for(Resource component : graph.syncRequest(new ObjectsWithType(composite, L0.ConsistsOf, STR.Component))) {
1652                 Resource type = graph.getPossibleType(component, STR.Component);
1653                         if(type != null && isUserComponent(graph, type)) {
1654                                 if(!Layer0Utils.isPublished(graph, type)) instances.add(Versions.getStandardPathNameString(graph, component));
1655                         }
1656                 }
1657         }
1658
1659         if(instances.isEmpty()) {
1660                 graph.getSession().asyncRequest(new WriteRequest() {
1661                         
1662                                 @Override
1663                                 public void perform(WriteGraph graph) throws DatabaseException {
1664                                 graph.markUndoPoint();
1665                                 publish(graph, componentType);
1666                                 }
1667                         
1668                 });
1669                 return;
1670         }
1671         
1672         PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
1673             @Override
1674             public void run() {
1675                 
1676                 if (!PlatformUI.isWorkbenchRunning())
1677                     return;
1678
1679                 Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();
1680                 ListDialog<String> dialog = new ListDialog<String>(
1681                         shell,
1682                         instances,
1683                         "Cannot publish user component",
1684                         "The following instances are referring to unpublished user components.") {
1685
1686                         protected void createButtonsForButtonBar(Composite parent) {
1687                                 createButton(parent, IDialogConstants.OK_ID, IDialogConstants.OK_LABEL,true);
1688                         }
1689                         
1690                 };
1691                 int result = dialog.open();
1692                 if (result != Dialog.OK)
1693                     return;
1694
1695             }
1696         });
1697         
1698     }
1699
1700     public static void publishSharedOntologyWithUI(WriteGraph graph, final Resource sharedOntology) throws DatabaseException {
1701         
1702         Layer0 L0 = Layer0.getInstance(graph);
1703         DiagramResource DIA = DiagramResource.getInstance(graph);
1704         StructuralResource2 STR = StructuralResource2.getInstance(graph);
1705         final List<String> instances = new ArrayList<String>();
1706         for(Resource type : searchByTypeShallow(graph, sharedOntology, STR.ComponentType)) {
1707                         // TODO: haxx
1708                         if(graph.isInheritedFrom(type, DIA.Element)) continue;
1709                 if(!Layer0Utils.isPublished(graph, type)) instances.add(Versions.getStandardPathNameString(graph, type));
1710         }
1711         for(Resource dep : graph.syncRequest(new ObjectsWithType(sharedOntology, L0.IsLinkedTo, L0.SharedOntology))) {
1712                 if(!Layer0Utils.isPublished(graph, dep)) instances.add(Versions.getStandardPathNameString(graph, dep));
1713         }
1714         
1715         if(instances.isEmpty()) {
1716                 graph.getSession().asyncRequest(new WriteRequest() {
1717                         
1718                                 @Override
1719                                 public void perform(WriteGraph graph) throws DatabaseException {
1720                                 graph.markUndoPoint();
1721                                 publish(graph, sharedOntology);
1722                                 }
1723                         
1724                 });
1725                 return;
1726         }
1727         
1728         PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
1729             @Override
1730             public void run() {
1731                 
1732                 if (!PlatformUI.isWorkbenchRunning())
1733                     return;
1734
1735                 Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();
1736                 ListDialog<String> dialog = new ListDialog<String>(
1737                         shell,
1738                         instances,
1739                         "Cannot publish shared library",
1740                         "The following dependencies are unpublished.") {
1741
1742                         protected void createButtonsForButtonBar(Composite parent) {
1743                                 createButton(parent, IDialogConstants.OK_ID, IDialogConstants.OK_LABEL,true);
1744                         }
1745                         
1746                 };
1747                 int result = dialog.open();
1748                 if (result != Dialog.OK)
1749                     return;
1750
1751             }
1752         });
1753         
1754     }
1755
1756     public static Resource createSCLModuleDefault(WriteGraph graph, Resource target) throws DatabaseException {
1757         String name = NameUtils.findFreshEscapedName(graph, "SCLModule", target);
1758         return createSCLModule(graph, target, name);
1759     }
1760
1761     public static Resource createSCLModule(WriteGraph graph, Resource target, String name) throws DatabaseException {
1762         graph.markUndoPoint();
1763         Layer0 L0 = Layer0.getInstance(graph);
1764         Resource sclModule = GraphUtils.create2(graph, L0.SCLModule,
1765                 L0.HasName, name,
1766                 L0.PartOf, target,
1767                 L0.SCLModule_definition, "");
1768         Layer0Utils.addCommentMetadata(graph, "Created SCL Module " + name + " " + sclModule.toString());
1769         return sclModule;
1770     }
1771
1772     public static Resource setSCLModuleDefinition(WriteGraph graph, Resource module, String definition) throws DatabaseException {
1773         graph.markUndoPoint();
1774         Layer0 L0 = Layer0.getInstance(graph);
1775         graph.claimLiteral(module, L0.SCLModule_definition, definition, Bindings.STRING);
1776         Layer0Utils.addCommentMetadata(graph, "Set SCL module " + module + " definition.");
1777         return module;
1778     }
1779
1780     public static Resource createSCLScriptDefault(WriteGraph graph, Resource target) throws DatabaseException {
1781         String name = NameUtils.findFreshEscapedName(graph, "SCLScript", target);
1782         return createSCLScript(graph, target, name);
1783     }
1784
1785     public static Resource createSCLScript(WriteGraph graph, Resource target, String name) throws DatabaseException {
1786         graph.markUndoPoint();
1787         Layer0 L0 = Layer0.getInstance(graph);
1788         Resource sclModule = GraphUtils.create2(graph, L0.SCLScript,
1789                 L0.HasName, name,
1790                 L0.PartOf, target,
1791                 L0.SCLScript_definition, "");
1792         Layer0Utils.addCommentMetadata(graph, "Created SCL Script " + name + " " + sclModule.toString());
1793         return sclModule;
1794     }
1795
1796     public static Resource setSCLScriptDefinition(WriteGraph graph, Resource script, String definition) throws DatabaseException {
1797         graph.markUndoPoint();
1798         Layer0 L0 = Layer0.getInstance(graph);
1799         graph.claimLiteral(script, L0.SCLScript_definition, definition, Bindings.STRING);
1800         Layer0Utils.addCommentMetadata(graph, "Set SCL script " + script + " definition.");
1801         return script;
1802     }
1803
1804     public static Resource createPGraphDefault(WriteGraph graph, Resource target) throws DatabaseException {
1805         String name = NameUtils.findFreshEscapedName(graph, "Ontology Definition File", target);
1806         return createPGraph(graph, target, name);
1807     }
1808
1809     public static Resource createPGraph(WriteGraph graph, Resource target, String name) throws DatabaseException {
1810         graph.markUndoPoint();
1811         Layer0 L0 = Layer0.getInstance(graph);
1812         Resource file = GraphUtils.create2(graph, L0.PGraph,
1813                 L0.HasName, name,
1814                 L0.PartOf, target,
1815                 L0.PGraph_definition, "");
1816         Layer0Utils.addCommentMetadata(graph, "Created Ontology Definition File " + name + " " + file.toString());
1817         return file;
1818     }
1819
1820     public static Resource setPGraphDefinition(WriteGraph graph, Resource pgraph, String definition) throws DatabaseException {
1821         graph.markUndoPoint();
1822         Layer0 L0 = Layer0.getInstance(graph);
1823         graph.claimLiteral(pgraph, L0.PGraph_definition, definition, Bindings.STRING);
1824         Layer0Utils.addCommentMetadata(graph, "Set PGraph " + pgraph + " definition.");
1825         return pgraph;
1826     }
1827
1828     public static void publish(WriteGraph graph, Resource target) throws DatabaseException {
1829         Layer0 L0 = Layer0.getInstance(graph);
1830         graph.claimLiteral(target, L0.Entity_published, true, Bindings.BOOLEAN);
1831         Layer0Utils.addCommentMetadata(graph, "Published " + graph.getPossibleRelatedValue2(target, L0.HasName, Bindings.STRING) + " " + target.toString());
1832     }
1833
1834     public static boolean isLinkedToDeep(ReadGraph graph, Resource r1, Resource r2) throws DatabaseException {
1835         return graph.syncRequest(new IsLinkedTo(r1, r2));
1836     }
1837     
1838     public static void openWizard(Display display, IStructuredSelection selection, String id) {
1839         // First see if this is a "new wizard".
1840         IWizardDescriptor descriptor = PlatformUI.getWorkbench()
1841                         .getNewWizardRegistry().findWizard(id);
1842         // If not check if it is an "import wizard".
1843         if  (descriptor == null) {
1844                 descriptor = PlatformUI.getWorkbench().getImportWizardRegistry()
1845                                 .findWizard(id);
1846         }
1847         // Or maybe an export wizard
1848         if  (descriptor == null) {
1849                 descriptor = PlatformUI.getWorkbench().getExportWizardRegistry()
1850                                 .findWizard(id);
1851         }
1852         try  {
1853                 // Then if we have a wizard, open it.
1854                 if  (descriptor != null) {
1855                         IWorkbenchWizard wizard = descriptor.createWizard();
1856                         wizard.init(PlatformUI.getWorkbench(), selection);
1857                         WizardDialog wd = new  WizardDialog(display.getActiveShell(), wizard);
1858                         wd.setTitle(wizard.getWindowTitle());
1859                         wd.open();
1860                 }
1861         } catch  (CoreException e) {
1862                 e.printStackTrace();
1863         }
1864     }
1865     
1866     public static String withinEpsilon(double value, double reference, double epsilon) {
1867         if(Math.abs(value-reference) < epsilon) return "True";
1868         else return "Not within epsilon value=" + value + ", reference=" + reference + " , epsilon=" + epsilon; 
1869     }
1870     
1871     public static boolean needsIdentifier(ReadGraph graph, Resource r) throws DatabaseException {
1872         Layer0 L0 = Layer0.getInstance(graph);
1873         Collection<Resource> types = graph.getPrincipalTypes(r);
1874         for(Resource type : types)
1875                 if(graph.syncRequest(new IsInstanceOf(type, L0.TypeWithIdentifier), TransientCacheAsyncListener.<Boolean>instance()))
1876                                 return true;
1877         return false;
1878     }
1879
1880     public static boolean needsModificationInfo(ReadGraph graph, Resource r) throws DatabaseException {
1881         ModelingResources MOD = ModelingResources.getInstance(graph);
1882         Collection<Resource> types = graph.getPrincipalTypes(r);
1883         for(Resource type : types)
1884                 if(graph.syncRequest(new IsInstanceOf(type, MOD.TypeWithChangeInformation), TransientCacheAsyncListener.<Boolean>instance()))
1885                                 return true;
1886         return false;
1887     }
1888
1889     public static void attachCreationInformation(IProgressMonitor monitor, WriteGraph graph, Resource model) throws DatabaseException {
1890         
1891         if(monitor == null) monitor = new NullProgressMonitor();
1892         
1893         final String author = System.getProperty("user.name", "");
1894         final long time = System.currentTimeMillis();
1895         
1896         monitor.setTaskName("Attach creation information");
1897
1898         ModelingResources MOD = ModelingResources.getInstance(graph);
1899         Collection<Resource> rs = ModelingUtils.searchByType(graph, model, MOD.TypeWithChangeInformation);
1900         Collection<Resource> supers = ModelingUtils.getMostUnspecificTypes(graph, rs);
1901         
1902         CollectionSupport cs = graph.getService(CollectionSupport.class);
1903         Collection<Resource> set = cs.createSet();
1904         for(Resource type : supers) {
1905                 set.addAll(ModelingUtils.searchByTypeShallow(graph, model, type));
1906         }
1907         Collection<Resource> instances = Layer0Utils.sortByCluster(graph, set);
1908
1909         int pc = instances.size() / 100;
1910         int done = 0;
1911         int stint = pc;
1912
1913         for(Resource instance : instances) {
1914                 ChangeInformation info = graph.getPossibleRelatedValue(instance, MOD.changeInformation, ChangeInformation.BINDING);
1915                 if(info == null) {
1916                         info = new ChangeInformation();
1917                         info.createdAt = time;
1918                         info.createdBy = author;
1919                         info.modifiedAt = time;
1920                         info.modifiedBy = author;
1921                         graph.claimLiteral(instance, MOD.changeInformation, MOD.changeInformation_Inverse, MOD.ChangeInformation, info, ChangeInformation.BINDING);
1922                 }
1923                 done++;
1924                 stint--;
1925                 if(stint == 0) {
1926                         Double d = (100.0*done)/instances.size();
1927                         monitor.setTaskName("Attach creation information " +  d.intValue() + "%");
1928                         stint = pc;
1929                 }
1930         }
1931         
1932                 monitor.setTaskName("Attach creation information - commit");
1933         
1934     }
1935
1936     public static class DiagramComponentInfo {
1937
1938         private static String CHILD_PREFIX             = "child:";
1939
1940                 final private String compositePathAndName;
1941                 final private String componentName;
1942                 final private GUID guid;
1943                 
1944                 public DiagramComponentInfo(String compositePathAndName, String componentName, GUID guid) {
1945                         this.compositePathAndName = compositePathAndName;
1946                         this.componentName = componentName;
1947                         this.guid = guid;
1948                 }
1949                 
1950                 public static boolean isDiagramComponent(String tgName) {
1951                         return tgName.startsWith(CHILD_PREFIX);
1952                 }
1953
1954                 public String getTGName(CompositeInfo info) {
1955                         return CHILD_PREFIX + info.getOriginalPath() + ModelingUtils.COMPOSITE_SEPARATOR_CHAR + info.getEscapedName() + ModelingUtils.COMPOSITE_SEPARATOR_CHAR + getEscapedComponentName() + ModelingUtils.COMPOSITE_SEPARATOR_CHAR + guid.indexString();
1956                 }
1957                 
1958                 public boolean existsGUID(ReadGraph graph, Resource indexRoot) throws DatabaseException {
1959                         Collection<Resource> res = ModelingUtils.searchByGUID(graph, indexRoot, guid);
1960                         return !res.isEmpty();
1961                 }
1962
1963                 public static DiagramComponentInfo fromResource(ReadGraph graph, CompositeInfo info, Resource resource) throws DatabaseException {
1964                         Layer0 L0 = Layer0.getInstance(graph);
1965                 GUID childId = graph.getRelatedValue(resource, L0.identifier, GUID.BINDING);
1966             String childName = graph.getRelatedValue(resource, L0.HasName, Bindings.STRING);
1967             return new DiagramComponentInfo(info.getStateKey(), URIStringUtils.escape(childName), childId);
1968                 }
1969                 
1970                 public GUID getGUID() {
1971                         return guid;
1972                 }
1973                 
1974                 public String getEscapedCompositePathAndName() {
1975                         return compositePathAndName;
1976                 }
1977                 
1978                 public String getEscapedComponentName() {
1979                         return componentName;
1980                 }
1981                 
1982                 public String getUnescapedComponentName() {
1983                         return URIStringUtils.unescape(getEscapedComponentName());
1984                 }
1985                 
1986                 // "child:path#compositeName#componentName#guid"
1987                 public static DiagramComponentInfo parse(String tgName) {
1988                         
1989             String name = tgName.substring(CHILD_PREFIX.length());
1990             String compositePathAndName = "";
1991             String moduleName = name;
1992             GUID guid = GUID.invalid();
1993             int lastHash = name.lastIndexOf(ModelingUtils.COMPOSITE_SEPARATOR_CHAR);
1994             if(lastHash >= 0) {
1995                 String first = name.substring(0, lastHash);
1996                 String second = name.substring(lastHash+1);
1997                 lastHash = first.lastIndexOf(ModelingUtils.COMPOSITE_SEPARATOR_CHAR);
1998                 if(lastHash >= 0) {
1999                         compositePathAndName = first.substring(0, lastHash);
2000                         moduleName = first.substring(lastHash+1);
2001                         guid = GUID.parseIndexString(second);
2002                 } else {
2003                         compositePathAndName = first;
2004                         moduleName = second;
2005                 }
2006             }
2007             return new DiagramComponentInfo(compositePathAndName, moduleName, guid); 
2008                         
2009                 }
2010
2011
2012         @Override
2013                 public int hashCode() {
2014                         final int prime = 31;
2015                         int result = 1;
2016                         result = prime * result + ((compositePathAndName == null) ? 0 : compositePathAndName.hashCode());
2017                         result = prime * result + ((componentName == null) ? 0 : componentName.hashCode());
2018                         return result;
2019                 }
2020
2021                 @Override
2022                 public boolean equals(Object obj) {
2023                         if (this == obj)
2024                                 return true;
2025                         if (obj == null)
2026                                 return false;
2027                         if (getClass() != obj.getClass())
2028                                 return false;
2029                         DiagramComponentInfo other = (DiagramComponentInfo) obj;
2030                         if (compositePathAndName == null) {
2031                                 if (other.compositePathAndName != null)
2032                                         return false;
2033                         } else if (!compositePathAndName.equals(other.compositePathAndName))
2034                                 return false;
2035                         if (componentName == null) {
2036                                 if (other.componentName != null)
2037                                         return false;
2038                         } else if (!componentName.equals(other.componentName))
2039                                 return false;
2040                         return true;
2041                 }
2042                 
2043     }
2044     
2045         public static class CompositeInfo {
2046
2047             public static String COMPOSITE_PREFIX         = "composite:";
2048
2049                 final private boolean useGuids;
2050                 final private boolean applyPaths;
2051                 final private String path;
2052                 final private String name;
2053                 final private GUID guid;
2054                 
2055                 private CompositeInfo(boolean useGuids, boolean applyPaths, String path, String name, GUID guid) {
2056                         this.useGuids = useGuids;
2057                         this.applyPaths = applyPaths;
2058                         this.path = path;
2059                         this.name = name;
2060                         this.guid = guid;
2061                 }
2062
2063                 @Override
2064                 public String toString() {
2065                         return "CompositeInfo[useGuids=" + useGuids + ", applyPaths=" + applyPaths + ", path=" + path + ", name=" + name + ", guid=" + guid.indexString() + "]";
2066                 }
2067
2068                 public static boolean isComposite(String tgName) {
2069                         return tgName.startsWith(COMPOSITE_PREFIX);
2070                 }
2071
2072                 public String getTGName() {
2073                         return COMPOSITE_PREFIX + getOriginalPath() + ModelingUtils.COMPOSITE_SEPARATOR_CHAR + getEscapedName() + ModelingUtils.COMPOSITE_SEPARATOR_CHAR + guid.indexString();
2074                 }
2075                 
2076                 public boolean existsGUID(ReadGraph graph, Resource indexRoot) throws DatabaseException {
2077                         Collection<Resource> res = ModelingUtils.searchByGUID(graph, indexRoot, guid);
2078                         return !res.isEmpty();
2079                 }
2080
2081                 public static CompositeInfo fromResource(ReadGraph graph, Resource resource) throws DatabaseException {
2082                         
2083                         Layer0 L0 = Layer0.getInstance(graph);
2084             GUID rootId = graph.getRelatedValue(resource, L0.identifier, GUID.BINDING);
2085             String rootName = graph.getRelatedValue(resource, L0.HasName, Bindings.STRING);
2086             String escapedRootName = URIStringUtils.escape(rootName);
2087             String escapedPath = ModelingUtils.getDiagramCompositePath(graph, resource);
2088             return new CompositeInfo(true, true, escapedPath, escapedRootName, rootId);
2089                         
2090                 }
2091
2092             public static CompositeInfo parse(String tgName) {
2093                 return parse(tgName, true, true);
2094             }
2095
2096             /*
2097              * Index 0 is root-relative folder path separated with '/' or null if target-relative positioning is used
2098              * Index 1 is diagram name
2099              */
2100             public static CompositeInfo parse(String tgName, boolean applyPaths, boolean useGuids) {
2101                 if(!tgName.startsWith(COMPOSITE_PREFIX)) return null;
2102                 tgName = tgName.substring(COMPOSITE_PREFIX.length());
2103                 if(!tgName.contains(COMPOSITE_SEPARATOR)) {
2104                         if(useGuids) throw new IllegalStateException("GUID identifiers were not found for diagrams.");
2105                         return new CompositeInfo(useGuids, applyPaths, null, tgName, null);
2106                 }
2107                 String[] parts = tgName.split(COMPOSITE_SEPARATOR);
2108                 if(parts.length == 2) {
2109                         String name = parts[1];
2110                         String path = applyPaths ? parts[0] : null;
2111                         if(useGuids) throw new IllegalStateException("GUID identifiers were not found for diagrams.");
2112                         return new CompositeInfo(useGuids, applyPaths, path, name, null);
2113                 } else if(parts.length == 3) {
2114                         String path = parts[0];
2115                         String name = parts[1];
2116                         GUID guid = GUID.parseIndexString(parts[2]);
2117                         return new CompositeInfo(useGuids, applyPaths, path, name, guid);
2118                 } else {
2119                         return null;
2120                 }
2121             }
2122
2123                 public GUID getGUID() {
2124                         return guid;
2125                 }
2126
2127                 public String getEscapedName() {
2128                         return name;
2129                 }
2130                 
2131                 public String getUnescapedName() {
2132                         return URIStringUtils.unescape(name);
2133                 }
2134                 
2135                 public String getOriginalPath() {
2136                         return path;
2137                 }
2138                 
2139                 public String getFinalPath() {
2140                         if(applyPaths) return path;
2141                         else return null;
2142                 }
2143                 
2144                 public CompositeInfo renamed(String newName) {
2145                         return new CompositeInfo(useGuids, applyPaths, path, newName, guid);
2146                 }
2147                 
2148                 public String getStateKey() {
2149                         return path + "#" + getEscapedName();
2150                 }
2151                 
2152                 private Resource getFromFolder(ReadGraph graph, Resource target) throws DatabaseException {
2153             Resource diagram = Layer0Utils.getPossibleChild(graph, target, URIStringUtils.unescape(name));
2154             if(diagram == null) return null;
2155             StructuralResource2 STR = StructuralResource2.getInstance(graph);
2156             return graph.isInstanceOf(diagram, STR.Composite) ? diagram : null;
2157                 }
2158                 
2159                 public Resource resolve(ReadGraph graph, Resource target) throws DatabaseException {
2160
2161                         if(useGuids && guid != null) {
2162                                 Resource indexRoot = graph.syncRequest(new IndexRoot(target));
2163                                 Collection<Resource> queryResult = searchByGUID(graph, indexRoot, guid);
2164                                 if(queryResult.size() == 1) {
2165                                         Resource composite = queryResult.iterator().next(); 
2166                             StructuralResource2 STR = StructuralResource2.getInstance(graph);
2167                             if(!graph.isInstanceOf(composite, STR.Composite)) return null;
2168                             return composite;
2169                                 }
2170                         }
2171                         
2172                         if(applyPaths) {
2173                                 Resource folder = resolveFolder(graph, target);
2174                                 if(folder == null) return null;
2175                         return getFromFolder(graph, folder);
2176                         } else {
2177                         return getFromFolder(graph, target);
2178                         }
2179                         
2180                 }
2181                 
2182                 public Resource resolveFolder(ReadGraph graph, Resource target) throws DatabaseException {
2183                         
2184                         String path = getFinalPath();
2185                         if(path == null) return target;
2186                         
2187                 Resource folder = graph.syncRequest(new Configuration(target));
2188                 String[] segments = path.split("/");
2189                 for(int i=0;i<segments.length;i++) {
2190                         if(segments[i].isEmpty()) continue;
2191                         folder = Layer0Utils.getPossibleChild(graph, folder, URIStringUtils.unescape(segments[i]));
2192                         if(folder == null) return null;
2193                 }
2194                 
2195                 return folder;
2196                         
2197                 }
2198                 
2199                 
2200                 @Override
2201                 public int hashCode() {
2202                         
2203                         if(useGuids) return guid.hashCode();
2204                         
2205                         final int prime = 31;
2206                         int result = name.hashCode();
2207                         result = prime * result + ((path == null) ? 0 : path.hashCode());
2208                         return result;
2209                         
2210                 }
2211
2212                 @Override
2213                 public boolean equals(Object obj) {
2214                         
2215                         if (this == obj)
2216                                 return true;
2217                         if (obj == null)
2218                                 return false;
2219                         if (getClass() != obj.getClass())
2220                                 return false;
2221                         
2222                         CompositeInfo other = (CompositeInfo) obj;
2223                         
2224                         if(useGuids) return guid.equals(other.guid);
2225                         
2226                         if (!name.equals(other.name))
2227                                 return false;
2228                         
2229                         if(applyPaths)
2230                                 if (!path.equals(other.path))
2231                                         return false;
2232                         
2233                         return true;
2234                         
2235                 }
2236                 
2237         }
2238         
2239     public static char   COMPOSITE_SEPARATOR_CHAR = '#';
2240     public static String COMPOSITE_SEPARATOR      = String.valueOf(COMPOSITE_SEPARATOR_CHAR);
2241     
2242     public static CompositeInfo parseCompositeNameFromRoot(Root root, boolean applyPaths, boolean useGuids) {
2243         return CompositeInfo.parse(root.name, applyPaths, useGuids);
2244     }
2245
2246     public static CompositeInfo parseCompositeNameFromRoot(Identity root, boolean applyPaths, boolean useGuids) {
2247         String coded = TransferableGraphUtils.getName(root);
2248         return CompositeInfo.parse(coded, applyPaths, useGuids);
2249     }
2250     
2251         private static StringBuilder getDiagramCompositePathInternal(ReadGraph graph, Resource folder, StringBuilder builder) throws DatabaseException {
2252                 SimulationResource SIMU = SimulationResource.getInstance(graph);
2253                 Resource model = graph.getPossibleObject(folder, SIMU.IsConfigurationOf);
2254                 if (model != null) return builder;
2255
2256                 Layer0 L0 = Layer0.getInstance(graph);
2257                 String name = graph.getPossibleRelatedValue(folder, L0.HasName, Bindings.STRING);
2258                 if (name == null) return null;
2259                 Resource parent = graph.getPossibleObject(folder, L0.PartOf);
2260                 if (parent == null) return null;
2261
2262                 StringBuilder sb = getDiagramCompositePathInternal(graph, parent, builder);
2263                 if (sb == null) return null;
2264                 if (sb.length() > 0)
2265                         sb.append(URIStringUtils.NAMESPACE_PATH_SEPARATOR);
2266                 sb.append( URIStringUtils.escape(name) );
2267                 return sb;
2268         }
2269
2270         /**
2271          * @param graph
2272          * @param diagram
2273          * @return diagram/folder path up until model configuration root with each
2274          *         segment escaped using {@link URIStringUtils#escape(String)} and
2275          *         {@value URIStringUtils#NAMESPACE_PATH_SEPARATOR} between each
2276          *         segment or <code>null</code> if the specified diagram composite
2277          *         is not part of any model configuration structure.
2278          * @throws DatabaseException
2279          */
2280         public static String getDiagramCompositePath(ReadGraph graph, Resource diagram) throws DatabaseException {
2281                 Layer0 L0 = Layer0.getInstance(graph);
2282                 Resource parent = graph.getPossibleObject(diagram, L0.PartOf);
2283                 if(parent == null) return null;
2284                 StringBuilder sb = getDiagramCompositePathInternal(graph, parent, new StringBuilder());
2285                 return sb != null ? sb.toString() : null;
2286         }
2287         
2288         public static void exportModel(ReadGraph graph, Resource model, String fileName, String format, int version) throws DatabaseException {
2289                 TransferableGraphConfiguration2 conf = new TransferableGraphConfiguration2(graph, model, true, false);
2290                 exportModel(graph, conf, fileName, format, version);
2291         }
2292         
2293         public static void exportModel(ReadGraph graph, TransferableGraphConfiguration2 conf, String fileName, String format, int version) throws DatabaseException {
2294                 
2295                 try {
2296                 TransferableGraphSource s = graph.syncRequest(new ModelTransferableGraphSourceRequest(conf));
2297                         TransferableGraphs.writeTransferableGraph(graph, format, version, s, new File(fileName));
2298                 } catch (DatabaseException e) {
2299                         throw e;
2300                 } catch (Exception e) {
2301                         throw new DatabaseException(e);
2302                 }
2303
2304         }
2305
2306         public static TransferableGraph1 exportSharedOntology(ReadGraph graph, Resource library, String fileName, String format, int version) throws DatabaseException {
2307                 
2308         Layer0 L0 = Layer0.getInstance(graph);
2309         String name = graph.getRelatedValue(library, L0.HasName, Bindings.STRING);
2310
2311         DraftStatusBean draft = null;
2312         boolean published = Layer0Utils.isPublished(graph, library);
2313         if(!published) draft = new DraftStatusBean(new String[0]);
2314         
2315         LibraryInfo info = new LibraryInfo(name, library, draft);
2316                 
2317         try {
2318                         return exportSharedOntology(new NullProgressMonitor(), graph, fileName != null ? new File(fileName) : null, format, version, info);
2319                 } catch (IOException e) {
2320                         throw new DatabaseException(e);
2321                 }
2322
2323         }
2324
2325     public static DraftStatusBean getDependencyDraftStatus(ReadGraph graph, Resource library) throws DatabaseException {
2326         Layer0 L0 = Layer0.getInstance(graph);
2327         List<String> drafts = new ArrayList<>();
2328         for (Resource shared : graph.syncRequest(new ObjectsWithType(library, L0.IsLinkedTo, L0.SharedOntology))) {
2329             boolean published = Layer0Utils.isPublished(graph, shared);
2330             if (!published)
2331                 drafts.add(graph.getURI(shared));
2332         }
2333         return drafts.isEmpty() ? null : new DraftStatusBean(drafts);
2334     }
2335
2336         public static Set<Resource> getMostUnspecificTypes(final ReadGraph graph, Collection<Resource> types) throws DatabaseException {
2337                 
2338                 final Set<Resource> work = new HashSet<Resource>(types);
2339                 for(Resource type : types) {
2340                         Set<Resource> supers = graph.getSupertypes(type);
2341                         if(!Collections.disjoint(supers, work)) work.remove(type);
2342                 }
2343
2344                 return work;
2345                 
2346         }
2347         
2348         public static void rewriteGUIDS(WriteGraph graph, Resource root, boolean deep) throws DatabaseException {
2349                 List<Resource> todo = new ArrayList<Resource>();
2350                 todo.add(root);
2351                 Layer0 L0 = Layer0.getInstance(graph);
2352                 while(!todo.isEmpty()) {
2353                         Resource resource = todo.remove(todo.size()-1);
2354                         Layer0Utils.claimNewIdentifier(graph, resource, false);
2355             if(deep)
2356                 todo.addAll(graph.getObjects(resource, L0.ConsistsOf));
2357                 }
2358         }
2359         
2360         public static void createMissingGUIDs(IProgressMonitor monitor, WriteGraph graph, Collection<Resource> roots) throws DatabaseException {
2361                 
2362         if(monitor == null) monitor = new NullProgressMonitor();
2363         
2364                 Layer0 L0 = Layer0.getInstance(graph);
2365                 
2366         // Allow this process to make 50k queries
2367         QueryMemoryWatcher memory = new QueryMemoryWatcher(graph, 50000);
2368
2369                 for(Resource root : roots) {
2370                         
2371                         boolean madeChanges = false;
2372                         
2373                 monitor.setTaskName("Creating missing GUID identifiers " + NameUtils.getSafeName(graph, root));
2374                         Resource indexRoot = graph.syncRequest(new PossibleIndexRoot(root));
2375                         for(Resource r : searchByTypeShallow(graph, indexRoot, L0.Entity)) {
2376
2377                                 memory.maintain();
2378
2379                                 if(graph.isImmutable(r)) continue;
2380
2381                                 if(!ModelingUtils.needsIdentifier(graph, r)) continue;
2382                                 
2383                                 GUID existing = graph.getPossibleRelatedValue(r, L0.identifier, GUID.BINDING);
2384                                 if(existing == null) {
2385                                     Layer0Utils.claimNewIdentifier(graph, r, true);
2386                                         madeChanges = true;
2387                                 }
2388                                 
2389                         }
2390                         
2391                         if(madeChanges)
2392                                 ModelingUtils.deleteIndex(graph, root);
2393                         
2394                 }
2395                 
2396                 
2397         }
2398         
2399         public static boolean activateModel(WriteGraph graph, Resource model) throws DatabaseException {
2400                 return graph.syncRequest(new ActivateModel(Simantics.getProjectResource(), model));
2401         }
2402         
2403         public static File fileDialog(String title, List<Tuple> namesAndExtensions) {
2404                 return new Runnable() {
2405                         private File result;
2406                         
2407                         File getFile() {
2408                                 Display.getDefault().syncExec(this);
2409                                 return result;
2410                         }
2411                         
2412                         @Override
2413                         public void run() {
2414                                 result = showDialog();
2415                         }
2416
2417                         private File showDialog() {
2418                                 Display display = Display.getCurrent();
2419                                 Shell shell = display.getActiveShell();
2420                                 
2421                         FileDialog dialog = new FileDialog(shell, SWT.OPEN);
2422                         dialog.setText(title);
2423                         
2424                         String[] extensions = new String[namesAndExtensions.size()];
2425                         String[] filterNames = new String[namesAndExtensions.size()];
2426                         int index = 0;
2427                         for(Tuple t : namesAndExtensions) {
2428                                 String filterName = (String)t.get(0);
2429                                 String extension = (String)t.get(1);
2430                                 filterNames[index] = filterName;
2431                                 extensions[index] = extension;
2432                                 index++;
2433                         }
2434                         
2435                         dialog.setFilterExtensions(extensions);
2436                         dialog.setFilterNames(filterNames);
2437                         final String fileName = dialog.open();
2438                         if (fileName == null) return null;
2439                         
2440                         return new File(fileName);
2441                         }
2442                 }.getFile();
2443         }
2444         
2445         public static Resource createLibrary(WriteGraph graph, Resource parent) throws DatabaseException {
2446         Layer0 l0 = Layer0.getInstance(graph);
2447         return createLibrary(graph, parent, NameUtils.findFreshName(graph, "Library", parent, l0.ConsistsOf));
2448     }
2449     
2450     public static Resource createLibrary(WriteGraph graph, Resource parent, String name) throws DatabaseException {
2451         graph.markUndoPoint();
2452         Layer0 l0 = Layer0.getInstance(graph);
2453
2454         Resource library = graph.newResource();
2455         graph.claim(library, l0.InstanceOf, null, l0.Library);
2456         graph.addLiteral(library, l0.HasName, l0.NameOf, l0.String, name, Bindings.STRING);
2457         graph.claim(library, l0.PartOf, parent);
2458
2459         Layer0Utils.addCommentMetadata(graph, "Created new Library named " + name + ", resource " + library);
2460
2461         return library;
2462     }
2463
2464     public static IModelingRules getModelingRules(ReadGraph graph, Resource diagramResource) throws DatabaseException {
2465         return DiagramGraphUtil.getModelingRules(graph, diagramResource, null);
2466     }
2467
2468     public static void markChanged(WriteGraph graph, Resource r) throws DatabaseException {
2469         VirtualGraphSupport support = Simantics.getSession().getService(VirtualGraphSupport.class);
2470         VirtualGraph vg = support.getWorkspacePersistent("changeInformation");
2471         graph.syncRequest(new WriteRequest(vg) {
2472             @Override
2473             public void perform(WriteGraph graph) throws DatabaseException {
2474                 ModelingResources MOD = ModelingResources.getInstance(graph);
2475                 graph.claim(r, MOD.changed, MOD.changed, r);
2476             }
2477         });
2478     }
2479     
2480 }