GUI.java 105 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326
  1. package ui.view;
  2. import classes.*;
  3. import com.google.gson.JsonNull;
  4. import com.google.gson.JsonObject;
  5. import com.google.gson.JsonParseException;
  6. import interfaces.CategoryListener;
  7. import org.apache.commons.compress.archivers.ArchiveException;
  8. import ui.controller.Control;
  9. import ui.controller.UpdateController;
  10. import ui.model.Model;
  11. import javax.swing.*;
  12. import javax.swing.border.LineBorder;
  13. import javax.swing.filechooser.FileNameExtensionFilter;
  14. import javax.swing.table.DefaultTableModel;
  15. import javax.swing.table.TableCellEditor;
  16. import javax.swing.table.TableCellRenderer;
  17. import javax.swing.tree.DefaultMutableTreeNode;
  18. import javax.swing.tree.DefaultTreeModel;
  19. import javax.swing.tree.TreeCellRenderer;
  20. import java.awt.*;
  21. import java.awt.datatransfer.UnsupportedFlavorException;
  22. import java.awt.event.*;
  23. import java.io.File;
  24. import java.io.IOException;
  25. import java.util.ArrayList;
  26. import java.util.List;
  27. import java.util.Timer;
  28. import java.util.TimerTask;
  29. import java.util.stream.Collectors;
  30. /**
  31. * Graphical User Interface.
  32. *
  33. * @author Gruppe14
  34. */
  35. public class GUI implements CategoryListener {
  36. private final AlgorithmMenu algorithmMenu;
  37. private final JMenuBar menuBar = new JMenuBar();
  38. private final JMenu mnNewMenu = new JMenu("File");
  39. private final JMenu mnNewMenuEdit = new JMenu("Edit");
  40. private final JMenu mnNewMenuOptions = new JMenu("Options");
  41. private final JMenu mnNewMenuView = new JMenu("View");
  42. private final JMenu mnHelp = new JMenu("Help");
  43. private final JCheckBox consoleLogCheckBox = new JCheckBox("Show program console log");
  44. private final JCheckBox useFlexibleDevicesCheckBox = new JCheckBox("Automatically use flexible devices");
  45. private final JMenuItem mntmOpen = new JMenuItem("Open");
  46. private final JMenuItem mntmNew = new JMenuItem("New");
  47. private final JMenuItem mntmSave = new JMenuItem("Save");
  48. private final JMenuItem mntmAboutUs = new JMenuItem("About Us");
  49. private final JMenuItem mntmCanvasSize = new JMenuItem("View Size");
  50. private final JMenuItem mntmBackground = new JMenuItem("Background Image");
  51. private final JMenuItem mntmSplitView = new JMenuItem("Split View");
  52. private final JSplitPane splitPane = new JSplitPane();
  53. private final JSplitPane splitPane1 = new JSplitPane();
  54. private final JSplitPane splitPaneCanvasConsole = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
  55. // the tabbed canvas containing the different sub-net tabs of the grid (Main Grid + Nodes of Nodes)
  56. private final JTabbedPane tabbedPaneInnerOriginal = new JTabbedPane(JTabbedPane.TOP);
  57. // the main canvas where we can see the grid currently displayed
  58. private final JScrollPane canvasSP = new JScrollPane();
  59. private final JScrollPane scrollPane1 = new JScrollPane();
  60. // private final JScrollPane holonSP = new JScrollPane();
  61. // the original tabbed Pane (containing tabs for view, statistics, holon, flexibility)
  62. private final JTabbedPane tabbedPaneOriginal = new JTabbedPane(JTabbedPane.TOP);
  63. // the same tabbed Pane that appears once the view is split
  64. private final JTabbedPane tabbedPaneSplit = new JTabbedPane(JTabbedPane.TOP);
  65. private final JPopupMenu popmenuEdit = new JPopupMenu();
  66. private final JMenuItem editItem = new JMenuItem("Edit Object");
  67. private final StatisticPanel statSplitPane;
  68. private final JScrollPane statScrollPane;
  69. private final JLabel maxGraph = new JLabel("100%");
  70. private final JLabel medGraph = new JLabel("50%");
  71. private final JLabel minGraph = new JLabel("0%");
  72. private final JLabel elementGraph = new JLabel("None ");
  73. private final ArrayList<HolonElement> selectedElements = new ArrayList<>();
  74. private final JTree tree = new JTree();
  75. /******************************************
  76. ************* Right Container*************
  77. ******************************************
  78. * Right Container: here comes the information about the HolonObject, such
  79. * as HolonElements Information, Properties and Consumption/Production
  80. * graph.
  81. **/
  82. private final JSplitPane splitHolonElPro = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
  83. private final JSplitPane splitGraphHolonEl = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
  84. private final int distanceBetweenElementsAndGraph = 350;
  85. // Model for single or multi selection
  86. private final JPanel scrollElements = new JPanel();
  87. private final JScrollPane tableHolonElementScrollPane = new JScrollPane();
  88. // In this section are all the properties that correspond to the clicked
  89. // HolonObject, such as connections, name, Type, etc.
  90. // Table for Properties --> Cell with (0,1) is editable by CpsObjt and
  91. // Cell(3,1) is editable by Edges
  92. private final JTable tableProperties = new JTable() {
  93. private static final long serialVersionUID = 1L;
  94. @Override
  95. public TableCellRenderer getCellRenderer(int row, int column) {
  96. if (getValueAt(row, column) instanceof Boolean) {
  97. return super.getDefaultRenderer(Boolean.class);
  98. } else {
  99. return super.getCellRenderer(row, column);
  100. }
  101. }
  102. @Override
  103. public TableCellEditor getCellEditor(int row, int column) {
  104. if (getValueAt(row, column) instanceof Boolean) {
  105. return super.getDefaultEditor(Boolean.class);
  106. } else {
  107. return super.getCellEditor(row, column);
  108. }
  109. }
  110. };
  111. private final JPanel graphLabel = new JPanel();
  112. private final JScrollPane scrollProperties = new JScrollPane();
  113. // In this section is the graph for the selected HolonElement of the clicked
  114. // HolonObject
  115. private final JTable tableGraph = new JTable();
  116. private final DefaultTableModel tableModelGraph = new DefaultTableModel();
  117. private final JScrollPane scrollGraph = new JScrollPane();
  118. private final Model model;
  119. private final Control controller;
  120. // In this section are all the Holonelements that correspond to the clicked
  121. // HolonObject with consumption/production, name and amount.
  122. private final JPanel panel = new JPanel();
  123. private final JPanel panelHolonEl = new JPanel();
  124. private final JComboBox comboBox = new JComboBox();
  125. // Buttons
  126. private final JButton btnAdd = new JButton("+");
  127. private final JButton btnDel = new JButton("-");
  128. private final JButton btnAddHolEL = new JButton("+");
  129. private final JButton btnDelHolEL = new JButton("-");
  130. private final JButton resetGraphBtn = new JButton("Reset");
  131. private final JToolBar toolBar = new JToolBar();
  132. private final JToolBar toolBarHolonEl = new JToolBar();
  133. private final JToolBar toolBarGraph = new JToolBar();
  134. // Languages
  135. private final JMenuItem englishBtn = new JMenuItem("EN");
  136. private final JMenuItem spanishBtn = new JMenuItem("ES");
  137. private final JMenuItem germanBtn = new JMenuItem("DE");
  138. private final JMenuItem czechBtn = new JMenuItem("CZ");
  139. private final JMenuItem chineseBtn = new JMenuItem("ZH");
  140. // private final JComboBox comboBoxGraph = new JComboBox();
  141. private final Console console = new Console();
  142. private final MyCanvas canvas;
  143. private final HolonCanvas holonCanvas;
  144. private final UnitGraph unitGraph;
  145. private final JSplitPane splitPane3 = new JSplitPane();
  146. private final JSlider sizeSlider = new JSlider();
  147. private final JLabel lblImageSize = new JLabel(Languages.getLanguage()[94]);
  148. private final JMenuItem mntmUndo = new JMenuItem("Undo");
  149. private final JMenuItem mntmRedo = new JMenuItem("Redo");
  150. private final JMenuItem mntmEditEdges = new JMenuItem("Edge Properties");
  151. private final JMenuItem mntmFindReplace = new JMenuItem("Find/ Replace");
  152. private final JMenuItem mntmEditShowedInformation = new JMenuItem("Edit showed Information");
  153. private final JMenuItem mntmResetCategory = new JMenuItem("Reset Categories");
  154. private final JMenu mnLanguage = new JMenu("Language");
  155. private final String[] columnNamesMulti = {"Object", "Nr.", "Device", "Energy", "Flexible Energy Available",
  156. "Quantity", "Activated", "Flexible"};
  157. private final String[] columnNamesSingle = {"Nr.", "Device", "Energy", "Flexible Energy Available", "Quantity",
  158. "Activated", "Flexible"};
  159. private final ArrayList<PropertyTable> tables = new ArrayList<>();
  160. private final String[] comboBoxCat = {"Category", "Object", "Switch"};
  161. private final UpdateController updCon;
  162. private final JSplitPane splitPane_1 = new JSplitPane();
  163. private final JSlider holonBodySizeSlider = new JSlider();
  164. private final JLabel lblHolonBodySize = new JLabel("HolonBody SIze");
  165. private final JLabel lblSelectedElement = new JLabel("Selected Element: ");
  166. // for doubleclick
  167. private boolean click = false;
  168. private JFrame frmCyberPhysical;
  169. private JTabbedPane tabTemp; // tabbedPaneOriginal or tabbedPaneSplit
  170. private JSplitPane tempSplit;
  171. private boolean initSplit = true;
  172. private String catOfObjToBeEdited;
  173. private UpperNodeCanvas unc;
  174. private JPanel contentPane;
  175. private String holonEleNamesDisplayed = "None ";
  176. // Pop up Windows
  177. private AddObjectPopUp addObjectPopUP;
  178. private AboutUsPopUp aboutUsPopUp;
  179. private AddElementPopUp addElementPopUp;
  180. // variables
  181. private boolean dragging = false;
  182. private String actualObjectClicked;
  183. private Image img = null;
  184. private AbstractCpsObject tempCps = null;
  185. private int yValueElements = 0;
  186. // Time Stuff
  187. private TimePanel timePanel;
  188. // Coord for all Cells with text
  189. private int yThis;
  190. private int xThis;
  191. // Coord for all Cells with boolean values (checkbox)
  192. private int yBTis;
  193. private int xBThis;
  194. // Coord for the Edit-Modus in the PropertieTable
  195. private int yProThis;
  196. private int xProThis;
  197. private int yProThisOneClick;
  198. private int xProThisOneClick;
  199. private AbstractCpsObject temp = null;
  200. private String warningText = "Warning";
  201. private String saveBeforeNew = "Do you want to save your current data?";
  202. private String eraseCategory = "Do you really want to delete the Category ";
  203. private String selectObjBeforeErase = "Please select a Category or an Object in order to delete something.";
  204. /**
  205. * Create the application.
  206. *
  207. * @param control the Controller
  208. */
  209. GUI(Control control) {
  210. this.controller = control;
  211. this.model = control.getModel();
  212. statSplitPane = new StatisticPanel(controller);
  213. model.addGraphListener(statSplitPane);
  214. model.setStatPanel(statSplitPane);
  215. statScrollPane = new JScrollPane(statSplitPane);
  216. this.unitGraph = new UnitGraph(model, control);
  217. this.canvas = new MyCanvas(model, control, unitGraph);
  218. this.holonCanvas = new HolonCanvas(model, control);
  219. control.initListener(this);
  220. controller.setCanvas(canvas);
  221. model.setConsole(console);
  222. algorithmMenu = new AlgorithmMenu(model, control);
  223. initialize();
  224. updateCategories(model.getCategories());
  225. updCon = new UpdateController(model, controller);
  226. }
  227. // /**
  228. // * Adds a Popup.
  229. // *
  230. // * @param component Component
  231. // * @param popup PopupMenu
  232. // */
  233. // private static void addPopup(Component component, final JPopupMenu popup) {
  234. // component.addMouseListener(new MouseAdapter() {
  235. // public void mousePressed(MouseEvent e) {
  236. // if (e.isPopupTrigger()) {
  237. // showMenu(e);
  238. // }
  239. // }
  240. //
  241. // public void mouseReleased(MouseEvent e) {
  242. // if (e.isPopupTrigger()) {
  243. // showMenu(e);
  244. // }
  245. // }
  246. //
  247. // private void showMenu(MouseEvent e) {
  248. // popup.show(e.getComponent(), e.getX(), e.getY());
  249. // }
  250. //
  251. // });
  252. // }
  253. /**
  254. * Initialize the contents of the frame.
  255. */
  256. @SuppressWarnings({"serial", "unchecked"})
  257. private void initialize() {
  258. frmCyberPhysical = new JFrame();
  259. frmCyberPhysical.setTitle("Cyber Physical Systems Model");
  260. // try to restore old position/dimensions
  261. ArrayList<Integer> savedWindowDim = controller.loadSavedWindowDimensionsIfExistent();
  262. if (savedWindowDim.size() == 4) {
  263. frmCyberPhysical.setBounds(savedWindowDim.get(0), savedWindowDim.get(1),
  264. savedWindowDim.get(2), savedWindowDim.get(3));
  265. }
  266. // if the upper part of the window is showing, the windows can still be moved,
  267. // but if it is not, we need to move it to somewhere else
  268. if (savedWindowDim.size() != 4 || !isUpperPanelInsideBounds()) {
  269. frmCyberPhysical.setBounds(100, 100, 1000, 800);
  270. frmCyberPhysical.setExtendedState(JFrame.MAXIMIZED_BOTH);
  271. }
  272. frmCyberPhysical.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
  273. frmCyberPhysical.addWindowListener(new java.awt.event.WindowAdapter() {
  274. @Override
  275. public void windowClosing(java.awt.event.WindowEvent windowEvent) {
  276. if (JOptionPane.showConfirmDialog(frmCyberPhysical, Languages.getLanguage()[88],
  277. "Cyber Physical Systems Model", JOptionPane.YES_NO_OPTION,
  278. JOptionPane.QUESTION_MESSAGE) == JOptionPane.YES_OPTION) {
  279. controller.deleteDirectory(new File(System.getProperty("user.home")
  280. + "/.config/HolonGUI/Autosave"));
  281. // try to save the position and size of the window, such that (if possible)
  282. // it can be opened in the same position the next time
  283. try {
  284. controller.savePosAndSizeOfWindow(frmCyberPhysical.getX(), frmCyberPhysical.getY(),
  285. frmCyberPhysical.getWidth(), frmCyberPhysical.getHeight());
  286. } catch (Exception e) {
  287. e.printStackTrace();
  288. }
  289. System.exit(0);
  290. }
  291. }
  292. });
  293. contentPane = (JPanel) frmCyberPhysical.getContentPane();
  294. int condition = JComponent.WHEN_IN_FOCUSED_WINDOW;
  295. InputMap inputMap = contentPane.getInputMap(condition);
  296. ActionMap actionMap = contentPane.getActionMap();
  297. String cntrlZDown = "controlZ";
  298. inputMap.put(KeyStroke.getKeyStroke("control Z"), cntrlZDown);
  299. actionMap.put(cntrlZDown, new AbstractAction() {
  300. private static final long serialVersionUID = 1L;
  301. @Override
  302. public void actionPerformed(ActionEvent e) {
  303. try {
  304. controller.loadAutoSave(controller.getUndoSave());
  305. canvas.repaint();
  306. unitGraph.update(model.getObjectsOnCanvas());
  307. updateUpperNodes();
  308. } catch (IOException eex) {
  309. eex.printStackTrace();
  310. }
  311. }
  312. });
  313. String cntrlYDown = "controlY";
  314. inputMap.put(KeyStroke.getKeyStroke("control Y"), cntrlYDown);
  315. actionMap.put(cntrlYDown, new AbstractAction() {
  316. private static final long serialVersionUID = 1L;
  317. @Override
  318. public void actionPerformed(ActionEvent e) {
  319. try {
  320. controller.loadAutoSave(controller.getRedoSave());
  321. canvas.repaint();
  322. unitGraph.update(model.getObjectsOnCanvas());
  323. updateUpperNodes();
  324. } catch (IOException ex) {
  325. ex.printStackTrace();
  326. }
  327. }
  328. });
  329. String cntrlADown = "controlA";
  330. inputMap.put(KeyStroke.getKeyStroke("control A"), cntrlADown);
  331. AbstractAction controlA = new AbstractAction() {
  332. private static final long serialVersionUID = 1L;
  333. @Override
  334. public void actionPerformed(ActionEvent e) {
  335. chooseTabTemp();
  336. model.getSelectedCpsObjects().clear();
  337. // Uppernode Canvas?
  338. JScrollPane scrollPane = getScrollPaneFromTabbedPane();
  339. Component canvasOrUpperNodeCanvas = scrollPane.getViewport().getComponent(0);
  340. if (canvasOrUpperNodeCanvas instanceof UpperNodeCanvas) {
  341. UpperNodeCanvas uNC = (UpperNodeCanvas) canvasOrUpperNodeCanvas;
  342. for (AbstractCpsObject cps : uNC.upperNode.getNodes()) {
  343. controller.addSelectedObject(cps);
  344. }
  345. uNC.repaint();
  346. // or Canvas?
  347. } else if (canvasOrUpperNodeCanvas instanceof MyCanvas) {
  348. for (AbstractCpsObject cps : model.getObjectsOnCanvas()) {
  349. controller.addSelectedObject(cps);
  350. }
  351. canvas.repaint();
  352. }
  353. controller.getObjectsInDepth();
  354. }
  355. };
  356. actionMap.put(cntrlADown, controlA);
  357. String delDown = "delete";
  358. inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0, false), delDown);
  359. actionMap.put(delDown, new AbstractAction() {
  360. private static final long serialVersionUID = 1L;
  361. @Override
  362. public void actionPerformed(ActionEvent e) {
  363. chooseTabTemp();
  364. // Uppernode Canvas?
  365. JScrollPane scrollPane = getScrollPaneFromTabbedPane();
  366. Component canvasOrUpperNodeCanvas = scrollPane.getViewport().getComponent(0);
  367. // check whether a producer was deleted (this triggers a complete re-evaluation of the net)
  368. boolean wasProducerDeleted = false;
  369. if (canvasOrUpperNodeCanvas instanceof UpperNodeCanvas) {
  370. UpperNodeCanvas uNC = (UpperNodeCanvas) canvasOrUpperNodeCanvas;
  371. for (AbstractCpsObject cps : model.getSelectedCpsObjects()) {
  372. if (cps instanceof HolonObject
  373. && ((HolonObject) cps).getState() == HolonObject.PRODUCER) {
  374. wasProducerDeleted = true;
  375. }
  376. controller.removeTrackingObj(cps);
  377. if (uNC.upperNode.getNodes().contains(cps)) {
  378. controller.delObjUpperNode(cps, uNC.upperNode);
  379. unc.setToolTip(false);
  380. // remove UpperNodeTab if UpperNode deleted
  381. removeUpperNodeTab(cps);
  382. }
  383. }
  384. uNC.repaint();
  385. // or Canvas?
  386. } else if (canvasOrUpperNodeCanvas instanceof MyCanvas) {
  387. boolean save = false;
  388. for (int j = 0; j < model.getSelectedCpsObjects().size(); j++) {
  389. AbstractCpsObject cps = model.getSelectedCpsObjects().get(j);
  390. if (cps instanceof HolonObject
  391. && ((HolonObject) cps).getState() == HolonObject.PRODUCER) {
  392. wasProducerDeleted = true;
  393. }
  394. controller.removeTrackingObj(cps);
  395. if (j < model.getSelectedCpsObjects().size() - 1)
  396. save = true;
  397. controller.delCanvasObject(cps, save);
  398. canvas.setToolTip(false);
  399. // remove UpperNodeTab if UpperNode deleted
  400. removeUpperNodeTab(cps);
  401. }
  402. canvas.repaint();
  403. }
  404. // recalculate net if a producer was deleted
  405. if (wasProducerDeleted) {
  406. controller.resetSimulation();
  407. controller.calculateStateForCurrentTimeStep();
  408. }
  409. model.getSelectedCpsObjects().clear();
  410. hideScrollGraph();
  411. }
  412. });
  413. String cntrlFDown = "controlF";
  414. inputMap.put(KeyStroke.getKeyStroke("control F"), cntrlFDown);
  415. actionMap.put(cntrlFDown, new AbstractAction() {
  416. private static final long serialVersionUID = 1L;
  417. @Override
  418. public void actionPerformed(ActionEvent e) {
  419. SearchPopUp dialog = new SearchPopUp(controller, canvas, frmCyberPhysical);
  420. dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
  421. dialog.setVisible(true);
  422. }
  423. });
  424. String cntrlCDown = "controlC";
  425. inputMap.put(KeyStroke.getKeyStroke("control C"), cntrlCDown);
  426. AbstractAction controlC = new AbstractAction() {
  427. private static final long serialVersionUID = 1L;
  428. @Override
  429. public void actionPerformed(ActionEvent e) {
  430. chooseTabTemp();
  431. JScrollPane scrollPane = getScrollPaneFromTabbedPane();
  432. if (!model.getSelectedCpsObjects().isEmpty()) {
  433. if (scrollPane.getViewport().getComponent(0) instanceof UpperNodeCanvas)
  434. controller.copy(((UpperNodeCanvas) scrollPane.getViewport().getComponent(0)).upperNode);
  435. else
  436. controller.copy(null);
  437. if (!model.getClipboradObjects().isEmpty()) {
  438. canvas.itemPaste.setEnabled(true);
  439. }
  440. }
  441. }
  442. };
  443. actionMap.put(cntrlCDown, controlC);
  444. String cntrlVDown = "controlV";
  445. inputMap.put(KeyStroke.getKeyStroke("control V"), cntrlVDown);
  446. AbstractAction controlV = new AbstractAction() {
  447. private static final long serialVersionUID = 1L;
  448. @Override
  449. public void actionPerformed(ActionEvent e) {
  450. try {
  451. tabTemp = null;
  452. if (tabbedPaneOriginal.getMousePosition() != null) {
  453. tabTemp = tabbedPaneOriginal;
  454. } else {
  455. if (!initSplit) {
  456. tabTemp = tabbedPaneSplit;
  457. }
  458. }
  459. JScrollPane scrollPane = getScrollPaneFromTabbedPane();
  460. Component canvasOrUpperNodeCanvas = scrollPane.getViewport().getComponent(0);
  461. if (tabTemp != null && canvasOrUpperNodeCanvas instanceof UpperNodeCanvas) {
  462. controller.paste(
  463. ((UpperNodeCanvas) canvasOrUpperNodeCanvas).upperNode,
  464. canvasOrUpperNodeCanvas.getMousePosition());
  465. unitGraph.update(model.getSelectedCpsObjects());
  466. scrollPane.getViewport().getComponent(0).repaint();
  467. } else {
  468. controller.paste(null, canvas.getMousePosition());
  469. unitGraph.update(model.getSelectedCpsObjects());
  470. canvas.repaint();
  471. }
  472. } catch (HeadlessException | JsonParseException | UnsupportedFlavorException | IOException e1) {
  473. JLabel message = new JLabel("The Clipboard information cannot be pasted into Application.");
  474. JOptionPane.showMessageDialog(null, message, "", JOptionPane.ERROR_MESSAGE);
  475. }
  476. }
  477. };
  478. actionMap.put(cntrlVDown, controlV);
  479. String cntrlXDown = "controlX";
  480. inputMap.put(KeyStroke.getKeyStroke("control X"), cntrlXDown);
  481. AbstractAction controlX = new AbstractAction() {
  482. private static final long serialVersionUID = 1L;
  483. @Override
  484. public void actionPerformed(ActionEvent e) {
  485. chooseTabTemp();
  486. JScrollPane scrollPane = getScrollPaneFromTabbedPane();
  487. if (!model.getSelectedCpsObjects().isEmpty()) {
  488. if (scrollPane.getViewport().getComponent(0) instanceof UpperNodeCanvas) {
  489. controller.cut(((UpperNodeCanvas) scrollPane.getViewport().getComponent(0)).upperNode);
  490. } else {
  491. controller.cut(null);
  492. }
  493. if (!model.getClipboradObjects().isEmpty()) {
  494. canvas.itemPaste.setEnabled(true);
  495. }
  496. canvas.repaint();
  497. }
  498. }
  499. };
  500. actionMap.put(cntrlXDown, controlX);
  501. frmCyberPhysical.setJMenuBar(menuBar);
  502. frmCyberPhysical.setIconImage(new ImageIcon(this.getClass().getResource("/Images/Dummy_House.png")).getImage()
  503. .getScaledInstance(30, 30, Image.SCALE_SMOOTH));
  504. menuBar.add(mnNewMenu);
  505. mnNewMenu.add(mntmNew);
  506. mnNewMenu.add(mntmOpen);
  507. mnNewMenu.add(mntmSave);
  508. menuBar.add(mnNewMenuEdit);
  509. mnNewMenuEdit.add(mntmUndo);
  510. mnNewMenuEdit.add(mntmRedo);
  511. mnLanguage.add(englishBtn);
  512. englishBtn.setIcon(new ImageIcon(new ImageIcon("res/Button_Images/FlagEN.png").getImage().getScaledInstance(20,
  513. 20, java.awt.Image.SCALE_SMOOTH)));
  514. mnLanguage.add(spanishBtn);
  515. spanishBtn.setIcon(new ImageIcon(new ImageIcon("res/Button_Images/FlagES.png").getImage().getScaledInstance(20,
  516. 20, java.awt.Image.SCALE_SMOOTH)));
  517. mnLanguage.add(germanBtn);
  518. germanBtn.setIcon(new ImageIcon(new ImageIcon("res/Button_Images/FlagDE.png").getImage().getScaledInstance(20,
  519. 20, java.awt.Image.SCALE_SMOOTH)));
  520. // mnLanguage.add(czechBtn);
  521. // czechBtn.setIcon(new ImageIcon(new
  522. // ImageIcon("res/Button_Images/FlagCZ.png").getImage().getScaledInstance(20,
  523. // 20, java.awt.Image.SCALE_SMOOTH)));
  524. mnLanguage.add(chineseBtn);
  525. chineseBtn.setIcon(new ImageIcon(new ImageIcon("res/Button_Images/FlagZH.png").getImage().getScaledInstance(20,
  526. 20, java.awt.Image.SCALE_SMOOTH)));
  527. mntmFindReplace.addActionListener(actionEvent -> {
  528. try {
  529. SearchPopUp dialog = new SearchPopUp(controller, canvas, frmCyberPhysical);
  530. dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
  531. dialog.setVisible(true);
  532. controller.getObjectsInDepth();
  533. } catch (Exception ex) {
  534. ex.printStackTrace();
  535. }
  536. });
  537. mnNewMenuEdit.add(mntmFindReplace);
  538. mntmEditShowedInformation.addActionListener(actionEvent -> {
  539. try {
  540. DisplayedInformationPopUp dialog = new DisplayedInformationPopUp(canvas, contentPane, controller);
  541. dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
  542. dialog.setVisible(true);
  543. } catch (Exception ex) {
  544. ex.printStackTrace();
  545. }
  546. });
  547. mnNewMenuEdit.add(mntmEditShowedInformation);
  548. mnNewMenuEdit.add(mntmEditEdges);
  549. mntmEditEdges.addActionListener(actionEvent -> {
  550. EditEdgesPopUp edgePopUp = new EditEdgesPopUp(frmCyberPhysical);
  551. edgePopUp.setCanvas(canvas);
  552. edgePopUp.setController(controller);
  553. edgePopUp.setVisible(true);
  554. });
  555. menuBar.add(mnNewMenuOptions);
  556. mnNewMenuOptions.add(mntmResetCategory);
  557. mntmResetCategory.addActionListener(actionEvent -> {
  558. ArrayList<Category> cat = model.getCategories();
  559. try {
  560. while (!cat.isEmpty()) {
  561. controller.deleteCategory(cat.get(0).getName());
  562. }
  563. controller.resetCategorys();
  564. } catch (Exception e2) {
  565. }
  566. tree.repaint();
  567. });
  568. mnNewMenuOptions.add(consoleLogCheckBox);
  569. consoleLogCheckBox.setSelected(true);
  570. consoleLogCheckBox.addActionListener(arg0 -> controller.setShowConsoleLog(consoleLogCheckBox.isSelected()));
  571. mnNewMenuOptions.add(useFlexibleDevicesCheckBox);
  572. useFlexibleDevicesCheckBox.setSelected(true);
  573. useFlexibleDevicesCheckBox.addActionListener(
  574. actionEvent -> model.setUseFlexibleDevices(useFlexibleDevicesCheckBox.isSelected()));
  575. menuBar.add(mnNewMenuView);
  576. mnNewMenuView.add(mntmCanvasSize);
  577. mntmCanvasSize.addActionListener(actionEvent -> {
  578. CanvasResizePopUp popUp = new CanvasResizePopUp(model, controller, canvas, tabbedPaneOriginal, tabbedPaneSplit, frmCyberPhysical);
  579. popUp.setVisible(true);
  580. });
  581. mnNewMenuView.add(splitPane3);
  582. sizeSlider.setMinimum(15);
  583. sizeSlider.setMaximum(115);
  584. sizeSlider.addChangeListener(changeEvent -> {
  585. controller.setScale(sizeSlider.getValue());
  586. JScrollPane scrollPane = getScrollPaneFromTabbedPane();
  587. if (scrollPane.getViewport()
  588. .getComponent(0) instanceof UpperNodeCanvas) {
  589. scrollPane.getViewport().getComponent(0).repaint();
  590. } else {
  591. canvas.repaint();
  592. }
  593. if (!initSplit && scrollPane.getViewport().getComponent(0) instanceof UpperNodeCanvas) {
  594. scrollPane.getViewport().getComponent(0).repaint();
  595. } else {
  596. canvas.repaint();
  597. }
  598. });
  599. mnNewMenuView.add(mntmCanvasSize);
  600. mnNewMenuView.add(mntmSplitView);
  601. // Split View
  602. mntmSplitView.addActionListener(actionEvent -> {
  603. if (splitPaneCanvasConsole.getLeftComponent() instanceof JSplitPane) {
  604. initSplit = true;
  605. Component tempC = tabbedPaneSplit.getSelectedComponent();
  606. tabbedPaneOriginal.setComponentAt(tabbedPaneSplit.getSelectedIndex(), tempC);
  607. tabbedPaneSplit.removeAll();
  608. splitPaneCanvasConsole.setLeftComponent(tabbedPaneOriginal);
  609. } else {
  610. for (int i = 0; i < tabbedPaneOriginal.getTabCount(); i++) {
  611. // add outer tabs
  612. // (inner tabs are added by tabbedPaneSplit changelistener)
  613. tabbedPaneSplit.addTab(tabbedPaneOriginal.getTitleAt(i), null);
  614. }
  615. if (tabbedPaneOriginal.getSelectedComponent() == statScrollPane) {
  616. tabbedPaneOriginal.setComponentAt(0, null);
  617. tabbedPaneSplit.setComponentAt(0, canvasSP);
  618. tabbedPaneSplit.setSelectedIndex(0);
  619. } else {
  620. tabbedPaneOriginal.setComponentAt(1, null);
  621. tabbedPaneSplit.setComponentAt(1, statScrollPane);
  622. tabbedPaneSplit.setSelectedIndex(1);
  623. }
  624. tempSplit = new JSplitPane();
  625. tempSplit.setBorder(null);
  626. tempSplit.setRightComponent(tabbedPaneSplit);
  627. tempSplit.setLeftComponent(tabbedPaneOriginal);
  628. tempSplit.setDividerLocation(tabbedPaneOriginal.getWidth() / 2);
  629. tempSplit.setResizeWeight(0.9);
  630. splitPaneCanvasConsole.setLeftComponent(tempSplit);
  631. initSplit = false;
  632. }
  633. contentPane.updateUI();
  634. });
  635. mnNewMenuView.add(mntmBackground);
  636. mntmBackground.addActionListener(actionEvent -> {
  637. tabTemp = tabbedPaneOriginal;
  638. JScrollPane scrollPane = getScrollPaneFromTabbedPane();
  639. if (scrollPane.getViewport().getComponent(0) instanceof MyCanvas) {
  640. BackgroundPopUp backgroundDialog = new BackgroundPopUp(model, controller, canvas, null, frmCyberPhysical);
  641. backgroundDialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
  642. backgroundDialog.setVisible(true);
  643. } else if (scrollPane.getViewport().getComponent(0) instanceof UpperNodeCanvas) {
  644. UpperNodeCanvas uNodeCanvas = (UpperNodeCanvas) (scrollPane.getViewport().getComponent(0));
  645. BackgroundPopUp backgroundDialog = new BackgroundPopUp(model, controller, null,
  646. uNodeCanvas.upperNode, frmCyberPhysical);
  647. backgroundDialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
  648. backgroundDialog.setVisible(true);
  649. uNodeCanvas.repaint();
  650. }
  651. });
  652. splitPane3.setRightComponent(sizeSlider);
  653. splitPane3.setLeftComponent(lblImageSize);
  654. mnNewMenuView.add(splitPane_1);
  655. holonBodySizeSlider.setValue(100);
  656. holonBodySizeSlider.setMinimum(1);
  657. holonBodySizeSlider.addChangeListener(changeEvent -> {
  658. controller.setHolonBodyScale(holonBodySizeSlider.getValue());
  659. tree.setRowHeight(50);
  660. canvas.repaint();
  661. });
  662. splitPane_1.setRightComponent(holonBodySizeSlider);
  663. splitPane_1.setLeftComponent(lblHolonBodySize);
  664. menuBar.add(algorithmMenu);
  665. menuBar.add(mnHelp);
  666. mnHelp.add(mntmAboutUs);
  667. tabbedPaneOriginal.addChangeListener(changeEvent -> {
  668. if (tabbedPaneOriginal.getSelectedComponent() == null) {
  669. Component tempC = tabbedPaneSplit.getSelectedComponent();
  670. tabbedPaneSplit.setComponentAt(tabbedPaneOriginal.getSelectedIndex(), null);
  671. tabbedPaneOriginal.setComponentAt(tabbedPaneOriginal.getSelectedIndex(), tempC);
  672. tempC = tabbedPaneOriginal.getComponentAt((tabbedPaneOriginal.getSelectedIndex() + 1) % (tabbedPaneOriginal.getTabCount()));
  673. tabbedPaneOriginal.setComponentAt((tabbedPaneOriginal.getSelectedIndex() + 1) % (tabbedPaneOriginal.getTabCount()), null);
  674. tabbedPaneSplit.setComponentAt((tabbedPaneOriginal.getSelectedIndex() + 1) % (tabbedPaneOriginal.getTabCount()), tempC);
  675. tabbedPaneSplit.setSelectedIndex((tabbedPaneOriginal.getSelectedIndex() + 1) % (tabbedPaneOriginal.getTabCount()));
  676. contentPane.updateUI();
  677. }
  678. });
  679. tabbedPaneSplit.addChangeListener(changeEvent -> {
  680. if (tabbedPaneSplit.getSelectedComponent() == null && !initSplit) {
  681. Component tempC = tabbedPaneOriginal.getComponentAt(tabbedPaneSplit.getSelectedIndex());
  682. tabbedPaneOriginal.setComponentAt(tabbedPaneSplit.getSelectedIndex(), null);
  683. tabbedPaneSplit.setComponentAt(tabbedPaneSplit.getSelectedIndex(), tempC);
  684. for (int i = 0; i < tabbedPaneOriginal.getTabCount(); i++) {
  685. if (tabbedPaneSplit.getComponentAt(i) != null && tabbedPaneSplit.getComponentAt(i) != tempC) {
  686. tempC = tabbedPaneSplit.getComponentAt(i);
  687. tabbedPaneSplit.setComponentAt(i, null);
  688. tabbedPaneOriginal.setComponentAt(i, tempC);
  689. break;
  690. }
  691. }
  692. if (tabbedPaneOriginal.getSelectedIndex() == tabbedPaneSplit.getSelectedIndex()) {
  693. tabbedPaneOriginal.setSelectedIndex((tabbedPaneSplit.getSelectedIndex() + 1) % tabbedPaneOriginal.getTabCount());
  694. }
  695. contentPane.updateUI();
  696. }
  697. });
  698. mnNewMenuOptions.add(mnLanguage);
  699. canvas.setBackground(Color.WHITE);
  700. canvas.setPreferredSize(new Dimension(model.getCanvasX(), model.getCanvasY()));
  701. holonCanvas.setBackground(Color.WHITE);
  702. holonCanvas.setPreferredSize(new Dimension(model.getCanvasX(), model.getCanvasY()));
  703. /********************
  704. * RIGHT CONTAINER (INFORMATION)
  705. **********************/
  706. // Set up of the HolonElements section
  707. // Two different Models: Multi for multi-selection mode and Single for
  708. // single-selection mode (CPS-Object)
  709. model.getMultiTable().setColumnIdentifiers(columnNamesMulti);
  710. model.getSingleTable().setColumnIdentifiers(columnNamesSingle);
  711. model.getTableHolonElement().setBorder(null);
  712. model.getTableHolonElement().setFillsViewportHeight(true);
  713. model.getTableHolonElement().setCellSelectionEnabled(true);
  714. model.getTableHolonElement().setColumnSelectionAllowed(true);
  715. tableHolonElementScrollPane.setViewportView(model.getTableHolonElement());
  716. scrollElements.setLayout(new BorderLayout(0, 0));
  717. scrollElements.add(panelHolonEl, BorderLayout.NORTH);
  718. scrollElements.add(tableHolonElementScrollPane);
  719. panelHolonEl.setLayout(new BoxLayout(panelHolonEl, BoxLayout.X_AXIS));
  720. toolBarHolonEl.add(btnAddHolEL);
  721. toolBarHolonEl.add(btnDelHolEL);
  722. toolBarHolonEl.setFloatable(false);
  723. panelHolonEl.add(toolBarHolonEl);
  724. // Set up of the Properties section
  725. tableProperties.setModel(model.getPropertyTable());
  726. tableProperties.setFillsViewportHeight(true);
  727. tableProperties.setCellSelectionEnabled(true);
  728. tableProperties.setColumnSelectionAllowed(true);
  729. scrollProperties.setViewportView(tableProperties);
  730. // Set up of the Graph section
  731. tableGraph.setModel(tableModelGraph);
  732. tableGraph.setFillsViewportHeight(true);
  733. tableGraph.setCellSelectionEnabled(true);
  734. tableGraph.setColumnSelectionAllowed(true);
  735. scrollGraph.setViewportView(unitGraph);
  736. graphLabel.setLayout(new BorderLayout(0, 10));
  737. graphLabel.add(maxGraph, BorderLayout.NORTH);
  738. graphLabel.add(medGraph, BorderLayout.CENTER);
  739. graphLabel.add(minGraph, BorderLayout.SOUTH);
  740. toolBarGraph.add(lblSelectedElement);
  741. toolBarGraph.add(elementGraph);
  742. Component horizontalStrut = Box.createHorizontalStrut(toolBarGraph.getWidth() - resetGraphBtn.getWidth());
  743. toolBarGraph.add(horizontalStrut);
  744. resetGraphBtn.setHorizontalAlignment(SwingConstants.RIGHT);
  745. toolBarGraph.add(resetGraphBtn);
  746. toolBarGraph.setFloatable(false);
  747. scrollGraph.setRowHeaderView(graphLabel);
  748. scrollGraph.setColumnHeaderView(toolBarGraph);
  749. tables.add(model.getSingleTable());
  750. tables.add(model.getMultiTable());
  751. /***********************
  752. * HolonElement Table Actions
  753. **********************/
  754. /*
  755. * Add HolonElement to given HolonObject
  756. */
  757. btnAddHolEL.addActionListener(actionEvent -> {
  758. if (model.getSelectedCpsObjects().size() == 1) {
  759. AbstractCpsObject tempCpsObject = updCon.getActualCps();
  760. if (tempCpsObject != null && tempCpsObject.getClass() == HolonObject.class
  761. && tempCpsObject.getId() != 0) {
  762. addElementPopUp = new AddElementPopUp(frmCyberPhysical);
  763. addElementPopUp.setActualCps(updCon.getActualCps());
  764. addElementPopUp.setVisible(true);
  765. HolonElement ele = addElementPopUp.getElement();
  766. if (ele != null) {
  767. controller.addElementCanvasObject(tempCpsObject.getId(), ele.getEleName(), ele.getAmount(),
  768. ele.getEnergyPerElement(), ele.getId());
  769. }
  770. controller.calculateStateForTimeStep(model.getCurIteration());
  771. triggerUpdateController(null);
  772. contentPane.updateUI();
  773. }
  774. }
  775. });
  776. /*
  777. * Delete the chosen HolonElement of the selected HolonObject,
  778. * Multi-Selection for CpsObjects as well as for HolonElements possible
  779. */
  780. btnDelHolEL.addActionListener(actionEvent -> {
  781. // For Single Selection of CpsObject
  782. if (model.getSelectedCpsObjects().size() == 1) {
  783. if (updCon.getActualCps().getClass() == HolonObject.class) {
  784. HolonObject obj = (HolonObject) updCon.getActualCps();
  785. for (HolonElement e : selectedElements) {
  786. controller.deleteElementCanvas(obj.getId(), e.getId());
  787. controller.calculateStateForTimeStep(model.getCurIteration());
  788. triggerUpdateController(null);
  789. contentPane.updateUI();
  790. // Names displayed in graph are not updated
  791. }
  792. model.getEleToDelete().clear();
  793. selectedElements.clear();
  794. }
  795. // For MultiSelection of CpsObject
  796. } else if (model.getSelectedCpsObjects().size() > 1) {
  797. for (Integer i : model.getEleToDelete().keySet()) {
  798. for (HolonElement e : model.getEleToDelete().get(i)) {
  799. controller.deleteElementCanvas(i, e.getId());
  800. }
  801. }
  802. triggerUpdateController(null);
  803. model.getEleToDelete().clear();
  804. selectedElements.clear();
  805. }
  806. triggerUpdateController(null);
  807. elementGraph.setText(Languages.getLanguage()[25]);
  808. holonEleNamesDisplayed = Languages.getLanguage()[25];
  809. });
  810. /*
  811. * Communication between HolonElement Table and displayed Graph and
  812. * Properties, as well as selection of different HolonElements
  813. */
  814. model.getTableHolonElement().addMouseListener(new MouseAdapter() {
  815. public void mousePressed(MouseEvent e) {
  816. HolonObject obj = null;
  817. if (model.getSelectedCpsObjects().size() == 1
  818. && model.getSelectedCpsObjects().get(0) instanceof HolonObject) {
  819. obj = (HolonObject) updCon.getActualCps();
  820. }
  821. yValueElements = e.getY();
  822. HolonElement ele;
  823. // Search for current clicked HolonElement
  824. if (model.getSelectedCpsObjects().size() == 1) {
  825. ele = updCon.getActualHolonElement(obj, yValueElements, 0, tables);
  826. } else {
  827. ele = updCon.getActualHolonElement(null, yValueElements, 0, tables);
  828. }
  829. // Multi-Selection of HolonElements through control button +
  830. // mouse click
  831. if (ele != null) {
  832. // make energy-consumption graph visible
  833. showScrollGraph();
  834. if (e.isControlDown()) {
  835. if (!selectedElements.contains(ele)) {
  836. selectedElements.add(ele);
  837. if (!holonEleNamesDisplayed.equals(Languages.getLanguage()[25])) {
  838. holonEleNamesDisplayed = holonEleNamesDisplayed + "; " + ele.getEleName() + " ";
  839. } else {
  840. holonEleNamesDisplayed = ele.getEleName() + " ";
  841. }
  842. unitGraph.repaintWithNewElement(selectedElements);
  843. }
  844. updCon.getActualHolonElement(null, yValueElements, 2, tables);
  845. }
  846. // if no control-button pressed but a HolonElement chosen
  847. else {
  848. selectedElements.clear();
  849. selectedElements.add(ele);
  850. updCon.getActualHolonElement(null, yValueElements, 1, tables);
  851. holonEleNamesDisplayed = ele.getEleName() + " ";
  852. unitGraph.repaintWithNewElement(selectedElements);
  853. }
  854. } else {
  855. elementGraph.setText(Languages.getLanguage()[25]);
  856. hideScrollGraph();
  857. }
  858. // if any HolonElement is double-clicked --> Edit-Mode started
  859. // for selected HolonElement
  860. if (e.getClickCount() == 2) {
  861. yThis = e.getY();
  862. xThis = e.getX();
  863. }
  864. // for single click and empty slot
  865. if (e.getClickCount() == 1 && ele == null) {
  866. selectedElements.clear();
  867. holonEleNamesDisplayed = Languages.getLanguage()[25];
  868. }
  869. elementGraph.setText(holonEleNamesDisplayed);
  870. yBTis = e.getY();
  871. xBThis = e.getX();
  872. }
  873. });
  874. /*
  875. * Triggered every time a change is made
  876. */
  877. model.getTableHolonElement().addPropertyChangeListener(propertyChangeEvent -> {
  878. try {
  879. int yMouse = yThis;
  880. int yBMouse = yBTis;
  881. int selectedValueY = (int) Math.floor(yMouse / 16);
  882. int selectedValueBY = (int) Math.floor(yBMouse / 16);
  883. // ------------------ multi-selection mode ------------------
  884. if (model.getSelectedCpsObjects().size() > 1) {
  885. int selectedValueX = (int) Math.floor(xThis / (model.getTableHolonElement().getWidth() / 8));
  886. int selectedValueBX = (int) Math.floor(xBThis / (model.getTableHolonElement().getWidth() / 8));
  887. if (updCon.getHolonObj(yMouse, model.getMultiTable()) != null) {
  888. // For active column (boolean with a checkbox)
  889. if (selectedValueBX == 6) {
  890. HolonElement eleBTemp = updCon.getActualHolonElement(null, yBMouse, 0, tables);
  891. String newBStuff = model.getMultiTable().getValueAt(selectedValueBY, selectedValueBX)
  892. .toString();
  893. Boolean bTemp = Boolean.parseBoolean(newBStuff);
  894. eleBTemp.setActive(bTemp);
  895. }
  896. // For activeFlex column (boolean with a checkbox)
  897. else if (selectedValueBX == 7) {
  898. HolonElement eleBTemp = updCon.getActualHolonElement(null, yBMouse, 0, tables);
  899. String newBStuff = model.getMultiTable().getValueAt(selectedValueBY, selectedValueBX)
  900. .toString();
  901. Boolean bTemp = Boolean.parseBoolean(newBStuff);
  902. eleBTemp.setFlexible(bTemp);
  903. } else {
  904. // Update of HolonElement
  905. HolonElement eleTemp = updCon.getActualHolonElement(null, yMouse, 0, tables);
  906. String newStuff = model.getMultiTable().getValueAt(selectedValueY, selectedValueX)
  907. .toString();
  908. // Name update
  909. if (selectedValueX == 2) {
  910. eleTemp.setEleName(newStuff);
  911. }
  912. // Energy Update
  913. else if (selectedValueX == 3) {
  914. Float ftemp = Float.parseFloat(newStuff);
  915. eleTemp.setEnergyPerElement(ftemp);
  916. }
  917. // Flexibility
  918. else if (selectedValueX == 4) {
  919. Float ftemp = Float.parseFloat(newStuff);
  920. eleTemp.setFlexibleEnergyAvailable(ftemp);
  921. }
  922. // Amount of Elements update
  923. else if (selectedValueX == 5) {
  924. Integer iTemp = Integer.parseInt(newStuff);
  925. eleTemp.setAmount(iTemp);
  926. }
  927. }
  928. }
  929. } // ------------------ single-selection mode ------------------
  930. else if (model.getSelectedCpsObjects().size() == 1) {
  931. int selectedValueX = (int) Math.floor(xThis / (model.getTableHolonElement().getWidth() / 7));
  932. int selectedValueBX = (int) Math.floor(xBThis / (model.getTableHolonElement().getWidth() / 7));
  933. if (updCon.getActualCps() != null && updCon.getActualCps().getClass() == HolonObject.class) {
  934. HolonElement eleTemp;
  935. // For active column (boolean with a checkbox)
  936. if (selectedValueBX == 5) {
  937. eleTemp = updCon
  938. .getActualHolonElement((HolonObject) updCon.getActualCps(), yBMouse, 0, tables);
  939. String newBStuff = model.getSingleTable().getValueAt(selectedValueBY, selectedValueBX)
  940. .toString();
  941. Boolean bTemp = Boolean.parseBoolean(newBStuff);
  942. eleTemp.setActive(bTemp);
  943. } // For activeFlex column (boolean with a checkbox)
  944. else if (selectedValueBX == 6) {
  945. eleTemp = updCon
  946. .getActualHolonElement((HolonObject) updCon.getActualCps(), yBMouse, 0, tables);
  947. String newBStuff = model.getSingleTable().getValueAt(selectedValueBY, selectedValueBX)
  948. .toString();
  949. Boolean bTemp = Boolean.parseBoolean(newBStuff);
  950. eleTemp.setFlexible(bTemp);
  951. } else {
  952. // Update of HolonElement
  953. eleTemp = updCon.getActualHolonElement((HolonObject) updCon.getActualCps(),
  954. yMouse, 0, tables);
  955. String newStuff = model.getSingleTable().getValueAt(selectedValueY, selectedValueX)
  956. .toString();
  957. // Name update
  958. if (selectedValueX == 1) {
  959. eleTemp.setEleName(newStuff);
  960. } // Energy Update
  961. else if (selectedValueX == 2) {
  962. Float ftemp = Float.parseFloat(newStuff);
  963. eleTemp.setEnergyPerElement(ftemp);
  964. } // Flexibility
  965. else if (selectedValueX == 3) {
  966. Float ftemp = Float.parseFloat(newStuff);
  967. eleTemp.setFlexibleEnergyAvailable(ftemp);
  968. // if this is a flexible device and the flexibly available energy was changed,
  969. // set used energy to 0, so that it can be computed anew
  970. if (eleTemp.isFlexible()) {
  971. eleTemp.setEnergyPerElement(0);
  972. }
  973. }
  974. // Amount of Elements update
  975. else if (selectedValueX == 4) {
  976. Integer iTemp = Integer.parseInt(newStuff);
  977. eleTemp.setAmount(iTemp);
  978. }
  979. }
  980. // set all cells anew, if anything was changed
  981. updateElementTableAfterChange(eleTemp, selectedValueBY);
  982. }
  983. }
  984. controller.calculateStateForTimeStep(model.getCurIteration());
  985. model.getSingleTable().fireTableDataChanged();
  986. triggerUpdateController(null);
  987. contentPane.updateUI();
  988. unitGraph.repaint();
  989. // trigger update of table after UnitGraph was painted
  990. SwingUtilities.invokeLater(() -> {
  991. triggerUpdateController(null);
  992. });
  993. } catch (Exception e) {
  994. }
  995. });
  996. /***********************
  997. * HolonElement Properties Actions
  998. **********************/
  999. /*
  1000. * Update of the mouse coord for Edit-Mode
  1001. */
  1002. tableProperties.addMouseListener(new MouseAdapter() {
  1003. public void mousePressed(MouseEvent e) {
  1004. if (e.getClickCount() == 2) {
  1005. yProThis = e.getY();
  1006. xProThis = e.getX();
  1007. }
  1008. yProThisOneClick = e.getY();
  1009. xProThisOneClick = e.getX();
  1010. }
  1011. });
  1012. /*
  1013. * Update any change in the Property table
  1014. */
  1015. tableProperties.addPropertyChangeListener(propertyChangeEvent -> {
  1016. try {
  1017. Object temp;
  1018. Object btemp;
  1019. int selValueY = (int) Math.floor(yProThis / 16);
  1020. int selValueX = (int) Math.floor(xProThis / (tableProperties.getWidth() / 2));
  1021. int selValueYBool = (int) Math.floor(yProThisOneClick / 16);
  1022. int selValueXBool = (int) Math.floor(xProThisOneClick / (tableProperties.getWidth() / 2));
  1023. if (updCon.getActualCps() != null) {
  1024. temp = model.getPropertyTable().getValueAt(selValueY, selValueX);
  1025. btemp = model.getPropertyTable().getValueAt(selValueYBool, selValueXBool);
  1026. // Case: Switch selected
  1027. if (updCon.getActualCps() instanceof HolonSwitch) {
  1028. if (selValueY == 0 && selValueX != 0) {
  1029. updCon.getActualCps().setName(temp.toString());
  1030. }
  1031. if (selValueYBool == 2) {
  1032. Boolean bbTemp = Boolean.parseBoolean(btemp.toString());
  1033. ((HolonSwitch) updCon.getActualCps()).setManualMode(bbTemp);
  1034. if (bbTemp) {
  1035. model.getPropertyTable().setCellEditable(3, 1, true);
  1036. } else {
  1037. model.getPropertyTable().setCellEditable(3, 1, false);
  1038. }
  1039. } else if (selValueYBool == 3) {
  1040. if (((HolonSwitch) updCon.getActualCps()).getManualMode()) {
  1041. model.getPropertyTable().setCellEditable(3, 1, true);
  1042. Boolean bTemp = Boolean.parseBoolean(btemp.toString());
  1043. ((HolonSwitch) updCon.getActualCps()).setManualState(bTemp);
  1044. }
  1045. }
  1046. } // Case: UpperNode selected
  1047. else if (updCon.getActualCps() instanceof CpsUpperNode && selValueX != 0) {
  1048. // Name edition through double click
  1049. updCon.getActualCps().setName(temp.toString());
  1050. // Update of name on the tab in the tab section
  1051. for (int index = 4; index < tabbedPaneOriginal.getTabCount(); index++) {
  1052. tabTemp = tabbedPaneOriginal;
  1053. JScrollPane scrollPane = getScrollPaneFromTabbedPane();
  1054. UpperNodeCanvas unc = ((UpperNodeCanvas) scrollPane.getViewport().getComponent(0));
  1055. if (unc.upperNode.getId() == updCon.getActualCps().getId()) {
  1056. tabbedPaneOriginal.setTitleAt(index, unc.upperNode.getName());
  1057. tabbedPaneOriginal.updateUI();
  1058. if (!initSplit) {
  1059. tabbedPaneSplit.setTitleAt(index, unc.upperNode.getName());
  1060. tabbedPaneSplit.updateUI();
  1061. }
  1062. }
  1063. }
  1064. } // Case: HolonObject is selected
  1065. else if (updCon.getActualCps() instanceof HolonObject && selValueX != 0) {
  1066. // Name edition through double click
  1067. updCon.getActualCps().setName(temp.toString());
  1068. }
  1069. } // Case: Edge is selected
  1070. else {
  1071. temp = model.getPropertyTable().getValueAt(selValueY, selValueX);
  1072. btemp = model.getPropertyTable().getValueAt(selValueYBool, selValueXBool);
  1073. // Edit modus for capacity by double clicking
  1074. if (selValueY == 2) {
  1075. Float ftemp;
  1076. if (Float.parseFloat(temp.toString()) >= 0.0) {
  1077. ftemp = Float.parseFloat(temp.toString());
  1078. } else {
  1079. ftemp = model.getSelectedEdge().getCapacity();
  1080. }
  1081. model.getSelectedEdge().setCapacity(ftemp);
  1082. }
  1083. // Status edition through a check box
  1084. if (selValueYBool == 3) {
  1085. Boolean bbTemp = Boolean.parseBoolean(btemp.toString());
  1086. model.getSelectedEdge().setWorkingState(bbTemp);
  1087. }
  1088. }
  1089. canvas.repaint();
  1090. } catch (Exception e) {
  1091. }
  1092. });
  1093. /***********************
  1094. * HolonElement Graph Actions
  1095. **********************/
  1096. /*
  1097. * Reset the graph of the selected HolonElement
  1098. */
  1099. resetGraphBtn.setBorder(new LineBorder(Color.BLACK));
  1100. resetGraphBtn.addActionListener(actionEvent -> unitGraph.reset());
  1101. /*****************************
  1102. * RIGHT CONTAINER DONE
  1103. *****************************/
  1104. frmCyberPhysical.getContentPane().setLayout(new BorderLayout(0, 0));
  1105. /****************
  1106. * Tree Stuff
  1107. ****************/
  1108. // Override Key Actions
  1109. inputMap = tree.getInputMap();
  1110. inputMap.put(KeyStroke.getKeyStroke("control C"), cntrlCDown);
  1111. inputMap.put(KeyStroke.getKeyStroke("control V"), cntrlVDown);
  1112. inputMap.put(KeyStroke.getKeyStroke("control X"), cntrlXDown);
  1113. inputMap.put(KeyStroke.getKeyStroke("control A"), cntrlADown);
  1114. TreeCellRenderer customRenderer = new TreeCellRenderer() {
  1115. @Override
  1116. public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded,
  1117. boolean leaf, int row, boolean hasFocus) {
  1118. JLabel label = new JLabel();
  1119. Image imgR;
  1120. if (leaf) {
  1121. for (Category cat : model.getCategories()) {
  1122. for (AbstractCpsObject cps : cat.getObjects()) {
  1123. if (value.toString().compareTo(cps.getObjName()) == 0) {
  1124. File checkPath = new File(cps.getImage());
  1125. if (checkPath.exists()) {
  1126. imgR = new ImageIcon(cps.getImage()).getImage().getScaledInstance(50, 50,
  1127. java.awt.Image.SCALE_SMOOTH);
  1128. } else {
  1129. imgR = new ImageIcon(this.getClass().getResource(cps.getImage())).getImage()
  1130. .getScaledInstance(50, 50, java.awt.Image.SCALE_SMOOTH);
  1131. }
  1132. if (imgR != null) {
  1133. label.setIcon(new ImageIcon(imgR));
  1134. }
  1135. label.setText(cps.getName());
  1136. }
  1137. }
  1138. }
  1139. }
  1140. tree.setRowHeight(50);
  1141. if (hasFocus) {
  1142. label.setForeground(new Color(0, 0, 255));
  1143. label.setOpaque(true);
  1144. }
  1145. if (label.getText().length() == 0) {
  1146. label.setText(value.toString());
  1147. if (value.toString().compareTo("Categories") != 0) {
  1148. label.setIcon(new ImageIcon(this.getClass().getResource("/Images/folder.png")));
  1149. }
  1150. }
  1151. return label;
  1152. }
  1153. };
  1154. tree.setCellRenderer(customRenderer);
  1155. tree.addMouseListener(new MouseAdapter() {
  1156. public void mouseReleased(MouseEvent e) {
  1157. try {
  1158. if (dragging) {
  1159. chooseTabTemp();
  1160. JScrollPane scrollPane = getScrollPaneFromTabbedPane();
  1161. Component canvasOrUpperNodeCanvas = scrollPane.getViewport().getComponent(0);
  1162. if (canvasOrUpperNodeCanvas instanceof UpperNodeCanvas) {
  1163. UpperNodeCanvas unc = (UpperNodeCanvas) canvasOrUpperNodeCanvas;
  1164. int x = (int) unc.getMousePosition().getX() + 16;
  1165. int y = (int) unc.getMousePosition().getY() + 16;
  1166. if (x > unc.upperNode.getLeftBorder()) {
  1167. AbstractCpsObject h = null;
  1168. if (tempCps instanceof HolonObject) {
  1169. h = new HolonObject(tempCps);
  1170. }
  1171. if (tempCps instanceof HolonSwitch) {
  1172. h = new HolonSwitch(tempCps);
  1173. }
  1174. if (tempCps instanceof HolonTransformer) {
  1175. h = new HolonTransformer(tempCps);
  1176. }
  1177. h.setPosition(x, y);
  1178. controller.addObjUpperNode(h, unc.upperNode);
  1179. unc.invalidate();
  1180. unc.repaint();
  1181. unc.setXY((int) canvas.getMousePosition().getX(),
  1182. (int) canvas.getMousePosition().getY());
  1183. }
  1184. } else {
  1185. int x = (int) canvas.getMousePosition().getX() + 16;
  1186. int y = (int) canvas.getMousePosition().getY() + 16;
  1187. AbstractCpsObject h = null;
  1188. if (tempCps instanceof HolonObject) {
  1189. h = new HolonObject(tempCps);
  1190. }
  1191. if (tempCps instanceof HolonSwitch) {
  1192. h = new HolonSwitch(tempCps);
  1193. }
  1194. if (tempCps instanceof HolonTransformer) {
  1195. h = new HolonTransformer(tempCps);
  1196. }
  1197. h.setPosition(x, y);
  1198. controller.addObjectCanvas(h);
  1199. canvas.invalidate();
  1200. canvas.setXY((int) canvas.getMousePosition().getX(),
  1201. (int) canvas.getMousePosition().getY());
  1202. canvas.repaint();
  1203. }
  1204. controller.calculateStateForCurrentTimeStep();
  1205. contentPane.updateUI();
  1206. dragging = false;
  1207. }
  1208. } catch (Exception eex) {
  1209. }
  1210. frmCyberPhysical.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
  1211. }
  1212. });
  1213. popmenuEdit.add(editItem);
  1214. editItem.setEnabled(false);
  1215. editItem.addActionListener(actionEvent -> {
  1216. });
  1217. tree.addMouseListener(new MouseAdapter() {
  1218. public void mousePressed(MouseEvent e) {
  1219. try {
  1220. actualObjectClicked = tree.getPathForLocation(e.getX(), e.getY()).getLastPathComponent().toString();
  1221. // if an Object was selected, the porperties are shown in
  1222. // the table
  1223. DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) tree
  1224. .getPathForLocation(e.getX(), e.getY()).getLastPathComponent();
  1225. if (selectedNode.getLevel() == 2) {
  1226. controller.searchCategoryObject(selectedNode.getParent().toString(), selectedNode.toString());
  1227. updCon.deleteRows(model.getSingleTable());
  1228. updCon.deleteRows(model.getMultiTable());
  1229. // if (selected instanceof HolonObject && selected !=
  1230. // null) {
  1231. // selected = (HolonObject) selected;
  1232. // fillElementTable(((HolonObject)
  1233. // selected).getElements());
  1234. // }
  1235. }
  1236. if (SwingUtilities.isRightMouseButton(e)) {
  1237. for (Category cat : model.getCategories()) {
  1238. for (AbstractCpsObject cps : cat.getObjects()) {
  1239. if (actualObjectClicked.compareTo(cps.getObjName()) == 0
  1240. && !(cps instanceof HolonSwitch)) {
  1241. editItem.setEnabled(true);
  1242. popmenuEdit.show(e.getComponent(), e.getX(), e.getY());
  1243. catOfObjToBeEdited = selectedNode.getParent().toString();
  1244. tempCps = cps;
  1245. }
  1246. }
  1247. }
  1248. } else {
  1249. for (Category cat : model.getCategories()) {
  1250. for (AbstractCpsObject cps : cat.getObjects()) {
  1251. if (actualObjectClicked.compareTo(cps.getObjName()) == 0) {
  1252. File checkPath = new File(cps.getImage());
  1253. if (checkPath.exists()) {
  1254. img = new ImageIcon(cps.getImage()).getImage().getScaledInstance(32, 32,
  1255. java.awt.Image.SCALE_SMOOTH);
  1256. } else {
  1257. img = new ImageIcon(this.getClass().getResource(cps.getImage())).getImage()
  1258. .getScaledInstance(32, 32, java.awt.Image.SCALE_SMOOTH);
  1259. }
  1260. tempCps = cps;
  1261. dragging = true;
  1262. Cursor cursor = Toolkit.getDefaultToolkit().createCustomCursor(img, new Point(0, 0),
  1263. "Image");
  1264. frmCyberPhysical.setCursor(cursor);
  1265. }
  1266. }
  1267. }
  1268. }
  1269. } catch (Exception eex) {
  1270. }
  1271. }
  1272. });
  1273. editItem.addActionListener(actionEvent -> {
  1274. // Remove the selected Object object
  1275. addObjectPopUP = new AddObjectPopUp(true, tempCps, catOfObjToBeEdited, frmCyberPhysical);
  1276. addObjectPopUP.setCategory(catOfObjToBeEdited);
  1277. addObjectPopUP.setController(controller);
  1278. addObjectPopUP.setVisible(true);
  1279. });
  1280. scrollPane1.setViewportView(tree);
  1281. scrollPane1.setColumnHeaderView(panel);
  1282. panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
  1283. toolBar.setAlignmentX(Component.LEFT_ALIGNMENT);
  1284. toolBar.setFloatable(false);
  1285. panel.add(toolBar);
  1286. comboBox.setMaximumSize(new Dimension(100, 20));
  1287. toolBar.add(comboBox);
  1288. comboBox.setModel(new DefaultComboBoxModel(comboBoxCat));
  1289. // Add Buttonnew DefaultComboBoxModel(comboBoxCat)
  1290. btnAdd.addActionListener(actionEvent -> {
  1291. Object nodeInfo = tree.getLastSelectedPathComponent();
  1292. String selectedOption = comboBox.getSelectedItem().toString();
  1293. DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) nodeInfo;
  1294. try {
  1295. switch (selectedOption) {
  1296. case "Category":
  1297. String catName = JOptionPane.showInputDialog(Languages.getLanguage()[56]);
  1298. if (catName.length() != 0) {
  1299. controller.addCategory(catName);
  1300. }
  1301. break;
  1302. case "Object":
  1303. if (selectedNode == null) {
  1304. JOptionPane.showMessageDialog(new JFrame(),
  1305. Languages.getLanguage()[57] + selectedOption + ".");
  1306. }
  1307. if (selectedNode != null && selectedNode.getLevel() == 1) {
  1308. AbstractCpsObject tmp = new HolonObject("");
  1309. addObjectPopUP = new AddObjectPopUp(false, tmp, null, frmCyberPhysical);
  1310. addObjectPopUP.setVisible(true);
  1311. addObjectPopUP.setController(controller);
  1312. addObjectPopUP.setCategory(selectedNode.toString());
  1313. }
  1314. break;
  1315. default:
  1316. addObjectAction(selectedOption, selectedNode);
  1317. break;
  1318. }
  1319. } catch (Exception e) {
  1320. }
  1321. tree.repaint();
  1322. });
  1323. /**
  1324. * Pop up - About Us with some important information about the
  1325. * developers, source and programming stuff
  1326. */
  1327. mntmAboutUs.addMouseListener(new MouseAdapter() {
  1328. @Override
  1329. public void mousePressed(MouseEvent e) {
  1330. aboutUsPopUp = new AboutUsPopUp(frmCyberPhysical);
  1331. aboutUsPopUp.setVisible(true);
  1332. }
  1333. });
  1334. /**
  1335. * Update of every interaction between the user and the canvas (only on
  1336. * the canvas). Basically the update of all the information concerning
  1337. * the clicked HolonObject. For multi-selection, the propertyTable would
  1338. * be disabled
  1339. */
  1340. canvas.addMouseListener(new MouseAdapter() {
  1341. @Override
  1342. public void mousePressed(MouseEvent e) {
  1343. }
  1344. @Override
  1345. public void mouseReleased(MouseEvent e) {
  1346. holonEleNamesDisplayed = Languages.getLanguage()[25];
  1347. // If any empty space is clicked
  1348. if (temp == null || temp.getId() != model.getSelectedObjectID()) {
  1349. hideScrollGraph();
  1350. elementGraph.setText(Languages.getLanguage()[25]);
  1351. }
  1352. temp = updCon.getActualCps();
  1353. // Erase old data in the PropertyTable
  1354. if (model.getPropertyTable().getRowCount() > 0) {
  1355. for (int i = model.getPropertyTable().getRowCount() - 1; i > -1; i--) {
  1356. model.getPropertyTable().removeRow(i);
  1357. }
  1358. }
  1359. if (e.isControlDown() && temp != null) {
  1360. if (model.getSelectedCpsObjects().contains(temp)) {
  1361. controller.deleteSelectedObject(temp);
  1362. } else {
  1363. controller.addSelectedObject(temp);
  1364. }
  1365. }
  1366. if (temp instanceof HolonSwitch) {
  1367. showScrollGraph();
  1368. unitGraph.repaintWithNewSwitch((HolonSwitch) temp);
  1369. unitGraph.fillArrayofBooleans();
  1370. }
  1371. // Write new data in the PropertyTable
  1372. triggerUpdateController(temp);
  1373. // New Tab with NodeOfNode
  1374. if (doubleClick() && MouseEvent.BUTTON3 != e.getButton() && temp instanceof CpsUpperNode) {
  1375. openNewUpperNodeTab();
  1376. try {
  1377. controller.autoSave();
  1378. } catch (IOException e1) {
  1379. e1.printStackTrace();
  1380. }
  1381. }
  1382. if (model.getSelectedCpsObjects().size() > 1) {
  1383. model.getTableHolonElement().setModel(model.getMultiTable());
  1384. } else if (model.getSelectedCpsObjects().size() == 1) {
  1385. model.getTableHolonElement().setModel(model.getSingleTable());
  1386. }
  1387. }
  1388. });
  1389. holonCanvas.addMouseListener(new MouseAdapter() {
  1390. @Override
  1391. public void mousePressed(MouseEvent e) {
  1392. hideScrollGraph();
  1393. elementGraph.setText(Languages.getLanguage()[25]);
  1394. if (model.getPropertyTable().getRowCount() > 0) {
  1395. for (int i = model.getPropertyTable().getRowCount() - 1; i > -1; i--) {
  1396. model.getPropertyTable().removeRow(i);
  1397. }
  1398. }
  1399. updCon.deleteRows(model.getMultiTable());
  1400. updCon.deleteRows(model.getSingleTable());
  1401. updCon.paintHolonBody(model.getSelectedHolonBody());
  1402. }
  1403. });
  1404. toolBar.add(btnAdd);
  1405. // Del Button
  1406. btnDel.addActionListener(actionEvent -> {
  1407. Object nodeInfo = tree.getLastSelectedPathComponent();
  1408. if (nodeInfo != null) {
  1409. DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) nodeInfo;
  1410. String nodeName = selectedNode.getUserObject().toString();
  1411. int depthOfNode = selectedNode.getLevel();
  1412. try {
  1413. switch (depthOfNode) {
  1414. case 1:
  1415. int dialogResult = JOptionPane.showConfirmDialog(null, eraseCategory + nodeName + "?",
  1416. warningText, JOptionPane.YES_NO_OPTION);
  1417. if (dialogResult == JOptionPane.YES_OPTION) {
  1418. controller.deleteCategory(nodeName);
  1419. }
  1420. break;
  1421. case 2:
  1422. DefaultMutableTreeNode parent = (DefaultMutableTreeNode) selectedNode.getParent();
  1423. controller.delObjectCategory(parent.getUserObject().toString(), nodeName);
  1424. break;
  1425. default:
  1426. JOptionPane.showMessageDialog(new JFrame(), selectObjBeforeErase);
  1427. }
  1428. } catch (Exception e2) {
  1429. }
  1430. } else {
  1431. JOptionPane.showMessageDialog(new JFrame(), selectObjBeforeErase);
  1432. }
  1433. tree.repaint();
  1434. });
  1435. toolBar.add(btnDel);
  1436. frmCyberPhysical.getContentPane().add(splitPane);
  1437. mntmNew.addActionListener(actionEvent -> {
  1438. if (model.getObjectsOnCanvas().size() != 0) {
  1439. int newWarning = JOptionPane.YES_NO_OPTION;
  1440. int dialogForNewWarning = JOptionPane.showConfirmDialog(null, saveBeforeNew, warningText,
  1441. newWarning);
  1442. if (dialogForNewWarning == JOptionPane.YES_OPTION) {
  1443. mntmSave.doClick();
  1444. }
  1445. }
  1446. model.getEdgesOnCanvas().removeAll(model.getEdgesOnCanvas());
  1447. model.getObjectsOnCanvas().removeAll(model.getObjectsOnCanvas());
  1448. controller.setSelectedObjectID(0);
  1449. controller.setSelecteEdge(null);
  1450. controller.setCurIteration(0);
  1451. hideScrollGraph();
  1452. elementGraph.setText(Languages.getLanguage()[25]);
  1453. canvas.tempCps = null;
  1454. canvas.repaint();
  1455. IdCounter.resetCounter();
  1456. IdCounterElem.resetCounter();
  1457. });
  1458. mntmOpen.addActionListener(new ActionListener() {
  1459. @Override
  1460. public void actionPerformed(ActionEvent evt) {
  1461. menuFileExitActionPerformed();
  1462. }
  1463. private void menuFileExitActionPerformed() {
  1464. JFileChooser fileChooser = new JFileChooser();
  1465. JFrame test = new JFrame();
  1466. FileNameExtensionFilter holonFilter = new FileNameExtensionFilter("Holon Save File(*.holon)", "holon");
  1467. fileChooser.setFileFilter(holonFilter);
  1468. if (fileChooser.showOpenDialog(test) == JFileChooser.APPROVE_OPTION) {
  1469. File file = fileChooser.getSelectedFile();
  1470. try {
  1471. controller.loadFile(file.getAbsolutePath());
  1472. canvas.repaint();
  1473. unitGraph.update(model.getObjectsOnCanvas());
  1474. tree.repaint();
  1475. for (JsonObject json : model.getStatisticData()) {
  1476. readStatistics(json);
  1477. }
  1478. } catch (IOException | ArchiveException e) {
  1479. e.printStackTrace();
  1480. JLabel message = new JLabel("The savefile is corrupt and cannot be opened.");
  1481. JOptionPane.showMessageDialog(null, message, "", JOptionPane.ERROR_MESSAGE);
  1482. }
  1483. }
  1484. }
  1485. });
  1486. mntmSave.addActionListener(new ActionListener() {
  1487. @Override
  1488. public void actionPerformed(ActionEvent evt) {
  1489. menuSaveActionPerformed();
  1490. }
  1491. private void menuSaveActionPerformed() {
  1492. JFileChooser fileChooser = new JFileChooser();
  1493. JFrame test = new JFrame();
  1494. FileNameExtensionFilter holonFilter = new FileNameExtensionFilter("Holon Save File(*.holon)", "holon");
  1495. fileChooser.setFileFilter(holonFilter);
  1496. if (fileChooser.showSaveDialog(test) == JFileChooser.APPROVE_OPTION) {
  1497. String file = fileChooser.getSelectedFile().getPath();
  1498. if (fileChooser.getFileFilter().equals(holonFilter)) {
  1499. if (!file.contains("."))
  1500. file += ".holon";
  1501. }
  1502. if (!file.endsWith(".holon")) {
  1503. String suffix = file.substring(file.lastIndexOf("."), file.length());
  1504. String[] options = new String[]{"keep .holon", "use " + suffix};
  1505. JLabel message = new JLabel(
  1506. "Are you sure to use the extension \"" + suffix + "\" instead of \".holon\"?");
  1507. int response = JOptionPane.showOptionDialog(null, message, "", JOptionPane.DEFAULT_OPTION,
  1508. JOptionPane.QUESTION_MESSAGE, null, options, options[1]);
  1509. if (response == 0)
  1510. file = file.replace(suffix, ".holon");
  1511. }
  1512. try {
  1513. controller.saveFile(new File(file).getAbsolutePath());
  1514. } catch (IOException | ArchiveException e) {
  1515. e.printStackTrace();
  1516. }
  1517. }
  1518. }
  1519. });
  1520. englishBtn.addActionListener(actionEvent -> {
  1521. Languages.setLanguage(0);
  1522. refreshLanguages();
  1523. updCon.refreshTableProperties(model.getPropertyTable());
  1524. });
  1525. spanishBtn.addActionListener(actionEvent -> {
  1526. Languages.setLanguage(1);
  1527. refreshLanguages();
  1528. updCon.refreshTableProperties(model.getPropertyTable());
  1529. });
  1530. germanBtn.addActionListener(actionEvent -> {
  1531. Languages.setLanguage(2);
  1532. refreshLanguages();
  1533. updCon.refreshTableProperties(model.getPropertyTable());
  1534. });
  1535. czechBtn.addActionListener(actionEvent -> {
  1536. Languages.setLanguage(3);
  1537. refreshLanguages();
  1538. updCon.refreshTableProperties(model.getPropertyTable());
  1539. });
  1540. chineseBtn.addActionListener(actionEvent -> {
  1541. Languages.setLanguage(4);
  1542. refreshLanguages();
  1543. updCon.refreshTableProperties(model.getPropertyTable());
  1544. });
  1545. mntmUndo.addActionListener(new ActionListener() {
  1546. @Override
  1547. public void actionPerformed(ActionEvent evt) {
  1548. menuUndoActionPerformed();
  1549. }
  1550. private void menuUndoActionPerformed() {
  1551. try {
  1552. controller.loadAutoSave(controller.getUndoSave());
  1553. canvas.repaint();
  1554. repaintGraphAfterUndoRedo();
  1555. hideScrollGraph();
  1556. } catch (IOException e) {
  1557. e.printStackTrace();
  1558. }
  1559. }
  1560. });
  1561. mntmRedo.addActionListener(new ActionListener() {
  1562. @Override
  1563. public void actionPerformed(ActionEvent evt) {
  1564. menuRedoActionPerformed();
  1565. }
  1566. private void menuRedoActionPerformed() {
  1567. try {
  1568. controller.loadAutoSave(controller.getRedoSave());
  1569. canvas.repaint();
  1570. repaintGraphAfterUndoRedo();
  1571. hideScrollGraph();
  1572. } catch (IOException e) {
  1573. e.printStackTrace();
  1574. }
  1575. }
  1576. });
  1577. timePanel = new TimePanel(model, controller);
  1578. timePanel.setBorder(null);
  1579. ((JSlider) (timePanel.getComponent(1))).addChangeListener(changeEvent -> {
  1580. int i = model.getCurIteration();
  1581. controller.calculateStateForTimeStep(i);
  1582. unitGraph.repaint();
  1583. if (model.getIsSimRunning()) {
  1584. controller.runAlgorithm(model, controller);
  1585. statSplitPane.repaintGraphs();
  1586. }
  1587. contentPane.updateUI();
  1588. });
  1589. splitPane1.setMinimumSize(new Dimension(0, 25));
  1590. splitPane.setRightComponent(splitPane1);
  1591. splitPane.setDividerLocation(200);
  1592. splitPane1.setDividerLocation(500);
  1593. splitPaneCanvasConsole.setDividerLocation(550);
  1594. splitPaneCanvasConsole.setResizeWeight(0.9);
  1595. splitPane.setLeftComponent(scrollPane1);
  1596. splitPaneCanvasConsole.setLeftComponent(tabbedPaneOriginal);
  1597. tabbedPaneOriginal.addTab("View", tabbedPaneInnerOriginal);
  1598. tabbedPaneInnerOriginal.addTab("Main Grid", canvasSP);
  1599. tabbedPaneOriginal.addTab("Statistics", statScrollPane);
  1600. tabbedPaneOriginal.addTab("Holon", holonCanvas);
  1601. FlexiblePane flexPane = new FlexiblePane(controller);
  1602. controller.setFlexiblePane(flexPane);
  1603. controller.getModel().getObjectListeners().add(flexPane);
  1604. tabbedPaneOriginal.addTab("Flexibility", flexPane);
  1605. splitPaneCanvasConsole.setRightComponent(console);
  1606. splitPane1.setLeftComponent(splitPaneCanvasConsole);
  1607. splitPane1.setRightComponent(splitHolonElPro);
  1608. splitPane1.setResizeWeight(0.9);
  1609. splitHolonElPro.setDividerLocation(700);
  1610. // containing the graph and the elements-list
  1611. splitHolonElPro.setTopComponent(splitGraphHolonEl);
  1612. // containing the object's properties
  1613. splitHolonElPro.setBottomComponent(scrollProperties);
  1614. splitGraphHolonEl.setDividerLocation(distanceBetweenElementsAndGraph);
  1615. splitGraphHolonEl.setTopComponent(scrollElements);
  1616. splitGraphHolonEl.setBottomComponent(scrollGraph);
  1617. canvasSP.setViewportView(canvas);
  1618. algorithmMenu.setBackground(new Color(240, 240, 240));
  1619. tabbedPaneOriginal.setBorder(null);
  1620. scrollProperties.setBorder(null);
  1621. scrollGraph.setBorder(null);
  1622. scrollElements.setBorder(null);
  1623. splitPane.setBorder(null);
  1624. splitPane1.setBorder(null);
  1625. splitPaneCanvasConsole.setBorder(null);
  1626. splitHolonElPro.setBorder(null);
  1627. splitGraphHolonEl.setBorder(null);
  1628. panelHolonEl.setBorder(null);
  1629. canvasSP.setBorder(null);
  1630. tableHolonElementScrollPane.setBorder(null);
  1631. frmCyberPhysical.getContentPane().add(timePanel, BorderLayout.SOUTH);
  1632. MouseAdapter focusCanvasAdapter = new FocusCanvasMouseAdapter();
  1633. model.getTableHolonElement().addMouseListener(focusCanvasAdapter);
  1634. tableProperties.addMouseListener(focusCanvasAdapter);
  1635. console.getConsoleText().addMouseListener(focusCanvasAdapter);
  1636. try {
  1637. controller.loadAutoSave(System.getProperty("user.home") + "/.config/HolonGUI/Category/Category.json");
  1638. } catch (IOException e1) {
  1639. }
  1640. String autoPath = System.getProperty("user.home") + "/.config/HolonGUI/Autosave/";
  1641. File dest = new File(autoPath);
  1642. ArrayList<File> oldAutoSaves = controller.filterOldAutoSaveFiles();
  1643. int nrOfOldSaves = oldAutoSaves.size();
  1644. if (nrOfOldSaves > 0) {
  1645. int dialogButton = JOptionPane.YES_NO_OPTION;
  1646. int dialogResult = JOptionPane.showConfirmDialog(null, "Old autosave file was found, should it be loaded?",
  1647. warningText, dialogButton);
  1648. if (dialogResult == JOptionPane.YES_OPTION) {
  1649. if (dest.exists()) {
  1650. model.setAutoSaveNr(nrOfOldSaves - 1);
  1651. mntmRedo.doClick();
  1652. } else {
  1653. JOptionPane.showMessageDialog(frmCyberPhysical, "Autosave could not be loaded.");
  1654. setUpAutoSave(dest);
  1655. }
  1656. } else {
  1657. setUpAutoSave(dest);
  1658. }
  1659. // after all: delete the obsolete/old autosave files from the directory
  1660. controller.deleteObsoleteAutoSaveFiles();
  1661. }
  1662. canvasSP.addComponentListener(new ComponentAdapter() {
  1663. @Override
  1664. public void componentResized(ComponentEvent e) {
  1665. controller.setCanvasX(Math.max(model.getCanvasX(), canvasSP.getViewport().getWidth()));
  1666. controller.setCanvasY(Math.max(model.getCanvasY(), canvasSP.getViewport().getHeight()));
  1667. canvas.repaint();
  1668. }
  1669. });
  1670. }
  1671. private void showScrollGraph() {
  1672. scrollGraph.setVisible(true);
  1673. splitGraphHolonEl.setBottomComponent(scrollGraph);
  1674. splitGraphHolonEl.setDividerLocation(distanceBetweenElementsAndGraph);
  1675. }
  1676. private void hideScrollGraph() {
  1677. scrollGraph.setVisible(false);
  1678. unitGraph.empty();
  1679. splitGraphHolonEl.remove(scrollGraph);
  1680. splitGraphHolonEl.setDividerLocation(0);
  1681. }
  1682. private boolean isUpperPanelInsideBounds() {
  1683. int x = frmCyberPhysical.getX();
  1684. int y = frmCyberPhysical.getY();
  1685. int width = frmCyberPhysical.getWidth();
  1686. // get all connected screen devices
  1687. GraphicsDevice[] screenDevices = GraphicsEnvironment.getLocalGraphicsEnvironment().getScreenDevices();
  1688. boolean isUpperPanelVisible = false;
  1689. // and check whether they contain the upper left or upper right point of the frame
  1690. for (GraphicsDevice device : screenDevices) {
  1691. Rectangle bounds = device.getDefaultConfiguration().getBounds();
  1692. if (bounds.contains(x, y) || bounds.contains(x + width, y)) {
  1693. isUpperPanelVisible = true;
  1694. break;
  1695. }
  1696. }
  1697. return isUpperPanelVisible;
  1698. }
  1699. /**
  1700. * Sets up autosave if no old one is loaded at the beginning
  1701. *
  1702. * @param dest path to save-folder
  1703. */
  1704. private void setUpAutoSave(File dest) {
  1705. dest.mkdirs();
  1706. try {
  1707. controller.autoSave();
  1708. } catch (IOException e1) {
  1709. e1.printStackTrace();
  1710. }
  1711. }
  1712. /**
  1713. * adds a specific object type to selected Category also handles input
  1714. * windows and illegal inputs.
  1715. *
  1716. * @param objType type of the Object
  1717. * @param selectedNode The selected Node
  1718. */
  1719. private void addObjectAction(String objType, DefaultMutableTreeNode selectedNode) {
  1720. if (selectedNode == null) {
  1721. JOptionPane.showMessageDialog(new JFrame(),
  1722. "Please select a Category first before adding " + objType + ".");
  1723. }
  1724. // if selected node is a directory for Categories
  1725. else {
  1726. if (selectedNode.getLevel() == 1) {
  1727. String objname = JOptionPane.showInputDialog("Please enter a Name for the " + objType);
  1728. Category cat = controller.searchCategory(selectedNode.getUserObject().toString());
  1729. if (objname.length() != 0) {
  1730. try {
  1731. switch (objType) {
  1732. case "Switch":
  1733. controller.addSwitch(cat, objname);
  1734. break;
  1735. }
  1736. } catch (Exception e) {
  1737. }
  1738. }
  1739. } else {
  1740. JOptionPane.showMessageDialog(new JFrame(),
  1741. "Objects can not be added to Objects. Please select a Category.");
  1742. }
  1743. }
  1744. }
  1745. /**
  1746. * reloads the Categories from Model.
  1747. *
  1748. * @param categories the current categories
  1749. */
  1750. private void updateCategories(final ArrayList<Category> categories) {
  1751. tree.setModel(new DefaultTreeModel(new DefaultMutableTreeNode("Categories") {
  1752. private static final long serialVersionUID = 1L;
  1753. {
  1754. DefaultMutableTreeNode node1;
  1755. for (Category c : categories) {
  1756. node1 = new DefaultMutableTreeNode(c.getName());
  1757. // kann eventuell umgeändert werden
  1758. for (AbstractCpsObject obj : c.getObjects()) {
  1759. node1.add(new DefaultMutableTreeNode(obj.getObjName()));
  1760. }
  1761. add(node1);
  1762. }
  1763. }
  1764. }));
  1765. }
  1766. /**
  1767. * When changes are made to the Categories.
  1768. *
  1769. * @param categories the Categories
  1770. */
  1771. public void onChange(ArrayList<Category> categories) {
  1772. DefaultTreeModel model = (DefaultTreeModel) tree.getModel();
  1773. updateCategories(categories);
  1774. model.reload();
  1775. }
  1776. /**
  1777. * Get the Frame.
  1778. *
  1779. * @return the Frame
  1780. */
  1781. JFrame getFrmCyberPhysical() {
  1782. return frmCyberPhysical;
  1783. }
  1784. private void refreshLanguages() {
  1785. String[] tempArray = Languages.getLanguage();
  1786. // ToolBar
  1787. mnNewMenu.setText(tempArray[0]);
  1788. mntmNew.setText(tempArray[1]);
  1789. mntmOpen.setText(tempArray[2]);
  1790. mntmSave.setText(tempArray[3]);
  1791. mnNewMenuEdit.setText(tempArray[4]);
  1792. mntmUndo.setText(tempArray[5]);
  1793. mntmRedo.setText(tempArray[6]);
  1794. mntmFindReplace.setText(tempArray[7]);
  1795. mntmEditShowedInformation.setText(tempArray[8]);
  1796. mnNewMenuOptions.setText(tempArray[9]);
  1797. mntmResetCategory.setText(tempArray[10]);
  1798. mnNewMenuView.setText(tempArray[11]);
  1799. mntmCanvasSize.setText(tempArray[12]);
  1800. mnHelp.setText(tempArray[13]);
  1801. mntmAboutUs.setText(tempArray[14]);
  1802. mntmEditEdges.setText(tempArray[15]);
  1803. mnLanguage.setText(tempArray[16]);
  1804. canvas.updateLanguages();
  1805. // Tables
  1806. System.arraycopy(tempArray, 17, columnNamesMulti, 0, columnNamesMulti.length);
  1807. model.getMultiTable().setColumnIdentifiers(columnNamesMulti);
  1808. System.arraycopy(tempArray, 18, columnNamesSingle, 0, columnNamesSingle.length);
  1809. model.getSingleTable().setColumnIdentifiers(columnNamesSingle);
  1810. model.colNames[0] = tempArray[23];
  1811. model.colNames[1] = tempArray[24];
  1812. model.getPropertyTable().setColumnIdentifiers(model.colNames);
  1813. // Graph
  1814. elementGraph.setText(tempArray[25]);
  1815. holonEleNamesDisplayed = tempArray[25];
  1816. resetGraphBtn.setText(tempArray[26]);
  1817. // Warning PopUps
  1818. warningText = tempArray[27];
  1819. saveBeforeNew = tempArray[28];
  1820. eraseCategory = tempArray[29];
  1821. selectObjBeforeErase = tempArray[30];
  1822. // SimMenu
  1823. algorithmMenu.algoFolderButton.setText(Languages.getLanguage()[85]);
  1824. // TimePanel
  1825. timePanel.playBtn.setToolTipText(Languages.getLanguage()[89]);
  1826. timePanel.timeResetBtn.setToolTipText(Languages.getLanguage()[90]);
  1827. timePanel.timeForwardBtn.setToolTipText(Languages.getLanguage()[91]);
  1828. timePanel.timeBackwardBtn.setToolTipText(Languages.getLanguage()[92]);
  1829. timePanel.timeSlider.setToolTipText(Languages.getLanguage()[93]);
  1830. // Image Size Slider
  1831. lblImageSize.setText(Languages.getLanguage()[94]);
  1832. }
  1833. /**
  1834. * Checks if a double click was made.
  1835. *
  1836. * @return true if doublecklick, false if not
  1837. */
  1838. private boolean doubleClick() {
  1839. if (click) {
  1840. click = false;
  1841. return true;
  1842. } else {
  1843. click = true;
  1844. Timer t = new Timer("doubleclickTimer", false);
  1845. t.schedule(new TimerTask() {
  1846. @Override
  1847. public void run() {
  1848. click = false;
  1849. }
  1850. }, 350);
  1851. }
  1852. return false;
  1853. }
  1854. /*
  1855. * Open a new Tab with an UpperNodeCanvas
  1856. */
  1857. private void openNewUpperNodeTab() {
  1858. chooseTabTemp();
  1859. JScrollPane scrollPane = getScrollPaneFromTabbedPane();
  1860. if (scrollPane.getViewport().getComponent(0) instanceof MyCanvas) {
  1861. unc = new UpperNodeCanvas(model, controller, unitGraph, (CpsUpperNode) temp, "");
  1862. } else {
  1863. unc = new UpperNodeCanvas(model, controller, unitGraph, (CpsUpperNode) temp,
  1864. ((UpperNodeCanvas) scrollPane.getViewport().getComponent(0)).path + " -> ");
  1865. }
  1866. unc.setShowedInformation(canvas.getShowedInformation());
  1867. // check if tab already open for clicked NodeOfNode
  1868. boolean dupl = false;
  1869. for (int i = 1; i < tabbedPaneInnerOriginal.getTabCount(); i++) {
  1870. JScrollPane paneOriginal = (JScrollPane) tabbedPaneInnerOriginal.getComponentAt(i);
  1871. if (paneOriginal != null &&
  1872. ((UpperNodeCanvas) paneOriginal.getViewport().getComponent(0)).upperNode.getId() == temp.getId()) {
  1873. dupl = true;
  1874. // set selected component to view
  1875. tabbedPaneOriginal.setSelectedComponent(tabbedPaneInnerOriginal);
  1876. // set selected tab in view to found upper-node-canvas
  1877. tabbedPaneInnerOriginal.setSelectedComponent(tabbedPaneInnerOriginal.getComponentAt(i));
  1878. }
  1879. if (tabbedPaneSplit.getTabCount() > 0) {
  1880. JTabbedPane tabbedPaneInnerSplit = (JTabbedPane) tabbedPaneSplit.getComponentAt(0);
  1881. if (tabbedPaneInnerSplit != null) {
  1882. JScrollPane paneSplit = (JScrollPane) tabbedPaneInnerSplit.getComponentAt(i);
  1883. if (!initSplit && paneSplit != null
  1884. && ((UpperNodeCanvas) paneSplit.getViewport().getComponent(0)).upperNode.getId() == temp.getId()) {
  1885. dupl = true;
  1886. // set selected component to view
  1887. tabbedPaneSplit.setSelectedComponent(tabbedPaneInnerSplit);
  1888. // set selected tab in view to found upper-node-canvas
  1889. tabbedPaneInnerSplit.setSelectedComponent(tabbedPaneInnerSplit.getComponentAt(i));
  1890. }
  1891. }
  1892. }
  1893. // if we found a duplicate, break
  1894. if (dupl) {
  1895. break;
  1896. }
  1897. }
  1898. if (!dupl) {
  1899. unc.setBorder(null);
  1900. unc.setBackground(Color.WHITE);
  1901. unc.setPreferredSize(new Dimension(model.getCanvasX(), model.getCanvasY()));
  1902. unc.addMouseListener(new MouseAdapter() {
  1903. @Override
  1904. public void mousePressed(MouseEvent e) {
  1905. hideScrollGraph();
  1906. holonEleNamesDisplayed = Languages.getLanguage()[25];
  1907. elementGraph.setText(holonEleNamesDisplayed);
  1908. chooseTabTemp();
  1909. JScrollPane scrollPane1 = getScrollPaneFromTabbedPane();
  1910. temp = ((UpperNodeCanvas) scrollPane1.getViewport().getComponent(0)).tempCps;
  1911. if (doubleClick() && MouseEvent.BUTTON3 != e.getButton() && temp instanceof CpsUpperNode) {
  1912. openNewUpperNodeTab();
  1913. }
  1914. if (temp instanceof HolonSwitch) {
  1915. unitGraph.repaintWithNewSwitch((HolonSwitch) temp);
  1916. unitGraph.fillArrayofBooleans();
  1917. }
  1918. }
  1919. });
  1920. JScrollPane sp = new JScrollPane(unc);
  1921. sp.setBorder(null);
  1922. // Selected tabbed Pane = tabbedPaneOriginal or tabbedPaneSplit
  1923. if (tabTemp == tabbedPaneOriginal) {
  1924. this.tabbedPaneInnerOriginal.add(temp.getName(), sp);
  1925. this.tabbedPaneInnerOriginal.setSelectedComponent(sp);
  1926. this.tabbedPaneInnerOriginal.setTabComponentAt(this.tabbedPaneInnerOriginal.getTabCount() - 1,
  1927. new ButtonTabComponent(this.tabbedPaneInnerOriginal, tabbedPaneSplit));
  1928. } else {
  1929. JTabbedPane tabbedPaneInnerSplit = (JTabbedPane) tabbedPaneSplit.getComponentAt(0);
  1930. tabbedPaneInnerSplit.add(temp.getName(), sp);
  1931. Component tempC = tabbedPaneInnerSplit.getSelectedComponent();
  1932. tabbedPaneInnerSplit.setComponentAt(tabbedPaneInnerSplit.getSelectedIndex(), null);
  1933. tabbedPaneOriginal.setComponentAt(tabbedPaneInnerSplit.getSelectedIndex(), tempC);
  1934. tabbedPaneInnerSplit.setSelectedComponent(sp);
  1935. tabbedPaneInnerOriginal.add(temp.getName(), null);
  1936. tabbedPaneInnerOriginal.setTabComponentAt(tabbedPaneInnerOriginal.getTabCount() - 1,
  1937. new ButtonTabComponent(tabbedPaneInnerOriginal, tabbedPaneInnerSplit));
  1938. }
  1939. temp = null;
  1940. }
  1941. }
  1942. private void updateUpperNodes() {
  1943. for (Component c : tabbedPaneInnerOriginal.getComponents()) {
  1944. if (!(c instanceof JScrollPane)) {
  1945. continue;
  1946. }
  1947. Component pane = ((JScrollPane) c).getViewport().getComponent(0);
  1948. if (pane instanceof UpperNodeCanvas) {
  1949. temp = model.getHashcodeMap().get(((UpperNodeCanvas) pane).code);
  1950. ((UpperNodeCanvas) pane).upperNode = (CpsUpperNode) temp;
  1951. }
  1952. }
  1953. }
  1954. /**
  1955. * Removes UpperNodeTab if UpperNode was deleted
  1956. *
  1957. * @param cps the CPS object that is currently selected
  1958. */
  1959. private void removeUpperNodeTab(AbstractCpsObject cps) {
  1960. if (cps instanceof CpsUpperNode) {
  1961. boolean splitView = false;
  1962. for (int i = 1; i < tabbedPaneInnerOriginal.getTabCount(); i++) {
  1963. JScrollPane scrollPaneOriginal = (JScrollPane) tabbedPaneInnerOriginal.getComponentAt(i);
  1964. if (scrollPaneOriginal == null) {
  1965. splitView = true;
  1966. } else if (((UpperNodeCanvas) scrollPaneOriginal.getViewport().getComponent(0)).upperNode.getId()
  1967. == cps.getId()) {
  1968. ((ButtonTabComponent) tabbedPaneInnerOriginal.getTabComponentAt(i)).removeTabs();
  1969. break;
  1970. }
  1971. }
  1972. // If SplitView is on and the view on
  1973. // tabbedPaneSplit is the deleted upperNode
  1974. if (splitView && tabbedPaneSplit.getComponentCount() > 0) {
  1975. JTabbedPane tabbedPaneInnerSplit = (JTabbedPane) tabbedPaneSplit.getComponentAt(0);
  1976. if (((UpperNodeCanvas) ((JScrollPane) tabbedPaneInnerSplit.getSelectedComponent())
  1977. .getViewport().getComponent(0)).upperNode.getId() == cps.getId()) {
  1978. ((ButtonTabComponent) tabbedPaneInnerOriginal
  1979. .getTabComponentAt(tabbedPaneInnerSplit.getSelectedIndex())).removeTabs();
  1980. }
  1981. }
  1982. }
  1983. }
  1984. private void readStatistics(JsonObject json) {
  1985. List<String> keys = json.entrySet().stream().map(i -> i.getKey())
  1986. .collect(Collectors.toCollection(ArrayList::new));
  1987. // Saved Values
  1988. JsonObject obj;
  1989. AbstractCpsObject cps;
  1990. int prop;
  1991. Color color;
  1992. StatisticGraphPanel stat = new StatisticGraphPanel(model, controller, json.get("KEY").getAsString(),
  1993. model.getGraphTable());
  1994. for (String k : keys) {
  1995. if (!k.equals("KEY")) {
  1996. obj = json.get(k).getAsJsonObject();
  1997. cps = (obj.get("ID") == JsonNull.INSTANCE ? null : controller.searchTracked(obj.get("ID").getAsInt()));
  1998. prop = obj.get("PROPERTY").getAsInt();
  1999. color = model.getGson().fromJson(obj.get("COLOR"), Color.class);
  2000. stat.addObject(new TrackedDataSet(cps, prop, color));
  2001. }
  2002. model.getGraphTable().put(json.get("KEY").getAsString(), stat);
  2003. model.getStatPanel().getGraphPanel().add(stat);
  2004. }
  2005. }
  2006. /**
  2007. * chooses whether to set the tabTemp to tabbedPaneOriginal or tabbedPaneSplit
  2008. */
  2009. private void chooseTabTemp() {
  2010. // is the uppernode on tabbedPaneOriginal or tabbedPaneSplit
  2011. if (tabbedPaneOriginal.getMousePosition() != null) {
  2012. tabTemp = tabbedPaneOriginal;
  2013. } else {
  2014. tabTemp = tabbedPaneSplit;
  2015. }
  2016. }
  2017. private JScrollPane getScrollPaneFromTabbedPane(JTabbedPane tabbedPane, int index) {
  2018. tabTemp = tabbedPane;
  2019. return getScrollPaneFromTabbedPane(index);
  2020. }
  2021. // private JScrollPane getScrollPaneFromTabbedPane(JTabbedPane tabbedPane) {
  2022. // return getScrollPaneFromTabbedPane(tabbedPane, -1);
  2023. // }
  2024. private JScrollPane getScrollPaneFromTabbedPane() {
  2025. return getScrollPaneFromTabbedPane(-1);
  2026. }
  2027. private JScrollPane getScrollPaneFromTabbedPane(int index) {
  2028. Component upperLevelSelectedComponent;
  2029. if (index == -1) {
  2030. upperLevelSelectedComponent = tabTemp.getSelectedComponent();
  2031. } else {
  2032. upperLevelSelectedComponent = tabTemp.getComponentAt(index);
  2033. }
  2034. if (upperLevelSelectedComponent instanceof JTabbedPane) {
  2035. return (JScrollPane) ((JTabbedPane) upperLevelSelectedComponent).getSelectedComponent();
  2036. } else if (upperLevelSelectedComponent instanceof JScrollPane) {
  2037. return (JScrollPane) upperLevelSelectedComponent;
  2038. } else {
  2039. return null;
  2040. }
  2041. }
  2042. private void repaintGraphAfterUndoRedo() {
  2043. for (AbstractCpsObject cps : model.getObjectsOnCanvas()) {
  2044. unitGraph.repaintGraph(cps);
  2045. }
  2046. }
  2047. /**
  2048. * if flexibility was turned on, then active needs to be turned off, the energy currently produced/consumed
  2049. *
  2050. * @param eleBTemp element that needs to be updated
  2051. * @param selectedValueBY the y value in the table
  2052. */
  2053. private void updateElementTableAfterChange(HolonElement eleBTemp, int selectedValueBY) {
  2054. model.getSingleTable().setValueAt(eleBTemp.isFlexible(), selectedValueBY, 6);
  2055. model.getSingleTable().setValueAt(eleBTemp.isActive(), selectedValueBY, 5);
  2056. model.getSingleTable().setValueAt(eleBTemp.getAmount(), selectedValueBY, 4);
  2057. model.getSingleTable().setValueAt(eleBTemp.getFlexibleEnergyAvailablePerElement(), selectedValueBY, 3);
  2058. model.getSingleTable().setValueAt(eleBTemp.getEnergyPerElement(), selectedValueBY, 2);
  2059. }
  2060. private void triggerUpdateController(AbstractCpsObject temp) {
  2061. if (temp != null) {
  2062. updCon.paintProperties(temp);
  2063. }
  2064. updCon.refreshTableHolonElement(model.getMultiTable(), model.getSingleTable());
  2065. updCon.refreshTableProperties(model.getPropertyTable());
  2066. }
  2067. /**
  2068. * Custom Mouse adapter makes contentPane gain focus once mouse leaves this component
  2069. * so copy/paste/cut and "select all" works
  2070. */
  2071. private class FocusCanvasMouseAdapter extends MouseAdapter {
  2072. @Override
  2073. public void mouseExited(MouseEvent e) {
  2074. contentPane.requestFocus();
  2075. }
  2076. }
  2077. }