GUI.java 51 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519
  1. package holeg.ui.view.main;
  2. import java.awt.BorderLayout;
  3. import java.awt.Color;
  4. import java.awt.Component;
  5. import java.awt.Cursor;
  6. import java.awt.Dimension;
  7. import java.awt.GraphicsDevice;
  8. import java.awt.GraphicsEnvironment;
  9. import java.awt.HeadlessException;
  10. import java.awt.Image;
  11. import java.awt.Point;
  12. import java.awt.Rectangle;
  13. import java.awt.Toolkit;
  14. import java.awt.datatransfer.UnsupportedFlavorException;
  15. import java.awt.event.ActionEvent;
  16. import java.awt.event.ActionListener;
  17. import java.awt.event.ComponentAdapter;
  18. import java.awt.event.ComponentEvent;
  19. import java.awt.event.KeyAdapter;
  20. import java.awt.event.KeyEvent;
  21. import java.awt.event.MouseAdapter;
  22. import java.awt.event.MouseEvent;
  23. import java.awt.event.MouseMotionAdapter;
  24. import java.io.File;
  25. import java.io.IOException;
  26. import java.net.URI;
  27. import java.util.ArrayList;
  28. import java.util.Collection;
  29. import java.util.logging.Logger;
  30. import java.util.stream.Collectors;
  31. import javax.swing.AbstractAction;
  32. import javax.swing.ActionMap;
  33. import javax.swing.BoxLayout;
  34. import javax.swing.ImageIcon;
  35. import javax.swing.InputMap;
  36. import javax.swing.JButton;
  37. import javax.swing.JCheckBoxMenuItem;
  38. import javax.swing.JComponent;
  39. import javax.swing.JFileChooser;
  40. import javax.swing.JFrame;
  41. import javax.swing.JLabel;
  42. import javax.swing.JMenu;
  43. import javax.swing.JMenuBar;
  44. import javax.swing.JMenuItem;
  45. import javax.swing.JOptionPane;
  46. import javax.swing.JPanel;
  47. import javax.swing.JPopupMenu;
  48. import javax.swing.JScrollPane;
  49. import javax.swing.JSplitPane;
  50. import javax.swing.JTabbedPane;
  51. import javax.swing.JTextField;
  52. import javax.swing.JToolBar;
  53. import javax.swing.JTree;
  54. import javax.swing.KeyStroke;
  55. import javax.swing.SwingUtilities;
  56. import javax.swing.filechooser.FileNameExtensionFilter;
  57. import javax.swing.tree.DefaultMutableTreeNode;
  58. import javax.swing.tree.DefaultTreeModel;
  59. import javax.swing.tree.TreeCellRenderer;
  60. import org.apache.commons.compress.archivers.ArchiveException;
  61. import com.google.gson.JsonParseException;
  62. import holeg.model.AbstractCanvasObject;
  63. import holeg.model.GroupNode;
  64. import holeg.model.HolonObject;
  65. import holeg.model.HolonSwitch;
  66. import holeg.preferences.ColorPreference;
  67. import holeg.preferences.ImagePreference;
  68. import holeg.ui.controller.Control;
  69. import holeg.ui.model.GuiSettings;
  70. import holeg.ui.model.IdCounter;
  71. import holeg.ui.model.IdCounter.CounterType;
  72. import holeg.ui.model.Model;
  73. import holeg.ui.model.Model.FairnessModel;
  74. import holeg.ui.view.canvas.Canvas;
  75. import holeg.ui.view.component.ButtonTabComponent;
  76. import holeg.ui.view.dialog.AboutUsPopUp;
  77. import holeg.ui.view.dialog.AddObjectPopUp;
  78. import holeg.ui.view.dialog.CanvasResizePopUp;
  79. import holeg.ui.view.dialog.CreateNewDialog;
  80. import holeg.ui.view.dialog.CreateNewDialog.Option;
  81. import holeg.ui.view.dialog.EditEdgesPopUp;
  82. import holeg.ui.view.information.HolonInformationPanel;
  83. import holeg.ui.view.inspector.Inspector;
  84. import holeg.ui.view.inspector.UnitGraph;
  85. import holeg.ui.view.window.AddOnWindow;
  86. import holeg.ui.view.window.FlexWindow;
  87. import holeg.ui.view.window.Outliner;
  88. import holeg.utility.image.Import;
  89. /**
  90. * Graphical User Interface.
  91. *
  92. * @author Gruppe14
  93. */
  94. public class GUI {
  95. private static final Logger log = Logger.getLogger(Model.class.getName());
  96. /**
  97. * Menu on the Top containing File, Edit View Help etc
  98. */
  99. private final JMenuBar menuBar = new JMenuBar();
  100. private final JMenu mnNewMenu = new JMenu("File");
  101. private final JMenu mnNewMenuEdit = new JMenu("Edit");
  102. private final JMenu mnNewMenuOptions = new JMenu("Options");
  103. private final JMenu mnNewMenuView = new JMenu("View");
  104. private final JMenu menuWindow = new JMenu("Window");
  105. /** Help Menu containing helpful Informations and the AboutUs Popup */
  106. private final JMenu mnHelp = new JMenu("Help");
  107. /**
  108. * Help -> Introduction A small Introduction of the Application, SmartGrids and
  109. * Holons
  110. */
  111. private final JMenuItem mntmIntroduction = new JMenuItem("Introduction");
  112. /**
  113. * Help -> UserManual
  114. */
  115. private final JMenuItem mntmUserManual = new JMenuItem("User Manual");
  116. /** Help -> Algorithm Help Menu */
  117. private final JMenuItem mntmAlgorithmHelp = new JMenuItem("Algorithm Introduction");
  118. /** Help -> CodeDocumentation */
  119. private final JMenuItem mntmCodeDoc = new JMenuItem("Code Documentation");
  120. /** Help -> AboutUs */
  121. private final JMenuItem mntmAboutUs = new JMenuItem("About Us");
  122. /** checked if supplyBars should be shown */
  123. private final JCheckBoxMenuItem showSupplyBarsCheckBox = new JCheckBoxMenuItem("Show supply bars.");
  124. /** menu for the different fairness Models */
  125. private final JMenu mnFairnessModel = new JMenu("Fairness Model");
  126. /** press to supply minimum demand first */
  127. private final JMenuItem mntmFairMinFirst = new JMenuItem("Minimum demand first");
  128. /** press to give everyone the same energy */
  129. private final JMenuItem mntmFairAlleEqual = new JMenuItem("Equal supply for everyone");
  130. private final JMenuItem mntmOpen = new JMenuItem("Open");
  131. private final JMenuItem mntmNew = new JMenuItem("New");
  132. private final JMenuItem mntmSave = new JMenuItem("Save");
  133. private final JMenuItem mntmCanvasSize = new JMenuItem("Set View Size");
  134. private final JSplitPane splitPane = new JSplitPane();
  135. private final JSplitPane splitPane1 = new JSplitPane();
  136. // the tabbed canvas containing the different sub-net tabs of the grid (Main
  137. // Grid + Nodes of Nodes)
  138. private final JPanel myPanel = new JPanel(new BorderLayout());
  139. private final JTabbedPane tabbedPaneInnerOriginal = new JTabbedPane(JTabbedPane.TOP);
  140. // the main canvas where we can see the grid currently displayed
  141. private final JScrollPane canvasSP = new JScrollPane();
  142. private final JScrollPane scrollPane1 = new JScrollPane();
  143. // private final JScrollPane holonSP = new JScrollPane();
  144. // the original tabbed Pane (containing tabs for view, statistics, holon,
  145. // flexibility)
  146. private final JTabbedPane tabbedPaneOriginal = new JTabbedPane(JTabbedPane.TOP);
  147. private final JPopupMenu popmenuEdit = new JPopupMenu();
  148. private final JMenuItem editItem = new JMenuItem("Edit Object");
  149. private final JLabel elementGraph = new JLabel("None ");
  150. private final JTree categoryTree = new JTree();
  151. /******************************************
  152. ************* Right Container*************
  153. ******************************************
  154. * Right Container: here comes the information about the HolonObject, such as
  155. * HolonElements Information, Properties and Consumption/Production graph.
  156. **/
  157. private final Inspector inspector;
  158. private final HolonInformationPanel informationPanel;
  159. private final JSplitPane splitHolonElPro = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
  160. // Prechoosed local Periods
  161. private final JScrollPane scrollProperties = new JScrollPane();
  162. // In this section is the graph for the selected HolonElement of the clicked
  163. private final Model model;
  164. private final Control control;
  165. // In this section are all the Holonelements that correspond to the clicked
  166. // HolonObject with consumption/production, name and amount.
  167. private final JPanel panel = new JPanel();
  168. private final JPanel panelHolonEl = new JPanel();
  169. // Buttons
  170. private final JButton btnAdd = new JButton();
  171. private final JPopupMenu btnAddPopUp = new JPopupMenu("Newacac");
  172. private final JMenuItem mItemNew = new JMenuItem("New..");
  173. private final JMenuItem mItemCategory = new JMenuItem("Category");
  174. private final JMenuItem mItemObject = new JMenuItem("Object");
  175. private final JMenuItem mItemSwitch = new JMenuItem("Switch");
  176. private final JButton btnDel = new JButton();
  177. private final JToolBar toolBar = new JToolBar();
  178. private final JToolBar toolBarHolonEl = new JToolBar();
  179. // Languages
  180. private final Canvas canvas;
  181. private final UnitGraph unitGraph;
  182. /** Textfield to show the period of an element */
  183. private final JTextField unitGraphLocalPeriod = new JTextField(6);
  184. private final JMenuItem mntmUndo = new JMenuItem("Undo");
  185. private final JMenuItem mntmRedo = new JMenuItem("Redo");
  186. private final JMenuItem mntmEditEdges = new JMenuItem("Edge Properties");
  187. private final JMenuItem mntmAlignAll = new JMenuItem("Align All");
  188. private final JMenuItem mntmResetCategory = new JMenuItem("Reset Categories");
  189. // TODO(Tom2021-12-1) make GUI a JFRAME and remove holegJFrame
  190. private JFrame holegJFrame;
  191. // tabbedPaneOriginal or tabbedPaneSplit
  192. private JTabbedPane tabTemp;
  193. private String catOfObjToBeEdited;
  194. private Canvas unc;
  195. private JPanel contentPane;
  196. // Pop up Windows
  197. private AddObjectPopUp addObjectPopUP;
  198. private AboutUsPopUp aboutUsPopUp;
  199. // variables
  200. private boolean dragging = false;
  201. private String actualObjectClicked;
  202. private Image img = null;
  203. private AbstractCanvasObject tempCps = null;
  204. // Time Stuff
  205. private TimePanel timePanel;
  206. public TimePanel getTimePanel() {
  207. return timePanel;
  208. }
  209. private AbstractCanvasObject temp = null;
  210. private String warningText = "Warning";
  211. private String saveBeforeNew = "Do you want to save your current data?";
  212. private String eraseCategory = "Do you really want to delete the Category ";
  213. private String selectObjBeforeErase = "Please select a Category or an Object in the left library in order to delete something.";
  214. private JMenuItem removeItem = new JMenuItem("Remove");
  215. /**
  216. * Create the application.
  217. *
  218. * @param control the Controller
  219. */
  220. GUI(Control control) {
  221. this.control = control;
  222. this.informationPanel = new HolonInformationPanel(control);
  223. this.model = control.getModel();
  224. inspector = new Inspector(control);
  225. control.calculateStateAndVisualForCurrentTimeStep();
  226. this.unitGraph = new UnitGraph(control);
  227. this.canvas = new Canvas(control, model.getCanvas());
  228. initialize();
  229. updateCategories(GuiSettings.getCategories());
  230. control.OnCategoryChanged.addListener(() -> this.updateCategoryUI(GuiSettings.getCategories()));
  231. this.unc = this.canvas;
  232. }
  233. /**
  234. * Initialize the contents of the frame.
  235. */
  236. private void initialize() {
  237. holegJFrame = new JFrame();
  238. holegJFrame.setTitle("HOLEG Simulator");
  239. // try to restore old position/dimensions
  240. ArrayList<Integer> savedWindowDim = control.loadSavedWindowDimensionsIfExistent();
  241. if (savedWindowDim.size() == 4) {
  242. holegJFrame.setBounds(savedWindowDim.get(0), savedWindowDim.get(1), savedWindowDim.get(2),
  243. savedWindowDim.get(3));
  244. }
  245. // if the upper part of the window is showing, the windows can still be
  246. // moved,
  247. // but if it is not, we need to move it to somewhere else
  248. if (savedWindowDim.size() != 4 || !isUpperPanelInsideBounds()) {
  249. holegJFrame.setBounds(100, 100, 1000, 800);
  250. holegJFrame.setExtendedState(JFrame.MAXIMIZED_BOTH);
  251. }
  252. holegJFrame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
  253. holegJFrame.addWindowListener(new java.awt.event.WindowAdapter() {
  254. @Override
  255. public void windowClosing(java.awt.event.WindowEvent windowEvent) {
  256. if (JOptionPane.showConfirmDialog(holegJFrame, "Are you sure you want to exit?", "HOLEG",
  257. JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE) == JOptionPane.YES_OPTION) {
  258. control
  259. .deleteDirectory(new File(System.getProperty("user.home") + "/.config/HolonGUI/Autosave"));
  260. // try to save the position and size of the window, such
  261. // that (if possible)
  262. // it can be opened in the same position the next time
  263. try {
  264. control.savePosAndSizeOfWindow(holegJFrame.getX(), holegJFrame.getY(),
  265. holegJFrame.getWidth(), holegJFrame.getHeight());
  266. } catch (Exception e) {
  267. e.printStackTrace();
  268. }
  269. System.exit(0);
  270. }
  271. }
  272. });
  273. contentPane = (JPanel) holegJFrame.getContentPane();
  274. int condition = JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT;
  275. InputMap inputMap = contentPane.getInputMap(condition);
  276. ActionMap actionMap = contentPane.getActionMap();
  277. String cntrlZDown = "controlZ";
  278. inputMap.put(KeyStroke.getKeyStroke("control Z"), cntrlZDown);
  279. actionMap.put(cntrlZDown, new AbstractAction() {
  280. private static final long serialVersionUID = 1L;
  281. @Override
  282. public void actionPerformed(ActionEvent e) {
  283. try {
  284. control.loadAutoSave(control.getUndoSave());
  285. closeInvalidUpperNodeTabs();
  286. control.calculateStateAndVisualForCurrentTimeStep();
  287. log.info("canvas.repaint0");
  288. canvas.repaint();
  289. updateUpperNodes();
  290. } catch (IOException eex) {
  291. eex.printStackTrace();
  292. }
  293. }
  294. });
  295. String cntrlYDown = "controlY";
  296. inputMap.put(KeyStroke.getKeyStroke("control Y"), cntrlYDown);
  297. actionMap.put(cntrlYDown, new AbstractAction() {
  298. private static final long serialVersionUID = 1L;
  299. @Override
  300. public void actionPerformed(ActionEvent e) {
  301. try {
  302. control.loadAutoSave(control.getRedoSave());
  303. closeInvalidUpperNodeTabs();
  304. control.calculateStateAndVisualForCurrentTimeStep();
  305. log.info("canvas.repaint1");
  306. canvas.repaint();
  307. updateUpperNodes();
  308. } catch (IOException ex) {
  309. ex.printStackTrace();
  310. }
  311. }
  312. });
  313. String cntrlADown = "controlA";
  314. inputMap.put(KeyStroke.getKeyStroke("control A"), cntrlADown);
  315. AbstractAction controlA = new AbstractAction() {
  316. private static final long serialVersionUID = 1L;
  317. @Override
  318. public void actionPerformed(ActionEvent e) {
  319. chooseTabTemp();
  320. GuiSettings.getSelectedObjects().clear();
  321. // Uppernode Canvas?
  322. JScrollPane scrollPane = getScrollPaneFromTabbedPane();
  323. Component canvasOrUpperNodeCanvas = scrollPane.getViewport().getComponent(0);
  324. if (canvasOrUpperNodeCanvas instanceof Canvas groupNodeCanvas) {
  325. control.addSelectedObjects(
  326. groupNodeCanvas.getGroupNode().getObjectsInThisLayer().collect(Collectors.toSet()));
  327. groupNodeCanvas.repaint();
  328. // or Canvas?
  329. }
  330. control.getObjectsInDepth();
  331. }
  332. };
  333. actionMap.put(cntrlADown, controlA);
  334. String delDown = "delete";
  335. inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0, false), delDown);
  336. actionMap.put(delDown, new AbstractAction() {
  337. private static final long serialVersionUID = 1L;
  338. @Override
  339. public void actionPerformed(ActionEvent e) {
  340. chooseTabTemp();
  341. // Uppernode Canvas?
  342. JScrollPane scrollPane = getScrollPaneFromTabbedPane();
  343. Component canvasOrUpperNodeCanvas = scrollPane.getViewport().getComponent(0);
  344. // check whether a producer was deleted (this triggers a
  345. // complete re-evaluation of the net)
  346. boolean wasProducerDeleted = true;
  347. if (canvasOrUpperNodeCanvas instanceof Canvas groupNodeCanvas) {
  348. for (AbstractCanvasObject cps : GuiSettings.getSelectedObjects()) {
  349. if (groupNodeCanvas.getGroupNode().getObjectsInThisLayer().anyMatch(object -> object == cps)) {
  350. control.deleteObjectInGroupNode(cps, groupNodeCanvas.getGroupNode());
  351. // remove UpperNodeTab if UpperNode deleted
  352. removeUpperNodeTab(cps);
  353. }
  354. }
  355. groupNodeCanvas.repaint();
  356. control.clearSelection();
  357. }
  358. // recalculate net if a producer was deleted
  359. if (wasProducerDeleted) {
  360. control.resetSimulation();
  361. control.calculateStateAndVisualForCurrentTimeStep();
  362. }
  363. GuiSettings.getSelectedObjects().clear();
  364. }
  365. });
  366. String cntrlCDown = "controlC";
  367. inputMap.put(KeyStroke.getKeyStroke("control C"), cntrlCDown);
  368. AbstractAction controlC = new AbstractAction() {
  369. private static final long serialVersionUID = 1L;
  370. @Override
  371. public void actionPerformed(ActionEvent e) {
  372. chooseTabTemp();
  373. JScrollPane scrollPane = getScrollPaneFromTabbedPane();
  374. if (!GuiSettings.getSelectedObjects().isEmpty()) {
  375. if (scrollPane.getViewport().getComponent(0)instanceof Canvas groupNodeCanvas)
  376. control.copy(groupNodeCanvas.getGroupNode());
  377. else
  378. control.copy(null);
  379. if (!GuiSettings.getClipboardObjects().isEmpty()) {
  380. //TODO(Tom2022-01-14): old code changes itemPaste
  381. //OLD: canvas.itemPaste.setEnabled(true);
  382. }
  383. }
  384. }
  385. };
  386. actionMap.put(cntrlCDown, controlC);
  387. String cntrlVDown = "controlV";
  388. inputMap.put(KeyStroke.getKeyStroke("control V"), cntrlVDown);
  389. AbstractAction controlV = new AbstractAction() {
  390. private static final long serialVersionUID = 1L;
  391. @Override
  392. public void actionPerformed(ActionEvent e) {
  393. try {
  394. tabTemp = null;
  395. if (tabbedPaneOriginal.getMousePosition() != null) {
  396. tabTemp = tabbedPaneOriginal;
  397. } else {
  398. }
  399. if (tabTemp == null)
  400. return;
  401. JScrollPane scrollPane = getScrollPaneFromTabbedPane();
  402. Component canvasOrUpperNodeCanvas = scrollPane.getViewport().getComponent(0);
  403. if (tabTemp != null && canvasOrUpperNodeCanvas instanceof Canvas groupNodeCanvas) {
  404. control.paste(groupNodeCanvas.getGroupNode(), canvasOrUpperNodeCanvas.getMousePosition());
  405. control.calculateStateAndVisualForCurrentTimeStep();
  406. scrollPane.getViewport().getComponent(0).repaint();
  407. } else {
  408. control.paste(null, canvas.getMousePosition());
  409. control.calculateStateAndVisualForCurrentTimeStep();
  410. log.info("canvas.repaint2");
  411. canvas.repaint();
  412. }
  413. } catch (HeadlessException | JsonParseException | UnsupportedFlavorException | IOException e1) {
  414. JLabel message = new JLabel("The Clipboard information cannot be pasted into Application.");
  415. JOptionPane.showMessageDialog(holegJFrame, message, "", JOptionPane.ERROR_MESSAGE);
  416. }
  417. }
  418. };
  419. actionMap.put(cntrlVDown, controlV);
  420. String cntrlXDown = "controlX";
  421. inputMap.put(KeyStroke.getKeyStroke("control X"), cntrlXDown);
  422. AbstractAction controlX = new AbstractAction() {
  423. private static final long serialVersionUID = 1L;
  424. @Override
  425. public void actionPerformed(ActionEvent e) {
  426. chooseTabTemp();
  427. JScrollPane scrollPane = getScrollPaneFromTabbedPane();
  428. if (!GuiSettings.getSelectedObjects().isEmpty()) {
  429. if (scrollPane.getViewport().getComponent(0)instanceof Canvas groupNodeCanvas) {
  430. control.cut(groupNodeCanvas.getGroupNode());
  431. control.calculateStateAndVisualForCurrentTimeStep();
  432. scrollPane.getViewport().getComponent(0).repaint();
  433. } else {
  434. control.cut(null);
  435. control.calculateStateAndVisualForCurrentTimeStep();
  436. log.info("canvas.repaint3");
  437. canvas.repaint();
  438. }
  439. if (!GuiSettings.getClipboardObjects().isEmpty()) {
  440. //TODO(Tom2022-01-14): old code changes itemPaste
  441. //OLD: canvas.itemPaste.setEnabled(true);
  442. }
  443. }
  444. }
  445. };
  446. actionMap.put(cntrlXDown, controlX);
  447. holegJFrame.setJMenuBar(menuBar);
  448. holegJFrame.setIconImage(Import.loadImage(ImagePreference.Logo, 30, 30));
  449. menuBar.add(mnNewMenu);
  450. mnNewMenu.add(mntmNew);
  451. mnNewMenu.add(mntmOpen);
  452. mnNewMenu.add(mntmSave);
  453. menuBar.add(mnNewMenuEdit);
  454. mnNewMenuEdit.add(mntmUndo);
  455. mnNewMenuEdit.add(mntmRedo);
  456. mnNewMenuEdit.add(mntmEditEdges);
  457. mntmEditEdges.addActionListener(actionEvent -> {
  458. EditEdgesPopUp edgePopUp = new EditEdgesPopUp(holegJFrame);
  459. edgePopUp.setCanvas(canvas);
  460. edgePopUp.setController(control);
  461. edgePopUp.setVisible(true);
  462. });
  463. // Edit -> Align All
  464. mnNewMenuEdit.add(mntmAlignAll);
  465. mntmAlignAll.addActionListener(actionEvent -> {
  466. // getScrollPaneFromTabbedPane().getViewport().getComponent(0) is always the
  467. // active canvas
  468. tryToAlignObjects();
  469. });
  470. menuBar.add(mnNewMenuOptions);
  471. mnNewMenuOptions.add(mntmResetCategory);
  472. mntmResetCategory.addActionListener(actionEvent -> {
  473. control.resetCategories();
  474. categoryTree.revalidate();
  475. categoryTree.repaint();
  476. });
  477. /**
  478. * Add Fairness Model Option to the option Menu
  479. */
  480. mnNewMenuOptions.add(mnFairnessModel);
  481. mnFairnessModel.add(mntmFairMinFirst);
  482. mntmFairMinFirst.setForeground(Color.BLUE);
  483. mntmFairMinFirst
  484. .setToolTipText("HolonObjects with the smallest mininum Demand will be partially supplied first.\n"
  485. + "After that as many HolonObjects as possible will get fully supplied.");
  486. mntmFairMinFirst.addActionListener(arg0 -> {
  487. control.getModel().setFairnessModel(FairnessModel.MininumDemandFirst);
  488. mntmFairMinFirst.setForeground(Color.BLUE);
  489. mntmFairAlleEqual.setForeground(mnFairnessModel.getForeground());
  490. control.calculateStateAndVisualForCurrentTimeStep();
  491. // Update UpperNodes
  492. Component canvasOrUpperNodeCanvas = getScrollPaneFromTabbedPane().getViewport().getComponent(0);
  493. if (canvasOrUpperNodeCanvas != null && canvasOrUpperNodeCanvas instanceof Canvas groupNodeCanvas) {
  494. groupNodeCanvas.repaint();
  495. }
  496. });
  497. mnFairnessModel.add(mntmFairAlleEqual);
  498. mntmFairAlleEqual.setToolTipText("HolonObjects will all get the same amount of energy.");
  499. mntmFairAlleEqual.addActionListener(arg0 -> {
  500. control.getModel().setFairnessModel(FairnessModel.AllEqual);
  501. mntmFairAlleEqual.setForeground(Color.BLUE);
  502. mntmFairMinFirst.setForeground(mnFairnessModel.getForeground());
  503. control.calculateStateAndVisualForCurrentTimeStep();
  504. // Update UpperNodes
  505. Component canvasOrUpperNodeCanvas = getScrollPaneFromTabbedPane().getViewport().getComponent(0);
  506. if (canvasOrUpperNodeCanvas != null && canvasOrUpperNodeCanvas instanceof Canvas groupNodeCanvas) {
  507. groupNodeCanvas.repaint();
  508. }
  509. });
  510. menuBar.add(mnNewMenuView);
  511. mnNewMenuView.add(mntmCanvasSize);
  512. mntmCanvasSize.addActionListener(actionEvent -> {
  513. CanvasResizePopUp popUp = new CanvasResizePopUp(model, control, canvas, this.tabbedPaneInnerOriginal,
  514. holegJFrame);
  515. popUp.setVisible(true);
  516. });
  517. tabbedPaneInnerOriginal.addChangeListener(change -> {
  518. control.clearSelection();
  519. });
  520. mnNewMenuView.add(mntmCanvasSize);
  521. /*
  522. * Adds Checkbox to turn supply bars on/off
  523. */
  524. mnNewMenuView.add(showSupplyBarsCheckBox);
  525. showSupplyBarsCheckBox.setSelected(true);
  526. showSupplyBarsCheckBox.addActionListener(arg0 -> {
  527. GuiSettings.showSupplyBars = showSupplyBarsCheckBox.isSelected();
  528. log.info("canvas.repaint4");
  529. canvas.repaint();
  530. // Update UpperNodes
  531. JScrollPane spane = getScrollPaneFromTabbedPane();
  532. if (spane != null) {
  533. Component canvasOrUpperNodeCanvas = spane.getViewport().getComponent(0);
  534. if (canvasOrUpperNodeCanvas != null
  535. && canvasOrUpperNodeCanvas instanceof Canvas groupNodeCanvas) {
  536. groupNodeCanvas.repaint();
  537. }
  538. }
  539. });
  540. initWindowMenu();
  541. /**
  542. * add Help Menu and its items
  543. */
  544. menuBar.add(mnHelp);
  545. mnHelp.add(mntmIntroduction);
  546. mnHelp.add(mntmUserManual);
  547. mnHelp.add(mntmAlgorithmHelp);
  548. mnHelp.add(mntmCodeDoc);
  549. mnHelp.add(mntmAboutUs);
  550. canvas.setBackground(Color.WHITE);
  551. canvas.setPreferredSize(new Dimension(GuiSettings.canvasSize.getX(), GuiSettings.canvasSize.getY()));
  552. /********************
  553. * RIGHT CONTAINER (INFORMATION)
  554. **********************/
  555. panelHolonEl.setLayout(new BoxLayout(panelHolonEl, BoxLayout.X_AXIS));
  556. toolBarHolonEl.setFloatable(false);
  557. panelHolonEl.add(toolBarHolonEl);
  558. /***********************
  559. * HolonElement Graph Actions
  560. **********************/
  561. /*
  562. * Update Local Period of an Element Graph
  563. */
  564. unitGraphLocalPeriod.addKeyListener(new KeyAdapter() {
  565. @Override
  566. public void keyReleased(KeyEvent e) {
  567. try {
  568. int localLength = Integer.parseInt(unitGraphLocalPeriod.getText());
  569. unitGraphLocalPeriod.setBackground(Color.WHITE);
  570. /**
  571. * set local graph Period
  572. */
  573. if (e.getKeyCode() == KeyEvent.VK_ENTER)
  574. unitGraph.setLocalPeriod(localLength);
  575. } catch (NumberFormatException ex) {
  576. unitGraphLocalPeriod.setBackground(ColorPreference.GUI.PALE_RED);
  577. }
  578. }
  579. });
  580. /*****************************
  581. * RIGHT CONTAINER DONE
  582. *****************************/
  583. holegJFrame.getContentPane().setLayout(new BorderLayout(0, 0));
  584. /****************
  585. * Tree Stuff
  586. ****************/
  587. // Override Key Actions
  588. inputMap = categoryTree.getInputMap();
  589. inputMap.put(KeyStroke.getKeyStroke("control C"), cntrlCDown);
  590. inputMap.put(KeyStroke.getKeyStroke("control V"), cntrlVDown);
  591. inputMap.put(KeyStroke.getKeyStroke("control X"), cntrlXDown);
  592. inputMap.put(KeyStroke.getKeyStroke("control A"), cntrlADown);
  593. TreeCellRenderer customRenderer = new TreeCellRenderer() {
  594. @Override
  595. public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded,
  596. boolean leaf, int row, boolean hasFocus) {
  597. JLabel label = new JLabel();
  598. Image imgR;
  599. if (leaf) {
  600. for (Category cat : GuiSettings.getCategories()) {
  601. for (AbstractCanvasObject cps : cat.getObjects()) {
  602. if (value.toString().equals(cps.getName())) {
  603. imgR = Import.loadImage(cps.getImage(), 50, 50);
  604. if (imgR != null) {
  605. label.setIcon(new ImageIcon(imgR));
  606. }
  607. label.setText(cps.getName());
  608. }
  609. }
  610. }
  611. }
  612. tree.setRowHeight(50);
  613. if (hasFocus) {
  614. label.setForeground(ColorPreference.Category.Focus);
  615. label.setOpaque(true);
  616. }
  617. if (label.getText().isEmpty()) {
  618. label.setText(value.toString());
  619. if (!value.toString().equals("Categories")) {
  620. label.setIcon(new ImageIcon(Import.loadImage(ImagePreference.Category.Folder)));
  621. }
  622. }
  623. return label;
  624. }
  625. };
  626. categoryTree.setCellRenderer(customRenderer);
  627. categoryTree.addMouseMotionListener(new MouseMotionAdapter() {
  628. public void mouseDragged(MouseEvent e) {
  629. checkForDragAndDrop(e);
  630. }
  631. /**
  632. * checks if an object of the current Panel could be replaced by the dragged
  633. * object
  634. *
  635. * @param e
  636. */
  637. private void checkForDragAndDrop(MouseEvent e) {
  638. try {
  639. /**
  640. * if no object gets dragged -> finished
  641. */
  642. if (!dragging)
  643. return;
  644. /**
  645. * select the current Panel
  646. */
  647. chooseTabTemp();
  648. JScrollPane scrollPane = getScrollPaneFromTabbedPane();
  649. if (scrollPane == null)
  650. return;
  651. Component canvasOrUpperNodeCanvas = scrollPane.getViewport().getComponent(0);
  652. /**
  653. * check for replacements on the canvas
  654. */
  655. if (canvasOrUpperNodeCanvas instanceof Canvas groupNodeCanvas) {
  656. if (unc.getMousePosition() == null)
  657. return;
  658. int x = (int) unc.getMousePosition().getX() + 16;
  659. int y = (int) unc.getMousePosition().getY() + 16;
  660. /**
  661. * check for replacement
  662. */
  663. groupNodeCanvas.checkForReplacement(x, y);
  664. /**
  665. * repaint
  666. */
  667. unc.invalidate();
  668. unc.repaint();
  669. } else {
  670. if (canvas.getMousePosition() == null)
  671. return;
  672. int x = (int) canvas.getMousePosition().getX() + 16;
  673. int y = (int) canvas.getMousePosition().getY() + 16;
  674. /**
  675. * check for replacement
  676. */
  677. canvas.checkForReplacement(x, y);
  678. /**
  679. * repaint
  680. */
  681. log.info("canvas.repaint5");
  682. canvas.repaint();
  683. }
  684. contentPane.updateUI();
  685. } catch (Exception eex) {
  686. eex.printStackTrace();
  687. }
  688. }
  689. });
  690. categoryTree.addMouseListener(new MouseAdapter() {
  691. public void mouseReleased(MouseEvent e) {
  692. try {
  693. if (dragging) {
  694. chooseTabTemp();
  695. JScrollPane scrollPane = getScrollPaneFromTabbedPane();
  696. Component canvasOrUpperNodeCanvas = scrollPane.getViewport().getComponent(0);
  697. if (canvasOrUpperNodeCanvas instanceof Canvas groupNodeCanvas) {
  698. int x = (int) groupNodeCanvas.getMousePosition().getX() + 16;
  699. int y = (int) groupNodeCanvas.getMousePosition().getY() + 16;
  700. AbstractCanvasObject h = null;
  701. if (tempCps instanceof HolonObject hO) {
  702. h = new HolonObject(hO);
  703. }
  704. if (tempCps instanceof HolonSwitch sw) {
  705. h = new HolonSwitch(sw);
  706. }
  707. h.setPosition(x, y);
  708. /**
  709. * close UpperNodeTabs of replaced UpperNode
  710. */
  711. //TODO(Tom2022-01-14): replacement with upperNode
  712. control.addObjectInGroupNode(h, groupNodeCanvas.getGroupNode());
  713. /**
  714. * object would be replaced
  715. */
  716. groupNodeCanvas.invalidate();
  717. control.calculateStateAndVisualForCurrentTimeStep();
  718. groupNodeCanvas.repaint();
  719. } else {
  720. int x = (int) canvas.getMousePosition().getX() + 16;
  721. int y = (int) canvas.getMousePosition().getY() + 16;
  722. AbstractCanvasObject h = null;
  723. if (tempCps instanceof HolonObject hO) {
  724. h = new HolonObject(hO);
  725. }
  726. if (tempCps instanceof HolonSwitch sw) {
  727. h = new HolonSwitch(sw);
  728. }
  729. h.setPosition(x, y);
  730. /**
  731. * close UpperNodeTabs of replaced UpperNode
  732. */
  733. control.addObjectCanvas(h);
  734. /**
  735. * no object should get replaced
  736. */
  737. log.info("canvas.repaint6");
  738. canvas.repaint();
  739. }
  740. control.calculateStateAndVisualForCurrentTimeStep();
  741. contentPane.updateUI();
  742. dragging = false;
  743. }
  744. } catch (Exception eex) {
  745. }
  746. holegJFrame.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
  747. }
  748. });
  749. popmenuEdit.add(editItem);
  750. popmenuEdit.add(removeItem);
  751. editItem.setEnabled(false);
  752. editItem.addActionListener(actionEvent -> {
  753. });
  754. categoryTree.addMouseListener(new MouseAdapter() {
  755. public void mousePressed(MouseEvent e) {
  756. try {
  757. actualObjectClicked = categoryTree.getPathForLocation(e.getX(), e.getY()).getLastPathComponent()
  758. .toString();
  759. // if an Object was selected, the porperties are shown in
  760. // the table
  761. DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) categoryTree
  762. .getPathForLocation(e.getX(), e.getY()).getLastPathComponent();
  763. if (SwingUtilities.isRightMouseButton(e)) {
  764. for (Category cat : GuiSettings.getCategories()) {
  765. for (AbstractCanvasObject cps : cat.getObjects()) {
  766. if (actualObjectClicked.equals(cps.getName())
  767. && !(cps instanceof HolonSwitch)) {
  768. editItem.setEnabled(true);
  769. popmenuEdit.show(e.getComponent(), e.getX(), e.getY());
  770. catOfObjToBeEdited = selectedNode.getParent().toString();
  771. tempCps = cps;
  772. }
  773. }
  774. }
  775. } else {
  776. for (Category cat : GuiSettings.getCategories()) {
  777. for (AbstractCanvasObject cps : cat.getObjects()) {
  778. if (actualObjectClicked.equals(cps.getName())) {
  779. File checkPath = new File(cps.getImage());
  780. if (checkPath.exists()) {
  781. img = new ImageIcon(cps.getImage()).getImage().getScaledInstance(32, 32,
  782. java.awt.Image.SCALE_SMOOTH);
  783. } else {
  784. img = Import.loadImage(cps.getImage(), 32, 32);
  785. }
  786. tempCps = cps;
  787. dragging = true;
  788. Cursor cursor = Toolkit.getDefaultToolkit().createCustomCursor(img, new Point(0, 0),
  789. "Image");
  790. holegJFrame.setCursor(cursor);
  791. }
  792. }
  793. }
  794. }
  795. } catch (Exception eex) {
  796. }
  797. }
  798. });
  799. editItem.addActionListener(actionEvent -> {
  800. // Remove the selected Object object
  801. // AddObjectPopUp(boolean edit, AbstractCpsObject obj, String cat, JFrame
  802. // parentFrame)
  803. System.out.println("Edit");
  804. addObjectPopUP = new AddObjectPopUp(true, tempCps, catOfObjToBeEdited, holegJFrame);
  805. addObjectPopUP.setCategory(catOfObjToBeEdited);
  806. addObjectPopUP.setController(control);
  807. addObjectPopUP.setVisible(true);
  808. });
  809. removeItem.addActionListener(actionEvent -> {
  810. // Remove the selected Object object
  811. log.info("catOfObjToBeEdited:" + catOfObjToBeEdited + ", tempCps:" + tempCps);
  812. control.findCategoryWithName(catOfObjToBeEdited).ifPresent(cat -> {
  813. cat.removeObjectsWithName(tempCps.getName());
  814. });
  815. });
  816. scrollPane1.setViewportView(categoryTree);
  817. scrollPane1.setColumnHeaderView(panel);
  818. panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
  819. toolBar.setAlignmentX(Component.LEFT_ALIGNMENT);
  820. toolBar.setFloatable(false);
  821. panel.add(toolBar);
  822. btnAddPopUp.add(mItemNew);
  823. mItemNew.addActionListener(actionEvent -> {
  824. new CreateNewDialog(control, holegJFrame);
  825. });
  826. btnAddPopUp.addSeparator();
  827. btnAddPopUp.add(mItemCategory);
  828. mItemCategory.addActionListener(actionEvent -> {
  829. new CreateNewDialog(control, Option.Category, holegJFrame);
  830. });
  831. btnAddPopUp.add(mItemObject);
  832. mItemObject.addActionListener(actionEvent -> {
  833. new CreateNewDialog(control, Option.Object, holegJFrame);
  834. });
  835. btnAddPopUp.add(mItemSwitch);
  836. mItemSwitch.addActionListener(actionEvent -> {
  837. new CreateNewDialog(control, Option.Switch, holegJFrame);
  838. });
  839. btnAdd.addActionListener(actionEvent -> btnAddPopUp.show(btnAdd, -1, +20));
  840. btnAdd.setIcon(new ImageIcon(Import.loadImage("images/buttons/plus.png", 16, 16)));
  841. btnAdd.setToolTipText("<html><b>New</b><br>Add a new Category or Item to the library.</html>");
  842. toolBar.add(btnAdd);
  843. /**
  844. * Help Menu Action Listeners
  845. */
  846. /**
  847. * URL of the telecommunication git Wiki
  848. */
  849. String tkWikiWebpage = "https://git.tk.informatik.tu-darmstadt.de/carlos.garcia/praktikum-holons/wiki/";
  850. /** open Introduction Web Page */
  851. mntmIntroduction.addMouseListener(new MouseAdapter() {
  852. @Override
  853. public void mousePressed(MouseEvent e) {
  854. openWebpage(tkWikiWebpage + "Introduction+V2.1");
  855. }
  856. });
  857. /** open UserManual WebPage */
  858. mntmUserManual.addMouseListener(new MouseAdapter() {
  859. @Override
  860. public void mousePressed(MouseEvent e) {
  861. openWebpage(tkWikiWebpage + "User+Manual+V2.1");
  862. }
  863. });
  864. /** open Algorithm Help Web Page */
  865. mntmAlgorithmHelp.addMouseListener(new MouseAdapter() {
  866. @Override
  867. public void mousePressed(MouseEvent e) {
  868. openWebpage(tkWikiWebpage + "Algorithms+V2.1");
  869. }
  870. });
  871. /** open Code Documentation Web Page */
  872. mntmCodeDoc.addMouseListener(new MouseAdapter() {
  873. @Override
  874. public void mousePressed(MouseEvent e) {
  875. openWebpage(tkWikiWebpage + "Code+documentation+V2.1");
  876. }
  877. });
  878. /**
  879. * Pop up - About Us with some important information about the developers,
  880. * source and programming stuff
  881. */
  882. mntmAboutUs.addMouseListener(new MouseAdapter() {
  883. @Override
  884. public void mousePressed(MouseEvent e) {
  885. aboutUsPopUp = new AboutUsPopUp(holegJFrame);
  886. aboutUsPopUp.setVisible(true);
  887. }
  888. });
  889. // Del Button
  890. btnDel.addActionListener(actionEvent -> {
  891. Object nodeInfo = categoryTree.getLastSelectedPathComponent();
  892. if (nodeInfo != null) {
  893. DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) nodeInfo;
  894. String nodeName = selectedNode.getUserObject().toString();
  895. int depthOfNode = selectedNode.getLevel();
  896. try {
  897. switch (depthOfNode) {
  898. case 1:
  899. int dialogResult = JOptionPane.showConfirmDialog(holegJFrame, eraseCategory + nodeName + "?",
  900. warningText, JOptionPane.YES_NO_OPTION);
  901. if (dialogResult == JOptionPane.YES_OPTION) {
  902. GuiSettings.getCategories().stream().filter(cat -> cat.getName() == nodeName).findAny()
  903. .ifPresent(cat -> {
  904. control.deleteCategory(cat);
  905. });
  906. }
  907. break;
  908. case 2:
  909. DefaultMutableTreeNode parent = (DefaultMutableTreeNode) selectedNode.getParent();
  910. control.findCategoryWithName(parent.getUserObject().toString()).ifPresent(cat -> {
  911. cat.removeObjectsWithName(nodeName);
  912. });
  913. break;
  914. default:
  915. JOptionPane.showMessageDialog(holegJFrame, selectObjBeforeErase);
  916. }
  917. } catch (Exception e2) {
  918. }
  919. } else {
  920. JOptionPane.showMessageDialog(holegJFrame, selectObjBeforeErase);
  921. }
  922. categoryTree.repaint();
  923. });
  924. btnDel.setIcon(new ImageIcon(Import.loadImage("images/buttons/minus.png", 16, 16)));
  925. btnDel.setToolTipText("<html><b>Delete</b><br>Removes a Category or a Category Item.</html>");
  926. toolBar.add(btnDel);
  927. holegJFrame.getContentPane().add(splitPane);
  928. mntmNew.addActionListener(actionEvent -> {
  929. if (model.getCanvas().getObjectsInThisLayer().findAny().isPresent()) {
  930. int newWarning = JOptionPane.YES_NO_OPTION;
  931. int dialogForNewWarning = JOptionPane.showConfirmDialog(holegJFrame, saveBeforeNew, warningText,
  932. newWarning);
  933. if (dialogForNewWarning == JOptionPane.YES_OPTION) {
  934. mntmSave.doClick();
  935. }
  936. }
  937. // Remove all but main tab
  938. while (tabbedPaneInnerOriginal.getTabCount() > 1) {
  939. tabbedPaneInnerOriginal.remove(1);
  940. }
  941. control.clearSelection();
  942. model.clear();
  943. control.OnSelectionChanged.broadcast();
  944. GuiSettings.getSelectedEdges().clear();
  945. control.getModel().setCurrentIteration(0);
  946. elementGraph.setText("None");
  947. log.info("canvas.repaint7");
  948. canvas.repaint();
  949. IdCounter.resetObjectCounter(CounterType.Object);
  950. IdCounter.resetObjectCounter(CounterType.Element);
  951. control.calculateStateAndVisualForCurrentTimeStep();
  952. });
  953. mntmOpen.addActionListener(new ActionListener() {
  954. @Override
  955. public void actionPerformed(ActionEvent evt) {
  956. menuFileExitActionPerformed();
  957. }
  958. private void menuFileExitActionPerformed() {
  959. JFileChooser fileChooser = new JFileChooser();
  960. fileChooser.setCurrentDirectory(new File(System.getProperty("user.dir") + "/exampleNetworks/"));
  961. FileNameExtensionFilter holonFilter = new FileNameExtensionFilter("Holon Save File(*.holon)", "holon");
  962. fileChooser.setFileFilter(holonFilter);
  963. if (fileChooser.showOpenDialog(holegJFrame) == JFileChooser.APPROVE_OPTION) {
  964. File file = fileChooser.getSelectedFile();
  965. try {
  966. while (tabbedPaneInnerOriginal.getTabCount() > 1) {
  967. tabbedPaneInnerOriginal.remove(1);
  968. }
  969. GuiSettings.getSelectedObjects().clear();
  970. control.loadFile(file.getAbsolutePath());
  971. log.info("canvas.repaint8");
  972. canvas.repaint();
  973. categoryTree.repaint();
  974. control.calculateStateAndVisualForCurrentTimeStep();
  975. } catch (IOException | ArchiveException e) {
  976. e.printStackTrace();
  977. JLabel message = new JLabel("The savefile is corrupt and cannot be opened.");
  978. JOptionPane.showMessageDialog(holegJFrame, message, "", JOptionPane.ERROR_MESSAGE);
  979. }
  980. }
  981. }
  982. });
  983. mntmSave.addActionListener(new ActionListener() {
  984. @Override
  985. public void actionPerformed(ActionEvent evt) {
  986. menuSaveActionPerformed();
  987. }
  988. private void menuSaveActionPerformed() {
  989. JFileChooser fileChooser = new JFileChooser();
  990. FileNameExtensionFilter holonFilter = new FileNameExtensionFilter("Holon Save File(*.holon)", "holon");
  991. fileChooser.setFileFilter(holonFilter);
  992. if (fileChooser.showSaveDialog(holegJFrame) == JFileChooser.APPROVE_OPTION) {
  993. File selectedFile = fileChooser.getSelectedFile();
  994. String fileName = selectedFile.getName();
  995. String fullPath = fileChooser.getSelectedFile().getPath();
  996. if (fileChooser.getFileFilter().equals(holonFilter)) {
  997. if (!fileName.contains("."))
  998. fullPath += ".holon";
  999. }
  1000. if (!fullPath.endsWith(".holon")) {
  1001. String suffix = fullPath.substring(fullPath.lastIndexOf("."), fullPath.length());
  1002. String[] options = new String[] { "keep .holon", "use " + suffix };
  1003. JLabel message = new JLabel(
  1004. "Are you sure to use the extension \"" + suffix + "\" instead of \".holon\"?");
  1005. int response = JOptionPane.showOptionDialog(holegJFrame, message, "",
  1006. JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[1]);
  1007. if (response == 0)
  1008. fullPath = fullPath.replace(suffix, ".holon");
  1009. }
  1010. try {
  1011. control.saveFile(new File(fullPath).getAbsolutePath());
  1012. } catch (IOException | ArchiveException e) {
  1013. e.printStackTrace();
  1014. }
  1015. }
  1016. }
  1017. });
  1018. mntmUndo.addActionListener(new ActionListener() {
  1019. @Override
  1020. public void actionPerformed(ActionEvent evt) {
  1021. menuUndoActionPerformed();
  1022. }
  1023. private void menuUndoActionPerformed() {
  1024. try {
  1025. control.loadAutoSave(control.getUndoSave());
  1026. closeInvalidUpperNodeTabs();
  1027. control.calculateStateAndVisualForCurrentTimeStep();
  1028. log.info("canvas.repaint9");
  1029. canvas.repaint();
  1030. } catch (IOException e) {
  1031. e.printStackTrace();
  1032. }
  1033. }
  1034. });
  1035. mntmRedo.addActionListener(new ActionListener() {
  1036. @Override
  1037. public void actionPerformed(ActionEvent evt) {
  1038. menuRedoActionPerformed();
  1039. }
  1040. private void menuRedoActionPerformed() {
  1041. try {
  1042. control.loadAutoSave(control.getRedoSave());
  1043. closeInvalidUpperNodeTabs();
  1044. control.calculateStateAndVisualForCurrentTimeStep();
  1045. log.info("canvas.repaint10");
  1046. canvas.repaint();
  1047. } catch (IOException e) {
  1048. e.printStackTrace();
  1049. }
  1050. }
  1051. });
  1052. timePanel = new TimePanel(control);
  1053. timePanel.setBorder(null);
  1054. timePanel.getTimeSlider().addChangeListener(changeEvent -> {
  1055. // TimeSliderChanged event
  1056. control.calculateStateAndVisualForTimeStep(timePanel.getTimeSlider().getValue());
  1057. unitGraph.repaint();
  1058. contentPane.updateUI();
  1059. });
  1060. splitPane1.setMinimumSize(new Dimension(0, 25));
  1061. splitPane.setRightComponent(splitPane1);
  1062. splitPane.setDividerLocation(200);
  1063. splitPane1.setDividerLocation(500);
  1064. splitPane.setLeftComponent(scrollPane1);
  1065. tabbedPaneOriginal.addTab("View", tabbedPaneInnerOriginal);
  1066. myPanel.add(canvasSP, BorderLayout.CENTER);
  1067. tabbedPaneInnerOriginal.addTab("Main Grid", myPanel);
  1068. splitPane1.setLeftComponent(tabbedPaneOriginal);
  1069. splitPane1.setRightComponent(splitHolonElPro);
  1070. splitPane1.setResizeWeight(0.9);
  1071. splitHolonElPro.setDividerLocation(700);
  1072. // containing the graph and the elements-list
  1073. splitHolonElPro.setTopComponent(inspector);
  1074. // containing the object's properties
  1075. splitHolonElPro.setBottomComponent(scrollProperties);
  1076. canvasSP.setViewportView(canvas);
  1077. // Set up of the Properties section
  1078. scrollProperties.setViewportView(this.informationPanel);
  1079. scrollProperties.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
  1080. scrollProperties.getVerticalScrollBar().setUnitIncrement(16);
  1081. tabbedPaneOriginal.setBorder(null);
  1082. scrollProperties.setBorder(null);
  1083. splitPane.setBorder(null);
  1084. splitPane1.setBorder(null);
  1085. splitHolonElPro.setBorder(null);
  1086. panelHolonEl.setBorder(null);
  1087. canvasSP.setBorder(null);
  1088. holegJFrame.getContentPane().add(timePanel, BorderLayout.SOUTH);
  1089. try {
  1090. control.loadAutoSave(System.getProperty("user.home") + "/.config/HolonGUI/Category/Category.json");
  1091. } catch (IOException e1) {
  1092. }
  1093. canvasSP.addComponentListener(new ComponentAdapter() {
  1094. @Override
  1095. public void componentResized(ComponentEvent e) {
  1096. GuiSettings.canvasSize.setX(Math.max(GuiSettings.canvasSize.getX(), canvasSP.getViewport().getWidth()));
  1097. GuiSettings.canvasSize
  1098. .setY(Math.max(GuiSettings.canvasSize.getY(), canvasSP.getViewport().getHeight()));
  1099. log.info("canvas.repaint11");
  1100. canvas.repaint();
  1101. }
  1102. });
  1103. }
  1104. private void tryToAlignObjects() {
  1105. //TODO(Tom2022-01-14): recreateTryToAlignObjects
  1106. }
  1107. private void initWindowMenu() {
  1108. menuBar.add(menuWindow);
  1109. // Algo
  1110. JMenuItem openMenu = new JMenuItem("Open Algorithm Panel", new ImageIcon(Import
  1111. .loadImage(ImagePreference.Button.Menu.Algo).getScaledInstance(20, 20, java.awt.Image.SCALE_SMOOTH)));
  1112. openMenu.addActionListener(actionEvent -> {
  1113. new AddOnWindow(holegJFrame, control);
  1114. });
  1115. openMenu.setAccelerator(KeyStroke.getKeyStroke('N', Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx()));
  1116. menuWindow.add(openMenu);
  1117. // Outliner
  1118. JMenuItem openOutliner = new JMenuItem("Open Outliner", new ImageIcon(Import
  1119. .loadImage(ImagePreference.Button.Menu.Outliner).getScaledInstance(20, 20, java.awt.Image.SCALE_SMOOTH)));
  1120. openOutliner.addActionListener(actionEvent -> {
  1121. new Outliner(holegJFrame, model, control);
  1122. });
  1123. openOutliner
  1124. .setAccelerator(KeyStroke.getKeyStroke('O', Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx()));
  1125. menuWindow.add(openOutliner);
  1126. // FlexWindow
  1127. JMenuItem openFlexMenuItem = new JMenuItem("Open Flexibility Panel", new ImageIcon(Import
  1128. .loadImage(ImagePreference.Button.Menu.Algo).getScaledInstance(20, 20, java.awt.Image.SCALE_SMOOTH)));
  1129. openFlexMenuItem.addActionListener(actionEvent -> {
  1130. new FlexWindow(holegJFrame, control);
  1131. });
  1132. openFlexMenuItem
  1133. .setAccelerator(KeyStroke.getKeyStroke('L', Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx()));
  1134. menuWindow.add(openFlexMenuItem);
  1135. }
  1136. private boolean isUpperPanelInsideBounds() {
  1137. int x = holegJFrame.getX();
  1138. int y = holegJFrame.getY();
  1139. int width = holegJFrame.getWidth();
  1140. // get all connected screen devices
  1141. GraphicsDevice[] screenDevices = GraphicsEnvironment.getLocalGraphicsEnvironment().getScreenDevices();
  1142. boolean isUpperPanelVisible = false;
  1143. // and check whether they contain the upper left or upper right point of
  1144. // the frame
  1145. for (GraphicsDevice device : screenDevices) {
  1146. Rectangle bounds = device.getDefaultConfiguration().getBounds();
  1147. if (bounds.contains(x, y) || bounds.contains(x + width, y)) {
  1148. isUpperPanelVisible = true;
  1149. break;
  1150. }
  1151. }
  1152. return isUpperPanelVisible;
  1153. }
  1154. /**
  1155. * reloads the Categories from Model.
  1156. *
  1157. * @param categories the current categories
  1158. */
  1159. private void updateCategories(Collection<Category> categories) {
  1160. DefaultTreeModel treemodel = new DefaultTreeModel(new DefaultMutableTreeNode("Categories") {
  1161. private static final long serialVersionUID = 1L;
  1162. {
  1163. DefaultMutableTreeNode node1;
  1164. for (Category c : categories) {
  1165. node1 = new DefaultMutableTreeNode(c.getName());
  1166. for (AbstractCanvasObject obj : c.getObjects()) {
  1167. node1.add(new DefaultMutableTreeNode(obj.getName()));
  1168. }
  1169. add(node1);
  1170. }
  1171. }
  1172. });
  1173. categoryTree.setModel(treemodel);
  1174. }
  1175. /**
  1176. * When changes are made to the Categories.
  1177. *
  1178. * @param categories the Categories
  1179. */
  1180. public void updateCategoryUI(Collection<Category> categories) {
  1181. DefaultTreeModel model = (DefaultTreeModel) categoryTree.getModel();
  1182. updateCategories(categories);
  1183. model.reload();
  1184. }
  1185. void setVisible(boolean value) {
  1186. holegJFrame.setVisible(value);
  1187. }
  1188. /*
  1189. * Open a new Tab with an UpperNodeCanvas
  1190. */
  1191. public void openNewUpperNodeTab(GroupNode node) {
  1192. chooseTabTemp();
  1193. JScrollPane scrollPane = getScrollPaneFromTabbedPane();
  1194. if (scrollPane.getViewport().getComponent(0)instanceof Canvas canvasPanel) {
  1195. unc = new Canvas(control, node);
  1196. }
  1197. // check if tab already open for clicked NodeOfNode
  1198. boolean dupl = false;
  1199. for (int i = 1; i < tabbedPaneInnerOriginal.getTabCount(); i++) {
  1200. JScrollPane paneOriginal = (JScrollPane) tabbedPaneInnerOriginal.getComponentAt(i);
  1201. if (paneOriginal != null && ((Canvas) paneOriginal.getViewport().getComponent(0)).getGroupNode()
  1202. .getId() == node.getId()) {
  1203. dupl = true;
  1204. // set selected component to view
  1205. tabbedPaneOriginal.setSelectedComponent(tabbedPaneInnerOriginal);
  1206. // set selected tab in view to found upper-node-canvas
  1207. tabbedPaneInnerOriginal.setSelectedComponent(tabbedPaneInnerOriginal.getComponentAt(i));
  1208. }
  1209. // if we found a duplicate, break
  1210. if (dupl) {
  1211. break;
  1212. }
  1213. }
  1214. if (!dupl) {
  1215. JScrollPane sp = new JScrollPane(unc);
  1216. sp.setBorder(null);
  1217. // Selected tabbed Pane = tabbedPaneOriginal or tabbedPaneSplit
  1218. if (tabTemp == tabbedPaneOriginal) {
  1219. this.tabbedPaneInnerOriginal.add(node.getName(), sp);
  1220. this.tabbedPaneInnerOriginal.setSelectedComponent(sp);
  1221. this.tabbedPaneInnerOriginal.setTabComponentAt(this.tabbedPaneInnerOriginal.getTabCount() - 1,
  1222. new ButtonTabComponent(this.tabbedPaneInnerOriginal));
  1223. }
  1224. }
  1225. }
  1226. // TODO(Tom2021-12-1) refactor tabbedPane and access to groupNodeViews
  1227. private void updateUpperNodes() {
  1228. for (Component c : tabbedPaneInnerOriginal.getComponents()) {
  1229. if (!(c instanceof JScrollPane)) {
  1230. continue;
  1231. }
  1232. Component pane = ((JScrollPane) c).getViewport().getComponent(0);
  1233. if (pane instanceof Canvas groupNodeCanvas) {
  1234. //TODO(Tom2021-12-20) maybe
  1235. if(temp instanceof GroupNode node) {
  1236. groupNodeCanvas.setGroupNode(node);
  1237. }else {
  1238. log.warning("TODO tabbedPane confickt");
  1239. }
  1240. }
  1241. }
  1242. }
  1243. /**
  1244. * Removes UpperNodeTab if UpperNode was deleted
  1245. *
  1246. * @param cps the CPS object that is currently selected
  1247. */
  1248. private void removeUpperNodeTab(AbstractCanvasObject cps) {
  1249. if (cps instanceof GroupNode) {
  1250. for (int i = 1; i < tabbedPaneInnerOriginal.getTabCount(); i++) {
  1251. JScrollPane scrollPaneOriginal = (JScrollPane) tabbedPaneInnerOriginal.getComponentAt(i);
  1252. if (scrollPaneOriginal == null) {
  1253. } else if (((Canvas) scrollPaneOriginal.getViewport().getComponent(0)).getGroupNode()
  1254. .getId() == cps.getId()) {
  1255. ((ButtonTabComponent) tabbedPaneInnerOriginal.getTabComponentAt(i)).removeTabs();
  1256. break;
  1257. }
  1258. }
  1259. }
  1260. }
  1261. /**
  1262. * chooses whether to set the tabTemp to tabbedPaneOriginal or tabbedPaneSplit
  1263. */
  1264. private void chooseTabTemp() {
  1265. // TODO(Tom2021-12-1) Remove tabTabbed
  1266. tabTemp = tabbedPaneOriginal;
  1267. }
  1268. private JScrollPane getScrollPaneFromTabbedPane() {
  1269. return getScrollPaneFromTabbedPane(-1);
  1270. }
  1271. private JScrollPane getScrollPaneFromTabbedPane(int index) {
  1272. Component upperLevelSelectedComponent;
  1273. if (tabTemp == null) {
  1274. return null;
  1275. }
  1276. if (index == -1) {
  1277. upperLevelSelectedComponent = tabTemp.getSelectedComponent();
  1278. } else {
  1279. upperLevelSelectedComponent = tabTemp.getComponentAt(index);
  1280. }
  1281. if (upperLevelSelectedComponent instanceof JTabbedPane) {
  1282. Component nextLevel = ((JTabbedPane) upperLevelSelectedComponent).getSelectedComponent();
  1283. if (nextLevel instanceof JPanel panel)
  1284. return (JScrollPane) panel.getComponent(0);
  1285. else
  1286. return (JScrollPane) nextLevel;
  1287. } else if (upperLevelSelectedComponent instanceof JScrollPane scrollPane) {
  1288. return scrollPane;
  1289. } else {
  1290. return null;
  1291. }
  1292. }
  1293. private void openWebpage(String URL) {
  1294. try {
  1295. java.awt.Desktop.getDesktop().browse(new URI(URL));
  1296. } catch (Exception e) {
  1297. e.printStackTrace();
  1298. }
  1299. }
  1300. /**
  1301. * closes all UpperNodeTabs, that don't have a valid UpperNode (e.g. if it was
  1302. * ungrouped/deleted/replaced and so on)
  1303. */
  1304. private void closeInvalidUpperNodeTabs() {
  1305. /**
  1306. * close bugged Tabs
  1307. */
  1308. for (int i = 1; i < tabbedPaneInnerOriginal.getTabCount(); i++) {
  1309. JScrollPane scrollPaneOriginal = (JScrollPane) tabbedPaneInnerOriginal.getComponentAt(i);
  1310. if (((Canvas) scrollPaneOriginal.getViewport().getComponent(0)).getGroupNode() == null) {
  1311. ((ButtonTabComponent) tabbedPaneInnerOriginal.getTabComponentAt(i)).removeTabs();
  1312. break;
  1313. }
  1314. }
  1315. }
  1316. public void repaintCanvas() {
  1317. log.info("repaintCanvas");
  1318. tabbedPaneInnerOriginal.revalidate();
  1319. tabbedPaneInnerOriginal.repaint();
  1320. for (int i = 1; i < tabbedPaneInnerOriginal.getTabCount(); i++) {
  1321. JScrollPane scrollPaneOriginal = (JScrollPane) tabbedPaneInnerOriginal.getComponentAt(i);
  1322. scrollPaneOriginal.revalidate();
  1323. }
  1324. }
  1325. }