GUI.java 92 KB

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