GUI.java 92 KB

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