diff --git a/de.dlr.sc.virsat.model.extension.cefx.ui/META-INF/MANIFEST.MF b/de.dlr.sc.virsat.model.extension.cefx.ui/META-INF/MANIFEST.MF index d59c8c38..9f3db036 100644 --- a/de.dlr.sc.virsat.model.extension.cefx.ui/META-INF/MANIFEST.MF +++ b/de.dlr.sc.virsat.model.extension.cefx.ui/META-INF/MANIFEST.MF @@ -22,7 +22,9 @@ Require-Bundle: org.eclipse.ui, de.dlr.sc.virsat.model.extension.cefx, org.eclipse.ui.navigator, de.dlr.sc.virsat.model.calculation.ui, - de.dlr.sc.virsat.cef.branding.ui + de.dlr.sc.virsat.cef.branding.ui, + org.eclipse.ui.ide, + de.dlr.sc.virsat.external.lib.comet.sdkj.servicedal Bundle-RequiredExecutionEnvironment: JavaSE-11 Bundle-ActivationPolicy: lazy Export-Package: de.dlr.sc.virsat.model.extension.cefx.ui.itemprovider, diff --git a/de.dlr.sc.virsat.model.extension.cefx.ui/icons/sample.png b/de.dlr.sc.virsat.model.extension.cefx.ui/icons/sample.png new file mode 100644 index 00000000..02c4b79e Binary files /dev/null and b/de.dlr.sc.virsat.model.extension.cefx.ui/icons/sample.png differ diff --git a/de.dlr.sc.virsat.model.extension.cefx.ui/icons/sample@2x.png b/de.dlr.sc.virsat.model.extension.cefx.ui/icons/sample@2x.png new file mode 100644 index 00000000..c1224d1f Binary files /dev/null and b/de.dlr.sc.virsat.model.extension.cefx.ui/icons/sample@2x.png differ diff --git a/de.dlr.sc.virsat.model.extension.cefx.ui/plugin.xml b/de.dlr.sc.virsat.model.extension.cefx.ui/plugin.xml index 57803d30..f4a3a274 100644 --- a/de.dlr.sc.virsat.model.extension.cefx.ui/plugin.xml +++ b/de.dlr.sc.virsat.model.extension.cefx.ui/plugin.xml @@ -2697,6 +2697,23 @@ + + + + + Import a file from the local file system into the workspace. + + + + diff --git a/de.dlr.sc.virsat.model.extension.cefx.ui/src/de/dlr/sc/virsat/model/extension/cefx/ui/importWizards/CometDataFetcher.java b/de.dlr.sc.virsat.model.extension.cefx.ui/src/de/dlr/sc/virsat/model/extension/cefx/ui/importWizards/CometDataFetcher.java new file mode 100644 index 00000000..f8ca5bef --- /dev/null +++ b/de.dlr.sc.virsat.model.extension.cefx.ui/src/de/dlr/sc/virsat/model/extension/cefx/ui/importWizards/CometDataFetcher.java @@ -0,0 +1,197 @@ +/******************************************************************************* + * Copyright (c) 2008-2019 German Aerospace Center (DLR), Simulation and Software Technology, Germany. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License 2.0 which is available at + * http://www.eclipse.org/legal/epl-2.0. + * + * SPDX-License-Identifier: EPL-2.0 + *******************************************************************************/ + + +package de.dlr.sc.virsat.model.extension.cefx.ui.importWizards; + +import cdp4common.engineeringmodeldata.ElementDefinition; +import cdp4common.engineeringmodeldata.ElementUsage; +import cdp4common.engineeringmodeldata.EngineeringModel; +import cdp4common.engineeringmodeldata.Iteration; +import cdp4common.engineeringmodeldata.Parameter; +import cdp4common.engineeringmodeldata.ParameterSwitchKind; +import cdp4common.engineeringmodeldata.ParameterValueSet; +import cdp4common.sitedirectorydata.DomainOfExpertise; +import cdp4dal.Session; +import cdp4dal.SessionImpl; +import cdp4dal.dal.Credentials; +import cdp4servicesdal.CdpServicesDal; +import org.eclipse.swt.SWT; +import org.eclipse.swt.widgets.Display; +import org.eclipse.swt.widgets.MessageBox; +import org.eclipse.swt.widgets.Tree; +import org.eclipse.swt.widgets.TreeItem; + +import java.io.IOException; +import java.net.URI; +import java.security.GeneralSecurityException; +import java.util.Optional; + +/** + * The CometDataFetcher class is responsible for fetching and populating + * data from a COMET system into a SWT Tree widget. + */ +public class CometDataFetcher { + + private final Credentials credentials; + private final Session session; + private final URI uri; + + /** + * Constructs a new CometDataFetcher instance. + * + * @param url The URL of the COMET system. + * @param username The username for authentication. + * @param password The password for authentication. + */ + public CometDataFetcher(String url, String username, String password) { + this.uri = URI.create(url); + CdpServicesDal dal = new CdpServicesDal(); + this.credentials = new Credentials(username, password, this.uri, null); + this.session = new SessionImpl(dal, this.credentials); + } + + /** + * Initiates the process to fetch data and populate the provided Tree. + */ + public void fetchData(Tree tree) { + new Thread(() -> { + try { + openSession(); + Display.getDefault().asyncExec(() -> populateTreeWithIteration(tree)); + } catch (IOException e) { + // Handle I/O exceptions, such as network issues + handleException(e, tree); + } catch (GeneralSecurityException e) { + // Handle security-related exceptions, such as authentication failures + handleException(e, tree); + } catch (RuntimeException e) { + // Handle any other runtime exceptions that might occur + handleException(e, tree); + } + }).start(); + } + + /** + * Opens the session for communication with the COMET system. + */ + public void openSession() throws IOException, GeneralSecurityException { + session.open().join(); + } + + /** + * Populates the provided Tree with data from the selected iteration + * of the engineering model. + * + * @param tree The SWT Tree widget to populate. + */ + private void populateTreeWithIteration(Tree tree) { + var siteDirectory = session.getAssembler().retrieveSiteDirectory(); + var model = siteDirectory.getModel().get(0); + + var iterationIid = model.getIterationSetup().get(0).getIterationIid(); + var domainOfExpertiseIid = model.getActiveDomain().get(0).getIid(); + + EngineeringModel engineeringModel = new EngineeringModel(model.getEngineeringModelIid(), session.getAssembler().getCache(), uri); + Iteration iteration = new Iteration(iterationIid, session.getAssembler().getCache(), uri); + iteration.setContainer(engineeringModel); + + DomainOfExpertise domainOfExpertise = new DomainOfExpertise(domainOfExpertiseIid, session.getAssembler().getCache(), uri); + + session.read(iteration, domainOfExpertise).join(); + + Optional openIteration = session.getOpenIterations().keySet().stream().findFirst(); + + if (openIteration.isPresent()) { + openIteration.get().getElement().stream() + .filter(this::isTopLevelElement) // Filter for the top-level element + .findFirst() + .ifPresent(element -> { + TreeItem topLevelItem = new TreeItem(tree, SWT.NONE); + topLevelItem.setText(element.getName()); + addChildren(topLevelItem, element); + topLevelItem.setExpanded(true); + }); + } else { + showErrorMessage(tree, "No open iteration found."); + } + } + + /** + * Custom method to determine if an ElementDefinition is a top-level element. + * A top-level element is typically not referenced by any other elements. + */ + private boolean isTopLevelElement(ElementDefinition element) { + return element.referencingElementUsages().isEmpty(); + } + + + + + /** + * Recursively adds child elements of a parent ElementDefinition to a TreeItem. + */ + private void addChildren(TreeItem parentItem, ElementDefinition parentElement) { + parentElement.getParameter().stream() + .filter(parameter -> "mass".equalsIgnoreCase(parameter.getParameterType().getName())) + .findFirst() + .ifPresent(parameter -> { + String massValue = fetchParameterValue(parameter); + TreeItem massItem = new TreeItem(parentItem, SWT.NONE); + massItem.setText("Mass: " + massValue + " kg"); + }); + + for (ElementUsage usage : parentElement.getContainedElement()) { + TreeItem usageItem = new TreeItem(parentItem, SWT.NONE); + usageItem.setText(usage.getName()); + addChildren(usageItem, usage.getElementDefinition()); + } + } + + /** + * Fetches the value of the specified Parameter. + * + */ + private String fetchParameterValue(Parameter parameter) { + try { + ParameterValueSet valueSet = parameter.getValueSet().get(0); + + if (valueSet.getValueSwitch() == ParameterSwitchKind.COMPUTED) { + return valueSet.getComputed().get(0); + } else if (valueSet.getValueSwitch() == ParameterSwitchKind.MANUAL) { + return valueSet.getManual().get(0); + } else { + return "No valid mass found"; + } + } catch (Exception e) { + e.printStackTrace(); + return "N/A"; + } + } + + /** + * Displays an error message in a MessageBox. + */ + private void showErrorMessage(Tree tree, String message) { + Display.getDefault().asyncExec(() -> { + MessageBox messageBox = new MessageBox(tree.getShell(), SWT.ICON_ERROR); + messageBox.setMessage(message); + messageBox.open(); + }); + } + + /** + * Handles exceptions by printing the stack trace and displaying an error message. + */ + private void handleException(Exception e, Tree tree) { + e.printStackTrace(); + showErrorMessage(tree, "An error occurred: " + e.getMessage()); + } +} \ No newline at end of file diff --git a/de.dlr.sc.virsat.model.extension.cefx.ui/src/de/dlr/sc/virsat/model/extension/cefx/ui/importWizards/CometImportWizard.java b/de.dlr.sc.virsat.model.extension.cefx.ui/src/de/dlr/sc/virsat/model/extension/cefx/ui/importWizards/CometImportWizard.java new file mode 100644 index 00000000..bff4789d --- /dev/null +++ b/de.dlr.sc.virsat.model.extension.cefx.ui/src/de/dlr/sc/virsat/model/extension/cefx/ui/importWizards/CometImportWizard.java @@ -0,0 +1,126 @@ +/******************************************************************************* + * Copyright (c) 2008-2019 German Aerospace Center (DLR), Simulation and Software Technology, Germany. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License 2.0 which is available at + * http://www.eclipse.org/legal/epl-2.0. + * + * SPDX-License-Identifier: EPL-2.0 + *******************************************************************************/ +package de.dlr.sc.virsat.model.extension.cefx.ui.importWizards; + +import org.eclipse.jface.wizard.IWizardPage; +import org.eclipse.jface.wizard.Wizard; +import org.eclipse.swt.widgets.TreeItem; +import org.eclipse.ui.IImportWizard; +import org.eclipse.ui.IWorkbench; + +import de.dlr.sc.virsat.model.dvlm.structural.StructuralElementInstance; +import de.dlr.sc.virsat.model.extension.ps.model.ConfigurationTree; +import de.dlr.sc.virsat.project.editingDomain.VirSatEditingDomainRegistry; +import de.dlr.sc.virsat.project.editingDomain.VirSatTransactionalEditingDomain; + +import java.util.List; + +import org.eclipse.core.resources.IResource; +import org.eclipse.core.resources.ResourcesPlugin; +import org.eclipse.core.runtime.CoreException; +import org.eclipse.emf.common.command.Command; +import org.eclipse.emf.edit.command.AddCommand; +import org.eclipse.jface.viewers.IStructuredSelection; + +/** + * This wizard handles the import of data from a Comet server. + * It guides the user through server configuration and initiates the data import process. + */ +public class CometImportWizard extends Wizard implements IImportWizard { + + private CometImportWizardPage mainPage; + private SelectedElementsPage selectedElementsPage; + + public CometImportWizard() { + super(); + setWindowTitle("CometImportWizard"); + setNeedsProgressMonitor(true); + } + + @Override + public void init(IWorkbench workbench, IStructuredSelection selection) { + mainPage = new CometImportWizardPage("Configure Comet Server"); + selectedElementsPage = new SelectedElementsPage("Selected Elements"); + addPage(mainPage); + addPage(selectedElementsPage); + } + + @Override + public boolean performFinish() { + TreeItem rootItem = selectedElementsPage.getTree().getItem(0); + + if (rootItem != null) { + ConfigurationTree configurationTree = importElements(rootItem); + + // Save the configuration tree + saveConfigurationTree(configurationTree); + } + + return true; + } + + + private ConfigurationTree importElements(TreeItem rootItem) { + ImportHandler importHandler = new ImportHandler(); + return importHandler.importElements(rootItem); + } + + /** + * Saves the imported ConfigurationTree to the editing domain. + */ + + + public void saveConfigurationTree(ConfigurationTree configurationTree) { + if (configurationTree == null) { + throw new IllegalStateException("ConfigurationTree is null. Import failed or was not executed correctly."); + } + + StructuralElementInstance rootInstance = configurationTree.getStructuralElementInstance(); + if (rootInstance == null) { + throw new IllegalStateException("StructuralElementInstance is null in the ConfigurationTree."); + } + + // Ensure that the rootInstance is associated with a resource + if (rootInstance.eResource() == null) { + throw new IllegalStateException("StructuralElementInstance's resource is null."); + } + + // Check if editing domain retrieval is successful + VirSatTransactionalEditingDomain editingDomain = VirSatEditingDomainRegistry.INSTANCE.getEd(rootInstance); + if (editingDomain == null) { + throw new IllegalStateException("Editing domain is null. Unable to get the editing domain for the StructuralElementInstance."); + } + + try { + Command addCommand = AddCommand.create(editingDomain, rootInstance.eResource(), rootInstance.eResource().getContents(), rootInstance); + editingDomain.getCommandStack().execute(addCommand); + editingDomain.saveAll(); + + ResourcesPlugin.getWorkspace().getRoot().refreshLocal(IResource.DEPTH_INFINITE, null); + } catch (CoreException e) { + e.printStackTrace(); + } + } + + + @Override + public IWizardPage getNextPage(IWizardPage page) { + if (page == mainPage) { + // Get the selected TreeItems from the mainPage + List checkedItems = mainPage.getCheckedItems(); + + // Pass the selected items to the SelectedElementsPage + selectedElementsPage.setSelectedElements(checkedItems); + return selectedElementsPage; + } + return super.getNextPage(page); + } + +} \ No newline at end of file diff --git a/de.dlr.sc.virsat.model.extension.cefx.ui/src/de/dlr/sc/virsat/model/extension/cefx/ui/importWizards/CometImportWizardPage.java b/de.dlr.sc.virsat.model.extension.cefx.ui/src/de/dlr/sc/virsat/model/extension/cefx/ui/importWizards/CometImportWizardPage.java new file mode 100644 index 00000000..b3c8b1ac --- /dev/null +++ b/de.dlr.sc.virsat.model.extension.cefx.ui/src/de/dlr/sc/virsat/model/extension/cefx/ui/importWizards/CometImportWizardPage.java @@ -0,0 +1,281 @@ +/******************************************************************************* + * Copyright (c) 2008-2019 German Aerospace Center (DLR), Simulation and Software Technology, Germany. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License 2.0 which is available at + * http://www.eclipse.org/legal/epl-2.0. + * + * SPDX-License-Identifier: EPL-2.0 + *******************************************************************************/ + +package de.dlr.sc.virsat.model.extension.cefx.ui.importWizards; + +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.core.runtime.Status; +import org.eclipse.jface.dialogs.ProgressMonitorDialog; +import org.eclipse.jface.operation.IRunnableWithProgress; +import org.eclipse.jface.wizard.WizardPage; +import org.eclipse.swt.SWT; +import org.eclipse.swt.events.SelectionAdapter; +import org.eclipse.swt.events.SelectionEvent; +import org.eclipse.swt.graphics.Color; +import org.eclipse.swt.graphics.Font; +import org.eclipse.swt.graphics.FontData; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.widgets.Button; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Display; +import org.eclipse.swt.widgets.Label; +import org.eclipse.swt.widgets.Shell; +import org.eclipse.swt.widgets.Text; +import org.eclipse.swt.widgets.Tree; +import org.eclipse.swt.widgets.TreeItem; +import org.eclipse.ui.statushandlers.StatusManager; + +import de.dlr.sc.virsat.build.ui.Activator; + +import java.util.ArrayList; +import java.util.List; + +/** + * The CometImportWizardPage class represents a wizard page used to configure + * and fetch data from a COMET server. It provides a UI for entering server details, + * initiating data fetch, and displaying the fetched data in a tree structure. + */ +public class CometImportWizardPage extends WizardPage { + + private static final int GRID_COLUMNS = 2; + private static final int VERTICALSPAN = 1; + private static final int TREE_HEIGHT_HINT = 400; + private static final int TREE_WIDTH_HINT = 600; + + private Text serverUrlText; + private Text loginText; + private Text passwordText; + private Tree targetTree; + private CometDataFetcher fetcher; + private boolean isDataFetched = false; + + /** + * Constructs a new CometImportWizardPage with the specified name. + * + * @param pageName The name of the wizard page. + */ + protected CometImportWizardPage(String pageName) { + super(pageName); + setTitle("Comet Server Configuration"); + setDescription(""); + } + + /** + * Creates the controls (UI elements) for this wizard page. + */ + @Override + public void createControl(Composite parent) { + Composite container = new Composite(parent, SWT.NONE); + GridLayout layout = new GridLayout(GRID_COLUMNS, false); + container.setLayout(layout); + + // Create red color and bold font + Color red = Display.getCurrent().getSystemColor(SWT.COLOR_RED); + FontData[] fontData = getFont().getFontData(); + for (FontData fd : fontData) { + fd.setStyle(SWT.BOLD); + } + Font boldFont = new Font(Display.getCurrent(), fontData); + + // Create a custom description label with red color and bold font + Label customDescription = new Label(container, SWT.NONE); + customDescription.setText("Enter details and fetch data."); + customDescription.setForeground(red); + customDescription.setFont(boldFont); + + GridData descriptionGridData = new GridData(SWT.FILL, SWT.CENTER, true, false, GRID_COLUMNS, VERTICALSPAN); + customDescription.setLayoutData(descriptionGridData); + + container.addDisposeListener(event -> boldFont.dispose()); + + // Create blue labels for the text fields + Color blue = Display.getCurrent().getSystemColor(SWT.COLOR_BLUE); + createLabelAndTextField(container, "Server URL:", SWT.BORDER, blue); + createLabelAndTextField(container, "Login:", SWT.BORDER, blue); + createLabelAndTextField(container, "Password:", SWT.BORDER | SWT.PASSWORD, blue); + + createFetchButton(container); + + targetTree = new Tree(container, SWT.CHECK | SWT.MULTI | SWT.BORDER); + targetTree.addSelectionListener(new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + if (e.detail == SWT.CHECK) { + TreeItem item = (TreeItem) e.item; + checkChildren(item, item.getChecked()); + } + } + }); + GridData treeGridData = new GridData(SWT.FILL, SWT.FILL, true, true, GRID_COLUMNS, VERTICALSPAN); + treeGridData.heightHint = TREE_HEIGHT_HINT; + treeGridData.widthHint = TREE_WIDTH_HINT; + targetTree.setLayoutData(treeGridData); + + setControl(container); + } + + /** + * Creates a "Fetch Data" button within the provided container. The button is aligned to the right side of the container. + */ + private void createFetchButton(Composite container) { + Button fetchButton = new Button(container, SWT.PUSH); + fetchButton.setText("Fetch Data"); + + // Set the button to be aligned to the right side + GridData fetchButtonGridData = new GridData(SWT.RIGHT, SWT.CENTER, false, false); + fetchButtonGridData.horizontalSpan = GRID_COLUMNS; + fetchButton.setLayoutData(fetchButtonGridData); + + fetchButton.addSelectionListener(new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + handleFetchData(); + } + }); + } + + /** + * Handles the process of fetching data from a server, triggered by the "Fetch Data" button. + * This method validates the input fields, retrieves user input (server URL, username, and password), + * and uses a ProgressMonitorDialog to display the progress of connecting to the COMET server + * and fetching data. It ensures that the data is fetched only once. + */ + private void handleFetchData() { + // Check if data has already been fetched + if (isDataFetched) { + setMessage("Data has already been fetched.", SWT.ICON_INFORMATION); + return; + } + + // Validate the input fields before proceeding + if (!validateInput()) { + return; + } + + // These variables will hold the input values from the UI + final String[] serverUrl = new String[1]; + final String[] username = new String[1]; + final String[] password = new String[1]; + + // Access UI elements from the UI thread + Display.getDefault().syncExec(() -> { + serverUrl[0] = serverUrlText.getText(); + username[0] = loginText.getText(); + password[0] = passwordText.getText(); + }); + + Shell shell = getShell(); + + // Use a ProgressMonitorDialog to show progress to the user + ProgressMonitorDialog progressDialog = new ProgressMonitorDialog(shell); + try { + progressDialog.run(true, true, new IRunnableWithProgress() { + @Override + public void run(IProgressMonitor monitor) { + try { + monitor.beginTask("Connecting to COMET server...", IProgressMonitor.UNKNOWN); + + // Instantiate the CometDataFetcher with the retrieved values + fetcher = new CometDataFetcher(serverUrl[0], username[0], password[0]); + + // Fetch and display data + fetcher.fetchData(targetTree); + + // After successful data fetch, set the flag to true + isDataFetched = true; + + } catch (Exception e) { + Status status = new Status(Status.ERROR, Activator.getPluginId(), "Failed to fetch data from COMET server.", e); + StatusManager.getManager().handle(status, StatusManager.LOG | StatusManager.SHOW); + } finally { + monitor.done(); + } + } + }); + } catch (Exception e) { + Status status = new Status(Status.ERROR, Activator.getPluginId(), "Failed to run progress dialog.", e); + StatusManager.getManager().handle(status, StatusManager.LOG | StatusManager.SHOW); + } + } + + /** + * Creates a label and a text field with the specified label text and style. + */ + private void createLabelAndTextField(Composite parent, String labelText, int style, Color labelColor) { + Label label = new Label(parent, SWT.NONE); + label.setText(labelText); + label.setForeground(labelColor); // Set label color to blue + Text text = new Text(parent, style); + text.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); + if (labelText.equals("Server URL:")) { + serverUrlText = text; + } else if (labelText.equals("Login:")) { + loginText = text; + } else if (labelText.equals("Password:")) { + passwordText = text; + } + } + + /** + * Validates the user input in the text fields. Ensures that all fields are filled. + */ + private boolean validateInput() { + if (serverUrlText.getText().isEmpty() || loginText.getText().isEmpty() || passwordText.getText().isEmpty()) { + setMessage("All fields are required.", SWT.ICON_WARNING); + return false; + } + if (!serverUrlText.getText().startsWith("http://") && !serverUrlText.getText().startsWith("https://")) { + setMessage("Server URL must start with http:// or https://", SWT.ICON_WARNING); + return false; + } + return true; + } + + /** + * Retrieves a list of all TreeItems that are checked in the Tree. + */ + public List getCheckedItems() { + List checkedItems = new ArrayList<>(); + for (TreeItem item : targetTree.getItems()) { + getCheckedItemsRecursively(item, checkedItems); + } + return checkedItems; + } + + /** + * Recursively collects checked TreeItems and adds them to the provided list. + */ + private void getCheckedItemsRecursively(TreeItem item, List checkedItems) { + if (item.getChecked()) { + checkedItems.add(item); + } + for (TreeItem child : item.getItems()) { + getCheckedItemsRecursively(child, checkedItems); + } + } + + /** + * Recursively checks or unchecks all child TreeItems of the specified TreeItem. + */ + private void checkChildren(TreeItem item, boolean checked) { + for (TreeItem child : item.getItems()) { + child.setChecked(checked); + checkChildren(child, checked); + } + } + + /** + * Performs the finish operation when the wizard is completed. + */ + public boolean performFinish() { + return true; + } +} \ No newline at end of file diff --git a/de.dlr.sc.virsat.model.extension.cefx.ui/src/de/dlr/sc/virsat/model/extension/cefx/ui/importWizards/ImportFromCometCommand.java b/de.dlr.sc.virsat.model.extension.cefx.ui/src/de/dlr/sc/virsat/model/extension/cefx/ui/importWizards/ImportFromCometCommand.java new file mode 100644 index 00000000..53868997 --- /dev/null +++ b/de.dlr.sc.virsat.model.extension.cefx.ui/src/de/dlr/sc/virsat/model/extension/cefx/ui/importWizards/ImportFromCometCommand.java @@ -0,0 +1,15 @@ +/******************************************************************************* + * Copyright (c) 2008-2019 German Aerospace Center (DLR), Simulation and Software Technology, Germany. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License 2.0 which is available at + * http://www.eclipse.org/legal/epl-2.0. + * + * SPDX-License-Identifier: EPL-2.0 + *******************************************************************************/ + +package de.dlr.sc.virsat.model.extension.cefx.ui.importWizards; + +public class ImportFromCometCommand { + +} diff --git a/de.dlr.sc.virsat.model.extension.cefx.ui/src/de/dlr/sc/virsat/model/extension/cefx/ui/importWizards/ImportFromCometToCTCommand.java b/de.dlr.sc.virsat.model.extension.cefx.ui/src/de/dlr/sc/virsat/model/extension/cefx/ui/importWizards/ImportFromCometToCTCommand.java new file mode 100644 index 00000000..ab57a163 --- /dev/null +++ b/de.dlr.sc.virsat.model.extension.cefx.ui/src/de/dlr/sc/virsat/model/extension/cefx/ui/importWizards/ImportFromCometToCTCommand.java @@ -0,0 +1,147 @@ +/******************************************************************************* + * Copyright (c) 2008-2019 German Aerospace Center (DLR), Simulation and Software Technology, Germany. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License 2.0 which is available at + * http://www.eclipse.org/legal/epl-2.0. + * + * SPDX-License-Identifier: EPL-2.0 + *******************************************************************************/ + +package de.dlr.sc.virsat.model.extension.cefx.ui.importWizards; + +import org.eclipse.emf.common.command.Command; +import org.eclipse.emf.common.command.CompoundCommand; +import org.eclipse.emf.transaction.RecordingCommand; +import de.dlr.sc.virsat.model.dvlm.concepts.Concept; +import de.dlr.sc.virsat.model.dvlm.structural.StructuralElementInstance; +import de.dlr.sc.virsat.model.extension.cefx.model.SystemParameters; +import de.dlr.sc.virsat.model.extension.ps.model.ConfigurationTree; +import de.dlr.sc.virsat.model.extension.ps.model.ElementConfiguration; +import de.dlr.sc.virsat.model.extension.cefx.model.SubSystemMassParameters; +import de.dlr.sc.virsat.project.editingDomain.VirSatTransactionalEditingDomain; +import org.eclipse.emf.edit.command.AddCommand; +import org.eclipse.swt.widgets.TreeItem; + +import java.util.Collections; +import java.util.List; + +public class ImportFromCometToCTCommand { + + private static final int SYSTEM_MARGIN_DEFAULT = 20; + + private VirSatTransactionalEditingDomain domain; + private StructuralElementInstance parentInstance; + private Concept activeConceptCefx; + private Concept activeConceptPs; + private List selectedItems; + + /** + * Constructor to initialize the ImportFromCometToCTCommand object. + */ + public ImportFromCometToCTCommand(VirSatTransactionalEditingDomain domain, StructuralElementInstance parentInstance, Concept activeConceptCefx, Concept activeConceptPs, List selectedItems) { + if (domain == null || parentInstance == null || activeConceptCefx == null || activeConceptPs == null || selectedItems == null || selectedItems.isEmpty()) { + throw new IllegalArgumentException("Invalid arguments provided to ImportFromCometToCTCommand constructor."); + } + + this.domain = domain; + this.parentInstance = parentInstance; + this.activeConceptCefx = activeConceptCefx; + this.activeConceptPs = activeConceptPs; + this.selectedItems = selectedItems; + } + + /** + * Creates a command that imports the selected elements from the Comet tool into the ConfigurationTree. + */ + public Command createImportCommand() { + if (selectedItems.isEmpty()) { + throw new IllegalStateException("No selected items to import."); + } + + // A compound command to hold all the subcommands + CompoundCommand compoundCommand = new CompoundCommand(); + + try { + // Create a new ConfigurationTree using the root name of the first selected item + String rootName = selectedItems.get(0).getText(); + if (rootName == null || rootName.isEmpty()) { + throw new IllegalStateException("Root name of the selected item is null or empty."); + } + + ConfigurationTree newCT = new ConfigurationTree(activeConceptPs); + newCT.setName(rootName); + + // Create a structural instance for the new ConfigurationTree and set its parent + StructuralElementInstance newCTInstance = newCT.getStructuralElementInstance(); + newCTInstance.setParent(parentInstance); + + // Add the new ConfigurationTree instance to the parent instance + Command addCTCommand = AddCommand.create(domain, parentInstance, null, Collections.singleton(newCTInstance)); + compoundCommand.append(addCTCommand); + + // For each selected item, add it to the ConfigurationTree + for (TreeItem item : selectedItems) { + String itemName = item.getText(); + if (itemName == null || itemName.isEmpty()) { + continue; + } + + // Create a new ElementConfiguration for the selected item + ElementConfiguration config = new ElementConfiguration(activeConceptPs); + config.setName(itemName); + + // Create a structural instance for the configuration and set its parent + StructuralElementInstance configInstance = config.getStructuralElementInstance(); + configInstance.setParent(newCTInstance); + + // Add the configuration instance to the new ConfigurationTree instance + Command addConfigCommand = AddCommand.create(domain, newCTInstance, null, Collections.singleton(configInstance)); + compoundCommand.append(addConfigCommand); + + // Add subsystem-specific parameters using a recording command + compoundCommand.append(new RecordingCommand(domain) { + @Override + protected void doExecute() { + addSubSystemParameters(activeConceptCefx, config); + } + }); + } + + // Add system parameters to the ConfigurationTree + compoundCommand.append(new RecordingCommand(domain) { + @Override + protected void doExecute() { + addSystemParameters(activeConceptCefx, newCT); + } + }); + + } catch (Exception e) { + e.printStackTrace(); + throw new RuntimeException("Failed to create import command: " + e.getMessage(), e); + } + + // Return the compound command that can be executed + return compoundCommand; + } + + /** + * Adds system parameters to the specified ConfigurationTree. + */ + private void addSystemParameters(Concept concept, ConfigurationTree system) { + SystemParameters systemParameters = new SystemParameters(concept); + systemParameters.setName("SystemParameters"); + systemParameters.setSystemMargin(SYSTEM_MARGIN_DEFAULT); + system.add(systemParameters); + } + + /** + * Adds subsystem-specific mass parameters to the specified ElementConfiguration. + */ + private void addSubSystemParameters(Concept concept, ElementConfiguration subSystem) { + SubSystemMassParameters subSystemMassParameters = new SubSystemMassParameters(concept); + subSystemMassParameters.setName("MassParameters"); + subSystem.add(subSystemMassParameters); + } +} + diff --git a/de.dlr.sc.virsat.model.extension.cefx.ui/src/de/dlr/sc/virsat/model/extension/cefx/ui/importWizards/ImportHandler.java b/de.dlr.sc.virsat.model.extension.cefx.ui/src/de/dlr/sc/virsat/model/extension/cefx/ui/importWizards/ImportHandler.java new file mode 100644 index 00000000..33b3f92a --- /dev/null +++ b/de.dlr.sc.virsat.model.extension.cefx.ui/src/de/dlr/sc/virsat/model/extension/cefx/ui/importWizards/ImportHandler.java @@ -0,0 +1,98 @@ +/******************************************************************************* + * Copyright (c) 2008-2019 German Aerospace Center (DLR), Simulation and Software Technology, Germany. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License 2.0 which is available at + * http://www.eclipse.org/legal/epl-2.0. + * + * SPDX-License-Identifier: EPL-2.0 + *******************************************************************************/ + +package de.dlr.sc.virsat.model.extension.cefx.ui.importWizards; + +import de.dlr.sc.virsat.model.extension.ps.model.ConfigurationTree; +import de.dlr.sc.virsat.model.extension.ps.model.ElementConfiguration; +import de.dlr.sc.virsat.model.concept.types.structural.IBeanStructuralElementInstance; +import de.dlr.sc.virsat.model.dvlm.structural.StructuralElement; +import de.dlr.sc.virsat.model.dvlm.structural.StructuralElementInstance; +import de.dlr.sc.virsat.model.dvlm.structural.StructuralFactory; +import org.eclipse.swt.widgets.TreeItem; + +public class ImportHandler { + + /** + * Imports the selected tree items and maps them. + */ + public ConfigurationTree importElements(TreeItem rootItem) { + // Create the root element as a ConfigurationTree + ConfigurationTree rootConfigurationTree = new ConfigurationTree(); + StructuralElementInstance rootInstance = createStructuralElementInstance(rootItem.getText()); + + if (rootInstance == null) { + throw new IllegalStateException("Root StructuralElementInstance could not be created."); + } + + rootConfigurationTree.setStructuralElementInstance(rootInstance); + rootConfigurationTree.setName(rootItem.getText()); + + // Recursively add children as ElementConfigurations + addChildren(rootConfigurationTree, rootItem); + + return rootConfigurationTree; + } + + /** + * Recursively adds children as ElementConfiguration instances. + */ + private void addChildren(IBeanStructuralElementInstance parentConfig, TreeItem parentItem) { + for (TreeItem childItem : parentItem.getItems()) { + // Create a new ElementConfiguration for each child + ElementConfiguration elementConfig = new ElementConfiguration(); + StructuralElementInstance childInstance = createStructuralElementInstance(childItem.getText()); + + if (childInstance == null) { + throw new IllegalStateException("Child StructuralElementInstance could not be created."); + } + + elementConfig.setStructuralElementInstance(childInstance); + elementConfig.setName(childItem.getText()); + + // Add the new ElementConfiguration as a child of the parent + parentConfig.add(elementConfig); + + // Recursively process children of this child item + addChildren(elementConfig, childItem); + } + } + + /** + * Helper method to create a StructuralElementInstance using a factory. + */ + private StructuralElementInstance createStructuralElementInstance(String name) { + // Use the StructuralFactory to create an instance + StructuralElementInstance sei = StructuralFactory.eINSTANCE.createStructuralElementInstance(); + + if (sei == null) { + throw new IllegalStateException("Failed to create StructuralElementInstance."); + } + sei.setName(name); + + // Create or find the corresponding StructuralElement to set the type + StructuralElement structuralElement = findOrCreateStructuralElement(name); + if (structuralElement == null) { + throw new IllegalStateException("Failed to find or create a StructuralElement for " + name); + } + + sei.setType(structuralElement); + + return sei; + } + + private StructuralElement findOrCreateStructuralElement(String name) { + // Find an existing StructuralElement by name or create a new one + StructuralElement structuralElement = StructuralFactory.eINSTANCE.createStructuralElement(); + structuralElement.setName(name); + + return structuralElement; + } +} diff --git a/de.dlr.sc.virsat.model.extension.cefx.ui/src/de/dlr/sc/virsat/model/extension/cefx/ui/importWizards/SelectedElementsPage.java b/de.dlr.sc.virsat.model.extension.cefx.ui/src/de/dlr/sc/virsat/model/extension/cefx/ui/importWizards/SelectedElementsPage.java new file mode 100644 index 00000000..81844bb8 --- /dev/null +++ b/de.dlr.sc.virsat.model.extension.cefx.ui/src/de/dlr/sc/virsat/model/extension/cefx/ui/importWizards/SelectedElementsPage.java @@ -0,0 +1,84 @@ +/******************************************************************************* + * Copyright (c) 2008-2019 German Aerospace Center (DLR), Simulation and Software Technology, Germany. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License 2.0 which is available at + * http://www.eclipse.org/legal/epl-2.0. + * + * SPDX-License-Identifier: EPL-2.0 + *******************************************************************************/ + +package de.dlr.sc.virsat.model.extension.cefx.ui.importWizards; + +import org.eclipse.jface.wizard.WizardPage; +import org.eclipse.swt.SWT; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Label; +import org.eclipse.swt.widgets.Tree; +import org.eclipse.swt.widgets.TreeItem; + +import java.util.List; + +public class SelectedElementsPage extends WizardPage { + + private Tree selectedElementsTree; + private List selectedTreeItems; + protected SelectedElementsPage(String pageName) { + super(pageName); + setTitle("Selected Elements"); + setDescription("Review the selected elements and tree structure."); + } + + @Override + public void createControl(Composite parent) { + Composite container = new Composite(parent, SWT.NONE); + container.setLayout(new GridLayout(1, false)); + + Label label = new Label(container, SWT.NONE); + label.setText("Selected Elements:"); + + selectedElementsTree = new Tree(container, SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL); + selectedElementsTree.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); + + setControl(container); + } + + /** + * Populates the Tree with the selected elements. + * This method will be called when the user clicks "Next" from the previous page. + */ + public void setSelectedElements(List selectedItems) { + + // Clear any existing items + selectedElementsTree.removeAll(); + + // Create root TreeItem based on the first selected item + if (!selectedItems.isEmpty()) { + TreeItem root = new TreeItem(selectedElementsTree, SWT.NONE); + root.setText(selectedItems.get(0).getText()); + addChildren(root, selectedItems.get(0)); + root.setExpanded(true); + } + } + + /** + * Recursively adds children of the TreeItems. + */ + private void addChildren(TreeItem parent, TreeItem original) { + for (TreeItem item : original.getItems()) { + TreeItem child = new TreeItem(parent, SWT.NONE); + child.setText(item.getText()); + addChildren(child, item); + } + } + + public Tree getTree() { + return selectedElementsTree; + } + + public List getSelectedItems() { + return this.selectedTreeItems; + } +} diff --git a/known_authors.txt b/known_authors.txt index c4d20d2c..c7885dd7 100644 --- a/known_authors.txt +++ b/known_authors.txt @@ -7,3 +7,4 @@ JAmmermann-DLR christoph-pietsch-DLR dellerDLR pchrszon-dlr +DimitriDiantos \ No newline at end of file