Control.java 16 KB

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