GUI.java 89 KB

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