GUI.java 103 KB

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