GUI.java 104 KB

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