1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519 |
- package holeg.ui.view.main;
- import java.awt.BorderLayout;
- import java.awt.Color;
- import java.awt.Component;
- import java.awt.Cursor;
- import java.awt.Dimension;
- import java.awt.GraphicsDevice;
- import java.awt.GraphicsEnvironment;
- import java.awt.HeadlessException;
- import java.awt.Image;
- import java.awt.Point;
- import java.awt.Rectangle;
- import java.awt.Toolkit;
- import java.awt.datatransfer.UnsupportedFlavorException;
- import java.awt.event.ActionEvent;
- import java.awt.event.ActionListener;
- import java.awt.event.ComponentAdapter;
- import java.awt.event.ComponentEvent;
- import java.awt.event.KeyAdapter;
- import java.awt.event.KeyEvent;
- import java.awt.event.MouseAdapter;
- import java.awt.event.MouseEvent;
- import java.awt.event.MouseMotionAdapter;
- import java.io.File;
- import java.io.IOException;
- import java.net.URI;
- import java.util.ArrayList;
- import java.util.Collection;
- import java.util.logging.Logger;
- import java.util.stream.Collectors;
- import javax.swing.AbstractAction;
- import javax.swing.ActionMap;
- import javax.swing.BoxLayout;
- import javax.swing.ImageIcon;
- import javax.swing.InputMap;
- import javax.swing.JButton;
- import javax.swing.JCheckBoxMenuItem;
- import javax.swing.JComponent;
- import javax.swing.JFileChooser;
- import javax.swing.JFrame;
- import javax.swing.JLabel;
- import javax.swing.JMenu;
- import javax.swing.JMenuBar;
- import javax.swing.JMenuItem;
- import javax.swing.JOptionPane;
- import javax.swing.JPanel;
- import javax.swing.JPopupMenu;
- import javax.swing.JScrollPane;
- import javax.swing.JSplitPane;
- import javax.swing.JTabbedPane;
- import javax.swing.JTextField;
- import javax.swing.JToolBar;
- import javax.swing.JTree;
- import javax.swing.KeyStroke;
- import javax.swing.SwingUtilities;
- import javax.swing.filechooser.FileNameExtensionFilter;
- import javax.swing.tree.DefaultMutableTreeNode;
- import javax.swing.tree.DefaultTreeModel;
- import javax.swing.tree.TreeCellRenderer;
- import org.apache.commons.compress.archivers.ArchiveException;
- import com.google.gson.JsonParseException;
- import holeg.model.AbstractCanvasObject;
- import holeg.model.GroupNode;
- import holeg.model.HolonObject;
- import holeg.model.HolonSwitch;
- import holeg.preferences.ColorPreference;
- import holeg.preferences.ImagePreference;
- import holeg.ui.controller.Control;
- import holeg.ui.model.GuiSettings;
- import holeg.ui.model.IdCounter;
- import holeg.ui.model.IdCounter.CounterType;
- import holeg.ui.model.Model;
- import holeg.ui.model.Model.FairnessModel;
- import holeg.ui.view.canvas.Canvas;
- import holeg.ui.view.component.ButtonTabComponent;
- import holeg.ui.view.dialog.AboutUsPopUp;
- import holeg.ui.view.dialog.AddObjectPopUp;
- import holeg.ui.view.dialog.CanvasResizePopUp;
- import holeg.ui.view.dialog.CreateNewDialog;
- import holeg.ui.view.dialog.CreateNewDialog.Option;
- import holeg.ui.view.dialog.EditEdgesPopUp;
- import holeg.ui.view.information.HolonInformationPanel;
- import holeg.ui.view.inspector.Inspector;
- import holeg.ui.view.inspector.UnitGraph;
- import holeg.ui.view.window.AddOnWindow;
- import holeg.ui.view.window.FlexWindow;
- import holeg.ui.view.window.Outliner;
- import holeg.utility.image.Import;
- /**
- * Graphical User Interface.
- *
- * @author Gruppe14
- */
- public class GUI {
- private static final Logger log = Logger.getLogger(Model.class.getName());
- /**
- * Menu on the Top containing File, Edit View Help etc
- */
- private final JMenuBar menuBar = new JMenuBar();
- private final JMenu mnNewMenu = new JMenu("File");
- private final JMenu mnNewMenuEdit = new JMenu("Edit");
- private final JMenu mnNewMenuOptions = new JMenu("Options");
- private final JMenu mnNewMenuView = new JMenu("View");
- private final JMenu menuWindow = new JMenu("Window");
- /** Help Menu containing helpful Informations and the AboutUs Popup */
- private final JMenu mnHelp = new JMenu("Help");
- /**
- * Help -> Introduction A small Introduction of the Application, SmartGrids and
- * Holons
- */
- private final JMenuItem mntmIntroduction = new JMenuItem("Introduction");
- /**
- * Help -> UserManual
- */
- private final JMenuItem mntmUserManual = new JMenuItem("User Manual");
- /** Help -> Algorithm Help Menu */
- private final JMenuItem mntmAlgorithmHelp = new JMenuItem("Algorithm Introduction");
- /** Help -> CodeDocumentation */
- private final JMenuItem mntmCodeDoc = new JMenuItem("Code Documentation");
- /** Help -> AboutUs */
- private final JMenuItem mntmAboutUs = new JMenuItem("About Us");
- /** checked if supplyBars should be shown */
- private final JCheckBoxMenuItem showSupplyBarsCheckBox = new JCheckBoxMenuItem("Show supply bars.");
- /** menu for the different fairness Models */
- private final JMenu mnFairnessModel = new JMenu("Fairness Model");
- /** press to supply minimum demand first */
- private final JMenuItem mntmFairMinFirst = new JMenuItem("Minimum demand first");
- /** press to give everyone the same energy */
- private final JMenuItem mntmFairAlleEqual = new JMenuItem("Equal supply for everyone");
- private final JMenuItem mntmOpen = new JMenuItem("Open");
- private final JMenuItem mntmNew = new JMenuItem("New");
- private final JMenuItem mntmSave = new JMenuItem("Save");
- private final JMenuItem mntmCanvasSize = new JMenuItem("Set View Size");
- private final JSplitPane splitPane = new JSplitPane();
- private final JSplitPane splitPane1 = new JSplitPane();
- // the tabbed canvas containing the different sub-net tabs of the grid (Main
- // Grid + Nodes of Nodes)
- private final JPanel myPanel = new JPanel(new BorderLayout());
- private final JTabbedPane tabbedPaneInnerOriginal = new JTabbedPane(JTabbedPane.TOP);
- // the main canvas where we can see the grid currently displayed
- private final JScrollPane canvasSP = new JScrollPane();
- private final JScrollPane scrollPane1 = new JScrollPane();
- // private final JScrollPane holonSP = new JScrollPane();
- // the original tabbed Pane (containing tabs for view, statistics, holon,
- // flexibility)
- private final JTabbedPane tabbedPaneOriginal = new JTabbedPane(JTabbedPane.TOP);
- private final JPopupMenu popmenuEdit = new JPopupMenu();
- private final JMenuItem editItem = new JMenuItem("Edit Object");
- private final JLabel elementGraph = new JLabel("None ");
- private final JTree categoryTree = new JTree();
- /******************************************
- ************* Right Container*************
- ******************************************
- * Right Container: here comes the information about the HolonObject, such as
- * HolonElements Information, Properties and Consumption/Production graph.
- **/
- private final Inspector inspector;
- private final HolonInformationPanel informationPanel;
- private final JSplitPane splitHolonElPro = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
- // Prechoosed local Periods
- private final JScrollPane scrollProperties = new JScrollPane();
- // In this section is the graph for the selected HolonElement of the clicked
- private final Model model;
- private final Control control;
- // In this section are all the Holonelements that correspond to the clicked
- // HolonObject with consumption/production, name and amount.
- private final JPanel panel = new JPanel();
- private final JPanel panelHolonEl = new JPanel();
- // Buttons
- private final JButton btnAdd = new JButton();
- private final JPopupMenu btnAddPopUp = new JPopupMenu("Newacac");
- private final JMenuItem mItemNew = new JMenuItem("New..");
- private final JMenuItem mItemCategory = new JMenuItem("Category");
- private final JMenuItem mItemObject = new JMenuItem("Object");
- private final JMenuItem mItemSwitch = new JMenuItem("Switch");
- private final JButton btnDel = new JButton();
- private final JToolBar toolBar = new JToolBar();
- private final JToolBar toolBarHolonEl = new JToolBar();
- // Languages
- private final Canvas canvas;
- private final UnitGraph unitGraph;
- /** Textfield to show the period of an element */
- private final JTextField unitGraphLocalPeriod = new JTextField(6);
- private final JMenuItem mntmUndo = new JMenuItem("Undo");
- private final JMenuItem mntmRedo = new JMenuItem("Redo");
- private final JMenuItem mntmEditEdges = new JMenuItem("Edge Properties");
- private final JMenuItem mntmAlignAll = new JMenuItem("Align All");
- private final JMenuItem mntmResetCategory = new JMenuItem("Reset Categories");
- // TODO(Tom2021-12-1) make GUI a JFRAME and remove holegJFrame
- private JFrame holegJFrame;
- // tabbedPaneOriginal or tabbedPaneSplit
- private JTabbedPane tabTemp;
- private String catOfObjToBeEdited;
- private Canvas unc;
- private JPanel contentPane;
- // Pop up Windows
- private AddObjectPopUp addObjectPopUP;
- private AboutUsPopUp aboutUsPopUp;
- // variables
- private boolean dragging = false;
- private String actualObjectClicked;
- private Image img = null;
- private AbstractCanvasObject tempCps = null;
- // Time Stuff
- private TimePanel timePanel;
- public TimePanel getTimePanel() {
- return timePanel;
- }
- private AbstractCanvasObject temp = null;
- private String warningText = "Warning";
- private String saveBeforeNew = "Do you want to save your current data?";
- private String eraseCategory = "Do you really want to delete the Category ";
- private String selectObjBeforeErase = "Please select a Category or an Object in the left library in order to delete something.";
- private JMenuItem removeItem = new JMenuItem("Remove");
- /**
- * Create the application.
- *
- * @param control the Controller
- */
- GUI(Control control) {
- this.control = control;
- this.informationPanel = new HolonInformationPanel(control);
- this.model = control.getModel();
- inspector = new Inspector(control);
- control.calculateStateAndVisualForCurrentTimeStep();
- this.unitGraph = new UnitGraph(control);
- this.canvas = new Canvas(control, model.getCanvas());
- initialize();
- updateCategories(GuiSettings.getCategories());
- control.OnCategoryChanged.addListener(() -> this.updateCategoryUI(GuiSettings.getCategories()));
- this.unc = this.canvas;
- }
- /**
- * Initialize the contents of the frame.
- */
- private void initialize() {
- holegJFrame = new JFrame();
- holegJFrame.setTitle("HOLEG Simulator");
- // try to restore old position/dimensions
- ArrayList<Integer> savedWindowDim = control.loadSavedWindowDimensionsIfExistent();
- if (savedWindowDim.size() == 4) {
- holegJFrame.setBounds(savedWindowDim.get(0), savedWindowDim.get(1), savedWindowDim.get(2),
- savedWindowDim.get(3));
- }
- // if the upper part of the window is showing, the windows can still be
- // moved,
- // but if it is not, we need to move it to somewhere else
- if (savedWindowDim.size() != 4 || !isUpperPanelInsideBounds()) {
- holegJFrame.setBounds(100, 100, 1000, 800);
- holegJFrame.setExtendedState(JFrame.MAXIMIZED_BOTH);
- }
- holegJFrame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
- holegJFrame.addWindowListener(new java.awt.event.WindowAdapter() {
- @Override
- public void windowClosing(java.awt.event.WindowEvent windowEvent) {
- if (JOptionPane.showConfirmDialog(holegJFrame, "Are you sure you want to exit?", "HOLEG",
- JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE) == JOptionPane.YES_OPTION) {
- control
- .deleteDirectory(new File(System.getProperty("user.home") + "/.config/HolonGUI/Autosave"));
- // try to save the position and size of the window, such
- // that (if possible)
- // it can be opened in the same position the next time
- try {
- control.savePosAndSizeOfWindow(holegJFrame.getX(), holegJFrame.getY(),
- holegJFrame.getWidth(), holegJFrame.getHeight());
- } catch (Exception e) {
- e.printStackTrace();
- }
- System.exit(0);
- }
- }
- });
- contentPane = (JPanel) holegJFrame.getContentPane();
- int condition = JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT;
- InputMap inputMap = contentPane.getInputMap(condition);
- ActionMap actionMap = contentPane.getActionMap();
- String cntrlZDown = "controlZ";
- inputMap.put(KeyStroke.getKeyStroke("control Z"), cntrlZDown);
- actionMap.put(cntrlZDown, new AbstractAction() {
- private static final long serialVersionUID = 1L;
- @Override
- public void actionPerformed(ActionEvent e) {
- try {
- control.loadAutoSave(control.getUndoSave());
- closeInvalidUpperNodeTabs();
- control.calculateStateAndVisualForCurrentTimeStep();
- log.info("canvas.repaint0");
- canvas.repaint();
- updateUpperNodes();
- } catch (IOException eex) {
- eex.printStackTrace();
- }
- }
- });
- String cntrlYDown = "controlY";
- inputMap.put(KeyStroke.getKeyStroke("control Y"), cntrlYDown);
- actionMap.put(cntrlYDown, new AbstractAction() {
- private static final long serialVersionUID = 1L;
- @Override
- public void actionPerformed(ActionEvent e) {
- try {
- control.loadAutoSave(control.getRedoSave());
- closeInvalidUpperNodeTabs();
- control.calculateStateAndVisualForCurrentTimeStep();
- log.info("canvas.repaint1");
- canvas.repaint();
- updateUpperNodes();
- } catch (IOException ex) {
- ex.printStackTrace();
- }
- }
- });
- String cntrlADown = "controlA";
- inputMap.put(KeyStroke.getKeyStroke("control A"), cntrlADown);
- AbstractAction controlA = new AbstractAction() {
- private static final long serialVersionUID = 1L;
- @Override
- public void actionPerformed(ActionEvent e) {
- chooseTabTemp();
- GuiSettings.getSelectedObjects().clear();
- // Uppernode Canvas?
- JScrollPane scrollPane = getScrollPaneFromTabbedPane();
- Component canvasOrUpperNodeCanvas = scrollPane.getViewport().getComponent(0);
- if (canvasOrUpperNodeCanvas instanceof Canvas groupNodeCanvas) {
- control.addSelectedObjects(
- groupNodeCanvas.getGroupNode().getObjectsInThisLayer().collect(Collectors.toSet()));
- groupNodeCanvas.repaint();
- // or Canvas?
- }
- control.getObjectsInDepth();
- }
- };
- actionMap.put(cntrlADown, controlA);
- String delDown = "delete";
- inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0, false), delDown);
- actionMap.put(delDown, new AbstractAction() {
- private static final long serialVersionUID = 1L;
- @Override
- public void actionPerformed(ActionEvent e) {
- chooseTabTemp();
- // Uppernode Canvas?
- JScrollPane scrollPane = getScrollPaneFromTabbedPane();
- Component canvasOrUpperNodeCanvas = scrollPane.getViewport().getComponent(0);
- // check whether a producer was deleted (this triggers a
- // complete re-evaluation of the net)
- boolean wasProducerDeleted = true;
- if (canvasOrUpperNodeCanvas instanceof Canvas groupNodeCanvas) {
- for (AbstractCanvasObject cps : GuiSettings.getSelectedObjects()) {
- if (groupNodeCanvas.getGroupNode().getObjectsInThisLayer().anyMatch(object -> object == cps)) {
- control.deleteObjectInGroupNode(cps, groupNodeCanvas.getGroupNode());
- // remove UpperNodeTab if UpperNode deleted
- removeUpperNodeTab(cps);
- }
- }
- groupNodeCanvas.repaint();
- control.clearSelection();
- }
- // recalculate net if a producer was deleted
- if (wasProducerDeleted) {
- control.resetSimulation();
- control.calculateStateAndVisualForCurrentTimeStep();
- }
- GuiSettings.getSelectedObjects().clear();
- }
- });
- String cntrlCDown = "controlC";
- inputMap.put(KeyStroke.getKeyStroke("control C"), cntrlCDown);
- AbstractAction controlC = new AbstractAction() {
- private static final long serialVersionUID = 1L;
- @Override
- public void actionPerformed(ActionEvent e) {
- chooseTabTemp();
- JScrollPane scrollPane = getScrollPaneFromTabbedPane();
- if (!GuiSettings.getSelectedObjects().isEmpty()) {
- if (scrollPane.getViewport().getComponent(0)instanceof Canvas groupNodeCanvas)
- control.copy(groupNodeCanvas.getGroupNode());
- else
- control.copy(null);
- if (!GuiSettings.getClipboardObjects().isEmpty()) {
- //TODO(Tom2022-01-14): old code changes itemPaste
- //OLD: canvas.itemPaste.setEnabled(true);
- }
- }
- }
- };
- actionMap.put(cntrlCDown, controlC);
- String cntrlVDown = "controlV";
- inputMap.put(KeyStroke.getKeyStroke("control V"), cntrlVDown);
- AbstractAction controlV = new AbstractAction() {
- private static final long serialVersionUID = 1L;
- @Override
- public void actionPerformed(ActionEvent e) {
- try {
- tabTemp = null;
- if (tabbedPaneOriginal.getMousePosition() != null) {
- tabTemp = tabbedPaneOriginal;
- } else {
- }
- if (tabTemp == null)
- return;
- JScrollPane scrollPane = getScrollPaneFromTabbedPane();
- Component canvasOrUpperNodeCanvas = scrollPane.getViewport().getComponent(0);
- if (tabTemp != null && canvasOrUpperNodeCanvas instanceof Canvas groupNodeCanvas) {
- control.paste(groupNodeCanvas.getGroupNode(), canvasOrUpperNodeCanvas.getMousePosition());
- control.calculateStateAndVisualForCurrentTimeStep();
- scrollPane.getViewport().getComponent(0).repaint();
- } else {
- control.paste(null, canvas.getMousePosition());
- control.calculateStateAndVisualForCurrentTimeStep();
- log.info("canvas.repaint2");
- canvas.repaint();
- }
- } catch (HeadlessException | JsonParseException | UnsupportedFlavorException | IOException e1) {
- JLabel message = new JLabel("The Clipboard information cannot be pasted into Application.");
- JOptionPane.showMessageDialog(holegJFrame, message, "", JOptionPane.ERROR_MESSAGE);
- }
- }
- };
- actionMap.put(cntrlVDown, controlV);
- String cntrlXDown = "controlX";
- inputMap.put(KeyStroke.getKeyStroke("control X"), cntrlXDown);
- AbstractAction controlX = new AbstractAction() {
- private static final long serialVersionUID = 1L;
- @Override
- public void actionPerformed(ActionEvent e) {
- chooseTabTemp();
- JScrollPane scrollPane = getScrollPaneFromTabbedPane();
- if (!GuiSettings.getSelectedObjects().isEmpty()) {
- if (scrollPane.getViewport().getComponent(0)instanceof Canvas groupNodeCanvas) {
- control.cut(groupNodeCanvas.getGroupNode());
- control.calculateStateAndVisualForCurrentTimeStep();
- scrollPane.getViewport().getComponent(0).repaint();
- } else {
- control.cut(null);
- control.calculateStateAndVisualForCurrentTimeStep();
- log.info("canvas.repaint3");
- canvas.repaint();
- }
- if (!GuiSettings.getClipboardObjects().isEmpty()) {
- //TODO(Tom2022-01-14): old code changes itemPaste
- //OLD: canvas.itemPaste.setEnabled(true);
- }
- }
- }
- };
- actionMap.put(cntrlXDown, controlX);
- holegJFrame.setJMenuBar(menuBar);
- holegJFrame.setIconImage(Import.loadImage(ImagePreference.Logo, 30, 30));
- menuBar.add(mnNewMenu);
- mnNewMenu.add(mntmNew);
- mnNewMenu.add(mntmOpen);
- mnNewMenu.add(mntmSave);
- menuBar.add(mnNewMenuEdit);
- mnNewMenuEdit.add(mntmUndo);
- mnNewMenuEdit.add(mntmRedo);
- mnNewMenuEdit.add(mntmEditEdges);
- mntmEditEdges.addActionListener(actionEvent -> {
- EditEdgesPopUp edgePopUp = new EditEdgesPopUp(holegJFrame);
- edgePopUp.setCanvas(canvas);
- edgePopUp.setController(control);
- edgePopUp.setVisible(true);
- });
- // Edit -> Align All
- mnNewMenuEdit.add(mntmAlignAll);
- mntmAlignAll.addActionListener(actionEvent -> {
- // getScrollPaneFromTabbedPane().getViewport().getComponent(0) is always the
- // active canvas
- tryToAlignObjects();
- });
- menuBar.add(mnNewMenuOptions);
- mnNewMenuOptions.add(mntmResetCategory);
- mntmResetCategory.addActionListener(actionEvent -> {
- control.resetCategories();
- categoryTree.revalidate();
- categoryTree.repaint();
- });
- /**
- * Add Fairness Model Option to the option Menu
- */
- mnNewMenuOptions.add(mnFairnessModel);
- mnFairnessModel.add(mntmFairMinFirst);
- mntmFairMinFirst.setForeground(Color.BLUE);
- mntmFairMinFirst
- .setToolTipText("HolonObjects with the smallest mininum Demand will be partially supplied first.\n"
- + "After that as many HolonObjects as possible will get fully supplied.");
- mntmFairMinFirst.addActionListener(arg0 -> {
- control.getModel().setFairnessModel(FairnessModel.MininumDemandFirst);
- mntmFairMinFirst.setForeground(Color.BLUE);
- mntmFairAlleEqual.setForeground(mnFairnessModel.getForeground());
- control.calculateStateAndVisualForCurrentTimeStep();
- // Update UpperNodes
- Component canvasOrUpperNodeCanvas = getScrollPaneFromTabbedPane().getViewport().getComponent(0);
- if (canvasOrUpperNodeCanvas != null && canvasOrUpperNodeCanvas instanceof Canvas groupNodeCanvas) {
- groupNodeCanvas.repaint();
- }
- });
- mnFairnessModel.add(mntmFairAlleEqual);
- mntmFairAlleEqual.setToolTipText("HolonObjects will all get the same amount of energy.");
- mntmFairAlleEqual.addActionListener(arg0 -> {
- control.getModel().setFairnessModel(FairnessModel.AllEqual);
- mntmFairAlleEqual.setForeground(Color.BLUE);
- mntmFairMinFirst.setForeground(mnFairnessModel.getForeground());
- control.calculateStateAndVisualForCurrentTimeStep();
- // Update UpperNodes
- Component canvasOrUpperNodeCanvas = getScrollPaneFromTabbedPane().getViewport().getComponent(0);
- if (canvasOrUpperNodeCanvas != null && canvasOrUpperNodeCanvas instanceof Canvas groupNodeCanvas) {
- groupNodeCanvas.repaint();
- }
- });
- menuBar.add(mnNewMenuView);
- mnNewMenuView.add(mntmCanvasSize);
- mntmCanvasSize.addActionListener(actionEvent -> {
- CanvasResizePopUp popUp = new CanvasResizePopUp(model, control, canvas, this.tabbedPaneInnerOriginal,
- holegJFrame);
- popUp.setVisible(true);
- });
- tabbedPaneInnerOriginal.addChangeListener(change -> {
- control.clearSelection();
- });
- mnNewMenuView.add(mntmCanvasSize);
- /*
- * Adds Checkbox to turn supply bars on/off
- */
- mnNewMenuView.add(showSupplyBarsCheckBox);
- showSupplyBarsCheckBox.setSelected(true);
- showSupplyBarsCheckBox.addActionListener(arg0 -> {
- GuiSettings.showSupplyBars = showSupplyBarsCheckBox.isSelected();
- log.info("canvas.repaint4");
- canvas.repaint();
- // Update UpperNodes
- JScrollPane spane = getScrollPaneFromTabbedPane();
- if (spane != null) {
- Component canvasOrUpperNodeCanvas = spane.getViewport().getComponent(0);
- if (canvasOrUpperNodeCanvas != null
- && canvasOrUpperNodeCanvas instanceof Canvas groupNodeCanvas) {
- groupNodeCanvas.repaint();
- }
- }
- });
- initWindowMenu();
- /**
- * add Help Menu and its items
- */
- menuBar.add(mnHelp);
- mnHelp.add(mntmIntroduction);
- mnHelp.add(mntmUserManual);
- mnHelp.add(mntmAlgorithmHelp);
- mnHelp.add(mntmCodeDoc);
- mnHelp.add(mntmAboutUs);
- canvas.setBackground(Color.WHITE);
- canvas.setPreferredSize(new Dimension(GuiSettings.canvasSize.getX(), GuiSettings.canvasSize.getY()));
- /********************
- * RIGHT CONTAINER (INFORMATION)
- **********************/
- panelHolonEl.setLayout(new BoxLayout(panelHolonEl, BoxLayout.X_AXIS));
- toolBarHolonEl.setFloatable(false);
- panelHolonEl.add(toolBarHolonEl);
- /***********************
- * HolonElement Graph Actions
- **********************/
- /*
- * Update Local Period of an Element Graph
- */
- unitGraphLocalPeriod.addKeyListener(new KeyAdapter() {
- @Override
- public void keyReleased(KeyEvent e) {
- try {
- int localLength = Integer.parseInt(unitGraphLocalPeriod.getText());
- unitGraphLocalPeriod.setBackground(Color.WHITE);
- /**
- * set local graph Period
- */
- if (e.getKeyCode() == KeyEvent.VK_ENTER)
- unitGraph.setLocalPeriod(localLength);
- } catch (NumberFormatException ex) {
- unitGraphLocalPeriod.setBackground(ColorPreference.GUI.PALE_RED);
- }
- }
- });
- /*****************************
- * RIGHT CONTAINER DONE
- *****************************/
- holegJFrame.getContentPane().setLayout(new BorderLayout(0, 0));
- /****************
- * Tree Stuff
- ****************/
- // Override Key Actions
- inputMap = categoryTree.getInputMap();
- inputMap.put(KeyStroke.getKeyStroke("control C"), cntrlCDown);
- inputMap.put(KeyStroke.getKeyStroke("control V"), cntrlVDown);
- inputMap.put(KeyStroke.getKeyStroke("control X"), cntrlXDown);
- inputMap.put(KeyStroke.getKeyStroke("control A"), cntrlADown);
- TreeCellRenderer customRenderer = new TreeCellRenderer() {
- @Override
- public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded,
- boolean leaf, int row, boolean hasFocus) {
- JLabel label = new JLabel();
- Image imgR;
- if (leaf) {
- for (Category cat : GuiSettings.getCategories()) {
- for (AbstractCanvasObject cps : cat.getObjects()) {
- if (value.toString().equals(cps.getName())) {
- imgR = Import.loadImage(cps.getImage(), 50, 50);
- if (imgR != null) {
- label.setIcon(new ImageIcon(imgR));
- }
- label.setText(cps.getName());
- }
- }
- }
- }
- tree.setRowHeight(50);
- if (hasFocus) {
- label.setForeground(ColorPreference.Category.Focus);
- label.setOpaque(true);
- }
- if (label.getText().isEmpty()) {
- label.setText(value.toString());
- if (!value.toString().equals("Categories")) {
- label.setIcon(new ImageIcon(Import.loadImage(ImagePreference.Category.Folder)));
- }
- }
- return label;
- }
- };
- categoryTree.setCellRenderer(customRenderer);
- categoryTree.addMouseMotionListener(new MouseMotionAdapter() {
- public void mouseDragged(MouseEvent e) {
- checkForDragAndDrop(e);
- }
- /**
- * checks if an object of the current Panel could be replaced by the dragged
- * object
- *
- * @param e
- */
- private void checkForDragAndDrop(MouseEvent e) {
- try {
- /**
- * if no object gets dragged -> finished
- */
- if (!dragging)
- return;
- /**
- * select the current Panel
- */
- chooseTabTemp();
- JScrollPane scrollPane = getScrollPaneFromTabbedPane();
- if (scrollPane == null)
- return;
- Component canvasOrUpperNodeCanvas = scrollPane.getViewport().getComponent(0);
- /**
- * check for replacements on the canvas
- */
- if (canvasOrUpperNodeCanvas instanceof Canvas groupNodeCanvas) {
- if (unc.getMousePosition() == null)
- return;
- int x = (int) unc.getMousePosition().getX() + 16;
- int y = (int) unc.getMousePosition().getY() + 16;
- /**
- * check for replacement
- */
- groupNodeCanvas.checkForReplacement(x, y);
- /**
- * repaint
- */
- unc.invalidate();
- unc.repaint();
- } else {
- if (canvas.getMousePosition() == null)
- return;
- int x = (int) canvas.getMousePosition().getX() + 16;
- int y = (int) canvas.getMousePosition().getY() + 16;
- /**
- * check for replacement
- */
- canvas.checkForReplacement(x, y);
- /**
- * repaint
- */
- log.info("canvas.repaint5");
- canvas.repaint();
- }
- contentPane.updateUI();
- } catch (Exception eex) {
- eex.printStackTrace();
- }
- }
- });
- categoryTree.addMouseListener(new MouseAdapter() {
- public void mouseReleased(MouseEvent e) {
- try {
- if (dragging) {
- chooseTabTemp();
- JScrollPane scrollPane = getScrollPaneFromTabbedPane();
- Component canvasOrUpperNodeCanvas = scrollPane.getViewport().getComponent(0);
- if (canvasOrUpperNodeCanvas instanceof Canvas groupNodeCanvas) {
- int x = (int) groupNodeCanvas.getMousePosition().getX() + 16;
- int y = (int) groupNodeCanvas.getMousePosition().getY() + 16;
- AbstractCanvasObject h = null;
- if (tempCps instanceof HolonObject hO) {
- h = new HolonObject(hO);
- }
- if (tempCps instanceof HolonSwitch sw) {
- h = new HolonSwitch(sw);
- }
- h.setPosition(x, y);
- /**
- * close UpperNodeTabs of replaced UpperNode
- */
- //TODO(Tom2022-01-14): replacement with upperNode
- control.addObjectInGroupNode(h, groupNodeCanvas.getGroupNode());
- /**
- * object would be replaced
- */
- groupNodeCanvas.invalidate();
- control.calculateStateAndVisualForCurrentTimeStep();
- groupNodeCanvas.repaint();
- } else {
- int x = (int) canvas.getMousePosition().getX() + 16;
- int y = (int) canvas.getMousePosition().getY() + 16;
- AbstractCanvasObject h = null;
- if (tempCps instanceof HolonObject hO) {
- h = new HolonObject(hO);
- }
- if (tempCps instanceof HolonSwitch sw) {
- h = new HolonSwitch(sw);
- }
- h.setPosition(x, y);
- /**
- * close UpperNodeTabs of replaced UpperNode
- */
- control.addObjectCanvas(h);
- /**
- * no object should get replaced
- */
- log.info("canvas.repaint6");
- canvas.repaint();
- }
- control.calculateStateAndVisualForCurrentTimeStep();
- contentPane.updateUI();
- dragging = false;
- }
- } catch (Exception eex) {
- }
- holegJFrame.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
- }
- });
- popmenuEdit.add(editItem);
- popmenuEdit.add(removeItem);
- editItem.setEnabled(false);
- editItem.addActionListener(actionEvent -> {
- });
- categoryTree.addMouseListener(new MouseAdapter() {
- public void mousePressed(MouseEvent e) {
- try {
- actualObjectClicked = categoryTree.getPathForLocation(e.getX(), e.getY()).getLastPathComponent()
- .toString();
- // if an Object was selected, the porperties are shown in
- // the table
- DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) categoryTree
- .getPathForLocation(e.getX(), e.getY()).getLastPathComponent();
- if (SwingUtilities.isRightMouseButton(e)) {
- for (Category cat : GuiSettings.getCategories()) {
- for (AbstractCanvasObject cps : cat.getObjects()) {
- if (actualObjectClicked.equals(cps.getName())
- && !(cps instanceof HolonSwitch)) {
- editItem.setEnabled(true);
- popmenuEdit.show(e.getComponent(), e.getX(), e.getY());
- catOfObjToBeEdited = selectedNode.getParent().toString();
- tempCps = cps;
- }
- }
- }
- } else {
- for (Category cat : GuiSettings.getCategories()) {
- for (AbstractCanvasObject cps : cat.getObjects()) {
- if (actualObjectClicked.equals(cps.getName())) {
- File checkPath = new File(cps.getImage());
- if (checkPath.exists()) {
- img = new ImageIcon(cps.getImage()).getImage().getScaledInstance(32, 32,
- java.awt.Image.SCALE_SMOOTH);
- } else {
- img = Import.loadImage(cps.getImage(), 32, 32);
- }
- tempCps = cps;
- dragging = true;
- Cursor cursor = Toolkit.getDefaultToolkit().createCustomCursor(img, new Point(0, 0),
- "Image");
- holegJFrame.setCursor(cursor);
- }
- }
- }
- }
- } catch (Exception eex) {
- }
- }
- });
- editItem.addActionListener(actionEvent -> {
- // Remove the selected Object object
- // AddObjectPopUp(boolean edit, AbstractCpsObject obj, String cat, JFrame
- // parentFrame)
- System.out.println("Edit");
- addObjectPopUP = new AddObjectPopUp(true, tempCps, catOfObjToBeEdited, holegJFrame);
- addObjectPopUP.setCategory(catOfObjToBeEdited);
- addObjectPopUP.setController(control);
- addObjectPopUP.setVisible(true);
- });
- removeItem.addActionListener(actionEvent -> {
- // Remove the selected Object object
- log.info("catOfObjToBeEdited:" + catOfObjToBeEdited + ", tempCps:" + tempCps);
- control.findCategoryWithName(catOfObjToBeEdited).ifPresent(cat -> {
- cat.removeObjectsWithName(tempCps.getName());
- });
- });
- scrollPane1.setViewportView(categoryTree);
- scrollPane1.setColumnHeaderView(panel);
- panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
- toolBar.setAlignmentX(Component.LEFT_ALIGNMENT);
- toolBar.setFloatable(false);
- panel.add(toolBar);
- btnAddPopUp.add(mItemNew);
- mItemNew.addActionListener(actionEvent -> {
- new CreateNewDialog(control, holegJFrame);
- });
- btnAddPopUp.addSeparator();
- btnAddPopUp.add(mItemCategory);
- mItemCategory.addActionListener(actionEvent -> {
- new CreateNewDialog(control, Option.Category, holegJFrame);
- });
- btnAddPopUp.add(mItemObject);
- mItemObject.addActionListener(actionEvent -> {
- new CreateNewDialog(control, Option.Object, holegJFrame);
- });
- btnAddPopUp.add(mItemSwitch);
- mItemSwitch.addActionListener(actionEvent -> {
- new CreateNewDialog(control, Option.Switch, holegJFrame);
- });
- btnAdd.addActionListener(actionEvent -> btnAddPopUp.show(btnAdd, -1, +20));
- btnAdd.setIcon(new ImageIcon(Import.loadImage("images/buttons/plus.png", 16, 16)));
- btnAdd.setToolTipText("<html><b>New</b><br>Add a new Category or Item to the library.</html>");
- toolBar.add(btnAdd);
- /**
- * Help Menu Action Listeners
- */
- /**
- * URL of the telecommunication git Wiki
- */
- String tkWikiWebpage = "https://git.tk.informatik.tu-darmstadt.de/carlos.garcia/praktikum-holons/wiki/";
- /** open Introduction Web Page */
- mntmIntroduction.addMouseListener(new MouseAdapter() {
- @Override
- public void mousePressed(MouseEvent e) {
- openWebpage(tkWikiWebpage + "Introduction+V2.1");
- }
- });
- /** open UserManual WebPage */
- mntmUserManual.addMouseListener(new MouseAdapter() {
- @Override
- public void mousePressed(MouseEvent e) {
- openWebpage(tkWikiWebpage + "User+Manual+V2.1");
- }
- });
- /** open Algorithm Help Web Page */
- mntmAlgorithmHelp.addMouseListener(new MouseAdapter() {
- @Override
- public void mousePressed(MouseEvent e) {
- openWebpage(tkWikiWebpage + "Algorithms+V2.1");
- }
- });
- /** open Code Documentation Web Page */
- mntmCodeDoc.addMouseListener(new MouseAdapter() {
- @Override
- public void mousePressed(MouseEvent e) {
- openWebpage(tkWikiWebpage + "Code+documentation+V2.1");
- }
- });
- /**
- * Pop up - About Us with some important information about the developers,
- * source and programming stuff
- */
- mntmAboutUs.addMouseListener(new MouseAdapter() {
- @Override
- public void mousePressed(MouseEvent e) {
- aboutUsPopUp = new AboutUsPopUp(holegJFrame);
- aboutUsPopUp.setVisible(true);
- }
- });
- // Del Button
- btnDel.addActionListener(actionEvent -> {
- Object nodeInfo = categoryTree.getLastSelectedPathComponent();
- if (nodeInfo != null) {
- DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) nodeInfo;
- String nodeName = selectedNode.getUserObject().toString();
- int depthOfNode = selectedNode.getLevel();
- try {
- switch (depthOfNode) {
- case 1:
- int dialogResult = JOptionPane.showConfirmDialog(holegJFrame, eraseCategory + nodeName + "?",
- warningText, JOptionPane.YES_NO_OPTION);
- if (dialogResult == JOptionPane.YES_OPTION) {
- GuiSettings.getCategories().stream().filter(cat -> cat.getName() == nodeName).findAny()
- .ifPresent(cat -> {
- control.deleteCategory(cat);
- });
- }
- break;
- case 2:
- DefaultMutableTreeNode parent = (DefaultMutableTreeNode) selectedNode.getParent();
- control.findCategoryWithName(parent.getUserObject().toString()).ifPresent(cat -> {
- cat.removeObjectsWithName(nodeName);
- });
- break;
- default:
- JOptionPane.showMessageDialog(holegJFrame, selectObjBeforeErase);
- }
- } catch (Exception e2) {
- }
- } else {
- JOptionPane.showMessageDialog(holegJFrame, selectObjBeforeErase);
- }
- categoryTree.repaint();
- });
- btnDel.setIcon(new ImageIcon(Import.loadImage("images/buttons/minus.png", 16, 16)));
- btnDel.setToolTipText("<html><b>Delete</b><br>Removes a Category or a Category Item.</html>");
- toolBar.add(btnDel);
- holegJFrame.getContentPane().add(splitPane);
- mntmNew.addActionListener(actionEvent -> {
- if (model.getCanvas().getObjectsInThisLayer().findAny().isPresent()) {
- int newWarning = JOptionPane.YES_NO_OPTION;
- int dialogForNewWarning = JOptionPane.showConfirmDialog(holegJFrame, saveBeforeNew, warningText,
- newWarning);
- if (dialogForNewWarning == JOptionPane.YES_OPTION) {
- mntmSave.doClick();
- }
- }
- // Remove all but main tab
- while (tabbedPaneInnerOriginal.getTabCount() > 1) {
- tabbedPaneInnerOriginal.remove(1);
- }
- control.clearSelection();
- model.clear();
- control.OnSelectionChanged.broadcast();
- GuiSettings.getSelectedEdges().clear();
- control.getModel().setCurrentIteration(0);
- elementGraph.setText("None");
- log.info("canvas.repaint7");
- canvas.repaint();
- IdCounter.resetObjectCounter(CounterType.Object);
- IdCounter.resetObjectCounter(CounterType.Element);
- control.calculateStateAndVisualForCurrentTimeStep();
- });
- mntmOpen.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent evt) {
- menuFileExitActionPerformed();
- }
- private void menuFileExitActionPerformed() {
- JFileChooser fileChooser = new JFileChooser();
- fileChooser.setCurrentDirectory(new File(System.getProperty("user.dir") + "/exampleNetworks/"));
- FileNameExtensionFilter holonFilter = new FileNameExtensionFilter("Holon Save File(*.holon)", "holon");
- fileChooser.setFileFilter(holonFilter);
- if (fileChooser.showOpenDialog(holegJFrame) == JFileChooser.APPROVE_OPTION) {
- File file = fileChooser.getSelectedFile();
- try {
- while (tabbedPaneInnerOriginal.getTabCount() > 1) {
- tabbedPaneInnerOriginal.remove(1);
- }
- GuiSettings.getSelectedObjects().clear();
- control.loadFile(file.getAbsolutePath());
- log.info("canvas.repaint8");
- canvas.repaint();
- categoryTree.repaint();
- control.calculateStateAndVisualForCurrentTimeStep();
- } catch (IOException | ArchiveException e) {
- e.printStackTrace();
- JLabel message = new JLabel("The savefile is corrupt and cannot be opened.");
- JOptionPane.showMessageDialog(holegJFrame, message, "", JOptionPane.ERROR_MESSAGE);
- }
- }
- }
- });
- mntmSave.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent evt) {
- menuSaveActionPerformed();
- }
- private void menuSaveActionPerformed() {
- JFileChooser fileChooser = new JFileChooser();
- FileNameExtensionFilter holonFilter = new FileNameExtensionFilter("Holon Save File(*.holon)", "holon");
- fileChooser.setFileFilter(holonFilter);
- if (fileChooser.showSaveDialog(holegJFrame) == JFileChooser.APPROVE_OPTION) {
- File selectedFile = fileChooser.getSelectedFile();
- String fileName = selectedFile.getName();
- String fullPath = fileChooser.getSelectedFile().getPath();
- if (fileChooser.getFileFilter().equals(holonFilter)) {
- if (!fileName.contains("."))
- fullPath += ".holon";
- }
- if (!fullPath.endsWith(".holon")) {
- String suffix = fullPath.substring(fullPath.lastIndexOf("."), fullPath.length());
- String[] options = new String[] { "keep .holon", "use " + suffix };
- JLabel message = new JLabel(
- "Are you sure to use the extension \"" + suffix + "\" instead of \".holon\"?");
- int response = JOptionPane.showOptionDialog(holegJFrame, message, "",
- JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[1]);
- if (response == 0)
- fullPath = fullPath.replace(suffix, ".holon");
- }
- try {
- control.saveFile(new File(fullPath).getAbsolutePath());
- } catch (IOException | ArchiveException e) {
- e.printStackTrace();
- }
- }
- }
- });
- mntmUndo.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent evt) {
- menuUndoActionPerformed();
- }
- private void menuUndoActionPerformed() {
- try {
- control.loadAutoSave(control.getUndoSave());
- closeInvalidUpperNodeTabs();
- control.calculateStateAndVisualForCurrentTimeStep();
- log.info("canvas.repaint9");
- canvas.repaint();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- });
- mntmRedo.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent evt) {
- menuRedoActionPerformed();
- }
- private void menuRedoActionPerformed() {
- try {
- control.loadAutoSave(control.getRedoSave());
- closeInvalidUpperNodeTabs();
- control.calculateStateAndVisualForCurrentTimeStep();
- log.info("canvas.repaint10");
- canvas.repaint();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- });
- timePanel = new TimePanel(control);
- timePanel.setBorder(null);
- timePanel.getTimeSlider().addChangeListener(changeEvent -> {
- // TimeSliderChanged event
- control.calculateStateAndVisualForTimeStep(timePanel.getTimeSlider().getValue());
- unitGraph.repaint();
- contentPane.updateUI();
- });
- splitPane1.setMinimumSize(new Dimension(0, 25));
- splitPane.setRightComponent(splitPane1);
- splitPane.setDividerLocation(200);
- splitPane1.setDividerLocation(500);
- splitPane.setLeftComponent(scrollPane1);
- tabbedPaneOriginal.addTab("View", tabbedPaneInnerOriginal);
- myPanel.add(canvasSP, BorderLayout.CENTER);
- tabbedPaneInnerOriginal.addTab("Main Grid", myPanel);
- splitPane1.setLeftComponent(tabbedPaneOriginal);
- splitPane1.setRightComponent(splitHolonElPro);
- splitPane1.setResizeWeight(0.9);
- splitHolonElPro.setDividerLocation(700);
- // containing the graph and the elements-list
- splitHolonElPro.setTopComponent(inspector);
- // containing the object's properties
- splitHolonElPro.setBottomComponent(scrollProperties);
- canvasSP.setViewportView(canvas);
- // Set up of the Properties section
- scrollProperties.setViewportView(this.informationPanel);
- scrollProperties.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
- scrollProperties.getVerticalScrollBar().setUnitIncrement(16);
- tabbedPaneOriginal.setBorder(null);
- scrollProperties.setBorder(null);
- splitPane.setBorder(null);
- splitPane1.setBorder(null);
- splitHolonElPro.setBorder(null);
- panelHolonEl.setBorder(null);
- canvasSP.setBorder(null);
- holegJFrame.getContentPane().add(timePanel, BorderLayout.SOUTH);
- try {
- control.loadAutoSave(System.getProperty("user.home") + "/.config/HolonGUI/Category/Category.json");
- } catch (IOException e1) {
- }
- canvasSP.addComponentListener(new ComponentAdapter() {
- @Override
- public void componentResized(ComponentEvent e) {
- GuiSettings.canvasSize.setX(Math.max(GuiSettings.canvasSize.getX(), canvasSP.getViewport().getWidth()));
- GuiSettings.canvasSize
- .setY(Math.max(GuiSettings.canvasSize.getY(), canvasSP.getViewport().getHeight()));
- log.info("canvas.repaint11");
- canvas.repaint();
- }
- });
- }
- private void tryToAlignObjects() {
- //TODO(Tom2022-01-14): recreateTryToAlignObjects
- }
- private void initWindowMenu() {
- menuBar.add(menuWindow);
- // Algo
- JMenuItem openMenu = new JMenuItem("Open Algorithm Panel", new ImageIcon(Import
- .loadImage(ImagePreference.Button.Menu.Algo).getScaledInstance(20, 20, java.awt.Image.SCALE_SMOOTH)));
- openMenu.addActionListener(actionEvent -> {
- new AddOnWindow(holegJFrame, control);
- });
- openMenu.setAccelerator(KeyStroke.getKeyStroke('N', Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx()));
- menuWindow.add(openMenu);
- // Outliner
- JMenuItem openOutliner = new JMenuItem("Open Outliner", new ImageIcon(Import
- .loadImage(ImagePreference.Button.Menu.Outliner).getScaledInstance(20, 20, java.awt.Image.SCALE_SMOOTH)));
- openOutliner.addActionListener(actionEvent -> {
- new Outliner(holegJFrame, model, control);
- });
- openOutliner
- .setAccelerator(KeyStroke.getKeyStroke('O', Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx()));
- menuWindow.add(openOutliner);
- // FlexWindow
- JMenuItem openFlexMenuItem = new JMenuItem("Open Flexibility Panel", new ImageIcon(Import
- .loadImage(ImagePreference.Button.Menu.Algo).getScaledInstance(20, 20, java.awt.Image.SCALE_SMOOTH)));
- openFlexMenuItem.addActionListener(actionEvent -> {
- new FlexWindow(holegJFrame, control);
- });
- openFlexMenuItem
- .setAccelerator(KeyStroke.getKeyStroke('L', Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx()));
- menuWindow.add(openFlexMenuItem);
- }
- private boolean isUpperPanelInsideBounds() {
- int x = holegJFrame.getX();
- int y = holegJFrame.getY();
- int width = holegJFrame.getWidth();
- // get all connected screen devices
- GraphicsDevice[] screenDevices = GraphicsEnvironment.getLocalGraphicsEnvironment().getScreenDevices();
- boolean isUpperPanelVisible = false;
- // and check whether they contain the upper left or upper right point of
- // the frame
- for (GraphicsDevice device : screenDevices) {
- Rectangle bounds = device.getDefaultConfiguration().getBounds();
- if (bounds.contains(x, y) || bounds.contains(x + width, y)) {
- isUpperPanelVisible = true;
- break;
- }
- }
- return isUpperPanelVisible;
- }
- /**
- * reloads the Categories from Model.
- *
- * @param categories the current categories
- */
- private void updateCategories(Collection<Category> categories) {
- DefaultTreeModel treemodel = new DefaultTreeModel(new DefaultMutableTreeNode("Categories") {
- private static final long serialVersionUID = 1L;
- {
- DefaultMutableTreeNode node1;
- for (Category c : categories) {
- node1 = new DefaultMutableTreeNode(c.getName());
- for (AbstractCanvasObject obj : c.getObjects()) {
- node1.add(new DefaultMutableTreeNode(obj.getName()));
- }
- add(node1);
- }
- }
- });
- categoryTree.setModel(treemodel);
- }
- /**
- * When changes are made to the Categories.
- *
- * @param categories the Categories
- */
- public void updateCategoryUI(Collection<Category> categories) {
- DefaultTreeModel model = (DefaultTreeModel) categoryTree.getModel();
- updateCategories(categories);
- model.reload();
- }
- void setVisible(boolean value) {
- holegJFrame.setVisible(value);
- }
- /*
- * Open a new Tab with an UpperNodeCanvas
- */
- public void openNewUpperNodeTab(GroupNode node) {
- chooseTabTemp();
- JScrollPane scrollPane = getScrollPaneFromTabbedPane();
- if (scrollPane.getViewport().getComponent(0)instanceof Canvas canvasPanel) {
- unc = new Canvas(control, node);
- }
- // check if tab already open for clicked NodeOfNode
- boolean dupl = false;
- for (int i = 1; i < tabbedPaneInnerOriginal.getTabCount(); i++) {
- JScrollPane paneOriginal = (JScrollPane) tabbedPaneInnerOriginal.getComponentAt(i);
- if (paneOriginal != null && ((Canvas) paneOriginal.getViewport().getComponent(0)).getGroupNode()
- .getId() == node.getId()) {
- dupl = true;
- // set selected component to view
- tabbedPaneOriginal.setSelectedComponent(tabbedPaneInnerOriginal);
- // set selected tab in view to found upper-node-canvas
- tabbedPaneInnerOriginal.setSelectedComponent(tabbedPaneInnerOriginal.getComponentAt(i));
- }
- // if we found a duplicate, break
- if (dupl) {
- break;
- }
- }
- if (!dupl) {
- JScrollPane sp = new JScrollPane(unc);
- sp.setBorder(null);
- // Selected tabbed Pane = tabbedPaneOriginal or tabbedPaneSplit
- if (tabTemp == tabbedPaneOriginal) {
- this.tabbedPaneInnerOriginal.add(node.getName(), sp);
- this.tabbedPaneInnerOriginal.setSelectedComponent(sp);
- this.tabbedPaneInnerOriginal.setTabComponentAt(this.tabbedPaneInnerOriginal.getTabCount() - 1,
- new ButtonTabComponent(this.tabbedPaneInnerOriginal));
- }
- }
- }
- // TODO(Tom2021-12-1) refactor tabbedPane and access to groupNodeViews
- private void updateUpperNodes() {
- for (Component c : tabbedPaneInnerOriginal.getComponents()) {
- if (!(c instanceof JScrollPane)) {
- continue;
- }
- Component pane = ((JScrollPane) c).getViewport().getComponent(0);
- if (pane instanceof Canvas groupNodeCanvas) {
- //TODO(Tom2021-12-20) maybe
- if(temp instanceof GroupNode node) {
- groupNodeCanvas.setGroupNode(node);
- }else {
- log.warning("TODO tabbedPane confickt");
- }
- }
- }
- }
- /**
- * Removes UpperNodeTab if UpperNode was deleted
- *
- * @param cps the CPS object that is currently selected
- */
- private void removeUpperNodeTab(AbstractCanvasObject cps) {
- if (cps instanceof GroupNode) {
- for (int i = 1; i < tabbedPaneInnerOriginal.getTabCount(); i++) {
- JScrollPane scrollPaneOriginal = (JScrollPane) tabbedPaneInnerOriginal.getComponentAt(i);
- if (scrollPaneOriginal == null) {
- } else if (((Canvas) scrollPaneOriginal.getViewport().getComponent(0)).getGroupNode()
- .getId() == cps.getId()) {
- ((ButtonTabComponent) tabbedPaneInnerOriginal.getTabComponentAt(i)).removeTabs();
- break;
- }
- }
- }
- }
- /**
- * chooses whether to set the tabTemp to tabbedPaneOriginal or tabbedPaneSplit
- */
- private void chooseTabTemp() {
- // TODO(Tom2021-12-1) Remove tabTabbed
- tabTemp = tabbedPaneOriginal;
- }
- private JScrollPane getScrollPaneFromTabbedPane() {
- return getScrollPaneFromTabbedPane(-1);
- }
- private JScrollPane getScrollPaneFromTabbedPane(int index) {
- Component upperLevelSelectedComponent;
- if (tabTemp == null) {
- return null;
- }
- if (index == -1) {
- upperLevelSelectedComponent = tabTemp.getSelectedComponent();
- } else {
- upperLevelSelectedComponent = tabTemp.getComponentAt(index);
- }
- if (upperLevelSelectedComponent instanceof JTabbedPane) {
- Component nextLevel = ((JTabbedPane) upperLevelSelectedComponent).getSelectedComponent();
- if (nextLevel instanceof JPanel panel)
- return (JScrollPane) panel.getComponent(0);
- else
- return (JScrollPane) nextLevel;
- } else if (upperLevelSelectedComponent instanceof JScrollPane scrollPane) {
- return scrollPane;
- } else {
- return null;
- }
- }
- private void openWebpage(String URL) {
- try {
- java.awt.Desktop.getDesktop().browse(new URI(URL));
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- /**
- * closes all UpperNodeTabs, that don't have a valid UpperNode (e.g. if it was
- * ungrouped/deleted/replaced and so on)
- */
- private void closeInvalidUpperNodeTabs() {
- /**
- * close bugged Tabs
- */
- for (int i = 1; i < tabbedPaneInnerOriginal.getTabCount(); i++) {
- JScrollPane scrollPaneOriginal = (JScrollPane) tabbedPaneInnerOriginal.getComponentAt(i);
- if (((Canvas) scrollPaneOriginal.getViewport().getComponent(0)).getGroupNode() == null) {
- ((ButtonTabComponent) tabbedPaneInnerOriginal.getTabComponentAt(i)).removeTabs();
- break;
- }
- }
- }
- public void repaintCanvas() {
- log.info("repaintCanvas");
- tabbedPaneInnerOriginal.revalidate();
- tabbedPaneInnerOriginal.repaint();
- for (int i = 1; i < tabbedPaneInnerOriginal.getTabCount(); i++) {
- JScrollPane scrollPaneOriginal = (JScrollPane) tabbedPaneInnerOriginal.getComponentAt(i);
- scrollPaneOriginal.revalidate();
- }
- }
- }
|