ClipboardController.java 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473
  1. package ui.controller;
  2. import classes.*;
  3. import com.google.gson.*;
  4. import ui.controller.SaveController.EDGETYPE;
  5. import ui.controller.SaveController.GRAPHTYPE;
  6. import ui.controller.SaveController.NUMTYPE;
  7. import ui.controller.SaveController.TYPE;
  8. import ui.model.Model;
  9. import java.awt.*;
  10. import java.awt.datatransfer.*;
  11. import java.awt.geom.Point2D;
  12. import java.io.IOException;
  13. import java.util.*;
  14. import java.util.List;
  15. import java.util.stream.Collectors;
  16. public class ClipboardController {
  17. private Model model;
  18. private SaveController store;
  19. private LoadController load;
  20. private CanvasController cvsC;
  21. private ObjectController objC;
  22. private NodeController uppC;
  23. private JsonParser parser;
  24. private Clipboard clipboard;
  25. private HashMap<Integer, Integer> objIDMap;
  26. private HashMap<Integer, Integer> eleIDMap;
  27. private String sav;
  28. private Point point;
  29. ClipboardController(Model model, SaveController store, LoadController load, CanvasController cvs,
  30. ObjectController obj, NodeController uppC, MultiPurposeController mp) {
  31. this.model = model;
  32. this.store = store;
  33. this.load = load;
  34. this.cvsC = cvs;
  35. this.objC = obj;
  36. this.uppC = uppC;
  37. this.clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
  38. parser = new JsonParser();
  39. }
  40. /**
  41. * Copy marked Objects into Clipboard in Json Format
  42. */
  43. public void copy(CpsUpperNode upperNode) {
  44. JsonObject file = new JsonObject();
  45. ArrayDeque<AbstractCpsObject> queue = new ArrayDeque<>();
  46. AbstractCpsObject u = null;
  47. store.initNumeration();
  48. file.add("SAV", new JsonPrimitive((upperNode == null ? "CVS" : "" + upperNode.getId())));
  49. Position pos = uppC.calculatePos(model.getSelectedCpsObjects());
  50. file.add("CENTER", model.getGson().toJsonTree(pos, Position.class));
  51. for (AbstractCpsObject abs : model.getSelectedCpsObjects()) {
  52. queue.add(abs);
  53. }
  54. System.out.println("heiCopy");
  55. while (!queue.isEmpty()) {
  56. u = queue.pop();
  57. String key = "CVSOBJECT" + store.getNumerator(NUMTYPE.OBJECT);
  58. file.add(key, model.getGson().toJsonTree(u, AbstractCpsObject.class));
  59. edgeToJson(EDGETYPE.CONNECTION, file, u.getId(), u.getConnections());
  60. if (u instanceof HolonObject)
  61. store.elementsToJson(TYPE.CANVAS, file, u);
  62. if (u instanceof HolonSwitch)
  63. if (((HolonSwitch) u).getGraphPoints().size() != 0)
  64. store.unitgraphToJson(GRAPHTYPE.SWITCH, file, u.getId(), ((HolonSwitch) u).getGraphPoints());
  65. if (u instanceof CpsUpperNode) {
  66. for (AbstractCpsObject adjacent : ((CpsUpperNode) u).getNodes()) {
  67. queue.add(adjacent);
  68. }
  69. edgeToJson(EDGETYPE.NODE, file, u.getId(), ((CpsUpperNode) u).getNodeEdges());
  70. edgeToJson(EDGETYPE.OLD, file, u.getId(), ((CpsUpperNode) u).getOldEdges());
  71. }
  72. }
  73. if (upperNode == null)
  74. edgeToJson(EDGETYPE.LAYER, file, 0, model.getEdgesOnCanvas());
  75. else
  76. edgeToJson(EDGETYPE.LAYER, file, upperNode.getId(), upperNode.getNodeEdges());
  77. StringSelection selection = new StringSelection(model.getGson().toJson(file));
  78. clipboard.setContents(selection, selection);
  79. }
  80. /**
  81. * Paste the Copied JsonTree into Canvas
  82. */
  83. void paste(CpsUpperNode upperNode, Point p)
  84. throws UnsupportedFlavorException, IOException, JsonParseException {
  85. if (p == null)
  86. return;
  87. JsonObject json;
  88. Transferable content = clipboard.getContents(null);
  89. if (content != null && content.isDataFlavorSupported(DataFlavor.stringFlavor)
  90. && !content.isDataFlavorSupported(DataFlavor.allHtmlFlavor)) {
  91. String str = (String) content.getTransferData(DataFlavor.stringFlavor);
  92. if (parser.parse(str).isJsonObject())
  93. json = (JsonObject) parser.parse(str);
  94. else
  95. throw new JsonParseException("Unknown Clipboard Information");
  96. } else
  97. return;
  98. List<String> keys = load.getKeys(json);
  99. List<String> edges = keys.stream().filter(key -> key.contains("EDGE"))
  100. .collect(Collectors.toCollection(ArrayList::new));
  101. HashMap<Integer, AbstractCpsObject> objDispatch = new HashMap<>();
  102. HashMap<Integer, HolonElement> eleDispatch = new HashMap<>();
  103. model.getSelectedCpsObjects().clear();
  104. objIDMap = new HashMap<>();
  105. eleIDMap = new HashMap<>();
  106. sav = json.get("SAV").getAsString();
  107. Position old = model.getGson().getAdapter(Position.class).fromJsonTree(json.get("CENTER"));
  108. point = new Point(old.x - p.x, old.y - p.y);
  109. forwardObjects(keys, json, objDispatch, eleDispatch, upperNode);
  110. // for selecting Cps
  111. getObjectsInDepth();
  112. forwardEdges(edges, json, objDispatch, upperNode);
  113. }
  114. /**
  115. * Cuts the marked Objects out of Canvas and saves them into the Clipboard
  116. */
  117. void cut(CpsUpperNode upperNode) {
  118. copy(upperNode);
  119. for (AbstractCpsObject abs : model.getSelectedCpsObjects()) {
  120. if (upperNode == null)
  121. cvsC.deleteObjectOnCanvas(abs);
  122. else
  123. uppC.deleteObjectInUpperNode(abs, upperNode);
  124. if (abs instanceof CpsUpperNode)
  125. cvsC.bfsNodeCleaner((CpsUpperNode) abs);
  126. }
  127. }
  128. private void forwardEdges(List<String> keys, JsonObject json, HashMap<Integer, AbstractCpsObject> objDispatch,
  129. CpsUpperNode upperNode) {
  130. List<String> conn = new ArrayList<>();
  131. for (String edge : keys) {
  132. if (edge.contains("LAYEREDGE"))
  133. loadEdge(EDGETYPE.LAYER, json.get(edge), objDispatch, upperNode);
  134. if (edge.contains("CONNEDGE"))
  135. conn.add(edge);
  136. if (edge.contains("NODEEDGE"))
  137. loadEdge(EDGETYPE.NODE, json.get(edge), objDispatch, null);
  138. if (edge.contains("OLDEDGE"))
  139. loadEdge(EDGETYPE.OLD, json.get(edge), objDispatch, null);
  140. }
  141. for (String edge : conn) {
  142. loadEdge(EDGETYPE.CONNECTION, json.get(edge), objDispatch, null);
  143. }
  144. }
  145. private void forwardObjects(List<String> keys, JsonObject json, HashMap<Integer, AbstractCpsObject> objDispatch,
  146. HashMap<Integer, HolonElement> eleDispatch, CpsUpperNode upperNode) {
  147. for (String key : keys) {
  148. if (key.contains("CVSOBJECT"))
  149. loadCanvasObject(json.get(key), objDispatch, upperNode);
  150. if (key.contains("CVSELEMENT"))
  151. loadCanvasElements(json.get(key), objDispatch, eleDispatch);
  152. if (key.contains("SWUNITGRAPH"))
  153. loadUnitGraph(GRAPHTYPE.SWITCH, json.get(key), objDispatch, null);
  154. if (key.contains("ELEUNITGRAPH"))
  155. loadUnitGraph(GRAPHTYPE.ELEMENT, json.get(key), null, eleDispatch);
  156. if (key.contains("ELETESTUNITGRAPH"))
  157. loadUnitGraph(GRAPHTYPE.TESTELEMENT, json.get(key), null, eleDispatch);
  158. }
  159. }
  160. private void loadCanvasObject(JsonElement jsonElement, HashMap<Integer, AbstractCpsObject> objDispatch,
  161. CpsUpperNode upperNode) {
  162. AbstractCpsObject temp = model.getGson().fromJson(jsonElement.getAsJsonObject(), AbstractCpsObject.class);
  163. load.initObjects(temp);
  164. objIDMapper(temp);
  165. updatePosition(temp, upperNode);
  166. // if its stored before on the canvas just put it there
  167. if (temp.getSav().equals(sav)) {
  168. if (upperNode == null)
  169. cvsC.addObject(temp, false);
  170. else
  171. uppC.addObjectInUpperNode(temp, upperNode, false);
  172. // mark the Pasted Objects
  173. model.getSelectedCpsObjects().add(temp);
  174. } else {
  175. // else look up the table and put it into the right Uppernode
  176. CpsUpperNode temp2 = (CpsUpperNode) objDispatch.get(objIDMap.get(Integer.parseInt(temp.getSav())));
  177. if(temp2!=null)
  178. uppC.addObjectInUpperNode(temp, temp2, false);
  179. else{
  180. /**
  181. * if corresponding Uppernode doesn't exist:
  182. * Add it to the current Canvas/UpperNode
  183. */
  184. if (upperNode == null)
  185. cvsC.addObject(temp, false);
  186. else
  187. uppC.addObjectInUpperNode(temp, upperNode, false);
  188. }
  189. }
  190. objDispatch.put(temp.getId(), temp);
  191. }
  192. private void loadCanvasElements(JsonElement jsonElement, HashMap<Integer, AbstractCpsObject> objDispatch,
  193. HashMap<Integer, HolonElement> eleDispatch) {
  194. JsonObject object = jsonElement.getAsJsonObject();
  195. HolonElement temp = model.getGson().fromJson(object.get("properties"), HolonElement.class);
  196. load.initElements(temp);
  197. eleIDMapper(temp);
  198. // id which Object it was stored before
  199. int stored = objIDMap.get(object.get("ID").getAsInt());
  200. // lookup that object
  201. HolonObject temp2 = (HolonObject) objDispatch.get(stored);
  202. // add it
  203. objC.addElement(temp2, temp);
  204. // store element also inside a table
  205. eleDispatch.put(temp.getId(), temp);
  206. }
  207. private void loadUnitGraph(GRAPHTYPE type, JsonElement jsonElement, HashMap<Integer, AbstractCpsObject> objDispatch,
  208. HashMap<Integer, HolonElement> eleDispatch) {
  209. JsonObject object = jsonElement.getAsJsonObject();
  210. List<String> keys = load.getKeys(object);
  211. String p;
  212. int mid, x, y;
  213. System.out.println("loadcontroller");
  214. LinkedList<Point> graphpoint = new LinkedList<>();
  215. int sav = 0;
  216. // foreach Point in the graph restore it
  217. for (String k : keys) {
  218. if (!k.equals("ID")) {
  219. p = object.get(k).getAsString();
  220. mid = p.indexOf(':');
  221. x = Integer.parseInt(p.substring(0, mid));
  222. y = Integer.parseInt(p.substring(mid + 1, p.length()));
  223. graphpoint.add(new Point(x, y));
  224. } else
  225. // else its an ID
  226. sav = object.get(k).getAsInt();
  227. }
  228. switch (type) {
  229. case SWITCH:
  230. sav = objIDMap.get(sav);
  231. HolonSwitch sw = (HolonSwitch) objDispatch.get(sav);
  232. sw.setGraphPoints(graphpoint);
  233. break;
  234. case ELEMENT:
  235. sav = eleIDMap.get(sav);
  236. HolonElement ele = eleDispatch.get(sav);
  237. ele.setGraphPoints(graphpoint);
  238. break;
  239. case TESTELEMENT:
  240. LinkedList<Point2D.Double> graphpointTEST = new LinkedList<>();
  241. for (String k : keys) {
  242. if (!k.equals("ID")) {
  243. p = object.get(k).getAsString();
  244. mid = p.indexOf(':');
  245. double x1 = Double.parseDouble(p.substring(0, mid));
  246. double y1 = Integer.parseInt(p.substring(mid + 1, p.length()));
  247. graphpointTEST.add(new Point2D.Double(x1, y1));
  248. } else
  249. // else its an ID
  250. sav = object.get(k).getAsInt();
  251. }
  252. sav = eleIDMap.get(sav);
  253. HolonElement ele1 = eleDispatch.get(sav);
  254. ele1.setTestGraphPoints(graphpointTEST);
  255. break;
  256. default:
  257. break;
  258. }
  259. }
  260. /**
  261. * loads an edge from json
  262. */
  263. private void loadEdge(EDGETYPE type, JsonElement jsonElement, HashMap<Integer, AbstractCpsObject> objDispatch,
  264. CpsUpperNode upperNode) {
  265. JsonObject object = jsonElement.getAsJsonObject();
  266. CpsEdge temp = model.getGson().fromJson(object.get("properties"), CpsEdge.class);
  267. load.initCpsEdge(temp);
  268. // look for A and B inside the Table
  269. temp.setA(objDispatch.get(objIDMap.get(object.get("A").getAsInt())));
  270. temp.setB(objDispatch.get(objIDMap.get(object.get("B").getAsInt())));
  271. int sav;
  272. switch (type) {
  273. case LAYER:
  274. // if in canvas add it into the canvas but delete connection before
  275. (upperNode == null ? model.getEdgesOnCanvas() : upperNode.getNodeEdges()).add(temp);
  276. break;
  277. case CONNECTION:
  278. // if no duplicates in connection store them into the given A and B
  279. if (!uppC.lookforDuplicates(temp.getA(), temp.getB(), temp.getA().getConnections()))
  280. temp.getA().getConnections().add(temp);
  281. if (!uppC.lookforDuplicates(temp.getA(), temp.getB(), temp.getB().getConnections()))
  282. temp.getB().getConnections().add(temp);
  283. break;
  284. case NODE:
  285. // put it into given nodeofnode
  286. sav = objIDMap.get(object.get("ID").getAsInt());
  287. ((CpsUpperNode) objDispatch.get(sav)).getNodeEdges().add(temp);
  288. break;
  289. case OLD:
  290. // same as above
  291. sav = objIDMap.get(object.get("ID").getAsInt());
  292. ((CpsUpperNode) objDispatch.get(sav)).getOldEdges().add(temp);
  293. break;
  294. default:
  295. break;
  296. }
  297. if (object.get("connection").getAsBoolean() && !type.equals(EDGETYPE.CONNECTION)) {
  298. temp.getA().getConnections().add(temp);
  299. temp.getB().getConnections().add(temp);
  300. }
  301. }
  302. /**
  303. * Modified Method from LoadController. Slightly different
  304. */
  305. private void edgeToJson(EDGETYPE type, JsonObject file, int id, ArrayList<CpsEdge> arr) {
  306. String k = null;
  307. boolean b = false;
  308. JsonObject temp = new JsonObject();
  309. for (CpsEdge edge : arr) {
  310. if (model.getClipboradObjects().contains(edge.getA())
  311. && model.getClipboradObjects().contains(edge.getB())) {
  312. // add properties and only the ids from a and b
  313. temp.add("properties", model.getGson().toJsonTree(edge));
  314. temp.add("A", new JsonPrimitive(edge.getA().getId()));
  315. temp.add("B", new JsonPrimitive(edge.getB().getId()));
  316. // Key and occasionally the id of Uppernode
  317. switch (type) {
  318. case LAYER:
  319. temp.add("ID", new JsonPrimitive(id));
  320. k = "LAYEREDGE" + store.getNumerator(NUMTYPE.EDGE);
  321. break;
  322. case CONNECTION:
  323. k = "CONNEDGE" + store.getNumerator(NUMTYPE.CONNECTION);
  324. break;
  325. case NODE:
  326. temp.add("ID", new JsonPrimitive(id));
  327. k = "NODEEDGE" + store.getNumerator(NUMTYPE.NODEEDGE);
  328. break;
  329. case OLD:
  330. temp.add("ID", new JsonPrimitive(id));
  331. k = "OLDEDGE" + store.getNumerator(NUMTYPE.OLDEDGE);
  332. break;
  333. default:
  334. break;
  335. }
  336. // lookup if the CVS, NODE or OLDEDGE are also connections
  337. if (edge.getA().getConnections().contains(edge) && edge.getA().getConnections().contains(edge)
  338. && !type.equals(EDGETYPE.CONNECTION))
  339. b = true;
  340. temp.add("connection", new JsonPrimitive(b));
  341. file.add(k, model.getGson().toJsonTree(temp));
  342. temp = new JsonObject();
  343. }
  344. }
  345. }
  346. /**
  347. * Adds all Objects in Depth into Clipboardobjects preemptive when objects are selected
  348. */
  349. void getObjectsInDepth() {
  350. model.setClipboradObjects(new ArrayList<>());
  351. for (AbstractCpsObject obj : model.getSelectedCpsObjects()) {
  352. clipboadDepth(obj);
  353. }
  354. }
  355. /**
  356. * Get all Objects inside the Currentobject and add them into ClipboardObjects
  357. */
  358. private void clipboadDepth(AbstractCpsObject obj) {
  359. //modified backtracking Algorithm no True/False
  360. if (!(obj instanceof CpsUpperNode)) {
  361. model.getClipboradObjects().add(obj);
  362. } else {
  363. model.getClipboradObjects().add(obj);
  364. for (AbstractCpsObject abs : ((CpsUpperNode) obj).getNodes()) {
  365. clipboadDepth(abs);
  366. }
  367. }
  368. }
  369. /**
  370. * Map the Copied Object ID into a new One
  371. */
  372. private void objIDMapper(AbstractCpsObject temp) {
  373. int id = temp.getId();
  374. temp.setId(IdCounter.nextId());
  375. // oldID -> currentID
  376. objIDMap.put(id, temp.getId());
  377. }
  378. /**
  379. * Map the Copied Element ID into a new One
  380. */
  381. private void eleIDMapper(HolonElement temp) {
  382. int id = temp.getId();
  383. temp.setId(IdCounterElem.nextId());
  384. // oldID -> currentID
  385. eleIDMap.put(id, temp.getId());
  386. }
  387. private void updatePosition(AbstractCpsObject temp, CpsUpperNode upperNode) {
  388. int x = temp.getPosition().x - point.x;
  389. int y = temp.getPosition().y - point.y;
  390. if (y < 0)
  391. y = 0 + model.getScaleDiv2() + 1;
  392. if (upperNode != null) {
  393. if (x < upperNode.getLeftBorder() + model.getScaleDiv2() + 1)
  394. x = upperNode.getLeftBorder() + model.getScaleDiv2() + 1;
  395. } else if (x < 0)
  396. x = 0 + model.getScaleDiv2() + 1;
  397. if (x > model.getCanvasX())
  398. x = model.getCanvasX() - model.getScaleDiv2() - 1;
  399. if (y > model.getCanvasX())
  400. y = model.getCanvasY() - model.getScaleDiv2() - 1;
  401. temp.setPosition(new Position(x, y));
  402. }
  403. }