Control.java 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600
  1. package holeg.ui.controller;
  2. import java.awt.Point;
  3. import java.awt.datatransfer.UnsupportedFlavorException;
  4. import java.io.File;
  5. import java.io.IOException;
  6. import java.util.ArrayList;
  7. import java.util.Collection;
  8. import java.util.HashSet;
  9. import java.util.List;
  10. import java.util.Optional;
  11. import java.util.Set;
  12. import java.util.logging.Logger;
  13. import java.util.stream.Collectors;
  14. import javax.swing.JFrame;
  15. import org.apache.commons.compress.archivers.ArchiveException;
  16. import com.google.gson.JsonParseException;
  17. import holeg.model.AbstractCanvasObject;
  18. import holeg.model.Edge;
  19. import holeg.model.GroupNode;
  20. import holeg.model.HolonElement;
  21. import holeg.model.HolonObject;
  22. import holeg.model.Node;
  23. import holeg.ui.model.GuiSettings;
  24. import holeg.ui.model.Model;
  25. import holeg.ui.view.dialog.CreateTemplatePopUp;
  26. import holeg.ui.view.main.Category;
  27. import holeg.ui.view.main.GUI;
  28. import holeg.utility.events.Action;
  29. import holeg.utility.events.Event;
  30. /**
  31. * The Class represents the controller in the model, controller view Pattern.
  32. *
  33. * @author Gruppe14
  34. */
  35. public class Control {
  36. private static final Logger log = Logger.getLogger(Control.class.getName());
  37. private final CategoryController categoryController;
  38. private final CanvasController canvasController;
  39. private final SaveController saveController;
  40. private final LoadController loadController;
  41. private final AutoSaveController autoSaveController;
  42. private final NodeController nodeController;
  43. private final ClipboardController clipboardController;
  44. private Model model;
  45. private SimulationManager simulationManager;
  46. private String autosaveDir = "";
  47. private String categoryDir = "";
  48. private String otherDir = "";
  49. private String dimensionsFileName = "dimensions";
  50. private int rand;
  51. public Event OnCategoryChanged = new Event();
  52. public Event OnSelectionChanged = new Event();
  53. public Event OnCanvasUpdate = new Event();
  54. public Action<Boolean> OnGuiSetEnabled = new Action<>();
  55. /**
  56. * Constructor.
  57. *
  58. * @param model the Model
  59. */
  60. public Control(Model model) {
  61. this.model = model;
  62. this.categoryController = new CategoryController(this);
  63. this.canvasController = new CanvasController(model);
  64. this.saveController = new SaveController(model);
  65. this.nodeController = new NodeController(model, canvasController);
  66. this.loadController = new LoadController(model, categoryController, canvasController,
  67. nodeController);
  68. this.simulationManager = new SimulationManager(model);
  69. this.autoSaveController = new AutoSaveController();
  70. this.clipboardController = new ClipboardController(model, saveController, loadController, canvasController,
  71. nodeController, this.simulationManager);
  72. autosaveDir = System.getProperty("user.home") + "/.config/HolonGUI/Autosave/";
  73. categoryDir = System.getProperty("user.home") + "/.config/HolonGUI/Category/";
  74. otherDir = System.getProperty("user.home") + "/.config/HolonGUI/Other/";
  75. File autoSave = new File(autosaveDir);
  76. File category = new File(categoryDir);
  77. File other = new File(otherDir);
  78. // deleteDirectory(dest);
  79. autoSave.mkdirs();
  80. category.mkdirs();
  81. other.mkdirs();
  82. createAutoRandom();
  83. tryAutoSave();
  84. }
  85. /**
  86. * Generate random number, so that every instance of the program has unique save
  87. * files
  88. */
  89. private void createAutoRandom() {
  90. rand = (int) (Math.random() * 1000);
  91. while (new File(autosaveDir + rand + (GuiSettings.autoSaveNr)).exists()) {
  92. rand = (int) Math.random() * 1000;
  93. }
  94. }
  95. /**
  96. * Delete a Directory.
  97. *
  98. * @param path to delete
  99. */
  100. public void deleteDirectory(File path) {
  101. if (path.exists()) {
  102. File[] files = path.listFiles();
  103. for (File file : files) {
  104. if (file.isDirectory()) {
  105. deleteDirectory(file);
  106. } else {
  107. if (file.getName().contains("" + rand))
  108. file.delete();
  109. }
  110. }
  111. // path.delete();
  112. }
  113. }
  114. public Optional<Category> findCategoryWithName(String name){
  115. return GuiSettings.getCategories().stream().filter(cat -> cat.getName().equals(name)).findAny();
  116. }
  117. /* Operations for Categories and Objects */
  118. /**
  119. * init default category and objects.
  120. */
  121. public void resetCategories() {
  122. categoryController.clearCategories();
  123. categoryController.initCategories();
  124. saveCategory();
  125. }
  126. /**
  127. * Adds New Category into Model.
  128. *
  129. * @param cat name of the new Category
  130. * @throws IOException
  131. */
  132. public void createCategoryWithName(String cat) {
  133. categoryController.createCategoryWithName(cat);
  134. saveCategory();
  135. }
  136. /**
  137. * Gives all Category as String
  138. *
  139. * @return a array of strings from all Categorys
  140. */
  141. public String[] getCategoriesStrings() {
  142. return GuiSettings.getCategories().stream().map(c -> c.getName()).collect(Collectors.toList())
  143. .toArray(new String[GuiSettings.getCategories().size()]);
  144. }
  145. /**
  146. * Add new Holon Object to a Category.
  147. *
  148. * @param cat Category
  149. * @param obj New Object Name
  150. * @param list Array of Elements
  151. * @param img the image Path
  152. * @throws IOException
  153. */
  154. public void addObject(Category cat, String obj, List<HolonElement> list, String img){
  155. categoryController.addNewHolonObject(cat, obj, list, img);
  156. saveCategory();
  157. }
  158. /**
  159. * Add new Holon Switch to a Category.
  160. *
  161. * @param cat Category
  162. * @param obj New Object Name
  163. * @throws IOException
  164. */
  165. public void addSwitch(Category cat, String obj) {
  166. categoryController.addNewHolonSwitch(cat, obj);
  167. saveCategory();
  168. }
  169. public void deleteCategory(Category category) {
  170. categoryController.removeCategory(category);
  171. saveCategory();
  172. }
  173. /**
  174. * removes a selectedObject from selection.
  175. *
  176. */
  177. public void removeObjectsFromSelection(Collection<AbstractCanvasObject> objects) {
  178. if(GuiSettings.getSelectedObjects().removeAll(objects)){
  179. OnSelectionChanged.broadcast();
  180. }
  181. }
  182. /**
  183. * removes a selectedObject from selection.
  184. *
  185. * @param obj Cpsobject
  186. */
  187. public void removeObjectFromSelection(AbstractCanvasObject obj) {
  188. if(GuiSettings.getSelectedObjects().remove(obj)){
  189. OnSelectionChanged.broadcast();
  190. }
  191. }
  192. /**
  193. * add an Object to selectedObject.
  194. *
  195. * @param obj AbstractCpsobject
  196. */
  197. public void addSelectedObject(AbstractCanvasObject obj) {
  198. if(GuiSettings.getSelectedObjects().add(obj)){
  199. OnSelectionChanged.broadcast();
  200. }
  201. }
  202. public void addSelectedObjects(Collection<AbstractCanvasObject> objects) {
  203. if(GuiSettings.getSelectedObjects().addAll(objects)){
  204. OnSelectionChanged.broadcast();
  205. }
  206. }
  207. public void clearSelection() {
  208. if (!GuiSettings.getSelectedObjects().isEmpty()) {
  209. GuiSettings.getSelectedObjects().clear();
  210. OnSelectionChanged.broadcast();
  211. }
  212. }
  213. /**
  214. * This method is primarily for the multi-selection. It adds unselected objects
  215. * to the selection and Removes selected objects from the selection. Like the
  216. * normal OS Desktop selection.
  217. *
  218. * @param objects
  219. */
  220. public void toggleSelectedObjects(Collection<AbstractCanvasObject> objects) {
  221. Set<AbstractCanvasObject> intersection = new HashSet<>(objects);
  222. intersection.retainAll(GuiSettings.getSelectedObjects());
  223. GuiSettings.getSelectedObjects().addAll(objects);
  224. GuiSettings.getSelectedObjects().removeAll(intersection);
  225. OnSelectionChanged.broadcast();
  226. }
  227. /* Operations for Canvas */
  228. /**
  229. * Add a new Object.
  230. *
  231. * @param object the Object
  232. */
  233. public void addObjectCanvas(AbstractCanvasObject object) {
  234. canvasController.addNewObject(object);
  235. calculateStateAndVisualForTimeStep(model.getCurrentIteration());
  236. if (!(object instanceof Node)) {
  237. tryAutoSave();
  238. }
  239. }
  240. /**
  241. * Deletes an CpsObject on the Canvas and its connections.
  242. *
  243. * @param obj AbstractCpsObject
  244. * @param save
  245. */
  246. public void delCanvasObject(AbstractCanvasObject obj, boolean save) {
  247. canvasController.deleteObjectOnCanvas(obj);
  248. if (obj instanceof GroupNode groupnode) {
  249. canvasController.deleteAllObjectsInGroupNode(groupnode);
  250. }
  251. calculateStateAndVisualForCurrentTimeStep();
  252. if (save) {
  253. tryAutoSave();
  254. }
  255. }
  256. public void delCanvasObjects(Collection<AbstractCanvasObject> objects) {
  257. canvasController.deleteObjectsOnCanvas(objects);
  258. calculateStateAndVisualForCurrentTimeStep();
  259. tryAutoSave();
  260. }
  261. /**
  262. * Replaces {@code toBeReplaced} by {@code by} on the canvas
  263. *
  264. * @param toBeReplaced the object that will be replaced
  265. * @param by the object that will replace it
  266. */
  267. public void replaceCanvasObject(AbstractCanvasObject toBeReplaced, AbstractCanvasObject by) {
  268. canvasController.replaceObjectOnCanvas(toBeReplaced, by);
  269. tryAutoSave();
  270. }
  271. /**
  272. * Add an edge to the Canvas.
  273. *
  274. * @param edge the edge
  275. */
  276. public void addEdgeOnCanvas(Edge edge) {
  277. canvasController.addEdgeOnCanvas(edge);
  278. tryAutoSave();
  279. }
  280. /**
  281. * Removes an Edge from the Canvas.
  282. *
  283. * @param edge the edge to remove
  284. */
  285. public void removeEdgesOnCanvas(Edge edge) {
  286. canvasController.removeEdgesOnCanvas(edge);
  287. tryAutoSave();
  288. }
  289. /**
  290. * Writes the current State of the Modelling into a JSON File which can be
  291. * loaded.
  292. *
  293. * @param path the Path
  294. * @throws IOException exception
  295. */
  296. public void saveFile(String path) throws IOException, ArchiveException {
  297. saveController.writeSave(path);
  298. }
  299. /**
  300. * Reads the the Save File and load the state into the Model.
  301. *
  302. * @param path the Path
  303. * @throws IOException exception
  304. * @throws ArchiveException
  305. */
  306. public void loadFile(String path) throws IOException, ArchiveException {
  307. loadController.readSave(path);
  308. saveCategory();
  309. autoSave();
  310. }
  311. /**
  312. * Reads the Json File from Autosave
  313. *
  314. * @param path
  315. * @throws IOException
  316. */
  317. public void loadAutoSave(String path) throws IOException {
  318. loadController.readJson(path);
  319. }
  320. public ArrayList<Integer> loadSavedWindowDimensionsIfExistent() {
  321. try {
  322. return loadController.readWindowDimensions(otherDir + dimensionsFileName);
  323. } catch (Exception e) {
  324. return new ArrayList<>();
  325. }
  326. }
  327. /**
  328. * calculates the flow of the edges and the supply for objects for the current
  329. * Timestep.
  330. */
  331. public void calculateStateAndVisualForCurrentTimeStep() {
  332. calculateStateAndVisualForTimeStep(model.getCurrentIteration());
  333. }
  334. public void calculateStateOnlyForCurrentTimeStep() {
  335. simulationManager.calculateStateForTimeStep(model.getCurrentIteration());
  336. }
  337. /**
  338. * calculates the flow of the edges and the supply for objects.
  339. *
  340. * @param x current Iteration
  341. */
  342. public void calculateStateAndVisualForTimeStep(int x) {
  343. simulationManager.calculateStateForTimeStep(x);
  344. OnCanvasUpdate.broadcast();
  345. }
  346. /**
  347. * resets the whole State of the simulation including a reset of all Edges to
  348. * the default "is working" state
  349. */
  350. public void resetSimulation() {
  351. model.reset();
  352. }
  353. /**
  354. * make an autosave.
  355. *
  356. * @throws IOException Exception
  357. */
  358. private void autoSave() throws IOException {
  359. autoSaveController.increaseAutoSaveNr();
  360. saveController.writeAutosave(autosaveDir + rand + GuiSettings.autoSaveNr);
  361. if (autoSaveController.allowed()) {
  362. new File(autosaveDir + rand + (GuiSettings.autoSaveNr - GuiSettings.numberOfSaves)).delete();
  363. }
  364. }
  365. public void tryAutoSave() {
  366. try {
  367. autoSave();
  368. } catch (IOException e) {
  369. log.warning(e.getStackTrace().toString());
  370. }
  371. }
  372. /**
  373. * find all old auto save files (with a file-name, that does not contain the
  374. * current rand)
  375. *
  376. * @return a list of files, that are not from the current run
  377. */
  378. public ArrayList<File> filterOldAutoSaveFiles() {
  379. File[] files = new File(autosaveDir).listFiles();
  380. ArrayList<File> oldAutoSaves = new ArrayList<>();
  381. for (File file : files) {
  382. if (!file.getName().contains(String.valueOf(rand)))
  383. oldAutoSaves.add(file);
  384. }
  385. return oldAutoSaves;
  386. }
  387. /**
  388. * deletes the old autosave files
  389. */
  390. public void deleteObsoleteAutoSaveFiles() {
  391. for (File file : filterOldAutoSaveFiles()) {
  392. file.delete();
  393. }
  394. }
  395. public void saveCategory() {
  396. try {
  397. saveController.writeCategory(categoryDir + "Category.json");
  398. } catch (IOException e) {
  399. }
  400. }
  401. public void savePosAndSizeOfWindow(int x, int y, int width, int height) throws IOException, ArchiveException {
  402. saveController.writeWindowStatus(otherDir + dimensionsFileName, x, y, width, height);
  403. }
  404. /**
  405. * Returns the undo save.
  406. *
  407. * @return the undo save
  408. */
  409. public String getUndoSave() {
  410. autoSaveController.decreaseAutoSaveNr();
  411. if (!new File(autosaveDir + rand + (GuiSettings.autoSaveNr)).exists()) {
  412. autoSaveController.increaseAutoSaveNr();
  413. }
  414. return autosaveDir + rand + (GuiSettings.autoSaveNr);
  415. }
  416. /**
  417. * Returns the redo save.
  418. *
  419. * @return the redo save
  420. */
  421. public String getRedoSave() {
  422. autoSaveController.increaseAutoSaveNr();
  423. if (!new File(autosaveDir + rand + (GuiSettings.autoSaveNr)).exists()) {
  424. autoSaveController.decreaseAutoSaveNr();
  425. // if it still does not exist, try old autosaves
  426. if (!new File(autosaveDir + rand + (GuiSettings.autoSaveNr)).exists()) {
  427. ArrayList<File> oldAutoSaves = filterOldAutoSaveFiles();
  428. if (oldAutoSaves.size() > 0) {
  429. return autosaveDir + oldAutoSaves.get(oldAutoSaves.size() - 1).getName();
  430. }
  431. }
  432. }
  433. return autosaveDir + rand + (GuiSettings.autoSaveNr);
  434. }
  435. /**
  436. * Getter for Model.
  437. *
  438. * @return the Model
  439. */
  440. public Model getModel() {
  441. return model;
  442. }
  443. /**
  444. * get the Simulation Manager.
  445. *
  446. * @return the Simulation Manager
  447. */
  448. public SimulationManager getSimManager() {
  449. return simulationManager;
  450. }
  451. // ========================== MANAGING TRACKED OBJECTS END ================
  452. /**
  453. * Controlling GroupNodes
  454. */
  455. public void addGroupNode(String nodeName, GroupNode groupNode, List<AbstractCanvasObject> toGroup) {
  456. nodeController.addGroupNode(nodeName, groupNode, toGroup);
  457. tryAutoSave();
  458. }
  459. public void undoGroupNode(GroupNode node, GroupNode groupNode) {
  460. nodeController.undoGroupNode(node, groupNode);
  461. tryAutoSave();
  462. }
  463. public void addObjectInGroupNode(AbstractCanvasObject object, GroupNode groupNode) {
  464. nodeController.addObjectInGroupNode(object, groupNode, true);
  465. tryAutoSave();
  466. }
  467. public void deleteObjectInGroupNode(AbstractCanvasObject object, GroupNode groupNode) {
  468. nodeController.deleteObjectInGroupNode(object, groupNode);
  469. if (object instanceof GroupNode groupnode) {
  470. canvasController.deleteAllObjectsInGroupNode(groupnode);
  471. }
  472. tryAutoSave();
  473. }
  474. /**
  475. * Replaces {@code toBePlaced} by {@code by} in {@code upperNode}
  476. *
  477. * @param toBeReplaced
  478. * @param by
  479. * @param upperNode
  480. */
  481. public void replaceObjectInGroupNode(AbstractCanvasObject toBeReplaced, AbstractCanvasObject by, GroupNode upperNode) {
  482. nodeController.replaceObjectInUpperNode(toBeReplaced, by, upperNode);
  483. tryAutoSave();
  484. }
  485. /**
  486. * Copy all Selected Objects.
  487. */
  488. public void copy(GroupNode upperNode) {
  489. clipboardController.copy(upperNode);
  490. }
  491. public void paste(GroupNode upperNode, Point point)
  492. throws JsonParseException, UnsupportedFlavorException, IOException {
  493. clipboardController.paste(upperNode, point);
  494. OnSelectionChanged.broadcast();
  495. tryAutoSave();
  496. }
  497. public void cut(GroupNode upperNode) {
  498. clipboardController.cut(upperNode);
  499. OnSelectionChanged.broadcast();
  500. tryAutoSave();
  501. }
  502. /**
  503. * creates a new Template for the given cps Object
  504. *
  505. * @param cps Object, which should become a template
  506. * @param parentFrame
  507. */
  508. public void createTemplate(HolonObject cps, JFrame parentFrame) {
  509. CreateTemplatePopUp t = new CreateTemplatePopUp(cps, model, parentFrame, this);
  510. t.setVisible(true);
  511. }
  512. public void getObjectsInDepth() {
  513. clipboardController.getObjectsInDepth();
  514. }
  515. public void guiSetEnabled(boolean state) {
  516. log.info("guiDisabled");
  517. OnGuiSetEnabled.broadcast(state);
  518. }
  519. }