Control.java 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486
  1. package holeg.ui.controller;
  2. import holeg.model.*;
  3. import holeg.preferences.ImagePreference;
  4. import holeg.ui.model.GuiSettings;
  5. import holeg.ui.model.IdCounter;
  6. import holeg.ui.view.category.Category;
  7. import holeg.ui.view.dialog.CreateTemplatePopUp;
  8. import holeg.utility.events.Action;
  9. import holeg.utility.events.Event;
  10. import holeg.utility.math.vector.Vec2i;
  11. import javax.swing.*;
  12. import java.io.File;
  13. import java.io.FileReader;
  14. import java.io.FileWriter;
  15. import java.io.IOException;
  16. import java.util.*;
  17. import java.util.logging.Logger;
  18. import java.util.stream.Collectors;
  19. import static holeg.serialize.ModelDeserializer.gson;
  20. /**
  21. * The Class represents the controller.
  22. */
  23. public class Control {
  24. private static final Logger log = Logger.getLogger(Control.class.getName());
  25. private final CanvasController canvasController;
  26. private final SimulationManager simulationManager;
  27. public Event OnCategoryChanged = new Event();
  28. public Event OnSelectionChanged = new Event();
  29. public Event OnCanvasUpdate = new Event();
  30. public Action<Boolean> OnGuiSetEnabled = new Action<>();
  31. public Action<GroupNode> OnShowGroupNode = new Action<>();
  32. public Action<GroupNode> OnRemoveGroupNode = new Action<>();
  33. public Event OnModelChanged = new Event();
  34. private Model model;
  35. public Control(Model model) {
  36. this.model = model;
  37. this.canvasController = new CanvasController(this);
  38. this.simulationManager = new SimulationManager(this);
  39. }
  40. /* Operations for Categories and Objects */
  41. /**
  42. * init default category and objects.
  43. */
  44. public void resetCategories() {
  45. clearCategories();
  46. initCategories();
  47. saveCategory();
  48. }
  49. /**
  50. * Gives all Category as String
  51. *
  52. * @return a array of strings from all Categorys
  53. */
  54. public String[] getCategoriesStrings() {
  55. return GuiSettings.getCategories().stream().map(Category::getName).toArray(String[]::new);
  56. }
  57. /**
  58. * Add new Holon Object to a Category.
  59. */
  60. public void addObject(Category cat, String obj, List<HolonElement> list, String img) {
  61. addNewHolonObject(cat, obj, list, img);
  62. saveCategory();
  63. }
  64. /**
  65. * Add new Holon Switch to a Category.
  66. *
  67. * @param cat Category
  68. * @param obj New Object Name
  69. */
  70. public void addSwitch(Category cat, String obj) {
  71. addNewHolonSwitch(cat, obj);
  72. saveCategory();
  73. }
  74. public void deleteCategory(Category category) {
  75. removeCategory(category);
  76. saveCategory();
  77. }
  78. /**
  79. * removes a selectedObject from selection.
  80. */
  81. public void removeObjectsFromSelection(Collection<AbstractCanvasObject> objects) {
  82. if (GuiSettings.getSelectedObjects().removeAll(objects)) {
  83. OnSelectionChanged.broadcast();
  84. }
  85. }
  86. /**
  87. * removes a selectedObject from selection.
  88. *
  89. * @param obj Cpsobject
  90. */
  91. public void removeObjectFromSelection(AbstractCanvasObject obj) {
  92. if (GuiSettings.getSelectedObjects().remove(obj)) {
  93. OnSelectionChanged.broadcast();
  94. }
  95. }
  96. public void addSelectedObject(AbstractCanvasObject obj) {
  97. if (GuiSettings.getSelectedObjects().add(obj)) {
  98. OnSelectionChanged.broadcast();
  99. }
  100. }
  101. public void addSelectedObjects(Collection<AbstractCanvasObject> objects) {
  102. if (GuiSettings.getSelectedObjects().addAll(objects)) {
  103. OnSelectionChanged.broadcast();
  104. }
  105. }
  106. public void setSelection(Collection<AbstractCanvasObject> objects) {
  107. GuiSettings.getSelectedObjects().clear();
  108. addSelectedObjects(objects);
  109. }
  110. public void clearSelection() {
  111. if (!GuiSettings.getSelectedObjects().isEmpty()) {
  112. GuiSettings.getSelectedObjects().clear();
  113. OnSelectionChanged.broadcast();
  114. }
  115. }
  116. public void addObjectOnCanvas(GroupNode node, AbstractCanvasObject object) {
  117. canvasController.addObject(node, object);
  118. calculateStateAndVisualForTimeStep(model.getCurrentIteration());
  119. }
  120. public void addCopyOnCanvas(GroupNode node, AbstractCanvasObject object) {
  121. addObjectOnCanvas(node, object.copy());
  122. }
  123. /**
  124. * Deletes an CpsObject on the Canvas and its connections.
  125. *
  126. * @param obj AbstractCpsObject
  127. */
  128. public void deleteCanvasObject(AbstractCanvasObject obj) {
  129. canvasController.deleteObject(obj);
  130. if (obj instanceof GroupNode groupnode) {
  131. canvasController.deleteAllObjectsInGroupNode(groupnode);
  132. }
  133. calculateStateAndVisualForCurrentTimeStep();
  134. }
  135. public void deleteCanvasObjects(Collection<AbstractCanvasObject> objects) {
  136. canvasController.deleteObjects(objects);
  137. calculateStateAndVisualForCurrentTimeStep();
  138. }
  139. /**
  140. * Replaces {@code toBeReplaced} by {@code by} on the canvas
  141. *
  142. * @param toBeReplaced the object that will be replaced
  143. * @param by the object that will replace it
  144. */
  145. public void replaceCanvasObject(AbstractCanvasObject toBeReplaced, AbstractCanvasObject by) {
  146. canvasController.replaceObject(toBeReplaced, by);
  147. }
  148. /**
  149. * Add an edge to the Canvas.
  150. *
  151. * @param edge the edge
  152. */
  153. public boolean addEdgeOnCanvas(Edge edge) {
  154. boolean connectsItSelf = edge.getA() == edge.getB();
  155. boolean connectionExist = model.getEdgesOnCanvas().stream().anyMatch(e -> (e.getA() == edge.getA() && e.getB() == edge.getB())
  156. || (e.getB() == edge.getA() && e.getA() == edge.getB()));
  157. if (connectsItSelf || connectionExist) {
  158. return false;
  159. }
  160. canvasController.addEdgeOnCanvas(edge);
  161. return true;
  162. }
  163. /**
  164. * Removes an Edge from the Canvas.
  165. *
  166. * @param edge the edge to remove
  167. */
  168. public void removeEdgesOnCanvas(Edge edge) {
  169. canvasController.removeEdgesOnCanvas(edge);
  170. }
  171. /**
  172. * calculates the flow of the edges and the supply for objects for the current
  173. * Timestep.
  174. */
  175. public void calculateStateAndVisualForCurrentTimeStep() {
  176. calculateStateAndVisualForTimeStep(model.getCurrentIteration());
  177. }
  178. public void calculateStateOnlyForCurrentTimeStep() {
  179. calculateStateForTimeStep(model.getCurrentIteration());
  180. }
  181. /**
  182. * calculates the flow of the edges and the supply for objects.
  183. *
  184. * @param x current Iteration
  185. */
  186. public void calculateStateAndVisualForTimeStep(int x) {
  187. simulationManager.calculateStateForTimeStep(x);
  188. log.info("OnCanvasUpdate");
  189. OnCanvasUpdate.broadcast();
  190. }
  191. /**
  192. * calculates the flow of the edges and the supply for objects.
  193. *
  194. * @param x current Iteration
  195. */
  196. public void calculateStateForTimeStep(int x) {
  197. simulationManager.calculateStateForTimeStep(x);
  198. }
  199. /**
  200. * resets the whole State of the simulation including a reset of all Edges to
  201. * the default "is working" state
  202. */
  203. public void resetSimulation() {
  204. model.reset();
  205. }
  206. public void saveCategory() {
  207. //TODO(Tom2022-01-27):
  208. }
  209. /**
  210. * Getter for Model.
  211. *
  212. * @return the Model
  213. */
  214. public Model getModel() {
  215. return model;
  216. }
  217. public void replaceObject(AbstractCanvasObject toBeReplaced, AbstractCanvasObject by) {
  218. canvasController.replaceObject(toBeReplaced, by);
  219. }
  220. /**
  221. * Copy all Selected Objects.
  222. */
  223. public void copy() {
  224. GuiSettings.getClipboardObjects().clear();
  225. GuiSettings.getClipboardObjects().addAll(GuiSettings.getSelectedObjects());
  226. }
  227. public void paste(GroupNode groupNode, Vec2i offset) {
  228. if (GuiSettings.getClipboardObjects().isEmpty()) {
  229. return;
  230. }
  231. Set<AbstractCanvasObject> copies = GuiSettings.getClipboardObjects().stream().map(AbstractCanvasObject::copy).collect(Collectors.toSet());
  232. copies.forEach(obj -> {
  233. obj.getPosition().addAssign(offset);
  234. obj.getPosition().clampX(0, GuiSettings.canvasSize.getX());
  235. obj.getPosition().clampY(0, GuiSettings.canvasSize.getY());
  236. });
  237. groupNode.addAll(copies);
  238. calculateStateAndVisualForTimeStep(model.getCurrentIteration());
  239. OnSelectionChanged.broadcast();
  240. }
  241. public void cut() {
  242. copy();
  243. deleteCanvasObjects(GuiSettings.getSelectedObjects());
  244. clearSelection();
  245. }
  246. public void createTemplate(HolonObject cps, JFrame parentFrame) {
  247. CreateTemplatePopUp t = new CreateTemplatePopUp(cps, model, parentFrame, this);
  248. t.setVisible(true);
  249. }
  250. public void guiSetEnabled(boolean state) {
  251. log.info("guiDisabled");
  252. OnGuiSetEnabled.broadcast(state);
  253. }
  254. /**
  255. * init default category and objects.
  256. */
  257. public void initCategories() {
  258. Category energy = createCategoryWithName("Energy");
  259. Category building = createCategoryWithName("Building");
  260. Category component = createCategoryWithName("Component");
  261. HolonObject powerPlant = addNewHolonObject(energy, "Power Plant", new ArrayList<>(),
  262. ImagePreference.Canvas.DefaultObject.PowerPlant);
  263. HolonObject house = addNewHolonObject(building, "House", new ArrayList<>(), ImagePreference.Canvas.DefaultObject.House);
  264. addNewHolonSwitch(component, "Switch");
  265. powerPlant.add(new HolonElement(null, "Power", 10000));
  266. energy.getObjects().add(powerPlant);
  267. house.add(new HolonElement(null, "TV", -250));
  268. house.add(new HolonElement(null, "TV", -250));
  269. house.add(new HolonElement(null, "Fridge", -500));
  270. house.add(new HolonElement(null, "Radio", -100));
  271. house.add(new HolonElement(null, "PC", -250));
  272. house.add(new HolonElement(null, "PC", -250));
  273. house.add(new HolonElement(null, "PC", -250));
  274. house.add(new HolonElement(null, "Light", -50));
  275. house.add(new HolonElement(null, "Light", -50));
  276. house.add(new HolonElement(null, "Light", -50));
  277. house.add(new HolonElement(null, "Light", -50));
  278. house.add(new HolonElement(null, "Light", -50));
  279. house.add(new HolonElement(null, "Solar Panel", 300));
  280. building.getObjects().add(house);
  281. OnCategoryChanged.broadcast();
  282. }
  283. public Category createCategoryWithName(String categoryName) {
  284. Optional<Category> category = findCategoryWithName(categoryName);
  285. if (category.isEmpty()) {
  286. Category cat = new Category(categoryName);
  287. GuiSettings.getCategories().add(cat);
  288. OnCategoryChanged.broadcast();
  289. return cat;
  290. } else {
  291. return category.get();
  292. }
  293. }
  294. /**
  295. * remove a Category from Model.
  296. *
  297. * @param c Category
  298. */
  299. public void removeCategory(Category c) {
  300. GuiSettings.getCategories().remove(c);
  301. OnCategoryChanged.broadcast();
  302. }
  303. public void clearCategories() {
  304. GuiSettings.getCategories().clear();
  305. }
  306. /**
  307. * Add Object into a Category.
  308. *
  309. * @param category Category
  310. * @param object Object
  311. */
  312. public void addObject(Category category, AbstractCanvasObject object) {
  313. int i = 0;
  314. //TODO(Tom2021-12-1) remove/redo this search
  315. while (category.findObjectWithName(object.getName()).isPresent()) {
  316. if (object.getName().contains("_"))
  317. object.setName(object.getName().substring(0, object.getName().indexOf('_')));
  318. object.setName(object.getName() + "_" + i);
  319. i++;
  320. }
  321. category.getObjects().add(object);
  322. }
  323. /**
  324. * Add new Holon Object to a Category.
  325. *
  326. * @param category Category
  327. * @param object New Object Name
  328. * @param list Array of Elements
  329. * @param image the image Path
  330. */
  331. public HolonObject addNewHolonObject(Category category, String object, List<HolonElement> list, String image) {
  332. HolonObject obj = new HolonObject(object);
  333. obj.setImagePath(image);
  334. obj.clearElements();
  335. obj.add(list);
  336. addObject(category, obj);
  337. return obj;
  338. }
  339. public HolonSwitch addNewHolonSwitch(Category cat, String objName) {
  340. HolonSwitch holonSwitch = new HolonSwitch(objName);
  341. addObject(cat, holonSwitch);
  342. return holonSwitch;
  343. }
  344. /**
  345. * Removes an Object from a Category.
  346. *
  347. * @param category Category
  348. * @param cps the Object
  349. */
  350. public void removeObject(Category category, AbstractCanvasObject cps) {
  351. category.getObjects().remove(cps);
  352. OnCategoryChanged.broadcast();
  353. }
  354. public Optional<Category> findCategoryWithName(String categoryName) {
  355. return GuiSettings.getCategories().stream().filter(cat -> cat.getName().equals(categoryName)).findAny();
  356. }
  357. public void loadFile(File file) {
  358. log.info("load" + file);
  359. try {
  360. FileReader reader = new FileReader(file);
  361. Model model = gson.fromJson(reader, Model.class);
  362. reader.close();
  363. this.model = model;
  364. calculateStateAndVisualForCurrentTimeStep();
  365. OnModelChanged.broadcast();
  366. } catch (IOException e) {
  367. log.warning(e.getLocalizedMessage());
  368. }
  369. clearSelection();
  370. GuiSettings.setActualSaveFile(file);
  371. }
  372. public void toggleSelectedObjects(Collection<AbstractCanvasObject> objects) {
  373. Set<AbstractCanvasObject> intersection = new HashSet<>(objects);
  374. intersection.retainAll(GuiSettings.getSelectedObjects());
  375. GuiSettings.getSelectedObjects().addAll(objects);
  376. GuiSettings.getSelectedObjects().removeAll(intersection);
  377. OnSelectionChanged.broadcast();
  378. }
  379. public void saveFile(File file) {
  380. log.info("save" + file);
  381. try {
  382. FileWriter writer = new FileWriter(file);
  383. gson.toJson(model, writer);
  384. writer.close();
  385. } catch (IOException e) {
  386. log.warning(e.getLocalizedMessage());
  387. }
  388. GuiSettings.setActualSaveFile(file);
  389. }
  390. public void group() {
  391. canvasController.group(GuiSettings.getSelectedObjects());
  392. clearSelection();
  393. OnCanvasUpdate.broadcast();
  394. }
  395. public void ungroup() {
  396. canvasController.ungroup(GuiSettings.getSelectedObjects());
  397. clearSelection();
  398. OnCanvasUpdate.broadcast();
  399. }
  400. public void clearModel() {
  401. model.clear();
  402. clearSelection();
  403. model.setCurrentIteration(0);
  404. IdCounter.reset();
  405. calculateStateAndVisualForCurrentTimeStep();
  406. OnModelChanged.broadcast();
  407. GuiSettings.setActualSaveFile(null);
  408. }
  409. public void showGroupNode(GroupNode groupNode) {
  410. OnShowGroupNode.broadcast(groupNode);
  411. clearSelection();
  412. }
  413. }