Browse Source

New Algorithm Menu v1

Tom Troppmann 5 years ago
parent
commit
741a5f1748

BIN
res/Button_Images/iconAlgo.png


BIN
res/Button_Images/iconOutliner.png


+ 14 - 0
src/api/Algorithm.java

@@ -0,0 +1,14 @@
+package api;
+
+import javax.swing.JPanel;
+
+import ui.controller.Control;
+
+/**
+ * Interface for a Algorithm that is executed on the current timestep.
+ * @author Tom Troppmann
+ */
+public interface Algorithm  {
+	public JPanel getAlgorithmPanel();
+	public void setController(Control control);
+}

+ 86 - 0
src/exampleAlgorithms/RandomSwitch.java

@@ -0,0 +1,86 @@
+package exampleAlgorithms;
+
+import java.awt.BorderLayout;
+import java.awt.Dimension;
+import java.util.Hashtable;
+
+import javax.swing.BorderFactory;
+import javax.swing.BoxLayout;
+import javax.swing.JButton;
+import javax.swing.JFrame;
+import javax.swing.JLabel;
+import javax.swing.JPanel;
+import javax.swing.JSlider;
+import javax.swing.JTextField;
+
+import api.Algorithm;
+import classes.HolonSwitch;
+import ui.controller.Control;
+
+public class RandomSwitch implements Algorithm {
+	private double  randomChance = 0.5;
+	private Control  control;
+	
+	private JPanel content = new JPanel();
+//	To Test the Layout Faster   
+//	public static void main(String[] args)
+//    {
+//        JFrame newFrame = new JFrame("exampleWindow");
+//        RandomSwitch instance = new RandomSwitch();
+//        newFrame.setContentPane(instance.getAlgorithmPanel());
+//        newFrame.pack();
+//        newFrame.setVisible(true);
+//    }
+	public RandomSwitch(){
+		content.setLayout(new BorderLayout());
+		content.add(createParameterPanel(), BorderLayout.CENTER);
+		JButton buttonRun = new JButton("Run");
+		buttonRun.addActionListener(actionEvent -> run());
+		content.add(buttonRun, BorderLayout.PAGE_END);
+		content.setPreferredSize(new Dimension(300,300));
+	}
+	private JPanel createParameterPanel() {
+		JPanel parameterPanel = new JPanel();
+		parameterPanel.setLayout(new BoxLayout(parameterPanel, BoxLayout.PAGE_AXIS));
+		parameterPanel.add(createFlipChanceSlider());
+		return parameterPanel;
+	}
+	private JSlider createFlipChanceSlider() {
+		JSlider flipChance =new JSlider(JSlider.HORIZONTAL,0, 100, 50);
+		flipChance.setBorder(BorderFactory.createTitledBorder("FlipChance"));
+		flipChance.setMajorTickSpacing(50);
+		flipChance.setMinorTickSpacing(5);
+		flipChance.setPaintTicks(true);
+		Hashtable<Integer, JLabel> labelTable = new Hashtable<Integer, JLabel>();
+		labelTable.put( new Integer( 0 ), new JLabel("0.0") );
+		labelTable.put( new Integer( 50 ), new JLabel("0.5") );
+		labelTable.put( new Integer( 100 ), new JLabel("1.0") );
+		flipChance.addChangeListener(actionEvent ->randomChance =(double)flipChance.getValue()/100.0);
+		flipChance.setLabelTable( labelTable );
+		flipChance.setPaintLabels(true);
+		return flipChance;
+	}
+	private void run() {
+		System.out.println("run");
+		for (HolonSwitch s : control.getModel().getSwitches()) {
+			// Set to Manual Mode
+			s.setManualMode(true);
+			// Generate a random number between 0 and 1
+			double randomDouble = Math.random();
+			if (randomDouble < randomChance) {
+				s.setManualState(!s.getActiveManual());
+			} 
+		}
+		control.calculateStateForCurrentTimeStep();
+	}
+	@Override
+	public JPanel getAlgorithmPanel() {
+		return content;
+	}
+	@Override
+	public void setController(Control control) {
+		this.control = control;
+		
+	}
+
+}

