FlexExample.java 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  1. package exampleAlgorithms;
  2. import java.awt.BorderLayout;
  3. import java.awt.Component;
  4. import java.awt.Dimension;
  5. import java.awt.FlowLayout;
  6. import java.awt.image.BufferedImage;
  7. import java.text.NumberFormat;
  8. import java.util.ArrayList;
  9. import java.util.HashMap;
  10. import java.util.List;
  11. import java.util.concurrent.TimeUnit;
  12. import java.util.stream.Collectors;
  13. import java.util.stream.Stream;
  14. import javax.swing.BorderFactory;
  15. import javax.swing.ImageIcon;
  16. import javax.swing.JButton;
  17. import javax.swing.JCheckBox;
  18. import javax.swing.JFormattedTextField;
  19. import javax.swing.JFrame;
  20. import javax.swing.JLabel;
  21. import javax.swing.JOptionPane;
  22. import javax.swing.JPanel;
  23. import javax.swing.JProgressBar;
  24. import javax.swing.JScrollPane;
  25. import javax.swing.JSplitPane;
  26. import javax.swing.JTextArea;
  27. import javax.swing.text.NumberFormatter;
  28. import api.Algorithm;
  29. import classes.AbstractCpsObject;
  30. import classes.CpsUpperNode;
  31. import classes.HolonElement;
  32. import classes.HolonObject;
  33. import classes.HolonSwitch;
  34. import ui.controller.Control;
  35. import ui.model.DecoratedGroupNode;
  36. import ui.model.Model;
  37. public class FlexExample implements Algorithm {
  38. //Parameter for Algo with default Values:
  39. private boolean closeSwitches = true;
  40. //Settings For GroupNode using and cancel
  41. private boolean useGroupNode = false;
  42. private DecoratedGroupNode dGroupNode = null;
  43. private boolean cancel = false;
  44. //Parameter defined by Algo
  45. private HashMap<Integer, AccessWrapper> access;
  46. private List<Boolean> initialState;
  47. private List<HolonSwitch> switchList;
  48. private List<HolonObject> objectList;
  49. //Gui Part:
  50. private Control control;
  51. private JTextArea textArea;
  52. private JPanel content = new JPanel();
  53. //ProgressBar
  54. private JProgressBar progressBar = new JProgressBar();
  55. private int progressBarCount = 0;
  56. private long startTime;
  57. private Thread runThread;
  58. public static void main(String[] args)
  59. {
  60. JFrame newFrame = new JFrame("exampleWindow");
  61. DemoAlgo instance = new DemoAlgo();
  62. newFrame.setContentPane(instance.getAlgorithmPanel());
  63. newFrame.pack();
  64. newFrame.setVisible(true);
  65. newFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  66. }
  67. public FlexExample() {
  68. content.setLayout(new BorderLayout());
  69. textArea = new JTextArea();
  70. textArea.setEditable(false);
  71. JScrollPane scrollPane = new JScrollPane(textArea);
  72. JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
  73. createOptionPanel() , scrollPane);
  74. splitPane.setResizeWeight(0.0);
  75. content.add(splitPane, BorderLayout.CENTER);
  76. content.setPreferredSize(new Dimension(800,800));
  77. }
  78. public JPanel createOptionPanel() {
  79. JPanel optionPanel = new JPanel(new BorderLayout());
  80. JScrollPane scrollPane = new JScrollPane(createParameterPanel());
  81. scrollPane.setBorder(BorderFactory.createTitledBorder("Parameter"));
  82. optionPanel.add(scrollPane, BorderLayout.CENTER);
  83. optionPanel.add(createButtonPanel(), BorderLayout.PAGE_END);
  84. return optionPanel;
  85. }
  86. private Component createParameterPanel() {
  87. JPanel parameterPanel = new JPanel(null);
  88. parameterPanel.setPreferredSize(new Dimension(510,300));
  89. // JLabel showDiagnosticsLabel = new JLabel("Set all switches closed:");
  90. // showDiagnosticsLabel.setBounds(200, 60, 170, 20);
  91. // parameterPanel.add(showDiagnosticsLabel);
  92. JPanel borderPanel = new JPanel(null);
  93. borderPanel.setBounds(200, 85, 185, 50);
  94. borderPanel.setBorder(BorderFactory.createTitledBorder(""));
  95. parameterPanel.add(borderPanel);
  96. JLabel showGroupNodeLabel = new JLabel("Use Group Node:");
  97. showGroupNodeLabel.setBounds(10, 1, 170, 20);
  98. borderPanel.add(showGroupNodeLabel);
  99. JButton selectGroupNodeButton = new JButton("Select GroupNode");
  100. selectGroupNodeButton.setEnabled(false);
  101. selectGroupNodeButton.setBounds(10, 25, 165, 20);
  102. selectGroupNodeButton.addActionListener(actionEvent -> selectGroupNode());
  103. borderPanel.add(selectGroupNodeButton);
  104. JCheckBox useGroupNodeCheckBox = new JCheckBox();
  105. useGroupNodeCheckBox.setSelected(false);
  106. useGroupNodeCheckBox.setBounds(155, 1, 25, 20);
  107. useGroupNodeCheckBox.addActionListener(actionEvent -> {
  108. useGroupNode = useGroupNodeCheckBox.isSelected();
  109. selectGroupNodeButton.setEnabled(useGroupNode);
  110. });
  111. borderPanel.add(useGroupNodeCheckBox);
  112. NumberFormat format = NumberFormat.getIntegerInstance();
  113. format.setGroupingUsed(false);
  114. format.setParseIntegerOnly(true);
  115. NumberFormatter integerFormatter = new NumberFormatter(format);
  116. integerFormatter.setMinimum(0);
  117. integerFormatter.setCommitsOnValidEdit(true);
  118. JLabel portLabel = new JLabel("between:");
  119. portLabel.setBounds(10, 330, 70, 30);
  120. parameterPanel.add(portLabel);
  121. JLabel afterLabel = new JLabel("after:");
  122. afterLabel.setBounds(10, 360, 70, 30);
  123. parameterPanel.add(afterLabel);
  124. return parameterPanel;
  125. }
  126. public JPanel createButtonPanel() {
  127. JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
  128. JButton cancelButton = new JButton("Cancel Run");
  129. cancelButton.addActionListener(actionEvent -> cancel());
  130. buttonPanel.add(cancelButton);
  131. JButton clearButton = new JButton("Clear Console");
  132. clearButton.addActionListener(actionEvent -> clear());
  133. buttonPanel.add(clearButton);
  134. JButton resetButton = new JButton("Reset");
  135. resetButton.setToolTipText("Resets the State to before the Algorithm has runed.");
  136. resetButton.addActionListener(actionEvent -> reset());
  137. buttonPanel.add(resetButton);
  138. JButton runButton = new JButton("Run");
  139. runButton.addActionListener(actionEvent -> {
  140. Runnable task = () -> run();
  141. runThread = new Thread(task);
  142. runThread.start();
  143. });
  144. buttonPanel.add(runButton);
  145. return buttonPanel;
  146. }
  147. private void cancel() {
  148. if(runThread.isAlive()) {
  149. println("");
  150. println("Cancel run.");
  151. cancel = true;
  152. progressBar.setValue(0);
  153. } else {
  154. println("Nothing to cancel.");
  155. }
  156. }
  157. private void run() {
  158. cancel = false;
  159. disableGuiInput(true);
  160. startTimer();
  161. executeDemoAlgo();
  162. if(cancel) {
  163. reset();
  164. disableGuiInput(false);
  165. return;
  166. }
  167. printElapsedTime();
  168. disableGuiInput(false);
  169. }
  170. private void reset() {
  171. if(initialState != null) {
  172. println("Resetting..");
  173. resetState();
  174. updateVisual();
  175. }else {
  176. println("No run inistialized.");
  177. }
  178. }
  179. private void disableGuiInput(boolean bool) {
  180. control.guiDiable(bool);
  181. }
  182. @Override
  183. public JPanel getAlgorithmPanel() {
  184. return content;
  185. }
  186. @Override
  187. public void setController(Control control) {
  188. this.control = control;
  189. }
  190. private void clear() {
  191. textArea.setText("");
  192. }
  193. private void print(String message) {
  194. textArea.append(message);
  195. }
  196. private void println(String message) {
  197. textArea.append(message + "\n");
  198. }
  199. private void selectGroupNode() {
  200. Object[] possibilities = control.getSimManager().getActualVisualRepresentationalState().getCreatedGroupNodes().values().stream().map(aCps -> new Handle<DecoratedGroupNode>(aCps)).toArray();
  201. @SuppressWarnings("unchecked")
  202. Handle<DecoratedGroupNode> selected = (Handle<DecoratedGroupNode>) JOptionPane.showInputDialog(content, "Select GroupNode:", "GroupNode?", JOptionPane.OK_OPTION,new ImageIcon(new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB)) , possibilities, "");
  203. if(selected != null) {
  204. println("Selected: " + selected);
  205. dGroupNode = selected.object;
  206. }
  207. }
  208. private void progressBarStep(){
  209. progressBar.setValue(++progressBarCount);
  210. }
  211. private void calculateProgressBarParameter() {
  212. int max = 100;
  213. progressBarCount = 0;
  214. progressBar.setValue(0);
  215. progressBar.setMaximum(max);
  216. }
  217. private void startTimer(){
  218. startTime = System.currentTimeMillis();
  219. }
  220. private void printElapsedTime(){
  221. long elapsedMilliSeconds = System.currentTimeMillis() - startTime;
  222. println("Execution Time of Algo in Milliseconds:" + elapsedMilliSeconds);
  223. }
  224. //Algo Part:
  225. private void executeDemoAlgo() {
  226. extractPositionAndAccess();
  227. int actualIteration = control.getModel().getCurIteration();
  228. print("AlgoStart....");
  229. print("AlgoEnde....");
  230. updateVisual();
  231. }
  232. /**
  233. * Method to get the current Position alias a ListOf Booleans for aktive settings on the Objects on the Canvas.
  234. * Also initialize the Access Hashmap to swap faster positions.
  235. * @param model
  236. * @return
  237. */
  238. private List<Boolean> extractPositionAndAccess() {
  239. Model model = control.getModel();
  240. switchList = new ArrayList<HolonSwitch>();
  241. objectList = new ArrayList<HolonObject>();
  242. initialState = new ArrayList<Boolean>();
  243. access= new HashMap<Integer, AccessWrapper>();
  244. rollOutNodes((useGroupNode && (dGroupNode != null))? dGroupNode.getModel().getNodes() :model.getObjectsOnCanvas(), initialState, model.getCurIteration());
  245. return initialState;
  246. }
  247. /**
  248. * Method to extract the Informations recursively out of the Model.
  249. * @param nodes
  250. * @param positionToInit
  251. * @param timeStep
  252. */
  253. private void rollOutNodes(List<AbstractCpsObject> nodes, List<Boolean> positionToInit, int timeStep) {
  254. for(AbstractCpsObject aCps : nodes) {
  255. if (aCps instanceof HolonObject) {
  256. for (HolonElement hE : ((HolonObject) aCps).getElements()) {
  257. positionToInit.add(hE.isActive());
  258. access.put(positionToInit.size() - 1 , new AccessWrapper(hE));
  259. }
  260. objectList.add((HolonObject) aCps);
  261. }
  262. else if (aCps instanceof HolonSwitch) {
  263. HolonSwitch sw = (HolonSwitch) aCps;
  264. positionToInit.add(sw.getState(timeStep));
  265. switchList.add(sw);
  266. access.put(positionToInit.size() - 1 , new AccessWrapper(sw));
  267. }
  268. else if(aCps instanceof CpsUpperNode) {
  269. rollOutNodes(((CpsUpperNode)aCps).getNodes(), positionToInit ,timeStep );
  270. }
  271. }
  272. }
  273. /**
  274. * To let the User See the current state without touching the Canvas.
  275. */
  276. private void updateVisual() {
  277. control.calculateStateAndVisualForCurrentTimeStep();
  278. control.updateCanvas();
  279. control.getGui().triggerUpdateController(null);
  280. }
  281. /**
  282. * Sets the Model back to its original State before the LAST run.
  283. */
  284. private void resetState() {
  285. setState(initialState);
  286. }
  287. /**
  288. * Sets the State out of the given position for calculation or to show the user.
  289. * @param position
  290. */
  291. private void setState(List<Boolean> position) {
  292. for(int i = 0;i<position.size();i++) {
  293. access.get(i).setState(position.get(i));
  294. }
  295. }
  296. private void addObjectToList(List<AbstractCpsObject> listToSearch, List<HolonObject> listToAdd){
  297. for (AbstractCpsObject aCps : listToSearch) {
  298. if (aCps instanceof HolonObject) listToAdd.add((HolonObject) aCps);
  299. else if(aCps instanceof CpsUpperNode) {
  300. addObjectToList(((CpsUpperNode)aCps).getNodes(),listToAdd);
  301. }
  302. }
  303. }
  304. /**
  305. * A Wrapper Class for Access HolonElement and HolonSwitch in one Element and not have to split the List.
  306. */
  307. private class AccessWrapper {
  308. public static final int HOLONELEMENT = 0;
  309. public static final int SWITCH = 1;
  310. private int type;
  311. private HolonSwitch hSwitch;
  312. private HolonElement hElement;
  313. public AccessWrapper(HolonSwitch hSwitch){
  314. type = SWITCH;
  315. this.hSwitch = hSwitch;
  316. }
  317. public AccessWrapper(HolonElement hElement){
  318. type = HOLONELEMENT;
  319. this.hElement = hElement;
  320. }
  321. public void setState(boolean state) {
  322. if(type == HOLONELEMENT) {
  323. hElement.setActive(state);
  324. }else{//is switch
  325. hSwitch.setManualMode(true);
  326. hSwitch.setManualState(state);
  327. }
  328. }
  329. public boolean getState(int timeStep) {
  330. return (type == HOLONELEMENT)?hElement.isActive():hSwitch.getState(timeStep);
  331. }
  332. public int getType() {
  333. return type;
  334. }
  335. }
  336. private class Handle<T>{
  337. public T object;
  338. Handle(T object){
  339. this.object = object;
  340. }
  341. public String toString() {
  342. return object.toString();
  343. }
  344. }
  345. }