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