Search in sources :

Example 1 with InputConstraint

use of edu.uah.rsesc.aadlsimulator.xtext.inputConstraint.InputConstraint in project AGREE by loonwerks.

the class CounterexampleLoaderHelper method simulateCounterexample.

private void simulateCounterexample(final Counterexample cex, final int startStepIndex, final Map<String, Object> signalNameToSimStateElementMap, final AGREESimulationEngine simulationEngine, final SimulationService simulationService, final SimulationUIService simulationUIService) {
    // For each frame in the counter example, step through the simulation and constrain the arguments to match those of the counter example
    for (int stepIndex = startStepIndex; stepIndex < cex.getLength(); stepIndex++) {
        simulationEngine.resetInputConstraints();
        // Constraint simulation variables based on the counterexample
        for (final Entry<String, Value> sv : cex.getStep(stepIndex).entrySet()) {
            final String signalName = sv.getKey();
            final Object stateElement = signalNameToSimStateElementMap.get(signalName);
            // Throw exception if the state element corresponding to the signal in the counterexample was not found unless the signal corresponds to a clock or a specification statement
            if (stateElement == null) {
            // TODO: Cleanup
            // Ignore variables that do not have state elements. Need a way to verify that they can be safely ignored. Clocks may be ignored if they aren't
            // used. Variables for SpecStatements are okay to ignore but we don't have a way of getting the reference in all cases.
            // In the case of a monolithic analysis, the references for all layers are not contained in the reference map
            /*
					final String renamedClockIdSuffix = agreeSimulationEngine.getSimulationProgram().getAgreeRenaming().forceRename(AgreeASTBuilder.clockIDSuffix);
					final boolean isClock = signalName.endsWith(renamedClockIdSuffix);
					final EObject ref = refMap.get(signalName);
					if(!isClock && !(ref instanceof SpecStatement)) {
						//throw new RuntimeException("Unable to find state element for signal '" + signalName + "'");
					}
					*/
            } else {
                // Don't include hidden variables
                if (!simulationEngine.getCurrentState().isElementHidden(stateElement)) {
                    // Constrain the next value of the variable to match the value contained in the counter example
                    final InputConstraint ic = lustreValueToInputConstraint(sv.getValue());
                    simulationEngine.setInputConstraint(stateElement, ic);
                }
            }
        }
        simulationEngine.stepForward();
    }
    simulationEngine.queueNotification(notification -> {
        // Check that the number of simulated frames matches the expected number. It should match the length of the counter example
        if (cex.getLength() == notification.getEngineState().getNumberOfFrames()) {
            simulationEngine.resetInputConstraints();
        } else {
            // Determine whether there are unsatisfied properties that are halting the simulation
            boolean hasUnsatisfiedProperty = false;
            for (final SimulationProperty simProp : simulationEngine.getSimulationProgram().getSimulationProperties()) {
                if (notification.getEngineState().getPropertyStatus(simProp) == AGREEPropertyStatus.UNSATISFIED_ERROR) {
                    hasUnsatisfiedProperty = true;
                }
            }
            if (hasUnsatisfiedProperty) {
                Display.getDefault().syncExec(() -> {
                    final IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
                    final IWorkbenchPage activePage = window.getActivePage();
                    if (activePage != null) {
                        try {
                            activePage.showView(UIConstants.PROPERTIES_VIEW_ID);
                        } catch (final PartInitException e) {
                        // Ignore
                        }
                    }
                    final Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();
                    final String errorMsg = "One or more properties could not be satisfied. Disable one or more properties from the Simulation Properties view and select Retry to continue.";
                    class RetryDialog extends MessageDialog {

                        public RetryDialog() {
                            super(shell, "Unable to Simulate Counterexample", null, errorMsg, MessageDialog.ERROR, new String[] { "Retry", "End Simulation" }, 0);
                            setShellStyle(SWT.CLOSE | SWT.MODELESS | SWT.BORDER | SWT.TITLE);
                            setBlockOnOpen(false);
                        }

                        @Override
                        protected void buttonPressed(final int buttonId) {
                            switch(buttonId) {
                                case // Retry
                                0:
                                    // Try to resume the simulation
                                    simulationEngine.stepBackward();
                                    simulateCounterexample(cex, notification.getEngineState().getNumberOfFrames() - 1, signalNameToSimStateElementMap, simulationEngine, simulationService, simulationUIService);
                                    break;
                                case // End Simulation
                                1:
                                    simulationService.dispose(simulationEngine);
                                    break;
                            }
                            super.buttonPressed(buttonId);
                        }
                    }
                    final MessageDialog dlg = new RetryDialog();
                    dlg.open();
                });
            } else {
                final StatusAdapter statusAdapter = new StatusAdapter(new Status(IStatus.WARNING, FrameworkUtil.getBundle(getClass()).getSymbolicName(), "Simulation halted before every step in the counterexample was simulated.", new RuntimeException("The number of simulated frames does not match the length of the counterexample.")));
                statusAdapter.setProperty(IStatusAdapterConstants.TITLE_PROPERTY, "Unable to Simulate Counterexample");
                StatusManager.getManager().handle(statusAdapter, StatusManager.SHOW);
            }
        }
    });
}
Also used : IStatus(org.eclipse.core.runtime.IStatus) AGREEPropertyStatus(edu.uah.rsesc.aadlsimulator.agree.engine.AGREEPropertyStatus) Status(org.eclipse.core.runtime.Status) IWorkbenchWindow(org.eclipse.ui.IWorkbenchWindow) StatusAdapter(org.eclipse.ui.statushandlers.StatusAdapter) InputConstraint(edu.uah.rsesc.aadlsimulator.xtext.inputConstraint.InputConstraint) Shell(org.eclipse.swt.widgets.Shell) RealValue(jkind.lustre.values.RealValue) IntegerValue(jkind.lustre.values.IntegerValue) Value(jkind.lustre.values.Value) BooleanValue(jkind.lustre.values.BooleanValue) IWorkbenchPage(org.eclipse.ui.IWorkbenchPage) EObject(org.eclipse.emf.ecore.EObject) SimulationProperty(edu.uah.rsesc.aadlsimulator.agree.SimulationProperty) PartInitException(org.eclipse.ui.PartInitException) MessageDialog(org.eclipse.jface.dialogs.MessageDialog) InputConstraint(edu.uah.rsesc.aadlsimulator.xtext.inputConstraint.InputConstraint)

