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