Control.java 18 KB

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