SaveController.java 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482
  1. package holeg.ui.controller;
  2. import com.google.gson.JsonObject;
  3. import com.google.gson.JsonPrimitive;
  4. import com.google.gson.reflect.TypeToken;
  5. import holeg.model.*;
  6. import holeg.ui.model.GuiSettings;
  7. import holeg.ui.model.IdCounter;
  8. import holeg.ui.model.Model;
  9. import holeg.ui.model.IdCounter.CounterType;
  10. import holeg.ui.view.main.Category;
  11. import holeg.utility.math.vector.Vec2f;
  12. import org.apache.commons.compress.archivers.ArchiveException;
  13. import org.apache.commons.compress.archivers.ArchiveOutputStream;
  14. import org.apache.commons.compress.archivers.ArchiveStreamFactory;
  15. import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
  16. import org.apache.commons.compress.utils.IOUtils;
  17. import java.io.BufferedInputStream;
  18. import java.io.File;
  19. import java.io.FileInputStream;
  20. import java.io.FileOutputStream;
  21. import java.io.FileWriter;
  22. import java.io.IOException;
  23. import java.io.OutputStream;
  24. import java.util.ArrayDeque;
  25. import java.util.ArrayList;
  26. import java.util.Arrays;
  27. import java.util.LinkedList;
  28. import java.util.List;
  29. /**
  30. * Controller for Storage.
  31. *
  32. * @author Gruppe14
  33. */
  34. public class SaveController {
  35. private Model model;
  36. private int nCat, nObj, nEle, nEdge, nConn, nNodeEdge, nOldEdge, nUnitGraph, nStatsGraph;
  37. /**
  38. * Constructor.
  39. *
  40. * @param model the Model
  41. */
  42. SaveController(Model model) {
  43. this.model = model;
  44. }
  45. /**
  46. * Writes the current State of the Modelling into a JSON File which can be
  47. * loaded.
  48. *
  49. * @param path the Path
  50. * @throws IOException exception
  51. */
  52. void writeSave(String path) throws IOException, ArchiveException {
  53. File dst = new File(path);
  54. File holonFile = File.createTempFile("tmp", ".json");
  55. holonFile.deleteOnExit();
  56. dst.delete();
  57. OutputStream output = new FileOutputStream(dst);
  58. ArchiveOutputStream stream = new ArchiveStreamFactory().createArchiveOutputStream(ArchiveStreamFactory.ZIP,
  59. output);
  60. initNumeration();
  61. JsonObject file = new JsonObject();
  62. initialize(MODE.COMPLETE, file);
  63. storeCategory(file);
  64. storeCanvas(file);
  65. storeData(stream);
  66. FileWriter writer = new FileWriter(holonFile);
  67. writer.write(GuiSettings.gson.toJson(file));
  68. writer.flush();
  69. writer.close();
  70. addFileToSave(holonFile, stream, false);
  71. stream.finish();
  72. output.close();
  73. }
  74. /**
  75. * Writes the windows status (its position and dimensions)
  76. *
  77. * @param path the Path where to save it
  78. */
  79. void writeWindowStatus(String path, int x, int y, int width, int height)
  80. throws IOException, ArchiveException {
  81. JsonObject file = new JsonObject();
  82. initialize(MODE.SIZE, file);
  83. storeWindowPosAndSize(file, x, y, width, height);
  84. FileWriter writer = new FileWriter(path);
  85. writer.write(GuiSettings.gson.toJson(file));
  86. writer.flush();
  87. writer.close();
  88. }
  89. /**
  90. * Writes the Autosave File.
  91. *
  92. * @param path the Path
  93. * @throws IOException Exception
  94. */
  95. void writeAutosave(String path) throws IOException {
  96. initNumeration();
  97. JsonObject file = new JsonObject();
  98. initialize(MODE.PARTIAL, file);
  99. storeCanvas(file);
  100. FileWriter writer = new FileWriter(path);
  101. writer.write(GuiSettings.gson.toJson(file));
  102. writer.flush();
  103. writer.close();
  104. }
  105. /**
  106. * Writes the Category File in Case of Changes
  107. */
  108. void writeCategory(String path) throws IOException {
  109. initNumeration();
  110. JsonObject file = new JsonObject();
  111. initialize(MODE.CATEGORY, file);
  112. storeCategory(file);
  113. FileWriter writer = new FileWriter(path);
  114. writer.write(GuiSettings.gson.toJson(file));
  115. writer.flush();
  116. writer.close();
  117. }
  118. /**
  119. * Write needed default parameter into the JsonObject. Can be extended later
  120. * on
  121. */
  122. private void initialize(MODE mode, JsonObject file) {
  123. switch (mode) {
  124. case COMPLETE:
  125. case PARTIAL:
  126. file.add("MODE", new JsonPrimitive(mode.name()));
  127. file.add("IDCOUNTER", new JsonPrimitive(IdCounter.actualId(CounterType.Object)));
  128. file.add("IDCOUNTERELEMENT", new JsonPrimitive(IdCounter.actualId(CounterType.Element)));
  129. file.add("CANVAS_SIZE_X", new JsonPrimitive(GuiSettings.canvasSize.getX()));
  130. file.add("CANVAS_SIZE_Y", new JsonPrimitive(GuiSettings.canvasSize.getY()));
  131. break;
  132. case CATEGORY:
  133. file.add("MODE", new JsonPrimitive(mode.name()));
  134. break;
  135. case SIZE:
  136. file.add("MODE", new JsonPrimitive(mode.name()));
  137. default:
  138. break;
  139. }
  140. }
  141. /**
  142. * Store all Categories and Object into a Json File via Serialization
  143. */
  144. private void storeCategory(JsonObject file) {
  145. // forall categories store them into the jsontree
  146. for (Category cat : GuiSettings.getCategories()) {
  147. String key = "CATEGORY" + getNumerator(NUMTYPE.CATEGORY);
  148. file.add(key, new JsonPrimitive(cat.getName()));
  149. // forall object in the category store them into the jsontree
  150. for (AbstractCanvasObject obj : cat.getObjects()) {
  151. file.add("CGOBJECT" + getNumerator(NUMTYPE.OBJECT),
  152. GuiSettings.gson.toJsonTree(obj, AbstractCanvasObject.class));
  153. // if its a holonobject add elements too
  154. if (obj instanceof HolonObject)
  155. elementsToJson(TYPE.CATEGORY, file, obj);
  156. }
  157. }
  158. }
  159. private void storeWindowPosAndSize(JsonObject file, int x, int y, int width, int height) {
  160. file.add("POS_X", new JsonPrimitive(x));
  161. file.add("POS_Y", new JsonPrimitive(y));
  162. file.add("WIDTH", new JsonPrimitive(width));
  163. file.add("HEIGHT", new JsonPrimitive(height));
  164. }
  165. /**
  166. * Travers through all Objects via BFS and Stores everything relevant
  167. */
  168. private void storeCanvas(JsonObject file) {
  169. //TODO(Tom2021-12-20): remove QUEUE
  170. ArrayDeque<AbstractCanvasObject> queue = new ArrayDeque<>();
  171. queue.addAll(model.getCanvas().getObjectsInThisLayer().toList());
  172. // while quene not empty
  173. while (!queue.isEmpty()) {
  174. // u = current node
  175. AbstractCanvasObject u = queue.pop();
  176. // add currentnode into jsontree
  177. String key = "CVSOBJECT" + getNumerator(NUMTYPE.OBJECT);
  178. file.add(key, GuiSettings.gson.toJsonTree(u, AbstractCanvasObject.class));
  179. // and its connections too
  180. edgeToJson(EDGETYPE.CONNECTION, file, u.getId(), new ArrayList<>());
  181. // if holonobject elements too
  182. if (u instanceof HolonObject)
  183. elementsToJson(TYPE.CANVAS, file, u);
  184. // if switch graphpoints too
  185. if (u instanceof HolonSwitch sw)
  186. if (sw.getGraphPoints().size() != 0)
  187. unitgraphToJson(GRAPHTYPE.SWITCH, file, u.getId(), ((HolonSwitch) u).getGraphPoints());
  188. // if uppernode put all nodes inside the uppernode into queue
  189. if (u instanceof GroupNode groupnode) {
  190. queue.addAll( groupnode.getObjectsInThisLayer().toList());
  191. }
  192. }
  193. // lastly add canvasedges into json
  194. edgeToJson(EDGETYPE.CANVAS, file, 0, model.getEdgesOnCanvas());
  195. }
  196. /**
  197. * Save wanted Data
  198. */
  199. private void storeData(ArchiveOutputStream stream) throws IOException {
  200. File images = new File(System.getProperty("user.home") + "/.config/HolonGUI/Images");
  201. File background = new File(System.getProperty("user.home") + "/.config/HolonGUI/BackgroundImages");
  202. addFilesToSave(images, stream);
  203. addFilesToSave(background, stream);
  204. }
  205. /**
  206. * Stores Category or Canvas Elements into Json
  207. */
  208. void elementsToJson(TYPE type, JsonObject file, AbstractCanvasObject obj) {
  209. JsonObject temp = new JsonObject();
  210. String key = null;
  211. // forall elements store them into json and include the id of the object
  212. for (HolonElement ele : ((HolonObject) obj).getElements().toList()) {
  213. temp.add("properties", GuiSettings.gson.toJsonTree(ele));
  214. temp.add("ID", new JsonPrimitive(obj.getId()));
  215. temp.add("FlexList", GuiSettings.gson.toJsonTree(ele.flexList, new TypeToken<List<Flexibility>>() {
  216. }.getType()));
  217. // switch for deciding the key
  218. switch (type) {
  219. case CANVAS:
  220. key = "CVSELEMENT" + getNumerator(NUMTYPE.ELEMENT);
  221. break;
  222. case CATEGORY:
  223. key = "CGELEMENT" + getNumerator(NUMTYPE.ELEMENT);
  224. break;
  225. default:
  226. break;
  227. }
  228. file.add(key, GuiSettings.gson.toJsonTree(temp));
  229. // if there are gps add them into
  230. if (!ele.getGraphPoints().isEmpty())
  231. unitgraphTESTToJson(file, ele.getId(), ele.getGraphPoints());
  232. temp = new JsonObject();
  233. }
  234. }
  235. /**
  236. * Put the UnitGraphs of Switches or Elements into Json
  237. */
  238. void unitgraphToJson(GRAPHTYPE type, JsonObject file, int id, LinkedList<Vec2f> graph) {
  239. JsonObject temp = new JsonObject();
  240. String key = null;
  241. // forall points add them
  242. for (int i = 0; i < graph.size(); i++) {
  243. temp.add("" + i, new JsonPrimitive(graph.get(i).x + ":" + graph.get(i).y));
  244. }
  245. // decide key
  246. switch (type) {
  247. case SWITCH:
  248. key = "SWUNITGRAPH" + getNumerator(NUMTYPE.UNITGRAPH);
  249. break;
  250. case ELEMENT:
  251. key = "ELEUNITGRAPH" + getNumerator(NUMTYPE.UNITGRAPH);
  252. break;
  253. case TESTELEMENT:
  254. key = "ELETESTUNITGRAPH" + getNumerator(NUMTYPE.UNITGRAPH);
  255. break;
  256. default:
  257. break;
  258. }
  259. // add id of element so it can be found again
  260. temp.add("ID", new JsonPrimitive(id));
  261. file.add(key, GuiSettings.gson.toJsonTree(temp));
  262. }
  263. /**
  264. * Put the UnitGraphs of Switches or Elements into Json
  265. */
  266. void unitgraphTESTToJson(JsonObject file, int id, LinkedList<Vec2f> graph) {
  267. JsonObject temp = new JsonObject();
  268. String key = null;
  269. // forall points add them
  270. for (int i = 0; i < graph.size(); i++) {
  271. temp.add("" + i, new JsonPrimitive(graph.get(i).x + ":" + graph.get(i).y));
  272. }
  273. key = "ELETESTUNITGRAPH" + getNumerator(NUMTYPE.UNITGRAPH);
  274. // add id of element so it can be found again
  275. temp.add("ID", new JsonPrimitive(id));
  276. file.add(key, GuiSettings.gson.toJsonTree(temp));
  277. }
  278. /**
  279. * Canvas-Edge, Connections, Node-Edge and Old-Edges to json
  280. */
  281. private void edgeToJson(EDGETYPE type, JsonObject file, int id, List<Edge> arr) {
  282. String k = null;
  283. boolean b = false;
  284. JsonObject temp = new JsonObject();
  285. for (Edge edge : arr) {
  286. // add properties and only the ids from a and b
  287. temp.add("properties", GuiSettings.gson.toJsonTree(edge));
  288. temp.add("A", new JsonPrimitive(edge.getA().getId()));
  289. temp.add("B", new JsonPrimitive(edge.getB().getId()));
  290. // Key and occasionally the id of Uppernode
  291. switch (type) {
  292. case CANVAS:
  293. k = "CVSEDGE" + getNumerator(NUMTYPE.EDGE);
  294. break;
  295. case CONNECTION:
  296. k = "CONNEDGE" + getNumerator(NUMTYPE.CONNECTION);
  297. break;
  298. case NODE:
  299. temp.add("ID", new JsonPrimitive(id));
  300. k = "NODEEDGE" + getNumerator(NUMTYPE.NODEEDGE);
  301. break;
  302. case OLD:
  303. temp.add("ID", new JsonPrimitive(id));
  304. k = "OLDEDGE" + getNumerator(NUMTYPE.OLDEDGE);
  305. break;
  306. default:
  307. break;
  308. }
  309. // lookup if the CVS, NODE or OLDEDGE are also connections
  310. temp.add("connection", new JsonPrimitive(b));
  311. file.add(k, GuiSettings.gson.toJsonTree(temp));
  312. temp = new JsonObject();
  313. }
  314. }
  315. /**
  316. * Differs Between Single file or whole Directory to Store
  317. */
  318. private void addFilesToSave(File src, ArchiveOutputStream stream) throws IOException {
  319. if (!src.exists())
  320. return;
  321. ArrayList<File> files = new ArrayList<>();
  322. files.addAll(Arrays.asList(src.listFiles()));
  323. for (File file : files) {
  324. if (file.isDirectory())
  325. addFilesToSave(file, stream);
  326. else
  327. addFileToSave(file, stream, true);
  328. }
  329. }
  330. /**
  331. * Add a File into the Archive
  332. */
  333. private void addFileToSave(File src, ArchiveOutputStream stream, boolean dir) throws IOException {
  334. String entryName = (dir ? src.getCanonicalPath() : src.getName());
  335. entryName = checkOS(entryName);
  336. ZipArchiveEntry entry = new ZipArchiveEntry(entryName);
  337. stream.putArchiveEntry(entry);
  338. BufferedInputStream input = new BufferedInputStream(new FileInputStream(src));
  339. IOUtils.copy(input, stream);
  340. input.close();
  341. stream.closeArchiveEntry();
  342. }
  343. private String checkOS(String entryName) {
  344. String os = System.getProperty("os.name").toLowerCase();
  345. String ret = entryName;
  346. String partition = null;
  347. if (os.contains("windows")) {
  348. partition = ret.substring(0, ret.indexOf(":") + 1);
  349. ret = ret.replace(System.getProperty("user.home") + "\\.config\\HolonGUI\\", "");
  350. ret = ret.replace(partition, "");
  351. }
  352. if (os.contains("mac")) {
  353. // dosmth
  354. ret = ret.replace(System.getProperty("user.home") + "/.config/HolonGUI/", "");
  355. }
  356. if (os.contains("linux")) {
  357. // dosmth
  358. ret = ret.replace(System.getProperty("user.home") + "/.config/HolonGUI/", "");
  359. }
  360. if (os.contains("solaris")) {
  361. // dosmth
  362. }
  363. return ret;
  364. }
  365. /**
  366. * Just initialize the Numerators for the Json Keys. Maybe bad Style..
  367. */
  368. void initNumeration() {
  369. this.nCat = this.nObj = this.nEle = this.nEdge = this.nConn = this.nNodeEdge = this.nOldEdge = this.nStatsGraph = 0;
  370. }
  371. /**
  372. * Get the wanted numerator and increment it
  373. */
  374. int getNumerator(NUMTYPE type) {
  375. switch (type) {
  376. case CATEGORY:
  377. return nCat++;
  378. case OBJECT:
  379. return nObj++;
  380. case ELEMENT:
  381. return nEle++;
  382. case EDGE:
  383. return nEdge++;
  384. case CONNECTION:
  385. return nConn++;
  386. case NODEEDGE:
  387. return nNodeEdge++;
  388. case OLDEDGE:
  389. return nOldEdge++;
  390. case UNITGRAPH:
  391. return nUnitGraph++;
  392. case STATSGRAPH:
  393. return nStatsGraph++;
  394. default:
  395. break;
  396. }
  397. return -1;
  398. }
  399. public enum MODE {
  400. COMPLETE, PARTIAL, CATEGORY, SIZE,
  401. }
  402. public enum TYPE {
  403. CATEGORY, CANVAS
  404. }
  405. public enum EDGETYPE {
  406. CANVAS, CONNECTION, NODE, OLD, LAYER
  407. }
  408. public enum NUMTYPE {
  409. CATEGORY, OBJECT, ELEMENT, EDGE, CONNECTION, NODEEDGE, OLDEDGE, UNITGRAPH, STATSGRAPH
  410. }
  411. public enum GRAPHTYPE {
  412. SWITCH, ELEMENT, TESTELEMENT
  413. }
  414. }