Exemple #1
0
  /* (non-Javadoc)
   * @see java.awt.event.ActionListener#actionPerformed(ActionEvent)
   */
  public void actionPerformed(ActionEvent aEvent) {
    // String command = aEvent.getActionCommand();
    if (aEvent.getSource() == _runMinimalSpanSolverButton) {
      try {
        _uConstraints = new UnitConstraints(_model, _entities, _relations);
        _solutions = _uConstraints.minimalSpanSolutions();
      } catch (IllegalActionException e) {
        MessageHandler.error("Minimal Span Solver failed: ", e);
        return;
      }

      _solutionsListModel.setSolutions(_solutions);
      _solutionsList.setModel(_solutionsListModel);
    } else if (aEvent.getSource() == _runFullSolverButton) {
      _solutionsList.clearSelection();

      try {
        _uConstraints = new UnitConstraints(_model, _entities, _relations);

        Solution solution = _uConstraints.completeSolution();
        _fullSolutionResult.setText(solution.getShortStateDesc());

        // solution.trace();
      } catch (IllegalActionException e) {
        MessageHandler.error("Full Solver failed: ", e);
        return;
      }
    } else if (aEvent.getSource() == _setToSelectedButton) {
      _setSelectedComponents();
    } else if (aEvent.getSource() == _showComponentsButton) {
      _showComponents();
    } else {
      super.actionPerformed(aEvent);
    }
  }
 /**
  * Construct a frame associated with an SCR Model.
  *
  * @param model The model to put in this frame, or null if none.
  * @param tableau The tableau responsible for this frame, or null if none.
  */
 public SCRTableFrame(NamedObj model, Tableau tableau) {
   super(tableau);
   if (model instanceof FSMActor) {
     _model = (FSMActor) model;
   } else {
     MessageHandler.error("Cannot initialize SCRTableFrame with a " + model.getClassName());
   }
   _init();
 }
  /**
   * React to the fact that the change has failed by reporting it.
   *
   * @param change The change that was attempted.
   * @param exception The exception that resulted.
   */
  public void changeFailed(ChangeRequest change, Exception exception) {
    // Ignore if this is not the originator.
    if ((change != null) && (change.getSource() != this)) {
      return;
    }

    if ((change != null) && !change.isErrorReported()) {
      change.setErrorReported(true);
      MessageHandler.error("Rename failed: ", exception);
    }
  }
 /**
  * Create a top-level viewer for the specified object with the specified parent window.
  *
  * @param object The object to configure, which is required to contain a parameter with name
  *     matching <i>parameterName</i> and value that is an array of records.
  * @param parent The parent window, which is required to be an instance of TableauFrame.
  */
 @Override
 public void createEditor(NamedObj object, Frame parent) {
   try {
     Parameter attributeToEdit =
         (Parameter) object.getAttribute(parameterName.getExpression(), Parameter.class);
     if (attributeToEdit == null) {
       MessageHandler.error("No such parameter: " + parameterName.getExpression());
       return;
     }
     Token value = attributeToEdit.getToken();
     if (!(value instanceof ArrayToken)) {
       MessageHandler.error(
           "Parameter does not contain an array token: " + attributeToEdit.toString());
       return;
     }
     ArrayOfRecordsPane pane = new ArrayOfRecordsPane();
     pane.display((ArrayToken) value, (ArrayToken) columns.getToken());
     new ComponentDialog(parent, object.getFullName(), pane);
   } catch (KernelException ex) {
     MessageHandler.error("Cannot get specified string attribute to edit.", ex);
     return;
   }
 }
    /** Perform the action. */
    public void actionPerformed(ActionEvent e) {
      super.actionPerformed(e);
      // Dialog to ask for a case name.
      Query query = new Query();
      List refinements = _case.entityList(Refinement.class);
      if (refinements.size() < 2) {
        MessageHandler.error("No cases to remove.");
      } else {
        String[] caseNames = new String[refinements.size() - 1];
        Iterator cases = refinements.iterator();
        int i = 0;
        while (cases.hasNext()) {
          String name = ((Nameable) cases.next()).getName();
          if (!name.equals("default")) {
            caseNames[i] = name;
            i++;
          }
        }
        query.addChoice("case", "Remove case", caseNames, caseNames[0]);
        ComponentDialog dialog = new ComponentDialog(CaseGraphFrame.this, "Remove Case", query);
        if (dialog.buttonPressed().equals("OK")) {
          final String name = query.getStringValue("case");
          String moml = "<deleteEntity name=\"" + StringUtilities.escapeForXML(name) + "\"/>";

          // The following is, regrettably, copied from ModalTransitionController.
          MoMLChangeRequest change =
              new MoMLChangeRequest(this, _case, moml) {
                protected void _execute() throws Exception {
                  super._execute();
                  // Find the tabbed pane that matches the name and remove it.
                  int count = _tabbedPane.getTabCount();
                  for (int i = 0; i < count; i++) {
                    if (name.equals(_tabbedPane.getTitleAt(i))) {
                      _tabbedPane.remove(i);
                      break;
                    }
                  }
                }
              };
          _case.requestChange(change);
        }
      }
    }
