GUI.java 103 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125
  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.SimulationManager;
  10. import ui.controller.UpdateController;
  11. import ui.model.Model;
  12. import ui.view.NewPopUp.Option;
  13. import javax.swing.*;
  14. import javax.swing.border.LineBorder;
  15. import javax.swing.event.AncestorEvent;
  16. import javax.swing.event.AncestorListener;
  17. import javax.swing.filechooser.FileNameExtensionFilter;
  18. import javax.swing.table.DefaultTableModel;
  19. import javax.swing.table.JTableHeader;
  20. import javax.swing.table.TableCellEditor;
  21. import javax.swing.table.TableCellRenderer;
  22. import javax.swing.tree.DefaultMutableTreeNode;
  23. import javax.swing.tree.DefaultTreeModel;
  24. import javax.swing.tree.TreeCellRenderer;
  25. import java.awt.*;
  26. import java.awt.datatransfer.UnsupportedFlavorException;
  27. import java.awt.event.*;
  28. import java.io.File;
  29. import java.io.IOException;
  30. import java.net.URI;
  31. import java.net.URISyntaxException;
  32. import java.util.ArrayList;
  33. import java.util.List;
  34. import java.util.Timer;
  35. import java.util.TimerTask;
  36. import java.util.stream.Collectors;
  37. /**
  38. * Graphical User Interface.
  39. *
  40. * @author Gruppe14
  41. */
  42. public class GUI implements CategoryListener {
  43. static final Color PALE_RED=new Color(255, 192, 192);
  44. /**
  45. * Menu on the Top containing File, Edit View Help etc
  46. */
  47. private final JMenuBar menuBar = new JMenuBar();
  48. private final JMenu mnNewMenu = new JMenu("File");
  49. private final JMenu mnNewMenuEdit = new JMenu("Edit");
  50. private final JMenu mnNewMenuOptions = new JMenu("Options");
  51. private final JMenu mnNewMenuView = new JMenu("View");
  52. private final AlgorithmMenu algorithmMenu;
  53. /** Help Menu containing helpful Informations and the AboutUs Popup */
  54. private final JMenu mnHelp = new JMenu("Help");
  55. /**
  56. * Help -> Introduction
  57. * A small Introduction of the Application, SmartGrids and Holons
  58. */
  59. private final JMenuItem mntmIntroduction = new JMenuItem("Introduction");
  60. /**
  61. * Help -> UserManual
  62. */
  63. private final JMenuItem mntmUserManual = new JMenuItem("User Manual");
  64. /** Help -> Algorithm Help Menu */
  65. private final JMenuItem mntmAlgorithmHelp = new JMenuItem("Algorithm Introduction");
  66. /** Help -> CodeDocumentation */
  67. private final JMenuItem mntmCodeDoc = new JMenuItem("Code Documentation");
  68. /** Help -> AboutUs */
  69. private final JMenuItem mntmAboutUs = new JMenuItem("About Us");
  70. private final JCheckBoxMenuItem consoleLogCheckBox = new JCheckBoxMenuItem(
  71. "Show program console log");
  72. private final JCheckBoxMenuItem useFlexibleDevicesCheckBox = new JCheckBoxMenuItem(
  73. "Automatically use flexible devices");
  74. /** checked if supplyBars should be shown */
  75. private final JCheckBoxMenuItem showSupplyBarsCheckBox = new JCheckBoxMenuItem(
  76. "Show supply bars.");
  77. private final JCheckBoxMenuItem showTooltipsCheckBox = new JCheckBoxMenuItem(
  78. "Show tooltips.");
  79. /** menu for the different fairness Models */
  80. private final JMenu mnFairnessModel = new JMenu("Fairness Model");
  81. /** press to supply minimum demand first */
  82. private final JMenuItem mntmFairMinFirst = new JMenuItem(
  83. "Minimum demand first");
  84. /** press to give everyone the same energy */
  85. private final JMenuItem mntmFairAlleEqual = new JMenuItem(
  86. "Equal supply for everyone");
  87. private final JMenuItem mntmOpen = new JMenuItem("Open");
  88. private final JMenuItem mntmNew = new JMenuItem("New");
  89. private final JMenuItem mntmSave = new JMenuItem("Save");
  90. private final JMenuItem mntmCanvasSize = new JMenuItem("View Size");
  91. private final JMenuItem mntmBackground = new JMenuItem("Background Image");
  92. private final JMenuItem mntmSplitView = new JMenuItem("Split View");
  93. private final JSplitPane splitPane = new JSplitPane();
  94. private final JSplitPane splitPane1 = new JSplitPane();
  95. private final JSplitPane splitPaneCanvasConsole = new JSplitPane(
  96. JSplitPane.VERTICAL_SPLIT);
  97. // the tabbed canvas containing the different sub-net tabs of the grid (Main
  98. // Grid + Nodes of Nodes)
  99. private final JLabel lblHint = new JLabel("To connect two Objects use SHIFT + Left Mouse Button");
  100. private final JPanel myPanel = new JPanel(new BorderLayout());
  101. private final JTabbedPane tabbedPaneInnerOriginal = new JTabbedPane(
  102. JTabbedPane.TOP);
  103. // the main canvas where we can see the grid currently displayed
  104. private final JScrollPane canvasSP = new JScrollPane();
  105. private final JScrollPane scrollPane1 = new JScrollPane();
  106. // private final JScrollPane holonSP = new JScrollPane();
  107. // the original tabbed Pane (containing tabs for view, statistics, holon,
  108. // flexibility)
  109. private final JTabbedPane tabbedPaneOriginal = new JTabbedPane(
  110. JTabbedPane.TOP);
  111. // the same tabbed Pane that appears once the view is split
  112. private final JTabbedPane tabbedPaneSplit = new JTabbedPane(JTabbedPane.TOP);
  113. private final JPopupMenu popmenuEdit = new JPopupMenu();
  114. private final JMenuItem editItem = new JMenuItem("Edit Object");
  115. private final StatisticPanel statSplitPane;
  116. private final JScrollPane statScrollPane;
  117. private final JLabel maxGraph = new JLabel("100%");
  118. private final JLabel medGraph = new JLabel("50%");
  119. private final JLabel minGraph = new JLabel("0%");
  120. private final JLabel elementGraph = new JLabel("None ");
  121. private final JLabel unitGraphLocalPeriodLbl = new JLabel("Local Period:");
  122. private final ArrayList<HolonElement> selectedElements = new ArrayList<>();
  123. private final JTree tree = new JTree();
  124. /******************************************
  125. ************* Right Container*************
  126. ******************************************
  127. * Right Container: here comes the information about the HolonObject, such
  128. * as HolonElements Information, Properties and Consumption/Production
  129. * graph.
  130. **/
  131. private final JSplitPane splitHolonElPro = new JSplitPane(
  132. JSplitPane.VERTICAL_SPLIT);
  133. private final JSplitPane splitGraphHolonEl = new JSplitPane(
  134. JSplitPane.VERTICAL_SPLIT);
  135. private final int distanceBetweenElementsAndGraph = 350;
  136. // Model for single or multi selection
  137. private final JPanel scrollElements = new JPanel();
  138. private final JScrollPane tableHolonElementScrollPane = new JScrollPane();
  139. // In this section are all the properties that correspond to the clicked
  140. // HolonObject, such as connections, name, Type, etc.
  141. // Table for Properties --> Cell with (0,1) is editable by CpsObjt and
  142. // Cell(3,1) is editable by Edges
  143. private final JTable tableProperties = new JTable() {
  144. private static final long serialVersionUID = 1L;
  145. @Override
  146. public TableCellRenderer getCellRenderer(int row, int column) {
  147. if (getValueAt(row, column) instanceof Boolean) {
  148. return super.getDefaultRenderer(Boolean.class);
  149. } else {
  150. return super.getCellRenderer(row, column);
  151. }
  152. }
  153. @Override
  154. public TableCellEditor getCellEditor(int row, int column) {
  155. if (getValueAt(row, column) instanceof Boolean) {
  156. return super.getDefaultEditor(Boolean.class);
  157. } else {
  158. return super.getCellEditor(row, column);
  159. }
  160. }
  161. };
  162. private final JPanel graphLabel = new JPanel();
  163. private final JScrollPane scrollProperties = new JScrollPane();
  164. // In this section is the graph for the selected HolonElement of the clicked
  165. // HolonObject
  166. private final JTable tableGraph = new JTable();
  167. private final DefaultTableModel tableModelGraph = new DefaultTableModel();
  168. private final JScrollPane scrollGraph = new JScrollPane();
  169. private final Model model;
  170. private final Control controller;
  171. // In this section are all the Holonelements that correspond to the clicked
  172. // HolonObject with consumption/production, name and amount.
  173. private final JPanel panel = new JPanel();
  174. private final JPanel panelHolonEl = new JPanel();
  175. private final JComboBox comboBox = new JComboBox();
  176. // Buttons
  177. private final JButton btnAdd = new JButton("New");
  178. private final JPopupMenu btnAddPopUp = new JPopupMenu("New");
  179. private final JMenuItem mItemNew = new JMenuItem("New..");
  180. private final JMenuItem mItemCategory = new JMenuItem("Category");
  181. private final JMenuItem mItemObject = new JMenuItem("Object");
  182. private final JMenuItem mItemSwitch = new JMenuItem("Switch");
  183. private final JMenuItem mItemBattery = new JMenuItem("Battery");
  184. private final JButton btnDel = new JButton("Delete");
  185. private final JButton btnAddHolEL = new JButton("New Element");
  186. private final JButton btnDelHolEL = new JButton("Delete Element");
  187. private final JButton resetGraphBtn = new JButton("Reset");
  188. private final JToolBar toolBar = new JToolBar();
  189. private final JToolBar toolBarHolonEl = new JToolBar();
  190. private final JToolBar toolBarGraph = new JToolBar();
  191. // Languages
  192. private final JMenuItem englishBtn = new JMenuItem("EN");
  193. private final JMenuItem spanishBtn = new JMenuItem("ES");
  194. private final JMenuItem germanBtn = new JMenuItem("DE");
  195. private final JMenuItem czechBtn = new JMenuItem("CZ");
  196. private final JMenuItem chineseBtn = new JMenuItem("ZH");
  197. // private final JComboBox comboBoxGraph = new JComboBox();
  198. private final Console console = new Console();
  199. private final MyCanvas canvas;
  200. private final HolonCanvas holonCanvas;
  201. private final UnitGraph unitGraph;
  202. /** Textfield to show the period of an element */
  203. private final JTextField unitGraphLocalPeriod = new JTextField(6);
  204. private final JCheckBox unitGraphStretchMode=new JCheckBox();
  205. private final JLabel unitGraphStretchModeLbl=new JLabel(" Use global: ");//Some padding
  206. private final JSplitPane splitPane3 = new JSplitPane();
  207. private final JSlider sizeSlider = new JSlider();
  208. private final JLabel lblImageSize = new JLabel(Languages.getLanguage()[94]);
  209. private final JMenuItem mntmUndo = new JMenuItem("Undo");
  210. private final JMenuItem mntmRedo = new JMenuItem("Redo");
  211. private final JMenuItem mntmEditEdges = new JMenuItem("Edge Properties");
  212. private final JMenuItem mntmFindReplace = new JMenuItem("Find/ Replace");
  213. private final JMenuItem mntmAlignAll = new JMenuItem("Align All");
  214. private final JMenuItem mntmEditShowedInformation = new JMenuItem(
  215. "Edit showed Information");
  216. private final JMenuItem mntmResetCategory = new JMenuItem(
  217. "Reset Categories");
  218. private final JMenu mnLanguage = new JMenu("Language");
  219. private final String[] columnNamesMulti = { "Object", "Nr.", "Device",
  220. "Energy", "Flexible Energy Available", "Quantity", "Activated",
  221. "Flexible" };
  222. private final String[] columnNamesSingle = { "Nr.", "Device", "Energy",
  223. "Flexible Energy Available", "Quantity", "Activated", "Flexible" };
  224. private final ArrayList<PropertyTable> tables = new ArrayList<>();
  225. private final String[] comboBoxCat = { "Category", "Object", "Switch", "Battery" };
  226. private final UpdateController updCon;
  227. private final JSplitPane splitPane_1 = new JSplitPane();
  228. private final JSlider holonBodySizeSlider = new JSlider();
  229. private final JLabel lblHolonBodySize = new JLabel("HolonBody SIze");
  230. private final JLabel lblSelectedElement = new JLabel("Selected Element: ");
  231. // for doubleclick
  232. private boolean click = false;
  233. private JFrame frmCyberPhysical;
  234. private JTabbedPane tabTemp; // tabbedPaneOriginal or tabbedPaneSplit
  235. private JSplitPane tempSplit;
  236. private boolean initSplit = true;
  237. private String catOfObjToBeEdited;
  238. private UpperNodeCanvas unc;
  239. private JPanel contentPane;
  240. private String holonEleNamesDisplayed = "None ";
  241. // Pop up Windows
  242. private AddObjectPopUp addObjectPopUP;
  243. private AboutUsPopUp aboutUsPopUp;
  244. private AddElementPopUp addElementPopUp;
  245. // variables
  246. private boolean dragging = false;
  247. private String actualObjectClicked;
  248. private Image img = null;
  249. private AbstractCpsObject tempCps = null;
  250. private int yValueElements = 0;
  251. // Time Stuff
  252. private TimePanel timePanel;
  253. // Coord for all Cells with text
  254. private int yThis;
  255. private int xThis;
  256. // Coord for all Cells with boolean values (checkbox)
  257. private int yBTis;
  258. private int xBThis;
  259. // Coord for the Edit-Modus in the PropertieTable
  260. private int yProThis;
  261. private int xProThis;
  262. private int yProThisOneClick;
  263. private int xProThisOneClick;
  264. private AbstractCpsObject temp = null;
  265. private String warningText = "Warning";
  266. private String saveBeforeNew = "Do you want to save your current data?";
  267. private String eraseCategory = "Do you really want to delete the Category ";
  268. private String selectObjBeforeErase = "Please select a Category or an Object in the left library in order to delete something.";
  269. /**
  270. * Create the application.
  271. *
  272. * @param control
  273. * the Controller
  274. */
  275. GUI(Control control) {
  276. this.controller = control;
  277. this.model = control.getModel();
  278. statSplitPane = new StatisticPanel(controller);
  279. model.addGraphListener(statSplitPane);
  280. model.setStatPanel(statSplitPane);
  281. statScrollPane = new JScrollPane(statSplitPane);
  282. this.unitGraph = new UnitGraph(model, control);
  283. this.canvas = new MyCanvas(model, control, unitGraph);
  284. this.holonCanvas = new HolonCanvas(model, control);
  285. control.initListener(this);
  286. controller.setCanvas(canvas);
  287. model.setConsole(console);
  288. model.setTableProperties(tableProperties);
  289. algorithmMenu = new AlgorithmMenu(model, control, this);
  290. initialize();
  291. updateCategories(model.getCategories());
  292. updCon = new UpdateController(model, controller);
  293. }
  294. // /**
  295. // * Adds a Popup.
  296. // *
  297. // * @param component Component
  298. // * @param popup PopupMenu
  299. // */
  300. // private static void addPopup(Component component, final JPopupMenu popup)
  301. // {
  302. // component.addMouseListener(new MouseAdapter() {
  303. // public void mousePressed(MouseEvent e) {
  304. // if (e.isPopupTrigger()) {
  305. // showMenu(e);
  306. // }
  307. // }
  308. //
  309. // public void mouseReleased(MouseEvent e) {
  310. // if (e.isPopupTrigger()) {
  311. // showMenu(e);
  312. // }
  313. // }
  314. //
  315. // private void showMenu(MouseEvent e) {
  316. // popup.show(e.getComponent(), e.getX(), e.getY());
  317. // }
  318. //
  319. // });
  320. // }
  321. /**
  322. * Initialize the contents of the frame.
  323. */
  324. @SuppressWarnings({ "serial", "unchecked" })
  325. private void initialize() {
  326. frmCyberPhysical = new JFrame();
  327. frmCyberPhysical.setTitle("HOLEG Simulator");
  328. // try to restore old position/dimensions
  329. ArrayList<Integer> savedWindowDim = controller
  330. .loadSavedWindowDimensionsIfExistent();
  331. if (savedWindowDim.size() == 4) {
  332. frmCyberPhysical.setBounds(savedWindowDim.get(0),
  333. savedWindowDim.get(1), savedWindowDim.get(2),
  334. savedWindowDim.get(3));
  335. }
  336. // if the upper part of the window is showing, the windows can still be
  337. // moved,
  338. // but if it is not, we need to move it to somewhere else
  339. if (savedWindowDim.size() != 4 || !isUpperPanelInsideBounds()) {
  340. frmCyberPhysical.setBounds(100, 100, 1000, 800);
  341. frmCyberPhysical.setExtendedState(JFrame.MAXIMIZED_BOTH);
  342. }
  343. frmCyberPhysical.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
  344. frmCyberPhysical.addWindowListener(new java.awt.event.WindowAdapter() {
  345. @Override
  346. public void windowClosing(java.awt.event.WindowEvent windowEvent) {
  347. if (JOptionPane.showConfirmDialog(frmCyberPhysical,
  348. Languages.getLanguage()[88],
  349. "Cyber Physical Systems Model",
  350. JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE) == JOptionPane.YES_OPTION) {
  351. controller.deleteDirectory(new File(System
  352. .getProperty("user.home")
  353. + "/.config/HolonGUI/Autosave"));
  354. // try to save the position and size of the window, such
  355. // that (if possible)
  356. // it can be opened in the same position the next time
  357. try {
  358. controller.savePosAndSizeOfWindow(
  359. frmCyberPhysical.getX(),
  360. frmCyberPhysical.getY(),
  361. frmCyberPhysical.getWidth(),
  362. frmCyberPhysical.getHeight());
  363. } catch (Exception e) {
  364. e.printStackTrace();
  365. }
  366. System.exit(0);
  367. }
  368. }
  369. });
  370. contentPane = (JPanel) frmCyberPhysical.getContentPane();
  371. int condition = JComponent.WHEN_IN_FOCUSED_WINDOW;
  372. InputMap inputMap = contentPane.getInputMap(condition);
  373. ActionMap actionMap = contentPane.getActionMap();
  374. String cntrlZDown = "controlZ";
  375. inputMap.put(KeyStroke.getKeyStroke("control Z"), cntrlZDown);
  376. actionMap.put(cntrlZDown, new AbstractAction() {
  377. private static final long serialVersionUID = 1L;
  378. @Override
  379. public void actionPerformed(ActionEvent e) {
  380. try {
  381. controller.loadAutoSave(controller.getUndoSave());
  382. controller.calculateStateForCurrentTimeStep();
  383. canvas.repaint();
  384. unitGraph.update(model.getObjectsOnCanvas());
  385. updateUpperNodes();
  386. } catch (IOException eex) {
  387. eex.printStackTrace();
  388. }
  389. }
  390. });
  391. String cntrlYDown = "controlY";
  392. inputMap.put(KeyStroke.getKeyStroke("control Y"), cntrlYDown);
  393. actionMap.put(cntrlYDown, new AbstractAction() {
  394. private static final long serialVersionUID = 1L;
  395. @Override
  396. public void actionPerformed(ActionEvent e) {
  397. try {
  398. controller.loadAutoSave(controller.getRedoSave());
  399. controller.calculateStateForCurrentTimeStep();
  400. canvas.repaint();
  401. unitGraph.update(model.getObjectsOnCanvas());
  402. updateUpperNodes();
  403. } catch (IOException ex) {
  404. ex.printStackTrace();
  405. }
  406. }
  407. });
  408. String cntrlADown = "controlA";
  409. inputMap.put(KeyStroke.getKeyStroke("control A"), cntrlADown);
  410. AbstractAction controlA = new AbstractAction() {
  411. private static final long serialVersionUID = 1L;
  412. @Override
  413. public void actionPerformed(ActionEvent e) {
  414. chooseTabTemp();
  415. model.getSelectedCpsObjects().clear();
  416. // Uppernode Canvas?
  417. JScrollPane scrollPane = getScrollPaneFromTabbedPane();
  418. Component canvasOrUpperNodeCanvas = scrollPane.getViewport()
  419. .getComponent(0);
  420. if (canvasOrUpperNodeCanvas instanceof UpperNodeCanvas) {
  421. UpperNodeCanvas uNC = (UpperNodeCanvas) canvasOrUpperNodeCanvas;
  422. for (AbstractCpsObject cps : uNC.upperNode.getNodes()) {
  423. controller.addSelectedObject(cps);
  424. }
  425. uNC.repaint();
  426. // or Canvas?
  427. } else if (canvasOrUpperNodeCanvas instanceof MyCanvas) {
  428. for (AbstractCpsObject cps : model.getObjectsOnCanvas()) {
  429. controller.addSelectedObject(cps);
  430. }
  431. canvas.repaint();
  432. }
  433. controller.getObjectsInDepth();
  434. }
  435. };
  436. actionMap.put(cntrlADown, controlA);
  437. String delDown = "delete";
  438. inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0, false),
  439. delDown);
  440. actionMap.put(delDown, new AbstractAction() {
  441. private static final long serialVersionUID = 1L;
  442. @Override
  443. public void actionPerformed(ActionEvent e) {
  444. chooseTabTemp();
  445. // Uppernode Canvas?
  446. JScrollPane scrollPane = getScrollPaneFromTabbedPane();
  447. Component canvasOrUpperNodeCanvas = scrollPane.getViewport()
  448. .getComponent(0);
  449. // check whether a producer was deleted (this triggers a
  450. // complete re-evaluation of the net)
  451. boolean wasProducerDeleted = false;
  452. if (canvasOrUpperNodeCanvas instanceof UpperNodeCanvas) {
  453. UpperNodeCanvas uNC = (UpperNodeCanvas) canvasOrUpperNodeCanvas;
  454. for (AbstractCpsObject cps : model.getSelectedCpsObjects()) {
  455. if (cps instanceof HolonObject
  456. && ((HolonObject) cps).getState() == HolonObject.PRODUCER) {
  457. wasProducerDeleted = true;
  458. }
  459. controller.removeTrackingObj(cps);
  460. if (uNC.upperNode.getNodes().contains(cps)) {
  461. controller.delObjUpperNode(cps, uNC.upperNode);
  462. unc.setToolTip(false);
  463. // remove UpperNodeTab if UpperNode deleted
  464. removeUpperNodeTab(cps);
  465. }
  466. }
  467. uNC.repaint();
  468. // or Canvas?
  469. } else if (canvasOrUpperNodeCanvas instanceof MyCanvas) {
  470. boolean save = false;
  471. // Edge Deleting
  472. CpsEdge edgeHighlight = model.getSelectedEdge();
  473. if (edgeHighlight != null) {
  474. controller.removeEdgesOnCanvas(edgeHighlight);
  475. // Look for a CPSNode with no Connections and delete
  476. // them
  477. if (edgeHighlight.getA().getClass() == CpsNode.class
  478. && edgeHighlight.getA().getConnections().size() == 0) {
  479. controller.delCanvasObject(edgeHighlight.getA(),
  480. false);
  481. }
  482. if (edgeHighlight.getB().getClass() == CpsNode.class
  483. && edgeHighlight.getB().getConnections().size() == 0) { // Look
  484. // on
  485. // the
  486. // other
  487. // end
  488. // of
  489. // the
  490. // cable
  491. controller.delCanvasObject(edgeHighlight.getB(),
  492. false);
  493. }
  494. ((MyCanvas) canvasOrUpperNodeCanvas).edgeHighlight = null;
  495. }
  496. for (int j = 0; j < model.getSelectedCpsObjects().size(); j++) {
  497. AbstractCpsObject cps = model.getSelectedCpsObjects()
  498. .get(j);
  499. if (cps instanceof HolonObject
  500. && ((HolonObject) cps).getState() == HolonObject.PRODUCER) {
  501. wasProducerDeleted = true;
  502. }
  503. controller.removeTrackingObj(cps);
  504. if (j < model.getSelectedCpsObjects().size() - 1)
  505. save = true;
  506. controller.delCanvasObject(cps, save);
  507. canvas.setToolTip(false);
  508. // remove UpperNodeTab if UpperNode deleted
  509. removeUpperNodeTab(cps);
  510. }
  511. canvas.repaint();
  512. }
  513. // recalculate net if a producer was deleted
  514. if (wasProducerDeleted) {
  515. controller.resetSimulation();
  516. controller.calculateStateForCurrentTimeStep();
  517. }
  518. model.getSelectedCpsObjects().clear();
  519. hideScrollGraph();
  520. }
  521. });
  522. String cntrlFDown = "controlF";
  523. inputMap.put(KeyStroke.getKeyStroke("control F"), cntrlFDown);
  524. actionMap.put(cntrlFDown, new AbstractAction() {
  525. private static final long serialVersionUID = 1L;
  526. @Override
  527. public void actionPerformed(ActionEvent e) {
  528. SearchPopUp dialog = new SearchPopUp(controller, canvas,
  529. frmCyberPhysical);
  530. dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
  531. dialog.setVisible(true);
  532. }
  533. });
  534. String cntrlCDown = "controlC";
  535. inputMap.put(KeyStroke.getKeyStroke("control C"), cntrlCDown);
  536. AbstractAction controlC = new AbstractAction() {
  537. private static final long serialVersionUID = 1L;
  538. @Override
  539. public void actionPerformed(ActionEvent e) {
  540. chooseTabTemp();
  541. JScrollPane scrollPane = getScrollPaneFromTabbedPane();
  542. if (!model.getSelectedCpsObjects().isEmpty()) {
  543. if (scrollPane.getViewport().getComponent(0) instanceof UpperNodeCanvas)
  544. controller.copy(((UpperNodeCanvas) scrollPane
  545. .getViewport().getComponent(0)).upperNode);
  546. else
  547. controller.copy(null);
  548. if (!model.getClipboradObjects().isEmpty()) {
  549. canvas.itemPaste.setEnabled(true);
  550. }
  551. }
  552. }
  553. };
  554. actionMap.put(cntrlCDown, controlC);
  555. String cntrlVDown = "controlV";
  556. inputMap.put(KeyStroke.getKeyStroke("control V"), cntrlVDown);
  557. AbstractAction controlV = new AbstractAction() {
  558. private static final long serialVersionUID = 1L;
  559. @Override
  560. public void actionPerformed(ActionEvent e) {
  561. try {
  562. tabTemp = null;
  563. if (tabbedPaneOriginal.getMousePosition() != null) {
  564. tabTemp = tabbedPaneOriginal;
  565. } else {
  566. if (!initSplit) {
  567. tabTemp = tabbedPaneSplit;
  568. }
  569. }
  570. if(tabTemp == null)return;
  571. JScrollPane scrollPane = getScrollPaneFromTabbedPane();
  572. Component canvasOrUpperNodeCanvas = scrollPane
  573. .getViewport().getComponent(0);
  574. if (tabTemp != null
  575. && canvasOrUpperNodeCanvas instanceof UpperNodeCanvas) {
  576. controller
  577. .paste(((UpperNodeCanvas) canvasOrUpperNodeCanvas).upperNode,
  578. canvasOrUpperNodeCanvas
  579. .getMousePosition());
  580. unitGraph.update(model.getSelectedCpsObjects());
  581. controller.calculateStateForCurrentTimeStep();
  582. scrollPane.getViewport().getComponent(0).repaint();
  583. } else {
  584. controller.paste(null, canvas.getMousePosition());
  585. unitGraph.update(model.getSelectedCpsObjects());
  586. controller.calculateStateForCurrentTimeStep();
  587. canvas.repaint();
  588. }
  589. } catch (HeadlessException | JsonParseException
  590. | UnsupportedFlavorException | IOException e1) {
  591. JLabel message = new JLabel(
  592. "The Clipboard information cannot be pasted into Application.");
  593. JOptionPane.showMessageDialog(frmCyberPhysical, message,
  594. "", JOptionPane.ERROR_MESSAGE);
  595. }
  596. }
  597. };
  598. actionMap.put(cntrlVDown, controlV);
  599. String cntrlXDown = "controlX";
  600. inputMap.put(KeyStroke.getKeyStroke("control X"), cntrlXDown);
  601. AbstractAction controlX = new AbstractAction() {
  602. private static final long serialVersionUID = 1L;
  603. @Override
  604. public void actionPerformed(ActionEvent e) {
  605. chooseTabTemp();
  606. JScrollPane scrollPane = getScrollPaneFromTabbedPane();
  607. if (!model.getSelectedCpsObjects().isEmpty()) {
  608. if (scrollPane.getViewport().getComponent(0) instanceof UpperNodeCanvas) {
  609. controller.cut(((UpperNodeCanvas) scrollPane
  610. .getViewport().getComponent(0)).upperNode);
  611. controller.calculateStateForCurrentTimeStep();
  612. scrollPane.getViewport().getComponent(0).repaint();
  613. } else {
  614. controller.cut(null);
  615. controller.calculateStateForCurrentTimeStep();
  616. canvas.repaint();
  617. }
  618. if (!model.getClipboradObjects().isEmpty()) {
  619. canvas.itemPaste.setEnabled(true);
  620. }
  621. }
  622. }
  623. };
  624. actionMap.put(cntrlXDown, controlX);
  625. frmCyberPhysical.setJMenuBar(menuBar);
  626. frmCyberPhysical.setIconImage(Util.loadImage(this,
  627. "/Images/Holeg.png", 30, 30));
  628. menuBar.add(mnNewMenu);
  629. mnNewMenu.add(mntmNew);
  630. mnNewMenu.add(mntmOpen);
  631. mnNewMenu.add(mntmSave);
  632. menuBar.add(mnNewMenuEdit);
  633. mnNewMenuEdit.add(mntmUndo);
  634. mnNewMenuEdit.add(mntmRedo);
  635. mnLanguage.add(englishBtn);
  636. englishBtn.setIcon(new ImageIcon(new ImageIcon(
  637. "res/Button_Images/FlagEN.png").getImage().getScaledInstance(
  638. 20, 20, java.awt.Image.SCALE_SMOOTH)));
  639. mnLanguage.add(spanishBtn);
  640. spanishBtn.setIcon(new ImageIcon(new ImageIcon(
  641. "res/Button_Images/FlagES.png").getImage().getScaledInstance(
  642. 20, 20, java.awt.Image.SCALE_SMOOTH)));
  643. mnLanguage.add(germanBtn);
  644. germanBtn.setIcon(new ImageIcon(new ImageIcon(
  645. "res/Button_Images/FlagDE.png").getImage().getScaledInstance(
  646. 20, 20, java.awt.Image.SCALE_SMOOTH)));
  647. // mnLanguage.add(czechBtn);
  648. // czechBtn.setIcon(new ImageIcon(new
  649. // ImageIcon("res/Button_Images/FlagCZ.png").getImage().getScaledInstance(20,
  650. // 20, java.awt.Image.SCALE_SMOOTH)));
  651. mnLanguage.add(chineseBtn);
  652. chineseBtn.setIcon(new ImageIcon(new ImageIcon(
  653. "res/Button_Images/FlagZH.png").getImage().getScaledInstance(
  654. 20, 20, java.awt.Image.SCALE_SMOOTH)));
  655. mntmFindReplace.addActionListener(actionEvent -> {
  656. try {
  657. SearchPopUp dialog = new SearchPopUp(controller, canvas,
  658. frmCyberPhysical);
  659. dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
  660. dialog.setVisible(true);
  661. controller.getObjectsInDepth();
  662. } catch (Exception ex) {
  663. ex.printStackTrace();
  664. }
  665. });
  666. mnNewMenuEdit.add(mntmFindReplace);
  667. mntmEditShowedInformation
  668. .addActionListener(actionEvent -> {
  669. try {
  670. DisplayedInformationPopUp dialog = new DisplayedInformationPopUp(
  671. canvas, contentPane, controller,
  672. frmCyberPhysical);
  673. dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
  674. dialog.setVisible(true);
  675. } catch (Exception ex) {
  676. ex.printStackTrace();
  677. }
  678. });
  679. mnNewMenuEdit.add(mntmEditShowedInformation);
  680. mnNewMenuEdit.add(mntmEditEdges);
  681. mntmEditEdges.addActionListener(actionEvent -> {
  682. EditEdgesPopUp edgePopUp = new EditEdgesPopUp(frmCyberPhysical);
  683. edgePopUp.setCanvas(canvas);
  684. edgePopUp.setController(controller);
  685. edgePopUp.setVisible(true);
  686. });
  687. //Edit -> Align All
  688. mnNewMenuEdit.add(mntmAlignAll);
  689. mntmAlignAll.addActionListener(actionEvent -> {
  690. // getScrollPaneFromTabbedPane().getViewport().getComponent(0) is always the active canvas
  691. AbstractCanvas activeCanvas = ((AbstractCanvas) getScrollPaneFromTabbedPane().getViewport().getComponent(0));
  692. if (activeCanvas != null) {
  693. activeCanvas.tryToAlignObjects();
  694. activeCanvas.repaint();
  695. }
  696. });
  697. menuBar.add(mnNewMenuOptions);
  698. mnNewMenuOptions.add(mntmResetCategory);
  699. mntmResetCategory.addActionListener(actionEvent -> {
  700. ArrayList<Category> cat = model.getCategories();
  701. try {
  702. while (!cat.isEmpty()) {
  703. controller.deleteCategory(cat.get(0).getName());
  704. }
  705. controller.resetCategorys();
  706. } catch (Exception e2) {
  707. }
  708. tree.repaint();
  709. });
  710. mnNewMenuOptions.add(consoleLogCheckBox);
  711. consoleLogCheckBox.setSelected(true);
  712. consoleLogCheckBox.addActionListener(arg0 -> controller
  713. .setShowConsoleLog(consoleLogCheckBox.isSelected()));
  714. mnNewMenuOptions.add(useFlexibleDevicesCheckBox);
  715. useFlexibleDevicesCheckBox.setSelected(true);
  716. useFlexibleDevicesCheckBox
  717. .addActionListener(actionEvent -> model
  718. .setUseFlexibleDevices(useFlexibleDevicesCheckBox
  719. .isSelected()));
  720. /**
  721. * Add Fairness Model Option to the option Menu
  722. */
  723. mnNewMenuOptions.add(mnFairnessModel);
  724. mnFairnessModel.add(mntmFairMinFirst);
  725. mntmFairMinFirst.setForeground(Color.BLUE);
  726. mntmFairMinFirst
  727. .setToolTipText("HolonObjects with the smallest mininum Demand will be partially supplied first.\n"
  728. + "After that as many HolonObjects as possible will get fully supplied.");
  729. mntmFairMinFirst
  730. .addActionListener(arg0 -> {
  731. controller
  732. .setFairnessModel(SimulationManager.fairnessMininumDemandFirst);
  733. mntmFairMinFirst.setForeground(Color.BLUE);
  734. mntmFairAlleEqual.setForeground(mnFairnessModel
  735. .getForeground());
  736. controller.calculateStateForCurrentTimeStep();
  737. // Update UpperNodes
  738. Component canvasOrUpperNodeCanvas = getScrollPaneFromTabbedPane()
  739. .getViewport().getComponent(0);
  740. if (canvasOrUpperNodeCanvas != null
  741. && canvasOrUpperNodeCanvas instanceof UpperNodeCanvas) {
  742. ((UpperNodeCanvas) canvasOrUpperNodeCanvas).repaint();
  743. }
  744. });
  745. mnFairnessModel.add(mntmFairAlleEqual);
  746. mntmFairAlleEqual
  747. .setToolTipText("HolonObjects will all get the same amount of energy.");
  748. mntmFairAlleEqual.addActionListener(arg0 -> {
  749. controller.setFairnessModel(SimulationManager.fairnessAllEqual);
  750. mntmFairAlleEqual.setForeground(Color.BLUE);
  751. mntmFairMinFirst.setForeground(mnFairnessModel.getForeground());
  752. controller.calculateStateForCurrentTimeStep();
  753. // Update UpperNodes
  754. Component canvasOrUpperNodeCanvas = getScrollPaneFromTabbedPane()
  755. .getViewport().getComponent(0);
  756. if (canvasOrUpperNodeCanvas != null
  757. && canvasOrUpperNodeCanvas instanceof UpperNodeCanvas) {
  758. ((UpperNodeCanvas) canvasOrUpperNodeCanvas).repaint();
  759. }
  760. });
  761. menuBar.add(mnNewMenuView);
  762. mnNewMenuView.add(mntmCanvasSize);
  763. mntmCanvasSize.addActionListener(actionEvent -> {
  764. CanvasResizePopUp popUp = new CanvasResizePopUp(model, controller,
  765. canvas, tabbedPaneOriginal, tabbedPaneSplit,
  766. frmCyberPhysical);
  767. popUp.setVisible(true);
  768. });
  769. mnNewMenuView.add(splitPane3);
  770. sizeSlider.setMinimum(15);
  771. sizeSlider.setMaximum(115);
  772. sizeSlider
  773. .addChangeListener(changeEvent -> {
  774. controller.setScale(sizeSlider.getValue());
  775. JScrollPane scrollPane = getScrollPaneFromTabbedPane();
  776. if (scrollPane.getViewport().getComponent(0) instanceof UpperNodeCanvas) {
  777. scrollPane.getViewport().getComponent(0).repaint();
  778. } else {
  779. canvas.repaint();
  780. }
  781. if (!initSplit
  782. && scrollPane.getViewport().getComponent(0) instanceof UpperNodeCanvas) {
  783. scrollPane.getViewport().getComponent(0).repaint();
  784. } else {
  785. canvas.repaint();
  786. }
  787. });
  788. mnNewMenuView.add(mntmCanvasSize);
  789. mnNewMenuView.add(mntmSplitView);
  790. /*
  791. * Adds Checkbox to turn supply bars on/off
  792. */
  793. mnNewMenuView.add(showSupplyBarsCheckBox);
  794. showSupplyBarsCheckBox.setSelected(true);
  795. showSupplyBarsCheckBox.addActionListener(arg0 -> {
  796. controller.setShowSupplyBars(showSupplyBarsCheckBox.isSelected());
  797. canvas.repaint();
  798. // Update UpperNodes
  799. Component canvasOrUpperNodeCanvas = getScrollPaneFromTabbedPane()
  800. .getViewport().getComponent(0);
  801. if (canvasOrUpperNodeCanvas != null
  802. && canvasOrUpperNodeCanvas instanceof UpperNodeCanvas) {
  803. ((UpperNodeCanvas) canvasOrUpperNodeCanvas).repaint();
  804. }
  805. });
  806. mnNewMenuView.add(showTooltipsCheckBox);
  807. showTooltipsCheckBox.setSelected(true);
  808. showTooltipsCheckBox.addActionListener(arg0 -> {
  809. showHint(showTooltipsCheckBox.isSelected());
  810. });
  811. // Split View
  812. mntmSplitView
  813. .addActionListener(actionEvent -> {
  814. if (splitPaneCanvasConsole.getLeftComponent() instanceof JSplitPane) {
  815. initSplit = true;
  816. Component tempC = tabbedPaneSplit
  817. .getSelectedComponent();
  818. tabbedPaneOriginal.setComponentAt(
  819. tabbedPaneSplit.getSelectedIndex(), tempC);
  820. tabbedPaneSplit.removeAll();
  821. splitPaneCanvasConsole
  822. .setLeftComponent(tabbedPaneOriginal);
  823. } else {
  824. for (int i = 0; i < tabbedPaneOriginal.getTabCount(); i++) {
  825. // add outer tabs
  826. // (inner tabs are added by tabbedPaneSplit
  827. // changelistener)
  828. tabbedPaneSplit.addTab(
  829. tabbedPaneOriginal.getTitleAt(i), null);
  830. }
  831. if (tabbedPaneOriginal.getSelectedComponent() == statScrollPane) {
  832. tabbedPaneOriginal.setComponentAt(0, null);
  833. tabbedPaneSplit.setComponentAt(0, canvasSP);
  834. tabbedPaneSplit.setSelectedIndex(0);
  835. } else {
  836. tabbedPaneOriginal.setComponentAt(1, null);
  837. tabbedPaneSplit.setComponentAt(1, statScrollPane);
  838. tabbedPaneSplit.setSelectedIndex(1);
  839. }
  840. tempSplit = new JSplitPane();
  841. tempSplit.setBorder(null);
  842. tempSplit.setRightComponent(tabbedPaneSplit);
  843. tempSplit.setLeftComponent(tabbedPaneOriginal);
  844. tempSplit.setDividerLocation(tabbedPaneOriginal
  845. .getWidth() / 2);
  846. tempSplit.setResizeWeight(0.9);
  847. splitPaneCanvasConsole.setLeftComponent(tempSplit);
  848. initSplit = false;
  849. }
  850. contentPane.updateUI();
  851. });
  852. mnNewMenuView.add(mntmBackground);
  853. mntmBackground
  854. .addActionListener(actionEvent -> {
  855. tabTemp = tabbedPaneOriginal;
  856. JScrollPane scrollPane = getScrollPaneFromTabbedPane();
  857. if (scrollPane.getViewport().getComponent(0) instanceof MyCanvas) {
  858. BackgroundPopUp backgroundDialog = new BackgroundPopUp(
  859. model, controller, canvas, null,
  860. frmCyberPhysical);
  861. backgroundDialog
  862. .setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
  863. backgroundDialog.setVisible(true);
  864. } else if (scrollPane.getViewport().getComponent(0) instanceof UpperNodeCanvas) {
  865. UpperNodeCanvas uNodeCanvas = (UpperNodeCanvas) (scrollPane
  866. .getViewport().getComponent(0));
  867. BackgroundPopUp backgroundDialog = new BackgroundPopUp(
  868. model, controller, null, uNodeCanvas.upperNode,
  869. frmCyberPhysical);
  870. backgroundDialog
  871. .setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
  872. backgroundDialog.setVisible(true);
  873. uNodeCanvas.repaint();
  874. }
  875. });
  876. splitPane3.setRightComponent(sizeSlider);
  877. splitPane3.setLeftComponent(lblImageSize);
  878. mnNewMenuView.add(splitPane_1);
  879. holonBodySizeSlider.setValue(100);
  880. holonBodySizeSlider.setMinimum(1);
  881. holonBodySizeSlider.addChangeListener(changeEvent -> {
  882. controller.setHolonBodyScale(holonBodySizeSlider.getValue());
  883. tree.setRowHeight(50);
  884. canvas.repaint();
  885. });
  886. splitPane_1.setRightComponent(holonBodySizeSlider);
  887. splitPane_1.setLeftComponent(lblHolonBodySize);
  888. menuBar.add(algorithmMenu);
  889. /**
  890. * add Help Menu and its items
  891. */
  892. menuBar.add(mnHelp);
  893. mnHelp.add(mntmIntroduction);
  894. mnHelp.add(mntmUserManual);
  895. mnHelp.add(mntmAlgorithmHelp);
  896. mnHelp.add(mntmCodeDoc);
  897. mnHelp.add(mntmAboutUs);
  898. tabbedPaneOriginal.addChangeListener(changeEvent -> {
  899. if (tabbedPaneOriginal.getSelectedComponent() == null) {
  900. Component tempC = tabbedPaneSplit.getSelectedComponent();
  901. tabbedPaneSplit.setComponentAt(
  902. tabbedPaneOriginal.getSelectedIndex(), null);
  903. tabbedPaneOriginal.setComponentAt(
  904. tabbedPaneOriginal.getSelectedIndex(), tempC);
  905. tempC = tabbedPaneOriginal.getComponentAt((tabbedPaneOriginal
  906. .getSelectedIndex() + 1)
  907. % (tabbedPaneOriginal.getTabCount()));
  908. tabbedPaneOriginal.setComponentAt(
  909. (tabbedPaneOriginal.getSelectedIndex() + 1)
  910. % (tabbedPaneOriginal.getTabCount()), null);
  911. tabbedPaneSplit.setComponentAt(
  912. (tabbedPaneOriginal.getSelectedIndex() + 1)
  913. % (tabbedPaneOriginal.getTabCount()), tempC);
  914. tabbedPaneSplit.setSelectedIndex((tabbedPaneOriginal
  915. .getSelectedIndex() + 1)
  916. % (tabbedPaneOriginal.getTabCount()));
  917. contentPane.updateUI();
  918. }
  919. });
  920. tabbedPaneSplit.addChangeListener(changeEvent -> {
  921. if (tabbedPaneSplit.getSelectedComponent() == null && !initSplit) {
  922. Component tempC = tabbedPaneOriginal
  923. .getComponentAt(tabbedPaneSplit.getSelectedIndex());
  924. tabbedPaneOriginal.setComponentAt(
  925. tabbedPaneSplit.getSelectedIndex(), null);
  926. tabbedPaneSplit.setComponentAt(
  927. tabbedPaneSplit.getSelectedIndex(), tempC);
  928. for (int i = 0; i < tabbedPaneOriginal.getTabCount(); i++) {
  929. if (tabbedPaneSplit.getComponentAt(i) != null
  930. && tabbedPaneSplit.getComponentAt(i) != tempC) {
  931. tempC = tabbedPaneSplit.getComponentAt(i);
  932. tabbedPaneSplit.setComponentAt(i, null);
  933. tabbedPaneOriginal.setComponentAt(i, tempC);
  934. break;
  935. }
  936. }
  937. if (tabbedPaneOriginal.getSelectedIndex() == tabbedPaneSplit
  938. .getSelectedIndex()) {
  939. tabbedPaneOriginal.setSelectedIndex((tabbedPaneSplit
  940. .getSelectedIndex() + 1)
  941. % tabbedPaneOriginal.getTabCount());
  942. }
  943. contentPane.updateUI();
  944. }
  945. });
  946. mnNewMenuOptions.add(mnLanguage);
  947. canvas.setBackground(Color.WHITE);
  948. canvas.setPreferredSize(new Dimension(model.getCanvasX(), model
  949. .getCanvasY()));
  950. holonCanvas.setBackground(Color.WHITE);
  951. holonCanvas.setPreferredSize(new Dimension(model.getCanvasX(), model
  952. .getCanvasY()));
  953. /********************
  954. * RIGHT CONTAINER (INFORMATION)
  955. **********************/
  956. // Set up of the HolonElements section
  957. // Two different Models: Multi for multi-selection mode and Single for
  958. // single-selection mode (CPS-Object)
  959. model.getMultiTable().setColumnIdentifiers(columnNamesMulti);
  960. model.getSingleTable().setColumnIdentifiers(columnNamesSingle);
  961. model.getTableHolonElement().setBorder(null);
  962. model.getTableHolonElement().setFillsViewportHeight(true);
  963. model.getTableHolonElement().setCellSelectionEnabled(true);
  964. model.getTableHolonElement().setColumnSelectionAllowed(true);
  965. /*
  966. * Register Clicks on ColumNames for sorting:
  967. */
  968. model.getTableHolonElement().getTableHeader()
  969. .addMouseListener(new MouseAdapter() {
  970. public void mouseClicked(MouseEvent e) {
  971. //TODO: sort
  972. //clicked column
  973. int col = model.getTableHolonElement().columnAtPoint(
  974. e.getPoint());
  975. //insert column into UpdateController
  976. updCon.setSortBy(col);
  977. //refresh HolonElementTable
  978. updCon.refreshTableHolonElement(model.getMultiTable(), model.getSingleTable());
  979. }
  980. @Override
  981. public void mouseExited(MouseEvent e) {
  982. /**
  983. * Stop Editing, if mouse exits the Table
  984. */
  985. JTable holElem = model.getTableHolonElement();
  986. JTableHeader holElemHead = holElem.getTableHeader();
  987. if(e.getX()<=0 || e.getX()>=holElemHead.getWidth()
  988. || e.getY() <= 0){
  989. CellEditor cellEditor = holElem.getCellEditor();
  990. if (cellEditor != null) {
  991. if (cellEditor.getCellEditorValue() != null) {
  992. /** TODO: Maybe try to save current Data */
  993. cellEditor.stopCellEditing();
  994. } else {
  995. cellEditor.cancelCellEditing();
  996. }
  997. }
  998. }
  999. }
  1000. });
  1001. model.getTableHolonElement().getTableHeader().setReorderingAllowed(false);
  1002. tableHolonElementScrollPane.setViewportView(model
  1003. .getTableHolonElement());
  1004. scrollElements.setLayout(new BorderLayout(0, 0));
  1005. scrollElements.add(panelHolonEl, BorderLayout.NORTH);
  1006. scrollElements.add(tableHolonElementScrollPane);
  1007. panelHolonEl.setLayout(new BoxLayout(panelHolonEl, BoxLayout.X_AXIS));
  1008. toolBarHolonEl.add(btnAddHolEL);
  1009. toolBarHolonEl.add(btnDelHolEL);
  1010. toolBarHolonEl.setFloatable(false);
  1011. panelHolonEl.add(toolBarHolonEl);
  1012. // Set up of the Properties section
  1013. tableProperties.setModel(model.getPropertyTable());
  1014. tableProperties.setFillsViewportHeight(true);
  1015. tableProperties.setCellSelectionEnabled(true);
  1016. tableProperties.setColumnSelectionAllowed(true);
  1017. scrollProperties.setViewportView(tableProperties);
  1018. // Set up of the Graph section
  1019. tableGraph.setModel(tableModelGraph);
  1020. tableGraph.setFillsViewportHeight(true);
  1021. tableGraph.setCellSelectionEnabled(true);
  1022. tableGraph.setColumnSelectionAllowed(true);
  1023. scrollGraph.setViewportView(unitGraph);
  1024. graphLabel.setLayout(new BorderLayout(0, 10));
  1025. graphLabel.add(maxGraph, BorderLayout.NORTH);
  1026. graphLabel.add(medGraph, BorderLayout.CENTER);
  1027. graphLabel.add(minGraph, BorderLayout.SOUTH);
  1028. GridBagLayout gbl=new GridBagLayout();
  1029. toolBarGraph.setLayout(gbl);
  1030. GridBagConstraints c=new GridBagConstraints();
  1031. c.weightx=0;
  1032. gbl.setConstraints(lblSelectedElement, c);
  1033. //TODO here
  1034. toolBarGraph.add(lblSelectedElement);
  1035. c.gridwidth=GridBagConstraints.REMAINDER;
  1036. gbl.setConstraints(elementGraph, c);
  1037. toolBarGraph.add(elementGraph/*, BorderLayout.AFTER_LINE_ENDS*/);//TODO
  1038. //Component horizontalStrut = Box.createHorizontalStrut(20);
  1039. /*
  1040. Component horizontalStrut = Box.createHorizontalStrut(toolBarGraph
  1041. .getWidth() - resetGraphBtn.getWidth() - unitGraphLocalPeriod.getWidth()
  1042. -unitGraphLocalPeriodLbl.getWidth());
  1043. */
  1044. //toolBarGraph.add(horizontalStrut);//What is this for?
  1045. /** Add local Graph length Textfield an Label */
  1046. unitGraphLocalPeriod.setPreferredSize(new Dimension(30, 20));//TODO
  1047. unitGraphLocalPeriod.setText(""+unitGraph.getLocalPeriod());
  1048. c.gridwidth=GridBagConstraints.NORTHWEST;
  1049. gbl.setConstraints(unitGraphLocalPeriodLbl, c);
  1050. toolBarGraph.add(unitGraphLocalPeriodLbl);//TODO
  1051. //unitGraphLocalPeriodLbl.setHorizontalAlignment(SwingConstants.RIGHT);
  1052. gbl.setConstraints(unitGraphLocalPeriod, c);
  1053. toolBarGraph.add(unitGraphLocalPeriod);//TODO
  1054. gbl.setConstraints(unitGraphStretchModeLbl, c);
  1055. toolBarGraph.add(unitGraphStretchModeLbl);//TODO
  1056. //unitGraphStretchModeLbl.setHorizontalAlignment(SwingConstants.RIGHT);
  1057. gbl.setConstraints(unitGraphStretchMode, c);
  1058. toolBarGraph.add(unitGraphStretchMode);//TODO
  1059. //unitGraphStretchMode.setHorizontalAlignment(SwingConstants.RIGHT);
  1060. gbl.setConstraints(resetGraphBtn, c);
  1061. //resetGraphBtn.setHorizontalAlignment(SwingConstants.RIGHT);
  1062. toolBarGraph.add(resetGraphBtn);//TODO
  1063. unitGraphStretchMode.addActionListener(e ->
  1064. {unitGraph.setStretching(unitGraphStretchMode.isSelected());}
  1065. );
  1066. toolBarGraph.setFloatable(false);
  1067. scrollGraph.setRowHeaderView(graphLabel);
  1068. scrollGraph.setColumnHeaderView(toolBarGraph);
  1069. tables.add(model.getSingleTable());
  1070. tables.add(model.getMultiTable());
  1071. /***********************
  1072. * HolonElement Table Actions
  1073. **********************/
  1074. /*
  1075. * Add HolonElement to given HolonObject
  1076. */
  1077. btnAddHolEL.addActionListener(actionEvent -> {
  1078. if (model.getSelectedCpsObjects().size() == 1) {
  1079. AbstractCpsObject tempCpsObject = updCon.getActualCps();
  1080. if (tempCpsObject != null
  1081. && tempCpsObject.getClass() == HolonObject.class
  1082. && tempCpsObject.getId() != 0) {
  1083. addElementPopUp = new AddElementPopUp(frmCyberPhysical, model);//TODO: I didn't even check
  1084. addElementPopUp.setActualCps(updCon.getActualCps());
  1085. addElementPopUp.setVisible(true);
  1086. HolonElement ele = addElementPopUp.getElement();
  1087. if (ele != null) {
  1088. controller.addElementCanvasObject(
  1089. tempCpsObject.getId(), ele.getEleName(),
  1090. ele.getAmount(), ele.getEnergyPerElement(),
  1091. ele.getId());
  1092. }
  1093. controller.calculateStateForTimeStep(model
  1094. .getCurIteration());
  1095. triggerUpdateController(null);
  1096. contentPane.updateUI();
  1097. }
  1098. }else
  1099. {
  1100. JOptionPane.showMessageDialog(contentPane, "No object selected.\nPlease select a object first." , "Message" , JOptionPane.INFORMATION_MESSAGE);
  1101. }
  1102. });
  1103. /*
  1104. * Delete the chosen HolonElement of the selected HolonObject,
  1105. * Multi-Selection for CpsObjects as well as for HolonElements possible
  1106. */
  1107. btnDelHolEL.addActionListener(actionEvent -> {
  1108. // For Single Selection of CpsObject
  1109. if (model.getSelectedCpsObjects().size() == 1) {
  1110. if (updCon.getActualCps().getClass() == HolonObject.class) {
  1111. HolonObject obj = (HolonObject) updCon.getActualCps();
  1112. if(selectedElements.isEmpty())
  1113. {
  1114. JOptionPane.showMessageDialog(contentPane, "No element selectet.\nPlease select a element in the list first." , "Message" , JOptionPane.INFORMATION_MESSAGE);
  1115. }
  1116. for (HolonElement e : selectedElements) {
  1117. controller.deleteElementCanvas(obj.getId(),
  1118. e.getId());
  1119. controller.calculateStateForTimeStep(model
  1120. .getCurIteration());
  1121. triggerUpdateController(null);
  1122. contentPane.updateUI();
  1123. // Names displayed in graph are not updated
  1124. }
  1125. model.getEleToDelete().clear();
  1126. selectedElements.clear();
  1127. }
  1128. // For MultiSelection of CpsObject
  1129. } else if (model.getSelectedCpsObjects().size() > 1) {
  1130. for (Integer i : model.getEleToDelete().keySet()) {
  1131. for (HolonElement e : model.getEleToDelete().get(i)) {
  1132. controller.deleteElementCanvas(i, e.getId());
  1133. }
  1134. }
  1135. triggerUpdateController(null);
  1136. model.getEleToDelete().clear();
  1137. selectedElements.clear();
  1138. }else
  1139. {
  1140. JOptionPane.showMessageDialog(contentPane, "No object selectet.\nPlease select a object first." , "No object selectet" , JOptionPane.INFORMATION_MESSAGE);
  1141. }
  1142. triggerUpdateController(null);
  1143. elementGraph.setText(Languages.getLanguage()[25]);
  1144. holonEleNamesDisplayed = Languages.getLanguage()[25];
  1145. }) ;
  1146. /*
  1147. * Communication between HolonElement Table and displayed Graph and
  1148. * Properties, as well as selection of different HolonElements
  1149. */
  1150. model.getTableHolonElement().addMouseListener(new MouseAdapter() {
  1151. public void mousePressed(MouseEvent e) {
  1152. HolonObject obj = null;
  1153. if (model.getSelectedCpsObjects().size() == 1
  1154. && model.getSelectedCpsObjects().get(0) instanceof HolonObject) {
  1155. obj = (HolonObject) updCon.getActualCps();
  1156. }
  1157. yValueElements = e.getY();
  1158. HolonElement ele;
  1159. // Search for current clicked HolonElement
  1160. if (model.getSelectedCpsObjects().size() == 1) {
  1161. ele = updCon.getActualHolonElement(obj, yValueElements, 0,
  1162. tables);
  1163. } else {
  1164. ele = updCon.getActualHolonElement(null, yValueElements, 0,
  1165. tables);
  1166. }
  1167. // Multi-Selection of HolonElements through control button +
  1168. // mouse click
  1169. if (ele != null) {
  1170. // make energy-consumption graph visible
  1171. showScrollGraph();
  1172. if (e.isControlDown()) {
  1173. if (!selectedElements.contains(ele)) {
  1174. selectedElements.add(ele);
  1175. if (!holonEleNamesDisplayed.equals(Languages
  1176. .getLanguage()[25])) {
  1177. holonEleNamesDisplayed = holonEleNamesDisplayed
  1178. + "; " + ele.getEleName() + " ";
  1179. } else {
  1180. holonEleNamesDisplayed = ele.getEleName() + " ";
  1181. }
  1182. repaintGraphAux(selectedElements);
  1183. }
  1184. updCon.getActualHolonElement(null, yValueElements, 2,
  1185. tables);
  1186. }
  1187. // if no control-button pressed but a HolonElement chosen
  1188. else {
  1189. selectedElements.clear();
  1190. selectedElements.add(ele);
  1191. updCon.getActualHolonElement(null, yValueElements, 1,
  1192. tables);
  1193. holonEleNamesDisplayed = ele.getEleName() + " ";
  1194. repaintGraphAux(selectedElements);
  1195. }
  1196. } else {
  1197. elementGraph.setText(Languages.getLanguage()[25]);
  1198. hideScrollGraph();
  1199. }
  1200. // if any HolonElement is double-clicked --> Edit-Mode started
  1201. // for selected HolonElement
  1202. if (e.getClickCount() == 2) {
  1203. yThis = e.getY();
  1204. xThis = e.getX();
  1205. }
  1206. // for single click and empty slot
  1207. if (e.getClickCount() == 1 && ele == null) {
  1208. selectedElements.clear();
  1209. holonEleNamesDisplayed = Languages.getLanguage()[25];
  1210. }
  1211. elementGraph.setText(holonEleNamesDisplayed);
  1212. yBTis = e.getY();
  1213. xBThis = e.getX();
  1214. }
  1215. @Override
  1216. public void mouseExited(MouseEvent e) {
  1217. /**
  1218. * Stop Editing, if mouse exits the Table
  1219. */
  1220. JTable holElem = model.getTableHolonElement();
  1221. if(e.getX()<=0 || e.getX()>=holElem.getWidth()
  1222. /*|| e.getY() <= 0*/|| e.getY()>= holElem.getHeight()){
  1223. CellEditor cellEditor = holElem.getCellEditor();
  1224. if (cellEditor != null) {
  1225. if (cellEditor.getCellEditorValue() != null) {
  1226. /** TODO: Maybe try to save current Data */
  1227. cellEditor.stopCellEditing();
  1228. } else {
  1229. cellEditor.cancelCellEditing();
  1230. }
  1231. }
  1232. }
  1233. }
  1234. });
  1235. /*
  1236. * Triggered every time a change is made
  1237. */
  1238. model.getTableHolonElement()
  1239. .addPropertyChangeListener(propertyChangeEvent -> {
  1240. try {
  1241. int yMouse = yThis;
  1242. int yBMouse = yBTis;
  1243. int selectedValueY = (int) Math.floor(yMouse / 16);
  1244. int selectedValueBY = (int) Math.floor(yBMouse / 16);
  1245. // ------------------ multi-selection mode
  1246. // ------------------
  1247. if (model.getSelectedCpsObjects().size() > 1) {
  1248. int selectedValueX = (int) Math
  1249. .floor(xThis
  1250. / (model.getTableHolonElement()
  1251. .getWidth() / 8));
  1252. int selectedValueBX = (int) Math
  1253. .floor(xBThis
  1254. / (model.getTableHolonElement()
  1255. .getWidth() / 8));
  1256. if (updCon.getHolonObj(yMouse,
  1257. model.getMultiTable()) != null) {
  1258. // For active column (boolean with a checkbox)
  1259. if (selectedValueBX == 6) {
  1260. HolonElement eleBTemp = updCon
  1261. .getActualHolonElement(null,
  1262. yBMouse, 0, tables);
  1263. String newBStuff = model
  1264. .getMultiTable()
  1265. .getValueAt(selectedValueBY,
  1266. selectedValueBX).toString();
  1267. Boolean bTemp = Boolean
  1268. .parseBoolean(newBStuff);
  1269. eleBTemp.setActive(bTemp);
  1270. }
  1271. // For activeFlex column (boolean with a
  1272. // checkbox)
  1273. else if (selectedValueBX == 7) {
  1274. HolonElement eleBTemp = updCon
  1275. .getActualHolonElement(null,
  1276. yBMouse, 0, tables);
  1277. String newBStuff = model
  1278. .getMultiTable()
  1279. .getValueAt(selectedValueBY,
  1280. selectedValueBX).toString();
  1281. Boolean bTemp = Boolean
  1282. .parseBoolean(newBStuff);
  1283. eleBTemp.setFlexible(bTemp);
  1284. } else {
  1285. // Update of HolonElement
  1286. HolonElement eleTemp = updCon
  1287. .getActualHolonElement(null,
  1288. yMouse, 0, tables);
  1289. String newStuff = model
  1290. .getMultiTable()
  1291. .getValueAt(selectedValueY,
  1292. selectedValueX).toString();
  1293. // Name update
  1294. if (selectedValueX == 2) {
  1295. eleTemp.setEleName(newStuff);
  1296. }
  1297. // Energy Update
  1298. else if (selectedValueX == 3) {
  1299. Float ftemp = Float
  1300. .parseFloat(newStuff);
  1301. eleTemp.setEnergyPerElement(ftemp);
  1302. }
  1303. // Flexibility
  1304. else if (selectedValueX == 4) {
  1305. Float ftemp = Float
  1306. .parseFloat(newStuff);
  1307. eleTemp.setFlexibleEnergyAvailable(ftemp);
  1308. }
  1309. // Amount of Elements update
  1310. else if (selectedValueX == 5) {
  1311. Integer iTemp = Integer
  1312. .parseInt(newStuff);
  1313. eleTemp.setAmount(iTemp);
  1314. }
  1315. }
  1316. }
  1317. } // ------------------ single-selection mode
  1318. // ------------------
  1319. else if (model.getSelectedCpsObjects().size() == 1) {
  1320. int selectedValueX = (int) Math
  1321. .floor(xThis
  1322. / (model.getTableHolonElement()
  1323. .getWidth() / 7));
  1324. int selectedValueBX = (int) Math
  1325. .floor(xBThis
  1326. / (model.getTableHolonElement()
  1327. .getWidth() / 7));
  1328. if (updCon.getActualCps() != null
  1329. && updCon.getActualCps().getClass() == HolonObject.class) {
  1330. HolonElement eleTemp;
  1331. // For active column (boolean with a checkbox)
  1332. if (selectedValueBX == 5) {
  1333. eleTemp = updCon.getActualHolonElement(
  1334. (HolonObject) updCon.getActualCps(),
  1335. yBMouse, 0, tables);
  1336. String newBStuff = model
  1337. .getSingleTable()
  1338. .getValueAt(selectedValueBY,
  1339. selectedValueBX).toString();
  1340. Boolean bTemp = Boolean
  1341. .parseBoolean(newBStuff);
  1342. eleTemp.setActive(bTemp);
  1343. } // For activeFlex column (boolean with a
  1344. // checkbox)
  1345. else if (selectedValueBX == 6) {
  1346. eleTemp = updCon.getActualHolonElement(
  1347. (HolonObject) updCon.getActualCps(),
  1348. yBMouse, 0, tables);
  1349. String newBStuff = model
  1350. .getSingleTable()
  1351. .getValueAt(selectedValueBY,
  1352. selectedValueBX).toString();
  1353. Boolean bTemp = Boolean
  1354. .parseBoolean(newBStuff);
  1355. eleTemp.setFlexible(bTemp);
  1356. } else {
  1357. // Update of HolonElement
  1358. eleTemp = updCon.getActualHolonElement(
  1359. (HolonObject) updCon.getActualCps(),
  1360. yMouse, 0, tables);
  1361. String newStuff = model
  1362. .getSingleTable()
  1363. .getValueAt(selectedValueY,
  1364. selectedValueX).toString();
  1365. // Name update
  1366. if (selectedValueX == 1) {
  1367. eleTemp.setEleName(newStuff);
  1368. } // Energy Update
  1369. else if (selectedValueX == 2) {
  1370. Float ftemp = Float
  1371. .parseFloat(newStuff);
  1372. eleTemp.setEnergyPerElement(ftemp);
  1373. } // Flexibility
  1374. else if (selectedValueX == 3) {
  1375. Float ftemp = Float
  1376. .parseFloat(newStuff);
  1377. eleTemp.setFlexibleEnergyAvailable(ftemp);
  1378. // if this is a flexible device and the
  1379. // flexibly available energy was
  1380. // changed,
  1381. // set used energy to 0, so that it can
  1382. // be computed anew
  1383. if (eleTemp.isFlexible()) {
  1384. eleTemp.setEnergyPerElement(0);
  1385. }
  1386. }
  1387. // Amount of Elements update
  1388. else if (selectedValueX == 4) {
  1389. Integer iTemp = Integer
  1390. .parseInt(newStuff);
  1391. eleTemp.setAmount(iTemp);
  1392. }
  1393. }
  1394. // set all cells anew, if anything was changed
  1395. updateElementTableAfterChange(eleTemp,
  1396. selectedValueBY);
  1397. }
  1398. }
  1399. controller.calculateStateForTimeStep(model
  1400. .getCurIteration());
  1401. model.getSingleTable().fireTableDataChanged();
  1402. triggerUpdateController(null);
  1403. contentPane.updateUI();
  1404. unitGraph.repaint();
  1405. // trigger update of table after UnitGraph was painted
  1406. SwingUtilities.invokeLater(() -> {
  1407. triggerUpdateController(null);
  1408. });
  1409. } catch (Exception e) {
  1410. }
  1411. });
  1412. /***********************
  1413. * HolonElement Properties Actions
  1414. **********************/
  1415. /*
  1416. * Update of the mouse coord for Edit-Mode
  1417. */
  1418. tableProperties.addMouseListener(new MouseAdapter() {
  1419. public void mousePressed(MouseEvent e) {
  1420. if (e.getClickCount() == 2) {
  1421. yProThis = e.getY();
  1422. xProThis = e.getX();
  1423. }
  1424. yProThisOneClick = e.getY();
  1425. xProThisOneClick = e.getX();
  1426. }
  1427. });
  1428. /*
  1429. * Update any change in the Property table
  1430. */
  1431. tableProperties.addPropertyChangeListener(propertyChangeEvent -> {
  1432. try {
  1433. Object temp;
  1434. Object btemp;
  1435. int selValueY = (int) Math.floor(yProThis / 16);
  1436. int selValueX = (int) Math.floor(xProThis
  1437. / (tableProperties.getWidth() / 2));
  1438. int selValueYBool = (int) Math.floor(yProThisOneClick / 16);
  1439. int selValueXBool = (int) Math.floor(xProThisOneClick
  1440. / (tableProperties.getWidth() / 2));
  1441. if (updCon.getActualCps() != null) {
  1442. temp = model.getPropertyTable().getValueAt(selValueY,
  1443. selValueX);
  1444. btemp = model.getPropertyTable().getValueAt(selValueYBool,
  1445. selValueXBool);
  1446. // Case: Switch selected
  1447. if (updCon.getActualCps() instanceof HolonSwitch) {
  1448. if (selValueY == 0 && selValueX != 0) {
  1449. updCon.getActualCps().setName(temp.toString());
  1450. }
  1451. if (selValueYBool == 2) {
  1452. Boolean bbTemp = Boolean.parseBoolean(btemp.toString());
  1453. ((HolonSwitch) updCon.getActualCps())
  1454. .setManualMode(bbTemp);
  1455. if (bbTemp) {
  1456. model.getPropertyTable()
  1457. .setCellEditable(3, 1, true);
  1458. } else {
  1459. model.getPropertyTable().setCellEditable(3, 1,
  1460. false);
  1461. }
  1462. } else if (selValueYBool == 3) {
  1463. if (((HolonSwitch) updCon.getActualCps())
  1464. .getManualMode()) {
  1465. model.getPropertyTable()
  1466. .setCellEditable(3, 1, true);
  1467. Boolean bTemp = Boolean.parseBoolean(btemp
  1468. .toString());
  1469. ((HolonSwitch) updCon.getActualCps())
  1470. .setManualState(bTemp);
  1471. }
  1472. }
  1473. } // Case: UpperNode selected
  1474. else if (updCon.getActualCps() instanceof CpsUpperNode
  1475. && selValueX != 0) {
  1476. // Name edition through double click
  1477. updCon.getActualCps().setName(temp.toString());
  1478. // Update of name on the tab in the tab section
  1479. for (int index = 4; index < tabbedPaneOriginal
  1480. .getTabCount(); index++) {
  1481. tabTemp = tabbedPaneOriginal;
  1482. JScrollPane scrollPane = getScrollPaneFromTabbedPane();
  1483. UpperNodeCanvas unc = ((UpperNodeCanvas) scrollPane
  1484. .getViewport().getComponent(0));
  1485. if (unc.upperNode.getId() == updCon.getActualCps()
  1486. .getId()) {
  1487. tabbedPaneOriginal.setTitleAt(index,
  1488. unc.upperNode.getName());
  1489. tabbedPaneOriginal.updateUI();
  1490. if (!initSplit) {
  1491. tabbedPaneSplit.setTitleAt(index,
  1492. unc.upperNode.getName());
  1493. tabbedPaneSplit.updateUI();
  1494. }
  1495. }
  1496. }
  1497. } // Case: HolonObject is selected
  1498. else if (updCon.getActualCps() instanceof HolonObject
  1499. && selValueX != 0) {
  1500. // Name edition through double click
  1501. updCon.getActualCps().setName(temp.toString());
  1502. }
  1503. } // Case: Edge is selected
  1504. else {
  1505. temp = model.getPropertyTable()
  1506. .getValueAt(selValueY, selValueX);
  1507. btemp = model.getPropertyTable().getValueAt(selValueYBool,
  1508. selValueXBool);
  1509. // Edit modus for capacity by double clicking
  1510. if (selValueY == 2) {
  1511. Float ftemp;
  1512. if (Float.parseFloat(temp.toString()) >= 0.0) {
  1513. ftemp = Float.parseFloat(temp.toString());
  1514. } else {
  1515. ftemp = model.getSelectedEdge().getCapacity();
  1516. }
  1517. model.getSelectedEdge().setCapacity(ftemp);
  1518. }
  1519. // Status edition through a check box
  1520. if (selValueYBool == 3) {
  1521. Boolean bbTemp = Boolean.parseBoolean(btemp.toString());
  1522. model.getSelectedEdge().setWorkingState(bbTemp);
  1523. }
  1524. }
  1525. canvas.repaint();
  1526. } catch (Exception e) {
  1527. }
  1528. }) ;
  1529. /***********************
  1530. * HolonElement Graph Actions
  1531. **********************/
  1532. /*
  1533. * Reset the graph of the selected HolonElement
  1534. */
  1535. resetGraphBtn.setBorder(new LineBorder(Color.BLACK));
  1536. resetGraphBtn.addActionListener(actionEvent -> unitGraph.reset());
  1537. /*
  1538. * Update Local Period of an Element Graph
  1539. */
  1540. unitGraphLocalPeriod.addKeyListener(new KeyAdapter() {
  1541. @Override
  1542. public void keyReleased(KeyEvent e) {
  1543. try{
  1544. int localLength = Integer.parseInt(unitGraphLocalPeriod.getText());
  1545. unitGraphLocalPeriod.setBackground(Color.WHITE);
  1546. /**
  1547. * set local graph Period
  1548. */
  1549. if(e.getKeyCode() == KeyEvent.VK_ENTER)
  1550. unitGraph.setLocalPeriod(localLength);
  1551. }catch(Exception ex){
  1552. unitGraphLocalPeriod.setBackground(Color.RED);
  1553. }
  1554. }
  1555. });
  1556. /*****************************
  1557. * RIGHT CONTAINER DONE
  1558. *****************************/
  1559. frmCyberPhysical.getContentPane().setLayout(new BorderLayout(0, 0));
  1560. /****************
  1561. * Tree Stuff
  1562. ****************/
  1563. // Override Key Actions
  1564. inputMap = tree.getInputMap();
  1565. inputMap.put(KeyStroke.getKeyStroke("control C"), cntrlCDown);
  1566. inputMap.put(KeyStroke.getKeyStroke("control V"), cntrlVDown);
  1567. inputMap.put(KeyStroke.getKeyStroke("control X"), cntrlXDown);
  1568. inputMap.put(KeyStroke.getKeyStroke("control A"), cntrlADown);
  1569. TreeCellRenderer customRenderer = new TreeCellRenderer() {
  1570. @Override
  1571. public Component getTreeCellRendererComponent(JTree tree,
  1572. Object value, boolean selected, boolean expanded,
  1573. boolean leaf, int row, boolean hasFocus) {
  1574. JLabel label = new JLabel();
  1575. Image imgR;
  1576. if (leaf) {
  1577. for (Category cat : model.getCategories()) {
  1578. for (AbstractCpsObject cps : cat.getObjects()) {
  1579. if (value.toString().compareTo(cps.getObjName()) == 0) {
  1580. imgR = Util.loadImage(this, cps.getImage(), 50,
  1581. 50);
  1582. if (imgR != null) {
  1583. label.setIcon(new ImageIcon(imgR));
  1584. }
  1585. label.setText(cps.getName());
  1586. }
  1587. }
  1588. }
  1589. }
  1590. tree.setRowHeight(50);
  1591. if (hasFocus) {
  1592. label.setForeground(new Color(0, 0, 255));
  1593. label.setOpaque(true);
  1594. }
  1595. if (label.getText().length() == 0) {
  1596. label.setText(value.toString());
  1597. if (value.toString().compareTo("Categories") != 0) {
  1598. label.setIcon(new ImageIcon(Util.loadImage(this,
  1599. "/Images/folder.png")));
  1600. }
  1601. }
  1602. return label;
  1603. }
  1604. };
  1605. tree.setCellRenderer(customRenderer);
  1606. tree.addMouseMotionListener(new MouseMotionAdapter() {
  1607. public void mouseDragged(MouseEvent e){
  1608. checkForDragAndDrop(e);
  1609. }
  1610. /**
  1611. * checks if an object of the current Panel
  1612. * could be replaced by the dragged object
  1613. * @param e
  1614. */
  1615. private void checkForDragAndDrop(MouseEvent e){
  1616. try {
  1617. /**
  1618. * if no object gets dragged -> finished
  1619. */
  1620. if(!dragging)return;
  1621. /**
  1622. * select the current Panel
  1623. */
  1624. chooseTabTemp();
  1625. JScrollPane scrollPane = getScrollPaneFromTabbedPane();
  1626. if(scrollPane == null)return;
  1627. Component canvasOrUpperNodeCanvas = scrollPane
  1628. .getViewport().getComponent(0);
  1629. /**
  1630. * check for replacements on the canvas
  1631. */
  1632. if (canvasOrUpperNodeCanvas instanceof UpperNodeCanvas) {
  1633. UpperNodeCanvas unc = (UpperNodeCanvas) canvasOrUpperNodeCanvas;
  1634. if(unc.getMousePosition()==null)return;
  1635. int x = (int) unc.getMousePosition().getX()+16;
  1636. int y = (int) unc.getMousePosition().getY()+16;
  1637. /**
  1638. * if in upperNode
  1639. */
  1640. if (x <= unc.upperNode.getLeftBorder()) return;
  1641. /**
  1642. * check for replacement
  1643. */
  1644. unc.checkForReplacement(x, y);
  1645. /**
  1646. * repaint
  1647. */
  1648. unc.invalidate();
  1649. unc.repaint();
  1650. } else {
  1651. if(canvas.getMousePosition()==null)return;
  1652. int x = (int) canvas.getMousePosition().getX()+16;
  1653. int y = (int) canvas.getMousePosition().getY()+16;
  1654. /**
  1655. * check for replacement
  1656. */
  1657. canvas.checkForReplacement(x, y);
  1658. /**
  1659. * repaint
  1660. */
  1661. canvas.invalidate();
  1662. canvas.repaint();
  1663. }
  1664. contentPane.updateUI();
  1665. } catch (Exception eex) {
  1666. eex.printStackTrace();
  1667. }
  1668. }});
  1669. tree.addMouseListener(new MouseAdapter() {
  1670. public void mouseReleased(MouseEvent e) {
  1671. try {
  1672. if (dragging) {
  1673. chooseTabTemp();
  1674. JScrollPane scrollPane = getScrollPaneFromTabbedPane();
  1675. Component canvasOrUpperNodeCanvas = scrollPane
  1676. .getViewport().getComponent(0);
  1677. if (canvasOrUpperNodeCanvas instanceof UpperNodeCanvas) {
  1678. UpperNodeCanvas unc = (UpperNodeCanvas) canvasOrUpperNodeCanvas;
  1679. int x = (int) unc.getMousePosition().getX() + 16;
  1680. int y = (int) unc.getMousePosition().getY() + 16;
  1681. if (x > unc.upperNode.getLeftBorder()) {
  1682. AbstractCpsObject h = null;
  1683. if (tempCps instanceof HolonObject) {
  1684. h = new HolonObject(tempCps);
  1685. }
  1686. if (tempCps instanceof HolonSwitch) {
  1687. h = new HolonSwitch(tempCps);
  1688. }
  1689. if (tempCps instanceof HolonTransformer) {
  1690. h = new HolonTransformer(tempCps);
  1691. }
  1692. if (tempCps instanceof HolonBattery)
  1693. {
  1694. h = new HolonBattery(tempCps);
  1695. }
  1696. h.setPosition(x, y);
  1697. /**
  1698. * close UpperNodeTabs of replaced UpperNode
  1699. */
  1700. if(unc.mayBeReplaced!=null &&unc.mayBeReplaced instanceof CpsUpperNode){
  1701. unc.closeUpperNodeTab(unc.mayBeReplaced.getId());
  1702. }
  1703. controller.addObjUpperNode(h, unc.upperNode);
  1704. /**
  1705. * object would be replaced
  1706. */
  1707. unc.mayBeReplaced = null;
  1708. unc.invalidate();
  1709. unc.repaint();
  1710. unc.setXY((int) canvas.getMousePosition()
  1711. .getX(), (int) canvas
  1712. .getMousePosition().getY());
  1713. }
  1714. } else {
  1715. int x = (int) canvas.getMousePosition().getX() + 16;
  1716. int y = (int) canvas.getMousePosition().getY() + 16;
  1717. AbstractCpsObject h = null;
  1718. if (tempCps instanceof HolonObject) {
  1719. h = new HolonObject(tempCps);
  1720. }
  1721. if (tempCps instanceof HolonSwitch) {
  1722. h = new HolonSwitch(tempCps);
  1723. }
  1724. if (tempCps instanceof HolonTransformer) {
  1725. h = new HolonTransformer(tempCps);
  1726. }
  1727. if (tempCps instanceof HolonBattery)
  1728. {
  1729. h = new HolonBattery(tempCps);
  1730. }
  1731. h.setPosition(x, y);
  1732. /**
  1733. * close UpperNodeTabs of replaced UpperNode
  1734. */
  1735. if(canvas.mayBeReplaced!=null &&canvas.mayBeReplaced instanceof CpsUpperNode){
  1736. canvas.closeUpperNodeTab(canvas.mayBeReplaced.getId());
  1737. }
  1738. controller.addObjectCanvas(h);
  1739. /**
  1740. * no object should get replaced
  1741. */
  1742. canvas.mayBeReplaced = null;
  1743. canvas.invalidate();
  1744. canvas.setXY(
  1745. (int) canvas.getMousePosition().getX(),
  1746. (int) canvas.getMousePosition().getY());
  1747. canvas.repaint();
  1748. }
  1749. controller.calculateStateForCurrentTimeStep();
  1750. contentPane.updateUI();
  1751. dragging = false;
  1752. }
  1753. } catch (Exception eex) {
  1754. }
  1755. frmCyberPhysical.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
  1756. }
  1757. });
  1758. popmenuEdit.add(editItem);
  1759. editItem.setEnabled(false);
  1760. editItem.addActionListener(actionEvent -> {
  1761. });
  1762. tree.addMouseListener(new MouseAdapter() {
  1763. public void mousePressed(MouseEvent e) {
  1764. try {
  1765. actualObjectClicked = tree
  1766. .getPathForLocation(e.getX(), e.getY())
  1767. .getLastPathComponent().toString();
  1768. // if an Object was selected, the porperties are shown in
  1769. // the table
  1770. DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) tree
  1771. .getPathForLocation(e.getX(), e.getY())
  1772. .getLastPathComponent();
  1773. if (selectedNode.getLevel() == 2) {
  1774. controller.searchCategoryObject(selectedNode
  1775. .getParent().toString(), selectedNode
  1776. .toString());
  1777. updCon.deleteRows(model.getSingleTable());
  1778. updCon.deleteRows(model.getMultiTable());
  1779. // if (selected instanceof HolonObject && selected !=
  1780. // null) {
  1781. // selected = (HolonObject) selected;
  1782. // fillElementTable(((HolonObject)
  1783. // selected).getElements());
  1784. // }
  1785. }
  1786. if (SwingUtilities.isRightMouseButton(e)) {
  1787. for (Category cat : model.getCategories()) {
  1788. for (AbstractCpsObject cps : cat.getObjects()) {
  1789. if (actualObjectClicked.compareTo(cps
  1790. .getObjName()) == 0
  1791. && !(cps instanceof HolonSwitch)) {
  1792. editItem.setEnabled(true);
  1793. popmenuEdit.show(e.getComponent(),
  1794. e.getX(), e.getY());
  1795. catOfObjToBeEdited = selectedNode
  1796. .getParent().toString();
  1797. tempCps = cps;
  1798. }
  1799. }
  1800. }
  1801. } else {
  1802. for (Category cat : model.getCategories()) {
  1803. for (AbstractCpsObject cps : cat.getObjects()) {
  1804. if (actualObjectClicked.compareTo(cps
  1805. .getObjName()) == 0) {
  1806. File checkPath = new File(cps.getImage());
  1807. if (checkPath.exists()) {
  1808. img = new ImageIcon(cps.getImage())
  1809. .getImage()
  1810. .getScaledInstance(
  1811. 32,
  1812. 32,
  1813. java.awt.Image.SCALE_SMOOTH);
  1814. } else {
  1815. img = Util.loadImage(this,
  1816. cps.getImage(), 32, 32);
  1817. }
  1818. tempCps = cps;
  1819. dragging = true;
  1820. Cursor cursor = Toolkit.getDefaultToolkit()
  1821. .createCustomCursor(img,
  1822. new Point(0, 0), "Image");
  1823. frmCyberPhysical.setCursor(cursor);
  1824. }
  1825. }
  1826. }
  1827. }
  1828. } catch (Exception eex) {
  1829. }
  1830. }
  1831. });
  1832. editItem.addActionListener(actionEvent -> {
  1833. // Remove the selected Object object
  1834. //AddObjectPopUp(boolean edit, AbstractCpsObject obj, String cat, JFrame parentFrame)
  1835. addObjectPopUP = new AddObjectPopUp(true, tempCps,
  1836. catOfObjToBeEdited, frmCyberPhysical);
  1837. addObjectPopUP.setCategory(catOfObjToBeEdited);
  1838. addObjectPopUP.setController(controller);
  1839. addObjectPopUP.setVisible(true);
  1840. });
  1841. scrollPane1.setViewportView(tree);
  1842. scrollPane1.setColumnHeaderView(panel);
  1843. panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
  1844. toolBar.setAlignmentX(Component.LEFT_ALIGNMENT);
  1845. toolBar.setFloatable(false);
  1846. panel.add(toolBar);
  1847. comboBox.setMaximumSize(new Dimension(100, 20));
  1848. //toolBar.add(comboBox);
  1849. //comboBox.setModel(new DefaultComboBoxModel(comboBoxCat));
  1850. // Add Buttonnew DefaultComboBoxModel(comboBoxCat)
  1851. //TODO: Add functionalyty
  1852. btnAddPopUp.add(mItemNew);
  1853. mItemNew.addActionListener(actionEvent -> {
  1854. new NewPopUp(controller, frmCyberPhysical);
  1855. });
  1856. btnAddPopUp.addSeparator();
  1857. btnAddPopUp.add(mItemCategory);
  1858. mItemCategory.addActionListener(actionEvent -> {
  1859. new NewPopUp(controller,Option.Category, frmCyberPhysical);
  1860. });
  1861. btnAddPopUp.add(mItemObject);
  1862. mItemObject.addActionListener(actionEvent -> {
  1863. new NewPopUp(controller,Option.Object, frmCyberPhysical);
  1864. });
  1865. btnAddPopUp.add(mItemSwitch);
  1866. mItemSwitch.addActionListener(actionEvent -> {
  1867. new NewPopUp(controller,Option.Switch, frmCyberPhysical);
  1868. });
  1869. btnAddPopUp.add(mItemBattery);
  1870. mItemBattery.addActionListener(actionEvent -> {
  1871. new NewPopUp(controller,Option.Battery, frmCyberPhysical);
  1872. });
  1873. btnAdd.addActionListener(actionEvent -> btnAddPopUp.show(btnAdd, 0, 0));
  1874. toolBar.add(btnAdd);
  1875. /**
  1876. * Help Menu Action Listeners
  1877. */
  1878. /**
  1879. * URL of the telecommunication git Wiki
  1880. */
  1881. String tkWikiWebpage = "https://git.tk.informatik.tu-darmstadt.de/carlos.garcia/praktikum-holons/wiki/";
  1882. /** open Introduction Web Page */
  1883. mntmIntroduction.addMouseListener(new MouseAdapter() {
  1884. @Override
  1885. public void mousePressed(MouseEvent e){
  1886. openWebpage(tkWikiWebpage + "Introduction+V2.1");
  1887. }
  1888. });
  1889. /** open UserManual WebPage */
  1890. mntmUserManual.addMouseListener(new MouseAdapter() {
  1891. @Override
  1892. public void mousePressed(MouseEvent e){
  1893. openWebpage(tkWikiWebpage + "User+Manual+V2.1");
  1894. }
  1895. });
  1896. /** open Algorithm Help Web Page*/
  1897. mntmAlgorithmHelp.addMouseListener(new MouseAdapter() {
  1898. @Override
  1899. public void mousePressed(MouseEvent e){
  1900. openWebpage(tkWikiWebpage + "Algorithms+V2.1");
  1901. }
  1902. });
  1903. /** open Code Documentation Web Page */
  1904. mntmCodeDoc.addMouseListener(new MouseAdapter() {
  1905. @Override
  1906. public void mousePressed(MouseEvent e){
  1907. openWebpage(tkWikiWebpage + "Code+documentation+V2.1");
  1908. }
  1909. });
  1910. /**
  1911. * Pop up - About Us with some important information about the
  1912. * developers, source and programming stuff
  1913. */
  1914. mntmAboutUs.addMouseListener(new MouseAdapter() {
  1915. @Override
  1916. public void mousePressed(MouseEvent e) {
  1917. aboutUsPopUp = new AboutUsPopUp(frmCyberPhysical);
  1918. aboutUsPopUp.setVisible(true);
  1919. }
  1920. });
  1921. /**
  1922. * Update of every interaction between the user and the canvas (only on
  1923. * the canvas). Basically the update of all the information concerning
  1924. * the clicked HolonObject. For multi-selection, the propertyTable would
  1925. * be disabled
  1926. */
  1927. canvas.addMouseListener(new MouseAdapter() {
  1928. @Override
  1929. public void mousePressed(MouseEvent e) {
  1930. }
  1931. @Override
  1932. public void mouseReleased(MouseEvent e) {
  1933. holonEleNamesDisplayed = Languages.getLanguage()[25];
  1934. // If any empty space is clicked
  1935. if (temp == null || temp.getId() != model.getSelectedObjectID()) {
  1936. hideScrollGraph();
  1937. elementGraph.setText(Languages.getLanguage()[25]);
  1938. }
  1939. temp = updCon.getActualCps();
  1940. // Erase old data in the PropertyTable
  1941. if (model.getPropertyTable().getRowCount() > 0) {
  1942. for (int i = model.getPropertyTable().getRowCount() - 1; i > -1; i--) {
  1943. model.getPropertyTable().removeRow(i);
  1944. }
  1945. }
  1946. if (e.isControlDown() && temp != null) {
  1947. if (model.getSelectedCpsObjects().contains(temp)) {
  1948. controller.deleteSelectedObject(temp);
  1949. } else {
  1950. controller.addSelectedObject(temp);
  1951. }
  1952. }
  1953. if (temp instanceof HolonSwitch) {
  1954. showScrollGraph();
  1955. repaintGraphAux((HolonSwitch)temp);
  1956. unitGraph.fillArrayofBooleans();
  1957. }
  1958. // Write new data in the PropertyTable
  1959. triggerUpdateController(temp);
  1960. // New Tab with NodeOfNode
  1961. if (doubleClick() && MouseEvent.BUTTON3 != e.getButton()
  1962. && temp instanceof CpsUpperNode) {
  1963. openNewUpperNodeTab();
  1964. try {
  1965. controller.autoSave();
  1966. } catch (IOException e1) {
  1967. e1.printStackTrace();
  1968. }
  1969. }
  1970. if (model.getSelectedCpsObjects().size() > 1) {
  1971. model.getTableHolonElement()
  1972. .setModel(model.getMultiTable());
  1973. } else if (model.getSelectedCpsObjects().size() == 1) {
  1974. model.getTableHolonElement().setModel(
  1975. model.getSingleTable());
  1976. }
  1977. }
  1978. });
  1979. holonCanvas.addMouseListener(new MouseAdapter() {
  1980. @Override
  1981. public void mousePressed(MouseEvent e) {
  1982. hideScrollGraph();
  1983. elementGraph.setText(Languages.getLanguage()[25]);
  1984. if (model.getPropertyTable().getRowCount() > 0) {
  1985. for (int i = model.getPropertyTable().getRowCount() - 1; i > -1; i--) {
  1986. model.getPropertyTable().removeRow(i);
  1987. }
  1988. }
  1989. updCon.deleteRows(model.getMultiTable());
  1990. updCon.deleteRows(model.getSingleTable());
  1991. updCon.paintHolonBody(model.getSelectedHolonBody());
  1992. }
  1993. });
  1994. // Del Button
  1995. btnDel.addActionListener(actionEvent -> {
  1996. Object nodeInfo = tree.getLastSelectedPathComponent();
  1997. if (nodeInfo != null) {
  1998. DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) nodeInfo;
  1999. String nodeName = selectedNode.getUserObject().toString();
  2000. int depthOfNode = selectedNode.getLevel();
  2001. try {
  2002. switch (depthOfNode) {
  2003. case 1:
  2004. int dialogResult = JOptionPane.showConfirmDialog(
  2005. frmCyberPhysical, eraseCategory + nodeName
  2006. + "?", warningText,
  2007. JOptionPane.YES_NO_OPTION);
  2008. if (dialogResult == JOptionPane.YES_OPTION) {
  2009. controller.deleteCategory(nodeName);
  2010. }
  2011. break;
  2012. case 2:
  2013. DefaultMutableTreeNode parent = (DefaultMutableTreeNode) selectedNode
  2014. .getParent();
  2015. controller.delObjectCategory(parent.getUserObject()
  2016. .toString(), nodeName);
  2017. break;
  2018. default:
  2019. JOptionPane.showMessageDialog(frmCyberPhysical,
  2020. selectObjBeforeErase);
  2021. }
  2022. } catch (Exception e2) {
  2023. }
  2024. } else {
  2025. JOptionPane.showMessageDialog(frmCyberPhysical,
  2026. selectObjBeforeErase);
  2027. }
  2028. tree.repaint();
  2029. });
  2030. toolBar.add(btnDel);
  2031. frmCyberPhysical.getContentPane().add(splitPane);
  2032. mntmNew.addActionListener(actionEvent -> {
  2033. if (model.getObjectsOnCanvas().size() != 0) {
  2034. int newWarning = JOptionPane.YES_NO_OPTION;
  2035. int dialogForNewWarning = JOptionPane.showConfirmDialog(
  2036. frmCyberPhysical, saveBeforeNew, warningText,
  2037. newWarning);
  2038. if (dialogForNewWarning == JOptionPane.YES_OPTION) {
  2039. mntmSave.doClick();
  2040. }
  2041. }
  2042. model.getEdgesOnCanvas().removeAll(model.getEdgesOnCanvas());
  2043. model.getObjectsOnCanvas().removeAll(model.getObjectsOnCanvas());
  2044. controller.setSelectedObjectID(0);
  2045. controller.setSelecteEdge(null);
  2046. controller.setCurIteration(0);
  2047. hideScrollGraph();
  2048. elementGraph.setText(Languages.getLanguage()[25]);
  2049. canvas.tempCps = null;
  2050. canvas.repaint();
  2051. IdCounter.resetCounter();
  2052. IdCounterElem.resetCounter();
  2053. });
  2054. mntmOpen.addActionListener(new ActionListener() {
  2055. @Override
  2056. public void actionPerformed(ActionEvent evt) {
  2057. menuFileExitActionPerformed();
  2058. }
  2059. private void menuFileExitActionPerformed() {
  2060. JFileChooser fileChooser = new JFileChooser();
  2061. FileNameExtensionFilter holonFilter = new FileNameExtensionFilter(
  2062. "Holon Save File(*.holon)", "holon");
  2063. fileChooser.setFileFilter(holonFilter);
  2064. if (fileChooser.showOpenDialog(frmCyberPhysical) == JFileChooser.APPROVE_OPTION) {
  2065. File file = fileChooser.getSelectedFile();
  2066. try {
  2067. controller.loadFile(file.getAbsolutePath());
  2068. canvas.repaint();
  2069. unitGraph.update(model.getObjectsOnCanvas());
  2070. tree.repaint();
  2071. for (JsonObject json : model.getStatisticData()) {
  2072. readStatistics(json);
  2073. }
  2074. } catch (IOException | ArchiveException e) {
  2075. e.printStackTrace();
  2076. JLabel message = new JLabel(
  2077. "The savefile is corrupt and cannot be opened.");
  2078. JOptionPane.showMessageDialog(frmCyberPhysical,
  2079. message, "", JOptionPane.ERROR_MESSAGE);
  2080. }
  2081. }
  2082. }
  2083. });
  2084. mntmSave.addActionListener(new ActionListener() {
  2085. @Override
  2086. public void actionPerformed(ActionEvent evt) {
  2087. menuSaveActionPerformed();
  2088. }
  2089. private void menuSaveActionPerformed() {
  2090. JFileChooser fileChooser = new JFileChooser();
  2091. FileNameExtensionFilter holonFilter = new FileNameExtensionFilter(
  2092. "Holon Save File(*.holon)", "holon");
  2093. fileChooser.setFileFilter(holonFilter);
  2094. if (fileChooser.showSaveDialog(frmCyberPhysical) == JFileChooser.APPROVE_OPTION) {
  2095. File selectedFile = fileChooser.getSelectedFile();
  2096. String fileName = selectedFile.getName();
  2097. String fullPath = fileChooser.getSelectedFile().getPath();
  2098. if (fileChooser.getFileFilter().equals(holonFilter)) {
  2099. if (!fileName.contains("."))
  2100. fullPath += ".holon";
  2101. }
  2102. if (!fullPath.endsWith(".holon")) {
  2103. String suffix = fullPath.substring(fullPath.lastIndexOf("."),
  2104. fullPath.length());
  2105. String[] options = new String[] { "keep .holon",
  2106. "use " + suffix };
  2107. JLabel message = new JLabel(
  2108. "Are you sure to use the extension \"" + suffix
  2109. + "\" instead of \".holon\"?");
  2110. int response = JOptionPane.showOptionDialog(
  2111. frmCyberPhysical, message, "",
  2112. JOptionPane.DEFAULT_OPTION,
  2113. JOptionPane.QUESTION_MESSAGE, null, options,
  2114. options[1]);
  2115. if (response == 0)
  2116. fullPath = fullPath.replace(suffix, ".holon");
  2117. }
  2118. try {
  2119. controller.saveFile(new File(fullPath).getAbsolutePath());
  2120. } catch (IOException | ArchiveException e) {
  2121. e.printStackTrace();
  2122. }
  2123. }
  2124. }
  2125. });
  2126. englishBtn.addActionListener(actionEvent -> {
  2127. Languages.setLanguage(0);
  2128. refreshLanguages();
  2129. updCon.refreshTableProperties(model.getPropertyTable());
  2130. });
  2131. spanishBtn.addActionListener(actionEvent -> {
  2132. Languages.setLanguage(1);
  2133. refreshLanguages();
  2134. updCon.refreshTableProperties(model.getPropertyTable());
  2135. });
  2136. germanBtn.addActionListener(actionEvent -> {
  2137. Languages.setLanguage(2);
  2138. refreshLanguages();
  2139. updCon.refreshTableProperties(model.getPropertyTable());
  2140. });
  2141. czechBtn.addActionListener(actionEvent -> {
  2142. Languages.setLanguage(3);
  2143. refreshLanguages();
  2144. updCon.refreshTableProperties(model.getPropertyTable());
  2145. });
  2146. chineseBtn.addActionListener(actionEvent -> {
  2147. Languages.setLanguage(4);
  2148. refreshLanguages();
  2149. updCon.refreshTableProperties(model.getPropertyTable());
  2150. });
  2151. mntmUndo.addActionListener(new ActionListener() {
  2152. @Override
  2153. public void actionPerformed(ActionEvent evt) {
  2154. menuUndoActionPerformed();
  2155. }
  2156. private void menuUndoActionPerformed() {
  2157. try {
  2158. controller.loadAutoSave(controller.getUndoSave());
  2159. controller.calculateStateForCurrentTimeStep();
  2160. canvas.repaint();
  2161. repaintGraphAfterUndoRedo();
  2162. hideScrollGraph();
  2163. } catch (IOException e) {
  2164. e.printStackTrace();
  2165. }
  2166. }
  2167. });
  2168. mntmRedo.addActionListener(new ActionListener() {
  2169. @Override
  2170. public void actionPerformed(ActionEvent evt) {
  2171. menuRedoActionPerformed();
  2172. }
  2173. private void menuRedoActionPerformed() {
  2174. try {
  2175. controller.loadAutoSave(controller.getRedoSave());
  2176. controller.calculateStateForCurrentTimeStep();
  2177. canvas.repaint();
  2178. repaintGraphAfterUndoRedo();
  2179. hideScrollGraph();
  2180. } catch (IOException e) {
  2181. e.printStackTrace();
  2182. }
  2183. }
  2184. });
  2185. timePanel = new TimePanel(this,controller);
  2186. timePanel.setBorder(null);
  2187. ((JSlider)
  2188. (
  2189. ((Container)timePanel.getComponent(1))//timePanel
  2190. .getComponent(1)//timeSlider
  2191. )
  2192. )//TODO: This hardcoded stuff
  2193. .addChangeListener(changeEvent -> {
  2194. int i = model.getCurIteration();
  2195. controller.calculateStateForTimeStep(i);
  2196. unitGraph.repaint();
  2197. if (model.getIsSimRunning()) {
  2198. controller.runAlgorithm(model, controller);
  2199. statSplitPane.repaintGraphs();
  2200. }
  2201. contentPane.updateUI();
  2202. });
  2203. splitPane1.setMinimumSize(new Dimension(0, 25));
  2204. splitPane.setRightComponent(splitPane1);
  2205. splitPane.setDividerLocation(200);
  2206. splitPane1.setDividerLocation(500);
  2207. splitPaneCanvasConsole.setDividerLocation(550);
  2208. splitPaneCanvasConsole.setResizeWeight(0.9);
  2209. splitPane.setLeftComponent(scrollPane1);
  2210. splitPaneCanvasConsole.setLeftComponent(tabbedPaneOriginal);
  2211. tabbedPaneOriginal.addTab("View", tabbedPaneInnerOriginal);
  2212. myPanel.add(canvasSP, BorderLayout.CENTER);
  2213. myPanel.add(lblHint, BorderLayout.PAGE_END);
  2214. lblHint.setBackground(new Color(53, 178, 76, 100));
  2215. lblHint.setOpaque(true);
  2216. tabbedPaneInnerOriginal.addTab("Main Grid", myPanel);
  2217. tabbedPaneOriginal.addTab("Statistics", statScrollPane);
  2218. tabbedPaneOriginal.addTab("Holon", holonCanvas);
  2219. FlexiblePane flexPane = new FlexiblePane(controller);
  2220. controller.setFlexiblePane(flexPane);
  2221. controller.getModel().getObjectListeners().add(flexPane);
  2222. tabbedPaneOriginal.addTab("Flexibility", flexPane);
  2223. splitPaneCanvasConsole.setRightComponent(console);
  2224. splitPane1.setLeftComponent(splitPaneCanvasConsole);
  2225. splitPane1.setRightComponent(splitHolonElPro);
  2226. splitPane1.setResizeWeight(0.9);
  2227. splitHolonElPro.setDividerLocation(700);
  2228. // containing the graph and the elements-list
  2229. splitHolonElPro.setTopComponent(splitGraphHolonEl);
  2230. // containing the object's properties
  2231. splitHolonElPro.setBottomComponent(scrollProperties);
  2232. splitGraphHolonEl.setDividerLocation(distanceBetweenElementsAndGraph);
  2233. splitGraphHolonEl.setTopComponent(scrollElements);
  2234. splitGraphHolonEl.setBottomComponent(scrollGraph);
  2235. canvasSP.setViewportView(canvas);
  2236. algorithmMenu.setBackground(new Color(240, 240, 240));
  2237. tabbedPaneOriginal.setBorder(null);
  2238. scrollProperties.setBorder(null);
  2239. scrollGraph.setBorder(null);
  2240. scrollElements.setBorder(null);
  2241. splitPane.setBorder(null);
  2242. splitPane1.setBorder(null);
  2243. splitPaneCanvasConsole.setBorder(null);
  2244. splitHolonElPro.setBorder(null);
  2245. splitGraphHolonEl.setBorder(null);
  2246. panelHolonEl.setBorder(null);
  2247. canvasSP.setBorder(null);
  2248. tableHolonElementScrollPane.setBorder(null);
  2249. frmCyberPhysical.getContentPane().add(timePanel, BorderLayout.SOUTH);
  2250. MouseAdapter focusCanvasAdapter = new FocusCanvasMouseAdapter();
  2251. model.getTableHolonElement().addMouseListener(focusCanvasAdapter);
  2252. tableProperties.addMouseListener(focusCanvasAdapter);
  2253. console.getConsoleText().addMouseListener(focusCanvasAdapter);
  2254. try {
  2255. controller.loadAutoSave(System.getProperty("user.home")
  2256. + "/.config/HolonGUI/Category/Category.json");
  2257. } catch (IOException e1) {
  2258. }
  2259. String autoPath = System.getProperty("user.home")
  2260. + "/.config/HolonGUI/Autosave/";
  2261. File dest = new File(autoPath);
  2262. ArrayList<File> oldAutoSaves = controller.filterOldAutoSaveFiles();
  2263. int nrOfOldSaves = oldAutoSaves.size();
  2264. if (nrOfOldSaves > 0) {
  2265. int dialogButton = JOptionPane.YES_NO_OPTION;
  2266. int dialogResult = JOptionPane.showConfirmDialog(frmCyberPhysical,
  2267. "Old autosave file was found, should it be loaded?",
  2268. warningText, dialogButton);
  2269. if (dialogResult == JOptionPane.YES_OPTION) {
  2270. if (dest.exists()) {
  2271. model.setAutoSaveNr(nrOfOldSaves - 1);
  2272. mntmRedo.doClick();
  2273. } else {
  2274. JOptionPane.showMessageDialog(frmCyberPhysical,
  2275. "Autosave could not be loaded.");
  2276. setUpAutoSave(dest);
  2277. }
  2278. } else {
  2279. setUpAutoSave(dest);
  2280. }
  2281. // after all: delete the obsolete/old autosave files from the
  2282. // directory
  2283. controller.deleteObsoleteAutoSaveFiles();
  2284. }
  2285. canvasSP.addComponentListener(new ComponentAdapter() {
  2286. @Override
  2287. public void componentResized(ComponentEvent e) {
  2288. controller.setCanvasX(Math.max(model.getCanvasX(), canvasSP
  2289. .getViewport().getWidth()));
  2290. controller.setCanvasY(Math.max(model.getCanvasY(), canvasSP
  2291. .getViewport().getHeight()));
  2292. canvas.repaint();
  2293. }
  2294. });
  2295. }
  2296. private void showScrollGraph() {
  2297. scrollGraph.setVisible(true);
  2298. splitGraphHolonEl.setBottomComponent(scrollGraph);
  2299. splitGraphHolonEl.setDividerLocation(distanceBetweenElementsAndGraph);
  2300. }
  2301. private void hideScrollGraph() {
  2302. scrollGraph.setVisible(false);
  2303. unitGraph.empty();
  2304. splitGraphHolonEl.remove(scrollGraph);
  2305. splitGraphHolonEl.setDividerLocation(0);
  2306. }
  2307. private boolean isUpperPanelInsideBounds() {
  2308. int x = frmCyberPhysical.getX();
  2309. int y = frmCyberPhysical.getY();
  2310. int width = frmCyberPhysical.getWidth();
  2311. // get all connected screen devices
  2312. GraphicsDevice[] screenDevices = GraphicsEnvironment
  2313. .getLocalGraphicsEnvironment().getScreenDevices();
  2314. boolean isUpperPanelVisible = false;
  2315. // and check whether they contain the upper left or upper right point of
  2316. // the frame
  2317. for (GraphicsDevice device : screenDevices) {
  2318. Rectangle bounds = device.getDefaultConfiguration().getBounds();
  2319. if (bounds.contains(x, y) || bounds.contains(x + width, y)) {
  2320. isUpperPanelVisible = true;
  2321. break;
  2322. }
  2323. }
  2324. return isUpperPanelVisible;
  2325. }
  2326. /**
  2327. * Sets up autosave if no old one is loaded at the beginning
  2328. *
  2329. * @param dest
  2330. * path to save-folder
  2331. */
  2332. private void setUpAutoSave(File dest) {
  2333. dest.mkdirs();
  2334. try {
  2335. controller.autoSave();
  2336. } catch (IOException e1) {
  2337. e1.printStackTrace();
  2338. }
  2339. }
  2340. /**
  2341. * adds a specific object type to selected Category also handles input
  2342. * windows and illegal inputs.
  2343. *
  2344. * @param objType
  2345. * type of the Object
  2346. * @param selectedNode
  2347. * The selected Node
  2348. */
  2349. private void addObjectAction(String objType,
  2350. DefaultMutableTreeNode selectedNode) {
  2351. if (selectedNode == null) {
  2352. JOptionPane.showMessageDialog(frmCyberPhysical,
  2353. "Please select a Category first before adding " + objType
  2354. + ".");
  2355. }
  2356. // if selected node is a directory for Categories
  2357. else {
  2358. if (selectedNode.getLevel() == 1) {
  2359. String objname = JOptionPane.showInputDialog(frmCyberPhysical,
  2360. "Please enter a Name for the " + objType);
  2361. Category cat = controller.searchCategory(selectedNode
  2362. .getUserObject().toString());
  2363. if (objname.length() != 0) {
  2364. try {
  2365. switch (objType) {
  2366. case "Switch":
  2367. controller.addSwitch(cat, objname);
  2368. break;
  2369. case "Battery":
  2370. controller.addBattery(cat, objname);
  2371. break;
  2372. }
  2373. } catch (Exception e) {
  2374. }
  2375. }
  2376. } else {
  2377. JOptionPane
  2378. .showMessageDialog(frmCyberPhysical,
  2379. "Objects can not be added to Objects. Please select a Category.");
  2380. }
  2381. }
  2382. }
  2383. /**
  2384. * reloads the Categories from Model.
  2385. *
  2386. * @param categories
  2387. * the current categories
  2388. */
  2389. private void updateCategories(final ArrayList<Category> categories) {
  2390. tree.setModel(new DefaultTreeModel(new DefaultMutableTreeNode(
  2391. "Categories") {
  2392. private static final long serialVersionUID = 1L;
  2393. {
  2394. DefaultMutableTreeNode node1;
  2395. for (Category c : categories) {
  2396. node1 = new DefaultMutableTreeNode(c.getName());
  2397. // kann eventuell umgeändert werden
  2398. for (AbstractCpsObject obj : c.getObjects()) {
  2399. node1.add(new DefaultMutableTreeNode(obj.getObjName()));
  2400. }
  2401. add(node1);
  2402. }
  2403. }
  2404. }));
  2405. }
  2406. /**
  2407. * When changes are made to the Categories.
  2408. *
  2409. * @param categories
  2410. * the Categories
  2411. */
  2412. public void onChange(ArrayList<Category> categories) {
  2413. DefaultTreeModel model = (DefaultTreeModel) tree.getModel();
  2414. updateCategories(categories);
  2415. model.reload();
  2416. }
  2417. /**
  2418. * Get the Frame.
  2419. *
  2420. * @return the Frame
  2421. */
  2422. JFrame getFrmCyberPhysical() {
  2423. return frmCyberPhysical;
  2424. }
  2425. private void refreshLanguages() {
  2426. String[] tempArray = Languages.getLanguage();
  2427. // ToolBar
  2428. mnNewMenu.setText(tempArray[0]);
  2429. mntmNew.setText(tempArray[1]);
  2430. mntmOpen.setText(tempArray[2]);
  2431. mntmSave.setText(tempArray[3]);
  2432. mnNewMenuEdit.setText(tempArray[4]);
  2433. mntmUndo.setText(tempArray[5]);
  2434. mntmRedo.setText(tempArray[6]);
  2435. mntmFindReplace.setText(tempArray[7]);
  2436. mntmEditShowedInformation.setText(tempArray[8]);
  2437. mnNewMenuOptions.setText(tempArray[9]);
  2438. mntmResetCategory.setText(tempArray[10]);
  2439. mnNewMenuView.setText(tempArray[11]);
  2440. mntmCanvasSize.setText(tempArray[12]);
  2441. mnHelp.setText(tempArray[13]);
  2442. mntmAboutUs.setText(tempArray[14]);
  2443. mntmEditEdges.setText(tempArray[15]);
  2444. mnLanguage.setText(tempArray[16]);
  2445. canvas.updateLanguages();
  2446. // Tables
  2447. System.arraycopy(tempArray, 17, columnNamesMulti, 0,
  2448. columnNamesMulti.length);
  2449. model.getMultiTable().setColumnIdentifiers(columnNamesMulti);
  2450. System.arraycopy(tempArray, 18, columnNamesSingle, 0,
  2451. columnNamesSingle.length);
  2452. model.getSingleTable().setColumnIdentifiers(columnNamesSingle);
  2453. model.colNames[0] = tempArray[23];
  2454. model.colNames[1] = tempArray[24];
  2455. model.getPropertyTable().setColumnIdentifiers(model.colNames);
  2456. // Graph
  2457. elementGraph.setText(tempArray[25]);
  2458. holonEleNamesDisplayed = tempArray[25];
  2459. resetGraphBtn.setText(tempArray[26]);
  2460. // Warning PopUps
  2461. warningText = tempArray[27];
  2462. saveBeforeNew = tempArray[28];
  2463. eraseCategory = tempArray[29];
  2464. selectObjBeforeErase = tempArray[30];
  2465. // SimMenu
  2466. algorithmMenu.algoFolderButton.setText(Languages.getLanguage()[85]);
  2467. // TimePanel
  2468. timePanel.playBtn.setToolTipText(Languages.getLanguage()[89]);
  2469. timePanel.timeResetBtn.setToolTipText(Languages.getLanguage()[90]);
  2470. timePanel.timeForwardBtn.setToolTipText(Languages.getLanguage()[91]);
  2471. timePanel.timeBackwardBtn.setToolTipText(Languages.getLanguage()[92]);
  2472. timePanel.timeSlider.setToolTipText(Languages.getLanguage()[93]);
  2473. // Image Size Slider
  2474. lblImageSize.setText(Languages.getLanguage()[94]);
  2475. }
  2476. /**
  2477. * Checks if a double click was made.
  2478. *
  2479. * @return true if doublecklick, false if not
  2480. */
  2481. private boolean doubleClick() {
  2482. if (click) {
  2483. click = false;
  2484. return true;
  2485. } else {
  2486. click = true;
  2487. Timer t = new Timer("doubleclickTimer", false);
  2488. t.schedule(new TimerTask() {
  2489. @Override
  2490. public void run() {
  2491. click = false;
  2492. }
  2493. }, 350);
  2494. }
  2495. return false;
  2496. }
  2497. /*
  2498. * Open a new Tab with an UpperNodeCanvas
  2499. */
  2500. private void openNewUpperNodeTab() {
  2501. chooseTabTemp();
  2502. JScrollPane scrollPane = getScrollPaneFromTabbedPane();
  2503. if (scrollPane.getViewport().getComponent(0) instanceof MyCanvas) {
  2504. unc = new UpperNodeCanvas(model, controller, unitGraph,
  2505. (CpsUpperNode) temp, "");
  2506. } else {
  2507. unc = new UpperNodeCanvas(model, controller, unitGraph,
  2508. (CpsUpperNode) temp, ((UpperNodeCanvas) scrollPane
  2509. .getViewport().getComponent(0)).path + " -> ");
  2510. }
  2511. unc.setShowedInformation(canvas.getShowedInformation());
  2512. // check if tab already open for clicked NodeOfNode
  2513. boolean dupl = false;
  2514. for (int i = 1; i < tabbedPaneInnerOriginal.getTabCount(); i++) {
  2515. JScrollPane paneOriginal = (JScrollPane) tabbedPaneInnerOriginal
  2516. .getComponentAt(i);
  2517. if (paneOriginal != null
  2518. && ((UpperNodeCanvas) paneOriginal.getViewport()
  2519. .getComponent(0)).upperNode.getId() == temp.getId()) {
  2520. dupl = true;
  2521. // set selected component to view
  2522. tabbedPaneOriginal
  2523. .setSelectedComponent(tabbedPaneInnerOriginal);
  2524. // set selected tab in view to found upper-node-canvas
  2525. tabbedPaneInnerOriginal
  2526. .setSelectedComponent(tabbedPaneInnerOriginal
  2527. .getComponentAt(i));
  2528. }
  2529. if (tabbedPaneSplit.getTabCount() > 0) {
  2530. JTabbedPane tabbedPaneInnerSplit = (JTabbedPane) tabbedPaneSplit
  2531. .getComponentAt(0);
  2532. if (tabbedPaneInnerSplit != null) {
  2533. JScrollPane paneSplit = (JScrollPane) tabbedPaneInnerSplit
  2534. .getComponentAt(i);
  2535. if (!initSplit
  2536. && paneSplit != null
  2537. && ((UpperNodeCanvas) paneSplit.getViewport()
  2538. .getComponent(0)).upperNode.getId() == temp
  2539. .getId()) {
  2540. dupl = true;
  2541. // set selected component to view
  2542. tabbedPaneSplit
  2543. .setSelectedComponent(tabbedPaneInnerSplit);
  2544. // set selected tab in view to found upper-node-canvas
  2545. tabbedPaneInnerSplit
  2546. .setSelectedComponent(tabbedPaneInnerSplit
  2547. .getComponentAt(i));
  2548. }
  2549. }
  2550. }
  2551. // if we found a duplicate, break
  2552. if (dupl) {
  2553. break;
  2554. }
  2555. }
  2556. if (!dupl) {
  2557. unc.setBorder(null);
  2558. unc.setBackground(Color.WHITE);
  2559. unc.setPreferredSize(new Dimension(model.getCanvasX(), model
  2560. .getCanvasY()));
  2561. unc.addMouseListener(new MouseAdapter() {
  2562. @Override
  2563. public void mousePressed(MouseEvent e) {
  2564. hideScrollGraph();
  2565. holonEleNamesDisplayed = Languages.getLanguage()[25];
  2566. elementGraph.setText(holonEleNamesDisplayed);
  2567. chooseTabTemp();
  2568. JScrollPane scrollPane1 = getScrollPaneFromTabbedPane();
  2569. temp = ((UpperNodeCanvas) scrollPane1.getViewport()
  2570. .getComponent(0)).tempCps;
  2571. if (doubleClick() && MouseEvent.BUTTON3 != e.getButton()
  2572. && temp instanceof CpsUpperNode) {
  2573. openNewUpperNodeTab();
  2574. }
  2575. if (temp instanceof HolonSwitch) {
  2576. repaintGraphAux((HolonSwitch)temp);
  2577. unitGraph.fillArrayofBooleans();
  2578. }
  2579. }
  2580. });
  2581. JScrollPane sp = new JScrollPane(unc);
  2582. sp.setBorder(null);
  2583. // Selected tabbed Pane = tabbedPaneOriginal or tabbedPaneSplit
  2584. if (tabTemp == tabbedPaneOriginal) {
  2585. this.tabbedPaneInnerOriginal.add(temp.getName(), sp);
  2586. this.tabbedPaneInnerOriginal.setSelectedComponent(sp);
  2587. this.tabbedPaneInnerOriginal.setTabComponentAt(
  2588. this.tabbedPaneInnerOriginal.getTabCount() - 1,
  2589. new ButtonTabComponent(this.tabbedPaneInnerOriginal,
  2590. tabbedPaneSplit));
  2591. } else {
  2592. JTabbedPane tabbedPaneInnerSplit = (JTabbedPane) tabbedPaneSplit
  2593. .getComponentAt(0);
  2594. tabbedPaneInnerSplit.add(temp.getName(), sp);
  2595. Component tempC = tabbedPaneInnerSplit.getSelectedComponent();
  2596. tabbedPaneInnerSplit.setComponentAt(
  2597. tabbedPaneInnerSplit.getSelectedIndex(), null);
  2598. tabbedPaneOriginal.setComponentAt(
  2599. tabbedPaneInnerSplit.getSelectedIndex(), tempC);
  2600. tabbedPaneInnerSplit.setSelectedComponent(sp);
  2601. tabbedPaneInnerOriginal.add(temp.getName(), null);
  2602. tabbedPaneInnerOriginal.setTabComponentAt(
  2603. tabbedPaneInnerOriginal.getTabCount() - 1,
  2604. new ButtonTabComponent(tabbedPaneInnerOriginal,
  2605. tabbedPaneInnerSplit));
  2606. }
  2607. temp = null;
  2608. }
  2609. }
  2610. private void updateUpperNodes() {
  2611. for (Component c : tabbedPaneInnerOriginal.getComponents()) {
  2612. if (!(c instanceof JScrollPane)) {
  2613. continue;
  2614. }
  2615. Component pane = ((JScrollPane) c).getViewport().getComponent(0);
  2616. if (pane instanceof UpperNodeCanvas) {
  2617. temp = model.getHashcodeMap()
  2618. .get(((UpperNodeCanvas) pane).code);
  2619. ((UpperNodeCanvas) pane).upperNode = (CpsUpperNode) temp;
  2620. }
  2621. }
  2622. }
  2623. /**
  2624. * Removes UpperNodeTab if UpperNode was deleted
  2625. *
  2626. * @param cps
  2627. * the CPS object that is currently selected
  2628. */
  2629. private void removeUpperNodeTab(AbstractCpsObject cps) {
  2630. if (cps instanceof CpsUpperNode) {
  2631. boolean splitView = false;
  2632. for (int i = 1; i < tabbedPaneInnerOriginal.getTabCount(); i++) {
  2633. JScrollPane scrollPaneOriginal = (JScrollPane) tabbedPaneInnerOriginal
  2634. .getComponentAt(i);
  2635. if (scrollPaneOriginal == null) {
  2636. splitView = true;
  2637. } else if (((UpperNodeCanvas) scrollPaneOriginal.getViewport()
  2638. .getComponent(0)).upperNode.getId() == cps.getId()) {
  2639. ((ButtonTabComponent) tabbedPaneInnerOriginal
  2640. .getTabComponentAt(i)).removeTabs();
  2641. break;
  2642. }
  2643. }
  2644. // If SplitView is on and the view on
  2645. // tabbedPaneSplit is the deleted upperNode
  2646. if (splitView && tabbedPaneSplit.getComponentCount() > 0) {
  2647. JTabbedPane tabbedPaneInnerSplit = (JTabbedPane) tabbedPaneSplit
  2648. .getComponentAt(0);
  2649. if (((UpperNodeCanvas) ((JScrollPane) tabbedPaneInnerSplit
  2650. .getSelectedComponent()).getViewport().getComponent(0)).upperNode
  2651. .getId() == cps.getId()) {
  2652. ((ButtonTabComponent) tabbedPaneInnerOriginal
  2653. .getTabComponentAt(tabbedPaneInnerSplit
  2654. .getSelectedIndex())).removeTabs();
  2655. }
  2656. }
  2657. }
  2658. }
  2659. private void readStatistics(JsonObject json) {
  2660. List<String> keys = json.entrySet().stream().map(i -> i.getKey())
  2661. .collect(Collectors.toCollection(ArrayList::new));
  2662. // Saved Values
  2663. JsonObject obj;
  2664. AbstractCpsObject cps;
  2665. int prop;
  2666. Color color;
  2667. StatisticGraphPanel stat = new StatisticGraphPanel(model, controller,//TODO
  2668. json.get("KEY").getAsString(), model.getGraphTable());
  2669. for (String k : keys) {
  2670. if (!k.equals("KEY")) {
  2671. obj = json.get(k).getAsJsonObject();
  2672. cps = (obj.get("ID") == JsonNull.INSTANCE ? null : controller
  2673. .searchTracked(obj.get("ID").getAsInt()));
  2674. prop = obj.get("PROPERTY").getAsInt();
  2675. color = model.getGson().fromJson(obj.get("COLOR"), Color.class);
  2676. stat.addObject(new TrackedDataSet(cps, prop, color, model.getIterations()));
  2677. }
  2678. model.getGraphTable().put(json.get("KEY").getAsString(), stat);
  2679. model.getStatPanel().getGraphPanel().add(stat);
  2680. }
  2681. }
  2682. /**
  2683. * chooses whether to set the tabTemp to tabbedPaneOriginal or
  2684. * tabbedPaneSplit
  2685. */
  2686. private void chooseTabTemp() {
  2687. // is the uppernode on tabbedPaneOriginal or tabbedPaneSplit
  2688. /* TODO: Fix or Remove SplitView */
  2689. if (tabbedPaneOriginal.getMousePosition() != null || initSplit) {
  2690. tabTemp = tabbedPaneOriginal;
  2691. } else {
  2692. tabTemp = tabbedPaneSplit;
  2693. }
  2694. }
  2695. private JScrollPane getScrollPaneFromTabbedPane(JTabbedPane tabbedPane,
  2696. int index) {
  2697. tabTemp = tabbedPane;
  2698. return getScrollPaneFromTabbedPane(index);
  2699. }
  2700. // private JScrollPane getScrollPaneFromTabbedPane(JTabbedPane tabbedPane) {
  2701. // return getScrollPaneFromTabbedPane(tabbedPane, -1);
  2702. // }
  2703. private JScrollPane getScrollPaneFromTabbedPane() {
  2704. return getScrollPaneFromTabbedPane(-1);
  2705. }
  2706. private JScrollPane getScrollPaneFromTabbedPane(int index) {
  2707. Component upperLevelSelectedComponent;
  2708. if (index == -1) {
  2709. upperLevelSelectedComponent = tabTemp.getSelectedComponent();
  2710. } else {
  2711. upperLevelSelectedComponent = tabTemp.getComponentAt(index);
  2712. }
  2713. if (upperLevelSelectedComponent instanceof JTabbedPane) {
  2714. Component nextLevel = ((JTabbedPane) upperLevelSelectedComponent).getSelectedComponent();
  2715. if(nextLevel instanceof JPanel)
  2716. return (JScrollPane) ((JPanel)nextLevel).getComponent(0);
  2717. else
  2718. return (JScrollPane) nextLevel;
  2719. } else if (upperLevelSelectedComponent instanceof JScrollPane) {
  2720. return (JScrollPane) upperLevelSelectedComponent;
  2721. } else {
  2722. return null;
  2723. }
  2724. }
  2725. private void repaintGraphAfterUndoRedo() {
  2726. for (AbstractCpsObject cps : model.getObjectsOnCanvas()) {
  2727. unitGraph.repaintGraph(cps);
  2728. }
  2729. }
  2730. /**
  2731. * if flexibility was turned on, then active needs to be turned off, the
  2732. * energy currently produced/consumed
  2733. *
  2734. * @param eleBTemp
  2735. * element that needs to be updated
  2736. * @param selectedValueBY
  2737. * the y value in the table
  2738. */
  2739. private void updateElementTableAfterChange(HolonElement eleBTemp,
  2740. int selectedValueBY) {
  2741. model.getSingleTable().setValueAt(eleBTemp.isFlexible(),
  2742. selectedValueBY, 6);
  2743. model.getSingleTable().setValueAt(eleBTemp.isActive(), selectedValueBY,
  2744. 5);
  2745. model.getSingleTable().setValueAt(eleBTemp.getAmount(),
  2746. selectedValueBY, 4);
  2747. model.getSingleTable().setValueAt(
  2748. eleBTemp.getFlexibleEnergyAvailablePerElement(),
  2749. selectedValueBY, 3);
  2750. model.getSingleTable().setValueAt(eleBTemp.getEnergyPerElement(),
  2751. selectedValueBY, 2);
  2752. }
  2753. private void triggerUpdateController(AbstractCpsObject temp) {
  2754. if (temp != null) {
  2755. updCon.paintProperties(temp);
  2756. }
  2757. updCon.refreshTableHolonElement(model.getMultiTable(),
  2758. model.getSingleTable());
  2759. updCon.refreshTableProperties(model.getPropertyTable());
  2760. }
  2761. /**
  2762. * Custom Mouse adapter makes contentPane gain focus once mouse leaves this
  2763. * component so copy/paste/cut and "select all" works
  2764. */
  2765. private class FocusCanvasMouseAdapter extends MouseAdapter {
  2766. @Override
  2767. public void mouseExited(MouseEvent e) {
  2768. contentPane.requestFocus();
  2769. }
  2770. }
  2771. private void repaintGraphAux(ArrayList<HolonElement> o){//TODO:
  2772. unitGraph.repaintWithNewElement((ArrayList<HolonElement>)o);
  2773. unitGraphLocalPeriod.setText(""+unitGraph.getLocalPeriod());
  2774. unitGraphStretchMode.setSelected(unitGraph.isStretching());
  2775. }
  2776. private void repaintGraphAux(HolonSwitch o){//TODO:
  2777. unitGraph.repaintWithNewSwitch(o);
  2778. unitGraphLocalPeriod.setText(""+unitGraph.getLocalPeriod());
  2779. unitGraphStretchMode.setSelected(unitGraph.isStretching());
  2780. }
  2781. public void updateIterations() {
  2782. this.statSplitPane.updateIterations();
  2783. }
  2784. private void openWebpage(String URL){
  2785. try {
  2786. java.awt.Desktop.getDesktop().browse(new URI(URL));
  2787. } catch (IOException e1) {
  2788. // TODO Auto-generated catch block
  2789. e1.printStackTrace();
  2790. } catch (URISyntaxException e1) {
  2791. // TODO Auto-generated catch block
  2792. e1.printStackTrace();
  2793. }
  2794. }
  2795. /**
  2796. * Function to set the visibility for Hints
  2797. * @param enable true = show false = hide
  2798. */
  2799. public void showHint(boolean enable){
  2800. lblHint.setVisible(enable);
  2801. }
  2802. }