Randomizer.java 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  1. package addOns;
  2. import java.awt.BorderLayout;
  3. import java.awt.Dimension;
  4. import java.io.File;
  5. import java.io.FileNotFoundException;
  6. import java.io.FileReader;
  7. import java.text.NumberFormat;
  8. import java.util.ArrayList;
  9. import java.util.Comparator;
  10. import java.util.HashMap;
  11. import java.util.Hashtable;
  12. import java.util.List;
  13. import java.util.stream.Collectors;
  14. import javax.swing.BorderFactory;
  15. import javax.swing.Box;
  16. import javax.swing.BoxLayout;
  17. import javax.swing.ImageIcon;
  18. import javax.swing.JButton;
  19. import javax.swing.JCheckBox;
  20. import javax.swing.JFileChooser;
  21. import javax.swing.JFormattedTextField;
  22. import javax.swing.JFrame;
  23. import javax.swing.JLabel;
  24. import javax.swing.JPanel;
  25. import javax.swing.JScrollPane;
  26. import javax.swing.JSlider;
  27. import javax.swing.JSplitPane;
  28. import javax.swing.filechooser.FileNameExtensionFilter;
  29. import javax.swing.text.NumberFormatter;
  30. import com.google.gson.Gson;
  31. import com.google.gson.JsonArray;
  32. import com.google.gson.JsonElement;
  33. import com.google.gson.JsonIOException;
  34. import com.google.gson.JsonParser;
  35. import com.google.gson.JsonSyntaxException;
  36. import com.google.gson.annotations.Expose;
  37. import com.google.gson.annotations.SerializedName;
  38. import addOns.JSON.HolonElementSketch;
  39. import api.AddOn;
  40. import classes.AbstractCanvasObject;
  41. import classes.Constrain;
  42. import classes.GroupNode;
  43. import classes.Flexibility;
  44. import classes.HolonElement;
  45. import classes.HolonElement.Priority;
  46. import classes.HolonObject;
  47. import classes.HolonSwitch;
  48. import ui.controller.Control;
  49. import ui.model.Model;
  50. import ui.view.RandomPriotity;
  51. import utility.Random;
  52. import utility.Util;
  53. public class Randomizer implements AddOn {
  54. private Control control;
  55. private int minAmountOfElements = 3;
  56. private int maxAmountOfElements = 7;
  57. private JPanel content = new JPanel();
  58. private JPanel tablePanel = new JPanel();
  59. private RandomPriotity prioPanel = new RandomPriotity();
  60. private JCheckBox priorityCheckbox = new JCheckBox("Random");
  61. private boolean useRandomPriority = true;
  62. //To Test the Layout Faster
  63. public static void main(String[] args)
  64. {
  65. JFrame newFrame = new JFrame("exampleWindow");
  66. Randomizer instance = new Randomizer();
  67. newFrame.setContentPane(instance.getPanel());
  68. newFrame.pack();
  69. newFrame.setVisible(true);
  70. newFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  71. }
  72. private File file;
  73. public double randomChance = 1.0;
  74. private HashMap<HolonObject, Boolean> objectMap = new HashMap<HolonObject, Boolean>();
  75. private List<JCheckBox> checkboxList = new ArrayList<JCheckBox>();
  76. public Randomizer(){
  77. for(int i = 0; i < 30; i++) {
  78. objectMap.put(new HolonObject("dude"), true);
  79. }
  80. content.setLayout(new BorderLayout());
  81. JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, createParameterPanel(), createFilterPanel());
  82. splitPane.setDividerLocation(0.5);
  83. content.add(splitPane, BorderLayout.CENTER);
  84. JButton buttonRun = new JButton("Run");
  85. buttonRun.addActionListener(actionEvent -> run());
  86. content.add(buttonRun, BorderLayout.PAGE_END);
  87. }
  88. private JScrollPane createFilterPanel() {
  89. //Table
  90. tablePanel.setLayout(new BoxLayout(tablePanel, BoxLayout.PAGE_AXIS));
  91. JScrollPane scrollPanel = new JScrollPane(tablePanel);
  92. scrollPanel.setPreferredSize(new Dimension(300,300));
  93. fillTablePanel();
  94. return scrollPanel;
  95. }
  96. private void fillTablePanel() {
  97. //Clear old Data
  98. tablePanel.removeAll();
  99. checkboxList.clear();
  100. //HeadPanel
  101. JPanel headPanel = new JPanel();
  102. headPanel.setLayout(new BoxLayout(headPanel, BoxLayout.LINE_AXIS));
  103. headPanel.add(new JLabel("FILTER"));
  104. headPanel.add(Box.createHorizontalGlue());
  105. headPanel.add(new JLabel("SelectAll"));
  106. JCheckBox selectAllCheckbox = new JCheckBox();
  107. selectAllCheckbox.setSelected(true);
  108. selectAllCheckbox.addItemListener(input -> checkboxList.forEach(box -> box.setSelected(selectAllCheckbox.isSelected())));
  109. headPanel.add(selectAllCheckbox);
  110. tablePanel.add(headPanel);
  111. //Entrys
  112. int lineSpace = 20;
  113. for(HolonObject hObject: objectMap.keySet().stream().sorted(Comparator.comparing(ob -> ob.getName())).collect(Collectors.toList())) {
  114. //Entry
  115. JPanel entryPanel = new JPanel();
  116. entryPanel.setLayout(new BoxLayout(entryPanel, BoxLayout.LINE_AXIS));
  117. JLabel label = new JLabel(hObject.getName() + "[" + hObject.getId() + "]", new ImageIcon(Util.loadImage(hObject.getImage(), lineSpace, lineSpace)), JLabel.LEFT);
  118. entryPanel.add(label);
  119. entryPanel.add(Box.createHorizontalGlue());
  120. JCheckBox checkbox = new JCheckBox();
  121. checkbox.setSelected(true);
  122. checkbox.addItemListener(change -> {
  123. objectMap.put(hObject, checkbox.isSelected());
  124. System.out.println("hObject:" + hObject + " changed to " + checkbox.isSelected());
  125. });
  126. checkboxList.add(checkbox);
  127. entryPanel.add(checkbox);
  128. tablePanel.add(entryPanel);
  129. }
  130. }
  131. private JSplitPane createParameterPanel() {
  132. JPanel choosePanel = new JPanel(null);
  133. choosePanel.setPreferredSize(new Dimension(300,200));
  134. choosePanel.setMinimumSize(new Dimension(300,200));
  135. JLabel minAmount = new JLabel("minAmountOfElements:");
  136. minAmount.setBounds(20, 60 , 200, 20);
  137. choosePanel.add(minAmount);
  138. JLabel maxAmount = new JLabel("maxAmountOfElements:");
  139. maxAmount.setBounds(20, 85 , 200, 20);
  140. choosePanel.add(maxAmount);
  141. //Integer formatter
  142. NumberFormat format = NumberFormat.getIntegerInstance();
  143. format.setGroupingUsed(false);
  144. format.setParseIntegerOnly(true);
  145. NumberFormatter integerFormatter = new NumberFormatter(format);
  146. integerFormatter.setMinimum(0);
  147. integerFormatter.setCommitsOnValidEdit(true);
  148. JFormattedTextField minAmountTextField = new JFormattedTextField(integerFormatter);
  149. minAmountTextField.setValue(this.minAmountOfElements);
  150. minAmountTextField.setToolTipText("Only positive Integer.");
  151. minAmountTextField.addPropertyChangeListener(actionEvent -> this.minAmountOfElements = Integer.parseInt(minAmountTextField.getValue().toString()));
  152. minAmountTextField.setBounds(220, 60, 50, 20);
  153. choosePanel.add(minAmountTextField);
  154. JFormattedTextField maxAmountTextField = new JFormattedTextField(integerFormatter);
  155. maxAmountTextField.setValue(this.maxAmountOfElements);
  156. maxAmountTextField.setToolTipText("Only positive Integer.");
  157. maxAmountTextField.addPropertyChangeListener(actionEvent -> this.maxAmountOfElements = Integer.parseInt(maxAmountTextField.getValue().toString()));
  158. maxAmountTextField.setBounds(220, 85, 50, 20);
  159. choosePanel.add(maxAmountTextField);
  160. JButton chooseFileButton = new JButton("Choose File");
  161. chooseFileButton.setBounds(20, 10, 200, 30);
  162. chooseFileButton.addActionListener(actionEvent -> file = openCatalogFile());
  163. choosePanel.add(chooseFileButton);
  164. JSlider bitSlider = createFlipChanceSlider();
  165. bitSlider.setBounds(10, 110, 280, 80);
  166. choosePanel.add(bitSlider);
  167. JPanel prioritySelectionPanel = new JPanel();
  168. prioritySelectionPanel.setLayout(new BoxLayout(prioritySelectionPanel, BoxLayout.PAGE_AXIS));
  169. //priorityCheckbox.setAlignmentY(0.0f);
  170. //selection
  171. prioritySelectionPanel.add(this.priorityCheckbox);
  172. priorityCheckbox.addItemListener(change -> {
  173. prioPanel.setEnabled(priorityCheckbox.isSelected());
  174. useRandomPriority = priorityCheckbox.isSelected();
  175. });
  176. priorityCheckbox.setSelected(useRandomPriority);
  177. prioritySelectionPanel.add(prioPanel);
  178. JSplitPane parameterPanel = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, choosePanel, prioritySelectionPanel);
  179. parameterPanel.setPreferredSize(new Dimension(600,200));
  180. return parameterPanel;
  181. }
  182. private void run() {
  183. List<HolonElementSketch> holonElementCatalog = new ArrayList<HolonElementSketch>();
  184. if(file == null)file = openCatalogFile();
  185. if(file == null) return;
  186. readCatalogFromJson(file, holonElementCatalog);
  187. holonElementCatalog.forEach(con -> con.checkValues());
  188. objectMap.forEach((hObject, state) ->{
  189. //Ignore Filtered objects
  190. System.out.println("hObject:" + hObject + " state:" + state);
  191. if(!state) {
  192. return;
  193. }
  194. //Randomize
  195. hObject.getElements().clear();
  196. int randomAmountOfElementsToAdd = Random.nextIntegerInRange(minAmountOfElements, maxAmountOfElements + 1);
  197. for(int i = 0; i < randomAmountOfElementsToAdd; i++) {
  198. HolonElement ele = holonElementCatalog.get(Random.nextIntegerInRange(0, holonElementCatalog.size())).createHolonElement(control.getModel(), Random.nextDouble() < randomChance , hObject.getName());
  199. if(this.useRandomPriority) ele.setPriority(prioPanel.getPriority());
  200. hObject.getElements().add(ele);
  201. }
  202. });
  203. control.calculateStateAndVisualForCurrentTimeStep();
  204. control.updateCanvas();
  205. }
  206. private void fillObjectMap(List<AbstractCanvasObject> nodes) {
  207. for (AbstractCanvasObject aCps : nodes) {
  208. if (aCps instanceof HolonObject) {
  209. HolonObject hO = (HolonObject) aCps;
  210. objectMap.put(hO, true);
  211. }
  212. else if(aCps instanceof GroupNode) {
  213. fillObjectMap(((GroupNode)aCps).getNodes());
  214. }
  215. }
  216. }
  217. public void updateFilterList() {
  218. objectMap.clear();
  219. fillObjectMap(control.getModel().getObjectsOnCanvas());
  220. this.fillTablePanel();
  221. }
  222. @Override
  223. public JPanel getPanel() {
  224. return content;
  225. }
  226. @Override
  227. public void setController(Control control) {
  228. this.control = control;
  229. //Update Filter List
  230. updateFilterList();
  231. }
  232. private JSlider createFlipChanceSlider() {
  233. JSlider flipChance =new JSlider(JSlider.HORIZONTAL,0, 100, 100);
  234. flipChance.setBorder(BorderFactory.createTitledBorder("ActiveProbability"));
  235. flipChance.setMajorTickSpacing(50);
  236. flipChance.setMinorTickSpacing(5);
  237. flipChance.setPaintTicks(true);
  238. Hashtable<Integer, JLabel> labelTable = new Hashtable<Integer, JLabel>();
  239. labelTable.put( Integer.valueOf(0), new JLabel("0.0") );
  240. labelTable.put( Integer.valueOf(50), new JLabel("0.5") );
  241. labelTable.put( Integer.valueOf(100), new JLabel("1.0") );
  242. flipChance.setToolTipText("" +randomChance);
  243. flipChance.addChangeListener(actionEvent ->{
  244. randomChance =(double)flipChance.getValue()/100.0;
  245. flipChance.setToolTipText("" +randomChance);
  246. });
  247. flipChance.setLabelTable( labelTable );
  248. flipChance.setPaintLabels(true);
  249. return flipChance;
  250. }
  251. private void readCatalogFromJson(File file, List<HolonElementSketch> catalog) {
  252. Gson gson = new Gson();
  253. JsonParser parser = new JsonParser();
  254. try {
  255. JsonElement jsonTreeRoot = parser.parse(new FileReader(file));
  256. if(jsonTreeRoot.isJsonArray()) {
  257. JsonArray jsonArray = jsonTreeRoot.getAsJsonArray();
  258. jsonArray.forEach(jsonObject -> {
  259. HolonElementSketch newObject= gson.fromJson( jsonObject, HolonElementSketch.class);
  260. System.out.println(gson.toJson(newObject));
  261. catalog.add(newObject);
  262. });
  263. }
  264. } catch (JsonSyntaxException e) {
  265. e.printStackTrace();
  266. } catch (JsonIOException e) {
  267. e.printStackTrace();
  268. } catch (FileNotFoundException e) {
  269. e.printStackTrace();
  270. }
  271. }
  272. public File openCatalogFile() {
  273. JFileChooser fileChooser = new JFileChooser();
  274. fileChooser.setCurrentDirectory(new File(System.getProperty("user.dir")+"/randomizerConfigFiles/"));
  275. fileChooser.setFileFilter(new FileNameExtensionFilter("JSON Files", "json"));
  276. fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
  277. fileChooser.setAcceptAllFileFilterUsed(false);
  278. int result = fileChooser.showOpenDialog(content);
  279. if(result == JFileChooser.APPROVE_OPTION) {
  280. //Found a file
  281. return fileChooser.getSelectedFile();
  282. }
  283. return null;
  284. }
  285. }