ClipboardController.java 14 KB

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