Exemple #6
0
  /**
   * If the model is deadlocked, report the deadlock if parameter "SuppressDeadlockReporting" is not
   * set to boolean true, and return false. Otherwise, return true. Deadlock occurs if the number of
   * blocked threads equals the number of active threads.
   *
   * @return False if deadlock occurred, true otherwise.
   * @exception IllegalActionException If thrown while getting the "SuppressDeadlockReporting"
   *     token.
   */
  protected synchronized boolean _resolveInternalDeadlock() throws IllegalActionException {
    if (_getBlockedThreadsCount() == _getActiveThreadsCount()) {
      // Report deadlock.
      Parameter suppress =
          (Parameter) getContainer().getAttribute("SuppressDeadlockReporting", Parameter.class);

      if ((suppress == null)
          || !(suppress.getToken() instanceof BooleanToken)
          || !((BooleanToken) suppress.getToken()).booleanValue()) {
        MessageHandler.message(
            "Model ended with a deadlock "
                + "(this may be normal for this model).\n"
                + "A parameter with name SuppressDeadlockReporting and "
                + "value true will suppress this message.");
      }

      return false;
    }

    return true;
  }
Exemple #7
0
  /**
   * Open a dialog to edit the target.
   *
   * @param e The event.
   */
  public void actionPerformed(ActionEvent e) {
    try {
      // Determine which entity was selected for the look inside action.
      super.actionPerformed(e);

      NamedObj target = getTarget();

      if (target == null) {
        return;
      }

      // Create a dialog for configuring the object.
      // First, identify the top parent frame.
      Frame parent = getFrame();
      openDialog(parent, target);
    } catch (Throwable throwable) {
      // Giotto code generator on giotto/demo/Hierarchy/Hierarchy.xml
      // was throwing an exception here that was not being displayed
      // in the UI.
      MessageHandler.error("Failed to open a dialog to edit the target.", throwable);
    }
  }
Exemple #8
0
  /**
   * Create the window with spinners set.
   *
   * @param widget Widget whose properties are being displayed.
   */
  public WidgetPropertiesFrame(Widget widget) {
    setLayout(new GridLayout(LAYOUT_ROWS, LAYOUT_COLS, DEFAULT_GAP, DEFAULT_GAP));
    setLocation(POSITION_X, POSITION_Y);

    // Set up row #1.
    add(new JLabel("Width: "));
    add(_widthSpinner);
    add(new JLabel("X: "));
    add(_xSpinner);

    // Set up row #2.
    add(new JLabel("Height: "));
    add(_heightSpinner);
    add(new JLabel("Y: "));
    add(_ySpinner);

    _widget = widget;
    if (_widget instanceof NamedObjectWidgetInterface) {
      NamedObj namedObj =
          ((NamedObjectWidgetInterface) _widget).getPositionableElement().getElement();

      if (HomerMainFrame.isLabelWidget(namedObj)) {
        _label.setText(((Settable) namedObj).getExpression());

        // Set up row #4.
        add(new JLabel("Label: "));
        add(_label);
        add(new JLabel(""));
        add(new JLabel(""));
      }

      if (namedObj instanceof Settable) {
        // Set up row #3.
        add(new JLabel(""));
        add(_enabled);
        add(_required);
        add(new JLabel(""));

        // If attribute set, mark checkbox accordingly.
        try {
          Attribute enabledAttr = namedObj.getAttribute(HomerConstants.ENABLED_NODE);
          if (enabledAttr instanceof Variable) {
            Token token = ((Variable) enabledAttr).getToken();
            if (token instanceof BooleanToken) {
              _enabled.setState(((BooleanToken) token).booleanValue());
            }
          }
        } catch (IllegalActionException e) {
          MessageHandler.error(e.getMessage(), e);
        }

        // If attribute set, mark checkbox accordingly.
        try {
          Attribute requiredAttr = namedObj.getAttribute(HomerConstants.REQUIRED_NODE);
          if (requiredAttr instanceof Variable) {
            Token token = ((Variable) requiredAttr).getToken();
            if (token instanceof BooleanToken) {
              _required.setState(((BooleanToken) token).booleanValue());
            }
          }
        } catch (IllegalActionException e) {
          MessageHandler.error(e.getMessage(), e);
        }
      }
    }

    _heightSpinner.setValue(widget.getPreferredBounds().height);
    _widthSpinner.setValue(widget.getPreferredBounds().width);
    _xSpinner.setValue(widget.getPreferredLocation().x + widget.getPreferredBounds().x);
    _ySpinner.setValue(widget.getPreferredLocation().y + widget.getPreferredBounds().y);
  }
