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.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.SelectionHints;
94 import org.simantics.db.layer0.adapter.CopyHandler;
95 import org.simantics.db.layer0.adapter.GenericRelationIndex;
96 import org.simantics.db.layer0.adapter.Instances;
97 import org.simantics.db.layer0.adapter.impl.DefaultPasteImportAdvisor;
98 import org.simantics.db.layer0.adapter.impl.EntityInstances.QueryIndex;
99 import org.simantics.db.layer0.adapter.impl.ImportAdvisorFactory;
100 import org.simantics.db.layer0.genericrelation.DependenciesRelation.DependencyChangesRequest;
101 import org.simantics.db.layer0.genericrelation.DependencyChanges;
102 import org.simantics.db.layer0.genericrelation.IndexedRelations;
103 import org.simantics.db.layer0.migration.MigrationUtils;
104 import org.simantics.db.layer0.request.ActivateModel;
105 import org.simantics.db.layer0.request.ActiveModels;
106 import org.simantics.db.layer0.request.Configuration;
107 import org.simantics.db.layer0.request.IsLinkedTo;
108 import org.simantics.db.layer0.request.PossibleModel;
109 import org.simantics.db.layer0.util.ClipboardUtils;
110 import org.simantics.db.layer0.util.DraftStatusBean;
111 import org.simantics.db.layer0.util.ExternalDownloadBean;
112 import org.simantics.db.layer0.util.Layer0Utils;
113 import org.simantics.db.layer0.util.ModelTransferableGraphSourceRequest;
114 import org.simantics.db.layer0.util.PasteEventHandler;
115 import org.simantics.db.layer0.util.RemoverUtil;
116 import org.simantics.db.layer0.util.SimanticsClipboard;
117 import org.simantics.db.layer0.util.SimanticsClipboard.Representation;
118 import org.simantics.db.layer0.util.SimanticsClipboardImpl;
119 import org.simantics.db.layer0.util.SimanticsKeys;
120 import org.simantics.db.layer0.util.TransferableGraphConfiguration2;
121 import org.simantics.db.layer0.variable.Variable;
122 import org.simantics.db.layer0.variable.Variables;
123 import org.simantics.db.request.Read;
124 import org.simantics.db.service.ClusterControl;
125 import org.simantics.db.service.CollectionSupport;
126 import org.simantics.db.service.GraphChangeListenerSupport;
127 import org.simantics.db.service.QueryControl;
128 import org.simantics.db.service.VirtualGraphSupport;
129 import org.simantics.diagram.stubs.DiagramResource;
130 import org.simantics.diagram.stubs.G2DResource;
131 import org.simantics.diagram.synchronization.graph.AddElement;
132 import org.simantics.graph.db.IImportAdvisor2;
133 import org.simantics.graph.db.ImportAdvisors;
134 import org.simantics.graph.db.MissingDependencyException;
135 import org.simantics.graph.db.StreamingTransferableGraphFileReader;
136 import org.simantics.graph.db.TransferableGraphException;
137 import org.simantics.graph.db.TransferableGraphSource;
138 import org.simantics.graph.db.TransferableGraphs;
139 import org.simantics.graph.representation.Identity;
140 import org.simantics.graph.representation.Root;
141 import org.simantics.graph.representation.TransferableGraph1;
142 import org.simantics.graph.representation.TransferableGraphUtils;
143 import org.simantics.issues.common.IssueSourceUtils;
144 import org.simantics.issues.ontology.IssueResource;
145 import org.simantics.layer0.Layer0;
146 import org.simantics.layer0.utils.direct.GraphUtils;
147 import org.simantics.modeling.adapters.ChangeInformation;
148 import org.simantics.modeling.template2d.ontology.Template2dResource;
149 import org.simantics.modeling.utils.OntologicalRequirementTracker;
150 import org.simantics.operation.Layer0X;
151 import org.simantics.project.ontology.ProjectResource;
152 import org.simantics.scenegraph.profile.ProfileUtils;
153 import org.simantics.scl.runtime.function.Function1;
154 import org.simantics.scl.runtime.tuple.Tuple;
155 import org.simantics.simulation.ontology.SimulationResource;
156 import org.simantics.structural.stubs.StructuralResource2;
157 import org.simantics.structural2.scl.StructuralComponent;
158 import org.simantics.structural2.utils.StructuralUtils;
159 import org.simantics.ui.SimanticsUI;
160 import org.simantics.utils.ObjectUtils;
161 import org.simantics.utils.datastructures.Pair;
162 import org.simantics.utils.datastructures.Triple;
163 import org.simantics.utils.datastructures.hints.HintContext;
164 import org.simantics.utils.ui.dialogs.ListDialog;
167 * @author Hannu Niemistö
169 public class ModelingUtils {
172 private WriteGraph wg;
174 private StructuralResource2 sr;
175 private DiagramResource dr;
176 public ModelingResources mr;
177 public SimulationResource SIMU;
179 public ModelingUtils(WriteGraph g) {
182 b = Layer0.getInstance(g);
183 sr = StructuralResource2.getInstance(g);
184 dr = DiagramResource.getInstance(g);
185 mr = ModelingResources.getInstance(g);
186 SIMU = SimulationResource.getInstance(g);
190 public Resource createSymbol2(String name) throws DatabaseException {
191 return createSymbol2(name, dr.Composite);
195 public Resource createSymbol2(String name, Resource diagramType) throws DatabaseException {
196 return createSymbol2(name, diagramType, dr.DefinedElement);
199 public Resource createSymbol2(String name, Resource diagramType, Resource symbolType) throws DatabaseException {
200 G2DResource g2d = G2DResource.getInstance(g);
202 // Resource visibleTag = wg.newResource();
203 // wg.claim(visibleTag, b.SubrelationOf, null, dr.IsVisible);
204 // Resource focusableTag = wg.newResource();
205 // wg.claim(focusableTag, b.SubrelationOf, null, dr.IsFocusable);
207 Double boxDimension = 6.0;
208 Collection<Statement> grid = g.getAssertedStatements(diagramType, dr.HasGridSize);
209 if(grid.size() == 1) {
210 Double d = g.getPossibleValue(grid.iterator().next().getObject(), Bindings.DOUBLE);
211 if(d != null) boxDimension = 2*d;
215 Resource element = GraphUtils.create(wg,
216 b.InstanceOf, dr.SVGElement,
218 "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>" +
219 // REMOVED by Tuukka, because This will cause
220 // parsers to get on the net and get the doctype
221 // definitions which can stall the UI for a long time.
222 // Besides, we're not using the validation for anything
223 // so it's useless to us.
224 //"<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\" \"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\">" +
225 "<svg xmlns=\"http://www.w3.org/2000/svg\" overflow=\"visible\" version=\"1.1\">" +
226 "<rect x=\"-" + boxDimension + "\" y=\"-" + boxDimension + "\" width=\"" + (2*boxDimension) + "\" height=\"" + (2*boxDimension) + "\" fill=\"none\" stroke=\"rgb(0,0,0)\" stroke-width=\"0.1\"/>" +
230 // wg.claim(element, visibleTag, element);
231 // wg.claim(element, focusableTag, element);
233 Resource orderedSet = OrderedSetUtils.create(wg, diagramType, element);
235 // wg.claim(orderedSet, dr.HasLayer, GraphUtils.create2(wg, dr.Layer,
236 // b.HasName, "Default",
237 // dr.IsActive, Boolean.TRUE,
238 // dr.HasVisibleTag, visibleTag,
239 // dr.HasFocusableTag, focusableTag));
241 Resource result = GraphUtils.create(wg,
244 sr.IsDefinedBy, orderedSet);
246 wg.claim(result, b.ConsistsOf, orderedSet);
247 wg.claimLiteral(orderedSet, b.HasName, "__DIAGRAM__", Bindings.STRING);
248 AddElement.claimFreshElementName(wg, orderedSet, element);
249 wg.claim(orderedSet, b.ConsistsOf, element);
251 wg.claim(result, b.Inherits, null, symbolType);
255 public static Collection<Resource> getElementCorrespondendences(ReadGraph g, Resource element) throws DatabaseException {
256 DiagramResource dr = DiagramResource.getInstance(g);
257 ModelingResources mr = ModelingResources.getInstance(g);
258 if(g.isInstanceOf(element, dr.Connection)) {
259 Resource mappedComponent = g.getPossibleObject(element, mr.ElementToComponent);
260 if(mappedComponent != null) return Collections.singletonList(mappedComponent);
261 Resource mappedConnection = g.getPossibleObject(element, mr.DiagramConnectionToConnection);
262 if(mappedConnection == null)
263 return Collections.emptyList();
264 ArrayList<Resource> result = new ArrayList<Resource>();
265 Collection<Resource> relatedMappedConnections = StructuralUtils.getRelatedConnections(g, mappedConnection);
266 for(Resource relatedMappedConnection : relatedMappedConnections)
267 for(Resource relatedConnection : g.getObjects(relatedMappedConnection, mr.ConnectionToDiagramConnection))
268 result.addAll(g.getObjects(relatedConnection, mr.ElementToComponent));
272 return g.getObjects(element, mr.ElementToComponent);
275 public static Resource getPossibleElement(ReadGraph g, Resource component) throws DatabaseException {
276 ModelingResources mr = ModelingResources.getInstance(g);
277 return g.getPossibleObject(component, mr.ComponentToElement);
280 public static Resource getPossibleElementCorrespondendence(ReadGraph g, Resource element) throws DatabaseException {
281 Collection<Resource> corrs = getElementCorrespondendences(g, element);
282 if(corrs.size() != 1) return null;
283 else return corrs.iterator().next();
286 public static Resource getSingleElementCorrespondendence(ReadGraph g, Resource element) throws DatabaseException {
287 Collection<Resource> corrs = getElementCorrespondendences(g, element);
288 if(corrs.size() != 1) throw new DatabaseException("Expected 1 element correspondence, got " + corrs.size());
289 else return corrs.iterator().next();
292 public static Resource createExperiment(WriteGraph graph, Resource model) throws DatabaseException {
294 Layer0 L0 = Layer0.getInstance(graph);
295 SimulationResource SIMU = SimulationResource.getInstance(graph);
296 Resource experiment = graph.newResource();
297 graph.claim(experiment, L0.InstanceOf, SIMU.Experiment);
298 graph.claimLiteral(experiment, L0.HasName, "Experiment");
299 graph.claim(model, L0.ConsistsOf, experiment);
304 public static Resource createModel(WriteGraph graph, Resource type) throws DatabaseException {
305 return createModel(graph, type, Simantics.getProjectResource(), null);
308 public static Resource createModel(WriteGraph graph, Resource type, String name) throws DatabaseException {
309 return createModel(graph, type, Simantics.getProjectResource(), name);
312 public static Resource createModel(WriteGraph graph, Resource type, final Resource target, String name) throws DatabaseException {
314 Layer0 L0 = Layer0.getInstance(graph);
315 SimulationResource SIMU = SimulationResource.getInstance(graph);
316 StructuralResource2 STR = StructuralResource2.getInstance(graph);
317 ModelingResources MOD = ModelingResources.getInstance(graph);
320 name = NameUtils.findFreshName(graph, "Model", target, L0.ConsistsOf, "%s%d");
322 final Resource model = graph.newResource();
323 graph.newClusterSet(model);
324 graph.claim(model, L0.InstanceOf, null, type);
325 graph.claimLiteral(model, L0.HasName, name);
327 graph.claim(target, L0.ConsistsOf, model);
329 Resource configurationType = graph.getPossibleObject(model, MOD.StructuralModel_HasConfigurationType);
330 if(configurationType == null) configurationType = STR.Composite;
332 Resource configuration = graph.newResource();
333 graph.claimLiteral(configuration, L0.HasName, "Configuration", Bindings.STRING);
334 graph.claim(configuration, L0.InstanceOf, null, configurationType);
335 graph.claim(model, L0.ConsistsOf, configuration);
336 graph.claim(model, SIMU.HasConfiguration, configuration);
338 Resource joinClusterSet = graph.newResource();
339 graph.newClusterSet(joinClusterSet);
340 graph.claim(joinClusterSet, L0.InstanceOf, L0.ClusterSet);
341 graph.claim(model, STR.HasJoinClusterSet, joinClusterSet);
343 linkOntologyDependenciesToModel(graph, model, target);
345 Resource ontology = graph.syncRequest(new PossibleIndexRoot(type));
346 if(ontology != null) {
347 graph.claim(model, L0.IsLinkedTo, ontology);
350 VirtualGraphSupport support = graph.getService(VirtualGraphSupport.class);
351 graph.asyncRequest(new WriteRequest(support.getWorkspacePersistent("activations")) {
354 public void perform(WriteGraph graph) throws DatabaseException {
355 Layer0X L0X = Layer0X.getInstance(graph);
356 Collection<Resource> actives = graph.syncRequest(new ActiveModels(target));
357 if(actives.isEmpty()) {
358 graph.claim(model, L0X.IsActivatedBy, target);
368 public static void linkOntologyDependenciesToModel(WriteGraph graph, Resource model, Resource target)
369 throws DatabaseException {
370 Layer0 L0 = Layer0.getInstance(graph);
371 ProjectResource PROJ = ProjectResource.getInstance(graph);
372 for(Resource dep : graph.getObjects(target, L0.IsLinkedTo)) {
373 if(graph.isInstanceOf(dep, PROJ.NamespaceRequirement)) {
374 for(Resource req : graph.getObjects(dep, PROJ.RequiresNamespace)) {
375 String uri = graph.getPossibleValue(req, Bindings.STRING);
377 Resource ns = graph.getResource(uri);
379 graph.claim(model, L0.IsLinkedTo, null, ns);
387 public static void addSCLMainToModel(WriteGraph graph, Resource model)
388 throws DatabaseException {
389 addSCLMainToModel(graph, model, "SCLMain", "include \"Simantics/All\"\n");
392 public static void addSCLMainToModel(WriteGraph graph, Resource model, String name, String contents)
393 throws DatabaseException {
394 Layer0 L0 = Layer0.getInstance(graph);
395 Resource sclmain = GraphUtils.create2(graph, L0.SCLModule, L0.PartOf, model, L0.HasName, name);
396 graph.claimLiteral(sclmain, L0.SCLModule_definition, contents, Bindings.STRING);
399 public static Resource createLocalLibrary(WriteGraph graph, Resource container, String name) throws DatabaseException {
400 Layer0 L0 = Layer0.getInstance(graph);
401 ModelingResources MOD = ModelingResources.getInstance(graph);
402 Resource library = graph.newResource();
403 graph.claim(library, L0.InstanceOf, null, L0.Library);
404 graph.addLiteral(library, L0.HasName, L0.NameOf, "Library", Bindings.STRING);
405 if (container != null) {
406 graph.claim(container, L0.ConsistsOf, L0.PartOf, library);
407 graph.claim(container, MOD.HasLocalLibrary, MOD.IsLocalLibraryOf, library);
412 public static void importModel(String fileName) {
414 Resource project = SimanticsUI.getProject().get();
416 try (StreamingTransferableGraphFileReader importer = new StreamingTransferableGraphFileReader(new File(fileName))) {
417 TransferableGraphSource tg = importer.readTG();
419 final DefaultPasteImportAdvisor advisor = new DefaultPasteImportAdvisor(project) {
421 public void analyzeType(ReadGraph graph, Root root) throws DatabaseException {
424 public Resource analyzeRoot(ReadGraph graph, Root root) throws DatabaseException {
425 library = Simantics.getProjectResource();
426 String newName = newName(graph, library, root.name);
427 nameMappings.put(root.name, newName);
431 TransferableGraphs.importGraph1(Simantics.getSession(), tg, advisor);
433 } catch (MissingDependencyException e) {
435 final Set<String> missingURIs = e.getMissingURIs();
437 class ErrorMessageDialog extends MessageDialog {
439 public ErrorMessageDialog(Shell shell) {
441 "Unsatisfied dependencies", null,
442 "The following dependencies were missing. Please import the dependencies and try again.",
443 MessageDialog.ERROR, new String[] { "Continue" }, 0);
447 protected Control createCustomArea(Composite composite) {
448 GridLayoutFactory.fillDefaults().applyTo(composite);
450 org.eclipse.swt.widgets.List list = new org.eclipse.swt.widgets.List(composite, SWT.BORDER | SWT.READ_ONLY);
451 GridDataFactory.fillDefaults().grab(true, true).applyTo(list);
452 for(String s : missingURIs) list.add(s);
458 Display display = Display.getCurrent();
459 if(display != null) {
460 ErrorMessageDialog md = new ErrorMessageDialog(display.getActiveShell());
463 Display.getDefault().asyncExec(new Runnable() {
467 Shell shell = Display.getCurrent().getActiveShell();
468 ErrorMessageDialog md = new ErrorMessageDialog(shell);
476 } catch (Exception e) {
477 Logger.defaultLogError(e);
482 public static void primeVirtualGraphs() {
483 VirtualGraphSupport support = Simantics.getSession().getService(VirtualGraphSupport.class);
484 support.getWorkspacePersistent("activations");
485 support.getWorkspacePersistent("experiments");
486 support.getWorkspacePersistent("issues");
487 support.getWorkspacePersistent("preferences");
490 public static Resource createProfileEntry(WriteGraph graph, String name, Resource style, Resource group) throws DatabaseException {
492 Layer0 L0 = Layer0.getInstance(graph);
493 DiagramResource DIA = DiagramResource.getInstance(graph);
495 Resource entry = graph.newResource();
496 graph.claim(entry, L0.InstanceOf, null, DIA.GroupStyleProfileEntry);
497 graph.claimLiteral(entry, L0.HasName, name);
498 graph.claimLiteral(entry, L0.HasLabel, name);
499 graph.claim(entry, DIA.ProfileEntry_HasStyle, style);
500 graph.claim(entry, DIA.ProfileEntry_HasGroup, group);
506 public static Resource createProfile(WriteGraph graph, String profileName, Resource... entries) throws DatabaseException {
508 Layer0 L0 = Layer0.getInstance(graph);
509 DiagramResource DIA = DiagramResource.getInstance(graph);
511 Resource list = ListUtils.create(graph, DIA.Profile, entries);
513 Resource profile = graph.newResource();
514 graph.claim(profile, L0.InstanceOf, null, DIA.Profile);
515 graph.claimLiteral(profile, L0.HasName, profileName);
516 graph.claim(profile, DIA.HasEntries, null, list);
522 public static Resource createProfile(WriteGraph graph, String profileName, Collection<Resource> entries) throws DatabaseException {
523 return createProfile(graph, profileName, entries.toArray(new Resource[entries.size()]));
526 public static Resource createToplevelProfile(WriteGraph graph, Resource model, String name, Resource ... profiles) throws DatabaseException {
528 Resource work = createProfile(graph, name, profiles);
530 Layer0 L0 = Layer0.getInstance(graph);
531 DiagramResource DIA = DiagramResource.getInstance(graph);
533 graph.deny(model, DIA.HasActiveProfile);
534 graph.claim(model, DIA.HasActiveProfile, work);
535 graph.claim(model, L0.ConsistsOf, L0.PartOf, work);
541 public static Resource createToplevelProfile(WriteGraph graph, Resource model, String name, Collection<Resource> profiles) throws DatabaseException {
542 return createToplevelProfile(graph, model, name, profiles.toArray(new Resource[profiles.size()]));
545 public static void activateProfileEntries(WriteGraph graph, final Resource profile, final Resource ... entries) {
547 VirtualGraphSupport support = graph.getService(VirtualGraphSupport.class);
548 graph.asyncRequest(new WriteRequest(support.getWorkspacePersistent("profiles")) {
551 public void perform(WriteGraph graph) throws DatabaseException {
552 SimulationResource SIMU = SimulationResource.getInstance(graph);
553 for(Resource entry : entries)
554 graph.claim(profile, SIMU.IsActive, entry);
561 public static void activateProfileEntries(WriteGraph graph, Resource profile, Collection<Resource> entries) {
562 activateProfileEntries(graph, profile, entries.toArray(new Resource[entries.size()]));
565 public static void toggleProfileGroup(WriteGraph graph, Resource runtimeProfile, String groupName, boolean enabled) throws DatabaseException {
566 Layer0 L0 = Layer0.getInstance(graph);
567 for (Resource group : ProfileUtils.getProfileChildren(graph, runtimeProfile)) {
568 String name = graph.getRelatedValue2(group, L0.HasName);
569 if (name.equals(groupName)) {
570 toggleProfileGroup(graph, runtimeProfile, group, enabled);
576 public static void toggleProfileGroup(WriteGraph graph, Resource runtimeProfile, Resource group, boolean enabled) throws DatabaseException {
577 DiagramResource DIA = DiagramResource.getInstance(graph);
579 if(graph.isInstanceOf(group, DIA.Profile)) {
581 for(Resource child : ProfileUtils.getProfileChildren(graph, group)) {
582 toggleProfileGroup(graph, runtimeProfile, child, enabled);
585 } else if(graph.isInstanceOf(group, DIA.ProfileEntry)) {
588 graph.claim(runtimeProfile, SimulationResource.getInstance(graph).IsActive, null, group);
590 graph.denyStatement(runtimeProfile, SimulationResource.getInstance(graph).IsActive, group);
596 public static void untrackDependencies() {
597 untrackDependencies(Simantics.getSession());
600 public static void untrackDependencies(RequestProcessor processor) {
603 processor.syncRequest(new ReadRequest() {
606 public void run(ReadGraph graph) throws DatabaseException {
607 Layer0X L0X = Layer0X.getInstance(graph);
608 GenericRelationIndex index = graph.adapt(L0X.DependenciesRelation, GenericRelationIndex.class);
609 index.untrack(graph.getSession(), graph.getRootLibrary());
613 } catch (DatabaseException e) {
614 Logger.defaultLogError(e);
619 public static void trackDependencies() {
620 trackDependencies(Simantics.getSession());
623 public static void trackDependencies(RequestProcessor processor) {
626 processor.syncRequest(new ReadRequest() {
629 public void run(ReadGraph graph) throws DatabaseException {
630 Layer0X L0X = Layer0X.getInstance(graph);
631 GenericRelationIndex index = graph.adapt(L0X.DependenciesRelation, GenericRelationIndex.class);
632 index.trackAndIndex(graph.getSession(), graph.getRootLibrary());
636 } catch (DatabaseException e) {
637 Logger.defaultLogError(e);
642 public static void trackOntologicalRequirements() {
643 Session session = Simantics.getSession();
644 GraphChangeListenerSupport changeListenerSupport = session.getService(GraphChangeListenerSupport.class);
645 changeListenerSupport.addMetadataListener( OntologicalRequirementListener.getInstance() );
648 public static void untrackOntologicalRequirements() {
649 Session session = Simantics.getSession();
650 GraphChangeListenerSupport changeListenerSupport = session.getService(GraphChangeListenerSupport.class);
651 changeListenerSupport.removeMetadataListener( OntologicalRequirementListener.getInstance() );
654 public static class OntologicalRequirementListener extends GenericChangeListener<DependencyChangesRequest, DependencyChanges> {
656 private static OntologicalRequirementListener INSTANCE;
658 public static OntologicalRequirementListener getInstance() {
659 if(INSTANCE == null) {
660 INSTANCE = new OntologicalRequirementListener();
665 private OntologicalRequirementListener() {
668 private OntologicalRequirementTracker changeInformationUpdater = new OntologicalRequirementTracker();
671 public boolean preEventRequest() {
672 return !Indexing.isDependenciesIndexingDisabled();
676 public void onEvent(ReadGraph graph, MetadataI metadata, DependencyChanges event) throws DatabaseException {
677 changeInformationUpdater.update(graph, metadata, event);
682 public static void removeIndex(WriteGraph graph, Resource model) throws DatabaseException {
683 Layer0X L0X = Layer0X.getInstance(graph);
684 IndexedRelations ir = graph.getService(IndexedRelations.class);
685 // Deletes index files
686 ir.reset(null, graph, L0X.DependenciesRelation, model);
689 public static void resetIssueSources(WriteGraph graph, Resource model) throws DatabaseException {
690 Layer0 L0 = Layer0.getInstance(graph);
691 IssueResource ISSUE = IssueResource.getInstance(graph);
692 for(Resource source : graph.sync(new ObjectsWithType(model, L0.ConsistsOf, ISSUE.ContinuousIssueSource))) {
693 IssueSourceUtils.update(graph, source);
697 public static void copyAnnotationTypes(WriteGraph graph, Resource sourceModel, Resource targetModel) throws DatabaseException {
699 Layer0 L0 = Layer0.getInstance(graph);
700 AnnotationResource ANNO = AnnotationResource.getInstance(graph);
702 Instances query = graph.adapt(ANNO.AnnotationType, Instances.class);
704 Resource library = graph.getPossibleObject(targetModel, ANNO.HasAnnotationTypeRoot);
706 if(library == null) {
707 library = graph.newResource();
708 graph.claim(library, L0.InstanceOf, null, ANNO.AnnotationTypeLibrary);
709 graph.claimLiteral(library, L0.HasName, L0.NameOf, L0.String, "Annotation types", Bindings.STRING);
710 graph.claim(library, L0.PartOf, L0.ConsistsOf, targetModel);
711 graph.claim(targetModel, ANNO.HasAnnotationTypeRoot, library);
714 for(Resource type : query.find(graph, sourceModel)) {
715 String name = graph.getRelatedValue(type, L0.HasName);
716 Resource existing = Layer0Utils.getPossibleChild(graph, library, name);
717 if(existing != null) {
718 RemoverUtil.remove(graph, existing);
720 Layer0Utils.copyTo(graph, library, type);
725 public static void deleteIndex(WriteGraph graph, Resource model) throws DatabaseException {
726 Layer0X L0X = Layer0X.getInstance(graph);
727 IndexedRelations ir = graph.getService(IndexedRelations.class);
728 // Deletes index files
729 ir.reset(null, graph, L0X.DependenciesRelation, model);
732 public static void disableDependencies(WriteGraph graph, Resource dummy) {
733 Layer0Utils.setDependenciesIndexingDisabled(graph, true);
736 public static void releaseMemory(WriteGraph graph) {
738 QueryControl qc = graph.getService(QueryControl.class);
739 ClusterControl cc = graph.getService(ClusterControl.class);
745 public static List<Resource> filterByIndexRoot(ReadGraph graph, Resource indexRoot, List<Resource> resources) throws DatabaseException {
746 ArrayList<Resource> result = new ArrayList<Resource>(resources.size());
747 for (Resource r : resources) {
748 Resource root = graph.syncRequest(new PossibleIndexRoot(r));
749 if (indexRoot.equals(root))
755 public static List<Resource> searchByTypeShallow(ReadGraph graph, Resource model, Resource type) throws DatabaseException {
756 return graph.syncRequest(new QueryIndex(model, type, ""), TransientCacheListener.<List<Resource>>instance());
759 public static List<Resource> searchByType(ReadGraph graph, Resource model, Resource type) throws DatabaseException {
760 Instances query = graph.adapt(type, Instances.class);
761 return Layer0Utils.sortByCluster(graph, query.find(graph, model));
764 public static List<Resource> searchByGUID(ReadGraph graph, Resource indexRoot, GUID guid) throws DatabaseException {
765 return searchByGUID(graph, indexRoot, guid.indexString());
768 public static List<Resource> searchByGUID(ReadGraph graph, Resource indexRoot, String indexString) throws DatabaseException {
769 return searchByQueryShallow(graph, indexRoot, "GUID:" + indexString);
772 public static List<Resource> searchByQueryShallow(ReadGraph graph, Resource model, String query) throws DatabaseException {
773 return graph.syncRequest(new QueryIndex(model, Layer0.getInstance(graph).Entity, query), TransientCacheListener.<List<Resource>>instance());
776 public static List<Resource> searchByQuery(ReadGraph graph, Resource model, String query) throws DatabaseException {
777 Instances instances = graph.adapt(Layer0.getInstance(graph).Entity, Instances.class);
778 Collection<Resource> queryResult = instances.find(graph, model, query);
779 return Layer0Utils.sortByCluster(graph, queryResult);
782 public static List<Resource> searchByTypeAndFilter(ReadGraph graph, Resource model, Resource type, Function1<Resource,Boolean> filter) throws DatabaseException {
783 Instances query = graph.adapt(type, Instances.class);
784 ArrayList<Resource> result = new ArrayList<Resource>();
785 for(Resource r : query.find(graph, model)) {
792 public static List<Triple<Resource, Resource, String>> getIndexEntries(ReadGraph graph, Resource model, String filter) throws DatabaseException {
793 Layer0 L0 = Layer0.getInstance(graph);
794 List<Resource> entries = searchByQuery(graph, model, filter);
795 List<Triple<Resource, Resource, String>> listOfTriples = new ArrayList<Triple<Resource,Resource,String>>();
796 for (Resource entry : entries) {
797 Resource type = graph.getPossibleObject(entry, L0.InstanceOf);
798 String name = NameUtils.getSafeName(graph, entry);
799 listOfTriples.add(new Triple<Resource, Resource, String>(entry, type, name));
801 return listOfTriples;
804 public static String listIndexEntries(ReadGraph graph, Resource model, String filter) throws DatabaseException {
805 List<Triple<Resource, Resource, String>> listOfTriples = getIndexEntries(graph, model, filter);
806 StringBuilder sb = new StringBuilder();
807 sb.append("== LISTING INDEX ENTRIES OF INDEX: " + NameUtils.getSafeName(graph, model) + ". AMOUNT OF ENTRIES: " + listOfTriples.size() + " ==\n");
808 for (Triple<Resource, Resource, String> entry : listOfTriples) {
809 String instanceOf = NameUtils.getSafeName(graph, entry.second);
810 sb.append("Name: " + entry.third + " instanceOf: " + instanceOf + " Resource: " + entry.first.toString() + "\n");
812 return sb.toString();
815 public static List<Resource> searchByTypeAndName(ReadGraph graph, Resource model, Resource type, String name) throws DatabaseException {
816 Instances query = graph.adapt(type, Instances.class);
817 ArrayList<Resource> result = new ArrayList<Resource>();
818 for(Resource r : query.findByName(graph, model, name)) {
819 if(graph.isInstanceOf(r, type))
825 public static List<Resource> searchByTypeAndNameShallow(ReadGraph graph, Resource model, Resource type, String name) throws DatabaseException {
826 return graph.syncRequest(new QueryIndex(model, type, name), TransientCacheListener.<List<Resource>>instance());
831 * database write access
832 * @param sourceContainer
833 * the source container to look for annotationProperty from to be
834 * used as the copy source
835 * @param targetContainer
836 * the target container for the copied annotationProperty
838 * @param annotationProperty
839 * the annotation property relation
840 * @return created copy of the original annotation or <code>null</code> if
841 * there was nothing to copy
842 * @throws DatabaseException
844 public static Resource copyPossibleAnnotation(WriteGraph graph, Resource sourceContainer, Resource targetContainer, Resource annotationProperty) throws DatabaseException {
845 return copyPossibleAnnotation2(graph, sourceContainer, targetContainer, annotationProperty, null);
848 public static List<String> getPossibleNamePath(ReadGraph graph, Resource resource) throws DatabaseException {
849 return getPossibleNamePath(graph, resource, null);
852 private static List<String> getPossibleNamePath(ReadGraph graph, Resource resource, List<String> result) throws DatabaseException {
854 Layer0 L0 = Layer0.getInstance(graph);
855 String name = graph.getPossibleRelatedValue(resource, L0.HasName, Bindings.STRING);
856 if(name == null) return null;
858 if(result == null) result = new ArrayList<String>();
860 SimulationResource SIMU = SimulationResource.getInstance(graph);
861 if(graph.isInstanceOf(resource, SIMU.Model)) return result;
863 Resource parent = graph.getPossibleObject(resource, L0.PartOf);
865 getPossibleNamePath(graph, parent, result);
876 public static Resource claimLibraryPath(WriteGraph graph, Resource resource, List<String> path) throws DatabaseException {
877 Layer0 L0 = Layer0.getInstance(graph);
878 for(int i=0;i<path.size()-1;i++) {
879 String p = path.get(i);
880 Resource child = Layer0Utils.getPossibleChild(graph, resource, p);
882 child = graph.newResource();
883 graph.claim(child, L0.InstanceOf, L0.Library);
884 graph.addLiteral(child, L0.HasName, L0.NameOf, L0.String, p, Bindings.STRING);
885 graph.claim(resource, L0.ConsistsOf, L0.PartOf, child);
894 * database write access
895 * @param sourceContainer
896 * the source container to look for annotationProperty from to be
897 * used as the copy source
898 * @param targetContainer
899 * the target container for the copied annotationProperty
901 * @param annotationProperty
902 * the annotation property relation
903 * @param annotationProperty
904 * the 2nd level annotation property relation or
905 * <code>null</code> if no 2nd level annotation exists
906 * @return created copy of the original annotation or <code>null</code> if
907 * there was nothing to copy
908 * @throws DatabaseException
910 public static Resource copyPossibleAnnotation2(WriteGraph graph,
911 Resource sourceContainer, Resource targetContainer,
912 Resource annotationProperty, Resource entryType) throws DatabaseException {
914 // Delete existing target value first
915 Layer0 L0 = Layer0.getInstance(graph);
916 Resource targetValue = graph.getPossibleObject(targetContainer, annotationProperty);
917 if (targetValue != null) {
918 if(!graph.hasStatement(targetValue, L0.PartOf))
919 RemoverUtil.remove(graph, targetValue);
920 graph.deny(targetContainer, annotationProperty);
923 Resource sourceValue = graph.getPossibleObject(sourceContainer, annotationProperty);
924 if (sourceValue == null)
927 List<String> sourceValuePath = getPossibleNamePath(graph, sourceValue);
928 if(sourceValuePath != null) {
929 Resource targetModel = graph.sync(new PossibleModel(targetContainer));
930 if(targetModel == null) throw new DatabaseException("No target model found for " + targetContainer);
931 Resource library = claimLibraryPath(graph, targetModel, sourceValuePath);
932 Resource existing = Layer0Utils.getPossibleChild(graph, library, sourceValuePath.get(sourceValuePath.size()-1));
933 if(existing == null) {
934 existing = doCopyPossibleAnnotation2(graph, sourceContainer, targetContainer, annotationProperty, entryType);
935 graph.claim(library, L0.ConsistsOf, L0.PartOf, existing);
937 graph.claim(targetContainer, annotationProperty, existing);
940 return doCopyPossibleAnnotation2(graph, sourceContainer, targetContainer, annotationProperty, entryType);
945 private static Resource doCopyPossibleAnnotation2(WriteGraph graph,
946 Resource sourceContainer, Resource targetContainer,
947 Resource annotationProperty, Resource entryType) throws DatabaseException {
949 Resource sourceValue = graph.getPossibleObject(sourceContainer, annotationProperty);
950 if (sourceValue == null)
953 // Copy 1st level annotation
954 Resource targetValue = createAnnotation(graph, targetContainer, annotationProperty, sourceValue);
956 // Copy possible 2nd level annotations and attach to 1st if entry
957 // property is defined.
958 Layer0 L0 = Layer0.getInstance(graph);
959 if (entryType != null) {
961 AnnotationResource ANNO = AnnotationResource.getInstance(graph);
962 for (Resource entry : graph.getObjects(sourceValue, ANNO.Annotation_HasEntry)) {
964 String name = graph.getRelatedValue(entry, L0.HasName, Bindings.STRING);
966 List<String> entryPath = getPossibleNamePath(graph, entry);
967 if(entryPath != null) {
968 Resource targetModel = graph.sync(new PossibleModel(targetContainer));
969 if(targetModel == null) throw new DatabaseException("No target model found for " + targetContainer);
970 Resource library = claimLibraryPath(graph, targetModel, entryPath);
971 Resource existing = Layer0Utils.getPossibleChild(graph, library, entryPath.get(entryPath.size()-1));
972 if(existing == null) {
973 existing = createTypedAnnotation(graph, null, null, entry, entryType, name);
974 graph.claim(library, L0.ConsistsOf, L0.PartOf, existing);
976 graph.claim(targetValue, ANNO.Annotation_HasEntry, existing);
978 Resource result = createTypedAnnotation(graph, null, null, entry, entryType, name);
979 graph.claim(targetValue, ANNO.Annotation_HasEntry, result);
991 * database write access
993 * the container resource to attach the new annotation to
995 * the annotation property relation. The type of the created
996 * annotation is decided from this property relation's range
997 * @param sourceAnnotation
998 * the annotation to copy data from or <code>null</code> if
999 * nothing shall be copied
1000 * @return the newly created annotation resource or <code>null</code> if the
1001 * annotation property relation didn't have a single range type
1002 * @throws DatabaseException
1004 public static Resource createAnnotation(WriteGraph graph, Resource container, Resource property, Resource sourceAnnotation) throws DatabaseException {
1005 return createAnnotation(graph, container, property, sourceAnnotation, null);
1010 * database write access
1012 * the container resource to attach the new annotation to
1014 * the annotation property relation. The type of the created
1015 * annotation is decided from this property relation's range
1016 * @param sourceAnnotation
1017 * the annotation to copy data from or <code>null</code> if
1018 * nothing shall be copied
1020 * name for newly created annotation or <code>null</code> to copy
1021 * name from source if available
1022 * @return the newly created annotation resource or <code>null</code> if the
1023 * annotation property relation didn't have a single range type
1024 * @throws DatabaseException
1026 public static Resource createAnnotation(WriteGraph graph, Resource container, Resource property, Resource sourceAnnotation, String name) throws DatabaseException {
1028 Layer0 L0 = Layer0.getInstance(graph);
1029 Resource annotationType = graph.getSingleObject(property, L0.HasRange);
1030 if (annotationType == null)
1033 return createTypedAnnotation(graph, container, property, sourceAnnotation, annotationType, name);
1039 * database write access
1041 * the container resource to attach the new annotation to
1043 * the annotation property relation
1044 * @param sourceAnnotation
1045 * the annotation to copy data from or <code>null</code> if
1046 * nothing shall be copied
1047 * @param annotationType
1048 * the type of the new annotation
1049 * @return the newly created annotation resource
1050 * @throws DatabaseException
1052 public static Resource createTypedAnnotation(WriteGraph graph, Resource container, Resource property, Resource sourceAnnotation, Resource annotationType) throws DatabaseException {
1053 return createTypedAnnotation(graph, container, property, sourceAnnotation, annotationType, null);
1058 * database write access
1060 * the container resource to attach the new annotation to
1062 * the annotation property relation
1063 * @param sourceAnnotation
1064 * the annotation to copy data from or <code>null</code> if
1065 * nothing shall be copied
1066 * @param annotationType
1067 * the type of the new annotation
1069 * name for newly created annotation or <code>null</code> to copy
1070 * name from source if available
1071 * @return the newly created annotation resource
1072 * @throws DatabaseException
1074 public static Resource createTypedAnnotation(WriteGraph graph, Resource container, Resource property, Resource sourceAnnotation, Resource annotationType, String name) throws DatabaseException {
1076 Layer0 L0 = Layer0.getInstance(graph);
1078 Resource anno = graph.newResource();
1080 graph.claim(anno, L0.InstanceOf, null, annotationType);
1083 graph.addLiteral(anno, L0.HasName, L0.NameOf, L0.String, name, Bindings.STRING);
1085 if (sourceAnnotation != null) {
1088 String sourceName = graph.getPossibleRelatedValue(sourceAnnotation, L0.HasName, Bindings.STRING);
1089 if(sourceName != null) graph.addLiteral(anno, L0.HasName, L0.NameOf, L0.String, sourceName, Bindings.STRING);
1092 Resource sourceType = graph.getSingleType(sourceAnnotation);
1093 List<AnnotationMap> am = getAnnotationMap(graph, annotationType, sourceType);
1094 for (AnnotationMap a : am) {
1095 Resource object = graph.getSingleObject(sourceAnnotation, a.sourcePredicate);
1096 Collection<Resource> objectTypes = graph.getTypes(object);
1097 if (objectTypes.contains(L0.Literal)) {
1098 Object value = graph.getValue(object, a.defaultValueBinding);
1099 if (!ObjectUtils.objectEquals(value, a.defaultValue)) {
1100 graph.addLiteral(anno, a.annotationPredicate, a.annotationPredicateInverse, a.defaultValueType, value, a.defaultValueBinding);
1106 if (container != null && property != null) {
1107 graph.claim(container, property, anno);
1114 private static class AnnotationMap {
1116 final public Resource sourcePredicate;
1117 final public Resource sourcePredicateInverse;
1119 final public Resource annotationPredicate;
1120 final public Resource annotationPredicateInverse;
1122 final public Resource defaultValueType;
1123 final public Object defaultValue;
1124 final public Binding defaultValueBinding;
1126 public AnnotationMap(Resource sp, Resource spi, Resource tp, Resource tpi, Resource defaultValueType, Object defaultValue, Binding defaultValueBinding) {
1127 sourcePredicate = sp;
1128 sourcePredicateInverse = spi;
1129 annotationPredicate = tp;
1130 annotationPredicateInverse = tpi;
1131 this.defaultValueType = defaultValueType;
1132 this.defaultValue = defaultValue;
1133 this.defaultValueBinding = defaultValueBinding;
1138 public static List<AnnotationMap> getAnnotationMap(ReadGraph graph, Resource annotationType, Resource sourceType) throws DatabaseException {
1139 return graph.syncRequest(new AnnotationMapRequest(annotationType, sourceType), TransientCacheListener.<List<AnnotationMap>>instance());
1142 static class AnnotationMapRequest extends ResourceRead2<List<AnnotationMap>> {
1144 public AnnotationMapRequest(Resource annotationType, Resource sourceType) {
1145 super(annotationType, sourceType);
1149 public List<AnnotationMap> perform(ReadGraph graph) throws DatabaseException {
1151 Layer0 L0 = Layer0.getInstance(graph);
1153 ArrayList<AnnotationMap> result = new ArrayList<AnnotationMap>();
1155 Map<String, Resource> annotationPredicates = new HashMap<String, Resource>();
1156 for(Resource predicate : graph.getObjects(resource, L0.DomainOf)) {
1157 String name = graph.getRelatedValue(predicate, L0.HasName, Bindings.STRING);
1158 annotationPredicates.put(name, predicate);
1160 Map<String, Resource> sourcePredicates = new HashMap<String, Resource>();
1161 for(Resource predicate : graph.getObjects(resource2, L0.DomainOf)) {
1162 String name = graph.getRelatedValue(predicate, L0.HasName, Bindings.STRING);
1163 sourcePredicates.put(name, predicate);
1166 for(String key : sourcePredicates.keySet()) {
1167 Resource sourcePredicate = sourcePredicates.get(key);
1168 Resource anno = annotationPredicates.get(key);
1169 if(sourcePredicate != null && anno != null) {
1170 Resource defaultValueType = graph.getSingleObject(anno, L0.HasRange);
1171 Binding defaultValueBinding = null;
1172 Object defaultValue = null;
1173 Resource assertion = graph.getPossibleObject(anno, L0.HasPredicateInverse);
1174 if (assertion != null) {
1175 Resource object = graph.getPossibleObject(assertion, L0.HasObject);
1176 if (object != null) {
1177 if(graph.isInstanceOf(object, L0.Literal)) {
1178 Datatype dt = graph.getDataType(object);
1179 defaultValueBinding = Bindings.getBeanBinding(dt);
1180 defaultValue = graph.getPossibleValue(object);
1184 result.add(new AnnotationMap(
1185 sourcePredicate, graph.getInverse(sourcePredicate),
1186 anno, graph.getInverse(anno),
1187 defaultValueType, defaultValue, defaultValueBinding));
1197 public static final String DRAWING_TEMPLATE_FORMAT = "drawingTemplate";
1198 public static final String DRAWING_TEMPLATE_FORMAT_V1 = DRAWING_TEMPLATE_FORMAT + ":1";
1199 public static final String DRAWING_TEMPLATE_FORMAT_V2 = DRAWING_TEMPLATE_FORMAT + ":2";
1201 public static Resource importDrawingTemplate(final Resource model, final File file) throws IOException, SerializationException, DatabaseException, TransferableGraphException {
1205 final Resource library = Simantics.sync(new WriteResultRequest<Resource>() {
1208 public Resource perform(WriteGraph graph) throws DatabaseException {
1210 Layer0 L0 = Layer0.getInstance(graph);
1211 Template2dResource TEMPLATE = Template2dResource.getInstance(graph);
1212 Resource root = graph.getPossibleObject(model, TEMPLATE.HasDrawingTemplateRoot);
1214 Template2dResource TEMPLATE2D = Template2dResource.getInstance(graph);
1215 root = graph.newResource();
1216 graph.claim(root, L0.InstanceOf, null, TEMPLATE2D.DrawingTemplateLibrary);
1217 graph.claim(root, L0.InstanceOf, null, TEMPLATE2D.DrawingTemplateLibraryUI);
1218 graph.claimLiteral(root, L0.HasName, L0.NameOf, L0.String, "Diagram Templates", Bindings.STRING);
1219 graph.claim(root, L0.PartOf, L0.ConsistsOf, model);
1220 graph.claim(model, TEMPLATE2D.HasDrawingTemplateRoot, root);
1223 String name = new Path(file.getAbsolutePath()).removeFileExtension().lastSegment();
1225 Resource existing = Layer0Utils.getPossibleChild(graph, root, name);
1226 if(existing != null)
1227 graph.deny(root, L0.ConsistsOf, existing);
1236 final DefaultPasteImportAdvisor advisor = new DefaultPasteImportAdvisor(library);
1239 HashMap<String, FormatHandler<Object>> handlers = new HashMap<String, FormatHandler<Object>>();
1240 FormatHandler<Object> handler = new FormatHandler<Object>() {
1242 public Binding getBinding() {
1243 return TransferableGraph1.BINDING;
1247 public Object process(DataContainer container) throws Exception {
1248 TransferableGraphs.importGraph1(Simantics.getSession(), (TransferableGraph1)container.content.getValue(),
1253 handlers.put(DRAWING_TEMPLATE_FORMAT_V1, handler);
1254 handlers.put(DRAWING_TEMPLATE_FORMAT_V2, handler);
1256 DataContainers.readFile(file, handlers);
1257 } catch(DataFormatException e) {
1258 throw new IOException(e);
1259 } catch(IOException e) {
1261 } catch(Exception e) {
1262 if(e instanceof RuntimeException)
1263 throw (RuntimeException)e;
1265 throw new RuntimeException(e);
1268 } catch(IOException e) {
1271 return advisor.getRoot();
1273 } catch (Throwable t) {
1274 Logger.defaultLogError("Unexpected exception while importing diagram template.", t);
1282 public static Collection<Variable> getMappedVariables(ReadGraph graph, Variable source) throws DatabaseException {
1284 ArrayList<Variable> result = new ArrayList<Variable>();
1285 Resource represents = source.getPossibleRepresents(graph);
1286 if(represents == null) return Collections.emptyList();
1287 ModelingResources MOD = ModelingResources.getInstance(graph);
1288 for(Resource r : getElementCorrespondendences(graph, represents)) {
1289 result.add(Variables.getVariable(graph, r));
1291 for(Resource r : graph.getObjects(represents, MOD.ComponentToElement)) {
1292 result.add(Variables.getVariable(graph, r));
1294 for(Resource r : graph.getObjects(represents, MOD.DiagramToComposite)) {
1295 result.add(Variables.getVariable(graph, r));
1297 for(Resource r : graph.getObjects(represents, MOD.CompositeToDiagram)) {
1298 result.add(Variables.getVariable(graph, r));
1304 public static Resource getPossibleModel(ReadGraph graph, Resource resource) throws DatabaseException {
1306 PossibleModel pm = new PossibleModel(resource);
1307 Resource model = pm.perform(graph);
1311 public static Resource possibleIndexRoot(ReadGraph graph, Resource resource) throws DatabaseException {
1312 return graph.syncRequest(new PossibleIndexRoot(resource));
1315 public static Object getMonitorValue(StructuralComponent _variable, ReadGraph graph, String path) throws DatabaseException {
1316 Variable variable = ((VariableStructuralContext)_variable).variable;
1317 Variable var = variable.browse(graph, path);
1318 return var.getValue(graph);
1321 public static void createSharedOntologyWithUI(ReadGraph graph, Variable variable, Resource baseType) throws DatabaseException {
1322 createSharedOntologyWithUI(graph, baseType);
1325 public static void createSharedOntologyWithUI(ReadGraph graph, Resource baseType) throws DatabaseException {
1327 // Resource indexRoot_ = variable.getPossibleRepresents(graph);
1328 // if(indexRoot_ == null) return;
1330 final Map<Resource, Pair<String,ImageDescriptor>> map = new HashMap<Resource, Pair<String,ImageDescriptor>>();
1332 Layer0 L0 = Layer0.getInstance(graph);
1333 SimulationResource SIMU = SimulationResource.getInstance(graph);
1334 Instances query = graph.adapt(L0.IndexRootType, Instances.class);
1335 for(Resource ontology : Layer0Utils.listOntologies(graph)) {
1336 for(Resource type : query.find(graph, ontology)) {
1337 if(graph.isInheritedFrom(type, SIMU.Model)) continue;
1338 if(graph.hasStatement(type, L0.Abstract)) continue;
1339 if(!graph.isInheritedFrom(type, baseType)) continue;
1340 String name = graph.getPossibleRelatedValue(type, L0.HasLabel, Bindings.STRING);
1341 if(name == null) name = graph.getRelatedValue(type, L0.HasName, Bindings.STRING);
1342 map.put(type, new Pair<String,ImageDescriptor>(name, null));
1346 Display.getDefault().asyncExec(new Runnable() {
1349 Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();
1350 CreateSharedOntologyDialog page = new CreateSharedOntologyDialog(shell, map, "Select type and name of new shared library");
1351 if (page.open() == Window.OK) {
1352 Object[] result = page.getResult();
1353 if (result != null && result.length == 1) {
1354 final Resource res = (Resource)result[0];
1355 final String name = "http://" + page.getName();
1356 Simantics.getSession().asyncRequest(new WriteRequest() {
1359 public void perform(WriteGraph graph) throws DatabaseException {
1360 graph.markUndoPoint();
1361 Resource target = Simantics.applySCL("Simantics/SharedOntologies", "createSharedOntology", graph, name+"@A", res);
1363 ProjectResource PROJ = ProjectResource.getInstance(graph);
1364 Layer0 L0 = Layer0.getInstance(graph);
1365 for(Resource dep : graph.getObjects(Simantics.getProjectResource(), L0.IsLinkedTo)) {
1366 if(graph.isInstanceOf(dep, PROJ.NamespaceRequirement)) {
1367 for(Resource req : graph.getObjects(dep, PROJ.RequiresNamespace)) {
1368 String uri = graph.getPossibleValue(req, Bindings.STRING);
1370 Resource ns = graph.getResource(uri);
1372 graph.claim(target, L0.IsLinkedTo, null, ns);
1389 public static void unlinkSharedOntologyWithUI(ReadGraph graph, Variable variable, final List<Resource> libraries) throws DatabaseException {
1391 final Resource indexRoot = variable.getPossibleRepresents(graph);
1392 if(indexRoot == null) return;
1394 StructuralResource2 STR = StructuralResource2.getInstance(graph);
1396 final List<String> instances = new ArrayList<String>();
1398 DiagramResource DIA = DiagramResource.getInstance(graph);
1400 for(Resource library : libraries) {
1401 for(Resource type : ModelingUtils.searchByTypeShallow(graph, library, STR.ComponentType)) {
1402 for(Resource instance : ModelingUtils.searchByTypeShallow(graph, indexRoot, type)) {
1404 if(graph.isInstanceOf(instance, DIA.Element)) continue;
1405 String name = Versions.getStandardPathNameString(graph, instance);
1406 instances.add(name);
1411 if(instances.isEmpty()) {
1412 graph.getSession().asyncRequest(new WriteRequest() {
1415 public void perform(WriteGraph graph) throws DatabaseException {
1416 Layer0 L0 = Layer0.getInstance(graph);
1417 for(Resource library : libraries)
1418 graph.deny(indexRoot, L0.IsLinkedTo, library);
1425 PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
1429 if (!PlatformUI.isWorkbenchRunning())
1432 Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();
1433 ListDialog<String> dialog = new ListDialog<String>(
1436 "Cannot unlink selected libraries",
1437 "Libraries cannot be unlinked since the following instances are referring to them.") {
1439 protected void createButtonsForButtonBar(Composite parent) {
1440 createButton(parent, IDialogConstants.OK_ID, IDialogConstants.OK_LABEL,true);
1444 int result = dialog.open();
1445 if (result != Dialog.OK)
1453 public static void importSharedOntology(String fileName) throws Exception {
1455 DataContainer dc = DataContainers.readFile(new File(fileName));
1456 TransferableGraph1 tg = (TransferableGraph1)dc.content.getValue(TransferableGraph1.BINDING);
1457 Variant draftStatus = dc.metadata.get(DraftStatusBean.EXTENSION_KEY);
1458 MigrationUtils.importSharedOntology(Simantics.getSession(), tg, draftStatus == null);
1459 } catch (Exception e) {
1460 Logger.defaultLogError(e);
1465 public static void importSharedOntologyWithUI(ReadGraph graph, final Variable variable) throws DatabaseException {
1467 Display.getDefault().asyncExec(new Runnable() {
1471 IStructuredSelection sel = new StructuredSelection(variable);
1472 openWizard(Display.getCurrent(), sel, "org.simantics.modeling.ui.sharedOntologyImportWizard");
1479 public static class LibraryInfo implements Comparable<LibraryInfo> {
1480 public NamedResource library;
1481 public DraftStatusBean draft;
1482 public LibraryInfo(String name, Resource r, DraftStatusBean draft) {
1483 library = new NamedResource(name, r);
1487 public int compareTo(LibraryInfo o) {
1488 return library.compareTo(o.library);
1491 public int hashCode() {
1492 return library.hashCode();
1495 public boolean equals(Object object) {
1498 else if (object == null)
1500 else if (!(object instanceof LibraryInfo))
1502 LibraryInfo info = (LibraryInfo)object;
1503 return info.library.equals(library);
1508 public static void exportSharedOntologyWithUI(final Resource sharedOntology) {
1510 Display.getDefault().asyncExec(new Runnable() {
1514 HintContext hc = new HintContext();
1515 hc.setHint(SelectionHints.KEY_MAIN, sharedOntology);
1516 IStructuredSelection sel = new StructuredSelection(hc);
1517 openWizard(Display.getCurrent(), sel, "org.simantics.modeling.ui.sharedOntologyExportWizard");
1524 public static TransferableGraph1 exportSharedOntology(IProgressMonitor monitor, RequestProcessor processor, File location, String format, int version, final LibraryInfo info) throws DatabaseException, IOException {
1526 if(monitor == null) monitor = new NullProgressMonitor();
1528 // TODO: figure out a way to make the TG go directly into a file
1529 // instead of having it all in memory at once.
1531 monitor.beginTask("Exporting shared library...", 100);
1532 SimanticsClipboard clipboard = processor.syncRequest(new Read<SimanticsClipboard>() {
1534 public SimanticsClipboard perform(ReadGraph graph) throws DatabaseException {
1535 CopyHandler ch = graph.adapt(info.library.getResource(), CopyHandler.class);
1536 SimanticsClipboardImpl clipboard = new SimanticsClipboardImpl();
1537 ch.copyToClipboard(graph, clipboard);
1542 TreeMap<String,Variant> metadata = getExportMetadata();
1543 DraftStatusBean draft = info.draft;
1545 metadata.put(DraftStatusBean.EXTENSION_KEY, new Variant(DraftStatusBean.BINDING ,draft));
1548 for (Set<Representation> object : clipboard.getContents()) {
1550 TransferableGraph1 tg = ClipboardUtils.accept(processor, object, SimanticsKeys.KEY_TRANSFERABLE_GRAPH);
1553 Variant edb = tg.extensions.get(ExternalDownloadBean.EXTENSION_KEY);
1555 metadata.put(ExternalDownloadBean.EXTENSION_KEY, edb);
1558 if(location != null) {
1559 monitor.setTaskName("Writing transferable graph...");
1560 DataContainers.writeFile(location, new DataContainer(
1562 metadata, new Variant(TransferableGraph1.BINDING, tg)));
1570 throw new DatabaseException("Failed to export");
1574 public static TreeMap<String, Variant> getExportMetadata() {
1576 TreeMap<String,Variant> metadata = new TreeMap<String,Variant>();
1577 metadata.put("date", Variant.ofInstance(DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL).format(new Date())));
1578 metadata.put("author", Variant.ofInstance(System.getProperty("user.name", "")));
1584 public static void createNewVersionWithoutUI(WriteGraph graph, Resource resource) throws DatabaseException {
1585 VersionInfo info = graph.syncRequest(new VersionInfoRequest(resource));
1586 int currentVersion = Integer.parseInt(info.version);
1587 String result = Integer.toString(currentVersion + 1);
1588 createNewVersion(graph, resource, info, result);
1591 public static void createNewVersionWithUI(ReadGraph graph, final Resource resource) throws DatabaseException {
1593 final VersionInfo info = graph.syncRequest(new VersionInfoRequest(resource));
1595 Display.getDefault().asyncExec(new Runnable() {
1598 Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();
1599 CreateVersionDialog dialog = new CreateVersionDialog(shell, info);
1600 if (dialog.open() == Window.OK) {
1601 final String result = dialog.getResult();
1602 Simantics.getSession().asyncRequest(new WriteRequest() {
1604 public void perform(WriteGraph graph) throws DatabaseException {
1605 createNewVersion(graph, resource, info, result);
1614 public static void createNewVersion(WriteGraph graph, Resource resource, final VersionInfo info, final String result) throws DatabaseException {
1615 graph.markUndoPoint();
1616 Layer0 L0 = Layer0.getInstance(graph);
1617 Resource parent = graph.getPossibleObject(resource, L0.PartOf);
1618 if(parent == null) return;
1619 final String parentURI = graph.getPossibleURI(parent);
1620 if(parentURI == null) return;
1621 Layer0Utils.copyTo(graph, parent, resource, new PasteEventHandler() {
1624 public void postProcess(WriteGraph graph, Resource root) throws DatabaseException {
1625 Layer0 L0 = Layer0.getInstance(graph);
1626 graph.deny(root, L0.Entity_published);
1630 public IImportAdvisor2 createAdvisor(ReadGraph graph, ImportAdvisorFactory factory, Resource target) throws DatabaseException {
1631 Map<String,Object> context = new HashMap<String,Object>();
1632 String base = parentURI + "/" + URIStringUtils.escape( info.baseName ) + "@";
1633 Map<String,String> renameMap = new HashMap<String,String>();
1634 renameMap.put(base + info.version, base + result);
1635 renameMap.put(info.baseName + "@" + info.version, info.baseName + "@" + result);
1636 context.put(ImportAdvisors.RENAME_MAP, renameMap);
1637 return factory.create(graph, target, context);
1641 Layer0Utils.addCommentMetadata(graph, "Created new version of " + info.baseName);
1644 public static boolean isUserComponent(ReadGraph graph, Resource type) throws DatabaseException {
1645 StructuralResource2 STR = StructuralResource2.getInstance(graph);
1646 if(graph.isInstanceOf(type, STR.ProceduralComponentType)) return true;
1647 else if (graph.hasStatement(type, STR.IsDefinedBy)) return true;
1651 public static void publishComponentTypeWithUI(WriteGraph graph, final Resource componentType) throws DatabaseException {
1653 Layer0 L0 = Layer0.getInstance(graph);
1654 StructuralResource2 STR = StructuralResource2.getInstance(graph);
1655 Resource composite = graph.getPossibleObject(componentType, STR.IsDefinedBy);
1656 final List<String> instances = new ArrayList<String>();
1657 if(composite != null) {
1658 for(Resource component : graph.syncRequest(new ObjectsWithType(composite, L0.ConsistsOf, STR.Component))) {
1659 Resource type = graph.getPossibleType(component, STR.Component);
1660 if(type != null && isUserComponent(graph, type)) {
1661 if(!Layer0Utils.isPublished(graph, type)) instances.add(Versions.getStandardPathNameString(graph, component));
1666 if(instances.isEmpty()) {
1667 graph.getSession().asyncRequest(new WriteRequest() {
1670 public void perform(WriteGraph graph) throws DatabaseException {
1671 graph.markUndoPoint();
1672 publish(graph, componentType);
1679 PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
1683 if (!PlatformUI.isWorkbenchRunning())
1686 Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();
1687 ListDialog<String> dialog = new ListDialog<String>(
1690 "Cannot publish user component",
1691 "The following instances are referring to unpublished user components.") {
1693 protected void createButtonsForButtonBar(Composite parent) {
1694 createButton(parent, IDialogConstants.OK_ID, IDialogConstants.OK_LABEL,true);
1698 int result = dialog.open();
1699 if (result != Dialog.OK)
1707 public static void publishSharedOntologyWithUI(WriteGraph graph, final Resource sharedOntology) throws DatabaseException {
1709 Layer0 L0 = Layer0.getInstance(graph);
1710 DiagramResource DIA = DiagramResource.getInstance(graph);
1711 StructuralResource2 STR = StructuralResource2.getInstance(graph);
1712 final List<String> instances = new ArrayList<String>();
1713 for(Resource type : searchByTypeShallow(graph, sharedOntology, STR.ComponentType)) {
1715 if(graph.isInheritedFrom(type, DIA.Element)) continue;
1716 if(!Layer0Utils.isPublished(graph, type)) instances.add(Versions.getStandardPathNameString(graph, type));
1718 for(Resource dep : graph.syncRequest(new ObjectsWithType(sharedOntology, L0.IsLinkedTo, L0.SharedOntology))) {
1719 if(!Layer0Utils.isPublished(graph, dep)) instances.add(Versions.getStandardPathNameString(graph, dep));
1722 if(instances.isEmpty()) {
1723 graph.getSession().asyncRequest(new WriteRequest() {
1726 public void perform(WriteGraph graph) throws DatabaseException {
1727 graph.markUndoPoint();
1728 publish(graph, sharedOntology);
1735 PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
1739 if (!PlatformUI.isWorkbenchRunning())
1742 Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();
1743 ListDialog<String> dialog = new ListDialog<String>(
1746 "Cannot publish shared library",
1747 "The following dependencies are unpublished.") {
1749 protected void createButtonsForButtonBar(Composite parent) {
1750 createButton(parent, IDialogConstants.OK_ID, IDialogConstants.OK_LABEL,true);
1754 int result = dialog.open();
1755 if (result != Dialog.OK)
1764 public static void createSCLModuleDefault(WriteGraph graph, Resource target) throws DatabaseException {
1765 String name = NameUtils.findFreshEscapedName(graph, "SCLModule", target);
1766 createSCLModule(graph, target, name);
1769 public static void createSCLModule(WriteGraph graph, Resource target, String name) throws DatabaseException {
1770 graph.markUndoPoint();
1771 Layer0 L0 = Layer0.getInstance(graph);
1772 Resource sclModule = GraphUtils.create2(graph, L0.SCLModule,
1775 L0.SCLModule_definition, "");
1776 Layer0Utils.addCommentMetadata(graph, "Created SCL Module " + name + " " + sclModule.toString());
1779 public static void createSCLScriptDefault(WriteGraph graph, Resource target) throws DatabaseException {
1780 String name = NameUtils.findFreshEscapedName(graph, "SCLScript", target);
1781 createSCLScript(graph, target, name);
1784 public static void 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,
1790 L0.SCLScript_definition, "");
1791 Layer0Utils.addCommentMetadata(graph, "Created SCL Script " + name + " " + sclModule.toString());
1794 public static void createPGraphDefault(WriteGraph graph, Resource target) throws DatabaseException {
1795 String name = NameUtils.findFreshEscapedName(graph, "Ontology Definition File", target);
1796 createPGraph(graph, target, name);
1799 public static void createPGraph(WriteGraph graph, Resource target, String name) throws DatabaseException {
1800 graph.markUndoPoint();
1801 Layer0 L0 = Layer0.getInstance(graph);
1802 Resource file = GraphUtils.create2(graph, L0.PGraph,
1805 L0.PGraph_definition, "");
1806 Layer0Utils.addCommentMetadata(graph, "Created Ontology Definition File " + name + " " + file.toString());
1809 public static void publish(WriteGraph graph, Resource target) throws DatabaseException {
1810 Layer0 L0 = Layer0.getInstance(graph);
1811 graph.claimLiteral(target, L0.Entity_published, true, Bindings.BOOLEAN);
1812 Layer0Utils.addCommentMetadata(graph, "Published " + graph.getPossibleRelatedValue2(target, L0.HasName, Bindings.STRING) + " " + target.toString());
1815 public static boolean isLinkedToDeep(ReadGraph graph, Resource r1, Resource r2) throws DatabaseException {
1816 return graph.syncRequest(new IsLinkedTo(r1, r2));
1819 public static void openWizard(Display display, IStructuredSelection selection, String id) {
1820 // First see if this is a "new wizard".
1821 IWizardDescriptor descriptor = PlatformUI.getWorkbench()
1822 .getNewWizardRegistry().findWizard(id);
1823 // If not check if it is an "import wizard".
1824 if (descriptor == null) {
1825 descriptor = PlatformUI.getWorkbench().getImportWizardRegistry()
1828 // Or maybe an export wizard
1829 if (descriptor == null) {
1830 descriptor = PlatformUI.getWorkbench().getExportWizardRegistry()
1834 // Then if we have a wizard, open it.
1835 if (descriptor != null) {
1836 IWorkbenchWizard wizard = descriptor.createWizard();
1837 wizard.init(PlatformUI.getWorkbench(), selection);
1838 WizardDialog wd = new WizardDialog(display.getActiveShell(), wizard);
1839 wd.setTitle(wizard.getWindowTitle());
1842 } catch (CoreException e) {
1843 e.printStackTrace();
1847 public static String withinEpsilon(double value, double reference, double epsilon) {
1848 if(Math.abs(value-reference) < epsilon) return "True";
1849 else return "Not within epsilon value=" + value + ", reference=" + reference + " , epsilon=" + epsilon;
1852 public static boolean needsIdentifier(ReadGraph graph, Resource r) throws DatabaseException {
1853 Layer0 L0 = Layer0.getInstance(graph);
1854 Collection<Resource> types = graph.getPrincipalTypes(r);
1855 for(Resource type : types)
1856 if(graph.syncRequest(new IsInstanceOf(type, L0.TypeWithIdentifier), TransientCacheAsyncListener.<Boolean>instance()))
1861 public static boolean needsModificationInfo(ReadGraph graph, Resource r) throws DatabaseException {
1862 ModelingResources MOD = ModelingResources.getInstance(graph);
1863 Collection<Resource> types = graph.getPrincipalTypes(r);
1864 for(Resource type : types)
1865 if(graph.syncRequest(new IsInstanceOf(type, MOD.TypeWithChangeInformation), TransientCacheAsyncListener.<Boolean>instance()))
1870 public static void attachCreationInformation(IProgressMonitor monitor, WriteGraph graph, Resource model) throws DatabaseException {
1872 if(monitor == null) monitor = new NullProgressMonitor();
1874 final String author = System.getProperty("user.name", "");
1875 final long time = System.currentTimeMillis();
1877 monitor.setTaskName("Attach creation information");
1879 ModelingResources MOD = ModelingResources.getInstance(graph);
1880 Collection<Resource> rs = ModelingUtils.searchByType(graph, model, MOD.TypeWithChangeInformation);
1881 Collection<Resource> supers = ModelingUtils.getMostUnspecificTypes(graph, rs);
1883 CollectionSupport cs = graph.getService(CollectionSupport.class);
1884 Collection<Resource> set = cs.createSet();
1885 for(Resource type : supers) {
1886 set.addAll(ModelingUtils.searchByTypeShallow(graph, model, type));
1888 Collection<Resource> instances = Layer0Utils.sortByCluster(graph, set);
1890 int pc = instances.size() / 100;
1894 for(Resource instance : instances) {
1895 ChangeInformation info = graph.getPossibleRelatedValue(instance, MOD.changeInformation, ChangeInformation.BINDING);
1897 info = new ChangeInformation();
1898 info.createdAt = time;
1899 info.createdBy = author;
1900 info.modifiedAt = time;
1901 info.modifiedBy = author;
1902 graph.claimLiteral(instance, MOD.changeInformation, MOD.changeInformation_Inverse, MOD.ChangeInformation, info, ChangeInformation.BINDING);
1907 Double d = (100.0*done)/instances.size();
1908 monitor.setTaskName("Attach creation information " + d.intValue() + "%");
1913 monitor.setTaskName("Attach creation information - commit");
1917 public static class DiagramComponentInfo {
1919 private static String CHILD_PREFIX = "child:";
1921 final private String compositePathAndName;
1922 final private String componentName;
1923 final private GUID guid;
1925 public DiagramComponentInfo(String compositePathAndName, String componentName, GUID guid) {
1926 this.compositePathAndName = compositePathAndName;
1927 this.componentName = componentName;
1931 public static boolean isDiagramComponent(String tgName) {
1932 return tgName.startsWith(CHILD_PREFIX);
1935 public String getTGName(CompositeInfo info) {
1936 return CHILD_PREFIX + info.getOriginalPath() + ModelingUtils.COMPOSITE_SEPARATOR_CHAR + info.getEscapedName() + ModelingUtils.COMPOSITE_SEPARATOR_CHAR + getEscapedComponentName() + ModelingUtils.COMPOSITE_SEPARATOR_CHAR + guid.indexString();
1939 public boolean existsGUID(ReadGraph graph, Resource indexRoot) throws DatabaseException {
1940 Collection<Resource> res = ModelingUtils.searchByGUID(graph, indexRoot, guid);
1941 return !res.isEmpty();
1944 public static DiagramComponentInfo fromResource(ReadGraph graph, CompositeInfo info, Resource resource) throws DatabaseException {
1945 Layer0 L0 = Layer0.getInstance(graph);
1946 GUID childId = graph.getRelatedValue(resource, L0.identifier, GUID.BINDING);
1947 String childName = graph.getRelatedValue(resource, L0.HasName, Bindings.STRING);
1948 return new DiagramComponentInfo(info.getStateKey(), URIStringUtils.escape(childName), childId);
1951 public GUID getGUID() {
1955 public String getEscapedCompositePathAndName() {
1956 return compositePathAndName;
1959 public String getEscapedComponentName() {
1960 return componentName;
1963 public String getUnescapedComponentName() {
1964 return URIStringUtils.unescape(getEscapedComponentName());
1967 // "child:path#compositeName#componentName#guid"
1968 public static DiagramComponentInfo parse(String tgName) {
1970 String name = tgName.substring(CHILD_PREFIX.length());
1971 String compositePathAndName = "";
1972 String moduleName = name;
1973 GUID guid = GUID.invalid();
1974 int lastHash = name.lastIndexOf(ModelingUtils.COMPOSITE_SEPARATOR_CHAR);
1976 String first = name.substring(0, lastHash);
1977 String second = name.substring(lastHash+1);
1978 lastHash = first.lastIndexOf(ModelingUtils.COMPOSITE_SEPARATOR_CHAR);
1980 compositePathAndName = first.substring(0, lastHash);
1981 moduleName = first.substring(lastHash+1);
1982 guid = GUID.parseIndexString(second);
1984 compositePathAndName = first;
1985 moduleName = second;
1988 return new DiagramComponentInfo(compositePathAndName, moduleName, guid);
1994 public int hashCode() {
1995 final int prime = 31;
1997 result = prime * result + ((compositePathAndName == null) ? 0 : compositePathAndName.hashCode());
1998 result = prime * result + ((componentName == null) ? 0 : componentName.hashCode());
2003 public boolean equals(Object obj) {
2008 if (getClass() != obj.getClass())
2010 DiagramComponentInfo other = (DiagramComponentInfo) obj;
2011 if (compositePathAndName == null) {
2012 if (other.compositePathAndName != null)
2014 } else if (!compositePathAndName.equals(other.compositePathAndName))
2016 if (componentName == null) {
2017 if (other.componentName != null)
2019 } else if (!componentName.equals(other.componentName))
2026 public static class CompositeInfo {
2028 public static String COMPOSITE_PREFIX = "composite:";
2030 final private boolean useGuids;
2031 final private boolean applyPaths;
2032 final private String path;
2033 final private String name;
2034 final private GUID guid;
2036 private CompositeInfo(boolean useGuids, boolean applyPaths, String path, String name, GUID guid) {
2037 this.useGuids = useGuids;
2038 this.applyPaths = applyPaths;
2045 public String toString() {
2046 return "CompositeInfo[useGuids=" + useGuids + ", applyPaths=" + applyPaths + ", path=" + path + ", name=" + name + ", guid=" + guid.indexString() + "]";
2049 public static boolean isComposite(String tgName) {
2050 return tgName.startsWith(COMPOSITE_PREFIX);
2053 public String getTGName() {
2054 return COMPOSITE_PREFIX + getOriginalPath() + ModelingUtils.COMPOSITE_SEPARATOR_CHAR + getEscapedName() + ModelingUtils.COMPOSITE_SEPARATOR_CHAR + guid.indexString();
2057 public boolean existsGUID(ReadGraph graph, Resource indexRoot) throws DatabaseException {
2058 Collection<Resource> res = ModelingUtils.searchByGUID(graph, indexRoot, guid);
2059 return !res.isEmpty();
2062 public static CompositeInfo fromResource(ReadGraph graph, Resource resource) throws DatabaseException {
2064 Layer0 L0 = Layer0.getInstance(graph);
2065 GUID rootId = graph.getRelatedValue(resource, L0.identifier, GUID.BINDING);
2066 String rootName = graph.getRelatedValue(resource, L0.HasName, Bindings.STRING);
2067 String escapedRootName = URIStringUtils.escape(rootName);
2068 String escapedPath = ModelingUtils.getDiagramCompositePath(graph, resource);
2069 return new CompositeInfo(true, true, escapedPath, escapedRootName, rootId);
2073 public static CompositeInfo parse(String tgName) {
2074 return parse(tgName, true, true);
2078 * Index 0 is root-relative folder path separated with '/' or null if target-relative positioning is used
2079 * Index 1 is diagram name
2081 public static CompositeInfo parse(String tgName, boolean applyPaths, boolean useGuids) {
2082 if(!tgName.startsWith(COMPOSITE_PREFIX)) return null;
2083 tgName = tgName.substring(COMPOSITE_PREFIX.length());
2084 if(!tgName.contains(COMPOSITE_SEPARATOR)) {
2085 if(useGuids) throw new IllegalStateException("GUID identifiers were not found for diagrams.");
2086 return new CompositeInfo(useGuids, applyPaths, null, tgName, null);
2088 String[] parts = tgName.split(COMPOSITE_SEPARATOR);
2089 if(parts.length == 2) {
2090 String name = parts[1];
2091 String path = applyPaths ? parts[0] : null;
2092 if(useGuids) throw new IllegalStateException("GUID identifiers were not found for diagrams.");
2093 return new CompositeInfo(useGuids, applyPaths, path, name, null);
2094 } else if(parts.length == 3) {
2095 String path = parts[0];
2096 String name = parts[1];
2097 GUID guid = GUID.parseIndexString(parts[2]);
2098 return new CompositeInfo(useGuids, applyPaths, path, name, guid);
2104 public GUID getGUID() {
2108 public String getEscapedName() {
2112 public String getUnescapedName() {
2113 return URIStringUtils.unescape(name);
2116 public String getOriginalPath() {
2120 public String getFinalPath() {
2121 if(applyPaths) return path;
2125 public CompositeInfo renamed(String newName) {
2126 return new CompositeInfo(useGuids, applyPaths, path, newName, guid);
2129 public String getStateKey() {
2130 return path + "#" + getEscapedName();
2133 private Resource getFromFolder(ReadGraph graph, Resource target) throws DatabaseException {
2134 Resource diagram = Layer0Utils.getPossibleChild(graph, target, URIStringUtils.unescape(name));
2135 if(diagram == null) return null;
2136 StructuralResource2 STR = StructuralResource2.getInstance(graph);
2137 return graph.isInstanceOf(diagram, STR.Composite) ? diagram : null;
2140 public Resource resolve(ReadGraph graph, Resource target) throws DatabaseException {
2142 if(useGuids && guid != null) {
2143 Resource indexRoot = graph.syncRequest(new IndexRoot(target));
2144 Collection<Resource> queryResult = searchByGUID(graph, indexRoot, guid);
2145 if(queryResult.size() == 1) {
2146 Resource composite = queryResult.iterator().next();
2147 StructuralResource2 STR = StructuralResource2.getInstance(graph);
2148 if(!graph.isInstanceOf(composite, STR.Composite)) return null;
2154 Resource folder = resolveFolder(graph, target);
2155 if(folder == null) return null;
2156 return getFromFolder(graph, folder);
2158 return getFromFolder(graph, target);
2163 public Resource resolveFolder(ReadGraph graph, Resource target) throws DatabaseException {
2165 String path = getFinalPath();
2166 if(path == null) return target;
2168 Resource folder = graph.syncRequest(new Configuration(target));
2169 String[] segments = path.split("/");
2170 for(int i=0;i<segments.length;i++) {
2171 if(segments[i].isEmpty()) continue;
2172 folder = Layer0Utils.getPossibleChild(graph, folder, URIStringUtils.unescape(segments[i]));
2173 if(folder == null) return null;
2182 public int hashCode() {
2184 if(useGuids) return guid.hashCode();
2186 final int prime = 31;
2187 int result = name.hashCode();
2188 result = prime * result + ((path == null) ? 0 : path.hashCode());
2194 public boolean equals(Object obj) {
2200 if (getClass() != obj.getClass())
2203 CompositeInfo other = (CompositeInfo) obj;
2205 if(useGuids) return guid.equals(other.guid);
2207 if (!name.equals(other.name))
2211 if (!path.equals(other.path))
2220 public static char COMPOSITE_SEPARATOR_CHAR = '#';
2221 public static String COMPOSITE_SEPARATOR = String.valueOf(COMPOSITE_SEPARATOR_CHAR);
2223 public static CompositeInfo parseCompositeNameFromRoot(Root root, boolean applyPaths, boolean useGuids) {
2224 return CompositeInfo.parse(root.name, applyPaths, useGuids);
2227 public static CompositeInfo parseCompositeNameFromRoot(Identity root, boolean applyPaths, boolean useGuids) {
2228 String coded = TransferableGraphUtils.getName(root);
2229 return CompositeInfo.parse(coded, applyPaths, useGuids);
2232 private static StringBuilder getDiagramCompositePathInternal(ReadGraph graph, Resource folder, StringBuilder builder) throws DatabaseException {
2233 SimulationResource SIMU = SimulationResource.getInstance(graph);
2234 Resource model = graph.getPossibleObject(folder, SIMU.IsConfigurationOf);
2235 if (model != null) return builder;
2237 Layer0 L0 = Layer0.getInstance(graph);
2238 String name = graph.getPossibleRelatedValue(folder, L0.HasName, Bindings.STRING);
2239 if (name == null) return null;
2240 Resource parent = graph.getPossibleObject(folder, L0.PartOf);
2241 if (parent == null) return null;
2243 StringBuilder sb = getDiagramCompositePathInternal(graph, parent, builder);
2244 if (sb == null) return null;
2245 if (sb.length() > 0)
2246 sb.append(URIStringUtils.NAMESPACE_PATH_SEPARATOR);
2247 sb.append( URIStringUtils.escape(name) );
2254 * @return diagram/folder path up until model configuration root with each
2255 * segment escaped using {@link URIStringUtils#escape(String)} and
2256 * {@value URIStringUtils#NAMESPACE_PATH_SEPARATOR} between each
2257 * segment or <code>null</code> if the specified diagram composite
2258 * is not part of any model configuration structure.
2259 * @throws DatabaseException
2261 public static String getDiagramCompositePath(ReadGraph graph, Resource diagram) throws DatabaseException {
2262 Layer0 L0 = Layer0.getInstance(graph);
2263 Resource parent = graph.getPossibleObject(diagram, L0.PartOf);
2264 if(parent == null) return null;
2265 StringBuilder sb = getDiagramCompositePathInternal(graph, parent, new StringBuilder());
2266 return sb != null ? sb.toString() : null;
2269 public static void exportModel(ReadGraph graph, Resource model, String fileName, String format, int version) throws DatabaseException {
2270 TransferableGraphConfiguration2 conf = new TransferableGraphConfiguration2(graph, model, true, false);
2271 exportModel(graph, conf, fileName, format, version);
2274 public static void exportModel(ReadGraph graph, TransferableGraphConfiguration2 conf, String fileName, String format, int version) throws DatabaseException {
2277 TransferableGraphSource s = graph.syncRequest(new ModelTransferableGraphSourceRequest(conf));
2278 TransferableGraphs.writeTransferableGraph(graph, format, version, s, new File(fileName));
2279 } catch (DatabaseException e) {
2281 } catch (Exception e) {
2282 throw new DatabaseException(e);
2287 public static TransferableGraph1 exportSharedOntology(ReadGraph graph, Resource library, String fileName, String format, int version) throws DatabaseException {
2289 Layer0 L0 = Layer0.getInstance(graph);
2290 String name = graph.getRelatedValue(library, L0.HasName, Bindings.STRING);
2292 DraftStatusBean draft = null;
2293 boolean published = Layer0Utils.isPublished(graph, library);
2294 if(!published) draft = new DraftStatusBean(new String[0]);
2296 LibraryInfo info = new LibraryInfo(name, library, draft);
2299 return exportSharedOntology(new NullProgressMonitor(), graph, fileName != null ? new File(fileName) : null, format, version, info);
2300 } catch (IOException e) {
2301 throw new DatabaseException(e);
2306 public static DraftStatusBean getDependencyDraftStatus(ReadGraph graph, Resource library) throws DatabaseException {
2307 Layer0 L0 = Layer0.getInstance(graph);
2308 List<String> drafts = new ArrayList<>();
2309 for (Resource shared : graph.syncRequest(new ObjectsWithType(library, L0.IsLinkedTo, L0.SharedOntology))) {
2310 boolean published = Layer0Utils.isPublished(graph, shared);
2312 drafts.add(graph.getURI(shared));
2314 return drafts.isEmpty() ? null : new DraftStatusBean(drafts);
2317 public static Set<Resource> getMostUnspecificTypes(final ReadGraph graph, Collection<Resource> types) throws DatabaseException {
2319 final Set<Resource> work = new HashSet<Resource>(types);
2320 for(Resource type : types) {
2321 Set<Resource> supers = graph.getSupertypes(type);
2322 if(!Collections.disjoint(supers, work)) work.remove(type);
2329 public static void rewriteGUIDS(WriteGraph graph, Resource root, boolean deep) throws DatabaseException {
2330 List<Resource> todo = new ArrayList<Resource>();
2332 Layer0 L0 = Layer0.getInstance(graph);
2333 while(!todo.isEmpty()) {
2334 Resource resource = todo.remove(todo.size()-1);
2335 Layer0Utils.claimNewIdentifier(graph, resource, false);
2337 todo.addAll(graph.getObjects(resource, L0.ConsistsOf));
2341 public static void createMissingGUIDs(IProgressMonitor monitor, WriteGraph graph, Collection<Resource> roots) throws DatabaseException {
2343 if(monitor == null) monitor = new NullProgressMonitor();
2345 Layer0 L0 = Layer0.getInstance(graph);
2347 // Allow this process to make 50k queries
2348 QueryMemoryWatcher memory = new QueryMemoryWatcher(graph, 50000);
2350 for(Resource root : roots) {
2352 boolean madeChanges = false;
2354 monitor.setTaskName("Creating missing GUID identifiers " + NameUtils.getSafeName(graph, root));
2355 Resource indexRoot = graph.syncRequest(new PossibleIndexRoot(root));
2356 for(Resource r : searchByType(graph, indexRoot, L0.Entity)) {
2360 if(graph.isImmutable(r)) continue;
2362 if(!ModelingUtils.needsIdentifier(graph, r)) continue;
2364 GUID existing = graph.getPossibleRelatedValue(r, L0.identifier, GUID.BINDING);
2365 if(existing == null) {
2366 Layer0Utils.claimNewIdentifier(graph, r, true);
2373 ModelingUtils.deleteIndex(graph, root);
2380 public static boolean activateModel(WriteGraph graph, Resource model) throws DatabaseException {
2381 return graph.syncRequest(new ActivateModel(Simantics.getProjectResource(), model));
2384 public static File fileDialog(String title, List<Tuple> namesAndExtensions) {
2386 Display display = Display.getCurrent();
2387 Shell shell = display.getActiveShell();
2389 FileDialog dialog = new FileDialog(shell, SWT.OPEN);
2390 dialog.setText(title);
2392 String[] extensions = new String[namesAndExtensions.size()];
2393 String[] filterNames = new String[namesAndExtensions.size()];
2395 for(Tuple t : namesAndExtensions) {
2396 String filterName = (String)t.get(0);
2397 String extension = (String)t.get(1);
2398 filterNames[index] = filterName;
2399 extensions[index] = extension;
2403 dialog.setFilterExtensions(extensions);
2404 dialog.setFilterNames(filterNames);
2405 final String fileName = dialog.open();
2406 if (fileName == null) return null;
2408 return new File(fileName);
2412 public static Resource createLibrary(WriteGraph graph, Resource parent) throws DatabaseException {
2413 Layer0 l0 = Layer0.getInstance(graph);
2414 return createLibrary(graph, parent, NameUtils.findFreshName(graph, "Library", parent, l0.ConsistsOf));
2417 public static Resource createLibrary(WriteGraph graph, Resource parent, String name) throws DatabaseException {
2418 graph.markUndoPoint();
2419 Layer0 l0 = Layer0.getInstance(graph);
2421 Resource library = graph.newResource();
2422 graph.claim(library, l0.InstanceOf, null, l0.Library);
2423 graph.addLiteral(library, l0.HasName, l0.NameOf, l0.String, name, Bindings.STRING);
2424 graph.claim(library, l0.PartOf, parent);
2426 Layer0Utils.addCommentMetadata(graph, "Created new Library named " + name + ", resource " + library);