Example 2 with InputConstraint

use of edu.uah.rsesc.aadlsimulator.xtext.inputConstraint.InputConstraint in project AGREE by loonwerks.

the class VariablesView method createView.

@PostConstruct
void createView(final Composite parent) {
    final Display display = parent.getDisplay();
    colorManager = new DeviceResourceManager(display);
    unchangedValueColor = colorManager.createColor(new RGB(192, 192, 192));
    constraintErrorColor = colorManager.createColor(red);
    greenImage = createColorIconImage(display, green);
    redImage = createColorIconImage(display, red);
    yellowImage = createColorIconImage(display, yellow);
    customColorImage = createColorIconImage(display, customRgb);
    // Create root composite
    final Composite root = new Composite(parent, SWT.NONE);
    final GridLayout rootLayout = new GridLayout(1, false);
    root.setLayout(rootLayout);
    // Create the variable tree viewer
    treeViewer = new VariablesTreeViewer(root, SWT.FULL_SELECTION);
    // Enable tooltip support
    ColumnViewerToolTipSupport.enableFor(treeViewer);
    treeSelectionTracker = new TreeSelectionTracker(treeViewer);
    GridDataFactory.fillDefaults().grab(true, true).applyTo(treeViewer.getTree());
    treeViewer.setUseHashlookup(true);
    final VariableContentProvider contentProvider = new VariableContentProvider();
    treeViewer.setContentProvider(contentProvider);
    treeViewer.setInput(null);
    treeViewer.setComparator(new ViewerComparator() {

        @Override
        public int compare(final Viewer viewer, final Object e1, final Object e2) {
            if (contentProvider.currentState == null) {
                return 0;
            }
            // Sort component instances before other variables
            final InstanceObject io1 = contentProvider.currentState.getEngineState().getElementInstanceObject(e1);
            final InstanceObject io2 = contentProvider.currentState.getEngineState().getElementInstanceObject(e2);
            if (io1 instanceof ComponentInstance && !(io2 instanceof ComponentInstance)) {
                return -1;
            } else if (io2 instanceof ComponentInstance && !(io1 instanceof ComponentInstance)) {
                return 1;
            }
            // Sort feature instances before the remainder
            if (io1 instanceof FeatureInstance && !(io2 instanceof FeatureInstance)) {
                return -1;
            } else if (io2 instanceof FeatureInstance && !(io1 instanceof FeatureInstance)) {
                return 1;
            }
            final String n1 = contentProvider.currentState.getEngineState().getElementName(e1);
            final String n2 = contentProvider.currentState.getEngineState().getElementName(e2);
            return getComparator().compare(n1, n2);
        }
    });
    treeViewer.setFilters(new ViewerFilter[] { new ViewerFilter() {

        @Override
        public boolean select(final Viewer viewer, final Object parentElement, final Object element) {
            return !contentProvider.currentState.getEngineState().isElementHidden(element);
        }
    } });
    // Create columns
    final TreeViewerColumn nameColumn = new TreeViewerColumn(treeViewer, SWT.NONE);
    nameColumn.getColumn().setWidth(200);
    nameColumn.getColumn().setText("Name");
    nameColumn.getColumn().addControlListener(resizeListener);
    nameColumn.setLabelProvider(new StyledCellLabelProvider() {

        @Override
        public void update(final ViewerCell cell) {
            cell.setText(getText(cell.getElement()));
            cell.setImage(getImage(cell.getElement()));
        }

        private String getText(final Object element) {
            // Get the name of the frame state element
            final SimulatorState state = contentProvider.getCurrentState();
            if (state == null) {
                return "";
            }
            return state.getEngineState().getElementName(element);
        }

        private Image getImage(final Object element) {
            final SimulatorState state = contentProvider.getCurrentState();
            if (state == null) {
                return null;
            }
            final InstanceObject instanceObject = state.getEngineState().getElementInstanceObject(element);
            return instanceObject == null ? null : UiUtil.getModelElementLabelProvider().getImage(instanceObject);
        }
    });
    final TreeViewerColumn nextValueColumn = new TreeViewerColumn(treeViewer, SWT.NONE);
    nextValueColumn.getColumn().setWidth(100);
    nextValueColumn.getColumn().setText("Next Value");
    nextValueColumn.setLabelProvider(new OwnerDrawLabelProvider() {

        @Override
        public void initialize(final ColumnViewer viewer, final ViewerColumn column) {
            super.initialize(viewer, column, true);
        }

        @Override
        public void update(final ViewerCell cell) {
            final String constraintTxt = getConstraintText(cell.getElement());
            final String txt;
            final Color foreground;
            if (constraintTxt == null) {
                // Attempt to retrieve the value for the next frame from from the engine state.
                final SimulatorState state = contentProvider.getCurrentState();
                if (state == null) {
                    txt = "";
                } else {
                    final SimulationEngineState engineState = state.getEngineState();
                    txt = ValueFormatter.formatValue(engineState.getElementValue(engineState.getNumberOfFrames(), cell.getElement()));
                }
                foreground = unchangedValueColor;
            } else {
                txt = constraintTxt;
                foreground = null;
            }
            cell.setText(txt);
            cell.setForeground(foreground);
            super.update(cell);
        }

        private String getConstraintText(final Object element) {
            // Return the invalid value if the input that was entered is not correct
            final ConstraintError constraintError = elementToConstraintErrorMap.get(element);
            if (constraintError != null) {
                return constraintError.constraint;
            }
            final SimulationEngineState engineState = simulationUiService.getCurrentState().getEngineState();
            if (engineState == null) {
                return null;
            }
            final InputConstraint ic = engineState.getElementInputConstraintForNextFrame(element);
            if (ic == null) {
                return null;
            }
            return inputConstraintHelper.unparse(ic);
        }

        @Override
        public String getToolTipText(final Object element) {
            final ConstraintError constraintError = elementToConstraintErrorMap.get(element);
            if (constraintError == null) {
                return super.getToolTipText(element);
            } else {
                return constraintError.errorMessage;
            }
        }

        @Override
        protected void measure(final Event event, final Object element) {
        }

        @Override
        protected void erase(final Event event, final Object element) {
            // Color cells which contain invalid values
            if (elementToConstraintErrorMap.containsKey(element)) {
                final GC gc = event.gc;
                final Color oldBackground = event.gc.getBackground();
                gc.setBackground(constraintErrorColor);
                final Rectangle bounds = event.getBounds();
                gc.fillRectangle(bounds);
                gc.setBackground(oldBackground);
                // Ensure that selection and hover indicators are not drawn for the highlighted cell
                event.detail &= ~SWT.SELECTED;
                event.detail &= ~SWT.HOT;
            }
            // Disable drawing foreground. paint() will draw the foreground text in order to fix coloring issues when the row is selected.
            event.detail &= ~SWT.FOREGROUND;
        }

        @Override
        protected void paint(final Event event, final Object element) {
            // Draw just the text with the appropriate background color
            final TreeItem item = (TreeItem) event.item;
            final Rectangle textBounds = item.getTextBounds(event.index);
            final GC gc = event.gc;
            final String txt = item.getText(event.index);
            gc.setForeground(item.getForeground(event.index));
            String drawTxt = txt;
            // Check the width of the text and truncate it as necessary
            final int maxWidth = Math.max(gc.getClipping().width - 6, textBounds.width);
            if (maxWidth > 0) {
                String truncatedTxt = txt;
                while (gc.textExtent(drawTxt).x > maxWidth && truncatedTxt.length() > 0) {
                    truncatedTxt = truncatedTxt.substring(0, truncatedTxt.length() - 1);
                    drawTxt = truncatedTxt + "...";
                }
                gc.drawString(drawTxt, textBounds.x, textBounds.y, true);
            }
        }
    });
    nextValueEditingSupport = new NextValueEditingSupport(simulationUiService, treeViewer);
    nextValueColumn.setEditingSupport(nextValueEditingSupport);
    nextValueColumn.getColumn().addControlListener(resizeListener);
    // Make headers and lines visible
    final Tree tree = treeViewer.getTree();
    tree.setHeaderVisible(true);
    tree.setLinesVisible(true);
    createContextMenu(tree);
    // Listen for tree resizing
    tree.addControlListener(resizeListener);
    // Create the slider
    frameSlider = new Slider(root, SWT.HORIZONTAL);
    frameSlider.addSelectionListener(new SelectionAdapter() {

        @Override
        public void widgetSelected(final SelectionEvent e) {
            if (!editingTreeViewer) {
                startEditingTreeViewer();
                frameScrollOffset = frameSlider.getMaximum() - frameSlider.getSelection() - frameSlider.getThumb();
                update();
                stopEditingTreeViewer();
            }
        }
    });
    GridDataFactory.fillDefaults().grab(true, false).applyTo(frameSlider);
    // Add listener and populate UI with current state
    simulationUiService.addStateChangeListener(stateListener);
    stateListener.onSimulatorStateChanged(simulationUiService.getCurrentState());
}
Also used : ViewerFilter(org.eclipse.jface.viewers.ViewerFilter) Slider(org.eclipse.swt.widgets.Slider) FeatureInstance(org.osate.aadl2.instance.FeatureInstance) SimulationEngineState(edu.uah.rsesc.aadlsimulator.SimulationEngineState) TreeItem(org.eclipse.swt.widgets.TreeItem) ColumnViewer(org.eclipse.jface.viewers.ColumnViewer) Rectangle(org.eclipse.swt.graphics.Rectangle) ColumnViewer(org.eclipse.jface.viewers.ColumnViewer) TreeViewer(org.eclipse.jface.viewers.TreeViewer) Viewer(org.eclipse.jface.viewers.Viewer) Image(org.eclipse.swt.graphics.Image) OwnerDrawLabelProvider(org.eclipse.jface.viewers.OwnerDrawLabelProvider) InstanceObject(org.osate.aadl2.instance.InstanceObject) GridLayout(org.eclipse.swt.layout.GridLayout) ComponentInstance(org.osate.aadl2.instance.ComponentInstance) SelectionEvent(org.eclipse.swt.events.SelectionEvent) Tree(org.eclipse.swt.widgets.Tree) InputConstraint(edu.uah.rsesc.aadlsimulator.xtext.inputConstraint.InputConstraint) GC(org.eclipse.swt.graphics.GC) StyledCellLabelProvider(org.eclipse.jface.viewers.StyledCellLabelProvider) DeviceResourceManager(org.eclipse.jface.resource.DeviceResourceManager) Composite(org.eclipse.swt.widgets.Composite) ViewerComparator(org.eclipse.jface.viewers.ViewerComparator) Color(org.eclipse.swt.graphics.Color) SelectionAdapter(org.eclipse.swt.events.SelectionAdapter) SimulatorState(edu.uah.rsesc.aadlsimulator.ui.services.SimulatorState) RGB(org.eclipse.swt.graphics.RGB) ViewerColumn(org.eclipse.jface.viewers.ViewerColumn) TreeViewerColumn(org.eclipse.jface.viewers.TreeViewerColumn) ViewerCell(org.eclipse.jface.viewers.ViewerCell) TreeViewerColumn(org.eclipse.jface.viewers.TreeViewerColumn) ControlEvent(org.eclipse.swt.events.ControlEvent) BeforeStepForwardEvent(edu.uah.rsesc.aadlsimulator.ui.events.BeforeStepForwardEvent) Event(org.eclipse.swt.widgets.Event) SelectionEvent(org.eclipse.swt.events.SelectionEvent) InstanceObject(org.osate.aadl2.instance.InstanceObject) Display(org.eclipse.swt.widgets.Display) PostConstruct(javax.annotation.PostConstruct)

