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.IdCounter.CounterType;
  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 utility.ImageImport;
  92. /**
  93. * Graphical User Interface.
  94. *
  95. * @author Gruppe14
  96. */
  97. public class GUI{
  98. static final Color PALE_RED=new Color(255, 192, 192);
  99. /**
  100. * Menu on the Top containing File, Edit View Help etc
  101. */
  102. private final JMenuBar menuBar = new JMenuBar();
  103. private final JMenu mnNewMenu = new JMenu("File");
  104. private final JMenu mnNewMenuEdit = new JMenu("Edit");
  105. private final JMenu mnNewMenuOptions = new JMenu("Options");
  106. private final JMenu mnNewMenuView = new JMenu("View");
  107. private final JMenu menuWindow = new JMenu("Window");
  108. /** Help Menu containing helpful Informations and the AboutUs Popup */
  109. private final JMenu mnHelp = new JMenu("Help");
  110. /**
  111. * Help -> Introduction
  112. * A small Introduction of the Application, SmartGrids and Holons
  113. */
  114. private final JMenuItem mntmIntroduction = new JMenuItem("Introduction");
  115. /**
  116. * Help -> UserManual
  117. */
  118. private final JMenuItem mntmUserManual = new JMenuItem("User Manual");
  119. /** Help -> Algorithm Help Menu */
  120. private final JMenuItem mntmAlgorithmHelp = new JMenuItem("Algorithm Introduction");
  121. /** Help -> CodeDocumentation */
  122. private final JMenuItem mntmCodeDoc = new JMenuItem("Code Documentation");
  123. /** Help -> AboutUs */
  124. private final JMenuItem mntmAboutUs = new JMenuItem("About Us");
  125. /** checked if supplyBars should be shown */
  126. private final JCheckBoxMenuItem showSupplyBarsCheckBox = new JCheckBoxMenuItem(
  127. "Show supply bars.");
  128. /** menu for the different fairness Models */
  129. private final JMenu mnFairnessModel = new JMenu("Fairness Model");
  130. /** press to supply minimum demand first */
  131. private final JMenuItem mntmFairMinFirst = new JMenuItem(
  132. "Minimum demand first");
  133. /** press to give everyone the same energy */
  134. private final JMenuItem mntmFairAlleEqual = new JMenuItem(
  135. "Equal supply for everyone");
  136. private final JMenuItem mntmOpen = new JMenuItem("Open");
  137. private final JMenuItem mntmNew = new JMenuItem("New");
  138. private final JMenuItem mntmSave = new JMenuItem("Save");
  139. private final JMenuItem mntmCanvasSize = new JMenuItem("Set View Size");
  140. private final JMenuItem mntmBackground = new JMenuItem("Set Background Image");
  141. private final JSplitPane splitPane = new JSplitPane();
  142. private final JSplitPane splitPane1 = new JSplitPane();
  143. // the tabbed canvas containing the different sub-net tabs of the grid (Main
  144. // Grid + Nodes of Nodes)
  145. private final JPanel myPanel = new JPanel(new BorderLayout());
  146. private final JTabbedPane tabbedPaneInnerOriginal = new JTabbedPane(
  147. JTabbedPane.TOP);
  148. // the main canvas where we can see the grid currently displayed
  149. private final JScrollPane canvasSP = new JScrollPane();
  150. private final JScrollPane scrollPane1 = new JScrollPane();
  151. // private final JScrollPane holonSP = new JScrollPane();
  152. // the original tabbed Pane (containing tabs for view, statistics, holon,
  153. // flexibility)
  154. private final JTabbedPane tabbedPaneOriginal = new JTabbedPane(
  155. JTabbedPane.TOP);
  156. // the same tabbed Pane that appears once the view is split
  157. private final JTabbedPane tabbedPaneSplit = new JTabbedPane(JTabbedPane.TOP);
  158. private final JPopupMenu popmenuEdit = new JPopupMenu();
  159. private final JMenuItem editItem = new JMenuItem("Edit Object");
  160. private final JLabel maxGraph = new JLabel("100%");
  161. private final JLabel medGraph = new JLabel("50%");
  162. private final JLabel minGraph = new JLabel("0%");
  163. private final JLabel elementGraph = new JLabel("None ");
  164. private final ArrayList<HolonElement> selectedElements = new ArrayList<>();
  165. private final JTree categoryTree = new JTree();
  166. /******************************************
  167. ************* Right Container*************
  168. ******************************************
  169. * Right Container: here comes the information about the HolonObject, such
  170. * as HolonElements Information, Properties and Consumption/Production
  171. * graph.
  172. **/
  173. private final JSplitPane splitHolonElPro = new JSplitPane(
  174. JSplitPane.VERTICAL_SPLIT);
  175. private final JSplitPane splitGraphHolonEl = new JSplitPane(
  176. JSplitPane.VERTICAL_SPLIT);
  177. private final int distanceBetweenElementsAndGraph = 350;
  178. // Model for single or multi selection
  179. private final JPanel scrollElements = new JPanel();
  180. private final JScrollPane tableHolonElementScrollPane = new JScrollPane();
  181. // In this section are all the properties that correspond to the clicked
  182. // HolonObject, such as connections, name, Type, etc.
  183. // Table for Properties --> Cell with (0,1) is editable by CpsObjt and
  184. // Cell(3,1) is editable by Edges
  185. private final JTable tableProperties = new JTable() {
  186. @Override
  187. public TableCellRenderer getCellRenderer(int row, int column) {
  188. if (getValueAt(row, column) instanceof Boolean) {
  189. return super.getDefaultRenderer(Boolean.class);
  190. } else {
  191. return super.getCellRenderer(row, column);
  192. }
  193. }
  194. @Override
  195. public TableCellEditor getCellEditor(int row, int column) {
  196. if (getValueAt(row, column) instanceof Boolean) {
  197. return super.getDefaultEditor(Boolean.class);
  198. } else {
  199. return super.getCellEditor(row, column);
  200. }
  201. }
  202. };
  203. //Prechoosed local Periods
  204. private String[] comboContext = {
  205. "", "5", "10", "20" ,"100", "1000"
  206. };
  207. private JComboBox<String> localPeriodInput = new JComboBox<String>(comboContext);
  208. JButton resetButton = new JButton("", new ImageIcon(ImageImport.loadImage("/Images/resetIcon3.png")));
  209. ImageIcon localPeriodButtonImage = new ImageIcon(GrayFilter.createDisabledImage(ImageImport.loadImage("/Images/Graph.png")));
  210. private JButton localPeriodButton = new JButton("", localPeriodButtonImage);
  211. private final JPanel graphLabel = new JPanel();
  212. private final JScrollPane scrollProperties = new JScrollPane();
  213. // In this section is the graph for the selected HolonElement of the clicked
  214. // HolonObject
  215. private final JTable tableGraph = new JTable();
  216. private final DefaultTableModel tableModelGraph = new DefaultTableModel();
  217. private final JScrollPane scrollGraph = new JScrollPane();
  218. private final Model model;
  219. private final Control controller;
  220. // In this section are all the Holonelements that correspond to the clicked
  221. // HolonObject with consumption/production, name and amount.
  222. private final JPanel panel = new JPanel();
  223. private final JPanel panelHolonEl = new JPanel();
  224. // Buttons
  225. private final JButton btnAdd = new JButton();
  226. private final JPopupMenu btnAddPopUp = new JPopupMenu("Newacac");
  227. private final JMenuItem mItemNew = new JMenuItem("New..");
  228. private final JMenuItem mItemCategory = new JMenuItem("Category");
  229. private final JMenuItem mItemObject = new JMenuItem("Object");
  230. private final JMenuItem mItemSwitch = new JMenuItem("Switch");
  231. private final JButton btnDel = new JButton();
  232. private final JButton btnAddHolEL = new JButton();
  233. private final JButton btnDelHolEL = new JButton();
  234. private final JToolBar toolBar = new JToolBar();
  235. private final JToolBar toolBarHolonEl = new JToolBar();
  236. private final JToolBar toolBarGraph = new JToolBar();
  237. // Languages
  238. private final MyCanvas canvas;
  239. private final UnitGraph unitGraph;
  240. /** Textfield to show the period of an element */
  241. private final JTextField unitGraphLocalPeriod = new JTextField(6);
  242. private final JMenuItem mntmUndo = new JMenuItem("Undo");
  243. private final JMenuItem mntmRedo = new JMenuItem("Redo");
  244. private final JMenuItem mntmEditEdges = new JMenuItem("Edge Properties");
  245. private final JMenuItem mntmFindReplace = new JMenuItem("Find/ Replace");
  246. private final JMenuItem mntmAlignAll = new JMenuItem("Align All");
  247. private final JMenuItem mntmResetCategory = new JMenuItem(
  248. "Reset Categories");
  249. private final String[] columnNamesMulti = { "Object", "Nr.", "Device",
  250. "Energy", "Flexibility active", "Quantity", "Activated" };
  251. private final String[] columnNamesSingle = { "Nr.", "Device", "Energy",
  252. "Flexibility active", "Quantity", "Activated" };
  253. private final ArrayList<PropertyTable> tables = new ArrayList<>();
  254. private final UpdateController updCon;
  255. // for doubleclick
  256. private boolean click = false;
  257. private JFrame holegJFrame;
  258. private JTabbedPane tabTemp; // tabbedPaneOriginal or tabbedPaneSplit
  259. private boolean initSplit = true;
  260. private String catOfObjToBeEdited;
  261. private GroupNodeCanvas unc;
  262. private JPanel contentPane;
  263. private String holonEleNamesDisplayed = "None ";
  264. // Pop up Windows
  265. private AddObjectPopUp addObjectPopUP;
  266. private AboutUsPopUp aboutUsPopUp;
  267. private AddElementPopUp addElementPopUp;
  268. // variables
  269. private boolean dragging = false;
  270. private String actualObjectClicked;
  271. private Image img = null;
  272. private AbstractCanvasObject tempCps = null;
  273. private int yValueElements = 0;
  274. // Time Stuff
  275. private TimePanel timePanel;
  276. public TimePanel getTimePanel() {
  277. return timePanel;
  278. }
  279. // Coord for all Cells with text
  280. private int yThis;
  281. private int xThis;
  282. // Coord for all Cells with boolean values (checkbox)
  283. private int yBTis;
  284. private int xBThis;
  285. // Coord for the Edit-Modus in the PropertieTable
  286. private int yProThis;
  287. private int xProThis;
  288. private int yProThisOneClick;
  289. private int xProThisOneClick;
  290. private AbstractCanvasObject temp = null;
  291. private String warningText = "Warning";
  292. private String saveBeforeNew = "Do you want to save your current data?";
  293. private String eraseCategory = "Do you really want to delete the Category ";
  294. private String selectObjBeforeErase = "Please select a Category or an Object in the left library in order to delete something.";
  295. private List<Outliner> outlinerList = new ArrayList<Outliner>();
  296. private List<FlexWindow> flexList = new ArrayList<FlexWindow>();
  297. private JMenuItem removeItem = new JMenuItem("Remove");
  298. /**
  299. * Create the application.
  300. *
  301. * @param control
  302. * the Controller
  303. */
  304. GUI(Control control) {
  305. this.controller = control;
  306. this.model = control.getModel();
  307. control.setGui(this);
  308. this.unitGraph = new UnitGraph(model, control);
  309. this.canvas = new MyCanvas(model, control, unitGraph);
  310. model.setTableProperties(tableProperties);
  311. initialize();
  312. updateCategories(model.getCategories());
  313. updCon = new UpdateController(model, controller);
  314. control.OnCategoryChanged.addListener(() -> this.updateCategoryUI(model.getCategories()));
  315. }
  316. /**
  317. * Initialize the contents of the frame.
  318. */
  319. private void initialize() {
  320. holegJFrame = new JFrame();
  321. holegJFrame.setTitle("HOLEG Simulator");
  322. // try to restore old position/dimensions
  323. ArrayList<Integer> savedWindowDim = controller
  324. .loadSavedWindowDimensionsIfExistent();
  325. if (savedWindowDim.size() == 4) {
  326. holegJFrame.setBounds(savedWindowDim.get(0),
  327. savedWindowDim.get(1), savedWindowDim.get(2),
  328. savedWindowDim.get(3));
  329. }
  330. // if the upper part of the window is showing, the windows can still be
  331. // moved,
  332. // but if it is not, we need to move it to somewhere else
  333. if (savedWindowDim.size() != 4 || !isUpperPanelInsideBounds()) {
  334. holegJFrame.setBounds(100, 100, 1000, 800);
  335. holegJFrame.setExtendedState(JFrame.MAXIMIZED_BOTH);
  336. }
  337. holegJFrame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
  338. holegJFrame.addWindowListener(new java.awt.event.WindowAdapter() {
  339. @Override
  340. public void windowClosing(java.awt.event.WindowEvent windowEvent) {
  341. if (JOptionPane.showConfirmDialog(holegJFrame,
  342. "Are you sure you want to exit?",
  343. "HOLEG",
  344. JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE) == JOptionPane.YES_OPTION) {
  345. controller.deleteDirectory(new File(System
  346. .getProperty("user.home")
  347. + "/.config/HolonGUI/Autosave"));
  348. // try to save the position and size of the window, such
  349. // that (if possible)
  350. // it can be opened in the same position the next time
  351. try {
  352. controller.savePosAndSizeOfWindow(
  353. holegJFrame.getX(),
  354. holegJFrame.getY(),
  355. holegJFrame.getWidth(),
  356. holegJFrame.getHeight());
  357. } catch (Exception e) {
  358. e.printStackTrace();
  359. }
  360. System.exit(1);
  361. }
  362. System.exit(0);
  363. }
  364. });
  365. contentPane = (JPanel) holegJFrame.getContentPane();
  366. int condition = JComponent.WHEN_IN_FOCUSED_WINDOW;
  367. InputMap inputMap = contentPane.getInputMap(condition);
  368. ActionMap actionMap = contentPane.getActionMap();
  369. String cntrlZDown = "controlZ";
  370. inputMap.put(KeyStroke.getKeyStroke("control Z"), cntrlZDown);
  371. actionMap.put(cntrlZDown, new AbstractAction() {
  372. private static final long serialVersionUID = 1L;
  373. @Override
  374. public void actionPerformed(ActionEvent e) {
  375. try {
  376. controller.loadAutoSave(controller.getUndoSave());
  377. closeInvalidUpperNodeTabs();
  378. controller.calculateStateAndVisualForCurrentTimeStep();
  379. canvas.repaint();
  380. updateUpperNodes();
  381. } catch (IOException eex) {
  382. eex.printStackTrace();
  383. }
  384. }
  385. });
  386. String cntrlYDown = "controlY";
  387. inputMap.put(KeyStroke.getKeyStroke("control Y"), cntrlYDown);
  388. actionMap.put(cntrlYDown, new AbstractAction() {
  389. private static final long serialVersionUID = 1L;
  390. @Override
  391. public void actionPerformed(ActionEvent e) {
  392. try {
  393. controller.loadAutoSave(controller.getRedoSave());
  394. closeInvalidUpperNodeTabs();
  395. controller.calculateStateAndVisualForCurrentTimeStep();
  396. canvas.repaint();
  397. updateUpperNodes();
  398. } catch (IOException ex) {
  399. ex.printStackTrace();
  400. }
  401. }
  402. });
  403. String cntrlADown = "controlA";
  404. inputMap.put(KeyStroke.getKeyStroke("control A"), cntrlADown);
  405. AbstractAction controlA = new AbstractAction() {
  406. private static final long serialVersionUID = 1L;
  407. @Override
  408. public void actionPerformed(ActionEvent e) {
  409. chooseTabTemp();
  410. model.getSelectedCpsObjects().clear();
  411. // Uppernode Canvas?
  412. JScrollPane scrollPane = getScrollPaneFromTabbedPane();
  413. Component canvasOrUpperNodeCanvas = scrollPane.getViewport()
  414. .getComponent(0);
  415. if (canvasOrUpperNodeCanvas instanceof GroupNodeCanvas) {
  416. GroupNodeCanvas uNC = (GroupNodeCanvas) canvasOrUpperNodeCanvas;
  417. for (AbstractCanvasObject cps : uNC.upperNode.getNodes()) {
  418. controller.addSelectedObject(cps);
  419. }
  420. uNC.repaint();
  421. // or Canvas?
  422. } else if (canvasOrUpperNodeCanvas instanceof MyCanvas) {
  423. for (AbstractCanvasObject cps : model.getObjectsOnCanvas()) {
  424. controller.addSelectedObject(cps);
  425. }
  426. canvas.repaint();
  427. }
  428. controller.getObjectsInDepth();
  429. }
  430. };
  431. actionMap.put(cntrlADown, controlA);
  432. String delDown = "delete";
  433. inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0, false),
  434. delDown);
  435. actionMap.put(delDown, new AbstractAction() {
  436. private static final long serialVersionUID = 1L;
  437. @Override
  438. public void actionPerformed(ActionEvent e) {
  439. chooseTabTemp();
  440. // Uppernode Canvas?
  441. JScrollPane scrollPane = getScrollPaneFromTabbedPane();
  442. Component canvasOrUpperNodeCanvas = scrollPane.getViewport()
  443. .getComponent(0);
  444. // check whether a producer was deleted (this triggers a
  445. // complete re-evaluation of the net)
  446. boolean wasProducerDeleted = true;
  447. if (canvasOrUpperNodeCanvas instanceof GroupNodeCanvas) {
  448. GroupNodeCanvas uNC = (GroupNodeCanvas) canvasOrUpperNodeCanvas;
  449. for (AbstractCanvasObject cps : model.getSelectedCpsObjects()) {
  450. if (uNC.upperNode.getNodes().contains(cps)) {
  451. controller.delObjUpperNode(cps, uNC.upperNode);
  452. unc.setToolTip(false);
  453. // remove UpperNodeTab if UpperNode deleted
  454. removeUpperNodeTab(cps);
  455. }
  456. }
  457. uNC.repaint();
  458. // or Canvas?
  459. } else if (canvasOrUpperNodeCanvas instanceof MyCanvas) {
  460. boolean save = false;
  461. // Edge Deleting
  462. Edge edgeHighlight = model.getSelectedEdge();
  463. if (edgeHighlight != null) {
  464. controller.removeEdgesOnCanvas(edgeHighlight);
  465. ((MyCanvas) canvasOrUpperNodeCanvas).edgeHighlight = null;
  466. }
  467. for (int j = 0; j < model.getSelectedCpsObjects().size(); j++) {
  468. AbstractCanvasObject cps = model.getSelectedCpsObjects()
  469. .get(j);
  470. if (j < model.getSelectedCpsObjects().size() - 1)
  471. save = true;
  472. controller.delCanvasObject(cps, save);
  473. canvas.setToolTip(false);
  474. // remove UpperNodeTab if UpperNode deleted
  475. removeUpperNodeTab(cps);
  476. }
  477. canvas.repaint();
  478. }
  479. // recalculate net if a producer was deleted
  480. if (wasProducerDeleted) {
  481. controller.resetSimulation();
  482. controller.calculateStateAndVisualForCurrentTimeStep();
  483. }
  484. model.getSelectedCpsObjects().clear();
  485. hideScrollGraph();
  486. }
  487. });
  488. String cntrlFDown = "controlF";
  489. inputMap.put(KeyStroke.getKeyStroke("control F"), cntrlFDown);
  490. actionMap.put(cntrlFDown, new AbstractAction() {
  491. private static final long serialVersionUID = 1L;
  492. @Override
  493. public void actionPerformed(ActionEvent e) {
  494. SearchPopUp dialog = new SearchPopUp(controller, canvas,
  495. holegJFrame);
  496. dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
  497. dialog.setVisible(true);
  498. }
  499. });
  500. String cntrlCDown = "controlC";
  501. inputMap.put(KeyStroke.getKeyStroke("control C"), cntrlCDown);
  502. AbstractAction controlC = new AbstractAction() {
  503. private static final long serialVersionUID = 1L;
  504. @Override
  505. public void actionPerformed(ActionEvent e) {
  506. chooseTabTemp();
  507. JScrollPane scrollPane = getScrollPaneFromTabbedPane();
  508. if (!model.getSelectedCpsObjects().isEmpty()) {
  509. if (scrollPane.getViewport().getComponent(0) instanceof GroupNodeCanvas)
  510. controller.copy(((GroupNodeCanvas) scrollPane
  511. .getViewport().getComponent(0)).upperNode);
  512. else
  513. controller.copy(null);
  514. if (!model.getClipboradObjects().isEmpty()) {
  515. canvas.itemPaste.setEnabled(true);
  516. }
  517. }
  518. }
  519. };
  520. actionMap.put(cntrlCDown, controlC);
  521. String cntrlVDown = "controlV";
  522. inputMap.put(KeyStroke.getKeyStroke("control V"), cntrlVDown);
  523. AbstractAction controlV = new AbstractAction() {
  524. private static final long serialVersionUID = 1L;
  525. @Override
  526. public void actionPerformed(ActionEvent e) {
  527. try {
  528. tabTemp = null;
  529. if (tabbedPaneOriginal.getMousePosition() != null) {
  530. tabTemp = tabbedPaneOriginal;
  531. } else {
  532. if (!initSplit) {
  533. tabTemp = tabbedPaneSplit;
  534. }
  535. }
  536. if(tabTemp == null)return;
  537. JScrollPane scrollPane = getScrollPaneFromTabbedPane();
  538. Component canvasOrUpperNodeCanvas = scrollPane
  539. .getViewport().getComponent(0);
  540. if (tabTemp != null
  541. && canvasOrUpperNodeCanvas instanceof GroupNodeCanvas) {
  542. controller
  543. .paste(((GroupNodeCanvas) canvasOrUpperNodeCanvas).upperNode,
  544. canvasOrUpperNodeCanvas
  545. .getMousePosition());
  546. controller.calculateStateAndVisualForCurrentTimeStep();
  547. scrollPane.getViewport().getComponent(0).repaint();
  548. } else {
  549. controller.paste(null, canvas.getMousePosition());
  550. controller.calculateStateAndVisualForCurrentTimeStep();
  551. canvas.repaint();
  552. }
  553. } catch (HeadlessException | JsonParseException
  554. | UnsupportedFlavorException | IOException e1) {
  555. JLabel message = new JLabel(
  556. "The Clipboard information cannot be pasted into Application.");
  557. JOptionPane.showMessageDialog(holegJFrame, message,
  558. "", JOptionPane.ERROR_MESSAGE);
  559. }
  560. }
  561. };
  562. actionMap.put(cntrlVDown, controlV);
  563. String cntrlXDown = "controlX";
  564. inputMap.put(KeyStroke.getKeyStroke("control X"), cntrlXDown);
  565. AbstractAction controlX = new AbstractAction() {
  566. private static final long serialVersionUID = 1L;
  567. @Override
  568. public void actionPerformed(ActionEvent e) {
  569. chooseTabTemp();
  570. JScrollPane scrollPane = getScrollPaneFromTabbedPane();
  571. if (!model.getSelectedCpsObjects().isEmpty()) {
  572. if (scrollPane.getViewport().getComponent(0) instanceof GroupNodeCanvas) {
  573. controller.cut(((GroupNodeCanvas) scrollPane
  574. .getViewport().getComponent(0)).upperNode);
  575. controller.calculateStateAndVisualForCurrentTimeStep();
  576. scrollPane.getViewport().getComponent(0).repaint();
  577. } else {
  578. controller.cut(null);
  579. controller.calculateStateAndVisualForCurrentTimeStep();
  580. canvas.repaint();
  581. }
  582. if (!model.getClipboradObjects().isEmpty()) {
  583. canvas.itemPaste.setEnabled(true);
  584. }
  585. }
  586. }
  587. };
  588. actionMap.put(cntrlXDown, controlX);
  589. holegJFrame.setJMenuBar(menuBar);
  590. holegJFrame.setIconImage(ImageImport.loadImage(
  591. "/Images/Holeg.png", 30, 30));
  592. menuBar.add(mnNewMenu);
  593. mnNewMenu.add(mntmNew);
  594. mnNewMenu.add(mntmOpen);
  595. mnNewMenu.add(mntmSave);
  596. menuBar.add(mnNewMenuEdit);
  597. mnNewMenuEdit.add(mntmUndo);
  598. mnNewMenuEdit.add(mntmRedo);
  599. mntmFindReplace.addActionListener(actionEvent -> {
  600. try {
  601. SearchPopUp dialog = new SearchPopUp(controller, canvas,
  602. holegJFrame);
  603. dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
  604. dialog.setVisible(true);
  605. controller.getObjectsInDepth();
  606. } catch (Exception ex) {
  607. ex.printStackTrace();
  608. }
  609. });
  610. mnNewMenuEdit.add(mntmFindReplace);
  611. mnNewMenuEdit.add(mntmEditEdges);
  612. mntmEditEdges.addActionListener(actionEvent -> {
  613. EditEdgesPopUp edgePopUp = new EditEdgesPopUp(holegJFrame);
  614. edgePopUp.setCanvas(canvas);
  615. edgePopUp.setController(controller);
  616. edgePopUp.setVisible(true);
  617. });
  618. //Edit -> Align All
  619. mnNewMenuEdit.add(mntmAlignAll);
  620. mntmAlignAll.addActionListener(actionEvent -> {
  621. // getScrollPaneFromTabbedPane().getViewport().getComponent(0) is always the active canvas
  622. AbstractCanvas activeCanvas = ((AbstractCanvas) getScrollPaneFromTabbedPane().getViewport().getComponent(0));
  623. if (activeCanvas != null) {
  624. activeCanvas.tryToAlignObjects();
  625. activeCanvas.repaint();
  626. }
  627. });
  628. menuBar.add(mnNewMenuOptions);
  629. mnNewMenuOptions.add(mntmResetCategory);
  630. mntmResetCategory.addActionListener(actionEvent -> {
  631. ArrayList<Category> cat = model.getCategories();
  632. try {
  633. while (!cat.isEmpty()) {
  634. controller.deleteCategory(cat.get(0).getName());
  635. }
  636. controller.resetCategorys();
  637. } catch (Exception e2) {
  638. System.out.println(e2.getMessage());
  639. }
  640. categoryTree.revalidate();
  641. categoryTree.repaint();
  642. });
  643. /**
  644. * Add Fairness Model Option to the option Menu
  645. */
  646. mnNewMenuOptions.add(mnFairnessModel);
  647. mnFairnessModel.add(mntmFairMinFirst);
  648. mntmFairMinFirst.setForeground(Color.BLUE);
  649. mntmFairMinFirst
  650. .setToolTipText("HolonObjects with the smallest mininum Demand will be partially supplied first.\n"
  651. + "After that as many HolonObjects as possible will get fully supplied.");
  652. mntmFairMinFirst
  653. .addActionListener(arg0 -> {
  654. controller.setFairnessModel(FairnessModel.MininumDemandFirst);
  655. mntmFairMinFirst.setForeground(Color.BLUE);
  656. mntmFairAlleEqual.setForeground(mnFairnessModel
  657. .getForeground());
  658. controller.calculateStateAndVisualForCurrentTimeStep();
  659. // Update UpperNodes
  660. Component canvasOrUpperNodeCanvas = getScrollPaneFromTabbedPane()
  661. .getViewport().getComponent(0);
  662. if (canvasOrUpperNodeCanvas != null
  663. && canvasOrUpperNodeCanvas instanceof GroupNodeCanvas) {
  664. ((GroupNodeCanvas) canvasOrUpperNodeCanvas).repaint();
  665. }
  666. });
  667. mnFairnessModel.add(mntmFairAlleEqual);
  668. mntmFairAlleEqual
  669. .setToolTipText("HolonObjects will all get the same amount of energy.");
  670. mntmFairAlleEqual.addActionListener(arg0 -> {
  671. controller.setFairnessModel(FairnessModel.AllEqual);
  672. mntmFairAlleEqual.setForeground(Color.BLUE);
  673. mntmFairMinFirst.setForeground(mnFairnessModel.getForeground());
  674. controller.calculateStateAndVisualForCurrentTimeStep();
  675. // Update UpperNodes
  676. Component canvasOrUpperNodeCanvas = getScrollPaneFromTabbedPane()
  677. .getViewport().getComponent(0);
  678. if (canvasOrUpperNodeCanvas != null
  679. && canvasOrUpperNodeCanvas instanceof GroupNodeCanvas) {
  680. ((GroupNodeCanvas) canvasOrUpperNodeCanvas).repaint();
  681. }
  682. });
  683. menuBar.add(mnNewMenuView);
  684. mnNewMenuView.add(mntmCanvasSize);
  685. mntmCanvasSize.addActionListener(actionEvent -> {
  686. CanvasResizePopUp popUp = new CanvasResizePopUp(model, controller,
  687. canvas, tabbedPaneOriginal, tabbedPaneSplit,
  688. holegJFrame);
  689. popUp.setVisible(true);
  690. });
  691. mnNewMenuView.add(mntmCanvasSize);
  692. /*
  693. * Adds Checkbox to turn supply bars on/off
  694. */
  695. mnNewMenuView.add(showSupplyBarsCheckBox);
  696. showSupplyBarsCheckBox.setSelected(true);
  697. showSupplyBarsCheckBox.addActionListener(arg0 -> {
  698. controller.setShowSupplyBars(showSupplyBarsCheckBox.isSelected());
  699. canvas.repaint();
  700. // Update UpperNodes
  701. JScrollPane spane = getScrollPaneFromTabbedPane();
  702. if(spane != null){
  703. Component canvasOrUpperNodeCanvas = spane.getViewport().getComponent(0);
  704. if (canvasOrUpperNodeCanvas != null
  705. && canvasOrUpperNodeCanvas instanceof GroupNodeCanvas) {
  706. ((GroupNodeCanvas) canvasOrUpperNodeCanvas).repaint();
  707. }
  708. }
  709. });
  710. initWindowMenu();
  711. mnNewMenuView.add(mntmBackground);
  712. mntmBackground
  713. .addActionListener(actionEvent -> {
  714. tabTemp = tabbedPaneOriginal;
  715. JScrollPane scrollPane = getScrollPaneFromTabbedPane();
  716. if (scrollPane.getViewport().getComponent(0) instanceof MyCanvas) {
  717. BackgroundPopUp backgroundDialog = new BackgroundPopUp(
  718. model, controller, canvas, null,
  719. holegJFrame);
  720. backgroundDialog
  721. .setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
  722. backgroundDialog.setVisible(true);
  723. } else if (scrollPane.getViewport().getComponent(0) instanceof GroupNodeCanvas) {
  724. GroupNodeCanvas uNodeCanvas = (GroupNodeCanvas) (scrollPane
  725. .getViewport().getComponent(0));
  726. BackgroundPopUp backgroundDialog = new BackgroundPopUp(
  727. model, controller, null, uNodeCanvas.upperNode,
  728. holegJFrame);
  729. backgroundDialog
  730. .setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
  731. backgroundDialog.setVisible(true);
  732. uNodeCanvas.repaint();
  733. }
  734. });
  735. /**
  736. * add Help Menu and its items
  737. */
  738. menuBar.add(mnHelp);
  739. mnHelp.add(mntmIntroduction);
  740. mnHelp.add(mntmUserManual);
  741. mnHelp.add(mntmAlgorithmHelp);
  742. mnHelp.add(mntmCodeDoc);
  743. mnHelp.add(mntmAboutUs);
  744. tabbedPaneOriginal.addChangeListener(changeEvent -> {
  745. if (tabbedPaneOriginal.getSelectedComponent() == null) {
  746. Component tempC = tabbedPaneSplit.getSelectedComponent();
  747. tabbedPaneSplit.setComponentAt(
  748. tabbedPaneOriginal.getSelectedIndex(), null);
  749. tabbedPaneOriginal.setComponentAt(
  750. tabbedPaneOriginal.getSelectedIndex(), tempC);
  751. tempC = tabbedPaneOriginal.getComponentAt((tabbedPaneOriginal
  752. .getSelectedIndex() + 1)
  753. % (tabbedPaneOriginal.getTabCount()));
  754. tabbedPaneOriginal.setComponentAt(
  755. (tabbedPaneOriginal.getSelectedIndex() + 1)
  756. % (tabbedPaneOriginal.getTabCount()), null);
  757. tabbedPaneSplit.setComponentAt(
  758. (tabbedPaneOriginal.getSelectedIndex() + 1)
  759. % (tabbedPaneOriginal.getTabCount()), tempC);
  760. tabbedPaneSplit.setSelectedIndex((tabbedPaneOriginal
  761. .getSelectedIndex() + 1)
  762. % (tabbedPaneOriginal.getTabCount()));
  763. contentPane.updateUI();
  764. }
  765. });
  766. tabbedPaneSplit.addChangeListener(changeEvent -> {
  767. if (tabbedPaneSplit.getSelectedComponent() == null && !initSplit) {
  768. Component tempC = tabbedPaneOriginal
  769. .getComponentAt(tabbedPaneSplit.getSelectedIndex());
  770. tabbedPaneOriginal.setComponentAt(
  771. tabbedPaneSplit.getSelectedIndex(), null);
  772. tabbedPaneSplit.setComponentAt(
  773. tabbedPaneSplit.getSelectedIndex(), tempC);
  774. for (int i = 0; i < tabbedPaneOriginal.getTabCount(); i++) {
  775. if (tabbedPaneSplit.getComponentAt(i) != null
  776. && tabbedPaneSplit.getComponentAt(i) != tempC) {
  777. tempC = tabbedPaneSplit.getComponentAt(i);
  778. tabbedPaneSplit.setComponentAt(i, null);
  779. tabbedPaneOriginal.setComponentAt(i, tempC);
  780. break;
  781. }
  782. }
  783. if (tabbedPaneOriginal.getSelectedIndex() == tabbedPaneSplit
  784. .getSelectedIndex()) {
  785. tabbedPaneOriginal.setSelectedIndex((tabbedPaneSplit
  786. .getSelectedIndex() + 1)
  787. % tabbedPaneOriginal.getTabCount());
  788. }
  789. contentPane.updateUI();
  790. }
  791. });
  792. canvas.setBackground(Color.WHITE);
  793. canvas.setPreferredSize(new Dimension(model.getCanvasX(), model
  794. .getCanvasY()));
  795. /********************
  796. * RIGHT CONTAINER (INFORMATION)
  797. **********************/
  798. // Set up of the HolonElements section
  799. // Two different Models: Multi for multi-selection mode and Single for
  800. // single-selection mode (CPS-Object)
  801. model.getMultiTable().setColumnIdentifiers(columnNamesMulti);
  802. model.getSingleTable().setColumnIdentifiers(columnNamesSingle);
  803. model.getTableHolonElement().setBorder(null);
  804. model.getTableHolonElement().setFillsViewportHeight(true);
  805. model.getTableHolonElement().setCellSelectionEnabled(true);
  806. model.getTableHolonElement().setColumnSelectionAllowed(true);
  807. /*
  808. * Register Clicks on ColumNames for sorting:
  809. */
  810. model.getTableHolonElement().getTableHeader()
  811. .addMouseListener(new MouseAdapter() {
  812. public void mouseClicked(MouseEvent e) {
  813. //TODO: sort
  814. //clicked column
  815. int col = model.getTableHolonElement().columnAtPoint(
  816. e.getPoint());
  817. //insert column into UpdateController
  818. updCon.setSortBy(col);
  819. //refresh HolonElementTable
  820. updCon.refreshTableHolonElement(model.getMultiTable(), model.getSingleTable());
  821. }
  822. @Override
  823. public void mouseExited(MouseEvent e) {
  824. /**
  825. * Stop Editing, if mouse exits the Table
  826. */
  827. JTable holElem = model.getTableHolonElement();
  828. JTableHeader holElemHead = holElem.getTableHeader();
  829. if(e.getX()<=0 || e.getX()>=holElemHead.getWidth()
  830. || e.getY() <= 0){
  831. CellEditor cellEditor = holElem.getCellEditor();
  832. if (cellEditor != null) {
  833. if (cellEditor.getCellEditorValue() != null) {
  834. /** TODO: Maybe try to save current Data */
  835. cellEditor.stopCellEditing();
  836. } else {
  837. cellEditor.cancelCellEditing();
  838. }
  839. }
  840. }
  841. }
  842. });
  843. model.getTableHolonElement().getTableHeader().setReorderingAllowed(false);
  844. tableHolonElementScrollPane.setViewportView(model
  845. .getTableHolonElement());
  846. scrollElements.setLayout(new BorderLayout(0, 0));
  847. scrollElements.add(panelHolonEl, BorderLayout.NORTH);
  848. scrollElements.add(tableHolonElementScrollPane);
  849. panelHolonEl.setLayout(new BoxLayout(panelHolonEl, BoxLayout.X_AXIS));
  850. toolBarHolonEl.add(btnAddHolEL);
  851. toolBarHolonEl.add(btnDelHolEL);
  852. toolBarHolonEl.setFloatable(false);
  853. panelHolonEl.add(toolBarHolonEl);
  854. // Set up of the Properties section
  855. tableProperties.setModel(model.getPropertyTable());
  856. tableProperties.setFillsViewportHeight(true);
  857. tableProperties.setCellSelectionEnabled(true);
  858. tableProperties.setColumnSelectionAllowed(true);
  859. scrollProperties.setViewportView(tableProperties);
  860. // Set up of the Graph section
  861. tableGraph.setModel(tableModelGraph);
  862. tableGraph.setFillsViewportHeight(true);
  863. tableGraph.setCellSelectionEnabled(true);
  864. tableGraph.setColumnSelectionAllowed(true);
  865. scrollGraph.setViewportView(unitGraph);
  866. graphLabel.setLayout(new BorderLayout(0, 10));
  867. graphLabel.add(maxGraph, BorderLayout.NORTH);
  868. graphLabel.add(medGraph, BorderLayout.CENTER);
  869. graphLabel.add(minGraph, BorderLayout.SOUTH);
  870. toolBarGraph.setFloatable(false);
  871. toolBarGraph.setAlignmentY(Component.RIGHT_ALIGNMENT);
  872. localPeriodButton.setToolTipText("Toggle Local/Global Mode");
  873. toolBarGraph.add(localPeriodButton);
  874. //ComboBox
  875. localPeriodInput.setEditable(true);
  876. localPeriodInput.setVisible(false);
  877. localPeriodInput.setMaximumSize(new Dimension(20,23));
  878. localPeriodInput.addItemListener(aListener->{
  879. if(aListener.getStateChange() == ItemEvent.DESELECTED) {
  880. validateInput(localPeriodInput.getEditor().getItem().toString(), true);
  881. }
  882. });
  883. toolBarGraph.add(localPeriodInput);
  884. //localPeriodButtonFunction
  885. localPeriodButton.addActionListener(actionEvent->{
  886. boolean newState= !localPeriodInput.isVisible();
  887. changeLocalPeriodButtonAppeareance(newState);
  888. unitGraph.setUseLocalPeriod(newState);
  889. });
  890. toolBarGraph.add(Box.createHorizontalGlue());
  891. resetButton.setToolTipText("Reset");
  892. resetButton.addActionListener(actionEvent -> unitGraph.reset());
  893. toolBarGraph.add(resetButton);
  894. scrollGraph.setRowHeaderView(graphLabel);
  895. scrollGraph.setColumnHeaderView(toolBarGraph);
  896. tables.add(model.getSingleTable());
  897. tables.add(model.getMultiTable());
  898. /***********************
  899. * HolonElement Table Actions
  900. **********************/
  901. /*
  902. * Add HolonElement to given HolonObject
  903. */
  904. btnAddHolEL.addActionListener(actionEvent -> {
  905. if (model.getSelectedCpsObjects().size() == 1) {
  906. AbstractCanvasObject tempCpsObject = updCon.getActualCps();
  907. if (tempCpsObject != null
  908. && tempCpsObject.getClass() == HolonObject.class
  909. && tempCpsObject.getId() != 0) {
  910. addElementPopUp = new AddElementPopUp(holegJFrame);
  911. addElementPopUp.setActualHolonObject((HolonObject)updCon.getActualCps());
  912. addElementPopUp.setVisible(true);
  913. HolonElement ele = addElementPopUp.getElement();
  914. if (ele != null) {
  915. controller.addElementCanvasObject(
  916. tempCpsObject.getId(), ele.getEleName(),
  917. ele.getAmount(), ele.getEnergyPerElement(),
  918. ele.getId());
  919. }
  920. controller.calculateStateAndVisualForTimeStep(model
  921. .getCurIteration());
  922. triggerUpdateController(null);
  923. contentPane.updateUI();
  924. }
  925. }else
  926. {
  927. JOptionPane.showMessageDialog(contentPane, "No object selected.\nPlease select a object first." , "Message" , JOptionPane.INFORMATION_MESSAGE);
  928. }
  929. });
  930. btnAddHolEL.setIcon(new ImageIcon(ImageImport.loadImage("Images/plus.png", 16, 16)));
  931. btnAddHolEL.setToolTipText("<html><b>Add Element</b><br>Add a new HolonElement to the HolonObject.</html>");
  932. /*
  933. * Delete the chosen HolonElement of the selected HolonObject,
  934. * Multi-Selection for CpsObjects as well as for HolonElements possible
  935. */
  936. btnDelHolEL.addActionListener(actionEvent -> {
  937. // For Single Selection of CpsObject
  938. if (model.getSelectedCpsObjects().size() == 1) {
  939. if (updCon.getActualCps().getClass() == HolonObject.class) {
  940. HolonObject obj = (HolonObject) updCon.getActualCps();
  941. if(selectedElements.isEmpty())
  942. {
  943. JOptionPane.showMessageDialog(contentPane, "No element selectet.\nPlease select a element in the list first." , "Message" , JOptionPane.INFORMATION_MESSAGE);
  944. }
  945. for (HolonElement e : selectedElements) {
  946. controller.deleteElementCanvas(obj.getId(),
  947. e.getId());
  948. controller.calculateStateAndVisualForTimeStep(model
  949. .getCurIteration());
  950. triggerUpdateController(null);
  951. contentPane.updateUI();
  952. // Names displayed in graph are not updated
  953. }
  954. model.getEleToDelete().clear();
  955. selectedElements.clear();
  956. }
  957. // For MultiSelection of CpsObject
  958. } else if (model.getSelectedCpsObjects().size() > 1) {
  959. for (Integer i : model.getEleToDelete().keySet()) {
  960. for (HolonElement e : model.getEleToDelete().get(i)) {
  961. controller.deleteElementCanvas(i, e.getId());
  962. }
  963. }
  964. triggerUpdateController(null);
  965. model.getEleToDelete().clear();
  966. selectedElements.clear();
  967. }else
  968. {
  969. JOptionPane.showMessageDialog(contentPane, "No object selectet.\nPlease select a object first." , "No object selectet" , JOptionPane.INFORMATION_MESSAGE);
  970. }
  971. triggerUpdateController(null);
  972. elementGraph.setText("None");
  973. holonEleNamesDisplayed = "None";
  974. }) ;
  975. btnDelHolEL.setIcon(new ImageIcon(ImageImport.loadImage("Images/minus.png", 16, 16)));
  976. btnDelHolEL.setToolTipText("<html><b>Remove Element</b><br>Removes the selected HolonElement from the HolonObject.</html>");
  977. /*
  978. * Communication between HolonElement Table and displayed Graph and
  979. * Properties, as well as selection of different HolonElements
  980. */
  981. model.getTableHolonElement().addMouseListener(new MouseAdapter() {
  982. public void mousePressed(MouseEvent e) {
  983. HolonObject obj = null;
  984. if (model.getSelectedCpsObjects().size() == 1
  985. && model.getSelectedCpsObjects().get(0) instanceof HolonObject) {
  986. obj = (HolonObject) updCon.getActualCps();
  987. }
  988. yValueElements = e.getY();
  989. HolonElement ele;
  990. // Search for current clicked HolonElement
  991. if (model.getSelectedCpsObjects().size() == 1) {
  992. ele = updCon.getActualHolonElement(obj, yValueElements, 0,
  993. tables);
  994. } else {
  995. ele = updCon.getActualHolonElement(null, yValueElements, 0,
  996. tables);
  997. }
  998. // Multi-Selection of HolonElements through control button +
  999. // mouse click
  1000. if (ele != null) {
  1001. // make energy-consumption graph visible
  1002. showScrollGraph();
  1003. if (e.isControlDown()) {
  1004. if (!selectedElements.contains(ele)) {
  1005. selectedElements.add(ele);
  1006. if (!holonEleNamesDisplayed.equals("None")) {
  1007. holonEleNamesDisplayed = holonEleNamesDisplayed
  1008. + "; " + ele.getEleName() + " ";
  1009. } else {
  1010. holonEleNamesDisplayed = ele.getEleName() + " ";
  1011. }
  1012. updateUnitGraph((GraphEditable)selectedElements.get(selectedElements.size()-1));
  1013. }
  1014. updCon.getActualHolonElement(null, yValueElements, 2,
  1015. tables);
  1016. }
  1017. // if no control-button pressed but a HolonElement chosen
  1018. else {
  1019. selectedElements.clear();
  1020. selectedElements.add(ele);
  1021. updCon.getActualHolonElement(null, yValueElements, 1,
  1022. tables);
  1023. holonEleNamesDisplayed = ele.getEleName() + " ";
  1024. updateUnitGraph((GraphEditable)selectedElements.get(selectedElements.size()-1));
  1025. }
  1026. } else {
  1027. elementGraph.setText("None");
  1028. hideScrollGraph();
  1029. }
  1030. // if any HolonElement is double-clicked --> Edit-Mode started
  1031. // for selected HolonElement
  1032. if (e.getClickCount() == 2) {
  1033. yThis = e.getY();
  1034. xThis = e.getX();
  1035. }
  1036. // for single click and empty slot
  1037. if (e.getClickCount() == 1 && ele == null) {
  1038. selectedElements.clear();
  1039. holonEleNamesDisplayed = "None";
  1040. }
  1041. elementGraph.setText(holonEleNamesDisplayed);
  1042. yBTis = e.getY();
  1043. xBThis = e.getX();
  1044. }
  1045. @Override
  1046. public void mouseExited(MouseEvent e) {
  1047. /**
  1048. * Stop Editing, if mouse exits the Table
  1049. */
  1050. JTable holElem = model.getTableHolonElement();
  1051. if(e.getX()<=0 || e.getX()>=holElem.getWidth()
  1052. /*|| e.getY() <= 0*/|| e.getY()>= holElem.getHeight()){
  1053. CellEditor cellEditor = holElem.getCellEditor();
  1054. if (cellEditor != null) {
  1055. if (cellEditor.getCellEditorValue() != null) {
  1056. /** TODO: Maybe try to save current Data */
  1057. cellEditor.stopCellEditing();
  1058. } else {
  1059. cellEditor.cancelCellEditing();
  1060. }
  1061. }
  1062. }
  1063. }
  1064. });
  1065. /*
  1066. * Triggered every time a change is made
  1067. */
  1068. model.getTableHolonElement()
  1069. .addPropertyChangeListener(propertyChangeEvent -> {
  1070. try {
  1071. int yMouse = yThis;
  1072. int yBMouse = yBTis;
  1073. int selectedValueY = (int) Math.floor(yMouse / 16);
  1074. int selectedValueBY = (int) Math.floor(yBMouse / 16);
  1075. // ------------------ multi-selection mode
  1076. // ------------------
  1077. if (model.getSelectedCpsObjects().size() > 1) {
  1078. int selectedValueX = (int) Math
  1079. .floor(xThis
  1080. / (model.getTableHolonElement()
  1081. .getWidth() / 8));
  1082. int selectedValueBX = (int) Math
  1083. .floor(xBThis
  1084. / (model.getTableHolonElement()
  1085. .getWidth() / 8));
  1086. if (updCon.getHolonObj(yMouse,
  1087. model.getMultiTable()) != null) {
  1088. // For active column (boolean with a checkbox)
  1089. if (selectedValueBX == 6) {
  1090. System.out.println("selectedValueBX == 6");
  1091. HolonElement eleBTemp = updCon
  1092. .getActualHolonElement(null,
  1093. yBMouse, 0, tables);
  1094. String newBStuff = model
  1095. .getMultiTable()
  1096. .getValueAt(selectedValueBY,
  1097. selectedValueBX).toString();
  1098. Boolean bTemp = Boolean
  1099. .parseBoolean(newBStuff);
  1100. eleBTemp.setActive(bTemp);
  1101. }
  1102. // For activeFlex column (boolean with a
  1103. // checkbox)
  1104. else if (selectedValueBX == 7) {
  1105. HolonElement eleBTemp = updCon
  1106. .getActualHolonElement(null,
  1107. yBMouse, 0, tables);
  1108. String newBStuff = model
  1109. .getMultiTable()
  1110. .getValueAt(selectedValueBY,
  1111. selectedValueBX).toString();
  1112. Boolean bTemp = Boolean
  1113. .parseBoolean(newBStuff);
  1114. eleBTemp.setActive(bTemp);
  1115. } else {
  1116. //TODO: check all possible fields.
  1117. // Update of HolonElement
  1118. HolonElement eleTemp = updCon
  1119. .getActualHolonElement(null,
  1120. yMouse, 0, tables);
  1121. String newStuff = model
  1122. .getMultiTable()
  1123. .getValueAt(selectedValueY,
  1124. selectedValueX).toString();
  1125. // Name update
  1126. if (selectedValueX == 2) {
  1127. eleTemp.setEleName(newStuff);
  1128. }
  1129. // Energy Update
  1130. else if (selectedValueX == 3) {
  1131. Float ftemp = Float
  1132. .parseFloat(newStuff);
  1133. eleTemp.setEnergyPerElement(ftemp);
  1134. }
  1135. // Flexibility
  1136. else if (selectedValueX == 4) {
  1137. }
  1138. // Amount of Elements update
  1139. else if (selectedValueX == 5) {
  1140. Integer iTemp = Integer
  1141. .parseInt(newStuff);
  1142. eleTemp.setAmount(iTemp);
  1143. }
  1144. else if (selectedValueX == 6) {
  1145. }
  1146. }
  1147. }
  1148. } // ------------------ single-selection mode
  1149. // ------------------
  1150. else if (model.getSelectedCpsObjects().size() == 1) {
  1151. int selectedValueX = (int) Math
  1152. .floor(xThis
  1153. / (model.getTableHolonElement()
  1154. .getWidth() / 7));
  1155. int selectedValueBX = (int) Math
  1156. .floor(xBThis
  1157. / (model.getTableHolonElement()
  1158. .getWidth() / 7));
  1159. if (updCon.getActualCps() != null
  1160. && updCon.getActualCps().getClass() == HolonObject.class) {
  1161. HolonElement eleTemp;
  1162. // For active column (boolean with a checkbox)
  1163. if (selectedValueBX == 5) {
  1164. eleTemp = updCon.getActualHolonElement(
  1165. (HolonObject) updCon.getActualCps(),
  1166. yBMouse, 0, tables);
  1167. String newBStuff = model
  1168. .getSingleTable()
  1169. .getValueAt(selectedValueBY,
  1170. selectedValueBX).toString();
  1171. Boolean bTemp = Boolean
  1172. .parseBoolean(newBStuff);
  1173. eleTemp.setActive(bTemp);
  1174. } // For activeFlex column (boolean with a
  1175. // checkbox)
  1176. else if (selectedValueBX == 6) {
  1177. eleTemp = updCon.getActualHolonElement(
  1178. (HolonObject) updCon.getActualCps(),
  1179. yBMouse, 0, tables);
  1180. String newBStuff = model
  1181. .getSingleTable()
  1182. .getValueAt(selectedValueBY,
  1183. selectedValueBX -1).toString();
  1184. eleTemp.setActive(Boolean
  1185. .parseBoolean(newBStuff));
  1186. } else {
  1187. //TODO check all possible assignements.
  1188. // Update of HolonElement
  1189. eleTemp = updCon.getActualHolonElement(
  1190. (HolonObject) updCon.getActualCps(),
  1191. yMouse, 0, tables);
  1192. String newStuff = model
  1193. .getSingleTable()
  1194. .getValueAt(selectedValueY,
  1195. selectedValueX).toString();
  1196. // Name update
  1197. if (selectedValueX == 1) {
  1198. eleTemp.setEleName(newStuff);
  1199. } // Energy Update
  1200. else if (selectedValueX == 2) {
  1201. Float ftemp = Float
  1202. .parseFloat(newStuff);
  1203. eleTemp.setEnergyPerElement(ftemp);
  1204. } // Flexibility
  1205. else if (selectedValueX == 3) {
  1206. }
  1207. // Amount of Elements update
  1208. else if (selectedValueX == 4) {
  1209. Integer iTemp = Integer
  1210. .parseInt(newStuff);
  1211. eleTemp.setAmount(iTemp);
  1212. }
  1213. }
  1214. // set all cells anew, if anything was changed
  1215. updateElementTableAfterChange(eleTemp,
  1216. selectedValueBY);
  1217. }
  1218. }
  1219. controller.calculateStateAndVisualForTimeStep(model
  1220. .getCurIteration());
  1221. model.getSingleTable().fireTableDataChanged();
  1222. triggerUpdateController(null);
  1223. contentPane.updateUI();
  1224. unitGraph.repaint();
  1225. // trigger update of table after UnitGraph was painted
  1226. SwingUtilities.invokeLater(() -> {
  1227. triggerUpdateController(null);
  1228. });
  1229. } catch (Exception e) {
  1230. }
  1231. });
  1232. /***********************
  1233. * HolonElement Properties Actions
  1234. **********************/
  1235. /*
  1236. * Update of the mouse coord for Edit-Mode
  1237. */
  1238. tableProperties.addMouseListener(new MouseAdapter() {
  1239. public void mousePressed(MouseEvent e) {
  1240. if (e.getClickCount() == 2) {
  1241. yProThis = e.getY();
  1242. xProThis = e.getX();
  1243. }
  1244. yProThisOneClick = e.getY();
  1245. xProThisOneClick = e.getX();
  1246. }
  1247. });
  1248. /*
  1249. * Update any change in the Property table
  1250. */
  1251. tableProperties.addPropertyChangeListener(propertyChangeEvent -> {
  1252. try {
  1253. Object temp;
  1254. Object btemp;
  1255. int selValueY = (int) Math.floor(yProThis / 16);
  1256. int selValueX = (int) Math.floor(xProThis
  1257. / (tableProperties.getWidth() / 2));
  1258. int selValueYBool = (int) Math.floor(yProThisOneClick / 16);
  1259. int selValueXBool = (int) Math.floor(xProThisOneClick
  1260. / (tableProperties.getWidth() / 2));
  1261. if (updCon.getActualCps() != null) {
  1262. temp = model.getPropertyTable().getValueAt(selValueY,
  1263. selValueX);
  1264. btemp = model.getPropertyTable().getValueAt(selValueYBool,
  1265. selValueXBool);
  1266. // Case: Switch selected
  1267. if (updCon.getActualCps() instanceof HolonSwitch) {
  1268. if (selValueY == 0 && selValueX != 0) {
  1269. updCon.getActualCps().setName(temp.toString());
  1270. }
  1271. if (selValueYBool == 2) {
  1272. Boolean bbTemp = Boolean.parseBoolean(btemp.toString());
  1273. ((HolonSwitch) updCon.getActualCps())
  1274. .setManualMode(bbTemp);
  1275. if (bbTemp) {
  1276. model.getPropertyTable()
  1277. .setCellEditable(3, 1, true);
  1278. } else {
  1279. model.getPropertyTable().setCellEditable(3, 1,
  1280. false);
  1281. }
  1282. } else if (selValueYBool == 3) {
  1283. if (((HolonSwitch) updCon.getActualCps())
  1284. .getManualMode()) {
  1285. model.getPropertyTable()
  1286. .setCellEditable(3, 1, true);
  1287. Boolean bTemp = Boolean.parseBoolean(btemp
  1288. .toString());
  1289. ((HolonSwitch) updCon.getActualCps())
  1290. .setManualState(bTemp);
  1291. }
  1292. }
  1293. } // Case: UpperNode selected
  1294. else if (updCon.getActualCps() instanceof GroupNode
  1295. && selValueX != 0) {
  1296. // Name edition through double click
  1297. updCon.getActualCps().setName(temp.toString());
  1298. // Update of name on the tab in the tab section
  1299. for (int index = 4; index < tabbedPaneOriginal
  1300. .getTabCount(); index++) {
  1301. tabTemp = tabbedPaneOriginal;
  1302. JScrollPane scrollPane = getScrollPaneFromTabbedPane();
  1303. GroupNodeCanvas unc = ((GroupNodeCanvas) scrollPane
  1304. .getViewport().getComponent(0));
  1305. if (unc.upperNode.getId() == updCon.getActualCps()
  1306. .getId()) {
  1307. tabbedPaneOriginal.setTitleAt(index,
  1308. unc.upperNode.getName());
  1309. tabbedPaneOriginal.updateUI();
  1310. if (!initSplit) {
  1311. tabbedPaneSplit.setTitleAt(index,
  1312. unc.upperNode.getName());
  1313. tabbedPaneSplit.updateUI();
  1314. }
  1315. }
  1316. }
  1317. } // Case: HolonObject is selected
  1318. else if (updCon.getActualCps() instanceof HolonObject
  1319. && selValueX != 0) {
  1320. // Name edition through double click
  1321. updCon.getActualCps().setName(temp.toString());
  1322. }
  1323. } // Case: Edge is selected
  1324. else {
  1325. temp = model.getPropertyTable()
  1326. .getValueAt(selValueY, selValueX);
  1327. btemp = model.getPropertyTable().getValueAt(selValueYBool,
  1328. selValueXBool);
  1329. // Edit modus for capacity by double clicking
  1330. if (selValueY == 2) {
  1331. Float ftemp;
  1332. if (Float.parseFloat(temp.toString()) >= 0.0) {
  1333. ftemp = Float.parseFloat(temp.toString());
  1334. } else {
  1335. ftemp = model.getSelectedEdge().getCapacity();
  1336. }
  1337. model.getSelectedEdge().setCapacity(ftemp);
  1338. }
  1339. }
  1340. canvas.repaint();
  1341. } catch (Exception e) {
  1342. }
  1343. }) ;
  1344. /***********************
  1345. * HolonElement Graph Actions
  1346. **********************/
  1347. /*
  1348. * Update Local Period of an Element Graph
  1349. */
  1350. unitGraphLocalPeriod.addKeyListener(new KeyAdapter() {
  1351. @Override
  1352. public void keyReleased(KeyEvent e) {
  1353. try{
  1354. int localLength = Integer.parseInt(unitGraphLocalPeriod.getText());
  1355. unitGraphLocalPeriod.setBackground(Color.WHITE);
  1356. /**
  1357. * set local graph Period
  1358. */
  1359. if(e.getKeyCode() == KeyEvent.VK_ENTER)
  1360. unitGraph.setLocalPeriod(localLength);
  1361. }catch(NumberFormatException ex){
  1362. unitGraphLocalPeriod.setBackground(PALE_RED);
  1363. }
  1364. }
  1365. });
  1366. /*****************************
  1367. * RIGHT CONTAINER DONE
  1368. *****************************/
  1369. holegJFrame.getContentPane().setLayout(new BorderLayout(0, 0));
  1370. /****************
  1371. * Tree Stuff
  1372. ****************/
  1373. // Override Key Actions
  1374. inputMap = categoryTree.getInputMap();
  1375. inputMap.put(KeyStroke.getKeyStroke("control C"), cntrlCDown);
  1376. inputMap.put(KeyStroke.getKeyStroke("control V"), cntrlVDown);
  1377. inputMap.put(KeyStroke.getKeyStroke("control X"), cntrlXDown);
  1378. inputMap.put(KeyStroke.getKeyStroke("control A"), cntrlADown);
  1379. TreeCellRenderer customRenderer = new TreeCellRenderer() {
  1380. @Override
  1381. public Component getTreeCellRendererComponent(JTree tree,
  1382. Object value, boolean selected, boolean expanded,
  1383. boolean leaf, int row, boolean hasFocus) {
  1384. JLabel label = new JLabel();
  1385. Image imgR;
  1386. if (leaf) {
  1387. for (Category cat : model.getCategories()) {
  1388. for (AbstractCanvasObject cps : cat.getObjects()) {
  1389. if (value.toString().compareTo(cps.getObjName()) == 0) {
  1390. imgR = ImageImport.loadImage(cps.getImage(), 50,
  1391. 50);
  1392. if (imgR != null) {
  1393. label.setIcon(new ImageIcon(imgR));
  1394. }
  1395. label.setText(cps.getName());
  1396. }
  1397. }
  1398. }
  1399. }
  1400. tree.setRowHeight(50);
  1401. if (hasFocus) {
  1402. label.setForeground(new Color(0, 0, 255));
  1403. label.setOpaque(true);
  1404. }
  1405. if (label.getText().length() == 0) {
  1406. label.setText(value.toString());
  1407. if (value.toString().compareTo("Categories") != 0) {
  1408. label.setIcon(new ImageIcon(ImageImport.loadImage(
  1409. "/Images/folder.png")));
  1410. }
  1411. }
  1412. return label;
  1413. }
  1414. };
  1415. categoryTree.setCellRenderer(customRenderer);
  1416. categoryTree.addMouseMotionListener(new MouseMotionAdapter() {
  1417. public void mouseDragged(MouseEvent e){
  1418. checkForDragAndDrop(e);
  1419. }
  1420. /**
  1421. * checks if an object of the current Panel
  1422. * could be replaced by the dragged object
  1423. * @param e
  1424. */
  1425. private void checkForDragAndDrop(MouseEvent e){
  1426. try {
  1427. /**
  1428. * if no object gets dragged -> finished
  1429. */
  1430. if(!dragging)return;
  1431. /**
  1432. * select the current Panel
  1433. */
  1434. chooseTabTemp();
  1435. JScrollPane scrollPane = getScrollPaneFromTabbedPane();
  1436. if(scrollPane == null)return;
  1437. Component canvasOrUpperNodeCanvas = scrollPane
  1438. .getViewport().getComponent(0);
  1439. /**
  1440. * check for replacements on the canvas
  1441. */
  1442. if (canvasOrUpperNodeCanvas instanceof GroupNodeCanvas) {
  1443. GroupNodeCanvas unc = (GroupNodeCanvas) canvasOrUpperNodeCanvas;
  1444. if(unc.getMousePosition()==null)return;
  1445. int x = (int) unc.getMousePosition().getX()+16;
  1446. int y = (int) unc.getMousePosition().getY()+16;
  1447. /**
  1448. * if in upperNode
  1449. */
  1450. if (x <= unc.upperNode.getLeftBorder()) return;
  1451. /**
  1452. * check for replacement
  1453. */
  1454. unc.checkForReplacement(x, y);
  1455. /**
  1456. * repaint
  1457. */
  1458. unc.invalidate();
  1459. unc.repaint();
  1460. } else {
  1461. if(canvas.getMousePosition()==null)return;
  1462. int x = (int) canvas.getMousePosition().getX()+16;
  1463. int y = (int) canvas.getMousePosition().getY()+16;
  1464. /**
  1465. * check for replacement
  1466. */
  1467. canvas.checkForReplacement(x, y);
  1468. /**
  1469. * repaint
  1470. */
  1471. canvas.invalidate();
  1472. canvas.repaint();
  1473. }
  1474. contentPane.updateUI();
  1475. } catch (Exception eex) {
  1476. eex.printStackTrace();
  1477. }
  1478. }});
  1479. categoryTree.addMouseListener(new MouseAdapter() {
  1480. public void mouseReleased(MouseEvent e) {
  1481. try {
  1482. if (dragging) {
  1483. chooseTabTemp();
  1484. JScrollPane scrollPane = getScrollPaneFromTabbedPane();
  1485. Component canvasOrUpperNodeCanvas = scrollPane
  1486. .getViewport().getComponent(0);
  1487. if (canvasOrUpperNodeCanvas instanceof GroupNodeCanvas) {
  1488. GroupNodeCanvas unc = (GroupNodeCanvas) canvasOrUpperNodeCanvas;
  1489. int x = (int) unc.getMousePosition().getX() + 16;
  1490. int y = (int) unc.getMousePosition().getY() + 16;
  1491. if (x > unc.upperNode.getLeftBorder()) {
  1492. AbstractCanvasObject h = null;
  1493. if (tempCps instanceof HolonObject) {
  1494. h = new HolonObject((HolonObject)tempCps);
  1495. }
  1496. if (tempCps instanceof HolonSwitch) {
  1497. h = new HolonSwitch(tempCps);
  1498. }
  1499. h.setPosition(x, y);
  1500. /**
  1501. * close UpperNodeTabs of replaced UpperNode
  1502. */
  1503. if(unc.mayBeReplaced!=null &&unc.mayBeReplaced instanceof GroupNode){
  1504. unc.closeUpperNodeTab(unc.mayBeReplaced.getId());
  1505. }
  1506. controller.addObjUpperNode(h, unc.upperNode);
  1507. /**
  1508. * object would be replaced
  1509. */
  1510. unc.mayBeReplaced = null;
  1511. unc.invalidate();
  1512. controller.calculateStateAndVisualForCurrentTimeStep();
  1513. unc.repaint();
  1514. unc.setXY((int) canvas.getMousePosition()
  1515. .getX(), (int) canvas
  1516. .getMousePosition().getY());
  1517. }
  1518. } else {
  1519. int x = (int) canvas.getMousePosition().getX() + 16;
  1520. int y = (int) canvas.getMousePosition().getY() + 16;
  1521. AbstractCanvasObject h = null;
  1522. if (tempCps instanceof HolonObject) {
  1523. h = new HolonObject((HolonObject)tempCps);
  1524. }
  1525. if (tempCps instanceof HolonSwitch) {
  1526. h = new HolonSwitch(tempCps);
  1527. }
  1528. h.setPosition(x, y);
  1529. /**
  1530. * close UpperNodeTabs of replaced UpperNode
  1531. */
  1532. if(canvas.mayBeReplaced!=null &&canvas.mayBeReplaced instanceof GroupNode){
  1533. canvas.closeUpperNodeTab(canvas.mayBeReplaced.getId());
  1534. }
  1535. controller.addObjectCanvas(h);
  1536. /**
  1537. * no object should get replaced
  1538. */
  1539. canvas.mayBeReplaced = null;
  1540. canvas.invalidate();
  1541. canvas.setXY(
  1542. (int) canvas.getMousePosition().getX(),
  1543. (int) canvas.getMousePosition().getY());
  1544. canvas.repaint();
  1545. }
  1546. controller.calculateStateAndVisualForCurrentTimeStep();
  1547. contentPane.updateUI();
  1548. dragging = false;
  1549. }
  1550. } catch (Exception eex) {
  1551. }
  1552. holegJFrame.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
  1553. }
  1554. });
  1555. popmenuEdit.add(editItem);
  1556. popmenuEdit.add(removeItem);
  1557. editItem.setEnabled(false);
  1558. editItem.addActionListener(actionEvent -> {
  1559. });
  1560. categoryTree.addMouseListener(new MouseAdapter() {
  1561. public void mousePressed(MouseEvent e) {
  1562. try {
  1563. actualObjectClicked = categoryTree
  1564. .getPathForLocation(e.getX(), e.getY())
  1565. .getLastPathComponent().toString();
  1566. // if an Object was selected, the porperties are shown in
  1567. // the table
  1568. DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) categoryTree
  1569. .getPathForLocation(e.getX(), e.getY())
  1570. .getLastPathComponent();
  1571. if (selectedNode.getLevel() == 2) {
  1572. controller.searchCategoryObject(selectedNode
  1573. .getParent().toString(), selectedNode
  1574. .toString());
  1575. updCon.deleteRows(model.getSingleTable());
  1576. updCon.deleteRows(model.getMultiTable());
  1577. // if (selected instanceof HolonObject && selected !=
  1578. // null) {
  1579. // selected = (HolonObject) selected;
  1580. // fillElementTable(((HolonObject)
  1581. // selected).getElements());
  1582. // }
  1583. }
  1584. if (SwingUtilities.isRightMouseButton(e)) {
  1585. for (Category cat : model.getCategories()) {
  1586. for (AbstractCanvasObject cps : cat.getObjects()) {
  1587. if (actualObjectClicked.compareTo(cps
  1588. .getObjName()) == 0
  1589. && !(cps instanceof HolonSwitch)) {
  1590. editItem.setEnabled(true);
  1591. popmenuEdit.show(e.getComponent(),
  1592. e.getX(), e.getY());
  1593. catOfObjToBeEdited = selectedNode
  1594. .getParent().toString();
  1595. tempCps = cps;
  1596. }
  1597. }
  1598. }
  1599. } else {
  1600. for (Category cat : model.getCategories()) {
  1601. for (AbstractCanvasObject cps : cat.getObjects()) {
  1602. if (actualObjectClicked.compareTo(cps
  1603. .getObjName()) == 0) {
  1604. File checkPath = new File(cps.getImage());
  1605. if (checkPath.exists()) {
  1606. img = new ImageIcon(cps.getImage())
  1607. .getImage()
  1608. .getScaledInstance(
  1609. 32,
  1610. 32,
  1611. java.awt.Image.SCALE_SMOOTH);
  1612. } else {
  1613. img = ImageImport.loadImage(
  1614. cps.getImage(), 32, 32);
  1615. }
  1616. tempCps = cps;
  1617. dragging = true;
  1618. Cursor cursor = Toolkit.getDefaultToolkit()
  1619. .createCustomCursor(img,
  1620. new Point(0, 0), "Image");
  1621. holegJFrame.setCursor(cursor);
  1622. }
  1623. }
  1624. }
  1625. }
  1626. } catch (Exception eex) {
  1627. }
  1628. }
  1629. });
  1630. editItem.addActionListener(actionEvent -> {
  1631. // Remove the selected Object object
  1632. //AddObjectPopUp(boolean edit, AbstractCpsObject obj, String cat, JFrame parentFrame)
  1633. System.out.println("Edit");
  1634. addObjectPopUP = new AddObjectPopUp(true, tempCps,
  1635. catOfObjToBeEdited, holegJFrame);
  1636. addObjectPopUP.setCategory(catOfObjToBeEdited);
  1637. addObjectPopUP.setController(controller);
  1638. addObjectPopUP.setVisible(true);
  1639. });
  1640. removeItem.addActionListener(actionEvent -> {
  1641. // Remove the selected Object object
  1642. try {
  1643. System.out.println("catOfObjToBeEdited:" + catOfObjToBeEdited + ", tempCps:" + tempCps);
  1644. controller.delObjectCategory(catOfObjToBeEdited, tempCps.getName());
  1645. }catch(IOException e) {
  1646. System.err.println("IOException");
  1647. e.printStackTrace();
  1648. }
  1649. });
  1650. scrollPane1.setViewportView(categoryTree);
  1651. scrollPane1.setColumnHeaderView(panel);
  1652. panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
  1653. toolBar.setAlignmentX(Component.LEFT_ALIGNMENT);
  1654. toolBar.setFloatable(false);
  1655. panel.add(toolBar);
  1656. btnAddPopUp.add(mItemNew);
  1657. mItemNew.addActionListener(actionEvent -> {
  1658. new CreateNewDialog(controller, holegJFrame);
  1659. });
  1660. btnAddPopUp.addSeparator();
  1661. btnAddPopUp.add(mItemCategory);
  1662. mItemCategory.addActionListener(actionEvent -> {
  1663. new CreateNewDialog(controller,Option.Category, holegJFrame);
  1664. });
  1665. btnAddPopUp.add(mItemObject);
  1666. mItemObject.addActionListener(actionEvent -> {
  1667. new CreateNewDialog(controller,Option.Object, holegJFrame);
  1668. });
  1669. btnAddPopUp.add(mItemSwitch);
  1670. mItemSwitch.addActionListener(actionEvent -> {
  1671. new CreateNewDialog(controller,Option.Switch, holegJFrame);
  1672. });
  1673. btnAdd.addActionListener(actionEvent -> btnAddPopUp.show(btnAdd, -1, +20));
  1674. btnAdd.setIcon(new ImageIcon(ImageImport.loadImage("Images/plus.png", 16, 16)));
  1675. btnAdd.setToolTipText("<html><b>New</b><br>Add a new Category or Item to the library.</html>");
  1676. toolBar.add(btnAdd);
  1677. /**
  1678. * Help Menu Action Listeners
  1679. */
  1680. /**
  1681. * URL of the telecommunication git Wiki
  1682. */
  1683. String tkWikiWebpage = "https://git.tk.informatik.tu-darmstadt.de/carlos.garcia/praktikum-holons/wiki/";
  1684. /** open Introduction Web Page */
  1685. mntmIntroduction.addMouseListener(new MouseAdapter() {
  1686. @Override
  1687. public void mousePressed(MouseEvent e){
  1688. openWebpage(tkWikiWebpage + "Introduction+V2.1");
  1689. }
  1690. });
  1691. /** open UserManual WebPage */
  1692. mntmUserManual.addMouseListener(new MouseAdapter() {
  1693. @Override
  1694. public void mousePressed(MouseEvent e){
  1695. openWebpage(tkWikiWebpage + "User+Manual+V2.1");
  1696. }
  1697. });
  1698. /** open Algorithm Help Web Page*/
  1699. mntmAlgorithmHelp.addMouseListener(new MouseAdapter() {
  1700. @Override
  1701. public void mousePressed(MouseEvent e){
  1702. openWebpage(tkWikiWebpage + "Algorithms+V2.1");
  1703. }
  1704. });
  1705. /** open Code Documentation Web Page */
  1706. mntmCodeDoc.addMouseListener(new MouseAdapter() {
  1707. @Override
  1708. public void mousePressed(MouseEvent e){
  1709. openWebpage(tkWikiWebpage + "Code+documentation+V2.1");
  1710. }
  1711. });
  1712. /**
  1713. * Pop up - About Us with some important information about the
  1714. * developers, source and programming stuff
  1715. */
  1716. mntmAboutUs.addMouseListener(new MouseAdapter() {
  1717. @Override
  1718. public void mousePressed(MouseEvent e) {
  1719. aboutUsPopUp = new AboutUsPopUp(holegJFrame);
  1720. aboutUsPopUp.setVisible(true);
  1721. }
  1722. });
  1723. /**
  1724. * Update of every interaction between the user and the canvas (only on
  1725. * the canvas). Basically the update of all the information concerning
  1726. * the clicked HolonObject. For multi-selection, the propertyTable would
  1727. * be disabled
  1728. */
  1729. canvas.addMouseListener(new MouseAdapter() {
  1730. @Override
  1731. public void mousePressed(MouseEvent e) {
  1732. }
  1733. @Override
  1734. public void mouseReleased(MouseEvent e) {
  1735. holonEleNamesDisplayed = "None";
  1736. // If any empty space is clicked
  1737. if (temp == null || temp.getId() != model.getSelectedObjectID()) {
  1738. hideScrollGraph();
  1739. elementGraph.setText("None");
  1740. }
  1741. temp = updCon.getActualCps();
  1742. // Erase old data in the PropertyTable
  1743. if (model.getPropertyTable().getRowCount() > 0) {
  1744. for (int i = model.getPropertyTable().getRowCount() - 1; i > -1; i--) {
  1745. model.getPropertyTable().removeRow(i);
  1746. }
  1747. }
  1748. if (e.isControlDown() && temp != null) {
  1749. if (model.getSelectedCpsObjects().contains(temp)) {
  1750. controller.deleteSelectedObject(temp);
  1751. } else {
  1752. controller.addSelectedObject(temp);
  1753. }
  1754. }
  1755. if (temp instanceof HolonSwitch) {
  1756. showScrollGraph();
  1757. updateUnitGraph((GraphEditable)temp);
  1758. }
  1759. // Write new data in the PropertyTable
  1760. triggerUpdateController(temp);
  1761. // New Tab with NodeOfNode
  1762. if (doubleClick() && MouseEvent.BUTTON3 != e.getButton()
  1763. && temp instanceof GroupNode) {
  1764. openNewUpperNodeTab();
  1765. try {
  1766. controller.autoSave();
  1767. } catch (IOException e1) {
  1768. e1.printStackTrace();
  1769. }
  1770. }
  1771. if (model.getSelectedCpsObjects().size() > 1) {
  1772. model.getTableHolonElement()
  1773. .setModel(model.getMultiTable());
  1774. } else if (model.getSelectedCpsObjects().size() == 1) {
  1775. model.getTableHolonElement().setModel(
  1776. model.getSingleTable());
  1777. }
  1778. }
  1779. });
  1780. // Del Button
  1781. btnDel.addActionListener(actionEvent -> {
  1782. Object nodeInfo = categoryTree.getLastSelectedPathComponent();
  1783. if (nodeInfo != null) {
  1784. DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) nodeInfo;
  1785. String nodeName = selectedNode.getUserObject().toString();
  1786. int depthOfNode = selectedNode.getLevel();
  1787. try {
  1788. switch (depthOfNode) {
  1789. case 1:
  1790. int dialogResult = JOptionPane.showConfirmDialog(
  1791. holegJFrame, eraseCategory + nodeName
  1792. + "?", warningText,
  1793. JOptionPane.YES_NO_OPTION);
  1794. if (dialogResult == JOptionPane.YES_OPTION) {
  1795. controller.deleteCategory(nodeName);
  1796. }
  1797. break;
  1798. case 2:
  1799. DefaultMutableTreeNode parent = (DefaultMutableTreeNode) selectedNode
  1800. .getParent();
  1801. controller.delObjectCategory(parent.getUserObject()
  1802. .toString(), nodeName);
  1803. break;
  1804. default:
  1805. JOptionPane.showMessageDialog(holegJFrame,
  1806. selectObjBeforeErase);
  1807. }
  1808. } catch (Exception e2) {
  1809. }
  1810. } else {
  1811. JOptionPane.showMessageDialog(holegJFrame,
  1812. selectObjBeforeErase);
  1813. }
  1814. categoryTree.repaint();
  1815. });
  1816. btnDel.setIcon(new ImageIcon(ImageImport.loadImage("Images/minus.png", 16, 16)));
  1817. btnDel.setToolTipText("<html><b>Delete</b><br>Removes a Category or a Category Item.</html>");
  1818. toolBar.add(btnDel);
  1819. holegJFrame.getContentPane().add(splitPane);
  1820. mntmNew.addActionListener(actionEvent -> {
  1821. if (model.getObjectsOnCanvas().size() != 0) {
  1822. int newWarning = JOptionPane.YES_NO_OPTION;
  1823. int dialogForNewWarning = JOptionPane.showConfirmDialog(
  1824. holegJFrame, saveBeforeNew, warningText,
  1825. newWarning);
  1826. if (dialogForNewWarning == JOptionPane.YES_OPTION) {
  1827. mntmSave.doClick();
  1828. }
  1829. }
  1830. model.getEdgesOnCanvas().removeAll(model.getEdgesOnCanvas());
  1831. model.getObjectsOnCanvas().removeAll(model.getObjectsOnCanvas());
  1832. controller.setSelectedObjectID(0);
  1833. controller.setSelecteEdge(null);
  1834. controller.setCurIteration(0);
  1835. hideScrollGraph();
  1836. elementGraph.setText("None");
  1837. canvas.tempCps = null;
  1838. canvas.repaint();
  1839. IdCounter.resetObjectCounter(CounterType.Object);
  1840. IdCounter.resetObjectCounter(CounterType.Element);
  1841. controller.calculateStateAndVisualForCurrentTimeStep();
  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 ().getMenuShortcutKeyMaskEx()));
  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 ().getMenuShortcutKeyMaskEx()));
  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 ().getMenuShortcutKeyMaskEx()));
  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. }