GUI.java 92 KB

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