Example 3 with InputConstraint

use of edu.uah.rsesc.aadlsimulator.xtext.inputConstraint.InputConstraint in project AGREE by loonwerks.

the class InputConstraintHelper method parse.

/**
 * @param str
 * @return the result of parsing the input constraint string. Returns a valid result with a null input constraint if str is null or empty.
 */
public Result parse(final String str) {
    if (str == null || str.trim().length() == 0) {
        return new Result((InputConstraint) null);
    }
    final IParseResult result = parser.parse(new StringReader(str));
    // Check for syntax errors
    if (result.hasSyntaxErrors()) {
        String errors = "Error parsing '" + str + "':";
        for (final INode err : result.getSyntaxErrors()) {
            errors += "\n" + err.getSyntaxErrorMessage().getMessage();
        }
        return new Result(errors);
    }
    final InputConstraint ic = (InputConstraint) result.getRootASTElement();
    final Resource r = createResource();
    r.getContents().add(ic);
    return new Result(ic);
}
Also used : INode(org.eclipse.xtext.nodemodel.INode) StringReader(java.io.StringReader) Resource(org.eclipse.emf.ecore.resource.Resource) IParseResult(org.eclipse.xtext.parser.IParseResult) InputConstraint(edu.uah.rsesc.aadlsimulator.xtext.inputConstraint.InputConstraint) IParseResult(org.eclipse.xtext.parser.IParseResult)

