📄 mediator.java
字号:
}
/**
* Saves the current model into current file if exists, otherwise calls saveModelAs()
* Author: Bertoli Marco
*/
public void saveModel() {
if (openedArchive == null) {
saveModelAs();
return;
}
// Updates station positions into data structure
updateStationPositions();
int status = modelLoader.saveModel(model, mainWindow, openedArchive);
switch (status) {
case ModelLoader.SUCCESS:
model.resetSaveState();
break;
case ModelLoader.FAILURE:
showErrorMessage(modelLoader.getFailureMotivation());
break;
}
}
/**
* Saves the current model into a user specified file.
* Author: Bertoli Marco
*/
public void saveModelAs() {
// Updates station positions into data structure
updateStationPositions();
int status = modelLoader.saveModel(model, mainWindow, null);
switch (status) {
case ModelLoader.SUCCESS:
model.resetSaveState();
openedArchive = modelLoader.getSelectedFile();
break;
case ModelLoader.FAILURE:
showErrorMessage(modelLoader.getFailureMotivation());
break;
}
}
/**
* Updates station positions into data structure to reflect the one shown on jgraph
* window. This method is called before saving model.
* Author: Bertoli Marco
*/
public void updateStationPositions() {
Object key;
Object[] cells = graph.getDescendants(graph.getRoots());
for (int i = 0; i < cells.length; i++) {
// Gets the cell object
Object cell = cells[i];
if (cell instanceof JmtCell) {
key = ((CellComponent)((JmtCell) cell).getUserObject()).getKey();
// Sets cell coordinate into data structure
model.setStationPosition(key, getCellCoordinates((JmtCell)cell));
}
}
}
/**
* Uses information retrived from data structure to recreate graph structure.
* This method has to be called after loading a model.
* <br>Author: Bertoli Marco
*/
public void populateGraph() {
Object[] stations = model.getStationKeys().toArray();
HashMap cells = new HashMap();
JmtCell cell;
// Variables for auto-placement. Currently items are placed on a grid... Need to be improved!!!
int count = 0;
int X = 150; // distance on the X axis
int Y = 50; // distance on the Y axis
int X0 = 50;
int Y0 = 15;
int colCount = (graph.getHeight() - 2*Y0) / Y;
// Shows stations
for (int i=0; i<stations.length; i++) {
cell = CellFactory.createStationCell(stations[i]);
Point2D position = model.getStationPosition(stations[i]);
// If position is not present, auto-position this station
// TODO implement a good algorithm for auto-placement... This is silly but avoids exceptions
while (position == null) {
Point tmp = new Point(X0+X*(count / colCount), Y0+Y*(count % colCount));
if (!overlapCells(tmp, cell)) {
position = tmp;
}
count++;
}
InsertCell(position, cell);
cells.put(stations[i], cell);
}
Vector forwardConnections;
// Shows connections
for (int i=0; i<stations.length; i++) {
forwardConnections = model.getForwardConnections(stations[i]);
for (int j=0; j<forwardConnections.size(); j++) {
// Forces connection as it's already present into data structure
connect((JmtCell)cells.get(stations[i]),
(JmtCell)cells.get(forwardConnections.get(j)), true);
}
}
// Now adds blocking regions
Vector regions = model.getRegionKeys();
for (int i=0; i<regions.size(); i++) {
Object key = regions.get(i);
Set regionStation = new HashSet();
Iterator stationKeys = model.getBlockingRegionStations(key).iterator();
while (stationKeys.hasNext())
regionStation.add(cells.get(stationKeys.next()));
// Adds cells to blocking region
addCellsToBlockingRegion(regionStation.toArray(), key);
}
graph.repaint();
}
/**
* @return the system <code>JGraph</code>.
*/
public JGraph getGraph() {
return graph;
}
/**
* Launches the <code>UserClass</code> editor.
*/
public void editUserClasses() {
DialogFactory.getDialog(new jmodelClassesPanel(model, model), "Define customer classes");
}
/**
* Enables or not the <code>UserClass</code> editor function.
*/
public void enableEditUserClasses(boolean state) {
editUserClasses.setEnabled(state);
}
/**
* Searches the cell with the given <i>name</i>.
* @param name A given cell name.
* @return <code>true</code> - if the searched cell will be found.
*/
public boolean existCell(String name) {
int nCells = graph.getModel().getRootCount();
for (int i = 0; i < nCells; i++) {
Object cell = graph.getModel().getRootAt(i);
if (cell instanceof JmtCell) {
// Map attributes = ((JmtCell) cell).getAttributes();
// String cellName = (String) attributes.get("NAME");
String cellName = ((JmtCell) cell).getUserObject().toString();
if (cellName.equals(name))
return true;
}
}
return false;
}
/**
* This function will put selected cells in place avoiding overlapping with other cells
* in graph window
* <br>
* Author: Bertoli Marco
*/
public void putSelectedCellsInGoodPlace() {
Object[] cells = graph.getDescendants(graph.getSelectionCells());
for (int i=0; i<cells.length;i++)
if(cells[i] instanceof JmtCell)
putCellInGoodPlace((JmtCell) cells[i]);
}
/**
* This function will put given cell in place avoiding overlapping with other cells
* in graph window
* <br>
* Author: Bertoli Marco
* @param cell Identifier of the cell to be moved
*/
public void putCellInGoodPlace(JmtCell cell) {
Rectangle bounds = GraphConstants.getBounds(cell.getAttributes()).getBounds();
// Avoids negative starting point
if (bounds.getX() < 0)
bounds.setLocation(0, (int)bounds.getY());
if (bounds.getY() < 0)
bounds.setLocation((int)bounds.getX(), 0);
Object[] overlapping = graph.getDescendants(graph.getRoots(bounds));
Point2D zero = new Point(0,0);
while (overlapping.length > 0) {
// Moves bounds until it doesn't overlap with anything
Point2D last = (Point2D) zero.clone();
for (int j=0; j<overlapping.length; j++) {
// Puts last to last corner of overlapping cells
if (overlapping[j] instanceof JmtCell && overlapping[j] != cell) {
Rectangle2D b = GraphConstants.getBounds(((JmtCell)overlapping[j]).getAttributes());
// Consider only rectangles that intersects with given bound
if (b.intersects(bounds)) {
if (b.getMaxX() > last.getX())
last.setLocation(b.getMaxX(), last.getY());
if (b.getMaxY() > last.getY())
last.setLocation(last.getX(), b.getMaxY());
}
}
}
// if last is still zero, only Blocking section were found overlapping
// so leave everyting as before
if (last.equals(zero))
break;
// Rounds last and moves bounds to found point
bounds.setLocation(new Point((int)(last.getX()+.5),(int)(last.getY()+.5)));
overlapping = graph.getDescendants(graph.getRoots(bounds));
}
// Puts this cell in found position
GraphConstants.setBounds(cell.getAttributes(), bounds);
}
/**
* Retrives the location of the given cell.
* @param cell The given cell
* @return The cell location
*/
public Point2D getCellCoordinates(JmtCell cell) {
Rectangle2D bounds = GraphConstants.getBounds(cell.getAttributes());
return new Point2D.Double(bounds.getMinX(), bounds.getMinY());
}
/**
* Checks whether the given cell overlaps an existing cell with its bounds.
* @param p The point where the given cell will be inserted.
* @param cell The given cell.
* @return <code>true</code> - whether there's an overlapping situation.
*/
public boolean overlapCells(Point2D p, JmtCell cell) {
Map attributes;
// Creates a rectangle representing the new cell bounds and position
Dimension cellsize = cell.getSize(graph);
Rectangle r = new Rectangle2D.Double(p.getX(), p.getY(), cellsize.getWidth(), cellsize.getHeight()).getBounds();
// Gets all cells that can overlap with given one
Object[] cells = graph.getDescendants(graph.getRoots(r));
for (int i = 0; i < cells.length; i++) {
// Gets the i-th cell
Object c = cells[i];
if (c instanceof JmtCell) {
if (!c.equals(cell)) {
// Retrives the i-th cell attributes
attributes = ((JmtCell) c).getAttributes();
// Is there an intersection ?
if (GraphConstants.getBounds(attributes).intersects(r)) {
// Yes
return true;
}
}
}
}
return false;
}
/**
* Checks whether the given region overlaps an existing cell with its bounds.
* This method is used to control overlapping before inserting new cell into the
* Jgraph.
* @param p The point where the given cell will be inserted.
* @param d The dimensions of cell to be inserted
* @return <code>true</code> - whether there's an overlapping situation.
*
* Author: Bertoli Marco
*/
public boolean overlapCells(Point p, Dimension d) {
Rectangle r = new Rectangle(p, d);
return graph.getRoots(r).length > 0;
}
/**
* Generates the xml to send to simulation engine.
*
* Author: Bertoli Marco
*
* Modified by Francesco D'Aquino
*/
public void startSimulation() {
//if simulation is not in pause state
if(!stopSimulation.isEnabled()){
// Asks for confirmation before overwriting previous simulation data
if (model.containsSimulationResults()) {
// Find frame to show confirm dialog
Component parent = mainWindow;
if (resultsWindow != null && resultsWindow.isFocused())
parent = resultsWindow;
int resultValue = JOptionPane.showConfirmDialog(parent,
"This operation will overwrite old simulation results."+
"Continue anyway?",
"JMT - Warning",
JOptionPane.YES_NO_OPTION,
JOptionPane.WARNING_MESSAGE);
if (resultValue == JOptionPane.NO_OPTION) {
return;
}
}
// Correct eventual problems on preloading for closed classes
model.manageJobs();
mc = new ModelChecker(model,model,model, model,false);
pw = new JModelProblemsWindow(mainWindow,mc,this);
if (!mc.isEverythingOkNormal()) {
pw.show();
}
if ( mc.isEverythingOkNormal() || ((!mc.isEverythingOkNormal())&&(pw.continued()))){
if (!model.isParametricAnalysisEnabled()) {
try {
// Removes previous ResultsWindow
if (resultsWindow != null) {
resultsWindow.dispose();
showResults.setEnabled(false);
}
File temp = File.createTempFile("~JModelSimulation",".xml");
temp.deleteOnExit();
XMLWriter.writeXML(temp, model);
// Creates results data structure
model.setSimulationResults(new ResultsModel(model.getPollingInterval()));
showResults.setEnabled(true);
dispatcher = new DispatcherThread(this, model,
(ResultsModel)model.getSimulationResults());
dispatcher.startSimulation(temp);
}
catch (Exception e) {
handleException(e);
}
}
else {
// Removes previous ResultsWindow
showResults.setEnabled(false);
if (resultsWindow != null) {
resultsWindow.dispose();
}
if (progressWindow == null) {
progressWindow = new PAProgressWindow(mainWindow,simulate,pauseSimulation,stopSimulation,model.getParametricAnalysisModel());
}
batchThread = new PADispatcherThread(this,model,progressWindow);
changeSimActionsState(false, true, true);
progressWindow.initialize(model.getParametricAnalysisModel().getNumberOfSteps());
progressWindow.start();
progressWindow.show();
batchThread.start();
}
}
}else{
if (!model.isParametricAnalysisEnabled()) dispatcher.restartSimulation();
else batchThread.restartSimulation();
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -