GUI.java 88 KB

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