Example 4 with InputConstraint

use of edu.uah.rsesc.aadlsimulator.xtext.inputConstraint.InputConstraint in project AGREE by loonwerks.

the class InputConstraintDialog method addTextExpressionMenuItem.

/**
 * This function will bubble up to edit the parent if the parent is a binary or negative expression
 * @param menu
 * @param ref
 * @param label
 * @param expectedType
 * @param defaultExpressionTxt used if the reference is null
 */
private void addTextExpressionMenuItem(final Menu menu, Reference ref, final String label, final ResultType expectedType, final String defaultExpressionTxt) {
    // If the value is part of a binary expression, prompt the user to edit the entire containing binary expression.
    while (ref.getParent() != null && (ref.getParent().get() instanceof BinaryExpression || ref.getParent().get() instanceof NegativeExpression)) {
        ref = ref.getParent();
    }
    final Reference refToEdit = ref;
    final MenuItem menuItem = new MenuItem(menu, SWT.NONE);
    menuItem.setText(label);
    // Disable the menu item if unable to unparse
    final InputConstraint ic = (InputConstraint) refToEdit.get();
    final String exprTxt = unparse(ic);
    menuItem.setEnabled(exprTxt != null);
    if (menuItem.isEnabled()) {
        menuItem.addSelectionListener(new SelectionAdapter() {

            @Override
            public void widgetSelected(final SelectionEvent e) {
                final InputDialog txtExpressionDlg = new InputDialog(dlg.getShell(), "Edit Expression", "Edit Expression", exprTxt, value -> getParseAndValidateResult(value, expectedType).getErrorMessage());
                if (txtExpressionDlg.open() == Window.OK) {
                    refToEdit.set(getParseAndValidateResult(txtExpressionDlg.getValue(), expectedType).getInputConstraint());
                    dlg.refreshContraint();
                }
            }
        });
    }
}
Also used : InputConstraintFactory(edu.uah.rsesc.aadlsimulator.xtext.inputConstraint.InputConstraintFactory) Arrays(java.util.Arrays) PreExpression(edu.uah.rsesc.aadlsimulator.xtext.inputConstraint.PreExpression) EStructuralFeature(org.eclipse.emf.ecore.EStructuralFeature) IDialogConstants(org.eclipse.jface.dialogs.IDialogConstants) RandomElementExpression(edu.uah.rsesc.aadlsimulator.xtext.inputConstraint.RandomElementExpression) MenuEvent(org.eclipse.swt.events.MenuEvent) Composite(org.eclipse.swt.widgets.Composite) Map(java.util.Map) Widget(org.eclipse.swt.widgets.Widget) RandomIntegerExpression(edu.uah.rsesc.aadlsimulator.xtext.inputConstraint.RandomIntegerExpression) IntegerLiteral(edu.uah.rsesc.aadlsimulator.xtext.inputConstraint.IntegerLiteral) SelectionAdapter(org.eclipse.swt.events.SelectionAdapter) Button(org.eclipse.swt.widgets.Button) BooleanLiteral(edu.uah.rsesc.aadlsimulator.xtext.inputConstraint.BooleanLiteral) InputConstraintStandaloneSetup(edu.uah.rsesc.aadlsimulator.xtext.InputConstraintStandaloneSetup) EObject(org.eclipse.emf.ecore.EObject) Display(org.eclipse.swt.widgets.Display) Collectors(java.util.stream.Collectors) ResultType(edu.uah.rsesc.aadlsimulator.xtext.util.ResultType) Objects(java.util.Objects) List(java.util.List) Window(org.eclipse.jface.window.Window) Stream(java.util.stream.Stream) MenuItem(org.eclipse.swt.widgets.MenuItem) RowLayoutFactory(org.eclipse.jface.layout.RowLayoutFactory) SWT(org.eclipse.swt.SWT) RandomRealExpression(edu.uah.rsesc.aadlsimulator.xtext.inputConstraint.RandomRealExpression) MenuListener(org.eclipse.swt.events.MenuListener) IntervalExpression(edu.uah.rsesc.aadlsimulator.xtext.inputConstraint.IntervalExpression) Operator(edu.uah.rsesc.aadlsimulator.xtext.inputConstraint.Operator) Label(org.eclipse.swt.widgets.Label) SelectionListener(org.eclipse.swt.events.SelectionListener) ScalarExpression(edu.uah.rsesc.aadlsimulator.xtext.inputConstraint.ScalarExpression) InputDialog(org.eclipse.jface.dialogs.InputDialog) BinaryExpression(edu.uah.rsesc.aadlsimulator.xtext.inputConstraint.BinaryExpression) InputConstraintPackage(edu.uah.rsesc.aadlsimulator.xtext.inputConstraint.InputConstraintPackage) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) ControlEvent(org.eclipse.swt.events.ControlEvent) InputConstraintHelper(edu.uah.rsesc.aadlsimulator.xtext.util.InputConstraintHelper) EClass(org.eclipse.emf.ecore.EClass) NegativeExpression(edu.uah.rsesc.aadlsimulator.xtext.inputConstraint.NegativeExpression) GridData(org.eclipse.swt.layout.GridData) RowData(org.eclipse.swt.layout.RowData) Link(org.eclipse.swt.widgets.Link) RealLiteral(edu.uah.rsesc.aadlsimulator.xtext.inputConstraint.RealLiteral) Shell(org.eclipse.swt.widgets.Shell) EcoreUtil(org.eclipse.emf.ecore.util.EcoreUtil) ConstRefExpression(edu.uah.rsesc.aadlsimulator.xtext.inputConstraint.ConstRefExpression) SetExpression(edu.uah.rsesc.aadlsimulator.xtext.inputConstraint.SetExpression) EClassifier(org.eclipse.emf.ecore.EClassifier) TestReferenceTypeResolver(edu.uah.rsesc.aadlsimulator.xtext.TestReferenceTypeResolver) InputConstraint(edu.uah.rsesc.aadlsimulator.xtext.inputConstraint.InputConstraint) Dialog(org.eclipse.jface.dialogs.Dialog) ControlAdapter(org.eclipse.swt.events.ControlAdapter) SelectionEvent(org.eclipse.swt.events.SelectionEvent) Menu(org.eclipse.swt.widgets.Menu) ElementRefExpression(edu.uah.rsesc.aadlsimulator.xtext.inputConstraint.ElementRefExpression) Control(org.eclipse.swt.widgets.Control) InputDialog(org.eclipse.jface.dialogs.InputDialog) BinaryExpression(edu.uah.rsesc.aadlsimulator.xtext.inputConstraint.BinaryExpression) SelectionAdapter(org.eclipse.swt.events.SelectionAdapter) SelectionEvent(org.eclipse.swt.events.SelectionEvent) MenuItem(org.eclipse.swt.widgets.MenuItem) InputConstraint(edu.uah.rsesc.aadlsimulator.xtext.inputConstraint.InputConstraint) NegativeExpression(edu.uah.rsesc.aadlsimulator.xtext.inputConstraint.NegativeExpression)

