GUI.java 104 KB

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