MyCanvas.java 36 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136
  1. package ui.view;
  2. import java.awt.BasicStroke;
  3. import java.awt.Color;
  4. import java.awt.Font;
  5. import java.awt.Graphics;
  6. import java.awt.Graphics2D;
  7. import java.awt.RenderingHints;
  8. import java.awt.datatransfer.UnsupportedFlavorException;
  9. import java.awt.event.MouseEvent;
  10. import java.awt.event.MouseListener;
  11. import java.awt.event.MouseMotionListener;
  12. import java.awt.geom.Line2D;
  13. import java.awt.image.BufferedImage;
  14. import java.io.IOException;
  15. import java.util.ArrayList;
  16. import java.util.HashSet;
  17. import javax.swing.ImageIcon;
  18. import javax.swing.JFrame;
  19. import javax.swing.JLabel;
  20. import javax.swing.JOptionPane;
  21. import javax.swing.JScrollPane;
  22. import javax.swing.JTabbedPane;
  23. import javax.swing.SwingUtilities;
  24. import com.google.gson.JsonParseException;
  25. import classes.AbstractCanvasObject;
  26. import classes.Edge;
  27. import classes.GroupNode;
  28. import classes.HolonObject;
  29. import classes.HolonSwitch;
  30. import classes.Node;
  31. import classes.Position;
  32. import preferences.ColorPreference;
  33. import ui.controller.Control;
  34. import ui.controller.UpdateController;
  35. import ui.model.Consumer;
  36. import ui.model.DecoratedCable;
  37. import ui.model.DecoratedGroupNode;
  38. import ui.model.DecoratedHolonObject;
  39. import ui.model.DecoratedHolonObject.HolonObjectState;
  40. import ui.model.DecoratedSwitch;
  41. import ui.model.ExitCable;
  42. import ui.model.DecoratedSwitch.SwitchState;
  43. import util.ImageImport;
  44. import ui.model.Model;
  45. import ui.model.Passiv;
  46. import ui.model.Supplier;
  47. import ui.model.VisualRepresentationalState;
  48. /**
  49. * This Class is the Canvas. All Objects will be visualized here
  50. *
  51. * @author Gruppe14
  52. */
  53. public class MyCanvas extends AbstractCanvas implements MouseListener,
  54. MouseMotionListener {
  55. private static final long serialVersionUID = 1L;
  56. public boolean disabled = false;
  57. /**
  58. * Constructor.
  59. *
  60. * @param mod
  61. * the Model
  62. * @param control
  63. * the Controller
  64. * @param unitGraph
  65. */
  66. public MyCanvas(Model mod, Control control, UnitGraph unitGraph) {
  67. toolTip = false;
  68. this.controller = control;
  69. this.model = mod;
  70. scalediv20 = model.getScale() / 20;
  71. showConnectionInformation = true;
  72. showedInformation[1] = true;
  73. showedInformation[3] = false;
  74. showedInformation[4] = true;
  75. control.setMaxCapacity(10000);
  76. popmenu.add(itemCut);
  77. popmenu.add(itemCopy);
  78. popmenu.add(itemPaste);
  79. popmenu.add(itemDelete);
  80. popmenu.add(itemAlign);
  81. popmenu.addSeparator();
  82. popmenu.add(itemGroup);
  83. popmenu.add(itemUngroup);
  84. popmenu.add(itemCreateTemplate);
  85. updCon = new UpdateController(mod, control);
  86. itemDelete.setEnabled(false);
  87. itemCut.setEnabled(false);
  88. itemCopy.setEnabled(false);
  89. itemPaste.setEnabled(true);
  90. itemAlign.setEnabled(false);
  91. itemGroup.setEnabled(false);
  92. itemUngroup.setEnabled(false);
  93. itemCut.setText("Cut");
  94. itemGroup.addActionListener(actionEvent -> {
  95. // calculate uppernode pos (taken from the controller)
  96. unPos = new Position(0, 0);
  97. animCps = new ArrayList<>();
  98. for (AbstractCanvasObject cps : model.getSelectedCpsObjects()) {
  99. animCps.add(cps); // add to animation Cps ArrayList
  100. unPos.x += cps.getPosition().x;
  101. unPos.y += cps.getPosition().y;
  102. }
  103. unPos.x /= animCps.size();
  104. unPos.y /= animCps.size();
  105. // save old Position
  106. savePos = new ArrayList<>();
  107. for (int i = 0; i < animCps.size(); i++) {
  108. savePos.add(new Position(0, 0));
  109. savePos.get(i).x = animCps.get(i).getPosition().x;
  110. savePos.get(i).y = animCps.get(i).getPosition().y;
  111. }
  112. animT = new javax.swing.Timer(animDelay, actionEvent1 -> {
  113. if (animDuration - animDelay > 0 && animCps.size() > 1) {
  114. for (AbstractCanvasObject animCpObject : animCps) {
  115. double x1 = animCpObject.getPosition().x - unPos.x;
  116. double y1 = animCpObject.getPosition().y - unPos.y;
  117. animCpObject.getPosition().x -= x1 / animSteps;
  118. animCpObject.getPosition().y -= y1 / animSteps;
  119. }
  120. repaint();
  121. animDuration -= animDelay;
  122. animSteps--;
  123. } else {
  124. animDuration = ANIMTIME;
  125. animSteps = animDuration / animDelay;
  126. animT.stop();
  127. for (int i = 0; i < animCps.size(); i++) {
  128. animCps.get(i).getPosition().x = savePos.get(i).x;
  129. animCps.get(i).getPosition().y = savePos.get(i).y;
  130. }
  131. controller.addUpperNode("GroupNode", null, animCps);
  132. controller.calculateStateAndVisualForCurrentTimeStep();
  133. triggerUpdateController();
  134. controller.clearSelection();
  135. repaint();
  136. }
  137. });
  138. animT.start();
  139. });
  140. itemUngroup
  141. .addActionListener(actionEvent -> {
  142. // save old Position
  143. int upperNodeId = tempCps.getId();
  144. closeUpperNodeTab(upperNodeId);
  145. savePos = new ArrayList<>();
  146. animCps = ((GroupNode) tempCps).getNodes();
  147. controller.ungroupGroupNode((GroupNode) tempCps, null);
  148. for (int i = 0; i < animCps.size(); i++) {
  149. savePos.add(new Position(0, 0));
  150. savePos.get(i).x = animCps.get(i).getPosition().x;
  151. savePos.get(i).y = animCps.get(i).getPosition().y;
  152. }
  153. for (AbstractCanvasObject cps : animCps) {
  154. int x = tempCps.getPosition().x;
  155. int y = tempCps.getPosition().y;
  156. cps.setPosition(new Position(x, y));
  157. }
  158. animT = new javax.swing.Timer(
  159. animDelay,
  160. actionEvent1 -> {
  161. controller.clearSelection();
  162. if (animDuration - animDelay >= 0) {
  163. for (int i = 0; i < animCps.size(); i++) {
  164. Position pos = animCps.get(i).getPosition();
  165. double x1 = pos.x - savePos.get(i).x;
  166. double y1 = pos.y - savePos.get(i).y;
  167. animCps.get(i).getPosition().x -= x1 / animSteps;
  168. animCps.get(i).getPosition().y -= y1 / animSteps;
  169. }
  170. repaint();
  171. animDuration -= animDelay;
  172. animSteps--;
  173. } else {
  174. animDuration = ANIMTIME;
  175. animSteps = animDuration / animDelay;
  176. animT.stop();
  177. for (int i = 0; i < animCps.size(); i++) {
  178. animCps.get(i).getPosition().x = savePos
  179. .get(i).x;
  180. animCps.get(i).getPosition().y = savePos
  181. .get(i).y;
  182. }
  183. controller.calculateStateAndVisualForCurrentTimeStep();
  184. triggerUpdateController();
  185. repaint();
  186. }
  187. });
  188. animT.start();
  189. });
  190. // adds the selected object(s) to the statistic panel
  191. itemDelete.addActionListener(actionEvent -> {
  192. // Remove the selected Object objects
  193. //Edge Deleting
  194. if (tempCps == null && edgeHighlight != null) {
  195. controller.removeEdgesOnCanvas(edgeHighlight);
  196. //Look for a CPSNode with no Connections and delete them
  197. if(edgeHighlight.getA().getClass() == Node.class && edgeHighlight.getA().getConnections().size() == 0){
  198. controller.deleteCanvasObject(edgeHighlight.getA(), false);
  199. }
  200. if(edgeHighlight.getB().getClass() == Node.class && edgeHighlight.getB().getConnections().size() == 0){ //Look on the other end of the cable
  201. controller.deleteCanvasObject(edgeHighlight.getB(), false);
  202. }
  203. edgeHighlight = null;
  204. }
  205. boolean save = false;
  206. for (int j = 0; j < model.getSelectedCpsObjects().size(); j++) {
  207. AbstractCanvasObject cps = model.getSelectedCpsObjects()
  208. .get(j);
  209. if (j == model.getSelectedCpsObjects().size() - 1)
  210. save = true;
  211. controller.deleteCanvasObject(cps, save);
  212. // Remove UpperNodeTab if UpperNode deleted
  213. if (cps instanceof GroupNode) {
  214. JTabbedPane tabbedPane = (JTabbedPane)getParent().getParent()
  215. .getParent().getParent();
  216. // Look if the uppernode is open in a Tab
  217. for (int i = 4; i < tabbedPane.getTabCount(); i++) {
  218. if (tabbedPane.getComponentAt(i) != null
  219. && ((GroupNodeCanvas) ((JScrollPane) tabbedPane
  220. .getComponentAt(i)).getViewport()
  221. .getComponent(0)).upperNode.getId() == cps
  222. .getId()) {
  223. ((ButtonTabComponent) tabbedPane
  224. .getTabComponentAt(i)).removeTabs();
  225. break;
  226. }
  227. }
  228. }
  229. toolTip = false;
  230. }
  231. controller.clearSelection();
  232. tempCps = null;
  233. repaint();
  234. });
  235. itemCut.addActionListener(actionEvent -> {
  236. controller.cut(null);
  237. itemPaste.setEnabled(true);
  238. repaint();
  239. });
  240. itemCopy.addActionListener(actionEvent -> {
  241. if(tempCps instanceof GroupNode)
  242. controller.getObjectsInDepth();
  243. controller.copy(null);
  244. itemPaste.setEnabled(true);
  245. repaint();
  246. });
  247. itemAlign.addActionListener(actionEvent ->
  248. {
  249. for(AbstractCanvasObject cps: model.getSelectedCpsObjects())
  250. align(cps, model.getScaleDiv2());
  251. repaint();
  252. });
  253. itemPaste
  254. .addActionListener(actionEvent -> {
  255. try {
  256. controller.paste(null, mousePosition);
  257. } catch (JsonParseException | UnsupportedFlavorException
  258. | IOException e1) {
  259. JLabel message = new JLabel(
  260. "The Clipboard information cannot be pastet into Application.");
  261. JOptionPane.showMessageDialog(null, message, "",
  262. JOptionPane.ERROR_MESSAGE);
  263. }
  264. repaint();
  265. });
  266. /*
  267. * create Template
  268. */
  269. itemCreateTemplate.addActionListener(actionEvent -> {
  270. controller.createTemplate((HolonObject)tempCps,(JFrame)SwingUtilities.getRoot(this));
  271. });
  272. this.addMouseListener(this);
  273. this.addMouseMotionListener(this);
  274. }
  275. /**
  276. * Paints all Components on the Canvas.
  277. *
  278. * @param g
  279. * Graphics
  280. */
  281. public static Color getStateColor(HolonObjectState state) {
  282. switch(state) {
  283. case NOT_SUPPLIED:
  284. return ColorPreference.HolonObject.NotSupplied;
  285. case NO_ENERGY:
  286. return ColorPreference.HolonObject.NoEnergy;
  287. case OVER_SUPPLIED:
  288. return ColorPreference.HolonObject.OverSupplied;
  289. case PARTIALLY_SUPPLIED:
  290. return ColorPreference.HolonObject.PartiallySupplied;
  291. case PRODUCER:
  292. return ColorPreference.HolonObject.Producer;
  293. case SUPPLIED:
  294. return ColorPreference.HolonObject.Supplied;
  295. default:
  296. return Color.BLACK;
  297. }
  298. }
  299. private void paintCanvasObject(Graphics2D g, DecoratedHolonObject decoratedHolonObject){
  300. Position pos = decoratedHolonObject.getModel().getPosition();
  301. Color statecolor = getStateColor(decoratedHolonObject.getState());
  302. g.setColor(statecolor);
  303. g.fillRect(pos.x - controller.getScaleDiv2(), pos.y - controller.getScaleDiv2(), controller.getScale(), controller.getScale());
  304. drawCanvasObject(g, decoratedHolonObject.getModel().getImage(), pos);
  305. }
  306. private void drawCanvasObjectString(Graphics2D g, Position posOfCanvasObject, float energy) {
  307. g.setColor(Color.BLACK);
  308. g.setFont(new Font("TimesNewRoman", Font.PLAIN, (int) (controller.getScale() / 4f) ));
  309. g.drawString((energy > 0)? "+" + Float.toString(energy): Float.toString(energy), posOfCanvasObject.x - controller.getScaleDiv2(), posOfCanvasObject.y - controller.getScaleDiv2() - 1);
  310. }
  311. private void paintConsumer(Graphics2D g, Consumer con){
  312. paintCanvasObject(g, con);
  313. paintSupplyBar(g,con.getSupplyBarPercentage(), getStateColor(con.getState()), con.getModel().getPosition());
  314. drawCanvasObjectString(g, con.getModel().getPosition(), -con.getEnergyNeededFromNetwork());
  315. }
  316. private void paintSupplier(Graphics2D g, Supplier sup){
  317. paintCanvasObject(g, sup);
  318. drawCanvasObjectString(g, sup.getModel().getPosition(), sup.getEnergyToSupplyNetwork());
  319. }
  320. private void drawCanvasObject(Graphics2D g, String Image, Position pos) {
  321. g.drawImage(ImageImport.loadImage(Image, controller.getScale(), controller.getScale()) ,
  322. pos.x - controller.getScaleDiv2(),
  323. pos.y - controller.getScaleDiv2(),
  324. controller.getScale(), controller.getScale() , null);
  325. }
  326. private void paintCable(Graphics2D g, DecoratedCable cable, boolean isSelected)
  327. {
  328. Position start = cable.getModel().getA().getPosition();
  329. Position end = cable.getModel().getB().getPosition();
  330. float currentEnergy = cable.getFlowEnergy();
  331. float capacity = cable.getModel().getCapacity();
  332. boolean unlimited = cable.getModel().isUnlimitedCapacity();
  333. switch(cable.getState()) {
  334. case Burned:
  335. g.setColor(Color.RED);
  336. g.setStroke(new BasicStroke(2));
  337. break;
  338. case Working:
  339. g.setColor(new Color(13, 175, 28));
  340. g.setStroke(new BasicStroke(unlimited?2f:(currentEnergy / capacity * 2f) + 1));
  341. break;
  342. }
  343. if(isSelected){
  344. g.setColor(Color.lightGray);
  345. }
  346. g.drawLine(start.x, start.y, end.x, end.y);
  347. if(showConnectionInformation) {
  348. Position middle = new Position((start.x + end.x) / 2, (start.y + end.y) / 2);
  349. g.setFont(new Font("TimesRoman", Font.PLAIN, Math.max((int) (controller.getScale() / 3.5f), 10) ));
  350. g.drawString(currentEnergy + "/" + (unlimited?"\u221E":capacity) , middle.x, middle.y);
  351. }
  352. }
  353. private void paintSwitch(Graphics2D g, DecoratedSwitch dSwitch)
  354. {
  355. drawCanvasObject(g, dSwitch.getState() == SwitchState.Open ? HolonSwitch.getSwitchOpenImage(): HolonSwitch.getSwitchClosedImage() , dSwitch.getModel().getPosition());
  356. }
  357. private void paintExitCable(Graphics2D g, ExitCable eCable) {
  358. Position start = eCable.getStart().getPosition();
  359. Position end = eCable.getFinish().getPosition();
  360. float currentEnergy = eCable.getCable().getFlowEnergy();
  361. float capacity = eCable.getCable().getModel().getCapacity();
  362. boolean unlimited = eCable.getCable().getModel().isUnlimitedCapacity();
  363. switch(eCable.getCable().getState()) {
  364. case Burned:
  365. g.setColor(Color.RED);
  366. g.setStroke(new BasicStroke(2));
  367. break;
  368. case Working:
  369. g.setColor(new Color(13, 175, 28));
  370. g.setStroke(new BasicStroke(unlimited?2f:(currentEnergy / capacity * 2f) + 1));
  371. break;
  372. }
  373. g.drawLine(start.x, start.y, end.x, end.y);
  374. Position middle = new Position((start.x + end.x) / 2, (start.y + end.y) / 2);
  375. g.setFont(new Font("TimesRoman", Font.PLAIN, Math.max((int) (controller.getScale() / 3.5f), 10) ));
  376. g.drawString(currentEnergy + "/" + (unlimited?"\u221E":capacity) , middle.x, middle.y);
  377. }
  378. private void paintGroupNode(Graphics2D g, DecoratedGroupNode dGroupNode) {
  379. Position pos = dGroupNode.getModel().getPosition();
  380. g.setColor(Color.lightGray);
  381. g.fillRect(pos.x - controller.getScaleDiv2(), pos.y - controller.getScaleDiv2(), controller.getScale(), controller.getScale());
  382. drawCanvasObject(g, "/Images/upper_node.png" , pos);
  383. paintGroupNodeBar(g, dGroupNode, pos);
  384. }
  385. private void paintGroupNodeBar(Graphics2D g, DecoratedGroupNode dGroupNode , Position pos) {
  386. // +1, -2, -1 little Adjustment for pixel perfect alignment
  387. int barWidth = (int) (controller.getScale());
  388. int barHeight = (int) (controller.getScale() / 5);
  389. g.setColor(Color.WHITE);
  390. g.fillRect(pos.x - controller.getScaleDiv2(), pos.y + controller.getScaleDiv2() - 1, (int) barWidth, barHeight);
  391. float[] percentages = getGroupNodeBarPercentages(dGroupNode);
  392. Color[] colors = new Color[6];
  393. colors[0] = getStateColor(HolonObjectState.PRODUCER);
  394. colors[1] = getStateColor(HolonObjectState.NOT_SUPPLIED);
  395. colors[2] = getStateColor(HolonObjectState.PARTIALLY_SUPPLIED);
  396. colors[3] = getStateColor(HolonObjectState.SUPPLIED);
  397. colors[4] = getStateColor(HolonObjectState.OVER_SUPPLIED);
  398. colors[5] = getStateColor(HolonObjectState.NO_ENERGY);
  399. for(int i = 5; i>=0; i--) {
  400. g.setColor(colors[i]);
  401. g.fillRect(pos.x - controller.getScaleDiv2(), pos.y + controller.getScaleDiv2() - 1, (int) (barWidth * percentages[i] - 1), barHeight);
  402. }
  403. // g.setColor(color);
  404. // g.fillRect(pos.x - controller.getScaleDiv2(), pos.y + controller.getScaleDiv2() - 1, (int) (barWidth * (percentage < 1 ? percentage : 1.0f) - 1), barHeight);
  405. g.setColor(Color.BLACK);
  406. g.setStroke(new BasicStroke(1));
  407. g.drawRect(pos.x - controller.getScaleDiv2(), pos.y + controller.getScaleDiv2() - 1, barWidth - 1 , barHeight);
  408. }
  409. /**
  410. * HardCoded Stuff dont try at Home ;)
  411. * @param dGroupNode
  412. * @return
  413. */
  414. public float[] getGroupNodeBarPercentages(DecoratedGroupNode dGroupNode) {
  415. int[] amountOfObjects = new int[6];
  416. amountOfObjects[0] = dGroupNode.getAmountOfSupplier();
  417. amountOfObjects[1] = dGroupNode.getAmountOfConsumerWithState(HolonObjectState.NOT_SUPPLIED);
  418. amountOfObjects[2] = dGroupNode.getAmountOfConsumerWithState(HolonObjectState.PARTIALLY_SUPPLIED);
  419. amountOfObjects[3] = dGroupNode.getAmountOfConsumerWithState(HolonObjectState.SUPPLIED);
  420. amountOfObjects[4] = dGroupNode.getAmountOfConsumerWithState(HolonObjectState.OVER_SUPPLIED);
  421. amountOfObjects[5] = dGroupNode.getAmountOfPassiv();
  422. int countHolonObjects = amountOfObjects[0] + amountOfObjects[1] + amountOfObjects[2] + amountOfObjects[3] + amountOfObjects[4] + amountOfObjects[5];
  423. float[] percentages = new float[6];
  424. int count = 0;
  425. for(int i = 0; i < 6; i++) {
  426. count += amountOfObjects[i];
  427. percentages[i] = (float)count / (float)countHolonObjects;
  428. }
  429. return percentages;
  430. }
  431. private void paintSupplyBar(Graphics2D g, float percentage, Color color, Position pos) {
  432. // +1, -2, -1 little Adjustment for pixel perfect alignment
  433. int barWidth = (int) (controller.getScale());
  434. int barHeight = (int) (controller.getScale() / 5);
  435. g.setColor(Color.WHITE);
  436. g.fillRect(pos.x - controller.getScaleDiv2(), pos.y + controller.getScaleDiv2() - 1, (int) barWidth, barHeight);
  437. g.setColor(color);
  438. g.fillRect(pos.x - controller.getScaleDiv2(), pos.y + controller.getScaleDiv2() - 1, (int) (barWidth * (percentage < 1 ? percentage : 1.0f) - 1), barHeight);
  439. g.setColor(Color.BLACK);
  440. g.setStroke(new BasicStroke(1));
  441. g.drawRect(pos.x - controller.getScaleDiv2(), pos.y + controller.getScaleDiv2() - 1, barWidth - 1 , barHeight);
  442. g.setFont(new Font("TimesNewRoman", Font.PLAIN, (int) (barHeight * 1.5) - 2));
  443. String percentageString = (Math.round((percentage * 100))) + "%";
  444. int stringWidth = (int) g.getFontMetrics().getStringBounds(percentageString, g).getWidth();
  445. if(percentage > 1.0f) g.setColor(Color.WHITE); //Just to see better on purple
  446. g.drawString(percentageString, pos.x + 1 - stringWidth / 2, pos.y + controller.getScaleDiv2() - 1+ barHeight);
  447. }
  448. //old code
  449. void drawMarker(Graphics2D g) {
  450. Color transparentGrey = new Color(128, 174, 247, 40);
  451. if (sx > x && sy > y) {
  452. g.drawRect(x, y, sx - x, sy - y);
  453. g.setColor(transparentGrey);
  454. g.fillRect(x, y, sx - x, sy - y);
  455. } else if (sx < x && sy < y) {
  456. g.drawRect(sx, sy, x - sx, y - sy);
  457. g.setColor(transparentGrey);
  458. g.fillRect(sx, sy, x - sx, y - sy);
  459. } else if (sx >= x) {
  460. g.drawRect(x, sy, sx - x, y - sy);
  461. g.setColor(transparentGrey);
  462. g.fillRect(x, sy, sx - x, y - sy);
  463. } else if (sy >= y) {
  464. g.drawRect(sx, y, x - sx, sy - y);
  465. g.setColor(transparentGrey);
  466. g.fillRect(sx, y, x - sx, sy - y);
  467. }
  468. }
  469. public void paintComponent(Graphics g) {
  470. super.paintComponent(g);
  471. Graphics2D g2d = (Graphics2D) g;
  472. g2d.setRenderingHints(new RenderingHints(RenderingHints.KEY_ANTIALIASING,
  473. RenderingHints.VALUE_ANTIALIAS_ON));
  474. //-->Old code
  475. if (drawEdge) {
  476. g2d.setColor(Color.BLACK);
  477. g2d.setStroke(new BasicStroke(1));
  478. g2d.drawLine(tempCps.getPosition().x, tempCps.getPosition().y, x, y);
  479. }
  480. //<--
  481. //SelectedCable
  482. HashSet<Edge> selectedEdges = new HashSet<Edge>();
  483. for(AbstractCanvasObject aCps: model.getSelectedCpsObjects()) {
  484. for(Edge edge: aCps.getConnections()) {
  485. selectedEdges.add(edge);
  486. }
  487. }
  488. if(model.getSelectedEdge() != null) selectedEdges.add(model.getSelectedEdge());
  489. //timstep:
  490. g.setFont(new Font("TimesNewRoman", Font.PLAIN, Math.max((int) (controller.getScale() / 3.5f), 10) ));
  491. g2d.setColor(Color.BLACK);
  492. VisualRepresentationalState visualState = controller.getSimManager().getActualVisualRepresentationalState();
  493. //VisualState Representation:
  494. if(visualState == null) System.out.println("AHHH");
  495. for(ExitCable cable : visualState.getExitCableList()) {
  496. paintExitCable(g2d, cable);
  497. }
  498. for(DecoratedCable cable : visualState.getCableList()) {
  499. paintCable(g2d, cable, selectedEdges.contains(cable.getModel()));
  500. }
  501. for(DecoratedGroupNode dGroupNode : visualState.getGroupNodeList()) {
  502. paintGroupNode(g2d, dGroupNode);
  503. }
  504. for(Consumer con: visualState.getConsumerList()) {
  505. paintConsumer(g2d, con);
  506. }
  507. for(Supplier sup: visualState.getSupplierList()) {
  508. paintSupplier(g2d, sup);
  509. }
  510. for(Passiv pas: visualState.getPassivList()) {
  511. paintCanvasObject(g2d, pas);
  512. }
  513. for(DecoratedSwitch dSwitch : visualState.getSwitchList()) {
  514. paintSwitch(g2d, dSwitch);
  515. }
  516. for(Node node : visualState.getNodeList()) {
  517. drawCanvasObject(g2d, "/Images/node.png" , node.getPosition());
  518. }
  519. //-->oldCode
  520. if (doMark) {
  521. g2d.setColor(Color.BLACK);
  522. g2d.setStroke(new BasicStroke(0));
  523. drawMarker(g2d);
  524. }
  525. //Test Selection
  526. //Objects:
  527. g2d.setColor(Color.BLUE);
  528. g2d.setStroke(new BasicStroke(1));
  529. Color transparentGrey = new Color(128, 174, 247, 40);
  530. for(AbstractCanvasObject aCps: model.getSelectedCpsObjects()) {
  531. if(aCps instanceof Node) {
  532. Position pos = aCps.getPosition();
  533. g2d.setColor(transparentGrey);
  534. g2d.fillOval(pos.x - (int) (controller.getScaleDiv2()), pos.y - (int) (controller.getScaleDiv2()), controller.getScale(), controller.getScale());
  535. g2d.setColor(Color.LIGHT_GRAY);
  536. g2d.setStroke(new BasicStroke(2));
  537. g2d.drawOval(pos.x - (int) (controller.getScaleDiv2()), pos.y - (int) (controller.getScaleDiv2()), controller.getScale(), controller.getScale());
  538. }
  539. else {
  540. Position pos = aCps.getPosition();
  541. g2d.setColor(transparentGrey);
  542. g2d.fillRect(pos.x - (int) (controller.getScaleDiv2()* 1.5f), pos.y - (int) (controller.getScaleDiv2()* 1.5f), (int) (controller.getScale()* 1.5f) , (int) (controller.getScale()* 1.5f));
  543. g2d.setColor(Color.LIGHT_GRAY);
  544. g2d.setStroke(new BasicStroke(2));
  545. g2d.drawRect(pos.x - (int) (controller.getScaleDiv2()* 1.5f), pos.y - (int) (controller.getScaleDiv2()* 1.5f), (int) (controller.getScale()* 1.5f) , (int) (controller.getScale()* 1.5f));
  546. }
  547. }
  548. //maybeReplace:
  549. if(mayBeReplaced != null){
  550. g2d.setColor(Color.RED);
  551. Position pos = mayBeReplaced.getPosition();
  552. g2d.drawImage(ImageImport.loadImage("/Images/replace.png") ,
  553. pos.x + controller.getScaleDiv2(),
  554. pos.y - controller.getScale(),
  555. controller.getScaleDiv2(), controller.getScaleDiv2(), null);
  556. }
  557. //<-- OldCode
  558. }
  559. @Override
  560. public void mouseClicked(MouseEvent e) {
  561. if(!disabled){
  562. if (e.getButton() == MouseEvent.BUTTON1) {
  563. DefaulTable propertyTable = model.getPropertyTable();
  564. if (propertyTable.getRowCount() > 0) {
  565. for (int i = propertyTable.getRowCount() - 1; i > -1; i--) {
  566. propertyTable.removeRow(i);
  567. }
  568. }
  569. triggerUpdateController();
  570. }
  571. stopEditing();
  572. }
  573. }
  574. @Override
  575. public void mouseEntered(MouseEvent e) {
  576. }
  577. @Override
  578. public void mouseExited(MouseEvent e) {
  579. }
  580. @Override
  581. public void mousePressed(MouseEvent e) {
  582. if(!disabled){
  583. stopEditing();
  584. tempCps = null;
  585. edgeHighlight = null;
  586. controller.setSelecteEdge(null);
  587. // Object Selection
  588. for (AbstractCanvasObject cps : model.getObjectsOnCanvas()) {
  589. cx = cps.getPosition().x - controller.getScaleDiv2();
  590. cy = cps.getPosition().y - controller.getScaleDiv2();
  591. if (x - controller.getScale() <= cx
  592. && y - controller.getScale() <= cy && x >= cx && y >= cy) {
  593. tempCps = cps;
  594. dragging = true;
  595. if (e.isControlDown() && tempCps != null) {
  596. if (model.getSelectedCpsObjects().contains(tempCps)) {
  597. controller.removeSelectedObjectFromSelection(tempCps);
  598. //TODO: RemoveDepth
  599. } else {
  600. controller.addSelectedObject(tempCps);
  601. if(tempCps instanceof GroupNode)
  602. controller.getObjectsInDepth();
  603. }
  604. }
  605. // If drawing an Edge (CTRL down)
  606. if (tempCps.getClass() == HolonObject.class) {
  607. HolonObject tempObj = ((HolonObject) tempCps);
  608. dataSelected = tempObj.getElements();
  609. }
  610. if (e.isShiftDown()) {
  611. drawEdge = true;
  612. dragging = false;
  613. }
  614. }
  615. }
  616. // Edge Selection
  617. if (tempCps == null) {
  618. edgeHighlight = mousePositionOnEdge(x, y);
  619. controller.setSelecteEdge(edgeHighlight);
  620. controller.setSelectedObjectID(0);
  621. if (!e.isControlDown() && e.getButton() != MouseEvent.BUTTON3) {
  622. controller.clearSelection();
  623. }
  624. }
  625. if (edgeHighlight == null && tempCps == null) {
  626. sx = e.getX();
  627. sy = e.getY();
  628. doMark = true;
  629. }
  630. repaint();
  631. }
  632. }
  633. @Override
  634. public void mouseReleased(MouseEvent e) {
  635. if(!disabled){
  636. x = e.getX();
  637. y = e.getY();
  638. dragging = false;
  639. if (drawEdge) {
  640. drawEdge = false;
  641. drawDeleteEdge();
  642. }
  643. if (dragged) {
  644. try {
  645. /**
  646. * Save before further Dragged interactions happen
  647. */
  648. controller.autoSave();
  649. } catch (IOException ex) {
  650. System.err.println("AutoSave error by dragging");
  651. ex.printStackTrace();
  652. }
  653. /**
  654. * check if a unique tempCps could replace an Object on the canvas
  655. */
  656. if(model.getSelectedCpsObjects().size()==1
  657. && checkForReplacement(model.getObjectsOnCanvas(), tempCps, tempCps.getPosition().x, tempCps.getPosition().y)){
  658. /**
  659. * if UpperNode would be replaced, close its tabs
  660. */
  661. if(mayBeReplaced instanceof GroupNode)
  662. closeUpperNodeTab(mayBeReplaced.getId());
  663. /**
  664. * replace on canvas (will save)
  665. */
  666. controller.replaceCanvasObject(mayBeReplaced, tempCps);
  667. mayBeReplaced=null;
  668. }
  669. }
  670. if (!e.isControlDown() && !dragged && tempCps != null
  671. && MouseEvent.BUTTON3 != e.getButton()) {
  672. controller.clearSelection();
  673. controller.addSelectedObject(tempCps);
  674. if(tempCps instanceof GroupNode)
  675. controller.getObjectsInDepth();
  676. }
  677. dragged = false;
  678. // Rightclick List
  679. setRightClickMenu(e);
  680. markObjects();
  681. if (doubleClick() && tempCps instanceof HolonSwitch
  682. && MouseEvent.BUTTON3 != e.getButton()&& tempCps != null) {
  683. ((HolonSwitch) tempCps).switchState();
  684. }
  685. controller.calculateStateAndVisualForTimeStep(model.getCurIteration());
  686. triggerUpdateController();
  687. repaint();
  688. }
  689. }
  690. @Override
  691. public void mouseDragged(MouseEvent e) {
  692. if(!disabled){
  693. // If Edge is drawn
  694. x = e.getX();
  695. y = e.getY();
  696. if (!model.getSelectedCpsObjects().contains(tempCps) && !doMark) {
  697. controller.clearSelection();
  698. if (tempCps != null) {
  699. controller.addSelectedObject(tempCps);
  700. }
  701. }
  702. if (dragging) {
  703. try {
  704. dragged = true;
  705. float xDist, yDist; // Distance
  706. x = e.getX();
  707. y = e.getY();
  708. // Make sure its in bounds
  709. int scaleDiv2 = controller.getScaleDiv2();
  710. if (e.getX() < scaleDiv2)
  711. x = scaleDiv2;
  712. else if (e.getX() > this.getWidth() - scaleDiv2)
  713. x = this.getWidth() - scaleDiv2;
  714. if (e.getY() < scaleDiv2)
  715. y = scaleDiv2;
  716. else if (e.getY() > this.getHeight()
  717. - scaleDiv2)
  718. y = this.getHeight() - scaleDiv2;
  719. // Distance
  720. xDist = x - tempCps.getPosition().x;
  721. yDist = y - tempCps.getPosition().y;
  722. tempCps.setPosition(x, y); // Drag Position
  723. // ToolTipText Position and name
  724. toolTip = true;
  725. toolTipText = tempCps.getName() + ", " + tempCps.getId();
  726. toolTipPos.x = tempCps.getPosition().x
  727. - scaleDiv2;
  728. toolTipPos.y = tempCps.getPosition().y
  729. + scaleDiv2;
  730. // All Selected Objects
  731. for (AbstractCanvasObject cps : model.getSelectedCpsObjects()) {
  732. if (cps != tempCps) {
  733. x = (int) (cps.getPosition().x + xDist);
  734. y = (int) (cps.getPosition().y + yDist);
  735. // Make sure its in bounds
  736. if (x <= scaleDiv2)
  737. x = scaleDiv2;
  738. else if (x > this.getWidth()
  739. - scaleDiv2)
  740. x = this.getWidth() - scaleDiv2;
  741. if (y <= scaleDiv2)
  742. y = scaleDiv2;
  743. else if (y > this.getHeight()
  744. - scaleDiv2)
  745. y = this.getHeight() - scaleDiv2;
  746. cps.setPosition(x, y);
  747. }
  748. }
  749. /**
  750. * check if something might be replaced
  751. */
  752. if(model.getSelectedCpsObjects().size()==1)
  753. checkForReplacement(model.getObjectsOnCanvas(), tempCps, x, y);
  754. repaint();
  755. } catch (Exception eex) {
  756. }
  757. }
  758. // Mark Objects
  759. if (doMark) {
  760. tempSelected.clear();
  761. for (AbstractCanvasObject cps : model.getObjectsOnCanvas()) {
  762. int x1 = sx, x2 = x, y1 = sy, y2 = y;
  763. if (sx >= x) {
  764. x1 = x;
  765. x2 = sx;
  766. }
  767. if (sy >= y) {
  768. y1 = y;
  769. y2 = sy;
  770. }
  771. if (x1 <= cps.getPosition().x + model.getScaleDiv2()
  772. && y1 <= cps.getPosition().y + model.getScaleDiv2()
  773. && x2 >= cps.getPosition().x
  774. && y2 >= cps.getPosition().y) {
  775. tempSelected.add(cps);
  776. }
  777. }
  778. }
  779. repaint();
  780. }
  781. }
  782. @Override
  783. public void mouseMoved(MouseEvent e) {
  784. if(!disabled){
  785. x = e.getX();
  786. y = e.getY();
  787. // Everything for the tooltip :)
  788. boolean on = false;
  789. for (AbstractCanvasObject cps : model.getObjectsOnCanvas()) {
  790. cx = cps.getPosition().x - controller.getScaleDiv2();
  791. cy = cps.getPosition().y - controller.getScaleDiv2();
  792. on = setToolTipInfoAndPosition(on, cps);
  793. }
  794. if(on||(!on && toolTip))
  795. repaint();
  796. toolTip = on;
  797. }
  798. }
  799. /**
  800. * Draws or Deletes an Edge.
  801. */
  802. void drawDeleteEdge() {
  803. if (getMousePosition() != null) {
  804. boolean node = true;
  805. boolean newEdge = true;
  806. boolean onEdge = true;
  807. boolean deleteNode = false;
  808. Edge e = null;
  809. for (AbstractCanvasObject cps : model.getObjectsOnCanvas()) {
  810. cx = cps.getPosition().x - controller.getScaleDiv2();
  811. cy = cps.getPosition().y - controller.getScaleDiv2();
  812. if (x - controller.getScale() <= cx
  813. && y - controller.getScale() <= cy && x >= cx
  814. && y >= cy && cps != tempCps) {
  815. node = false;
  816. onEdge = false;
  817. for (Edge p : tempCps.getConnections()) {
  818. if ((p.getA() == tempCps && p.getB() == cps)
  819. || (p.getB() == tempCps && p.getA() == cps)) {
  820. newEdge = false;
  821. e = p;
  822. }
  823. }
  824. if (!newEdge) {
  825. controller.removeEdgesOnCanvas(e);
  826. // Node ohne Edge?
  827. if (e.getA().getClass() == Node.class
  828. && e.getA().getConnections().isEmpty()) {
  829. tempCps = e.getA();
  830. deleteNode = true;
  831. }
  832. if (e.getB().getClass() == Node.class
  833. && e.getB().getConnections().isEmpty()) {
  834. deleteNode = true;
  835. }
  836. } else {
  837. if(!(cps instanceof GroupNode || tempCps instanceof GroupNode)) {
  838. e = new Edge(cps, tempCps, model.getMaxCapacity());
  839. controller.addEdgeOnCanvas(e);
  840. }else if (cps instanceof GroupNode && !(tempCps instanceof GroupNode)){
  841. GroupNode thisUpperNode = (GroupNode)cps;
  842. Object[] possibilities = thisUpperNode.getNodes().stream().map(aCps -> new ACpsHandle(aCps)).filter(aCpsHandle -> !(aCpsHandle.object instanceof GroupNode)).toArray();
  843. if(possibilities.length != 0) {
  844. ACpsHandle selected = (ACpsHandle) JOptionPane.showInputDialog(this, "Select a inside Object:", "Connection To?", JOptionPane.OK_OPTION,new ImageIcon(new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB)) , possibilities, "");
  845. if(selected != null) {
  846. e = new Edge(selected.object, tempCps, model.getMaxCapacity());
  847. controller.addEdgeOnCanvas(e);
  848. }
  849. }else {
  850. Node n = new Node("Node");
  851. n.setPosition(x, y);
  852. controller.addObjUpperNode(n, thisUpperNode);
  853. e = new Edge(n, tempCps, model.getMaxCapacity());
  854. controller.addEdgeOnCanvas(e);
  855. }
  856. }
  857. }
  858. }
  859. }
  860. // Edge auf eine Edge gezogen?
  861. if (onEdge && !checkForReplacement(x, y)) {
  862. Edge p = mousePositionOnEdge(x, y);
  863. if (p != null) {
  864. Edge e1;
  865. Edge e2;
  866. node = false;
  867. Node n = new Node("Node");
  868. n.setPosition(x, y);
  869. controller.addObjectCanvas(n);
  870. AbstractCanvasObject r, k;
  871. r = p.getA();
  872. k = p.getB();
  873. e = new Edge(n, tempCps, model.getMaxCapacity());
  874. e1 = new Edge(n, r, model.getMaxCapacity());
  875. e2 = new Edge(n, k, model.getMaxCapacity());
  876. controller.removeEdgesOnCanvas(p);
  877. controller.addEdgeOnCanvas(e);
  878. controller.addEdgeOnCanvas(e1);
  879. controller.addEdgeOnCanvas(e2);
  880. }
  881. }else{
  882. mayBeReplaced = null;
  883. }
  884. // ins leere Gedragged
  885. if (node && !checkForReplacement(x, y)) {
  886. Node n = new Node("Node");
  887. n.setPosition(x, y);
  888. controller.addObjectCanvas(n);
  889. e = new Edge(n, tempCps, model.getMaxCapacity());
  890. controller.addEdgeOnCanvas(e);
  891. }else{
  892. mayBeReplaced = null;
  893. }
  894. // Wenn ein Node ohne Connections da ist
  895. if (deleteNode) {
  896. controller.deleteCanvasObject(tempCps, true);
  897. tempCps = null;
  898. }
  899. }
  900. }
  901. /**
  902. * Checks if the mouse is on an Edge.
  903. *
  904. * @param x
  905. * Position of the Mouse
  906. * @param y
  907. * Position of the Mouse
  908. * @return CpsEdge the Mouse is on, null if the mouse is not on an Edge
  909. */
  910. private Edge mousePositionOnEdge(int x, int y) {
  911. x += controller.getScaleDiv2();
  912. y += controller.getScaleDiv2();
  913. for (Edge p : model.getEdgesOnCanvas()) {
  914. Line2D l = new Line2D.Float(p.getA().getPosition().x, p.getA()
  915. .getPosition().y, p.getB().getPosition().x, p.getB()
  916. .getPosition().y);
  917. int[] positions = determineMousePositionOnEdge(p);
  918. int lx = positions[0];
  919. int ly = positions[1];
  920. int hx = positions[2];
  921. int hy = positions[3];
  922. // distance from a point to a line and between both Objects
  923. if (l.ptLineDistSq(x - model.getScaleDiv2(),
  924. y - model.getScaleDiv2()) < 20
  925. && x > lx && x < hx && y > ly && y < hy) {
  926. return p;
  927. }
  928. }
  929. return null;
  930. }
  931. void updateLanguages() {
  932. itemCut.setText("Cut");
  933. itemCopy.setText("Copy");
  934. itemPaste.setText("Paste");
  935. itemDelete.setText("Delete");
  936. itemGroup.setText("Group");
  937. itemUngroup.setText("Ungroup");
  938. }
  939. /**
  940. * Set if Information should be shown.
  941. *
  942. * @param connection
  943. * boolean for conecction
  944. * @param object
  945. * boolean for objects
  946. * @param nodeOfnode
  947. */
  948. void setShowedInformation(boolean connection, boolean object,
  949. boolean border, boolean nodeOfnode) {
  950. showConnectionInformation = connection;
  951. showedInformation[1] = object;
  952. showedInformation[3] = border;
  953. showedInformation[4] = nodeOfnode;
  954. }
  955. /**
  956. * Returns if Information should be shown.
  957. *
  958. * @return Array of boolean [0] = connection, [1] = objects
  959. */
  960. boolean[] getShowedInformation() {
  961. return showedInformation;
  962. }
  963. /**
  964. * set toolTip
  965. *
  966. * @param bool
  967. */
  968. void setToolTip(boolean bool) {
  969. this.toolTip = bool;
  970. }
  971. /**
  972. * Set the Mouse
  973. *
  974. * @param x
  975. * @param y
  976. */
  977. void setXY(int x, int y) {
  978. this.x = x;
  979. this.y = y;
  980. }
  981. @Override
  982. public boolean checkForReplacement(int x, int y) {
  983. return checkForReplacement(model.getObjectsOnCanvas(), null, x, y);
  984. }
  985. @Override
  986. public void tryToAlignObjects(){
  987. /**
  988. * Align all Objects
  989. */
  990. for(AbstractCanvasObject cps: model.getObjectsOnCanvas())
  991. align(cps,3*model.getScaleDiv2());
  992. /**
  993. * AutoSave new Positons
  994. */
  995. try{
  996. controller.autoSave();
  997. } catch (IOException ex) {
  998. System.err.println("AutoSave error by aligning");
  999. ex.printStackTrace();
  1000. }
  1001. }
  1002. @Override
  1003. public void closeUpperNodeTab(int upperNodeId) {
  1004. JTabbedPane tabbedPaneInner = (JTabbedPane) getParent()
  1005. .getParent().getParent().getParent();
  1006. for (int i = 1; i < tabbedPaneInner.getTabCount(); i++) {
  1007. if (((GroupNodeCanvas) ((JScrollPane) tabbedPaneInner
  1008. .getComponentAt(i)).getViewport().getComponent(
  1009. 0)).upperNode.getId() == upperNodeId) {
  1010. tabbedPaneInner.remove(i);
  1011. break;
  1012. }
  1013. }
  1014. }
  1015. }