Exemple #9
0
 /**
  * React to the fact that a change failed by setting a flag that causes an exception to be thrown
  * in next call to prefire() or wrapup().
  *
  * @param change The change request.
  * @param exception The exception that resulted.
  */
 public void changeFailed(ChangeRequest change, java.lang.Exception exception) {
   MessageHandler.error("Failed to set variable.", exception);
 }
Exemple #10
0
  /**
   * Process this event. If the mode is {@link Mode#ERROR}, a message is shown in an error dialog.
   * If the mode is {@link Mode#EXCEPTION}, a message is shown in the form of an exception. If the
   * mode is {@link Mode#MESSAGE}, a message is shown in a message dialog. If the mode is {@link
   * Mode#TABLEAU}, a tableau is opened to show the message. The default tableau is the one defined
   * in the {@link #tableau} parameter. However, if {@link #referredTableau} is not an empty string,
   * its value is interpreted as the name of the tableau parameter in the model, whose tableau
   * should be used instead of the default one. If the mode is {@link Mode#WARNING}, a message is
   * shown in a warning dialog. If the mode is {@link Mode#YES_OR_NO}, a query dialog is shown with
   * the message, which allows the user to answer with yes or no. The answer is stored in {@link
   * #response}.
   *
   * @param arguments The arguments used to process this event, which must be either an ArrayToken
   *     or a RecordToken.
   * @return A refiring data structure that contains a non-negative double number if refire() should
   *     be called after that amount of model time, or null if refire() need not be called.
   * @exception IllegalActionException If the tableau cannot be used, or if thrown by the
   *     superclass.
   */
  public RefiringData fire(Token arguments) throws IllegalActionException {
    RefiringData data = super.fire(arguments);

    Mode choice = (Mode) mode.getChosenValue();
    String text = message.stringValue();
    MessageHandler oldHandler;
    switch (choice) {
      case ERROR:
        oldHandler = MessageHandler.getMessageHandler();
        try {
          MessageHandler.setMessageHandler(_MESSAGE_HANDLER);
          MessageHandler.error(text);
        } finally {
          MessageHandler.setMessageHandler(oldHandler);
        }
        break;
      case MESSAGE:
        oldHandler = MessageHandler.getMessageHandler();
        try {
          MessageHandler.setMessageHandler(_MESSAGE_HANDLER);
          MessageHandler.message(text);
        } finally {
          MessageHandler.setMessageHandler(oldHandler);
        }
        break;
      case EXCEPTION:
        throw new RuntimeException(text);
      case TABLEAU:
        Effigy effigy = EventUtils.findToplevelEffigy(this);
        if (effigy == null) {
          // The effigy may be null if the model is closed.
          return data;
        }

        Tableau tableau = EventUtils.getTableau(this, referredTableau, this.tableau);
        if (tableau != null && !(tableau.getFrame() instanceof TextEditor)) {
          EventUtils.setTableau(this, referredTableau, this.tableau, null);
          EventUtils.closeTableau(tableau);
          tableau = null;
        }

        boolean openNewWindow = true;
        String previousText = null;
        if (tableau != null) {
          JFrame frame = tableau.getFrame();
          if (frame instanceof TextEditor) {
            TextEditor editor = (TextEditor) frame;
            if (editor.getEffigy() == null) {
              previousText = editor.text.getText();
            } else {
              openNewWindow = false;
            }
          }
        }

        TextEditor frame;
        if (openNewWindow) {
          TextEffigy textEffigy;
          try {
            textEffigy = TextEffigy.newTextEffigy(effigy, "");
          } catch (Exception e) {
            throw new IllegalActionException(this, e, "Unable to " + "create effigy.");
          }
          try {
            tableau = new Tableau(textEffigy, "tableau");
          } catch (NameDuplicationException e) {
            throw new IllegalActionException(this, e, "Unable to " + "create tableau.");
          }
          frame = new TextEditor(tableau.getTitle(), textEffigy.getDocument());
          frame.text.setColumns(((IntToken) columnsDisplayed.getToken()).intValue());
          frame.text.setRows(((IntToken) rowsDisplayed.getToken()).intValue());
          tableau.setFrame(frame);
          frame.setTableau(tableau);
          EventUtils.setTableau(this, referredTableau, this.tableau, tableau);
          frame.pack();
          frame.setVisible(true);
          if (previousText != null) {
            frame.text.setText(previousText);
          }
        } else {
          frame = (TextEditor) tableau.getFrame();
        }
        frame.text.append(text + "\n");
        try {
          int lineOffset = frame.text.getLineStartOffset(frame.text.getLineCount() - 1);
          frame.text.setCaretPosition(lineOffset);
        } catch (BadLocationException ex) {
          // Ignore ... worst case is that the scrollbar
          // doesn't move.
        }
        break;
      case WARNING:
        try {
          oldHandler = MessageHandler.getMessageHandler();
          try {
            MessageHandler.setMessageHandler(_MESSAGE_HANDLER);
            MessageHandler.warning(text);
          } finally {
            MessageHandler.setMessageHandler(oldHandler);
          }
          response.setToken(BooleanToken.TRUE);
        } catch (CancelException e) {
          response.setToken(BooleanToken.FALSE);
        }
        break;
      case YES_OR_NO:
        oldHandler = MessageHandler.getMessageHandler();
        boolean success = false;
        boolean answer;
        try {
          MessageHandler.setMessageHandler(_MESSAGE_HANDLER);
          answer = MessageHandler.yesNoQuestion(text);
          success = true;
        } finally {
          MessageHandler.setMessageHandler(oldHandler);
        }
        if (success) {
          response.setToken(BooleanToken.getInstance(answer));
        }
        break;
      default:
        throw new IllegalActionException(
            "Unrecognized mode choice \"" + mode.getExpression() + "\".");
    }

    return data;
  }
  /**
   * Populate the actor by reading the file specified by the <i>source</i> parameter. Note that the
   * exception thrown here is a runtime exception, inappropriately. This is because execution of
   * this method is deferred to the last possible moment, and it is often evaluated in a context
   * where a compile-time exception cannot be thrown. Thus, extra care should be exercised to
   * provide valid MoML specifications.
   *
   * @exception InvalidStateException If the source cannot be read, or if an exception is thrown
   *     parsing its MoML data.
   */
  public void populate() throws InvalidStateException {
    boolean resetPolulatingValue = false;
    try {
      if (_populating) {
        resetPolulatingValue = true;
        return;
      }

      // Avoid populating during cloning.
      if (_cloning) {
        return;
      }

      // Do not populate if this is a derived object.
      // Instead, populate the object is this is derived
      // from, which will have the side effect of populating
      // this object.
      if (getDerivedLevel() != Integer.MAX_VALUE) {
        // Object is derived. Delegate to the most remote
        // prototype.
        List prototypes = getPrototypeList();
        if (prototypes == null || prototypes.size() == 0) {
          throw new InternalErrorException(
              getFullName() + ": Object says it is derived but reports no prototypes!");
        }
        // The prototype must have the same class as this.
        LazyTypedCompositeActor prototype =
            (LazyTypedCompositeActor) prototypes.get(prototypes.size() - 1);
        prototype.populate();
        return;
      }

      _populating = true;

      if (!_configureDone) {
        // NOTE: If you suspect this is being called prematurely,
        // the uncomment the following to see who is doing the
        // calling.
        // System.out.println("-----------------------");
        // (new Exception()).printStackTrace();
        // NOTE: Set this early to prevent repeated attempts to
        // evaluate if an exception occurs.  This way, it will
        // be possible to examine a partially populated entity.
        _configureDone = true;

        // NOTE: This does not seem like the right thing to do!
        // removeAllEntities();

        // If we have a subclass that has LazyTypedCompositeActor
        // in it, then things get tricky.  See
        // actor/lib/test/auto/LazySubClassModel.xml

        // If this is an instance or subclass of something, that
        // something must also be a LazyTypedCompositeActor and
        // it should be populated first.
        if (getParent() != null) {
          ((LazyTypedCompositeActor) getParent()).populate();
        }

        // We were getting ConcurrentModifications because
        // when we instantiate and call
        // NamedObj._markContentsDerived() we end up
        // eventually calling populate(), which calls
        // parse(URL, String, Reader) and adds a
        // ParserAttribute, which results in a
        // ConcurrentModificationException

        MoMLParser parser = new MoMLParser(workspace());

        // If we get the parser from ParserAttribute, then
        // after we call parse(), MoMLParser._xmlParser gets
        // set to null, which causes problems for the calling
        // parse() method.
        // NamedObj toplevel = toplevel();
        // MoMLParser parser = ParserAttribute.getParser(toplevel);

        parser.setContext(this);

        List savedFilters = MoMLParser.getMoMLFilters();
        try {
          MoMLParser.setMoMLFilters(null);
          if ((_configureSource != null) && !_configureSource.equals("")) {
            URL xmlFile = new URL(_base, _configureSource);
            parser.parse(xmlFile, xmlFile);
          }

          if ((_configureText != null) && !_configureText.equals("")) {
            // NOTE: Regrettably, the XML parser we are using cannot
            // deal with having a single processing instruction at the
            // outer level.  Thus, we have to strip it.
            String trimmed = _configureText.trim();

            if (trimmed.startsWith("<?") && trimmed.endsWith("?>")) {
              trimmed = trimmed.substring(2, trimmed.length() - 2).trim();

              if (trimmed.startsWith("moml")) {
                trimmed = trimmed.substring(4).trim();
                parser.parse(_base, trimmed);
              }

              // If it's not a moml processing instruction, ignore.
            } else {
              // Data is not enclosed in a processing instruction.
              // Must have been given in a CDATA section.
              parser.parse(_base, _configureText);

              // Our work here is done, free this up.
              _configureText = null;
            }
          }
        } finally {
          MoMLParser.setMoMLFilters(savedFilters);
        }
      }
    } catch (Exception ex) {
      MessageHandler.error("Failed to populate contents.", ex);

      // Oddly, under JDK1.3.1, we may see the line
      // "Exception occurred during event dispatching:"
      // in the console window, but there is no stack trace.
      // If we change this exception to a RuntimeException, then
      // the stack trace appears.  My guess is this indicates a
      // bug in the ptolemy.kernel.Exception* classes or in JDK1.3.1
      // Note that under JDK1.4, the stack trace is printed in
      // both cases.
      throw new InvalidStateException(this, ex, "Failed to populate contents");
    } finally {
      _populating = resetPolulatingValue;
    }
  }