Example 5 with InputConstraint

use of edu.uah.rsesc.aadlsimulator.xtext.inputConstraint.InputConstraint in project AGREE by loonwerks.

the class InputConstraintDialog method main.

public static void main(final String[] args) {
    new Display();
    final com.google.inject.Injector injector = new InputConstraintStandaloneSetup().createInjectorAndDoEMFRegistration();
    final InputConstraintHelper icHelper = injector.getInstance(InputConstraintHelper.class);
    final TestReferenceTypeResolver resolver = new TestReferenceTypeResolver();
    // Create model to provide information to the dialog.
    final Model model = new Model() {

        @Override
        public String unparse(final InputConstraint ic) {
            return icHelper.unparse(ic);
        }

        @Override
        public InputConstraintHelper.Result parseAndValidate(final String str, final ResultType expectedType, final int numberOfPreviousSteps) {
            return icHelper.parseAndValidate(str, resolver, expectedType, numberOfPreviousSteps);
        }

        @Override
        public InputConstraintHelper.Result validate(final InputConstraint ic, final ResultType expectedType, final int numberOfPreviousSteps) {
            return icHelper.validate(ic, resolver, expectedType, numberOfPreviousSteps);
        }

        @Override
        public Stream<ElementRefExpression> getVariables() {
            final Stream.Builder<ElementRefExpression> builder = Stream.builder();
            builder.add(createElementRefExpression("a1", "b", "d"));
            builder.add(createElementRefExpression("a1"));
            builder.add(createElementRefExpression("a1", "b"));
            builder.add(createElementRefExpression("a1", "b", "c"));
            builder.add(createElementRefExpression("a2", "b"));
            builder.add(createElementRefExpression("a2"));
            return builder.build();
        }

        private ElementRefExpression createElementRefExpression(String... ids) {
            final ElementRefExpression result = InputConstraintFactory.eINSTANCE.createElementRefExpression();
            result.getIds().addAll(Arrays.asList(ids));
            return result;
        }

        @Override
        public ResultType getElementReferenceType(final ElementRefExpression reference) {
            return resolver.getElementReferenceType(reference);
        }

        @Override
        public Stream<ConstRefExpression> getConstants() {
            final Stream.Builder<ConstRefExpression> builder = Stream.builder();
            builder.add(createConstRefExpression("C1", "my_pkg"));
            builder.add(createConstRefExpression("C2", "my_pkg", "inner_pkg"));
            builder.add(createConstRefExpression("C3A", "my_pkg", "inner_pkg", "inner_inner_pkg"));
            builder.add(createConstRefExpression("C3B", "my_pkg", "inner_pkg", "inner_inner_pkg"));
            builder.add(createConstRefExpression("C3C", "my_pkg", "inner_pkg", "inner_inner_pkg"));
            builder.add(createConstRefExpression("C3D", "my_pkg", "inner_pkg", "inner_inner_pkg"));
            return builder.build();
        }

        private ConstRefExpression createConstRefExpression(final String constantName, final String... packageSegments) {
            final ConstRefExpression result = InputConstraintFactory.eINSTANCE.createConstRefExpression();
            result.setConstantName(constantName);
            result.getPackageSegments().addAll(Arrays.asList(packageSegments));
            return result;
        }

        @Override
        public ResultType getConstReferenceType(final ConstRefExpression reference) {
            return resolver.getConstReferenceType(reference);
        }
    };
    // Show the dialog
    final InputConstraint initialConstraint = icHelper.parse("5 + 5").getInputConstraint();
    final Result result = InputConstraintDialog.show(null, model, "z", initialConstraint, ResultType.INTEGER, 1);
    if (result == null) {
        System.out.println("Dialog canceled");
    } else {
        System.out.println("Result:");
        System.out.println(result.inputConstraint);
    }
}
Also used : ConstRefExpression(edu.uah.rsesc.aadlsimulator.xtext.inputConstraint.ConstRefExpression) InputConstraintHelper(edu.uah.rsesc.aadlsimulator.xtext.util.InputConstraintHelper) ResultType(edu.uah.rsesc.aadlsimulator.xtext.util.ResultType) TestReferenceTypeResolver(edu.uah.rsesc.aadlsimulator.xtext.TestReferenceTypeResolver) Stream(java.util.stream.Stream) InputConstraintStandaloneSetup(edu.uah.rsesc.aadlsimulator.xtext.InputConstraintStandaloneSetup) InputConstraint(edu.uah.rsesc.aadlsimulator.xtext.inputConstraint.InputConstraint) Display(org.eclipse.swt.widgets.Display) ElementRefExpression(edu.uah.rsesc.aadlsimulator.xtext.inputConstraint.ElementRefExpression)

