GUI.java 103 KB

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