GUI.java 88 KB

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