1 /*******************************************************************************
2 * Copyright (c) 2007, 2010 Association for Decentralized Information Management
4 * All rights reserved. This program and the accompanying materials
5 * are made available under the terms of the Eclipse Public License v1.0
6 * which accompanies this distribution, and is available at
7 * http://www.eclipse.org/legal/epl-v10.html
10 * VTT Technical Research Centre of Finland - initial API and implementation
11 *******************************************************************************/
12 package org.simantics.modeling;
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;
26 import java.util.TreeMap;
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.core.runtime.SubMonitor;
33 import org.eclipse.jface.dialogs.Dialog;
34 import org.eclipse.jface.dialogs.IDialogConstants;
35 import org.eclipse.jface.dialogs.MessageDialog;
36 import org.eclipse.jface.layout.GridDataFactory;
37 import org.eclipse.jface.layout.GridLayoutFactory;
38 import org.eclipse.jface.resource.ImageDescriptor;
39 import org.eclipse.jface.viewers.IStructuredSelection;
40 import org.eclipse.jface.viewers.StructuredSelection;
41 import org.eclipse.jface.window.Window;
42 import org.eclipse.jface.wizard.WizardDialog;
43 import org.eclipse.swt.SWT;
44 import org.eclipse.swt.widgets.Composite;
45 import org.eclipse.swt.widgets.Control;
46 import org.eclipse.swt.widgets.Display;
47 import org.eclipse.swt.widgets.FileDialog;
48 import org.eclipse.swt.widgets.Shell;
49 import org.eclipse.ui.IWorkbenchWizard;
50 import org.eclipse.ui.PlatformUI;
51 import org.eclipse.ui.wizards.IWizardDescriptor;
52 import org.simantics.Simantics;
53 import org.simantics.annotation.ontology.AnnotationResource;
54 import org.simantics.databoard.Bindings;
55 import org.simantics.databoard.binding.Binding;
56 import org.simantics.databoard.binding.mutable.Variant;
57 import org.simantics.databoard.container.DataContainer;
58 import org.simantics.databoard.container.DataContainers;
59 import org.simantics.databoard.container.DataFormatException;
60 import org.simantics.databoard.container.FormatHandler;
61 import org.simantics.databoard.serialization.SerializationException;
62 import org.simantics.databoard.type.Datatype;
63 import org.simantics.databoard.util.URIStringUtils;
64 import org.simantics.datatypes.literal.GUID;
65 import org.simantics.db.MetadataI;
66 import org.simantics.db.ReadGraph;
67 import org.simantics.db.RequestProcessor;
68 import org.simantics.db.Resource;
69 import org.simantics.db.Session;
70 import org.simantics.db.Statement;
71 import org.simantics.db.VirtualGraph;
72 import org.simantics.db.WriteGraph;
73 import org.simantics.db.common.Indexing;
74 import org.simantics.db.common.NamedResource;
75 import org.simantics.db.common.QueryMemoryWatcher;
76 import org.simantics.db.common.changeset.GenericChangeListener;
77 import org.simantics.db.common.primitiverequest.IsInstanceOf;
78 import org.simantics.db.common.procedure.adapter.TransientCacheAsyncListener;
79 import org.simantics.db.common.procedure.adapter.TransientCacheListener;
80 import org.simantics.db.common.request.IndexRoot;
81 import org.simantics.db.common.request.ObjectsWithType;
82 import org.simantics.db.common.request.PossibleIndexRoot;
83 import org.simantics.db.common.request.ReadRequest;
84 import org.simantics.db.common.request.ResourceRead2;
85 import org.simantics.db.common.request.WriteRequest;
86 import org.simantics.db.common.request.WriteResultRequest;
87 import org.simantics.db.common.utils.ListUtils;
88 import org.simantics.db.common.utils.Logger;
89 import org.simantics.db.common.utils.NameUtils;
90 import org.simantics.db.common.utils.OrderedSetUtils;
91 import org.simantics.db.common.utils.VersionInfo;
92 import org.simantics.db.common.utils.VersionInfoRequest;
93 import org.simantics.db.common.utils.Versions;
94 import org.simantics.db.exception.DatabaseException;
95 import org.simantics.db.layer0.QueryIndexUtils;
96 import org.simantics.db.layer0.SelectionHints;
97 import org.simantics.db.layer0.adapter.CopyHandler;
98 import org.simantics.db.layer0.adapter.GenericRelationIndex;
99 import org.simantics.db.layer0.adapter.Instances;
100 import org.simantics.db.layer0.adapter.impl.DefaultPasteImportAdvisor;
101 import org.simantics.db.layer0.adapter.impl.ImportAdvisorFactory;
102 import org.simantics.db.layer0.genericrelation.DependenciesRelation.DependencyChangesRequest;
103 import org.simantics.db.layer0.genericrelation.DependencyChanges;
104 import org.simantics.db.layer0.genericrelation.IndexedRelations;
105 import org.simantics.db.layer0.migration.MigratedImportResult;
106 import org.simantics.db.layer0.migration.MigrationUtils;
107 import org.simantics.db.layer0.request.ActivateModel;
108 import org.simantics.db.layer0.request.ActiveModels;
109 import org.simantics.db.layer0.request.Configuration;
110 import org.simantics.db.layer0.request.IsLinkedTo;
111 import org.simantics.db.layer0.request.PossibleModel;
112 import org.simantics.db.layer0.util.ClipboardUtils;
113 import org.simantics.db.layer0.util.DraftStatusBean;
114 import org.simantics.db.layer0.util.ExternalDownloadBean;
115 import org.simantics.db.layer0.util.Layer0Utils;
116 import org.simantics.db.layer0.util.ModelTransferableGraphSourceRequest;
117 import org.simantics.db.layer0.util.PasteEventHandler;
118 import org.simantics.db.layer0.util.RemoverUtil;
119 import org.simantics.db.layer0.util.SimanticsClipboard;
120 import org.simantics.db.layer0.util.SimanticsClipboard.Representation;
121 import org.simantics.db.layer0.util.SimanticsClipboardImpl;
122 import org.simantics.db.layer0.util.SimanticsKeys;
123 import org.simantics.db.layer0.util.TransferableGraphConfiguration2;
124 import org.simantics.db.layer0.variable.Variable;
125 import org.simantics.db.layer0.variable.Variables;
126 import org.simantics.db.request.Read;
127 import org.simantics.db.service.ClusterControl;
128 import org.simantics.db.service.CollectionSupport;
129 import org.simantics.db.service.GraphChangeListenerSupport;
130 import org.simantics.db.service.QueryControl;
131 import org.simantics.db.service.VirtualGraphSupport;
132 import org.simantics.diagram.stubs.DiagramResource;
133 import org.simantics.diagram.stubs.G2DResource;
134 import org.simantics.diagram.synchronization.graph.AddElement;
135 import org.simantics.diagram.synchronization.graph.DiagramGraphUtil;
136 import org.simantics.graph.db.IImportAdvisor2;
137 import org.simantics.graph.db.ImportAdvisors;
138 import org.simantics.graph.db.MissingDependencyException;
139 import org.simantics.graph.db.StreamingTransferableGraphFileReader;
140 import org.simantics.graph.db.TransferableGraphException;
141 import org.simantics.graph.db.TransferableGraphSource;
142 import org.simantics.graph.db.TransferableGraphs;
143 import org.simantics.graph.representation.Identity;
144 import org.simantics.graph.representation.Root;
145 import org.simantics.graph.representation.TransferableGraph1;
146 import org.simantics.graph.representation.TransferableGraphUtils;
147 import org.simantics.issues.common.IssueSourceUtils;
148 import org.simantics.issues.ontology.IssueResource;
149 import org.simantics.layer0.Layer0;
150 import org.simantics.layer0.utils.direct.GraphUtils;
151 import org.simantics.modeling.adapters.ChangeInformation;
152 import org.simantics.modeling.template2d.ontology.Template2dResource;
153 import org.simantics.modeling.utils.OntologicalRequirementTracker;
154 import org.simantics.operation.Layer0X;
155 import org.simantics.project.ontology.ProjectResource;
156 import org.simantics.scenegraph.profile.ProfileUtils;
157 import org.simantics.scl.runtime.function.Function1;
158 import org.simantics.scl.runtime.tuple.Tuple;
159 import org.simantics.simulation.ontology.SimulationResource;
160 import org.simantics.structural.stubs.StructuralResource2;
161 import org.simantics.structural2.modelingRules.IModelingRules;
162 import org.simantics.structural2.scl.StructuralComponent;
163 import org.simantics.structural2.utils.StructuralUtils;
164 import org.simantics.utils.ObjectUtils;
165 import org.simantics.utils.datastructures.Pair;
166 import org.simantics.utils.datastructures.Triple;
167 import org.simantics.utils.datastructures.hints.HintContext;
168 import org.simantics.utils.ui.dialogs.ListDialog;
171 * @author Hannu Niemistö
173 public class ModelingUtils {
176 private WriteGraph wg;
178 private StructuralResource2 sr;
179 private DiagramResource dr;
180 public ModelingResources mr;
181 public SimulationResource SIMU;
183 public ModelingUtils(WriteGraph g) {
186 b = Layer0.getInstance(g);
187 sr = StructuralResource2.getInstance(g);
188 dr = DiagramResource.getInstance(g);
189 mr = ModelingResources.getInstance(g);
190 SIMU = SimulationResource.getInstance(g);
194 public Resource createSymbol2(String name) throws DatabaseException {
195 return createSymbol2(name, dr.Composite);
199 public Resource createSymbol2(String name, Resource diagramType) throws DatabaseException {
200 return createSymbol2(name, diagramType, dr.DefinedElement);
203 public Resource createSymbol2(String name, Resource diagramType, Resource symbolType) throws DatabaseException {
204 G2DResource g2d = G2DResource.getInstance(g);
206 // Resource visibleTag = wg.newResource();
207 // wg.claim(visibleTag, b.SubrelationOf, null, dr.IsVisible);
208 // Resource focusableTag = wg.newResource();
209 // wg.claim(focusableTag, b.SubrelationOf, null, dr.IsFocusable);
211 Double boxDimension = 6.0;
212 Collection<Statement> grid = g.getAssertedStatements(diagramType, dr.HasGridSize);
213 if(grid.size() == 1) {
214 Double d = g.getPossibleValue(grid.iterator().next().getObject(), Bindings.DOUBLE);
215 if(d != null) boxDimension = 2*d;
219 Resource element = GraphUtils.create(wg,
220 b.InstanceOf, dr.SVGElement,
222 "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>" +
223 // REMOVED by Tuukka, because This will cause
224 // parsers to get on the net and get the doctype
225 // definitions which can stall the UI for a long time.
226 // Besides, we're not using the validation for anything
227 // so it's useless to us.
228 //"<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\" \"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\">" +
229 "<svg xmlns=\"http://www.w3.org/2000/svg\" overflow=\"visible\" version=\"1.1\">" +
230 "<rect x=\"-" + boxDimension + "\" y=\"-" + boxDimension + "\" width=\"" + (2*boxDimension) + "\" height=\"" + (2*boxDimension) + "\" fill=\"none\" stroke=\"rgb(0,0,0)\" stroke-width=\"0.1\"/>" +
234 // wg.claim(element, visibleTag, element);
235 // wg.claim(element, focusableTag, element);
237 Resource orderedSet = OrderedSetUtils.create(wg, diagramType, element);
239 // wg.claim(orderedSet, dr.HasLayer, GraphUtils.create2(wg, dr.Layer,
240 // b.HasName, "Default",
241 // dr.IsActive, Boolean.TRUE,
242 // dr.HasVisibleTag, visibleTag,
243 // dr.HasFocusableTag, focusableTag));
245 Resource result = GraphUtils.create(wg,
248 sr.IsDefinedBy, orderedSet);
250 wg.claim(result, b.ConsistsOf, orderedSet);
251 wg.claimLiteral(orderedSet, b.HasName, "__DIAGRAM__", Bindings.STRING);
252 AddElement.claimFreshElementName(wg, orderedSet, element);
253 wg.claim(orderedSet, b.ConsistsOf, element);
255 wg.claim(result, b.Inherits, null, symbolType);
259 public static Collection<Resource> getElementCorrespondendences(ReadGraph g, Resource element) throws DatabaseException {
260 DiagramResource dr = DiagramResource.getInstance(g);
261 ModelingResources mr = ModelingResources.getInstance(g);
262 if(g.isInstanceOf(element, dr.Connection)) {
263 Resource mappedComponent = g.getPossibleObject(element, mr.ElementToComponent);
264 if(mappedComponent != null) return Collections.singletonList(mappedComponent);
265 Resource mappedConnection = g.getPossibleObject(element, mr.DiagramConnectionToConnection);
266 if(mappedConnection == null)
267 return Collections.emptyList();
268 ArrayList<Resource> result = new ArrayList<Resource>();
269 Collection<Resource> relatedMappedConnections = StructuralUtils.getRelatedConnections(g, mappedConnection);
270 for(Resource relatedMappedConnection : relatedMappedConnections)
271 for(Resource relatedConnection : g.getObjects(relatedMappedConnection, mr.ConnectionToDiagramConnection))
272 result.addAll(g.getObjects(relatedConnection, mr.ElementToComponent));
276 return g.getObjects(element, mr.ElementToComponent);
279 public static Resource getPossibleElement(ReadGraph g, Resource component) throws DatabaseException {
280 ModelingResources mr = ModelingResources.getInstance(g);
281 return g.getPossibleObject(component, mr.ComponentToElement);
284 public static Resource getPossibleElementCorrespondendence(ReadGraph g, Resource element) throws DatabaseException {
285 Collection<Resource> corrs = getElementCorrespondendences(g, element);
286 if(corrs.size() != 1) return null;
287 else return corrs.iterator().next();
290 public static Resource getSingleElementCorrespondendence(ReadGraph g, Resource element) throws DatabaseException {
291 Collection<Resource> corrs = getElementCorrespondendences(g, element);
292 if(corrs.size() != 1) throw new DatabaseException("Expected 1 element correspondence, got " + corrs.size());
293 else return corrs.iterator().next();
296 public static Resource createExperiment(WriteGraph graph, Resource model) throws DatabaseException {
298 Layer0 L0 = Layer0.getInstance(graph);
299 SimulationResource SIMU = SimulationResource.getInstance(graph);
300 Resource experiment = graph.newResource();
301 graph.claim(experiment, L0.InstanceOf, SIMU.Experiment);
302 graph.claimLiteral(experiment, L0.HasName, "Experiment");
303 graph.claim(model, L0.ConsistsOf, experiment);
308 public static Resource createModel(WriteGraph graph, Resource type) throws DatabaseException {
309 return createModel(graph, type, Simantics.getProjectResource(), null);
312 public static Resource createModel(WriteGraph graph, Resource type, String name) throws DatabaseException {
313 return createModel(graph, type, Simantics.getProjectResource(), name);
316 public static Resource createModel(WriteGraph graph, Resource type, final Resource target, String name) throws DatabaseException {
318 Layer0 L0 = Layer0.getInstance(graph);
319 SimulationResource SIMU = SimulationResource.getInstance(graph);
320 StructuralResource2 STR = StructuralResource2.getInstance(graph);
321 ModelingResources MOD = ModelingResources.getInstance(graph);
324 name = NameUtils.findFreshName(graph, "Model", target, L0.ConsistsOf, "%s%d");
326 final Resource model = graph.newResource();
327 graph.newClusterSet(model);
328 graph.claim(model, L0.InstanceOf, null, type);
329 graph.claimLiteral(model, L0.HasName, name);
331 graph.claim(target, L0.ConsistsOf, model);
333 Resource configurationType = graph.getPossibleObject(model, MOD.StructuralModel_HasConfigurationType);
334 if(configurationType == null) configurationType = STR.Composite;
336 Resource configuration = graph.newResource();
337 graph.claimLiteral(configuration, L0.HasName, "Configuration", Bindings.STRING);
338 graph.claim(configuration, L0.InstanceOf, null, configurationType);
339 graph.claim(model, L0.ConsistsOf, configuration);
340 graph.claim(model, SIMU.HasConfiguration, configuration);
342 Resource joinClusterSet = graph.newResource();
343 graph.newClusterSet(joinClusterSet);
344 graph.claim(joinClusterSet, L0.InstanceOf, L0.ClusterSet);
345 graph.claim(model, STR.HasJoinClusterSet, joinClusterSet);
347 linkOntologyDependenciesToModel(graph, model, target);
349 Resource ontology = graph.syncRequest(new PossibleIndexRoot(type));
350 if(ontology != null) {
351 graph.claim(model, L0.IsLinkedTo, ontology);
354 VirtualGraphSupport support = graph.getService(VirtualGraphSupport.class);
355 graph.asyncRequest(new WriteRequest(support.getWorkspacePersistent("activations")) {
358 public void perform(WriteGraph graph) throws DatabaseException {
359 Layer0X L0X = Layer0X.getInstance(graph);
360 Collection<Resource> actives = graph.syncRequest(new ActiveModels(target));
361 if(actives.isEmpty()) {
362 graph.claim(model, L0X.IsActivatedBy, target);
372 public static void linkOntologyDependenciesToModel(WriteGraph graph, Resource model, Resource target)
373 throws DatabaseException {
374 Layer0 L0 = Layer0.getInstance(graph);
375 ProjectResource PROJ = ProjectResource.getInstance(graph);
376 for(Resource dep : graph.getObjects(target, L0.IsLinkedTo)) {
377 if(graph.isInstanceOf(dep, PROJ.NamespaceRequirement)) {
378 for(Resource req : graph.getObjects(dep, PROJ.RequiresNamespace)) {
379 String uri = graph.getPossibleValue(req, Bindings.STRING);
381 Resource ns = graph.getResource(uri);
383 graph.claim(model, L0.IsLinkedTo, null, ns);
391 public static void addSCLMainToModel(WriteGraph graph, Resource model)
392 throws DatabaseException {
393 addSCLMainToModel(graph, model, "SCLMain", "include \"Simantics/All\"\n");
396 public static void addSCLMainToModel(WriteGraph graph, Resource model, String name, String contents)
397 throws DatabaseException {
398 Layer0 L0 = Layer0.getInstance(graph);
399 Resource sclmain = GraphUtils.create2(graph, L0.SCLModule, L0.PartOf, model, L0.HasName, name);
400 graph.claimLiteral(sclmain, L0.SCLModule_definition, contents, Bindings.STRING);
403 public static Resource createLocalLibrary(WriteGraph graph, Resource container, String name) throws DatabaseException {
404 Layer0 L0 = Layer0.getInstance(graph);
405 ModelingResources MOD = ModelingResources.getInstance(graph);
406 Resource library = graph.newResource();
407 graph.claim(library, L0.InstanceOf, null, L0.Library);
408 graph.addLiteral(library, L0.HasName, L0.NameOf, "Library", Bindings.STRING);
409 if (container != null) {
410 graph.claim(container, L0.ConsistsOf, L0.PartOf, library);
411 graph.claim(container, MOD.HasLocalLibrary, MOD.IsLocalLibraryOf, library);
416 public static void importModel(String fileName) {
418 Resource project = Simantics.getProject().get();
420 try (StreamingTransferableGraphFileReader importer = new StreamingTransferableGraphFileReader(new File(fileName))) {
421 TransferableGraphSource tg = importer.readTG();
423 final DefaultPasteImportAdvisor advisor = new DefaultPasteImportAdvisor(project) {
425 public void analyzeType(ReadGraph graph, Root root) throws DatabaseException {
428 public Resource analyzeRoot(ReadGraph graph, Root root) throws DatabaseException {
429 library = Simantics.getProjectResource();
430 String newName = newName(graph, library, root.name);
431 nameMappings.put(root.name, newName);
435 TransferableGraphs.importGraph1(Simantics.getSession(), tg, advisor);
437 } catch (MissingDependencyException e) {
439 final Set<String> missingURIs = e.getMissingURIs();
441 class ErrorMessageDialog extends MessageDialog {
443 public ErrorMessageDialog(Shell shell) {
445 "Unsatisfied dependencies", null,
446 "The following dependencies were missing. Please import the dependencies and try again.",
447 MessageDialog.ERROR, new String[] { "Continue" }, 0);
451 protected Control createCustomArea(Composite composite) {
452 GridLayoutFactory.fillDefaults().applyTo(composite);
454 org.eclipse.swt.widgets.List list = new org.eclipse.swt.widgets.List(composite, SWT.BORDER | SWT.READ_ONLY);
455 GridDataFactory.fillDefaults().grab(true, true).applyTo(list);
456 for(String s : missingURIs) list.add(s);
462 Display display = Display.getCurrent();
463 if(display != null) {
464 ErrorMessageDialog md = new ErrorMessageDialog(display.getActiveShell());
467 Display.getDefault().asyncExec(new Runnable() {
471 Shell shell = Display.getCurrent().getActiveShell();
472 ErrorMessageDialog md = new ErrorMessageDialog(shell);
480 } catch (Exception e) {
481 Logger.defaultLogError(e);
486 public static void primeVirtualGraphs() {
487 VirtualGraphSupport support = Simantics.getSession().getService(VirtualGraphSupport.class);
488 support.getWorkspacePersistent("activations");
489 support.getWorkspacePersistent("experiments");
490 support.getWorkspacePersistent("issues");
491 support.getWorkspacePersistent("preferences");
494 public static Resource createProfileEntry(WriteGraph graph, String name, Resource style, Resource group) throws DatabaseException {
496 Layer0 L0 = Layer0.getInstance(graph);
497 DiagramResource DIA = DiagramResource.getInstance(graph);
499 Resource entry = graph.newResource();
500 graph.claim(entry, L0.InstanceOf, null, DIA.GroupStyleProfileEntry);
501 graph.claimLiteral(entry, L0.HasName, name);
502 graph.claimLiteral(entry, L0.HasLabel, name);
503 graph.claim(entry, DIA.ProfileEntry_HasStyle, style);
504 graph.claim(entry, DIA.ProfileEntry_HasGroup, group);
510 public static Resource createProfile(WriteGraph graph, String profileName, Resource... entries) throws DatabaseException {
512 Layer0 L0 = Layer0.getInstance(graph);
513 DiagramResource DIA = DiagramResource.getInstance(graph);
515 Resource list = ListUtils.create(graph, DIA.Profile, entries);
517 Resource profile = graph.newResource();
518 graph.claim(profile, L0.InstanceOf, null, DIA.Profile);
519 graph.claimLiteral(profile, L0.HasName, profileName);
520 graph.claim(profile, DIA.HasEntries, null, list);
526 public static Resource createProfile(WriteGraph graph, String profileName, Collection<Resource> entries) throws DatabaseException {
527 return createProfile(graph, profileName, entries.toArray(new Resource[entries.size()]));
530 public static Resource createToplevelProfile(WriteGraph graph, Resource model, String name, Resource ... profiles) throws DatabaseException {
532 Resource work = createProfile(graph, name, profiles);
534 Layer0 L0 = Layer0.getInstance(graph);
535 DiagramResource DIA = DiagramResource.getInstance(graph);
537 graph.deny(model, DIA.HasActiveProfile);
538 graph.claim(model, DIA.HasActiveProfile, work);
539 graph.claim(model, L0.ConsistsOf, L0.PartOf, work);
545 public static Resource createToplevelProfile(WriteGraph graph, Resource model, String name, Collection<Resource> profiles) throws DatabaseException {
546 return createToplevelProfile(graph, model, name, profiles.toArray(new Resource[profiles.size()]));
549 public static void activateProfileEntries(WriteGraph graph, final Resource profile, final Resource ... entries) {
551 VirtualGraphSupport support = graph.getService(VirtualGraphSupport.class);
552 graph.asyncRequest(new WriteRequest(support.getWorkspacePersistent("profiles")) {
555 public void perform(WriteGraph graph) throws DatabaseException {
556 SimulationResource SIMU = SimulationResource.getInstance(graph);
557 for(Resource entry : entries)
558 graph.claim(profile, SIMU.IsActive, entry);
565 public static void activateProfileEntries(WriteGraph graph, Resource profile, Collection<Resource> entries) {
566 activateProfileEntries(graph, profile, entries.toArray(new Resource[entries.size()]));
569 public static void toggleProfileGroup(WriteGraph graph, Resource runtimeProfile, String groupName, boolean enabled) throws DatabaseException {
570 Layer0 L0 = Layer0.getInstance(graph);
571 for (Resource group : ProfileUtils.getProfileChildren(graph, runtimeProfile)) {
572 String name = graph.getRelatedValue2(group, L0.HasName);
573 if (name.equals(groupName)) {
574 toggleProfileGroup(graph, runtimeProfile, group, enabled);
580 public static void toggleProfileGroup(WriteGraph graph, Resource runtimeProfile, Resource group, boolean enabled) throws DatabaseException {
581 DiagramResource DIA = DiagramResource.getInstance(graph);
583 if(graph.isInstanceOf(group, DIA.Profile)) {
585 for(Resource child : ProfileUtils.getProfileChildren(graph, group)) {
586 toggleProfileGroup(graph, runtimeProfile, child, enabled);
589 } else if(graph.isInstanceOf(group, DIA.ProfileEntry)) {
592 graph.claim(runtimeProfile, SimulationResource.getInstance(graph).IsActive, null, group);
594 graph.denyStatement(runtimeProfile, SimulationResource.getInstance(graph).IsActive, group);
600 public static void untrackDependencies() {
601 untrackDependencies(Simantics.getSession());
604 public static void untrackDependencies(RequestProcessor processor) {
607 processor.syncRequest(new ReadRequest() {
610 public void run(ReadGraph graph) throws DatabaseException {
611 Layer0X L0X = Layer0X.getInstance(graph);
612 GenericRelationIndex index = graph.adapt(L0X.DependenciesRelation, GenericRelationIndex.class);
613 index.untrack(graph.getSession(), graph.getRootLibrary());
617 } catch (DatabaseException e) {
618 Logger.defaultLogError(e);
623 public static void trackDependencies() {
624 trackDependencies(Simantics.getSession());
627 public static void trackDependencies(RequestProcessor processor) {
630 processor.syncRequest(new ReadRequest() {
633 public void run(ReadGraph graph) throws DatabaseException {
634 Layer0X L0X = Layer0X.getInstance(graph);
635 GenericRelationIndex index = graph.adapt(L0X.DependenciesRelation, GenericRelationIndex.class);
636 index.trackAndIndex(graph.getSession(), graph.getRootLibrary());
640 } catch (DatabaseException e) {
641 Logger.defaultLogError(e);
646 public static void trackOntologicalRequirements() {
647 Session session = Simantics.getSession();
648 GraphChangeListenerSupport changeListenerSupport = session.getService(GraphChangeListenerSupport.class);
649 changeListenerSupport.addMetadataListener( OntologicalRequirementListener.getInstance() );
652 public static void untrackOntologicalRequirements() {
653 Session session = Simantics.getSession();
654 GraphChangeListenerSupport changeListenerSupport = session.getService(GraphChangeListenerSupport.class);
655 changeListenerSupport.removeMetadataListener( OntologicalRequirementListener.getInstance() );
658 public static class OntologicalRequirementListener extends GenericChangeListener<DependencyChangesRequest, DependencyChanges> {
660 private static OntologicalRequirementListener INSTANCE;
662 public static OntologicalRequirementListener getInstance() {
663 if(INSTANCE == null) {
664 INSTANCE = new OntologicalRequirementListener();
669 private OntologicalRequirementListener() {
672 private OntologicalRequirementTracker changeInformationUpdater = new OntologicalRequirementTracker();
675 public boolean preEventRequest() {
676 return !Indexing.isDependenciesIndexingDisabled();
680 public void onEvent(ReadGraph graph, MetadataI metadata, DependencyChanges event) throws DatabaseException {
681 changeInformationUpdater.update(graph, metadata, event);
686 public static void removeIndex(WriteGraph graph, Resource model) throws DatabaseException {
687 Layer0X L0X = Layer0X.getInstance(graph);
688 IndexedRelations ir = graph.getService(IndexedRelations.class);
689 // Deletes index files
690 ir.reset(null, graph, L0X.DependenciesRelation, model);
693 public static void resetIssueSources(WriteGraph graph, Resource model) throws DatabaseException {
694 Layer0 L0 = Layer0.getInstance(graph);
695 IssueResource ISSUE = IssueResource.getInstance(graph);
696 for(Resource source : graph.sync(new ObjectsWithType(model, L0.ConsistsOf, ISSUE.ContinuousIssueSource))) {
697 IssueSourceUtils.update(graph, source);
701 public static void copyAnnotationTypes(WriteGraph graph, Resource sourceModel, Resource targetModel) throws DatabaseException {
703 Layer0 L0 = Layer0.getInstance(graph);
704 AnnotationResource ANNO = AnnotationResource.getInstance(graph);
706 Instances query = graph.adapt(ANNO.AnnotationType, Instances.class);
708 Resource library = graph.getPossibleObject(targetModel, ANNO.HasAnnotationTypeRoot);
710 if(library == null) {
711 library = graph.newResource();
712 graph.claim(library, L0.InstanceOf, null, ANNO.AnnotationTypeLibrary);
713 graph.claimLiteral(library, L0.HasName, L0.NameOf, L0.String, "Annotation types", Bindings.STRING);
714 graph.claim(library, L0.PartOf, L0.ConsistsOf, targetModel);
715 graph.claim(targetModel, ANNO.HasAnnotationTypeRoot, library);
718 for(Resource type : query.find(graph, sourceModel)) {
719 String name = graph.getRelatedValue(type, L0.HasName);
720 Resource existing = Layer0Utils.getPossibleChild(graph, library, name);
721 if(existing != null) {
722 RemoverUtil.remove(graph, existing);
724 Layer0Utils.copyTo(graph, library, type);
729 public static void deleteIndex(WriteGraph graph, Resource model) throws DatabaseException {
730 Layer0X L0X = Layer0X.getInstance(graph);
731 IndexedRelations ir = graph.getService(IndexedRelations.class);
732 // Deletes index files
733 ir.reset(null, graph, L0X.DependenciesRelation, model);
736 public static void disableDependencies(WriteGraph graph, Resource dummy) {
737 Layer0Utils.setDependenciesIndexingDisabled(graph, true);
740 public static void releaseMemory(WriteGraph graph) {
742 QueryControl qc = graph.getService(QueryControl.class);
743 ClusterControl cc = graph.getService(ClusterControl.class);
749 public static List<Resource> filterByIndexRoot(ReadGraph graph, Resource indexRoot, List<Resource> resources) throws DatabaseException {
750 ArrayList<Resource> result = new ArrayList<Resource>(resources.size());
751 for (Resource r : resources) {
752 Resource root = graph.syncRequest(new PossibleIndexRoot(r));
753 if (indexRoot.equals(root))
760 public static List<Resource> searchByTypeShallow(ReadGraph graph, Resource model, Resource type) throws DatabaseException {
761 return QueryIndexUtils.searchByTypeShallow(graph, model, type);
765 public static List<Resource> searchByType(ReadGraph graph, Resource model, Resource type) throws DatabaseException {
766 return QueryIndexUtils.searchByType(graph, model, type);
770 public static List<Resource> searchByGUID(ReadGraph graph, Resource indexRoot, GUID guid) throws DatabaseException {
771 return QueryIndexUtils.searchByGUID(graph, indexRoot, guid);
775 public static List<Resource> searchByGUID(ReadGraph graph, Resource indexRoot, String indexString) throws DatabaseException {
776 return QueryIndexUtils.searchByGUID(graph, indexRoot, indexString);
780 public static List<Resource> searchByQueryShallow(ReadGraph graph, Resource model, String query) throws DatabaseException {
781 return QueryIndexUtils.searchByQueryShallow(graph, model, query);
785 public static List<Resource> searchByQuery(ReadGraph graph, Resource model, String query) throws DatabaseException {
786 return QueryIndexUtils.searchByQuery(graph, model, query);
790 public static List<Resource> searchByTypeAndFilter(ReadGraph graph, Resource model, Resource type, Function1<Resource,Boolean> filter) throws DatabaseException {
791 return QueryIndexUtils.searchByTypeAndFilter(graph, model, type, filter);
795 public static List<Triple<Resource, Resource, String>> getIndexEntries(ReadGraph graph, Resource model, String filter) throws DatabaseException {
796 return QueryIndexUtils.getIndexEntries(graph, model, filter);
800 public static String listIndexEntries(ReadGraph graph, Resource model, String filter) throws DatabaseException {
801 return QueryIndexUtils.listIndexEntries(graph, model, filter);
805 public static List<Resource> searchByTypeAndName(ReadGraph graph, Resource model, Resource type, String name) throws DatabaseException {
806 return QueryIndexUtils.searchByTypeAndName(graph, model, type, name);
810 public static List<Resource> searchByTypeAndNameShallow(ReadGraph graph, Resource model, Resource type, String name) throws DatabaseException {
811 return QueryIndexUtils.searchByTypeAndNameShallow(graph, model, type, name);
816 * database write access
817 * @param sourceContainer
818 * the source container to look for annotationProperty from to be
819 * used as the copy source
820 * @param targetContainer
821 * the target container for the copied annotationProperty
823 * @param annotationProperty
824 * the annotation property relation
825 * @return created copy of the original annotation or <code>null</code> if
826 * there was nothing to copy
827 * @throws DatabaseException
829 public static Resource copyPossibleAnnotation(WriteGraph graph, Resource sourceContainer, Resource targetContainer, Resource annotationProperty) throws DatabaseException {
830 return copyPossibleAnnotation2(graph, sourceContainer, targetContainer, annotationProperty, null);
833 public static List<String> getPossibleNamePath(ReadGraph graph, Resource resource) throws DatabaseException {
834 return getPossibleNamePath(graph, resource, null);
837 private static List<String> getPossibleNamePath(ReadGraph graph, Resource resource, List<String> result) throws DatabaseException {
839 Layer0 L0 = Layer0.getInstance(graph);
840 String name = graph.getPossibleRelatedValue(resource, L0.HasName, Bindings.STRING);
841 if(name == null) return null;
843 if(result == null) result = new ArrayList<String>();
845 SimulationResource SIMU = SimulationResource.getInstance(graph);
846 if(graph.isInstanceOf(resource, SIMU.Model)) return result;
848 Resource parent = graph.getPossibleObject(resource, L0.PartOf);
850 getPossibleNamePath(graph, parent, result);
861 public static Resource claimLibraryPath(WriteGraph graph, Resource resource, List<String> path) throws DatabaseException {
862 Layer0 L0 = Layer0.getInstance(graph);
863 for(int i=0;i<path.size()-1;i++) {
864 String p = path.get(i);
865 Resource child = Layer0Utils.getPossibleChild(graph, resource, p);
867 child = graph.newResource();
868 graph.claim(child, L0.InstanceOf, L0.Library);
869 graph.addLiteral(child, L0.HasName, L0.NameOf, L0.String, p, Bindings.STRING);
870 graph.claim(resource, L0.ConsistsOf, L0.PartOf, child);
879 * database write access
880 * @param sourceContainer
881 * the source container to look for annotationProperty from to be
882 * used as the copy source
883 * @param targetContainer
884 * the target container for the copied annotationProperty
886 * @param annotationProperty
887 * the annotation property relation
888 * @param annotationProperty
889 * the 2nd level annotation property relation or
890 * <code>null</code> if no 2nd level annotation exists
891 * @return created copy of the original annotation or <code>null</code> if
892 * there was nothing to copy
893 * @throws DatabaseException
895 public static Resource copyPossibleAnnotation2(WriteGraph graph,
896 Resource sourceContainer, Resource targetContainer,
897 Resource annotationProperty, Resource entryType) throws DatabaseException {
899 // Delete existing target value first
900 Layer0 L0 = Layer0.getInstance(graph);
901 Resource targetValue = graph.getPossibleObject(targetContainer, annotationProperty);
902 if (targetValue != null) {
903 if(!graph.hasStatement(targetValue, L0.PartOf))
904 RemoverUtil.remove(graph, targetValue);
905 graph.deny(targetContainer, annotationProperty);
908 Resource sourceValue = graph.getPossibleObject(sourceContainer, annotationProperty);
909 if (sourceValue == null)
912 List<String> sourceValuePath = getPossibleNamePath(graph, sourceValue);
913 if(sourceValuePath != null) {
914 Resource targetModel = graph.sync(new PossibleModel(targetContainer));
915 if(targetModel == null) throw new DatabaseException("No target model found for " + targetContainer);
916 Resource library = claimLibraryPath(graph, targetModel, sourceValuePath);
917 Resource existing = Layer0Utils.getPossibleChild(graph, library, sourceValuePath.get(sourceValuePath.size()-1));
918 if(existing == null) {
919 existing = doCopyPossibleAnnotation2(graph, sourceContainer, targetContainer, annotationProperty, entryType);
920 graph.claim(library, L0.ConsistsOf, L0.PartOf, existing);
922 graph.claim(targetContainer, annotationProperty, existing);
925 return doCopyPossibleAnnotation2(graph, sourceContainer, targetContainer, annotationProperty, entryType);
930 private static Resource doCopyPossibleAnnotation2(WriteGraph graph,
931 Resource sourceContainer, Resource targetContainer,
932 Resource annotationProperty, Resource entryType) throws DatabaseException {
934 Resource sourceValue = graph.getPossibleObject(sourceContainer, annotationProperty);
935 if (sourceValue == null)
938 // Copy 1st level annotation
939 Resource targetValue = createAnnotation(graph, targetContainer, annotationProperty, sourceValue);
941 // Copy possible 2nd level annotations and attach to 1st if entry
942 // property is defined.
943 Layer0 L0 = Layer0.getInstance(graph);
944 if (entryType != null) {
946 AnnotationResource ANNO = AnnotationResource.getInstance(graph);
947 for (Resource entry : graph.getObjects(sourceValue, ANNO.Annotation_HasEntry)) {
949 String name = graph.getRelatedValue(entry, L0.HasName, Bindings.STRING);
951 List<String> entryPath = getPossibleNamePath(graph, entry);
952 if(entryPath != null) {
953 Resource targetModel = graph.sync(new PossibleModel(targetContainer));
954 if(targetModel == null) throw new DatabaseException("No target model found for " + targetContainer);
955 Resource library = claimLibraryPath(graph, targetModel, entryPath);
956 Resource existing = Layer0Utils.getPossibleChild(graph, library, entryPath.get(entryPath.size()-1));
957 if(existing == null) {
958 existing = createTypedAnnotation(graph, null, null, entry, entryType, name);
959 graph.claim(library, L0.ConsistsOf, L0.PartOf, existing);
961 graph.claim(targetValue, ANNO.Annotation_HasEntry, existing);
963 Resource result = createTypedAnnotation(graph, null, null, entry, entryType, name);
964 graph.claim(targetValue, ANNO.Annotation_HasEntry, result);
976 * database write access
978 * the container resource to attach the new annotation to
980 * the annotation property relation. The type of the created
981 * annotation is decided from this property relation's range
982 * @param sourceAnnotation
983 * the annotation to copy data from or <code>null</code> if
984 * nothing shall be copied
985 * @return the newly created annotation resource or <code>null</code> if the
986 * annotation property relation didn't have a single range type
987 * @throws DatabaseException
989 public static Resource createAnnotation(WriteGraph graph, Resource container, Resource property, Resource sourceAnnotation) throws DatabaseException {
990 return createAnnotation(graph, container, property, sourceAnnotation, null);
995 * database write access
997 * the container resource to attach the new annotation to
999 * the annotation property relation. The type of the created
1000 * annotation is decided from this property relation's range
1001 * @param sourceAnnotation
1002 * the annotation to copy data from or <code>null</code> if
1003 * nothing shall be copied
1005 * name for newly created annotation or <code>null</code> to copy
1006 * name from source if available
1007 * @return the newly created annotation resource or <code>null</code> if the
1008 * annotation property relation didn't have a single range type
1009 * @throws DatabaseException
1011 public static Resource createAnnotation(WriteGraph graph, Resource container, Resource property, Resource sourceAnnotation, String name) throws DatabaseException {
1013 Layer0 L0 = Layer0.getInstance(graph);
1014 Resource annotationType = graph.getSingleObject(property, L0.HasRange);
1015 if (annotationType == null)
1018 return createTypedAnnotation(graph, container, property, sourceAnnotation, annotationType, name);
1024 * database write access
1026 * the container resource to attach the new annotation to
1028 * the annotation property relation
1029 * @param sourceAnnotation
1030 * the annotation to copy data from or <code>null</code> if
1031 * nothing shall be copied
1032 * @param annotationType
1033 * the type of the new annotation
1034 * @return the newly created annotation resource
1035 * @throws DatabaseException
1037 public static Resource createTypedAnnotation(WriteGraph graph, Resource container, Resource property, Resource sourceAnnotation, Resource annotationType) throws DatabaseException {
1038 return createTypedAnnotation(graph, container, property, sourceAnnotation, annotationType, null);
1043 * database write access
1045 * the container resource to attach the new annotation to
1047 * the annotation property relation
1048 * @param sourceAnnotation
1049 * the annotation to copy data from or <code>null</code> if
1050 * nothing shall be copied
1051 * @param annotationType
1052 * the type of the new annotation
1054 * name for newly created annotation or <code>null</code> to copy
1055 * name from source if available
1056 * @return the newly created annotation resource
1057 * @throws DatabaseException
1059 public static Resource createTypedAnnotation(WriteGraph graph, Resource container, Resource property, Resource sourceAnnotation, Resource annotationType, String name) throws DatabaseException {
1061 Layer0 L0 = Layer0.getInstance(graph);
1063 Resource anno = graph.newResource();
1065 graph.claim(anno, L0.InstanceOf, null, annotationType);
1068 graph.addLiteral(anno, L0.HasName, L0.NameOf, L0.String, name, Bindings.STRING);
1070 if (sourceAnnotation != null) {
1073 String sourceName = graph.getPossibleRelatedValue(sourceAnnotation, L0.HasName, Bindings.STRING);
1074 if(sourceName != null) graph.addLiteral(anno, L0.HasName, L0.NameOf, L0.String, sourceName, Bindings.STRING);
1077 Resource sourceType = graph.getSingleType(sourceAnnotation);
1078 List<AnnotationMap> am = getAnnotationMap(graph, annotationType, sourceType);
1079 for (AnnotationMap a : am) {
1080 Resource object = graph.getSingleObject(sourceAnnotation, a.sourcePredicate);
1081 Collection<Resource> objectTypes = graph.getTypes(object);
1082 if (objectTypes.contains(L0.Literal)) {
1083 Object value = graph.getValue(object, a.defaultValueBinding);
1084 if (!ObjectUtils.objectEquals(value, a.defaultValue)) {
1085 graph.addLiteral(anno, a.annotationPredicate, a.annotationPredicateInverse, a.defaultValueType, value, a.defaultValueBinding);
1091 if (container != null && property != null) {
1092 graph.claim(container, property, anno);
1099 private static class AnnotationMap {
1101 final public Resource sourcePredicate;
1102 final public Resource sourcePredicateInverse;
1104 final public Resource annotationPredicate;
1105 final public Resource annotationPredicateInverse;
1107 final public Resource defaultValueType;
1108 final public Object defaultValue;
1109 final public Binding defaultValueBinding;
1111 public AnnotationMap(Resource sp, Resource spi, Resource tp, Resource tpi, Resource defaultValueType, Object defaultValue, Binding defaultValueBinding) {
1112 sourcePredicate = sp;
1113 sourcePredicateInverse = spi;
1114 annotationPredicate = tp;
1115 annotationPredicateInverse = tpi;
1116 this.defaultValueType = defaultValueType;
1117 this.defaultValue = defaultValue;
1118 this.defaultValueBinding = defaultValueBinding;
1123 public static List<AnnotationMap> getAnnotationMap(ReadGraph graph, Resource annotationType, Resource sourceType) throws DatabaseException {
1124 return graph.syncRequest(new AnnotationMapRequest(annotationType, sourceType), TransientCacheListener.<List<AnnotationMap>>instance());
1127 static class AnnotationMapRequest extends ResourceRead2<List<AnnotationMap>> {
1129 public AnnotationMapRequest(Resource annotationType, Resource sourceType) {
1130 super(annotationType, sourceType);
1134 public List<AnnotationMap> perform(ReadGraph graph) throws DatabaseException {
1136 Layer0 L0 = Layer0.getInstance(graph);
1138 ArrayList<AnnotationMap> result = new ArrayList<AnnotationMap>();
1140 Map<String, Resource> annotationPredicates = new HashMap<String, Resource>();
1141 for(Resource predicate : graph.getObjects(resource, L0.DomainOf)) {
1142 String name = graph.getRelatedValue(predicate, L0.HasName, Bindings.STRING);
1143 annotationPredicates.put(name, predicate);
1145 Map<String, Resource> sourcePredicates = new HashMap<String, Resource>();
1146 for(Resource predicate : graph.getObjects(resource2, L0.DomainOf)) {
1147 String name = graph.getRelatedValue(predicate, L0.HasName, Bindings.STRING);
1148 sourcePredicates.put(name, predicate);
1151 for(String key : sourcePredicates.keySet()) {
1152 Resource sourcePredicate = sourcePredicates.get(key);
1153 Resource anno = annotationPredicates.get(key);
1154 if(sourcePredicate != null && anno != null) {
1155 Resource defaultValueType = graph.getSingleObject(anno, L0.HasRange);
1156 Binding defaultValueBinding = null;
1157 Object defaultValue = null;
1158 Resource assertion = graph.getPossibleObject(anno, L0.HasPredicateInverse);
1159 if (assertion != null) {
1160 Resource object = graph.getPossibleObject(assertion, L0.HasObject);
1161 if (object != null) {
1162 if(graph.isInstanceOf(object, L0.Literal)) {
1163 Datatype dt = graph.getDataType(object);
1164 defaultValueBinding = Bindings.getBeanBinding(dt);
1165 defaultValue = graph.getPossibleValue(object);
1169 result.add(new AnnotationMap(
1170 sourcePredicate, graph.getInverse(sourcePredicate),
1171 anno, graph.getInverse(anno),
1172 defaultValueType, defaultValue, defaultValueBinding));
1182 public static final String DRAWING_TEMPLATE_FORMAT = "drawingTemplate";
1183 public static final String DRAWING_TEMPLATE_FORMAT_V1 = DRAWING_TEMPLATE_FORMAT + ":1";
1184 public static final String DRAWING_TEMPLATE_FORMAT_V2 = DRAWING_TEMPLATE_FORMAT + ":2";
1186 public static Resource importDrawingTemplate(final Resource model, final File file) throws IOException, SerializationException, DatabaseException, TransferableGraphException {
1190 final Resource library = Simantics.sync(new WriteResultRequest<Resource>() {
1193 public Resource perform(WriteGraph graph) throws DatabaseException {
1195 Layer0 L0 = Layer0.getInstance(graph);
1196 Template2dResource TEMPLATE = Template2dResource.getInstance(graph);
1197 Resource root = graph.getPossibleObject(model, TEMPLATE.HasDrawingTemplateRoot);
1199 Template2dResource TEMPLATE2D = Template2dResource.getInstance(graph);
1200 root = graph.newResource();
1201 graph.claim(root, L0.InstanceOf, null, TEMPLATE2D.DrawingTemplateLibrary);
1202 graph.claim(root, L0.InstanceOf, null, TEMPLATE2D.DrawingTemplateLibraryUI);
1203 graph.claimLiteral(root, L0.HasName, L0.NameOf, L0.String, "Diagram Templates", Bindings.STRING);
1204 graph.claim(root, L0.PartOf, L0.ConsistsOf, model);
1205 graph.claim(model, TEMPLATE2D.HasDrawingTemplateRoot, root);
1208 String name = new Path(file.getAbsolutePath()).removeFileExtension().lastSegment();
1210 Resource existing = Layer0Utils.getPossibleChild(graph, root, name);
1211 if(existing != null)
1212 graph.deny(root, L0.ConsistsOf, existing);
1221 final DefaultPasteImportAdvisor advisor = new DefaultPasteImportAdvisor(library);
1224 HashMap<String, FormatHandler<Object>> handlers = new HashMap<String, FormatHandler<Object>>();
1225 FormatHandler<Object> handler = new FormatHandler<Object>() {
1227 public Binding getBinding() {
1228 return TransferableGraph1.BINDING;
1232 public Object process(DataContainer container) throws Exception {
1233 TransferableGraphs.importGraph1(Simantics.getSession(), (TransferableGraph1)container.content.getValue(),
1238 handlers.put(DRAWING_TEMPLATE_FORMAT_V1, handler);
1239 handlers.put(DRAWING_TEMPLATE_FORMAT_V2, handler);
1241 DataContainers.readFile(file, handlers);
1242 } catch(DataFormatException e) {
1243 throw new IOException(e);
1244 } catch(IOException e) {
1246 } catch(Exception e) {
1247 if(e instanceof RuntimeException)
1248 throw (RuntimeException)e;
1250 throw new RuntimeException(e);
1253 } catch(IOException e) {
1256 return advisor.getRoot();
1258 } catch (Throwable t) {
1259 Logger.defaultLogError("Unexpected exception while importing diagram template.", t);
1267 public static Collection<Variable> getMappedVariables(ReadGraph graph, Variable source) throws DatabaseException {
1269 ArrayList<Variable> result = new ArrayList<Variable>();
1270 Resource represents = source.getPossibleRepresents(graph);
1271 if(represents == null) return Collections.emptyList();
1272 ModelingResources MOD = ModelingResources.getInstance(graph);
1273 for(Resource r : getElementCorrespondendences(graph, represents)) {
1274 result.add(Variables.getVariable(graph, r));
1276 for(Resource r : graph.getObjects(represents, MOD.ComponentToElement)) {
1277 result.add(Variables.getVariable(graph, r));
1279 for(Resource r : graph.getObjects(represents, MOD.DiagramToComposite)) {
1280 result.add(Variables.getVariable(graph, r));
1282 for(Resource r : graph.getObjects(represents, MOD.CompositeToDiagram)) {
1283 result.add(Variables.getVariable(graph, r));
1289 public static Resource getPossibleModel(ReadGraph graph, Resource resource) throws DatabaseException {
1291 PossibleModel pm = new PossibleModel(resource);
1292 Resource model = pm.perform(graph);
1296 public static Resource possibleIndexRoot(ReadGraph graph, Resource resource) throws DatabaseException {
1297 return graph.syncRequest(new PossibleIndexRoot(resource));
1300 public static Object getMonitorValue(StructuralComponent _variable, ReadGraph graph, String path) throws DatabaseException {
1301 Variable variable = ((VariableStructuralContext)_variable).variable;
1302 Variable var = variable.browse(graph, path);
1303 return var.getValue(graph);
1306 public static void createSharedOntologyWithUI(ReadGraph graph, Variable variable, Resource baseType) throws DatabaseException {
1307 createSharedOntologyWithUI(graph, baseType);
1310 public static void createSharedOntologyWithUI(ReadGraph graph, Resource baseType) throws DatabaseException {
1312 // Resource indexRoot_ = variable.getPossibleRepresents(graph);
1313 // if(indexRoot_ == null) return;
1315 final Map<Resource, Pair<String,ImageDescriptor>> map = new HashMap<Resource, Pair<String,ImageDescriptor>>();
1317 Layer0 L0 = Layer0.getInstance(graph);
1318 SimulationResource SIMU = SimulationResource.getInstance(graph);
1319 Instances query = graph.adapt(L0.IndexRootType, Instances.class);
1320 for(Resource ontology : Layer0Utils.listOntologies(graph)) {
1321 for(Resource type : query.find(graph, ontology)) {
1322 if(graph.isInheritedFrom(type, SIMU.Model)) continue;
1323 if(graph.hasStatement(type, L0.Abstract)) continue;
1324 if(!graph.isInheritedFrom(type, baseType)) continue;
1325 String name = graph.getPossibleRelatedValue(type, L0.HasLabel, Bindings.STRING);
1326 if(name == null) name = graph.getRelatedValue(type, L0.HasName, Bindings.STRING);
1327 map.put(type, new Pair<String,ImageDescriptor>(name, null));
1331 Display.getDefault().asyncExec(new Runnable() {
1334 Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();
1335 CreateSharedOntologyDialog page = new CreateSharedOntologyDialog(shell, map, "Select type and name of new shared library");
1336 if (page.open() == Window.OK) {
1337 Object[] result = page.getResult();
1338 if (result != null && result.length == 1) {
1339 final Resource res = (Resource)result[0];
1340 final String name = "http://" + page.getName();
1341 Simantics.getSession().asyncRequest(new WriteRequest() {
1344 public void perform(WriteGraph graph) throws DatabaseException {
1345 graph.markUndoPoint();
1346 Resource target = Simantics.applySCL("Simantics/SharedOntologies", "createSharedOntology", graph, name+"@A", res);
1348 ProjectResource PROJ = ProjectResource.getInstance(graph);
1349 Layer0 L0 = Layer0.getInstance(graph);
1350 for(Resource dep : graph.getObjects(Simantics.getProjectResource(), L0.IsLinkedTo)) {
1351 if(graph.isInstanceOf(dep, PROJ.NamespaceRequirement)) {
1352 for(Resource req : graph.getObjects(dep, PROJ.RequiresNamespace)) {
1353 String uri = graph.getPossibleValue(req, Bindings.STRING);
1355 Resource ns = graph.getResource(uri);
1357 graph.claim(target, L0.IsLinkedTo, null, ns);
1374 public static void unlinkSharedOntologyWithUI(ReadGraph graph, Variable variable, final List<Resource> libraries) throws DatabaseException {
1376 final Resource indexRoot = variable.getPossibleRepresents(graph);
1377 if(indexRoot == null) return;
1379 StructuralResource2 STR = StructuralResource2.getInstance(graph);
1381 final List<String> instances = new ArrayList<String>();
1383 DiagramResource DIA = DiagramResource.getInstance(graph);
1385 for(Resource library : libraries) {
1386 for(Resource type : ModelingUtils.searchByTypeShallow(graph, library, STR.ComponentType)) {
1387 for(Resource instance : ModelingUtils.searchByTypeShallow(graph, indexRoot, type)) {
1389 if(graph.isInstanceOf(instance, DIA.Element)) continue;
1390 String name = Versions.getStandardPathNameString(graph, instance);
1391 instances.add(name);
1396 if(instances.isEmpty()) {
1397 graph.getSession().asyncRequest(new WriteRequest() {
1400 public void perform(WriteGraph graph) throws DatabaseException {
1401 Layer0 L0 = Layer0.getInstance(graph);
1402 for(Resource library : libraries)
1403 graph.deny(indexRoot, L0.IsLinkedTo, library);
1410 PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
1414 if (!PlatformUI.isWorkbenchRunning())
1417 Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();
1418 ListDialog<String> dialog = new ListDialog<String>(
1421 "Cannot unlink selected libraries",
1422 "Libraries cannot be unlinked since the following instances are referring to them.") {
1424 protected void createButtonsForButtonBar(Composite parent) {
1425 createButton(parent, IDialogConstants.OK_ID, IDialogConstants.OK_LABEL,true);
1429 int result = dialog.open();
1430 if (result != Dialog.OK)
1438 public static MigratedImportResult importSharedOntologyWithResult(String fileName) throws Exception {
1440 DataContainer dc = DataContainers.readFile(new File(fileName));
1441 TransferableGraph1 tg = (TransferableGraph1)dc.content.getValue(TransferableGraph1.BINDING);
1442 Variant draftStatus = dc.metadata.get(DraftStatusBean.EXTENSION_KEY);
1443 return MigrationUtils.importSharedOntology(Simantics.getSession(), tg, draftStatus == null);
1444 } catch (Exception e) {
1445 Logger.defaultLogError(e);
1450 public static void importSharedOntology(String fileName) throws Exception {
1451 importSharedOntologyWithResult(fileName);
1454 public static List<Resource> importSharedOntology2(String fileName) throws Exception {
1455 MigratedImportResult result = importSharedOntologyWithResult(fileName);
1456 return new ArrayList<Resource>(result.roots);
1459 public static void importSharedOntologyWithUI(ReadGraph graph, final Variable variable) throws DatabaseException {
1461 Display.getDefault().asyncExec(new Runnable() {
1465 IStructuredSelection sel = new StructuredSelection(variable);
1466 openWizard(Display.getCurrent(), sel, "org.simantics.modeling.ui.sharedOntologyImportWizard");
1473 public static class LibraryInfo implements Comparable<LibraryInfo> {
1474 public NamedResource library;
1475 public DraftStatusBean draft;
1476 public LibraryInfo(String name, Resource r, DraftStatusBean draft) {
1477 library = new NamedResource(name, r);
1481 public int compareTo(LibraryInfo o) {
1482 return library.compareTo(o.library);
1485 public int hashCode() {
1486 return library.hashCode();
1489 public boolean equals(Object object) {
1492 else if (object == null)
1494 else if (!(object instanceof LibraryInfo))
1496 LibraryInfo info = (LibraryInfo)object;
1497 return info.library.equals(library);
1502 public static void exportSharedOntologyWithUI(final Resource sharedOntology) {
1504 Display.getDefault().asyncExec(new Runnable() {
1508 HintContext hc = new HintContext();
1509 hc.setHint(SelectionHints.KEY_MAIN, sharedOntology);
1510 IStructuredSelection sel = new StructuredSelection(hc);
1511 openWizard(Display.getCurrent(), sel, "org.simantics.modeling.ui.sharedOntologyExportWizard");
1518 public static TransferableGraph1 exportSharedOntology(IProgressMonitor monitor, RequestProcessor processor, File location, String format, int version, final LibraryInfo info) throws DatabaseException, IOException {
1519 SubMonitor mon = SubMonitor.convert(monitor, "Exporting shared library", 100);
1521 // TODO: figure out a way to make the TG go directly into a file
1522 // instead of having it all in memory at once.
1524 SimanticsClipboard clipboard = processor.syncRequest((ReadGraph graph) -> {
1525 CopyHandler ch = graph.adapt(info.library.getResource(), CopyHandler.class);
1526 SimanticsClipboardImpl result = new SimanticsClipboardImpl();
1527 ch.copyToClipboard(graph, result, mon.split(5));
1531 TreeMap<String,Variant> metadata = getExportMetadata();
1532 DraftStatusBean draft = info.draft;
1534 metadata.put(DraftStatusBean.EXTENSION_KEY, new Variant(DraftStatusBean.BINDING ,draft));
1537 for (Set<Representation> object : clipboard.getContents()) {
1538 mon.subTask("Constructing exported material");
1539 TransferableGraph1 tg = ClipboardUtils.accept(processor, object, SimanticsKeys.KEY_TRANSFERABLE_GRAPH);
1542 Variant edb = tg.extensions.get(ExternalDownloadBean.EXTENSION_KEY);
1544 metadata.put(ExternalDownloadBean.EXTENSION_KEY, edb);
1547 if(location != null) {
1548 monitor.subTask("Writing transferable graph");
1549 DataContainers.writeFile(location, new DataContainer(
1551 metadata, new Variant(TransferableGraph1.BINDING, tg)));
1558 throw new DatabaseException("Export failed, no contents to export");
1561 public static TreeMap<String, Variant> getExportMetadata() {
1563 TreeMap<String,Variant> metadata = new TreeMap<String,Variant>();
1564 metadata.put("date", Variant.ofInstance(DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL).format(new Date())));
1565 metadata.put("author", Variant.ofInstance(System.getProperty("user.name", "")));
1571 public static void createNewVersionWithoutUI(WriteGraph graph, Resource resource) throws DatabaseException {
1572 VersionInfo info = graph.syncRequest(new VersionInfoRequest(resource));
1573 int currentVersion = Integer.parseInt(info.version);
1574 String result = Integer.toString(currentVersion + 1);
1575 createNewVersion(graph, resource, info, result);
1578 public static void createNewVersionWithUI(ReadGraph graph, final Resource resource) throws DatabaseException {
1580 final VersionInfo info = graph.syncRequest(new VersionInfoRequest(resource));
1582 Display.getDefault().asyncExec(new Runnable() {
1585 Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();
1586 CreateVersionDialog dialog = new CreateVersionDialog(shell, info);
1587 if (dialog.open() == Window.OK) {
1588 final String result = dialog.getResult();
1589 Simantics.getSession().asyncRequest(new WriteRequest() {
1591 public void perform(WriteGraph graph) throws DatabaseException {
1592 createNewVersion(graph, resource, info, result);
1601 public static void createNewVersion(WriteGraph graph, Resource resource, final VersionInfo info, final String result) throws DatabaseException {
1602 graph.markUndoPoint();
1603 Layer0 L0 = Layer0.getInstance(graph);
1604 Resource parent = graph.getPossibleObject(resource, L0.PartOf);
1605 if(parent == null) return;
1606 final String parentURI = graph.getPossibleURI(parent);
1607 if(parentURI == null) return;
1608 Layer0Utils.copyTo(graph, parent, resource, new PasteEventHandler() {
1611 public void postProcess(WriteGraph graph, Resource root) throws DatabaseException {
1612 Layer0 L0 = Layer0.getInstance(graph);
1613 graph.deny(root, L0.Entity_published);
1617 public IImportAdvisor2 createAdvisor(ReadGraph graph, ImportAdvisorFactory factory, Resource target) throws DatabaseException {
1618 Map<String,Object> context = new HashMap<String,Object>();
1619 String base = parentURI + "/" + URIStringUtils.escape( info.baseName ) + "@";
1620 Map<String,String> renameMap = new HashMap<String,String>();
1621 renameMap.put(base + info.version, base + result);
1622 renameMap.put(info.baseName + "@" + info.version, info.baseName + "@" + result);
1623 context.put(ImportAdvisors.RENAME_MAP, renameMap);
1624 return factory.create(graph, target, context);
1628 Layer0Utils.addCommentMetadata(graph, "Created new version of " + info.baseName);
1631 public static boolean isUserComponent(ReadGraph graph, Resource type) throws DatabaseException {
1632 StructuralResource2 STR = StructuralResource2.getInstance(graph);
1633 if(graph.isInstanceOf(type, STR.ProceduralComponentType)) return true;
1634 else if (graph.hasStatement(type, STR.IsDefinedBy)) return true;
1638 public static void publishComponentTypeWithUI(WriteGraph graph, final Resource componentType) throws DatabaseException {
1640 Layer0 L0 = Layer0.getInstance(graph);
1641 StructuralResource2 STR = StructuralResource2.getInstance(graph);
1642 Resource composite = graph.getPossibleObject(componentType, STR.IsDefinedBy);
1643 final List<String> instances = new ArrayList<String>();
1644 if(composite != null) {
1645 for(Resource component : graph.syncRequest(new ObjectsWithType(composite, L0.ConsistsOf, STR.Component))) {
1646 Resource type = graph.getPossibleType(component, STR.Component);
1647 if(type != null && isUserComponent(graph, type)) {
1648 if(!Layer0Utils.isPublished(graph, type)) instances.add(Versions.getStandardPathNameString(graph, component));
1653 if(instances.isEmpty()) {
1654 graph.getSession().asyncRequest(new WriteRequest() {
1657 public void perform(WriteGraph graph) throws DatabaseException {
1658 graph.markUndoPoint();
1659 publish(graph, componentType);
1666 PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
1670 if (!PlatformUI.isWorkbenchRunning())
1673 Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();
1674 ListDialog<String> dialog = new ListDialog<String>(
1677 "Cannot publish user component",
1678 "The following instances are referring to unpublished user components.") {
1680 protected void createButtonsForButtonBar(Composite parent) {
1681 createButton(parent, IDialogConstants.OK_ID, IDialogConstants.OK_LABEL,true);
1685 int result = dialog.open();
1686 if (result != Dialog.OK)
1694 public static void publishSharedOntologyWithUI(WriteGraph graph, final Resource sharedOntology) throws DatabaseException {
1696 Layer0 L0 = Layer0.getInstance(graph);
1697 DiagramResource DIA = DiagramResource.getInstance(graph);
1698 StructuralResource2 STR = StructuralResource2.getInstance(graph);
1699 final List<String> instances = new ArrayList<String>();
1700 for(Resource type : searchByTypeShallow(graph, sharedOntology, STR.ComponentType)) {
1702 if(graph.isInheritedFrom(type, DIA.Element)) continue;
1703 if(!Layer0Utils.isPublished(graph, type)) instances.add(Versions.getStandardPathNameString(graph, type));
1705 for(Resource dep : graph.syncRequest(new ObjectsWithType(sharedOntology, L0.IsLinkedTo, L0.SharedOntology))) {
1706 if(!Layer0Utils.isPublished(graph, dep)) instances.add(Versions.getStandardPathNameString(graph, dep));
1709 if(instances.isEmpty()) {
1710 graph.getSession().asyncRequest(new WriteRequest() {
1713 public void perform(WriteGraph graph) throws DatabaseException {
1714 graph.markUndoPoint();
1715 publish(graph, sharedOntology);
1722 PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
1726 if (!PlatformUI.isWorkbenchRunning())
1729 Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();
1730 ListDialog<String> dialog = new ListDialog<String>(
1733 "Cannot publish shared library",
1734 "The following dependencies are unpublished.") {
1736 protected void createButtonsForButtonBar(Composite parent) {
1737 createButton(parent, IDialogConstants.OK_ID, IDialogConstants.OK_LABEL,true);
1741 int result = dialog.open();
1742 if (result != Dialog.OK)
1750 public static Resource createSCLModuleDefault(WriteGraph graph, Resource target) throws DatabaseException {
1751 String name = NameUtils.findFreshEscapedName(graph, "SCLModule", target);
1752 return createSCLModule(graph, target, name);
1755 public static Resource createSCLModule(WriteGraph graph, Resource target, String name) throws DatabaseException {
1756 graph.markUndoPoint();
1757 Layer0 L0 = Layer0.getInstance(graph);
1758 Resource sclModule = GraphUtils.create2(graph, L0.SCLModule,
1761 L0.SCLModule_definition, "");
1762 Layer0Utils.addCommentMetadata(graph, "Created SCL Module " + name + " " + sclModule.toString());
1766 public static Resource setSCLModuleDefinition(WriteGraph graph, Resource module, String definition) throws DatabaseException {
1767 graph.markUndoPoint();
1768 Layer0 L0 = Layer0.getInstance(graph);
1769 graph.claimLiteral(module, L0.SCLModule_definition, definition, Bindings.STRING);
1770 Layer0Utils.addCommentMetadata(graph, "Set SCL module " + module + " definition.");
1774 public static Resource createSCLScriptDefault(WriteGraph graph, Resource target) throws DatabaseException {
1775 String name = NameUtils.findFreshEscapedName(graph, "SCLScript", target);
1776 return createSCLScript(graph, target, name);
1779 public static Resource createSCLScript(WriteGraph graph, Resource target, String name) throws DatabaseException {
1780 graph.markUndoPoint();
1781 Layer0 L0 = Layer0.getInstance(graph);
1782 Resource sclModule = GraphUtils.create2(graph, L0.SCLScript,
1785 L0.SCLScript_definition, "");
1786 Layer0Utils.addCommentMetadata(graph, "Created SCL Script " + name + " " + sclModule.toString());
1790 public static Resource setSCLScriptDefinition(WriteGraph graph, Resource script, String definition) throws DatabaseException {
1791 graph.markUndoPoint();
1792 Layer0 L0 = Layer0.getInstance(graph);
1793 graph.claimLiteral(script, L0.SCLScript_definition, definition, Bindings.STRING);
1794 Layer0Utils.addCommentMetadata(graph, "Set SCL script " + script + " definition.");
1798 public static Resource createPGraphDefault(WriteGraph graph, Resource target) throws DatabaseException {
1799 String name = NameUtils.findFreshEscapedName(graph, "Ontology Definition File", target);
1800 return createPGraph(graph, target, name);
1803 public static Resource createPGraph(WriteGraph graph, Resource target, String name) throws DatabaseException {
1804 graph.markUndoPoint();
1805 Layer0 L0 = Layer0.getInstance(graph);
1806 Resource file = GraphUtils.create2(graph, L0.PGraph,
1809 L0.PGraph_definition, "");
1810 Layer0Utils.addCommentMetadata(graph, "Created Ontology Definition File " + name + " " + file.toString());
1814 public static Resource setPGraphDefinition(WriteGraph graph, Resource pgraph, String definition) throws DatabaseException {
1815 graph.markUndoPoint();
1816 Layer0 L0 = Layer0.getInstance(graph);
1817 graph.claimLiteral(pgraph, L0.PGraph_definition, definition, Bindings.STRING);
1818 Layer0Utils.addCommentMetadata(graph, "Set PGraph " + pgraph + " definition.");
1822 public static void publish(WriteGraph graph, Resource target) throws DatabaseException {
1823 Layer0 L0 = Layer0.getInstance(graph);
1824 graph.claimLiteral(target, L0.Entity_published, true, Bindings.BOOLEAN);
1825 Layer0Utils.addCommentMetadata(graph, "Published " + graph.getPossibleRelatedValue2(target, L0.HasName, Bindings.STRING) + " " + target.toString());
1828 public static boolean isLinkedToDeep(ReadGraph graph, Resource r1, Resource r2) throws DatabaseException {
1829 return graph.syncRequest(new IsLinkedTo(r1, r2));
1832 public static void openWizard(Display display, IStructuredSelection selection, String id) {
1833 // First see if this is a "new wizard".
1834 IWizardDescriptor descriptor = PlatformUI.getWorkbench()
1835 .getNewWizardRegistry().findWizard(id);
1836 // If not check if it is an "import wizard".
1837 if (descriptor == null) {
1838 descriptor = PlatformUI.getWorkbench().getImportWizardRegistry()
1841 // Or maybe an export wizard
1842 if (descriptor == null) {
1843 descriptor = PlatformUI.getWorkbench().getExportWizardRegistry()
1847 // Then if we have a wizard, open it.
1848 if (descriptor != null) {
1849 IWorkbenchWizard wizard = descriptor.createWizard();
1850 wizard.init(PlatformUI.getWorkbench(), selection);
1851 WizardDialog wd = new WizardDialog(display.getActiveShell(), wizard);
1852 wd.setTitle(wizard.getWindowTitle());
1855 } catch (CoreException e) {
1856 e.printStackTrace();
1860 public static String withinEpsilon(double value, double reference, double epsilon) {
1861 if(Math.abs(value-reference) < epsilon) return "True";
1862 else return "Not within epsilon value=" + value + ", reference=" + reference + " , epsilon=" + epsilon;
1865 public static boolean needsIdentifier(ReadGraph graph, Resource r) throws DatabaseException {
1866 Layer0 L0 = Layer0.getInstance(graph);
1867 Collection<Resource> types = graph.getPrincipalTypes(r);
1868 for(Resource type : types)
1869 if(graph.syncRequest(new IsInstanceOf(type, L0.TypeWithIdentifier), TransientCacheAsyncListener.<Boolean>instance()))
1874 public static boolean needsModificationInfo(ReadGraph graph, Resource r) throws DatabaseException {
1875 ModelingResources MOD = ModelingResources.getInstance(graph);
1876 Collection<Resource> types = graph.getPrincipalTypes(r);
1877 for(Resource type : types)
1878 if(graph.syncRequest(new IsInstanceOf(type, MOD.TypeWithChangeInformation), TransientCacheAsyncListener.<Boolean>instance()))
1883 public static void attachCreationInformation(IProgressMonitor monitor, WriteGraph graph, Resource model) throws DatabaseException {
1885 if(monitor == null) monitor = new NullProgressMonitor();
1887 final String author = System.getProperty("user.name", "");
1888 final long time = System.currentTimeMillis();
1890 monitor.setTaskName("Attach creation information");
1892 ModelingResources MOD = ModelingResources.getInstance(graph);
1893 Collection<Resource> rs = ModelingUtils.searchByType(graph, model, MOD.TypeWithChangeInformation);
1894 Collection<Resource> supers = ModelingUtils.getMostUnspecificTypes(graph, rs);
1896 CollectionSupport cs = graph.getService(CollectionSupport.class);
1897 Collection<Resource> set = cs.createSet();
1898 for(Resource type : supers) {
1899 set.addAll(ModelingUtils.searchByTypeShallow(graph, model, type));
1901 Collection<Resource> instances = Layer0Utils.sortByCluster(graph, set);
1903 int pc = instances.size() / 100;
1907 for(Resource instance : instances) {
1908 ChangeInformation info = graph.getPossibleRelatedValue(instance, MOD.changeInformation, ChangeInformation.BINDING);
1910 info = new ChangeInformation();
1911 info.createdAt = time;
1912 info.createdBy = author;
1913 info.modifiedAt = time;
1914 info.modifiedBy = author;
1915 graph.claimLiteral(instance, MOD.changeInformation, MOD.changeInformation_Inverse, MOD.ChangeInformation, info, ChangeInformation.BINDING);
1920 Double d = (100.0*done)/instances.size();
1921 monitor.setTaskName("Attach creation information " + d.intValue() + "%");
1926 monitor.setTaskName("Attach creation information - commit");
1930 public static class DiagramComponentInfo {
1932 private static String CHILD_PREFIX = "child:";
1934 final private String compositePathAndName;
1935 final private String componentName;
1936 final private GUID guid;
1938 public DiagramComponentInfo(String compositePathAndName, String componentName, GUID guid) {
1939 this.compositePathAndName = compositePathAndName;
1940 this.componentName = componentName;
1944 public static boolean isDiagramComponent(String tgName) {
1945 return tgName.startsWith(CHILD_PREFIX);
1948 public String getTGName(CompositeInfo info) {
1949 return CHILD_PREFIX + info.getOriginalPath() + ModelingUtils.COMPOSITE_SEPARATOR_CHAR + info.getEscapedName() + ModelingUtils.COMPOSITE_SEPARATOR_CHAR + getEscapedComponentName() + ModelingUtils.COMPOSITE_SEPARATOR_CHAR + guid.indexString();
1952 public boolean existsGUID(ReadGraph graph, Resource indexRoot) throws DatabaseException {
1953 Collection<Resource> res = ModelingUtils.searchByGUID(graph, indexRoot, guid);
1954 return !res.isEmpty();
1957 public static DiagramComponentInfo fromResource(ReadGraph graph, CompositeInfo info, Resource resource) throws DatabaseException {
1958 Layer0 L0 = Layer0.getInstance(graph);
1959 GUID childId = graph.getRelatedValue(resource, L0.identifier, GUID.BINDING);
1960 String childName = graph.getRelatedValue(resource, L0.HasName, Bindings.STRING);
1961 return new DiagramComponentInfo(info.getStateKey(), URIStringUtils.escape(childName), childId);
1964 public GUID getGUID() {
1968 public String getEscapedCompositePathAndName() {
1969 return compositePathAndName;
1972 public String getEscapedComponentName() {
1973 return componentName;
1976 public String getUnescapedComponentName() {
1977 return URIStringUtils.unescape(getEscapedComponentName());
1980 // "child:path#compositeName#componentName#guid"
1981 public static DiagramComponentInfo parse(String tgName) {
1983 String name = tgName.substring(CHILD_PREFIX.length());
1984 String compositePathAndName = "";
1985 String moduleName = name;
1986 GUID guid = GUID.invalid();
1987 int lastHash = name.lastIndexOf(ModelingUtils.COMPOSITE_SEPARATOR_CHAR);
1989 String first = name.substring(0, lastHash);
1990 String second = name.substring(lastHash+1);
1991 lastHash = first.lastIndexOf(ModelingUtils.COMPOSITE_SEPARATOR_CHAR);
1993 compositePathAndName = first.substring(0, lastHash);
1994 moduleName = first.substring(lastHash+1);
1995 guid = GUID.parseIndexString(second);
1997 compositePathAndName = first;
1998 moduleName = second;
2001 return new DiagramComponentInfo(compositePathAndName, moduleName, guid);
2007 public int hashCode() {
2008 final int prime = 31;
2010 result = prime * result + ((compositePathAndName == null) ? 0 : compositePathAndName.hashCode());
2011 result = prime * result + ((componentName == null) ? 0 : componentName.hashCode());
2016 public boolean equals(Object obj) {
2021 if (getClass() != obj.getClass())
2023 DiagramComponentInfo other = (DiagramComponentInfo) obj;
2024 if (compositePathAndName == null) {
2025 if (other.compositePathAndName != null)
2027 } else if (!compositePathAndName.equals(other.compositePathAndName))
2029 if (componentName == null) {
2030 if (other.componentName != null)
2032 } else if (!componentName.equals(other.componentName))
2039 public static class CompositeInfo {
2041 public static String COMPOSITE_PREFIX = "composite:";
2043 final private boolean useGuids;
2044 final private boolean applyPaths;
2045 final private String path;
2046 final private String name;
2047 final private GUID guid;
2049 private CompositeInfo(boolean useGuids, boolean applyPaths, String path, String name, GUID guid) {
2050 this.useGuids = useGuids;
2051 this.applyPaths = applyPaths;
2058 public String toString() {
2059 return "CompositeInfo[useGuids=" + useGuids + ", applyPaths=" + applyPaths + ", path=" + path + ", name=" + name + ", guid=" + guid.indexString() + "]";
2062 public static boolean isComposite(String tgName) {
2063 return tgName.startsWith(COMPOSITE_PREFIX);
2066 public String getTGName() {
2067 return COMPOSITE_PREFIX + getOriginalPath() + ModelingUtils.COMPOSITE_SEPARATOR_CHAR + getEscapedName() + ModelingUtils.COMPOSITE_SEPARATOR_CHAR + guid.indexString();
2070 public boolean existsGUID(ReadGraph graph, Resource indexRoot) throws DatabaseException {
2071 Collection<Resource> res = ModelingUtils.searchByGUID(graph, indexRoot, guid);
2072 return !res.isEmpty();
2075 public static CompositeInfo fromResource(ReadGraph graph, Resource resource) throws DatabaseException {
2077 Layer0 L0 = Layer0.getInstance(graph);
2078 GUID rootId = graph.getRelatedValue(resource, L0.identifier, GUID.BINDING);
2079 String rootName = graph.getRelatedValue(resource, L0.HasName, Bindings.STRING);
2080 String escapedRootName = URIStringUtils.escape(rootName);
2081 String escapedPath = ModelingUtils.getDiagramCompositePath(graph, resource);
2082 return new CompositeInfo(true, true, escapedPath, escapedRootName, rootId);
2086 public static CompositeInfo parse(String tgName) {
2087 return parse(tgName, true, true);
2091 * Index 0 is root-relative folder path separated with '/' or null if target-relative positioning is used
2092 * Index 1 is diagram name
2094 public static CompositeInfo parse(String tgName, boolean applyPaths, boolean useGuids) {
2095 if(!tgName.startsWith(COMPOSITE_PREFIX)) return null;
2096 tgName = tgName.substring(COMPOSITE_PREFIX.length());
2097 if(!tgName.contains(COMPOSITE_SEPARATOR)) {
2098 if(useGuids) throw new IllegalStateException("GUID identifiers were not found for diagrams.");
2099 return new CompositeInfo(useGuids, applyPaths, null, tgName, null);
2101 String[] parts = tgName.split(COMPOSITE_SEPARATOR);
2102 if(parts.length == 2) {
2103 String name = parts[1];
2104 String path = applyPaths ? parts[0] : null;
2105 if(useGuids) throw new IllegalStateException("GUID identifiers were not found for diagrams.");
2106 return new CompositeInfo(useGuids, applyPaths, path, name, null);
2107 } else if(parts.length == 3) {
2108 String path = parts[0];
2109 String name = parts[1];
2110 GUID guid = GUID.parseIndexString(parts[2]);
2111 return new CompositeInfo(useGuids, applyPaths, path, name, guid);
2117 public GUID getGUID() {
2121 public String getEscapedName() {
2125 public String getUnescapedName() {
2126 return URIStringUtils.unescape(name);
2129 public String getOriginalPath() {
2133 public String getFinalPath() {
2134 if(applyPaths) return path;
2138 public CompositeInfo renamed(String newName) {
2139 return new CompositeInfo(useGuids, applyPaths, path, newName, guid);
2142 public String getStateKey() {
2143 return path + "#" + getEscapedName();
2146 private Resource getFromFolder(ReadGraph graph, Resource target) throws DatabaseException {
2147 Resource diagram = Layer0Utils.getPossibleChild(graph, target, URIStringUtils.unescape(name));
2148 if(diagram == null) return null;
2149 StructuralResource2 STR = StructuralResource2.getInstance(graph);
2150 return graph.isInstanceOf(diagram, STR.Composite) ? diagram : null;
2153 public Resource resolve(ReadGraph graph, Resource target) throws DatabaseException {
2155 if(useGuids && guid != null) {
2156 Resource indexRoot = graph.syncRequest(new IndexRoot(target));
2157 Collection<Resource> queryResult = searchByGUID(graph, indexRoot, guid);
2158 if(queryResult.size() == 1) {
2159 Resource composite = queryResult.iterator().next();
2160 StructuralResource2 STR = StructuralResource2.getInstance(graph);
2161 if(!graph.isInstanceOf(composite, STR.Composite)) return null;
2167 Resource folder = resolveFolder(graph, target);
2168 if(folder == null) return null;
2169 return getFromFolder(graph, folder);
2171 return getFromFolder(graph, target);
2176 public Resource resolveFolder(ReadGraph graph, Resource target) throws DatabaseException {
2178 String path = getFinalPath();
2179 if(path == null) return target;
2181 Resource folder = graph.syncRequest(new Configuration(target));
2182 String[] segments = path.split("/");
2183 for(int i=0;i<segments.length;i++) {
2184 if(segments[i].isEmpty()) continue;
2185 folder = Layer0Utils.getPossibleChild(graph, folder, URIStringUtils.unescape(segments[i]));
2186 if(folder == null) return null;
2195 public int hashCode() {
2197 if(useGuids) return guid.hashCode();
2199 final int prime = 31;
2200 int result = name.hashCode();
2201 result = prime * result + ((path == null) ? 0 : path.hashCode());
2207 public boolean equals(Object obj) {
2213 if (getClass() != obj.getClass())
2216 CompositeInfo other = (CompositeInfo) obj;
2218 if(useGuids) return guid.equals(other.guid);
2220 if (!name.equals(other.name))
2224 if (!path.equals(other.path))
2233 public static char COMPOSITE_SEPARATOR_CHAR = '#';
2234 public static String COMPOSITE_SEPARATOR = String.valueOf(COMPOSITE_SEPARATOR_CHAR);
2236 public static CompositeInfo parseCompositeNameFromRoot(Root root, boolean applyPaths, boolean useGuids) {
2237 return CompositeInfo.parse(root.name, applyPaths, useGuids);
2240 public static CompositeInfo parseCompositeNameFromRoot(Identity root, boolean applyPaths, boolean useGuids) {
2241 String coded = TransferableGraphUtils.getName(root);
2242 return CompositeInfo.parse(coded, applyPaths, useGuids);
2245 private static StringBuilder getDiagramCompositePathInternal(ReadGraph graph, Resource folder, StringBuilder builder) throws DatabaseException {
2246 SimulationResource SIMU = SimulationResource.getInstance(graph);
2247 Resource model = graph.getPossibleObject(folder, SIMU.IsConfigurationOf);
2248 if (model != null) return builder;
2250 Layer0 L0 = Layer0.getInstance(graph);
2251 String name = graph.getPossibleRelatedValue(folder, L0.HasName, Bindings.STRING);
2252 if (name == null) return null;
2253 Resource parent = graph.getPossibleObject(folder, L0.PartOf);
2254 if (parent == null) return null;
2256 StringBuilder sb = getDiagramCompositePathInternal(graph, parent, builder);
2257 if (sb == null) return null;
2258 if (sb.length() > 0)
2259 sb.append(URIStringUtils.NAMESPACE_PATH_SEPARATOR);
2260 sb.append( URIStringUtils.escape(name) );
2267 * @return diagram/folder path up until model configuration root with each
2268 * segment escaped using {@link URIStringUtils#escape(String)} and
2269 * {@value URIStringUtils#NAMESPACE_PATH_SEPARATOR} between each
2270 * segment or <code>null</code> if the specified diagram composite
2271 * is not part of any model configuration structure.
2272 * @throws DatabaseException
2274 public static String getDiagramCompositePath(ReadGraph graph, Resource diagram) throws DatabaseException {
2275 Layer0 L0 = Layer0.getInstance(graph);
2276 Resource parent = graph.getPossibleObject(diagram, L0.PartOf);
2277 if(parent == null) return null;
2278 StringBuilder sb = getDiagramCompositePathInternal(graph, parent, new StringBuilder());
2279 return sb != null ? sb.toString() : null;
2282 public static void exportModel(ReadGraph graph, Resource model, String fileName, String format, int version) throws DatabaseException {
2283 TransferableGraphConfiguration2 conf = new TransferableGraphConfiguration2(graph, model, true, false);
2284 exportModel(graph, conf, fileName, format, version);
2287 public static void exportModel(ReadGraph graph, TransferableGraphConfiguration2 conf, String fileName, String format, int version) throws DatabaseException {
2290 TransferableGraphSource s = graph.syncRequest(new ModelTransferableGraphSourceRequest(conf));
2291 TransferableGraphs.writeTransferableGraph(graph, format, version, s, new File(fileName));
2292 } catch (DatabaseException e) {
2294 } catch (Exception e) {
2295 throw new DatabaseException(e);
2300 public static TransferableGraph1 exportSharedOntology(ReadGraph graph, Resource library, String fileName, String format, int version) throws DatabaseException {
2302 Layer0 L0 = Layer0.getInstance(graph);
2303 String name = graph.getRelatedValue(library, L0.HasName, Bindings.STRING);
2305 DraftStatusBean draft = null;
2306 boolean published = Layer0Utils.isPublished(graph, library);
2307 if(!published) draft = new DraftStatusBean(new String[0]);
2309 LibraryInfo info = new LibraryInfo(name, library, draft);
2312 return exportSharedOntology(new NullProgressMonitor(), graph, fileName != null ? new File(fileName) : null, format, version, info);
2313 } catch (IOException e) {
2314 throw new DatabaseException(e);
2319 public static DraftStatusBean getDependencyDraftStatus(ReadGraph graph, Resource library) throws DatabaseException {
2320 Layer0 L0 = Layer0.getInstance(graph);
2321 List<String> drafts = new ArrayList<>();
2322 for (Resource shared : graph.syncRequest(new ObjectsWithType(library, L0.IsLinkedTo, L0.SharedOntology))) {
2323 boolean published = Layer0Utils.isPublished(graph, shared);
2325 drafts.add(graph.getURI(shared));
2327 return drafts.isEmpty() ? null : new DraftStatusBean(drafts);
2330 public static Set<Resource> getMostUnspecificTypes(final ReadGraph graph, Collection<Resource> types) throws DatabaseException {
2332 final Set<Resource> work = new HashSet<Resource>(types);
2333 for(Resource type : types) {
2334 Set<Resource> supers = graph.getSupertypes(type);
2335 if(!Collections.disjoint(supers, work)) work.remove(type);
2342 public static void rewriteGUIDS(WriteGraph graph, Resource root, boolean deep) throws DatabaseException {
2343 List<Resource> todo = new ArrayList<Resource>();
2345 Layer0 L0 = Layer0.getInstance(graph);
2346 while(!todo.isEmpty()) {
2347 Resource resource = todo.remove(todo.size()-1);
2348 Layer0Utils.claimNewIdentifier(graph, resource, false);
2350 todo.addAll(graph.getObjects(resource, L0.ConsistsOf));
2354 public static void createMissingGUIDs(IProgressMonitor monitor, WriteGraph graph, Collection<Resource> roots) throws DatabaseException {
2356 if(monitor == null) monitor = new NullProgressMonitor();
2358 Layer0 L0 = Layer0.getInstance(graph);
2360 // Allow this process to make 50k queries
2361 QueryMemoryWatcher memory = new QueryMemoryWatcher(graph, 50000);
2363 for(Resource root : roots) {
2365 boolean madeChanges = false;
2367 monitor.setTaskName("Creating missing GUID identifiers " + NameUtils.getSafeName(graph, root));
2368 Resource indexRoot = graph.syncRequest(new PossibleIndexRoot(root));
2369 for(Resource r : searchByTypeShallow(graph, indexRoot, L0.Entity)) {
2373 if(graph.isImmutable(r)) continue;
2375 if(!ModelingUtils.needsIdentifier(graph, r)) continue;
2377 GUID existing = graph.getPossibleRelatedValue(r, L0.identifier, GUID.BINDING);
2378 if(existing == null) {
2379 Layer0Utils.claimNewIdentifier(graph, r, true);
2386 ModelingUtils.deleteIndex(graph, root);
2393 public static boolean activateModel(WriteGraph graph, Resource model) throws DatabaseException {
2394 return graph.syncRequest(new ActivateModel(Simantics.getProjectResource(), model));
2397 public static File fileDialog(String title, List<Tuple> namesAndExtensions) {
2398 return new Runnable() {
2399 private File result;
2402 Display.getDefault().syncExec(this);
2408 result = showDialog();
2411 private File showDialog() {
2412 Display display = Display.getCurrent();
2413 Shell shell = display.getActiveShell();
2415 FileDialog dialog = new FileDialog(shell, SWT.OPEN);
2416 dialog.setText(title);
2418 String[] extensions = new String[namesAndExtensions.size()];
2419 String[] filterNames = new String[namesAndExtensions.size()];
2421 for(Tuple t : namesAndExtensions) {
2422 String filterName = (String)t.get(0);
2423 String extension = (String)t.get(1);
2424 filterNames[index] = filterName;
2425 extensions[index] = extension;
2429 dialog.setFilterExtensions(extensions);
2430 dialog.setFilterNames(filterNames);
2431 final String fileName = dialog.open();
2432 if (fileName == null) return null;
2434 return new File(fileName);
2439 public static Resource createLibrary(WriteGraph graph, Resource parent) throws DatabaseException {
2440 Layer0 l0 = Layer0.getInstance(graph);
2441 return createLibrary(graph, parent, NameUtils.findFreshName(graph, "Library", parent, l0.ConsistsOf));
2444 public static Resource createLibrary(WriteGraph graph, Resource parent, String name) throws DatabaseException {
2445 graph.markUndoPoint();
2446 Layer0 l0 = Layer0.getInstance(graph);
2448 Resource library = graph.newResource();
2449 graph.claim(library, l0.InstanceOf, null, l0.Library);
2450 graph.addLiteral(library, l0.HasName, l0.NameOf, l0.String, name, Bindings.STRING);
2451 graph.claim(library, l0.PartOf, parent);
2453 Layer0Utils.addCommentMetadata(graph, "Created new Library named " + name + ", resource " + library);
2458 public static IModelingRules getModelingRules(ReadGraph graph, Resource diagramResource) throws DatabaseException {
2459 return DiagramGraphUtil.getModelingRules(graph, diagramResource, null);
2462 public static void markChanged(WriteGraph graph, Resource r) throws DatabaseException {
2463 VirtualGraphSupport support = Simantics.getSession().getService(VirtualGraphSupport.class);
2464 VirtualGraph vg = support.getWorkspacePersistent("changeInformation");
2465 graph.syncRequest(new WriteRequest(vg) {
2467 public void perform(WriteGraph graph) throws DatabaseException {
2468 ModelingResources MOD = ModelingResources.getInstance(graph);
2469 graph.claim(r, MOD.changed, MOD.changed, r);