Aggregations

InputConstraint (edu.uah.rsesc.aadlsimulator.xtext.inputConstraint.InputConstraint)6 Display (org.eclipse.swt.widgets.Display)3 InputConstraintStandaloneSetup (edu.uah.rsesc.aadlsimulator.xtext.InputConstraintStandaloneSetup)2 TestReferenceTypeResolver (edu.uah.rsesc.aadlsimulator.xtext.TestReferenceTypeResolver)2 ConstRefExpression (edu.uah.rsesc.aadlsimulator.xtext.inputConstraint.ConstRefExpression)2 ElementRefExpression (edu.uah.rsesc.aadlsimulator.xtext.inputConstraint.ElementRefExpression)2 InputConstraintHelper (edu.uah.rsesc.aadlsimulator.xtext.util.InputConstraintHelper)2 ResultType (edu.uah.rsesc.aadlsimulator.xtext.util.ResultType)2 Stream (java.util.stream.Stream)2 EObject (org.eclipse.emf.ecore.EObject)2 SimulationEngineState (edu.uah.rsesc.aadlsimulator.SimulationEngineState)1 SimulationProperty (edu.uah.rsesc.aadlsimulator.agree.SimulationProperty)1 AGREEPropertyStatus (edu.uah.rsesc.aadlsimulator.agree.engine.AGREEPropertyStatus)1 BeforeStepForwardEvent (edu.uah.rsesc.aadlsimulator.ui.events.BeforeStepForwardEvent)1 SimulatorState (edu.uah.rsesc.aadlsimulator.ui.services.SimulatorState)1 BinaryExpression (edu.uah.rsesc.aadlsimulator.xtext.inputConstraint.BinaryExpression)1 BooleanLiteral (edu.uah.rsesc.aadlsimulator.xtext.inputConstraint.BooleanLiteral)1 InputConstraintFactory (edu.uah.rsesc.aadlsimulator.xtext.inputConstraint.InputConstraintFactory)1 InputConstraintPackage (edu.uah.rsesc.aadlsimulator.xtext.inputConstraint.InputConstraintPackage)1 IntegerLiteral (edu.uah.rsesc.aadlsimulator.xtext.inputConstraint.IntegerLiteral)1