+ 1 - 0
src/exampleAlgorithms/RandomSwitchesAlgorithm.java

@@ -30,5 +30,6 @@ public class RandomSwitchesAlgorithm implements CpsAlgorithm {
 				s.setManualState(false);
 			}
 		}
+		
 	}
 }

+ 7 - 1
src/ui/controller/SimulationManager.java

@@ -781,7 +781,13 @@ public class SimulationManager {
 	public void setCanvas(MyCanvas can) {
 		canvas = can;
 	}
-
+	/**
+	 * Should be a better way to update the canvas -.-
+	 * @param can
+	 */
+	public void updateCanvas() {
+		canvas.repaint();
+	}
 	/**
 	 * Reset all Data to the current state of the Model.
 	 */

+ 182 - 0
src/ui/view/AlgoWindow.java

@@ -0,0 +1,182 @@
+package ui.view;
+
+import java.awt.BorderLayout;
+import java.awt.Dimension;
+import java.awt.Font;
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.FileReader;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.net.URLClassLoader;
+import java.util.Arrays;
+import java.util.Scanner;
+import java.util.stream.Collectors;
+
+import javax.swing.JButton;
+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.JPanel;
+import javax.swing.JTextArea;
+import javax.swing.JTextPane;
+import javax.swing.text.SimpleAttributeSet;
+import javax.swing.text.StyleConstants;
+import javax.swing.text.StyledDocument;
+import javax.tools.JavaCompiler;
+import javax.tools.ToolProvider;
+
+import api.Algorithm;
+import ui.controller.Control;
+
+//TODO delete old class AlgorithmMenu and change this class to AlgorithmMenu;
+public class AlgoWindow extends JFrame{
+	private File root;
+	private Algorithm actual;
+	private Control control;
+	private JPanel content = new JPanel();
+	AlgoWindow(JFrame parentFrame, Control control){
+		this.control = control;
+		this.setTitle("Algorithm");
+		this.setVisible(true);
+		this.setContentPane(content);
+		this.setIconImage(Util.loadImage("/Images/Holeg.png", 30, 30));
+		initMenuBar();
+		initDefaultContentPanel();
+		this.pack();
+		this.setLocationRelativeTo(parentFrame);
+	}
+	private void initMenuBar() {
+		JMenuBar menuBar = new JMenuBar();
+		JMenu menuSelect = new JMenu("File");
+		JMenuItem menuItemFolder= new JMenuItem("Open Folder..");
+		
+		
+		JMenuItem menuItemAlgorithm= new JMenuItem("Open .java-File..");
+		menuItemAlgorithm.addActionListener(actionEvent -> {
+			System.out.println("Test");
+			JFileChooser fileChooser = new JFileChooser();
+			fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
+			fileChooser.setAcceptAllFileFilterUsed(false);
+			int result = fileChooser.showOpenDialog(this);
+			if(result == JFileChooser.APPROVE_OPTION) {
+				//Found a file
+				File founded = fileChooser.getSelectedFile();
+				//Get Class name:
+				String name = founded.getName().substring(0, founded.getName().lastIndexOf("."));
+				//get Package name
+				String packageName = "";
+				Scanner in = null;
+				try {
+					in = new Scanner(founded);
+				} catch (FileNotFoundException e) {
+					System.out.println("File not Found");
+				}
+				while(in.hasNext()) {
+					String line = in.nextLine().trim();
+					if(line.startsWith("package")) {
+						packageName = line.substring(8, line.length()-1);
+						break;
+					}
+				}
+				//GetPathName
+				String path =  founded.getParentFile().isDirectory() ? founded.getParentFile().getAbsolutePath() : "";
+				File folder = founded.getParentFile();
+				System.out.println(founded.getName() + ", Name:" + name + ", Package:" + packageName + ", Path:" + path);
+				// Compile source file.
+				JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
+				if (ToolProvider.getSystemJavaCompiler() == null) {
+					System.out.println("MissingCompiler");
+				}else {
+					compiler.run(null, null, null, founded.getAbsolutePath());					
+				}
+				try {
+				URLClassLoader classLoader = URLClassLoader.newInstance(new URL[] { folder.toURI().toURL() });
+				Class<?> cls = Class.forName(packageName.isEmpty()?name:packageName + "." +name, true, classLoader);
+				Object object = cls.newInstance();
+				if(!(object instanceof Algorithm)) {
+					System.out.println("Class does not implement CpsAlgorithm!");
+				}else {
+					actual = (Algorithm)object;
+					actual.setController(control);
+					this.setContentPane(actual.getAlgorithmPanel());
+					this.pack();
+				}
+				} catch (MalformedURLException e) {
+					System.out.println("URLClassLoader error");
+					e.printStackTrace();
+				} catch (ClassNotFoundException e) {
+					System.out.println("ClassNotFound error" + e.getMessage());
+				} catch (InstantiationException e) {
+					// TODO Auto-generated catch block
+					e.printStackTrace();
+				} catch (IllegalAccessException e) {
+					// TODO Auto-generated catch block
+					e.printStackTrace();
+				}
+			}else {
+				//Not
+			}
+				
+			
+		});
+		menuSelect.add(menuItemAlgorithm);
+		menuItemFolder.addActionListener(actionEvent->openFolder(menuSelect));
+		menuSelect.add(menuItemFolder);
+		menuSelect.addSeparator();
+		JMenu menuHelp = new JMenu("Help");
+		menuBar.add(menuSelect);
+		menuBar.add(menuHelp);
+		this.setJMenuBar(menuBar);
+	}
+	private void initDefaultContentPanel() {
+		content.setLayout(new BorderLayout());
+		JTextPane textPane = new JTextPane();
+		SimpleAttributeSet attribs = new SimpleAttributeSet();  
+		StyleConstants.setAlignment(attribs , StyleConstants.ALIGN_JUSTIFIED);
+		textPane.setParagraphAttributes(attribs, true);
+		textPane.setText("No algorithm is loaded."
+				+"\n OPTION[1]:"
+				+"\n•  Select '.java'-file via the file browser. (File\u2192Open .jave-File..)"
+				+"\n"
+				+"\n OPTION[2]: CURRENTLY NOT WORKING"
+				+"\n• First select the folder where the algorithm '.java'-file is located. (File\u2192Open Folder..)"
+				+"\n• Second load the algorithm. (File\u2192'YourAlgo')");
+		textPane.setFont(new Font("Serif", Font.PLAIN, 16));
+		
+		
+		content.add(textPane, BorderLayout.CENTER);
+		//content.add(new JButton("Run"),BorderLayout.PAGE_END );
+		content.setPreferredSize(new Dimension(500, 500));
+	}
+	
+	private void openFolder(JMenu menuSelect) {
+		System.out.println("OpenFolder");
+		JFileChooser fileChooser = new JFileChooser();
+		fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
+		fileChooser.setAcceptAllFileFilterUsed(false);
+		int result = fileChooser.showOpenDialog(this);
+		if(result == JFileChooser.APPROVE_OPTION) {
+			System.out.println("Richtig" + menuSelect.getItemCount());
+			System.out.println(fileChooser.getSelectedFile().getAbsolutePath());
+			root = fileChooser.getSelectedFile();
+			File[] files = fileChooser.getSelectedFile().listFiles(file -> file.getName().endsWith(".java"));
+			
+			//Remove all Index from old Folder
+			for(int i= menuSelect.getItemCount()-1; i> 2; i--) {
+				menuSelect.remove(i);
+			}
+			for(File file: files) {
+				menuSelect.add(new JMenuItem(file.getName().substring(0, file.getName().lastIndexOf("."))));
+			}
+			//System.out.println(Arrays.asList(files).stream().map(Object::toString).collect(Collectors.joining(", ")));
+		}else {
+			System.out.println("Falsch");
+		}
+			
+		//
+	}
+}

+ 0 - 1
src/ui/view/AlgorithmMenu.java

@@ -25,7 +25,6 @@ import java.util.HashMap;
 public class AlgorithmMenu extends JMenu {
 
 	private static final long serialVersionUID = 1L;
-
 	JMenuItem algoFolderButton = new JMenuItem("Select Algorithm Folder");
 	// root Directory
 	File root = null;

+ 23 - 8
src/ui/view/GUI.java

@@ -68,6 +68,7 @@ public class GUI implements CategoryListener {
 	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");
 	private final AlgorithmMenu algorithmMenu;
 	
 	/** Help Menu containing helpful Informations and the AboutUs Popup */
@@ -117,7 +118,6 @@ public class GUI implements CategoryListener {
 	private final JMenuItem mntmSave = new JMenuItem("Save");
 	private final JMenuItem mntmCanvasSize = new JMenuItem("Set View Size");
 	private final JMenuItem mntmBackground = new JMenuItem("Background Image");
-	private final JMenuItem mntmOutLiner = new JMenuItem("Outliner");
 	private final JMenuItem mntmSplitView = new JMenuItem("Split View");
 	private final JSplitPane splitPane = new JSplitPane();
 	private final JSplitPane splitPane1 = new JSplitPane();
@@ -860,7 +860,7 @@ public class GUI implements CategoryListener {
 					frmCyberPhysical);
 			popUp.setVisible(true);
 		});
-
+		
 		mnNewMenuView.add(splitPane3);
 
 		sizeSlider.setMinimum(15);
@@ -913,8 +913,7 @@ public class GUI implements CategoryListener {
 		showTooltipsCheckBox.addActionListener(arg0 -> {
 			showHint(showTooltipsCheckBox.isSelected());
 			});
-		
-
+		initWindowMenu();
 		// Split View
 		mntmSplitView
 				.addActionListener(actionEvent -> {
@@ -947,10 +946,6 @@ public class GUI implements CategoryListener {
 				});
 		
 		
-		mnNewMenuView.add(mntmOutLiner);
-		mntmOutLiner.addActionListener(actienEvent -> {
-			outlinerList.add(new Outliner(frmCyberPhysical, model, controller, this, outlinerList));
-		});
 		
 		
 		mnNewMenuView.add(mntmBackground);
@@ -2516,6 +2511,26 @@ public class GUI implements CategoryListener {
 		});
 	}
 
+	private void initWindowMenu() {
+		menuBar.add(menuWindow);
+		//Algo
+		JMenuItem openMenu =  new JMenuItem("Open Algorithm Panel", new ImageIcon(Util.loadImage("/Button_Images/iconAlgo.png").getScaledInstance(20, 20, java.awt.Image.SCALE_SMOOTH)));
+		openMenu.addActionListener(actionEvent -> {
+			System.out.println("sdfsdf");
+			new AlgoWindow(frmCyberPhysical, controller);
+		});
+		openMenu.setAccelerator(KeyStroke.getKeyStroke('N', Toolkit.getDefaultToolkit ().getMenuShortcutKeyMask()));
+		menuWindow.add(openMenu);
+		//Outliner
+		JMenuItem openOutliner =  new JMenuItem("Open Outliner", new ImageIcon(Util.loadImage("/Button_Images/iconOutliner.png").getScaledInstance(20, 20, java.awt.Image.SCALE_SMOOTH)));
+		openOutliner.addActionListener(actionEvent -> {
+			outlinerList.add(new Outliner(frmCyberPhysical, model, controller));
+		});
+		openOutliner.setAccelerator(KeyStroke.getKeyStroke('O', Toolkit.getDefaultToolkit ().getMenuShortcutKeyMask()));
+		menuWindow.add(openOutliner);
+	}
+
+
 	public void updateOutliners(DecoratedState state)
 	{
 		//remove closed Outliner

+ 1 - 1
src/ui/view/Outliner.java

@@ -46,7 +46,7 @@ public class Outliner extends JFrame {
 	JPanel statePanel = new JPanel(new BorderLayout());
 	public boolean isClosed = false;
 	ArrayList<MinimumNetwork> list;
-	Outliner(JFrame parentFrame, Model model, Control controller, GUI gui, List<Outliner> outlinerList){ 
+	Outliner(JFrame parentFrame, Model model, Control controller){ 
 		setBounds(0, 0, 400, parentFrame.getHeight());
 		this.setIconImage(Util.loadImage("/Images/Holeg.png", 30, 30));
 		this.setTitle("Outliner");