Exemple #12
0
  /**
   * Process the edit icon command.
   *
   * @param e The event.
   */
  public void actionPerformed(ActionEvent e) {
    if (_configuration == null) {
      MessageHandler.error("Cannot edit icon without a configuration.");
      return;
    }

    // Determine which entity was selected for the action.
    super.actionPerformed(e);

    final NamedObj object = getTarget();

    // Do this as a change request since it may add a new icon.
    ChangeRequest request =
        new ChangeRequest(this, "Edit Custom Icon") {
          protected void _execute() throws Exception {
            EditorIcon icon = null;
            List iconList = object.attributeList(EditorIcon.class);

            if (iconList.size() > 0) {
              // Get the last icon.
              icon = (EditorIcon) iconList.get(iconList.size() - 1);
            }

            if (icon == null) {
              icon = new EditorIcon(object, "_icon");
            } else if (icon instanceof XMLIcon) {
              // There is an icon currently that is not custom.
              // Without trashing the _iconDescription, we can remove
              // this icon and replace it.
              icon.setContainer(null);
              icon = new EditorIcon(object, "_icon");

              // Propagate this to derived objects, being
              // careful to not trash their custom icons
              // if they have them. However, there is a trickiness.
              // They may not have a custom icon, but rather have
              // an instance of XMLIcon. We have to remove that
              // first.
              Iterator derivedObjects = object.getDerivedList().iterator();

              while (derivedObjects.hasNext()) {
                NamedObj derived = (NamedObj) derivedObjects.next();

                // See whether it has an icon.
                EditorIcon derivedIcon = null;
                List derivedIconList = derived.attributeList(EditorIcon.class);

                if (derivedIconList.size() > 0) {
                  // Get the last icon.
                  derivedIcon = (EditorIcon) derivedIconList.get(derivedIconList.size() - 1);
                }

                if (derivedIcon instanceof XMLIcon) {
                  // There is an icon currently that is not custom.
                  // Without trashing the _iconDescription, we can
                  // remove
                  // this icon and replace it.
                  derivedIcon.setContainer(null);
                }
              }

              // Now it is safe to propagate.
              icon.propagateExistence();
            }

            _configuration.openModel(icon);
          }
        };

    object.requestChange(request);
  }