GUI.java 92 KB

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