Control.java 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610
  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. /**
  170. * delete a given Category.
  171. *
  172. * @param cat the Category
  173. * @throws IOException
  174. */
  175. public void deleteCategory(Category category) {
  176. categoryController.removeCategory(category);
  177. saveCategory();
  178. }
  179. /**
  180. * removes a selectedObject from selection.
  181. *
  182. * @param obj Cpsobject
  183. */
  184. public void removeObjectsFromSelection(Collection<AbstractCanvasObject> objects) {
  185. for (AbstractCanvasObject obj : objects) {
  186. GuiSettings.getSelectedObjects().remove(obj);
  187. }
  188. OnSelectionChanged.broadcast();
  189. }
  190. /**
  191. * removes a selectedObject from selection.
  192. *
  193. * @param obj Cpsobject
  194. */
  195. public void removeObjectFromSelection(AbstractCanvasObject obj) {
  196. GuiSettings.getSelectedObjects().remove(obj);
  197. OnSelectionChanged.broadcast();
  198. }
  199. /**
  200. * add an Object to selectedObject.
  201. *
  202. * @param obj AbstractCpsobject
  203. */
  204. public void addSelectedObject(AbstractCanvasObject obj) {
  205. GuiSettings.getSelectedObjects().add(obj);
  206. OnSelectionChanged.broadcast();
  207. }
  208. public void addSelectedObjects(Collection<AbstractCanvasObject> objects) {
  209. GuiSettings.getSelectedObjects().addAll(objects);
  210. OnSelectionChanged.broadcast();
  211. }
  212. public void clearSelection() {
  213. if (!GuiSettings.getSelectedObjects().isEmpty()) {
  214. GuiSettings.getSelectedObjects().clear();
  215. OnSelectionChanged.broadcast();
  216. }
  217. }
  218. /**
  219. * This method is primarily for the multi-selection. It adds unselected objects
  220. * to the selection and Removes selected objects from the selection. Like the
  221. * normal OS Desktop selection.
  222. *
  223. * @param objects
  224. */
  225. public void toggleSelectedObjects(Collection<AbstractCanvasObject> objects) {
  226. Set<AbstractCanvasObject> intersection = new HashSet<>(objects);
  227. intersection.retainAll(GuiSettings.getSelectedObjects());
  228. GuiSettings.getSelectedObjects().addAll(objects);
  229. GuiSettings.getSelectedObjects().removeAll(intersection);
  230. OnSelectionChanged.broadcast();
  231. }
  232. /* Operations for Canvas */
  233. /**
  234. * Add a new Object.
  235. *
  236. * @param object the Object
  237. */
  238. public void addObjectCanvas(AbstractCanvasObject object) {
  239. canvasController.addNewObject(object);
  240. calculateStateAndVisualForTimeStep(model.getCurrentIteration());
  241. if (!(object instanceof Node)) {
  242. tryAutoSave();
  243. }
  244. }
  245. /**
  246. * Deletes an CpsObject on the Canvas and its connections.
  247. *
  248. * @param obj AbstractCpsObject
  249. * @param save
  250. */
  251. public void delCanvasObject(AbstractCanvasObject obj, boolean save) {
  252. canvasController.deleteObjectOnCanvas(obj);
  253. if (obj instanceof GroupNode groupnode) {
  254. canvasController.deleteAllObjectsInGroupNode(groupnode);
  255. }
  256. calculateStateAndVisualForCurrentTimeStep();
  257. if (save) {
  258. tryAutoSave();
  259. }
  260. }
  261. public void delCanvasObjects(Collection<AbstractCanvasObject> objects) {
  262. canvasController.deleteObjectsOnCanvas(objects);
  263. calculateStateAndVisualForCurrentTimeStep();
  264. tryAutoSave();
  265. }
  266. /**
  267. * Replaces {@code toBeReplaced} by {@code by} on the canvas
  268. *
  269. * @param toBeReplaced the object that will be replaced
  270. * @param by the object that will replace it
  271. */
  272. public void replaceCanvasObject(AbstractCanvasObject toBeReplaced, AbstractCanvasObject by) {
  273. canvasController.replaceObjectOnCanvas(toBeReplaced, by);
  274. tryAutoSave();
  275. }
  276. /**
  277. * Add an edge to the Canvas.
  278. *
  279. * @param edge the edge
  280. */
  281. public void addEdgeOnCanvas(Edge edge) {
  282. canvasController.addEdgeOnCanvas(edge);
  283. tryAutoSave();
  284. }
  285. /**
  286. * Removes an Edge from the Canvas.
  287. *
  288. * @param edge the edge to remove
  289. */
  290. public void removeEdgesOnCanvas(Edge edge) {
  291. canvasController.removeEdgesOnCanvas(edge);
  292. tryAutoSave();
  293. }
  294. /**
  295. * Writes the current State of the Modelling into a JSON File which can be
  296. * loaded.
  297. *
  298. * @param path the Path
  299. * @throws IOException exception
  300. */
  301. public void saveFile(String path) throws IOException, ArchiveException {
  302. saveController.writeSave(path);
  303. }
  304. /**
  305. * Reads the the Save File and load the state into the Model.
  306. *
  307. * @param path the Path
  308. * @throws IOException exception
  309. * @throws ArchiveException
  310. */
  311. public void loadFile(String path) throws IOException, ArchiveException {
  312. loadController.readSave(path);
  313. saveCategory();
  314. autoSave();
  315. }
  316. /**
  317. * Reads the Json File from Autosave
  318. *
  319. * @param path
  320. * @throws IOException
  321. */
  322. public void loadAutoSave(String path) throws IOException {
  323. loadController.readJson(path);
  324. }
  325. public ArrayList<Integer> loadSavedWindowDimensionsIfExistent() {
  326. try {
  327. return loadController.readWindowDimensions(otherDir + dimensionsFileName);
  328. } catch (Exception e) {
  329. return new ArrayList<>();
  330. }
  331. }
  332. /**
  333. * calculates the flow of the edges and the supply for objects for the current
  334. * Timestep.
  335. */
  336. public void calculateStateAndVisualForCurrentTimeStep() {
  337. calculateStateAndVisualForTimeStep(model.getCurrentIteration());
  338. }
  339. public void calculateStateOnlyForCurrentTimeStep() {
  340. simulationManager.calculateStateForTimeStep(model.getCurrentIteration(), false);
  341. }
  342. /**
  343. * calculates the flow of the edges and the supply for objects.
  344. *
  345. * @param x current Iteration
  346. */
  347. public void calculateStateAndVisualForTimeStep(int x) {
  348. simulationManager.calculateStateForTimeStep(x, true);
  349. OnCanvasUpdate.broadcast();
  350. // TODO(Tom2021-12-2): Convert to Events
  351. this.updateCanvas();
  352. }
  353. /**
  354. * resets the whole State of the simulation including a reset of all Edges to
  355. * the default "is working" state
  356. */
  357. public void resetSimulation() {
  358. model.reset();
  359. }
  360. /**
  361. * make an autosave.
  362. *
  363. * @throws IOException Exception
  364. */
  365. private void autoSave() throws IOException {
  366. autoSaveController.increaseAutoSaveNr();
  367. saveController.writeAutosave(autosaveDir + rand + GuiSettings.autoSaveNr);
  368. if (autoSaveController.allowed()) {
  369. new File(autosaveDir + rand + (GuiSettings.autoSaveNr - GuiSettings.numberOfSaves)).delete();
  370. }
  371. }
  372. public void tryAutoSave() {
  373. try {
  374. autoSave();
  375. } catch (IOException e) {
  376. log.warning(e.getStackTrace().toString());
  377. }
  378. }
  379. /**
  380. * find all old auto save files (with a file-name, that does not contain the
  381. * current rand)
  382. *
  383. * @return a list of files, that are not from the current run
  384. */
  385. public ArrayList<File> filterOldAutoSaveFiles() {
  386. File[] files = new File(autosaveDir).listFiles();
  387. ArrayList<File> oldAutoSaves = new ArrayList<>();
  388. for (File file : files) {
  389. if (!file.getName().contains(String.valueOf(rand)))
  390. oldAutoSaves.add(file);
  391. }
  392. return oldAutoSaves;
  393. }
  394. /**
  395. * deletes the old autosave files
  396. */
  397. public void deleteObsoleteAutoSaveFiles() {
  398. for (File file : filterOldAutoSaveFiles()) {
  399. file.delete();
  400. }
  401. }
  402. public void saveCategory() {
  403. try {
  404. saveController.writeCategory(categoryDir + "Category.json");
  405. } catch (IOException e) {
  406. }
  407. }
  408. public void savePosAndSizeOfWindow(int x, int y, int width, int height) throws IOException, ArchiveException {
  409. saveController.writeWindowStatus(otherDir + dimensionsFileName, x, y, width, height);
  410. }
  411. /**
  412. * Returns the undo save.
  413. *
  414. * @return the undo save
  415. */
  416. public String getUndoSave() {
  417. autoSaveController.decreaseAutoSaveNr();
  418. if (!new File(autosaveDir + rand + (GuiSettings.autoSaveNr)).exists()) {
  419. autoSaveController.increaseAutoSaveNr();
  420. }
  421. return autosaveDir + rand + (GuiSettings.autoSaveNr);
  422. }
  423. /**
  424. * Returns the redo save.
  425. *
  426. * @return the redo save
  427. */
  428. public String getRedoSave() {
  429. autoSaveController.increaseAutoSaveNr();
  430. if (!new File(autosaveDir + rand + (GuiSettings.autoSaveNr)).exists()) {
  431. autoSaveController.decreaseAutoSaveNr();
  432. // if it still does not exist, try old autosaves
  433. if (!new File(autosaveDir + rand + (GuiSettings.autoSaveNr)).exists()) {
  434. ArrayList<File> oldAutoSaves = filterOldAutoSaveFiles();
  435. if (oldAutoSaves.size() > 0) {
  436. return autosaveDir + oldAutoSaves.get(oldAutoSaves.size() - 1).getName();
  437. }
  438. }
  439. }
  440. return autosaveDir + rand + (GuiSettings.autoSaveNr);
  441. }
  442. /**
  443. * Getter for Model.
  444. *
  445. * @return the Model
  446. */
  447. public Model getModel() {
  448. return model;
  449. }
  450. /**
  451. * get the Simulation Manager.
  452. *
  453. * @return the Simulation Manager
  454. */
  455. public SimulationManager getSimManager() {
  456. return simulationManager;
  457. }
  458. // ========================== MANAGING TRACKED OBJECTS END ================
  459. /**
  460. * Controlling GroupNodes
  461. */
  462. public void addGroupNode(String nodeName, GroupNode groupNode, List<AbstractCanvasObject> toGroup) {
  463. nodeController.addGroupNode(nodeName, groupNode, toGroup);
  464. tryAutoSave();
  465. }
  466. public void undoGroupNode(GroupNode node, GroupNode groupNode) {
  467. nodeController.undoGroupNode(node, groupNode);
  468. tryAutoSave();
  469. }
  470. public void addObjectInGroupNode(AbstractCanvasObject object, GroupNode groupNode) {
  471. nodeController.addObjectInGroupNode(object, groupNode, true);
  472. tryAutoSave();
  473. }
  474. public void deleteObjectInGroupNode(AbstractCanvasObject object, GroupNode groupNode) {
  475. nodeController.deleteObjectInGroupNode(object, groupNode);
  476. if (object instanceof GroupNode groupnode) {
  477. canvasController.deleteAllObjectsInGroupNode(groupnode);
  478. }
  479. tryAutoSave();
  480. }
  481. /**
  482. * Replaces {@code toBePlaced} by {@code by} in {@code upperNode}
  483. *
  484. * @param toBeReplaced
  485. * @param by
  486. * @param upperNode
  487. */
  488. public void replaceObjectInGroupNode(AbstractCanvasObject toBeReplaced, AbstractCanvasObject by, GroupNode upperNode) {
  489. nodeController.replaceObjectInUpperNode(toBeReplaced, by, upperNode);
  490. tryAutoSave();
  491. }
  492. /**
  493. * Copy all Selected Objects.
  494. */
  495. public void copy(GroupNode upperNode) {
  496. clipboardController.copy(upperNode);
  497. }
  498. public void paste(GroupNode upperNode, Point point)
  499. throws JsonParseException, UnsupportedFlavorException, IOException {
  500. clipboardController.paste(upperNode, point);
  501. OnSelectionChanged.broadcast();
  502. tryAutoSave();
  503. }
  504. public void cut(GroupNode upperNode) {
  505. clipboardController.cut(upperNode);
  506. OnSelectionChanged.broadcast();
  507. tryAutoSave();
  508. }
  509. /**
  510. * creates a new Template for the given cps Object
  511. *
  512. * @param cps Object, which should become a template
  513. * @param parentFrame
  514. */
  515. public void createTemplate(HolonObject cps, JFrame parentFrame) {
  516. CreateTemplatePopUp t = new CreateTemplatePopUp(cps, model, parentFrame, this);
  517. t.setVisible(true);
  518. }
  519. public void getObjectsInDepth() {
  520. clipboardController.getObjectsInDepth();
  521. }
  522. public void updateCanvas() {
  523. log.info("updateCanvas");
  524. }
  525. public void guiSetEnabled(boolean state) {
  526. log.info("guiDisabled");
  527. OnGuiSetEnabled.broadcast(state);
  528. }
  529. }