Control.java 16 KB

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