Control.java 16 KB

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