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.QueryIndexUtils;
94 import org.simantics.db.layer0.SelectionHints;
95 import org.simantics.db.layer0.adapter.CopyHandler;
96 import org.simantics.db.layer0.adapter.GenericRelationIndex;
97 import org.simantics.db.layer0.adapter.Instances;
98 import org.simantics.db.layer0.adapter.impl.DefaultPasteImportAdvisor;
99 import org.simantics.db.layer0.adapter.impl.EntityInstances.QueryIndex;
100 import org.simantics.db.layer0.adapter.impl.ImportAdvisorFactory;
101 import org.simantics.db.layer0.genericrelation.DependenciesRelation.DependencyChangesRequest;
102 import org.simantics.db.layer0.genericrelation.DependencyChanges;
103 import org.simantics.db.layer0.genericrelation.IndexedRelations;
104 import org.simantics.db.layer0.migration.MigratedImportResult;
105 import org.simantics.db.layer0.migration.MigrationUtils;
106 import org.simantics.db.layer0.request.ActivateModel;
107 import org.simantics.db.layer0.request.ActiveModels;
108 import org.simantics.db.layer0.request.Configuration;
109 import org.simantics.db.layer0.request.IsLinkedTo;
110 import org.simantics.db.layer0.request.PossibleModel;
111 import org.simantics.db.layer0.util.ClipboardUtils;
112 import org.simantics.db.layer0.util.DraftStatusBean;
113 import org.simantics.db.layer0.util.ExternalDownloadBean;
114 import org.simantics.db.layer0.util.Layer0Utils;
115 import org.simantics.db.layer0.util.ModelTransferableGraphSourceRequest;
116 import org.simantics.db.layer0.util.PasteEventHandler;
117 import org.simantics.db.layer0.util.RemoverUtil;
118 import org.simantics.db.layer0.util.SimanticsClipboard;
119 import org.simantics.db.layer0.util.SimanticsClipboard.Representation;
120 import org.simantics.db.layer0.util.SimanticsClipboardImpl;
121 import org.simantics.db.layer0.util.SimanticsKeys;
122 import org.simantics.db.layer0.util.TransferableGraphConfiguration2;
123 import org.simantics.db.layer0.variable.Variable;
124 import org.simantics.db.layer0.variable.Variables;
125 import org.simantics.db.request.Read;
126 import org.simantics.db.service.ClusterControl;
127 import org.simantics.db.service.CollectionSupport;
128 import org.simantics.db.service.GraphChangeListenerSupport;
129 import org.simantics.db.service.QueryControl;
130 import org.simantics.db.service.VirtualGraphSupport;
131 import org.simantics.diagram.stubs.DiagramResource;
132 import org.simantics.diagram.stubs.G2DResource;
133 import org.simantics.diagram.synchronization.graph.AddElement;
134 import org.simantics.graph.db.IImportAdvisor2;
135 import org.simantics.graph.db.ImportAdvisors;
136 import org.simantics.graph.db.MissingDependencyException;
137 import org.simantics.graph.db.StreamingTransferableGraphFileReader;
138 import org.simantics.graph.db.TransferableGraphException;
139 import org.simantics.graph.db.TransferableGraphSource;
140 import org.simantics.graph.db.TransferableGraphs;
141 import org.simantics.graph.representation.Identity;
142 import org.simantics.graph.representation.Root;
143 import org.simantics.graph.representation.TransferableGraph1;
144 import org.simantics.graph.representation.TransferableGraphUtils;
145 import org.simantics.issues.common.IssueSourceUtils;
146 import org.simantics.issues.ontology.IssueResource;
147 import org.simantics.layer0.Layer0;
148 import org.simantics.layer0.utils.direct.GraphUtils;
149 import org.simantics.modeling.adapters.ChangeInformation;
150 import org.simantics.modeling.template2d.ontology.Template2dResource;
151 import org.simantics.modeling.utils.OntologicalRequirementTracker;
152 import org.simantics.operation.Layer0X;
153 import org.simantics.project.ontology.ProjectResource;
154 import org.simantics.scenegraph.profile.ProfileUtils;
155 import org.simantics.scl.runtime.function.Function1;
156 import org.simantics.scl.runtime.tuple.Tuple;
157 import org.simantics.simulation.ontology.SimulationResource;
158 import org.simantics.structural.stubs.StructuralResource2;
159 import org.simantics.structural2.scl.StructuralComponent;
160 import org.simantics.structural2.utils.StructuralUtils;
161 import org.simantics.ui.SimanticsUI;
162 import org.simantics.utils.ObjectUtils;
163 import org.simantics.utils.datastructures.Pair;
164 import org.simantics.utils.datastructures.Triple;
165 import org.simantics.utils.datastructures.hints.HintContext;
166 import org.simantics.utils.ui.dialogs.ListDialog;
169 * @author Hannu Niemistö
171 public class ModelingUtils {
174 private WriteGraph wg;
176 private StructuralResource2 sr;
177 private DiagramResource dr;
178 public ModelingResources mr;
179 public SimulationResource SIMU;
181 public ModelingUtils(WriteGraph g) {
184 b = Layer0.getInstance(g);
185 sr = StructuralResource2.getInstance(g);
186 dr = DiagramResource.getInstance(g);
187 mr = ModelingResources.getInstance(g);
188 SIMU = SimulationResource.getInstance(g);
192 public Resource createSymbol2(String name) throws DatabaseException {
193 return createSymbol2(name, dr.Composite);
197 public Resource createSymbol2(String name, Resource diagramType) throws DatabaseException {
198 return createSymbol2(name, diagramType, dr.DefinedElement);
201 public Resource createSymbol2(String name, Resource diagramType, Resource symbolType) throws DatabaseException {
202 G2DResource g2d = G2DResource.getInstance(g);
204 // Resource visibleTag = wg.newResource();
205 // wg.claim(visibleTag, b.SubrelationOf, null, dr.IsVisible);
206 // Resource focusableTag = wg.newResource();
207 // wg.claim(focusableTag, b.SubrelationOf, null, dr.IsFocusable);
209 Double boxDimension = 6.0;
210 Collection<Statement> grid = g.getAssertedStatements(diagramType, dr.HasGridSize);
211 if(grid.size() == 1) {
212 Double d = g.getPossibleValue(grid.iterator().next().getObject(), Bindings.DOUBLE);
213 if(d != null) boxDimension = 2*d;
217 Resource element = GraphUtils.create(wg,
218 b.InstanceOf, dr.SVGElement,
220 "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>" +
221 // REMOVED by Tuukka, because This will cause
222 // parsers to get on the net and get the doctype
223 // definitions which can stall the UI for a long time.
224 // Besides, we're not using the validation for anything
225 // so it's useless to us.
226 //"<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\" \"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\">" +
227 "<svg xmlns=\"http://www.w3.org/2000/svg\" overflow=\"visible\" version=\"1.1\">" +
228 "<rect x=\"-" + boxDimension + "\" y=\"-" + boxDimension + "\" width=\"" + (2*boxDimension) + "\" height=\"" + (2*boxDimension) + "\" fill=\"none\" stroke=\"rgb(0,0,0)\" stroke-width=\"0.1\"/>" +
232 // wg.claim(element, visibleTag, element);
233 // wg.claim(element, focusableTag, element);
235 Resource orderedSet = OrderedSetUtils.create(wg, diagramType, element);
237 // wg.claim(orderedSet, dr.HasLayer, GraphUtils.create2(wg, dr.Layer,
238 // b.HasName, "Default",
239 // dr.IsActive, Boolean.TRUE,
240 // dr.HasVisibleTag, visibleTag,
241 // dr.HasFocusableTag, focusableTag));
243 Resource result = GraphUtils.create(wg,
246 sr.IsDefinedBy, orderedSet);
248 wg.claim(result, b.ConsistsOf, orderedSet);
249 wg.claimLiteral(orderedSet, b.HasName, "__DIAGRAM__", Bindings.STRING);
250 AddElement.claimFreshElementName(wg, orderedSet, element);
251 wg.claim(orderedSet, b.ConsistsOf, element);
253 wg.claim(result, b.Inherits, null, symbolType);
257 public static Collection<Resource> getElementCorrespondendences(ReadGraph g, Resource element) throws DatabaseException {
258 DiagramResource dr = DiagramResource.getInstance(g);
259 ModelingResources mr = ModelingResources.getInstance(g);
260 if(g.isInstanceOf(element, dr.Connection)) {
261 Resource mappedComponent = g.getPossibleObject(element, mr.ElementToComponent);
262 if(mappedComponent != null) return Collections.singletonList(mappedComponent);
263 Resource mappedConnection = g.getPossibleObject(element, mr.DiagramConnectionToConnection);
264 if(mappedConnection == null)
265 return Collections.emptyList();
266 ArrayList<Resource> result = new ArrayList<Resource>();
267 Collection<Resource> relatedMappedConnections = StructuralUtils.getRelatedConnections(g, mappedConnection);
268 for(Resource relatedMappedConnection : relatedMappedConnections)
269 for(Resource relatedConnection : g.getObjects(relatedMappedConnection, mr.ConnectionToDiagramConnection))
270 result.addAll(g.getObjects(relatedConnection, mr.ElementToComponent));
274 return g.getObjects(element, mr.ElementToComponent);
277 public static Resource getPossibleElement(ReadGraph g, Resource component) throws DatabaseException {
278 ModelingResources mr = ModelingResources.getInstance(g);
279 return g.getPossibleObject(component, mr.ComponentToElement);
282 public static Resource getPossibleElementCorrespondendence(ReadGraph g, Resource element) throws DatabaseException {
283 Collection<Resource> corrs = getElementCorrespondendences(g, element);
284 if(corrs.size() != 1) return null;
285 else return corrs.iterator().next();
288 public static Resource getSingleElementCorrespondendence(ReadGraph g, Resource element) throws DatabaseException {
289 Collection<Resource> corrs = getElementCorrespondendences(g, element);
290 if(corrs.size() != 1) throw new DatabaseException("Expected 1 element correspondence, got " + corrs.size());
291 else return corrs.iterator().next();
294 public static Resource createExperiment(WriteGraph graph, Resource model) throws DatabaseException {
296 Layer0 L0 = Layer0.getInstance(graph);
297 SimulationResource SIMU = SimulationResource.getInstance(graph);
298 Resource experiment = graph.newResource();
299 graph.claim(experiment, L0.InstanceOf, SIMU.Experiment);
300 graph.claimLiteral(experiment, L0.HasName, "Experiment");
301 graph.claim(model, L0.ConsistsOf, experiment);
306 public static Resource createModel(WriteGraph graph, Resource type) throws DatabaseException {
307 return createModel(graph, type, Simantics.getProjectResource(), null);
310 public static Resource createModel(WriteGraph graph, Resource type, String name) throws DatabaseException {
311 return createModel(graph, type, Simantics.getProjectResource(), name);
314 public static Resource createModel(WriteGraph graph, Resource type, final Resource target, String name) throws DatabaseException {
316 Layer0 L0 = Layer0.getInstance(graph);
317 SimulationResource SIMU = SimulationResource.getInstance(graph);
318 StructuralResource2 STR = StructuralResource2.getInstance(graph);
319 ModelingResources MOD = ModelingResources.getInstance(graph);
322 name = NameUtils.findFreshName(graph, "Model", target, L0.ConsistsOf, "%s%d");
324 final Resource model = graph.newResource();
325 graph.newClusterSet(model);
326 graph.claim(model, L0.InstanceOf, null, type);
327 graph.claimLiteral(model, L0.HasName, name);
329 graph.claim(target, L0.ConsistsOf, model);
331 Resource configurationType = graph.getPossibleObject(model, MOD.StructuralModel_HasConfigurationType);
332 if(configurationType == null) configurationType = STR.Composite;
334 Resource configuration = graph.newResource();
335 graph.claimLiteral(configuration, L0.HasName, "Configuration", Bindings.STRING);
336 graph.claim(configuration, L0.InstanceOf, null, configurationType);
337 graph.claim(model, L0.ConsistsOf, configuration);
338 graph.claim(model, SIMU.HasConfiguration, configuration);
340 Resource joinClusterSet = graph.newResource();
341 graph.newClusterSet(joinClusterSet);
342 graph.claim(joinClusterSet, L0.InstanceOf, L0.ClusterSet);
343 graph.claim(model, STR.HasJoinClusterSet, joinClusterSet);
345 linkOntologyDependenciesToModel(graph, model, target);
347 Resource ontology = graph.syncRequest(new PossibleIndexRoot(type));
348 if(ontology != null) {
349 graph.claim(model, L0.IsLinkedTo, ontology);
352 VirtualGraphSupport support = graph.getService(VirtualGraphSupport.class);
353 graph.asyncRequest(new WriteRequest(support.getWorkspacePersistent("activations")) {
356 public void perform(WriteGraph graph) throws DatabaseException {
357 Layer0X L0X = Layer0X.getInstance(graph);
358 Collection<Resource> actives = graph.syncRequest(new ActiveModels(target));
359 if(actives.isEmpty()) {
360 graph.claim(model, L0X.IsActivatedBy, target);
370 public static void linkOntologyDependenciesToModel(WriteGraph graph, Resource model, Resource target)
371 throws DatabaseException {
372 Layer0 L0 = Layer0.getInstance(graph);
373 ProjectResource PROJ = ProjectResource.getInstance(graph);
374 for(Resource dep : graph.getObjects(target, L0.IsLinkedTo)) {
375 if(graph.isInstanceOf(dep, PROJ.NamespaceRequirement)) {
376 for(Resource req : graph.getObjects(dep, PROJ.RequiresNamespace)) {
377 String uri = graph.getPossibleValue(req, Bindings.STRING);
379 Resource ns = graph.getResource(uri);
381 graph.claim(model, L0.IsLinkedTo, null, ns);
389 public static void addSCLMainToModel(WriteGraph graph, Resource model)
390 throws DatabaseException {
391 addSCLMainToModel(graph, model, "SCLMain", "include \"Simantics/All\"\n");
394 public static void addSCLMainToModel(WriteGraph graph, Resource model, String name, String contents)
395 throws DatabaseException {
396 Layer0 L0 = Layer0.getInstance(graph);
397 Resource sclmain = GraphUtils.create2(graph, L0.SCLModule, L0.PartOf, model, L0.HasName, name);
398 graph.claimLiteral(sclmain, L0.SCLModule_definition, contents, Bindings.STRING);
401 public static Resource createLocalLibrary(WriteGraph graph, Resource container, String name) throws DatabaseException {
402 Layer0 L0 = Layer0.getInstance(graph);
403 ModelingResources MOD = ModelingResources.getInstance(graph);
404 Resource library = graph.newResource();
405 graph.claim(library, L0.InstanceOf, null, L0.Library);
406 graph.addLiteral(library, L0.HasName, L0.NameOf, "Library", Bindings.STRING);
407 if (container != null) {
408 graph.claim(container, L0.ConsistsOf, L0.PartOf, library);
409 graph.claim(container, MOD.HasLocalLibrary, MOD.IsLocalLibraryOf, library);
414 public static void importModel(String fileName) {
416 Resource project = SimanticsUI.getProject().get();
418 try (StreamingTransferableGraphFileReader importer = new StreamingTransferableGraphFileReader(new File(fileName))) {
419 TransferableGraphSource tg = importer.readTG();
421 final DefaultPasteImportAdvisor advisor = new DefaultPasteImportAdvisor(project) {
423 public void analyzeType(ReadGraph graph, Root root) throws DatabaseException {
426 public Resource analyzeRoot(ReadGraph graph, Root root) throws DatabaseException {
427 library = Simantics.getProjectResource();
428 String newName = newName(graph, library, root.name);
429 nameMappings.put(root.name, newName);
433 TransferableGraphs.importGraph1(Simantics.getSession(), tg, advisor);
435 } catch (MissingDependencyException e) {
437 final Set<String> missingURIs = e.getMissingURIs();
439 class ErrorMessageDialog extends MessageDialog {
441 public ErrorMessageDialog(Shell shell) {
443 "Unsatisfied dependencies", null,
444 "The following dependencies were missing. Please import the dependencies and try again.",
445 MessageDialog.ERROR, new String[] { "Continue" }, 0);
449 protected Control createCustomArea(Composite composite) {
450 GridLayoutFactory.fillDefaults().applyTo(composite);
452 org.eclipse.swt.widgets.List list = new org.eclipse.swt.widgets.List(composite, SWT.BORDER | SWT.READ_ONLY);
453 GridDataFactory.fillDefaults().grab(true, true).applyTo(list);
454 for(String s : missingURIs) list.add(s);
460 Display display = Display.getCurrent();
461 if(display != null) {
462 ErrorMessageDialog md = new ErrorMessageDialog(display.getActiveShell());
465 Display.getDefault().asyncExec(new Runnable() {
469 Shell shell = Display.getCurrent().getActiveShell();
470 ErrorMessageDialog md = new ErrorMessageDialog(shell);
478 } catch (Exception e) {
479 Logger.defaultLogError(e);
484 public static void primeVirtualGraphs() {
485 VirtualGraphSupport support = Simantics.getSession().getService(VirtualGraphSupport.class);
486 support.getWorkspacePersistent("activations");
487 support.getWorkspacePersistent("experiments");
488 support.getWorkspacePersistent("issues");
489 support.getWorkspacePersistent("preferences");
492 public static Resource createProfileEntry(WriteGraph graph, String name, Resource style, Resource group) throws DatabaseException {
494 Layer0 L0 = Layer0.getInstance(graph);
495 DiagramResource DIA = DiagramResource.getInstance(graph);
497 Resource entry = graph.newResource();
498 graph.claim(entry, L0.InstanceOf, null, DIA.GroupStyleProfileEntry);
499 graph.claimLiteral(entry, L0.HasName, name);
500 graph.claimLiteral(entry, L0.HasLabel, name);
501 graph.claim(entry, DIA.ProfileEntry_HasStyle, style);
502 graph.claim(entry, DIA.ProfileEntry_HasGroup, group);
508 public static Resource createProfile(WriteGraph graph, String profileName, Resource... entries) throws DatabaseException {
510 Layer0 L0 = Layer0.getInstance(graph);
511 DiagramResource DIA = DiagramResource.getInstance(graph);
513 Resource list = ListUtils.create(graph, DIA.Profile, entries);
515 Resource profile = graph.newResource();
516 graph.claim(profile, L0.InstanceOf, null, DIA.Profile);
517 graph.claimLiteral(profile, L0.HasName, profileName);
518 graph.claim(profile, DIA.HasEntries, null, list);
524 public static Resource createProfile(WriteGraph graph, String profileName, Collection<Resource> entries) throws DatabaseException {
525 return createProfile(graph, profileName, entries.toArray(new Resource[entries.size()]));
528 public static Resource createToplevelProfile(WriteGraph graph, Resource model, String name, Resource ... profiles) throws DatabaseException {
530 Resource work = createProfile(graph, name, profiles);
532 Layer0 L0 = Layer0.getInstance(graph);
533 DiagramResource DIA = DiagramResource.getInstance(graph);
535 graph.deny(model, DIA.HasActiveProfile);
536 graph.claim(model, DIA.HasActiveProfile, work);
537 graph.claim(model, L0.ConsistsOf, L0.PartOf, work);
543 public static Resource createToplevelProfile(WriteGraph graph, Resource model, String name, Collection<Resource> profiles) throws DatabaseException {
544 return createToplevelProfile(graph, model, name, profiles.toArray(new Resource[profiles.size()]));
547 public static void activateProfileEntries(WriteGraph graph, final Resource profile, final Resource ... entries) {
549 VirtualGraphSupport support = graph.getService(VirtualGraphSupport.class);
550 graph.asyncRequest(new WriteRequest(support.getWorkspacePersistent("profiles")) {
553 public void perform(WriteGraph graph) throws DatabaseException {
554 SimulationResource SIMU = SimulationResource.getInstance(graph);
555 for(Resource entry : entries)
556 graph.claim(profile, SIMU.IsActive, entry);
563 public static void activateProfileEntries(WriteGraph graph, Resource profile, Collection<Resource> entries) {
564 activateProfileEntries(graph, profile, entries.toArray(new Resource[entries.size()]));
567 public static void toggleProfileGroup(WriteGraph graph, Resource runtimeProfile, String groupName, boolean enabled) throws DatabaseException {
568 Layer0 L0 = Layer0.getInstance(graph);
569 for (Resource group : ProfileUtils.getProfileChildren(graph, runtimeProfile)) {
570 String name = graph.getRelatedValue2(group, L0.HasName);
571 if (name.equals(groupName)) {
572 toggleProfileGroup(graph, runtimeProfile, group, enabled);
578 public static void toggleProfileGroup(WriteGraph graph, Resource runtimeProfile, Resource group, boolean enabled) throws DatabaseException {
579 DiagramResource DIA = DiagramResource.getInstance(graph);
581 if(graph.isInstanceOf(group, DIA.Profile)) {
583 for(Resource child : ProfileUtils.getProfileChildren(graph, group)) {
584 toggleProfileGroup(graph, runtimeProfile, child, enabled);
587 } else if(graph.isInstanceOf(group, DIA.ProfileEntry)) {
590 graph.claim(runtimeProfile, SimulationResource.getInstance(graph).IsActive, null, group);
592 graph.denyStatement(runtimeProfile, SimulationResource.getInstance(graph).IsActive, group);
598 public static void untrackDependencies() {
599 untrackDependencies(Simantics.getSession());
602 public static void untrackDependencies(RequestProcessor processor) {
605 processor.syncRequest(new ReadRequest() {
608 public void run(ReadGraph graph) throws DatabaseException {
609 Layer0X L0X = Layer0X.getInstance(graph);
610 GenericRelationIndex index = graph.adapt(L0X.DependenciesRelation, GenericRelationIndex.class);
611 index.untrack(graph.getSession(), graph.getRootLibrary());
615 } catch (DatabaseException e) {
616 Logger.defaultLogError(e);
621 public static void trackDependencies() {
622 trackDependencies(Simantics.getSession());
625 public static void trackDependencies(RequestProcessor processor) {
628 processor.syncRequest(new ReadRequest() {
631 public void run(ReadGraph graph) throws DatabaseException {
632 Layer0X L0X = Layer0X.getInstance(graph);
633 GenericRelationIndex index = graph.adapt(L0X.DependenciesRelation, GenericRelationIndex.class);
634 index.trackAndIndex(graph.getSession(), graph.getRootLibrary());
638 } catch (DatabaseException e) {
639 Logger.defaultLogError(e);
644 public static void trackOntologicalRequirements() {
645 Session session = Simantics.getSession();
646 GraphChangeListenerSupport changeListenerSupport = session.getService(GraphChangeListenerSupport.class);
647 changeListenerSupport.addMetadataListener( OntologicalRequirementListener.getInstance() );
650 public static void untrackOntologicalRequirements() {
651 Session session = Simantics.getSession();
652 GraphChangeListenerSupport changeListenerSupport = session.getService(GraphChangeListenerSupport.class);
653 changeListenerSupport.removeMetadataListener( OntologicalRequirementListener.getInstance() );
656 public static class OntologicalRequirementListener extends GenericChangeListener<DependencyChangesRequest, DependencyChanges> {
658 private static OntologicalRequirementListener INSTANCE;
660 public static OntologicalRequirementListener getInstance() {
661 if(INSTANCE == null) {
662 INSTANCE = new OntologicalRequirementListener();
667 private OntologicalRequirementListener() {
670 private OntologicalRequirementTracker changeInformationUpdater = new OntologicalRequirementTracker();
673 public boolean preEventRequest() {
674 return !Indexing.isDependenciesIndexingDisabled();
678 public void onEvent(ReadGraph graph, MetadataI metadata, DependencyChanges event) throws DatabaseException {
679 changeInformationUpdater.update(graph, metadata, event);
684 public static void removeIndex(WriteGraph graph, Resource model) throws DatabaseException {
685 Layer0X L0X = Layer0X.getInstance(graph);
686 IndexedRelations ir = graph.getService(IndexedRelations.class);
687 // Deletes index files
688 ir.reset(null, graph, L0X.DependenciesRelation, model);
691 public static void resetIssueSources(WriteGraph graph, Resource model) throws DatabaseException {
692 Layer0 L0 = Layer0.getInstance(graph);
693 IssueResource ISSUE = IssueResource.getInstance(graph);
694 for(Resource source : graph.sync(new ObjectsWithType(model, L0.ConsistsOf, ISSUE.ContinuousIssueSource))) {
695 IssueSourceUtils.update(graph, source);
699 public static void copyAnnotationTypes(WriteGraph graph, Resource sourceModel, Resource targetModel) throws DatabaseException {
701 Layer0 L0 = Layer0.getInstance(graph);
702 AnnotationResource ANNO = AnnotationResource.getInstance(graph);
704 Instances query = graph.adapt(ANNO.AnnotationType, Instances.class);
706 Resource library = graph.getPossibleObject(targetModel, ANNO.HasAnnotationTypeRoot);
708 if(library == null) {
709 library = graph.newResource();
710 graph.claim(library, L0.InstanceOf, null, ANNO.AnnotationTypeLibrary);
711 graph.claimLiteral(library, L0.HasName, L0.NameOf, L0.String, "Annotation types", Bindings.STRING);
712 graph.claim(library, L0.PartOf, L0.ConsistsOf, targetModel);
713 graph.claim(targetModel, ANNO.HasAnnotationTypeRoot, library);
716 for(Resource type : query.find(graph, sourceModel)) {
717 String name = graph.getRelatedValue(type, L0.HasName);
718 Resource existing = Layer0Utils.getPossibleChild(graph, library, name);
719 if(existing != null) {
720 RemoverUtil.remove(graph, existing);
722 Layer0Utils.copyTo(graph, library, type);
727 public static void deleteIndex(WriteGraph graph, Resource model) throws DatabaseException {
728 Layer0X L0X = Layer0X.getInstance(graph);
729 IndexedRelations ir = graph.getService(IndexedRelations.class);
730 // Deletes index files
731 ir.reset(null, graph, L0X.DependenciesRelation, model);
734 public static void disableDependencies(WriteGraph graph, Resource dummy) {
735 Layer0Utils.setDependenciesIndexingDisabled(graph, true);
738 public static void releaseMemory(WriteGraph graph) {
740 QueryControl qc = graph.getService(QueryControl.class);
741 ClusterControl cc = graph.getService(ClusterControl.class);
747 public static List<Resource> filterByIndexRoot(ReadGraph graph, Resource indexRoot, List<Resource> resources) throws DatabaseException {
748 ArrayList<Resource> result = new ArrayList<Resource>(resources.size());
749 for (Resource r : resources) {
750 Resource root = graph.syncRequest(new PossibleIndexRoot(r));
751 if (indexRoot.equals(root))
758 public static List<Resource> searchByTypeShallow(ReadGraph graph, Resource model, Resource type) throws DatabaseException {
759 return QueryIndexUtils.searchByTypeShallow(graph, model, type);
763 public static List<Resource> searchByType(ReadGraph graph, Resource model, Resource type) throws DatabaseException {
764 return QueryIndexUtils.searchByType(graph, model, type);
768 public static List<Resource> searchByGUID(ReadGraph graph, Resource indexRoot, GUID guid) throws DatabaseException {
769 return QueryIndexUtils.searchByGUID(graph, indexRoot, guid);
773 public static List<Resource> searchByGUID(ReadGraph graph, Resource indexRoot, String indexString) throws DatabaseException {
774 return QueryIndexUtils.searchByGUID(graph, indexRoot, indexString);
778 public static List<Resource> searchByQueryShallow(ReadGraph graph, Resource model, String query) throws DatabaseException {
779 return QueryIndexUtils.searchByQueryShallow(graph, model, query);
783 public static List<Resource> searchByQuery(ReadGraph graph, Resource model, String query) throws DatabaseException {
784 return QueryIndexUtils.searchByQuery(graph, model, query);
788 public static List<Resource> searchByTypeAndFilter(ReadGraph graph, Resource model, Resource type, Function1<Resource,Boolean> filter) throws DatabaseException {
789 return QueryIndexUtils.searchByTypeAndFilter(graph, model, type, filter);
793 public static List<Triple<Resource, Resource, String>> getIndexEntries(ReadGraph graph, Resource model, String filter) throws DatabaseException {
794 return QueryIndexUtils.getIndexEntries(graph, model, filter);
798 public static String listIndexEntries(ReadGraph graph, Resource model, String filter) throws DatabaseException {
799 return QueryIndexUtils.listIndexEntries(graph, model, filter);
803 public static List<Resource> searchByTypeAndName(ReadGraph graph, Resource model, Resource type, String name) throws DatabaseException {
804 return QueryIndexUtils.searchByTypeAndName(graph, model, type, name);
808 public static List<Resource> searchByTypeAndNameShallow(ReadGraph graph, Resource model, Resource type, String name) throws DatabaseException {
809 return QueryIndexUtils.searchByTypeAndNameShallow(graph, model, type, name);
814 * database write access
815 * @param sourceContainer
816 * the source container to look for annotationProperty from to be
817 * used as the copy source
818 * @param targetContainer
819 * the target container for the copied annotationProperty
821 * @param annotationProperty
822 * the annotation property relation
823 * @return created copy of the original annotation or <code>null</code> if
824 * there was nothing to copy
825 * @throws DatabaseException
827 public static Resource copyPossibleAnnotation(WriteGraph graph, Resource sourceContainer, Resource targetContainer, Resource annotationProperty) throws DatabaseException {
828 return copyPossibleAnnotation2(graph, sourceContainer, targetContainer, annotationProperty, null);
831 public static List<String> getPossibleNamePath(ReadGraph graph, Resource resource) throws DatabaseException {
832 return getPossibleNamePath(graph, resource, null);
835 private static List<String> getPossibleNamePath(ReadGraph graph, Resource resource, List<String> result) throws DatabaseException {
837 Layer0 L0 = Layer0.getInstance(graph);
838 String name = graph.getPossibleRelatedValue(resource, L0.HasName, Bindings.STRING);
839 if(name == null) return null;
841 if(result == null) result = new ArrayList<String>();
843 SimulationResource SIMU = SimulationResource.getInstance(graph);
844 if(graph.isInstanceOf(resource, SIMU.Model)) return result;
846 Resource parent = graph.getPossibleObject(resource, L0.PartOf);
848 getPossibleNamePath(graph, parent, result);
859 public static Resource claimLibraryPath(WriteGraph graph, Resource resource, List<String> path) throws DatabaseException {
860 Layer0 L0 = Layer0.getInstance(graph);
861 for(int i=0;i<path.size()-1;i++) {
862 String p = path.get(i);
863 Resource child = Layer0Utils.getPossibleChild(graph, resource, p);
865 child = graph.newResource();
866 graph.claim(child, L0.InstanceOf, L0.Library);
867 graph.addLiteral(child, L0.HasName, L0.NameOf, L0.String, p, Bindings.STRING);
868 graph.claim(resource, L0.ConsistsOf, L0.PartOf, child);
877 * database write access
878 * @param sourceContainer
879 * the source container to look for annotationProperty from to be
880 * used as the copy source
881 * @param targetContainer
882 * the target container for the copied annotationProperty
884 * @param annotationProperty
885 * the annotation property relation
886 * @param annotationProperty
887 * the 2nd level annotation property relation or
888 * <code>null</code> if no 2nd level annotation exists
889 * @return created copy of the original annotation or <code>null</code> if
890 * there was nothing to copy
891 * @throws DatabaseException
893 public static Resource copyPossibleAnnotation2(WriteGraph graph,
894 Resource sourceContainer, Resource targetContainer,
895 Resource annotationProperty, Resource entryType) throws DatabaseException {
897 // Delete existing target value first
898 Layer0 L0 = Layer0.getInstance(graph);
899 Resource targetValue = graph.getPossibleObject(targetContainer, annotationProperty);
900 if (targetValue != null) {
901 if(!graph.hasStatement(targetValue, L0.PartOf))
902 RemoverUtil.remove(graph, targetValue);
903 graph.deny(targetContainer, annotationProperty);
906 Resource sourceValue = graph.getPossibleObject(sourceContainer, annotationProperty);
907 if (sourceValue == null)
910 List<String> sourceValuePath = getPossibleNamePath(graph, sourceValue);
911 if(sourceValuePath != null) {
912 Resource targetModel = graph.sync(new PossibleModel(targetContainer));
913 if(targetModel == null) throw new DatabaseException("No target model found for " + targetContainer);
914 Resource library = claimLibraryPath(graph, targetModel, sourceValuePath);
915 Resource existing = Layer0Utils.getPossibleChild(graph, library, sourceValuePath.get(sourceValuePath.size()-1));
916 if(existing == null) {
917 existing = doCopyPossibleAnnotation2(graph, sourceContainer, targetContainer, annotationProperty, entryType);
918 graph.claim(library, L0.ConsistsOf, L0.PartOf, existing);
920 graph.claim(targetContainer, annotationProperty, existing);
923 return doCopyPossibleAnnotation2(graph, sourceContainer, targetContainer, annotationProperty, entryType);
928 private static Resource doCopyPossibleAnnotation2(WriteGraph graph,
929 Resource sourceContainer, Resource targetContainer,
930 Resource annotationProperty, Resource entryType) throws DatabaseException {
932 Resource sourceValue = graph.getPossibleObject(sourceContainer, annotationProperty);
933 if (sourceValue == null)
936 // Copy 1st level annotation
937 Resource targetValue = createAnnotation(graph, targetContainer, annotationProperty, sourceValue);
939 // Copy possible 2nd level annotations and attach to 1st if entry
940 // property is defined.
941 Layer0 L0 = Layer0.getInstance(graph);
942 if (entryType != null) {
944 AnnotationResource ANNO = AnnotationResource.getInstance(graph);
945 for (Resource entry : graph.getObjects(sourceValue, ANNO.Annotation_HasEntry)) {
947 String name = graph.getRelatedValue(entry, L0.HasName, Bindings.STRING);
949 List<String> entryPath = getPossibleNamePath(graph, entry);
950 if(entryPath != null) {
951 Resource targetModel = graph.sync(new PossibleModel(targetContainer));
952 if(targetModel == null) throw new DatabaseException("No target model found for " + targetContainer);
953 Resource library = claimLibraryPath(graph, targetModel, entryPath);
954 Resource existing = Layer0Utils.getPossibleChild(graph, library, entryPath.get(entryPath.size()-1));
955 if(existing == null) {
956 existing = createTypedAnnotation(graph, null, null, entry, entryType, name);
957 graph.claim(library, L0.ConsistsOf, L0.PartOf, existing);
959 graph.claim(targetValue, ANNO.Annotation_HasEntry, existing);
961 Resource result = createTypedAnnotation(graph, null, null, entry, entryType, name);
962 graph.claim(targetValue, ANNO.Annotation_HasEntry, result);
974 * database write access
976 * the container resource to attach the new annotation to
978 * the annotation property relation. The type of the created
979 * annotation is decided from this property relation's range
980 * @param sourceAnnotation
981 * the annotation to copy data from or <code>null</code> if
982 * nothing shall be copied
983 * @return the newly created annotation resource or <code>null</code> if the
984 * annotation property relation didn't have a single range type
985 * @throws DatabaseException
987 public static Resource createAnnotation(WriteGraph graph, Resource container, Resource property, Resource sourceAnnotation) throws DatabaseException {
988 return createAnnotation(graph, container, property, sourceAnnotation, null);
993 * database write access
995 * the container resource to attach the new annotation to
997 * the annotation property relation. The type of the created
998 * annotation is decided from this property relation's range
999 * @param sourceAnnotation
1000 * the annotation to copy data from or <code>null</code> if
1001 * nothing shall be copied
1003 * name for newly created annotation or <code>null</code> to copy
1004 * name from source if available
1005 * @return the newly created annotation resource or <code>null</code> if the
1006 * annotation property relation didn't have a single range type
1007 * @throws DatabaseException
1009 public static Resource createAnnotation(WriteGraph graph, Resource container, Resource property, Resource sourceAnnotation, String name) throws DatabaseException {
1011 Layer0 L0 = Layer0.getInstance(graph);
1012 Resource annotationType = graph.getSingleObject(property, L0.HasRange);
1013 if (annotationType == null)
1016 return createTypedAnnotation(graph, container, property, sourceAnnotation, annotationType, name);
1022 * database write access
1024 * the container resource to attach the new annotation to
1026 * the annotation property relation
1027 * @param sourceAnnotation
1028 * the annotation to copy data from or <code>null</code> if
1029 * nothing shall be copied
1030 * @param annotationType
1031 * the type of the new annotation
1032 * @return the newly created annotation resource
1033 * @throws DatabaseException
1035 public static Resource createTypedAnnotation(WriteGraph graph, Resource container, Resource property, Resource sourceAnnotation, Resource annotationType) throws DatabaseException {
1036 return createTypedAnnotation(graph, container, property, sourceAnnotation, annotationType, null);
1041 * database write access
1043 * the container resource to attach the new annotation to
1045 * the annotation property relation
1046 * @param sourceAnnotation
1047 * the annotation to copy data from or <code>null</code> if
1048 * nothing shall be copied
1049 * @param annotationType
1050 * the type of the new annotation
1052 * name for newly created annotation or <code>null</code> to copy
1053 * name from source if available
1054 * @return the newly created annotation resource
1055 * @throws DatabaseException
1057 public static Resource createTypedAnnotation(WriteGraph graph, Resource container, Resource property, Resource sourceAnnotation, Resource annotationType, String name) throws DatabaseException {
1059 Layer0 L0 = Layer0.getInstance(graph);
1061 Resource anno = graph.newResource();
1063 graph.claim(anno, L0.InstanceOf, null, annotationType);
1066 graph.addLiteral(anno, L0.HasName, L0.NameOf, L0.String, name, Bindings.STRING);
1068 if (sourceAnnotation != null) {
1071 String sourceName = graph.getPossibleRelatedValue(sourceAnnotation, L0.HasName, Bindings.STRING);
1072 if(sourceName != null) graph.addLiteral(anno, L0.HasName, L0.NameOf, L0.String, sourceName, Bindings.STRING);
1075 Resource sourceType = graph.getSingleType(sourceAnnotation);
1076 List<AnnotationMap> am = getAnnotationMap(graph, annotationType, sourceType);
1077 for (AnnotationMap a : am) {
1078 Resource object = graph.getSingleObject(sourceAnnotation, a.sourcePredicate);
1079 Collection<Resource> objectTypes = graph.getTypes(object);
1080 if (objectTypes.contains(L0.Literal)) {
1081 Object value = graph.getValue(object, a.defaultValueBinding);
1082 if (!ObjectUtils.objectEquals(value, a.defaultValue)) {
1083 graph.addLiteral(anno, a.annotationPredicate, a.annotationPredicateInverse, a.defaultValueType, value, a.defaultValueBinding);
1089 if (container != null && property != null) {
1090 graph.claim(container, property, anno);
1097 private static class AnnotationMap {
1099 final public Resource sourcePredicate;
1100 final public Resource sourcePredicateInverse;
1102 final public Resource annotationPredicate;
1103 final public Resource annotationPredicateInverse;
1105 final public Resource defaultValueType;
1106 final public Object defaultValue;
1107 final public Binding defaultValueBinding;
1109 public AnnotationMap(Resource sp, Resource spi, Resource tp, Resource tpi, Resource defaultValueType, Object defaultValue, Binding defaultValueBinding) {
1110 sourcePredicate = sp;
1111 sourcePredicateInverse = spi;
1112 annotationPredicate = tp;
1113 annotationPredicateInverse = tpi;
1114 this.defaultValueType = defaultValueType;
1115 this.defaultValue = defaultValue;
1116 this.defaultValueBinding = defaultValueBinding;
1121 public static List<AnnotationMap> getAnnotationMap(ReadGraph graph, Resource annotationType, Resource sourceType) throws DatabaseException {
1122 return graph.syncRequest(new AnnotationMapRequest(annotationType, sourceType), TransientCacheListener.<List<AnnotationMap>>instance());
1125 static class AnnotationMapRequest extends ResourceRead2<List<AnnotationMap>> {
1127 public AnnotationMapRequest(Resource annotationType, Resource sourceType) {
1128 super(annotationType, sourceType);
1132 public List<AnnotationMap> perform(ReadGraph graph) throws DatabaseException {
1134 Layer0 L0 = Layer0.getInstance(graph);
1136 ArrayList<AnnotationMap> result = new ArrayList<AnnotationMap>();
1138 Map<String, Resource> annotationPredicates = new HashMap<String, Resource>();
1139 for(Resource predicate : graph.getObjects(resource, L0.DomainOf)) {
1140 String name = graph.getRelatedValue(predicate, L0.HasName, Bindings.STRING);
1141 annotationPredicates.put(name, predicate);
1143 Map<String, Resource> sourcePredicates = new HashMap<String, Resource>();
1144 for(Resource predicate : graph.getObjects(resource2, L0.DomainOf)) {
1145 String name = graph.getRelatedValue(predicate, L0.HasName, Bindings.STRING);
1146 sourcePredicates.put(name, predicate);
1149 for(String key : sourcePredicates.keySet()) {
1150 Resource sourcePredicate = sourcePredicates.get(key);
1151 Resource anno = annotationPredicates.get(key);
1152 if(sourcePredicate != null && anno != null) {
1153 Resource defaultValueType = graph.getSingleObject(anno, L0.HasRange);
1154 Binding defaultValueBinding = null;
1155 Object defaultValue = null;
1156 Resource assertion = graph.getPossibleObject(anno, L0.HasPredicateInverse);
1157 if (assertion != null) {
1158 Resource object = graph.getPossibleObject(assertion, L0.HasObject);
1159 if (object != null) {
1160 if(graph.isInstanceOf(object, L0.Literal)) {
1161 Datatype dt = graph.getDataType(object);
1162 defaultValueBinding = Bindings.getBeanBinding(dt);
1163 defaultValue = graph.getPossibleValue(object);
1167 result.add(new AnnotationMap(
1168 sourcePredicate, graph.getInverse(sourcePredicate),
1169 anno, graph.getInverse(anno),
1170 defaultValueType, defaultValue, defaultValueBinding));
1180 public static final String DRAWING_TEMPLATE_FORMAT = "drawingTemplate";
1181 public static final String DRAWING_TEMPLATE_FORMAT_V1 = DRAWING_TEMPLATE_FORMAT + ":1";
1182 public static final String DRAWING_TEMPLATE_FORMAT_V2 = DRAWING_TEMPLATE_FORMAT + ":2";
1184 public static Resource importDrawingTemplate(final Resource model, final File file) throws IOException, SerializationException, DatabaseException, TransferableGraphException {
1188 final Resource library = Simantics.sync(new WriteResultRequest<Resource>() {
1191 public Resource perform(WriteGraph graph) throws DatabaseException {
1193 Layer0 L0 = Layer0.getInstance(graph);
1194 Template2dResource TEMPLATE = Template2dResource.getInstance(graph);
1195 Resource root = graph.getPossibleObject(model, TEMPLATE.HasDrawingTemplateRoot);
1197 Template2dResource TEMPLATE2D = Template2dResource.getInstance(graph);
1198 root = graph.newResource();
1199 graph.claim(root, L0.InstanceOf, null, TEMPLATE2D.DrawingTemplateLibrary);
1200 graph.claim(root, L0.InstanceOf, null, TEMPLATE2D.DrawingTemplateLibraryUI);
1201 graph.claimLiteral(root, L0.HasName, L0.NameOf, L0.String, "Diagram Templates", Bindings.STRING);
1202 graph.claim(root, L0.PartOf, L0.ConsistsOf, model);
1203 graph.claim(model, TEMPLATE2D.HasDrawingTemplateRoot, root);
1206 String name = new Path(file.getAbsolutePath()).removeFileExtension().lastSegment();
1208 Resource existing = Layer0Utils.getPossibleChild(graph, root, name);
1209 if(existing != null)
1210 graph.deny(root, L0.ConsistsOf, existing);
1219 final DefaultPasteImportAdvisor advisor = new DefaultPasteImportAdvisor(library);
1222 HashMap<String, FormatHandler<Object>> handlers = new HashMap<String, FormatHandler<Object>>();
1223 FormatHandler<Object> handler = new FormatHandler<Object>() {
1225 public Binding getBinding() {
1226 return TransferableGraph1.BINDING;
1230 public Object process(DataContainer container) throws Exception {
1231 TransferableGraphs.importGraph1(Simantics.getSession(), (TransferableGraph1)container.content.getValue(),
1236 handlers.put(DRAWING_TEMPLATE_FORMAT_V1, handler);
1237 handlers.put(DRAWING_TEMPLATE_FORMAT_V2, handler);
1239 DataContainers.readFile(file, handlers);
1240 } catch(DataFormatException e) {
1241 throw new IOException(e);
1242 } catch(IOException e) {
1244 } catch(Exception e) {
1245 if(e instanceof RuntimeException)
1246 throw (RuntimeException)e;
1248 throw new RuntimeException(e);
1251 } catch(IOException e) {
1254 return advisor.getRoot();
1256 } catch (Throwable t) {
1257 Logger.defaultLogError("Unexpected exception while importing diagram template.", t);
1265 public static Collection<Variable> getMappedVariables(ReadGraph graph, Variable source) throws DatabaseException {
1267 ArrayList<Variable> result = new ArrayList<Variable>();
1268 Resource represents = source.getPossibleRepresents(graph);
1269 if(represents == null) return Collections.emptyList();
1270 ModelingResources MOD = ModelingResources.getInstance(graph);
1271 for(Resource r : getElementCorrespondendences(graph, represents)) {
1272 result.add(Variables.getVariable(graph, r));
1274 for(Resource r : graph.getObjects(represents, MOD.ComponentToElement)) {
1275 result.add(Variables.getVariable(graph, r));
1277 for(Resource r : graph.getObjects(represents, MOD.DiagramToComposite)) {
1278 result.add(Variables.getVariable(graph, r));
1280 for(Resource r : graph.getObjects(represents, MOD.CompositeToDiagram)) {
1281 result.add(Variables.getVariable(graph, r));
1287 public static Resource getPossibleModel(ReadGraph graph, Resource resource) throws DatabaseException {
1289 PossibleModel pm = new PossibleModel(resource);
1290 Resource model = pm.perform(graph);
1294 public static Resource possibleIndexRoot(ReadGraph graph, Resource resource) throws DatabaseException {
1295 return graph.syncRequest(new PossibleIndexRoot(resource));
1298 public static Object getMonitorValue(StructuralComponent _variable, ReadGraph graph, String path) throws DatabaseException {
1299 Variable variable = ((VariableStructuralContext)_variable).variable;
1300 Variable var = variable.browse(graph, path);
1301 return var.getValue(graph);
1304 public static void createSharedOntologyWithUI(ReadGraph graph, Variable variable, Resource baseType) throws DatabaseException {
1305 createSharedOntologyWithUI(graph, baseType);
1308 public static void createSharedOntologyWithUI(ReadGraph graph, Resource baseType) throws DatabaseException {
1310 // Resource indexRoot_ = variable.getPossibleRepresents(graph);
1311 // if(indexRoot_ == null) return;
1313 final Map<Resource, Pair<String,ImageDescriptor>> map = new HashMap<Resource, Pair<String,ImageDescriptor>>();
1315 Layer0 L0 = Layer0.getInstance(graph);
1316 SimulationResource SIMU = SimulationResource.getInstance(graph);
1317 Instances query = graph.adapt(L0.IndexRootType, Instances.class);
1318 for(Resource ontology : Layer0Utils.listOntologies(graph)) {
1319 for(Resource type : query.find(graph, ontology)) {
1320 if(graph.isInheritedFrom(type, SIMU.Model)) continue;
1321 if(graph.hasStatement(type, L0.Abstract)) continue;
1322 if(!graph.isInheritedFrom(type, baseType)) continue;
1323 String name = graph.getPossibleRelatedValue(type, L0.HasLabel, Bindings.STRING);
1324 if(name == null) name = graph.getRelatedValue(type, L0.HasName, Bindings.STRING);
1325 map.put(type, new Pair<String,ImageDescriptor>(name, null));
1329 Display.getDefault().asyncExec(new Runnable() {
1332 Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();
1333 CreateSharedOntologyDialog page = new CreateSharedOntologyDialog(shell, map, "Select type and name of new shared library");
1334 if (page.open() == Window.OK) {
1335 Object[] result = page.getResult();
1336 if (result != null && result.length == 1) {
1337 final Resource res = (Resource)result[0];
1338 final String name = "http://" + page.getName();
1339 Simantics.getSession().asyncRequest(new WriteRequest() {
1342 public void perform(WriteGraph graph) throws DatabaseException {
1343 graph.markUndoPoint();
1344 Resource target = Simantics.applySCL("Simantics/SharedOntologies", "createSharedOntology", graph, name+"@A", res);
1346 ProjectResource PROJ = ProjectResource.getInstance(graph);
1347 Layer0 L0 = Layer0.getInstance(graph);
1348 for(Resource dep : graph.getObjects(Simantics.getProjectResource(), L0.IsLinkedTo)) {
1349 if(graph.isInstanceOf(dep, PROJ.NamespaceRequirement)) {
1350 for(Resource req : graph.getObjects(dep, PROJ.RequiresNamespace)) {
1351 String uri = graph.getPossibleValue(req, Bindings.STRING);
1353 Resource ns = graph.getResource(uri);
1355 graph.claim(target, L0.IsLinkedTo, null, ns);
1372 public static void unlinkSharedOntologyWithUI(ReadGraph graph, Variable variable, final List<Resource> libraries) throws DatabaseException {
1374 final Resource indexRoot = variable.getPossibleRepresents(graph);
1375 if(indexRoot == null) return;
1377 StructuralResource2 STR = StructuralResource2.getInstance(graph);
1379 final List<String> instances = new ArrayList<String>();
1381 DiagramResource DIA = DiagramResource.getInstance(graph);
1383 for(Resource library : libraries) {
1384 for(Resource type : ModelingUtils.searchByTypeShallow(graph, library, STR.ComponentType)) {
1385 for(Resource instance : ModelingUtils.searchByTypeShallow(graph, indexRoot, type)) {
1387 if(graph.isInstanceOf(instance, DIA.Element)) continue;
1388 String name = Versions.getStandardPathNameString(graph, instance);
1389 instances.add(name);
1394 if(instances.isEmpty()) {
1395 graph.getSession().asyncRequest(new WriteRequest() {
1398 public void perform(WriteGraph graph) throws DatabaseException {
1399 Layer0 L0 = Layer0.getInstance(graph);
1400 for(Resource library : libraries)
1401 graph.deny(indexRoot, L0.IsLinkedTo, library);
1408 PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
1412 if (!PlatformUI.isWorkbenchRunning())
1415 Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();
1416 ListDialog<String> dialog = new ListDialog<String>(
1419 "Cannot unlink selected libraries",
1420 "Libraries cannot be unlinked since the following instances are referring to them.") {
1422 protected void createButtonsForButtonBar(Composite parent) {
1423 createButton(parent, IDialogConstants.OK_ID, IDialogConstants.OK_LABEL,true);
1427 int result = dialog.open();
1428 if (result != Dialog.OK)
1436 public static MigratedImportResult importSharedOntologyWithResult(String fileName) throws Exception {
1438 DataContainer dc = DataContainers.readFile(new File(fileName));
1439 TransferableGraph1 tg = (TransferableGraph1)dc.content.getValue(TransferableGraph1.BINDING);
1440 Variant draftStatus = dc.metadata.get(DraftStatusBean.EXTENSION_KEY);
1441 return MigrationUtils.importSharedOntology(Simantics.getSession(), tg, draftStatus == null);
1442 } catch (Exception e) {
1443 Logger.defaultLogError(e);
1448 public static void importSharedOntology(String fileName) throws Exception {
1449 importSharedOntologyWithResult(fileName);
1452 public static List<Resource> importSharedOntology2(String fileName) throws Exception {
1453 MigratedImportResult result = importSharedOntologyWithResult(fileName);
1454 return new ArrayList<Resource>(result.roots);
1457 public static void importSharedOntologyWithUI(ReadGraph graph, final Variable variable) throws DatabaseException {
1459 Display.getDefault().asyncExec(new Runnable() {
1463 IStructuredSelection sel = new StructuredSelection(variable);
1464 openWizard(Display.getCurrent(), sel, "org.simantics.modeling.ui.sharedOntologyImportWizard");
1471 public static class LibraryInfo implements Comparable<LibraryInfo> {
1472 public NamedResource library;
1473 public DraftStatusBean draft;
1474 public LibraryInfo(String name, Resource r, DraftStatusBean draft) {
1475 library = new NamedResource(name, r);
1479 public int compareTo(LibraryInfo o) {
1480 return library.compareTo(o.library);
1483 public int hashCode() {
1484 return library.hashCode();
1487 public boolean equals(Object object) {
1490 else if (object == null)
1492 else if (!(object instanceof LibraryInfo))
1494 LibraryInfo info = (LibraryInfo)object;
1495 return info.library.equals(library);
1500 public static void exportSharedOntologyWithUI(final Resource sharedOntology) {
1502 Display.getDefault().asyncExec(new Runnable() {
1506 HintContext hc = new HintContext();
1507 hc.setHint(SelectionHints.KEY_MAIN, sharedOntology);
1508 IStructuredSelection sel = new StructuredSelection(hc);
1509 openWizard(Display.getCurrent(), sel, "org.simantics.modeling.ui.sharedOntologyExportWizard");
1516 public static TransferableGraph1 exportSharedOntology(IProgressMonitor monitor, RequestProcessor processor, File location, String format, int version, final LibraryInfo info) throws DatabaseException, IOException {
1518 if(monitor == null) monitor = new NullProgressMonitor();
1520 // TODO: figure out a way to make the TG go directly into a file
1521 // instead of having it all in memory at once.
1523 monitor.beginTask("Exporting shared library...", 100);
1524 SimanticsClipboard clipboard = processor.syncRequest(new Read<SimanticsClipboard>() {
1526 public SimanticsClipboard perform(ReadGraph graph) throws DatabaseException {
1527 CopyHandler ch = graph.adapt(info.library.getResource(), CopyHandler.class);
1528 SimanticsClipboardImpl clipboard = new SimanticsClipboardImpl();
1529 ch.copyToClipboard(graph, clipboard);
1534 TreeMap<String,Variant> metadata = getExportMetadata();
1535 DraftStatusBean draft = info.draft;
1537 metadata.put(DraftStatusBean.EXTENSION_KEY, new Variant(DraftStatusBean.BINDING ,draft));
1540 for (Set<Representation> object : clipboard.getContents()) {
1542 TransferableGraph1 tg = ClipboardUtils.accept(processor, object, SimanticsKeys.KEY_TRANSFERABLE_GRAPH);
1545 Variant edb = tg.extensions.get(ExternalDownloadBean.EXTENSION_KEY);
1547 metadata.put(ExternalDownloadBean.EXTENSION_KEY, edb);
1550 if(location != null) {
1551 monitor.setTaskName("Writing transferable graph...");
1552 DataContainers.writeFile(location, new DataContainer(
1554 metadata, new Variant(TransferableGraph1.BINDING, tg)));
1562 throw new DatabaseException("Failed to export");
1566 public static TreeMap<String, Variant> getExportMetadata() {
1568 TreeMap<String,Variant> metadata = new TreeMap<String,Variant>();
1569 metadata.put("date", Variant.ofInstance(DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL).format(new Date())));
1570 metadata.put("author", Variant.ofInstance(System.getProperty("user.name", "")));
1576 public static void createNewVersionWithoutUI(WriteGraph graph, Resource resource) throws DatabaseException {
1577 VersionInfo info = graph.syncRequest(new VersionInfoRequest(resource));
1578 int currentVersion = Integer.parseInt(info.version);
1579 String result = Integer.toString(currentVersion + 1);
1580 createNewVersion(graph, resource, info, result);
1583 public static void createNewVersionWithUI(ReadGraph graph, final Resource resource) throws DatabaseException {
1585 final VersionInfo info = graph.syncRequest(new VersionInfoRequest(resource));
1587 Display.getDefault().asyncExec(new Runnable() {
1590 Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();
1591 CreateVersionDialog dialog = new CreateVersionDialog(shell, info);
1592 if (dialog.open() == Window.OK) {
1593 final String result = dialog.getResult();
1594 Simantics.getSession().asyncRequest(new WriteRequest() {
1596 public void perform(WriteGraph graph) throws DatabaseException {
1597 createNewVersion(graph, resource, info, result);
1606 public static void createNewVersion(WriteGraph graph, Resource resource, final VersionInfo info, final String result) throws DatabaseException {
1607 graph.markUndoPoint();
1608 Layer0 L0 = Layer0.getInstance(graph);
1609 Resource parent = graph.getPossibleObject(resource, L0.PartOf);
1610 if(parent == null) return;
1611 final String parentURI = graph.getPossibleURI(parent);
1612 if(parentURI == null) return;
1613 Layer0Utils.copyTo(graph, parent, resource, new PasteEventHandler() {
1616 public void postProcess(WriteGraph graph, Resource root) throws DatabaseException {
1617 Layer0 L0 = Layer0.getInstance(graph);
1618 graph.deny(root, L0.Entity_published);
1622 public IImportAdvisor2 createAdvisor(ReadGraph graph, ImportAdvisorFactory factory, Resource target) throws DatabaseException {
1623 Map<String,Object> context = new HashMap<String,Object>();
1624 String base = parentURI + "/" + URIStringUtils.escape( info.baseName ) + "@";
1625 Map<String,String> renameMap = new HashMap<String,String>();
1626 renameMap.put(base + info.version, base + result);
1627 renameMap.put(info.baseName + "@" + info.version, info.baseName + "@" + result);
1628 context.put(ImportAdvisors.RENAME_MAP, renameMap);
1629 return factory.create(graph, target, context);
1633 Layer0Utils.addCommentMetadata(graph, "Created new version of " + info.baseName);
1636 public static boolean isUserComponent(ReadGraph graph, Resource type) throws DatabaseException {
1637 StructuralResource2 STR = StructuralResource2.getInstance(graph);
1638 if(graph.isInstanceOf(type, STR.ProceduralComponentType)) return true;
1639 else if (graph.hasStatement(type, STR.IsDefinedBy)) return true;
1643 public static void publishComponentTypeWithUI(WriteGraph graph, final Resource componentType) throws DatabaseException {
1645 Layer0 L0 = Layer0.getInstance(graph);
1646 StructuralResource2 STR = StructuralResource2.getInstance(graph);
1647 Resource composite = graph.getPossibleObject(componentType, STR.IsDefinedBy);
1648 final List<String> instances = new ArrayList<String>();
1649 if(composite != null) {
1650 for(Resource component : graph.syncRequest(new ObjectsWithType(composite, L0.ConsistsOf, STR.Component))) {
1651 Resource type = graph.getPossibleType(component, STR.Component);
1652 if(type != null && isUserComponent(graph, type)) {
1653 if(!Layer0Utils.isPublished(graph, type)) instances.add(Versions.getStandardPathNameString(graph, component));
1658 if(instances.isEmpty()) {
1659 graph.getSession().asyncRequest(new WriteRequest() {
1662 public void perform(WriteGraph graph) throws DatabaseException {
1663 graph.markUndoPoint();
1664 publish(graph, componentType);
1671 PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
1675 if (!PlatformUI.isWorkbenchRunning())
1678 Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();
1679 ListDialog<String> dialog = new ListDialog<String>(
1682 "Cannot publish user component",
1683 "The following instances are referring to unpublished user components.") {
1685 protected void createButtonsForButtonBar(Composite parent) {
1686 createButton(parent, IDialogConstants.OK_ID, IDialogConstants.OK_LABEL,true);
1690 int result = dialog.open();
1691 if (result != Dialog.OK)
1699 public static void publishSharedOntologyWithUI(WriteGraph graph, final Resource sharedOntology) throws DatabaseException {
1701 Layer0 L0 = Layer0.getInstance(graph);
1702 DiagramResource DIA = DiagramResource.getInstance(graph);
1703 StructuralResource2 STR = StructuralResource2.getInstance(graph);
1704 final List<String> instances = new ArrayList<String>();
1705 for(Resource type : searchByTypeShallow(graph, sharedOntology, STR.ComponentType)) {
1707 if(graph.isInheritedFrom(type, DIA.Element)) continue;
1708 if(!Layer0Utils.isPublished(graph, type)) instances.add(Versions.getStandardPathNameString(graph, type));
1710 for(Resource dep : graph.syncRequest(new ObjectsWithType(sharedOntology, L0.IsLinkedTo, L0.SharedOntology))) {
1711 if(!Layer0Utils.isPublished(graph, dep)) instances.add(Versions.getStandardPathNameString(graph, dep));
1714 if(instances.isEmpty()) {
1715 graph.getSession().asyncRequest(new WriteRequest() {
1718 public void perform(WriteGraph graph) throws DatabaseException {
1719 graph.markUndoPoint();
1720 publish(graph, sharedOntology);
1727 PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
1731 if (!PlatformUI.isWorkbenchRunning())
1734 Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();
1735 ListDialog<String> dialog = new ListDialog<String>(
1738 "Cannot publish shared library",
1739 "The following dependencies are unpublished.") {
1741 protected void createButtonsForButtonBar(Composite parent) {
1742 createButton(parent, IDialogConstants.OK_ID, IDialogConstants.OK_LABEL,true);
1746 int result = dialog.open();
1747 if (result != Dialog.OK)
1755 public static Resource createSCLModuleDefault(WriteGraph graph, Resource target) throws DatabaseException {
1756 String name = NameUtils.findFreshEscapedName(graph, "SCLModule", target);
1757 return createSCLModule(graph, target, name);
1760 public static Resource createSCLModule(WriteGraph graph, Resource target, String name) throws DatabaseException {
1761 graph.markUndoPoint();
1762 Layer0 L0 = Layer0.getInstance(graph);
1763 Resource sclModule = GraphUtils.create2(graph, L0.SCLModule,
1766 L0.SCLModule_definition, "");
1767 Layer0Utils.addCommentMetadata(graph, "Created SCL Module " + name + " " + sclModule.toString());
1771 public static Resource setSCLModuleDefinition(WriteGraph graph, Resource module, String definition) throws DatabaseException {
1772 graph.markUndoPoint();
1773 Layer0 L0 = Layer0.getInstance(graph);
1774 graph.claimLiteral(module, L0.SCLModule_definition, definition, Bindings.STRING);
1775 Layer0Utils.addCommentMetadata(graph, "Set SCL module " + module + " definition.");
1779 public static Resource createSCLScriptDefault(WriteGraph graph, Resource target) throws DatabaseException {
1780 String name = NameUtils.findFreshEscapedName(graph, "SCLScript", target);
1781 return createSCLScript(graph, target, name);
1784 public static Resource createSCLScript(WriteGraph graph, Resource target, String name) throws DatabaseException {
1785 graph.markUndoPoint();
1786 Layer0 L0 = Layer0.getInstance(graph);
1787 Resource sclModule = GraphUtils.create2(graph, L0.SCLScript,
1790 L0.SCLScript_definition, "");
1791 Layer0Utils.addCommentMetadata(graph, "Created SCL Script " + name + " " + sclModule.toString());
1795 public static Resource setSCLScriptDefinition(WriteGraph graph, Resource script, String definition) throws DatabaseException {
1796 graph.markUndoPoint();
1797 Layer0 L0 = Layer0.getInstance(graph);
1798 graph.claimLiteral(script, L0.SCLScript_definition, definition, Bindings.STRING);
1799 Layer0Utils.addCommentMetadata(graph, "Set SCL script " + script + " definition.");
1803 public static Resource createPGraphDefault(WriteGraph graph, Resource target) throws DatabaseException {
1804 String name = NameUtils.findFreshEscapedName(graph, "Ontology Definition File", target);
1805 return createPGraph(graph, target, name);
1808 public static Resource createPGraph(WriteGraph graph, Resource target, String name) throws DatabaseException {
1809 graph.markUndoPoint();
1810 Layer0 L0 = Layer0.getInstance(graph);
1811 Resource file = GraphUtils.create2(graph, L0.PGraph,
1814 L0.PGraph_definition, "");
1815 Layer0Utils.addCommentMetadata(graph, "Created Ontology Definition File " + name + " " + file.toString());
1819 public static Resource setPGraphDefinition(WriteGraph graph, Resource pgraph, String definition) throws DatabaseException {
1820 graph.markUndoPoint();
1821 Layer0 L0 = Layer0.getInstance(graph);
1822 graph.claimLiteral(pgraph, L0.PGraph_definition, definition, Bindings.STRING);
1823 Layer0Utils.addCommentMetadata(graph, "Set PGraph " + pgraph + " definition.");
1827 public static void publish(WriteGraph graph, Resource target) throws DatabaseException {
1828 Layer0 L0 = Layer0.getInstance(graph);
1829 graph.claimLiteral(target, L0.Entity_published, true, Bindings.BOOLEAN);
1830 Layer0Utils.addCommentMetadata(graph, "Published " + graph.getPossibleRelatedValue2(target, L0.HasName, Bindings.STRING) + " " + target.toString());
1833 public static boolean isLinkedToDeep(ReadGraph graph, Resource r1, Resource r2) throws DatabaseException {
1834 return graph.syncRequest(new IsLinkedTo(r1, r2));
1837 public static void openWizard(Display display, IStructuredSelection selection, String id) {
1838 // First see if this is a "new wizard".
1839 IWizardDescriptor descriptor = PlatformUI.getWorkbench()
1840 .getNewWizardRegistry().findWizard(id);
1841 // If not check if it is an "import wizard".
1842 if (descriptor == null) {
1843 descriptor = PlatformUI.getWorkbench().getImportWizardRegistry()
1846 // Or maybe an export wizard
1847 if (descriptor == null) {
1848 descriptor = PlatformUI.getWorkbench().getExportWizardRegistry()
1852 // Then if we have a wizard, open it.
1853 if (descriptor != null) {
1854 IWorkbenchWizard wizard = descriptor.createWizard();
1855 wizard.init(PlatformUI.getWorkbench(), selection);
1856 WizardDialog wd = new WizardDialog(display.getActiveShell(), wizard);
1857 wd.setTitle(wizard.getWindowTitle());
1860 } catch (CoreException e) {
1861 e.printStackTrace();
1865 public static String withinEpsilon(double value, double reference, double epsilon) {
1866 if(Math.abs(value-reference) < epsilon) return "True";
1867 else return "Not within epsilon value=" + value + ", reference=" + reference + " , epsilon=" + epsilon;
1870 public static boolean needsIdentifier(ReadGraph graph, Resource r) throws DatabaseException {
1871 Layer0 L0 = Layer0.getInstance(graph);
1872 Collection<Resource> types = graph.getPrincipalTypes(r);
1873 for(Resource type : types)
1874 if(graph.syncRequest(new IsInstanceOf(type, L0.TypeWithIdentifier), TransientCacheAsyncListener.<Boolean>instance()))
1879 public static boolean needsModificationInfo(ReadGraph graph, Resource r) throws DatabaseException {
1880 ModelingResources MOD = ModelingResources.getInstance(graph);
1881 Collection<Resource> types = graph.getPrincipalTypes(r);
1882 for(Resource type : types)
1883 if(graph.syncRequest(new IsInstanceOf(type, MOD.TypeWithChangeInformation), TransientCacheAsyncListener.<Boolean>instance()))
1888 public static void attachCreationInformation(IProgressMonitor monitor, WriteGraph graph, Resource model) throws DatabaseException {
1890 if(monitor == null) monitor = new NullProgressMonitor();
1892 final String author = System.getProperty("user.name", "");
1893 final long time = System.currentTimeMillis();
1895 monitor.setTaskName("Attach creation information");
1897 ModelingResources MOD = ModelingResources.getInstance(graph);
1898 Collection<Resource> rs = ModelingUtils.searchByType(graph, model, MOD.TypeWithChangeInformation);
1899 Collection<Resource> supers = ModelingUtils.getMostUnspecificTypes(graph, rs);
1901 CollectionSupport cs = graph.getService(CollectionSupport.class);
1902 Collection<Resource> set = cs.createSet();
1903 for(Resource type : supers) {
1904 set.addAll(ModelingUtils.searchByTypeShallow(graph, model, type));
1906 Collection<Resource> instances = Layer0Utils.sortByCluster(graph, set);
1908 int pc = instances.size() / 100;
1912 for(Resource instance : instances) {
1913 ChangeInformation info = graph.getPossibleRelatedValue(instance, MOD.changeInformation, ChangeInformation.BINDING);
1915 info = new ChangeInformation();
1916 info.createdAt = time;
1917 info.createdBy = author;
1918 info.modifiedAt = time;
1919 info.modifiedBy = author;
1920 graph.claimLiteral(instance, MOD.changeInformation, MOD.changeInformation_Inverse, MOD.ChangeInformation, info, ChangeInformation.BINDING);
1925 Double d = (100.0*done)/instances.size();
1926 monitor.setTaskName("Attach creation information " + d.intValue() + "%");
1931 monitor.setTaskName("Attach creation information - commit");
1935 public static class DiagramComponentInfo {
1937 private static String CHILD_PREFIX = "child:";
1939 final private String compositePathAndName;
1940 final private String componentName;
1941 final private GUID guid;
1943 public DiagramComponentInfo(String compositePathAndName, String componentName, GUID guid) {
1944 this.compositePathAndName = compositePathAndName;
1945 this.componentName = componentName;
1949 public static boolean isDiagramComponent(String tgName) {
1950 return tgName.startsWith(CHILD_PREFIX);
1953 public String getTGName(CompositeInfo info) {
1954 return CHILD_PREFIX + info.getOriginalPath() + ModelingUtils.COMPOSITE_SEPARATOR_CHAR + info.getEscapedName() + ModelingUtils.COMPOSITE_SEPARATOR_CHAR + getEscapedComponentName() + ModelingUtils.COMPOSITE_SEPARATOR_CHAR + guid.indexString();
1957 public boolean existsGUID(ReadGraph graph, Resource indexRoot) throws DatabaseException {
1958 Collection<Resource> res = ModelingUtils.searchByGUID(graph, indexRoot, guid);
1959 return !res.isEmpty();
1962 public static DiagramComponentInfo fromResource(ReadGraph graph, CompositeInfo info, Resource resource) throws DatabaseException {
1963 Layer0 L0 = Layer0.getInstance(graph);
1964 GUID childId = graph.getRelatedValue(resource, L0.identifier, GUID.BINDING);
1965 String childName = graph.getRelatedValue(resource, L0.HasName, Bindings.STRING);
1966 return new DiagramComponentInfo(info.getStateKey(), URIStringUtils.escape(childName), childId);
1969 public GUID getGUID() {
1973 public String getEscapedCompositePathAndName() {
1974 return compositePathAndName;
1977 public String getEscapedComponentName() {
1978 return componentName;
1981 public String getUnescapedComponentName() {
1982 return URIStringUtils.unescape(getEscapedComponentName());
1985 // "child:path#compositeName#componentName#guid"
1986 public static DiagramComponentInfo parse(String tgName) {
1988 String name = tgName.substring(CHILD_PREFIX.length());
1989 String compositePathAndName = "";
1990 String moduleName = name;
1991 GUID guid = GUID.invalid();
1992 int lastHash = name.lastIndexOf(ModelingUtils.COMPOSITE_SEPARATOR_CHAR);
1994 String first = name.substring(0, lastHash);
1995 String second = name.substring(lastHash+1);
1996 lastHash = first.lastIndexOf(ModelingUtils.COMPOSITE_SEPARATOR_CHAR);
1998 compositePathAndName = first.substring(0, lastHash);
1999 moduleName = first.substring(lastHash+1);
2000 guid = GUID.parseIndexString(second);
2002 compositePathAndName = first;
2003 moduleName = second;
2006 return new DiagramComponentInfo(compositePathAndName, moduleName, guid);
2012 public int hashCode() {
2013 final int prime = 31;
2015 result = prime * result + ((compositePathAndName == null) ? 0 : compositePathAndName.hashCode());
2016 result = prime * result + ((componentName == null) ? 0 : componentName.hashCode());
2021 public boolean equals(Object obj) {
2026 if (getClass() != obj.getClass())
2028 DiagramComponentInfo other = (DiagramComponentInfo) obj;
2029 if (compositePathAndName == null) {
2030 if (other.compositePathAndName != null)
2032 } else if (!compositePathAndName.equals(other.compositePathAndName))
2034 if (componentName == null) {
2035 if (other.componentName != null)
2037 } else if (!componentName.equals(other.componentName))
2044 public static class CompositeInfo {
2046 public static String COMPOSITE_PREFIX = "composite:";
2048 final private boolean useGuids;
2049 final private boolean applyPaths;
2050 final private String path;
2051 final private String name;
2052 final private GUID guid;
2054 private CompositeInfo(boolean useGuids, boolean applyPaths, String path, String name, GUID guid) {
2055 this.useGuids = useGuids;
2056 this.applyPaths = applyPaths;
2063 public String toString() {
2064 return "CompositeInfo[useGuids=" + useGuids + ", applyPaths=" + applyPaths + ", path=" + path + ", name=" + name + ", guid=" + guid.indexString() + "]";
2067 public static boolean isComposite(String tgName) {
2068 return tgName.startsWith(COMPOSITE_PREFIX);
2071 public String getTGName() {
2072 return COMPOSITE_PREFIX + getOriginalPath() + ModelingUtils.COMPOSITE_SEPARATOR_CHAR + getEscapedName() + ModelingUtils.COMPOSITE_SEPARATOR_CHAR + guid.indexString();
2075 public boolean existsGUID(ReadGraph graph, Resource indexRoot) throws DatabaseException {
2076 Collection<Resource> res = ModelingUtils.searchByGUID(graph, indexRoot, guid);
2077 return !res.isEmpty();
2080 public static CompositeInfo fromResource(ReadGraph graph, Resource resource) throws DatabaseException {
2082 Layer0 L0 = Layer0.getInstance(graph);
2083 GUID rootId = graph.getRelatedValue(resource, L0.identifier, GUID.BINDING);
2084 String rootName = graph.getRelatedValue(resource, L0.HasName, Bindings.STRING);
2085 String escapedRootName = URIStringUtils.escape(rootName);
2086 String escapedPath = ModelingUtils.getDiagramCompositePath(graph, resource);
2087 return new CompositeInfo(true, true, escapedPath, escapedRootName, rootId);
2091 public static CompositeInfo parse(String tgName) {
2092 return parse(tgName, true, true);
2096 * Index 0 is root-relative folder path separated with '/' or null if target-relative positioning is used
2097 * Index 1 is diagram name
2099 public static CompositeInfo parse(String tgName, boolean applyPaths, boolean useGuids) {
2100 if(!tgName.startsWith(COMPOSITE_PREFIX)) return null;
2101 tgName = tgName.substring(COMPOSITE_PREFIX.length());
2102 if(!tgName.contains(COMPOSITE_SEPARATOR)) {
2103 if(useGuids) throw new IllegalStateException("GUID identifiers were not found for diagrams.");
2104 return new CompositeInfo(useGuids, applyPaths, null, tgName, null);
2106 String[] parts = tgName.split(COMPOSITE_SEPARATOR);
2107 if(parts.length == 2) {
2108 String name = parts[1];
2109 String path = applyPaths ? parts[0] : null;
2110 if(useGuids) throw new IllegalStateException("GUID identifiers were not found for diagrams.");
2111 return new CompositeInfo(useGuids, applyPaths, path, name, null);
2112 } else if(parts.length == 3) {
2113 String path = parts[0];
2114 String name = parts[1];
2115 GUID guid = GUID.parseIndexString(parts[2]);
2116 return new CompositeInfo(useGuids, applyPaths, path, name, guid);
2122 public GUID getGUID() {
2126 public String getEscapedName() {
2130 public String getUnescapedName() {
2131 return URIStringUtils.unescape(name);
2134 public String getOriginalPath() {
2138 public String getFinalPath() {
2139 if(applyPaths) return path;
2143 public CompositeInfo renamed(String newName) {
2144 return new CompositeInfo(useGuids, applyPaths, path, newName, guid);
2147 public String getStateKey() {
2148 return path + "#" + getEscapedName();
2151 private Resource getFromFolder(ReadGraph graph, Resource target) throws DatabaseException {
2152 Resource diagram = Layer0Utils.getPossibleChild(graph, target, URIStringUtils.unescape(name));
2153 if(diagram == null) return null;
2154 StructuralResource2 STR = StructuralResource2.getInstance(graph);
2155 return graph.isInstanceOf(diagram, STR.Composite) ? diagram : null;
2158 public Resource resolve(ReadGraph graph, Resource target) throws DatabaseException {
2160 if(useGuids && guid != null) {
2161 Resource indexRoot = graph.syncRequest(new IndexRoot(target));
2162 Collection<Resource> queryResult = searchByGUID(graph, indexRoot, guid);
2163 if(queryResult.size() == 1) {
2164 Resource composite = queryResult.iterator().next();
2165 StructuralResource2 STR = StructuralResource2.getInstance(graph);
2166 if(!graph.isInstanceOf(composite, STR.Composite)) return null;
2172 Resource folder = resolveFolder(graph, target);
2173 if(folder == null) return null;
2174 return getFromFolder(graph, folder);
2176 return getFromFolder(graph, target);
2181 public Resource resolveFolder(ReadGraph graph, Resource target) throws DatabaseException {
2183 String path = getFinalPath();
2184 if(path == null) return target;
2186 Resource folder = graph.syncRequest(new Configuration(target));
2187 String[] segments = path.split("/");
2188 for(int i=0;i<segments.length;i++) {
2189 if(segments[i].isEmpty()) continue;
2190 folder = Layer0Utils.getPossibleChild(graph, folder, URIStringUtils.unescape(segments[i]));
2191 if(folder == null) return null;
2200 public int hashCode() {
2202 if(useGuids) return guid.hashCode();
2204 final int prime = 31;
2205 int result = name.hashCode();
2206 result = prime * result + ((path == null) ? 0 : path.hashCode());
2212 public boolean equals(Object obj) {
2218 if (getClass() != obj.getClass())
2221 CompositeInfo other = (CompositeInfo) obj;
2223 if(useGuids) return guid.equals(other.guid);
2225 if (!name.equals(other.name))
2229 if (!path.equals(other.path))
2238 public static char COMPOSITE_SEPARATOR_CHAR = '#';
2239 public static String COMPOSITE_SEPARATOR = String.valueOf(COMPOSITE_SEPARATOR_CHAR);
2241 public static CompositeInfo parseCompositeNameFromRoot(Root root, boolean applyPaths, boolean useGuids) {
2242 return CompositeInfo.parse(root.name, applyPaths, useGuids);
2245 public static CompositeInfo parseCompositeNameFromRoot(Identity root, boolean applyPaths, boolean useGuids) {
2246 String coded = TransferableGraphUtils.getName(root);
2247 return CompositeInfo.parse(coded, applyPaths, useGuids);
2250 private static StringBuilder getDiagramCompositePathInternal(ReadGraph graph, Resource folder, StringBuilder builder) throws DatabaseException {
2251 SimulationResource SIMU = SimulationResource.getInstance(graph);
2252 Resource model = graph.getPossibleObject(folder, SIMU.IsConfigurationOf);
2253 if (model != null) return builder;
2255 Layer0 L0 = Layer0.getInstance(graph);
2256 String name = graph.getPossibleRelatedValue(folder, L0.HasName, Bindings.STRING);
2257 if (name == null) return null;
2258 Resource parent = graph.getPossibleObject(folder, L0.PartOf);
2259 if (parent == null) return null;
2261 StringBuilder sb = getDiagramCompositePathInternal(graph, parent, builder);
2262 if (sb == null) return null;
2263 if (sb.length() > 0)
2264 sb.append(URIStringUtils.NAMESPACE_PATH_SEPARATOR);
2265 sb.append( URIStringUtils.escape(name) );
2272 * @return diagram/folder path up until model configuration root with each
2273 * segment escaped using {@link URIStringUtils#escape(String)} and
2274 * {@value URIStringUtils#NAMESPACE_PATH_SEPARATOR} between each
2275 * segment or <code>null</code> if the specified diagram composite
2276 * is not part of any model configuration structure.
2277 * @throws DatabaseException
2279 public static String getDiagramCompositePath(ReadGraph graph, Resource diagram) throws DatabaseException {
2280 Layer0 L0 = Layer0.getInstance(graph);
2281 Resource parent = graph.getPossibleObject(diagram, L0.PartOf);
2282 if(parent == null) return null;
2283 StringBuilder sb = getDiagramCompositePathInternal(graph, parent, new StringBuilder());
2284 return sb != null ? sb.toString() : null;
2287 public static void exportModel(ReadGraph graph, Resource model, String fileName, String format, int version) throws DatabaseException {
2288 TransferableGraphConfiguration2 conf = new TransferableGraphConfiguration2(graph, model, true, false);
2289 exportModel(graph, conf, fileName, format, version);
2292 public static void exportModel(ReadGraph graph, TransferableGraphConfiguration2 conf, String fileName, String format, int version) throws DatabaseException {
2295 TransferableGraphSource s = graph.syncRequest(new ModelTransferableGraphSourceRequest(conf));
2296 TransferableGraphs.writeTransferableGraph(graph, format, version, s, new File(fileName));
2297 } catch (DatabaseException e) {
2299 } catch (Exception e) {
2300 throw new DatabaseException(e);
2305 public static TransferableGraph1 exportSharedOntology(ReadGraph graph, Resource library, String fileName, String format, int version) throws DatabaseException {
2307 Layer0 L0 = Layer0.getInstance(graph);
2308 String name = graph.getRelatedValue(library, L0.HasName, Bindings.STRING);
2310 DraftStatusBean draft = null;
2311 boolean published = Layer0Utils.isPublished(graph, library);
2312 if(!published) draft = new DraftStatusBean(new String[0]);
2314 LibraryInfo info = new LibraryInfo(name, library, draft);
2317 return exportSharedOntology(new NullProgressMonitor(), graph, fileName != null ? new File(fileName) : null, format, version, info);
2318 } catch (IOException e) {
2319 throw new DatabaseException(e);
2324 public static DraftStatusBean getDependencyDraftStatus(ReadGraph graph, Resource library) throws DatabaseException {
2325 Layer0 L0 = Layer0.getInstance(graph);
2326 List<String> drafts = new ArrayList<>();
2327 for (Resource shared : graph.syncRequest(new ObjectsWithType(library, L0.IsLinkedTo, L0.SharedOntology))) {
2328 boolean published = Layer0Utils.isPublished(graph, shared);
2330 drafts.add(graph.getURI(shared));
2332 return drafts.isEmpty() ? null : new DraftStatusBean(drafts);
2335 public static Set<Resource> getMostUnspecificTypes(final ReadGraph graph, Collection<Resource> types) throws DatabaseException {
2337 final Set<Resource> work = new HashSet<Resource>(types);
2338 for(Resource type : types) {
2339 Set<Resource> supers = graph.getSupertypes(type);
2340 if(!Collections.disjoint(supers, work)) work.remove(type);
2347 public static void rewriteGUIDS(WriteGraph graph, Resource root, boolean deep) throws DatabaseException {
2348 List<Resource> todo = new ArrayList<Resource>();
2350 Layer0 L0 = Layer0.getInstance(graph);
2351 while(!todo.isEmpty()) {
2352 Resource resource = todo.remove(todo.size()-1);
2353 Layer0Utils.claimNewIdentifier(graph, resource, false);
2355 todo.addAll(graph.getObjects(resource, L0.ConsistsOf));
2359 public static void createMissingGUIDs(IProgressMonitor monitor, WriteGraph graph, Collection<Resource> roots) throws DatabaseException {
2361 if(monitor == null) monitor = new NullProgressMonitor();
2363 Layer0 L0 = Layer0.getInstance(graph);
2365 // Allow this process to make 50k queries
2366 QueryMemoryWatcher memory = new QueryMemoryWatcher(graph, 50000);
2368 for(Resource root : roots) {
2370 boolean madeChanges = false;
2372 monitor.setTaskName("Creating missing GUID identifiers " + NameUtils.getSafeName(graph, root));
2373 Resource indexRoot = graph.syncRequest(new PossibleIndexRoot(root));
2374 for(Resource r : searchByTypeShallow(graph, indexRoot, L0.Entity)) {
2378 if(graph.isImmutable(r)) continue;
2380 if(!ModelingUtils.needsIdentifier(graph, r)) continue;
2382 GUID existing = graph.getPossibleRelatedValue(r, L0.identifier, GUID.BINDING);
2383 if(existing == null) {
2384 Layer0Utils.claimNewIdentifier(graph, r, true);
2391 ModelingUtils.deleteIndex(graph, root);
2398 public static boolean activateModel(WriteGraph graph, Resource model) throws DatabaseException {
2399 return graph.syncRequest(new ActivateModel(Simantics.getProjectResource(), model));
2402 public static File fileDialog(String title, List<Tuple> namesAndExtensions) {
2404 Display display = Display.getCurrent();
2405 Shell shell = display.getActiveShell();
2407 FileDialog dialog = new FileDialog(shell, SWT.OPEN);
2408 dialog.setText(title);
2410 String[] extensions = new String[namesAndExtensions.size()];
2411 String[] filterNames = new String[namesAndExtensions.size()];
2413 for(Tuple t : namesAndExtensions) {
2414 String filterName = (String)t.get(0);
2415 String extension = (String)t.get(1);
2416 filterNames[index] = filterName;
2417 extensions[index] = extension;
2421 dialog.setFilterExtensions(extensions);
2422 dialog.setFilterNames(filterNames);
2423 final String fileName = dialog.open();
2424 if (fileName == null) return null;
2426 return new File(fileName);
2430 public static Resource createLibrary(WriteGraph graph, Resource parent) throws DatabaseException {
2431 Layer0 l0 = Layer0.getInstance(graph);
2432 return createLibrary(graph, parent, NameUtils.findFreshName(graph, "Library", parent, l0.ConsistsOf));
2435 public static Resource createLibrary(WriteGraph graph, Resource parent, String name) throws DatabaseException {
2436 graph.markUndoPoint();
2437 Layer0 l0 = Layer0.getInstance(graph);
2439 Resource library = graph.newResource();
2440 graph.claim(library, l0.InstanceOf, null, l0.Library);
2441 graph.addLiteral(library, l0.HasName, l0.NameOf, l0.String, name, Bindings.STRING);
2442 graph.claim(library, l0.PartOf, parent);
2444 Layer0Utils.addCommentMetadata(graph, "Created new Library named " + name + ", resource " + library);