MyCanvas.java 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140
  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. case Unused:
  343. g.setColor(Color.blue);
  344. g.setStroke(new BasicStroke(unlimited?2f:(currentEnergy / capacity * 2f) + 1));
  345. break;
  346. }
  347. if(isSelected){
  348. g.setColor(Color.lightGray);
  349. }
  350. g.drawLine(start.x, start.y, end.x, end.y);
  351. if(showConnectionInformation) {
  352. Position middle = new Position((start.x + end.x) / 2, (start.y + end.y) / 2);
  353. g.setFont(new Font("TimesRoman", Font.PLAIN, Math.max((int) (controller.getScale() / 3.5f), 10) ));
  354. g.drawString(currentEnergy + "/" + (unlimited?"\u221E":capacity) , middle.x, middle.y);
  355. }
  356. }
  357. private void paintSwitch(Graphics2D g, DecoratedSwitch dSwitch)
  358. {
  359. drawCanvasObject(g, dSwitch.getState() == SwitchState.Open ? HolonSwitch.getSwitchOpenImage(): HolonSwitch.getSwitchClosedImage() , dSwitch.getModel().getPosition());
  360. }
  361. private void paintExitCable(Graphics2D g, ExitCable eCable) {
  362. Position start = eCable.getStart().getPosition();
  363. Position end = eCable.getFinish().getPosition();
  364. float currentEnergy = eCable.getCable().getFlowEnergy();
  365. float capacity = eCable.getCable().getModel().getCapacity();
  366. boolean unlimited = eCable.getCable().getModel().isUnlimitedCapacity();
  367. switch(eCable.getCable().getState()) {
  368. case Burned:
  369. g.setColor(Color.RED);
  370. g.setStroke(new BasicStroke(2));
  371. break;
  372. case Working:
  373. g.setColor(new Color(13, 175, 28));
  374. g.setStroke(new BasicStroke(unlimited?2f:(currentEnergy / capacity * 2f) + 1));
  375. break;
  376. }
  377. g.drawLine(start.x, start.y, end.x, end.y);
  378. Position middle = new Position((start.x + end.x) / 2, (start.y + end.y) / 2);
  379. g.setFont(new Font("TimesRoman", Font.PLAIN, Math.max((int) (controller.getScale() / 3.5f), 10) ));
  380. g.drawString(currentEnergy + "/" + (unlimited?"\u221E":capacity) , middle.x, middle.y);
  381. }
  382. private void paintGroupNode(Graphics2D g, DecoratedGroupNode dGroupNode) {
  383. Position pos = dGroupNode.getModel().getPosition();
  384. g.setColor(Color.lightGray);
  385. g.fillRect(pos.x - controller.getScaleDiv2(), pos.y - controller.getScaleDiv2(), controller.getScale(), controller.getScale());
  386. drawCanvasObject(g, "/Images/upper_node.png" , pos);
  387. paintGroupNodeBar(g, dGroupNode, pos);
  388. }
  389. private void paintGroupNodeBar(Graphics2D g, DecoratedGroupNode dGroupNode , Position pos) {
  390. // +1, -2, -1 little Adjustment for pixel perfect alignment
  391. int barWidth = (int) (controller.getScale());
  392. int barHeight = (int) (controller.getScale() / 5);
  393. g.setColor(Color.WHITE);
  394. g.fillRect(pos.x - controller.getScaleDiv2(), pos.y + controller.getScaleDiv2() - 1, (int) barWidth, barHeight);
  395. float[] percentages = getGroupNodeBarPercentages(dGroupNode);
  396. Color[] colors = new Color[6];
  397. colors[0] = getStateColor(HolonObjectState.PRODUCER);
  398. colors[1] = getStateColor(HolonObjectState.NOT_SUPPLIED);
  399. colors[2] = getStateColor(HolonObjectState.PARTIALLY_SUPPLIED);
  400. colors[3] = getStateColor(HolonObjectState.SUPPLIED);
  401. colors[4] = getStateColor(HolonObjectState.OVER_SUPPLIED);
  402. colors[5] = getStateColor(HolonObjectState.NO_ENERGY);
  403. for(int i = 5; i>=0; i--) {
  404. g.setColor(colors[i]);
  405. g.fillRect(pos.x - controller.getScaleDiv2(), pos.y + controller.getScaleDiv2() - 1, (int) (barWidth * percentages[i] - 1), barHeight);
  406. }
  407. // g.setColor(color);
  408. // g.fillRect(pos.x - controller.getScaleDiv2(), pos.y + controller.getScaleDiv2() - 1, (int) (barWidth * (percentage < 1 ? percentage : 1.0f) - 1), barHeight);
  409. g.setColor(Color.BLACK);
  410. g.setStroke(new BasicStroke(1));
  411. g.drawRect(pos.x - controller.getScaleDiv2(), pos.y + controller.getScaleDiv2() - 1, barWidth - 1 , barHeight);
  412. }
  413. /**
  414. * HardCoded Stuff dont try at Home ;)
  415. * @param dGroupNode
  416. * @return
  417. */
  418. public float[] getGroupNodeBarPercentages(DecoratedGroupNode dGroupNode) {
  419. int[] amountOfObjects = new int[6];
  420. amountOfObjects[0] = dGroupNode.getAmountOfSupplier();
  421. amountOfObjects[1] = dGroupNode.getAmountOfConsumerWithState(HolonObjectState.NOT_SUPPLIED);
  422. amountOfObjects[2] = dGroupNode.getAmountOfConsumerWithState(HolonObjectState.PARTIALLY_SUPPLIED);
  423. amountOfObjects[3] = dGroupNode.getAmountOfConsumerWithState(HolonObjectState.SUPPLIED);
  424. amountOfObjects[4] = dGroupNode.getAmountOfConsumerWithState(HolonObjectState.OVER_SUPPLIED);
  425. amountOfObjects[5] = dGroupNode.getAmountOfPassiv();
  426. int countHolonObjects = amountOfObjects[0] + amountOfObjects[1] + amountOfObjects[2] + amountOfObjects[3] + amountOfObjects[4] + amountOfObjects[5];
  427. float[] percentages = new float[6];
  428. int count = 0;
  429. for(int i = 0; i < 6; i++) {
  430. count += amountOfObjects[i];
  431. percentages[i] = (float)count / (float)countHolonObjects;
  432. }
  433. return percentages;
  434. }
  435. private void paintSupplyBar(Graphics2D g, float percentage, Color color, Position pos) {
  436. // +1, -2, -1 little Adjustment for pixel perfect alignment
  437. int barWidth = (int) (controller.getScale());
  438. int barHeight = (int) (controller.getScale() / 5);
  439. g.setColor(Color.WHITE);
  440. g.fillRect(pos.x - controller.getScaleDiv2(), pos.y + controller.getScaleDiv2() - 1, (int) barWidth, barHeight);
  441. g.setColor(color);
  442. g.fillRect(pos.x - controller.getScaleDiv2(), pos.y + controller.getScaleDiv2() - 1, (int) (barWidth * (percentage < 1 ? percentage : 1.0f) - 1), barHeight);
  443. g.setColor(Color.BLACK);
  444. g.setStroke(new BasicStroke(1));
  445. g.drawRect(pos.x - controller.getScaleDiv2(), pos.y + controller.getScaleDiv2() - 1, barWidth - 1 , barHeight);
  446. g.setFont(new Font("TimesNewRoman", Font.PLAIN, (int) (barHeight * 1.5) - 2));
  447. String percentageString = (Math.round((percentage * 100))) + "%";
  448. int stringWidth = (int) g.getFontMetrics().getStringBounds(percentageString, g).getWidth();
  449. if(percentage > 1.0f) g.setColor(Color.WHITE); //Just to see better on purple
  450. g.drawString(percentageString, pos.x + 1 - stringWidth / 2, pos.y + controller.getScaleDiv2() - 1+ barHeight);
  451. }
  452. //old code
  453. void drawMarker(Graphics2D g) {
  454. Color transparentGrey = new Color(128, 174, 247, 40);
  455. if (sx > x && sy > y) {
  456. g.drawRect(x, y, sx - x, sy - y);
  457. g.setColor(transparentGrey);
  458. g.fillRect(x, y, sx - x, sy - y);
  459. } else if (sx < x && sy < y) {
  460. g.drawRect(sx, sy, x - sx, y - sy);
  461. g.setColor(transparentGrey);
  462. g.fillRect(sx, sy, x - sx, y - sy);
  463. } else if (sx >= x) {
  464. g.drawRect(x, sy, sx - x, y - sy);
  465. g.setColor(transparentGrey);
  466. g.fillRect(x, sy, sx - x, y - sy);
  467. } else if (sy >= y) {
  468. g.drawRect(sx, y, x - sx, sy - y);
  469. g.setColor(transparentGrey);
  470. g.fillRect(sx, y, x - sx, sy - y);
  471. }
  472. }
  473. public void paintComponent(Graphics g) {
  474. super.paintComponent(g);
  475. Graphics2D g2d = (Graphics2D) g;
  476. g2d.setRenderingHints(new RenderingHints(RenderingHints.KEY_ANTIALIASING,
  477. RenderingHints.VALUE_ANTIALIAS_ON));
  478. //-->Old code
  479. if (drawEdge) {
  480. g2d.setColor(Color.BLACK);
  481. g2d.setStroke(new BasicStroke(1));
  482. g2d.drawLine(tempCps.getPosition().x, tempCps.getPosition().y, x, y);
  483. }
  484. //<--
  485. //SelectedCable
  486. HashSet<Edge> selectedEdges = new HashSet<Edge>();
  487. for(AbstractCanvasObject aCps: model.getSelectedCpsObjects()) {
  488. for(Edge edge: aCps.getConnections()) {
  489. selectedEdges.add(edge);
  490. }
  491. }
  492. if(model.getSelectedEdge() != null) selectedEdges.add(model.getSelectedEdge());
  493. //timstep:
  494. g.setFont(new Font("TimesNewRoman", Font.PLAIN, Math.max((int) (controller.getScale() / 3.5f), 10) ));
  495. g2d.setColor(Color.BLACK);
  496. VisualRepresentationalState visualState = controller.getSimManager().getActualVisualRepresentationalState();
  497. //VisualState Representation:
  498. if(visualState == null) System.out.println("AHHH");
  499. for(ExitCable cable : visualState.getExitCableList()) {
  500. paintExitCable(g2d, cable);
  501. }
  502. for(DecoratedCable cable : visualState.getCableList()) {
  503. paintCable(g2d, cable, selectedEdges.contains(cable.getModel()));
  504. }
  505. for(DecoratedGroupNode dGroupNode : visualState.getGroupNodeList()) {
  506. paintGroupNode(g2d, dGroupNode);
  507. }
  508. for(Consumer con: visualState.getConsumerList()) {
  509. paintConsumer(g2d, con);
  510. }
  511. for(Supplier sup: visualState.getSupplierList()) {
  512. paintSupplier(g2d, sup);
  513. }
  514. for(Passiv pas: visualState.getPassivList()) {
  515. paintCanvasObject(g2d, pas);
  516. }
  517. for(DecoratedSwitch dSwitch : visualState.getSwitchList()) {
  518. paintSwitch(g2d, dSwitch);
  519. }
  520. for(Node node : visualState.getNodeList()) {
  521. drawCanvasObject(g2d, "/Images/node.png" , node.getPosition());
  522. }
  523. //-->oldCode
  524. if (doMark) {
  525. g2d.setColor(Color.BLACK);
  526. g2d.setStroke(new BasicStroke(0));
  527. drawMarker(g2d);
  528. }
  529. //Test Selection
  530. //Objects:
  531. g2d.setColor(Color.BLUE);
  532. g2d.setStroke(new BasicStroke(1));
  533. Color transparentGrey = new Color(128, 174, 247, 40);
  534. for(AbstractCanvasObject aCps: model.getSelectedCpsObjects()) {
  535. if(aCps instanceof Node) {
  536. Position pos = aCps.getPosition();
  537. g2d.setColor(transparentGrey);
  538. g2d.fillOval(pos.x - (int) (controller.getScaleDiv2()), pos.y - (int) (controller.getScaleDiv2()), controller.getScale(), controller.getScale());
  539. g2d.setColor(Color.LIGHT_GRAY);
  540. g2d.setStroke(new BasicStroke(2));
  541. g2d.drawOval(pos.x - (int) (controller.getScaleDiv2()), pos.y - (int) (controller.getScaleDiv2()), controller.getScale(), controller.getScale());
  542. }
  543. else {
  544. Position pos = aCps.getPosition();
  545. g2d.setColor(transparentGrey);
  546. 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));
  547. g2d.setColor(Color.LIGHT_GRAY);
  548. g2d.setStroke(new BasicStroke(2));
  549. 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));
  550. }
  551. }
  552. //maybeReplace:
  553. if(mayBeReplaced != null){
  554. g2d.setColor(Color.RED);
  555. Position pos = mayBeReplaced.getPosition();
  556. g2d.drawImage(ImageImport.loadImage("/Images/replace.png") ,
  557. pos.x + controller.getScaleDiv2(),
  558. pos.y - controller.getScale(),
  559. controller.getScaleDiv2(), controller.getScaleDiv2(), null);
  560. }
  561. //<-- OldCode
  562. }
  563. @Override
  564. public void mouseClicked(MouseEvent e) {
  565. if(!disabled){
  566. if (e.getButton() == MouseEvent.BUTTON1) {
  567. DefaulTable propertyTable = model.getPropertyTable();
  568. if (propertyTable.getRowCount() > 0) {
  569. for (int i = propertyTable.getRowCount() - 1; i > -1; i--) {
  570. propertyTable.removeRow(i);
  571. }
  572. }
  573. triggerUpdateController();
  574. }
  575. stopEditing();
  576. }
  577. }
  578. @Override
  579. public void mouseEntered(MouseEvent e) {
  580. }
  581. @Override
  582. public void mouseExited(MouseEvent e) {
  583. }
  584. @Override
  585. public void mousePressed(MouseEvent e) {
  586. if(!disabled){
  587. stopEditing();
  588. tempCps = null;
  589. edgeHighlight = null;
  590. controller.setSelecteEdge(null);
  591. // Object Selection
  592. for (AbstractCanvasObject cps : model.getObjectsOnCanvas()) {
  593. cx = cps.getPosition().x - controller.getScaleDiv2();
  594. cy = cps.getPosition().y - controller.getScaleDiv2();
  595. if (x - controller.getScale() <= cx
  596. && y - controller.getScale() <= cy && x >= cx && y >= cy) {
  597. tempCps = cps;
  598. dragging = true;
  599. if (e.isControlDown() && tempCps != null) {
  600. if (model.getSelectedCpsObjects().contains(tempCps)) {
  601. controller.removeSelectedObjectFromSelection(tempCps);
  602. //TODO: RemoveDepth
  603. } else {
  604. controller.addSelectedObject(tempCps);
  605. if(tempCps instanceof GroupNode)
  606. controller.getObjectsInDepth();
  607. }
  608. }
  609. // If drawing an Edge (CTRL down)
  610. if (tempCps.getClass() == HolonObject.class) {
  611. HolonObject tempObj = ((HolonObject) tempCps);
  612. dataSelected = tempObj.getElements();
  613. }
  614. if (e.isShiftDown()) {
  615. drawEdge = true;
  616. dragging = false;
  617. }
  618. }
  619. }
  620. // Edge Selection
  621. if (tempCps == null) {
  622. edgeHighlight = mousePositionOnEdge(x, y);
  623. controller.setSelecteEdge(edgeHighlight);
  624. controller.setSelectedObjectID(0);
  625. if (!e.isControlDown() && e.getButton() != MouseEvent.BUTTON3) {
  626. controller.clearSelection();
  627. }
  628. }
  629. if (edgeHighlight == null && tempCps == null) {
  630. sx = e.getX();
  631. sy = e.getY();
  632. doMark = true;
  633. }
  634. repaint();
  635. }
  636. }
  637. @Override
  638. public void mouseReleased(MouseEvent e) {
  639. if(!disabled){
  640. x = e.getX();
  641. y = e.getY();
  642. dragging = false;
  643. if (drawEdge) {
  644. drawEdge = false;
  645. drawDeleteEdge();
  646. }
  647. if (dragged) {
  648. try {
  649. /**
  650. * Save before further Dragged interactions happen
  651. */
  652. controller.autoSave();
  653. } catch (IOException ex) {
  654. System.err.println("AutoSave error by dragging");
  655. ex.printStackTrace();
  656. }
  657. /**
  658. * check if a unique tempCps could replace an Object on the canvas
  659. */
  660. if(model.getSelectedCpsObjects().size()==1
  661. && checkForReplacement(model.getObjectsOnCanvas(), tempCps, tempCps.getPosition().x, tempCps.getPosition().y)){
  662. /**
  663. * if UpperNode would be replaced, close its tabs
  664. */
  665. if(mayBeReplaced instanceof GroupNode)
  666. closeUpperNodeTab(mayBeReplaced.getId());
  667. /**
  668. * replace on canvas (will save)
  669. */
  670. controller.replaceCanvasObject(mayBeReplaced, tempCps);
  671. mayBeReplaced=null;
  672. }
  673. }
  674. if (!e.isControlDown() && !dragged && tempCps != null
  675. && MouseEvent.BUTTON3 != e.getButton()) {
  676. controller.clearSelection();
  677. controller.addSelectedObject(tempCps);
  678. if(tempCps instanceof GroupNode)
  679. controller.getObjectsInDepth();
  680. }
  681. dragged = false;
  682. // Rightclick List
  683. setRightClickMenu(e);
  684. markObjects();
  685. if (doubleClick() && tempCps instanceof HolonSwitch
  686. && MouseEvent.BUTTON3 != e.getButton()&& tempCps != null) {
  687. ((HolonSwitch) tempCps).switchState();
  688. }
  689. controller.calculateStateAndVisualForTimeStep(model.getCurIteration());
  690. triggerUpdateController();
  691. repaint();
  692. }
  693. }
  694. @Override
  695. public void mouseDragged(MouseEvent e) {
  696. if(!disabled){
  697. // If Edge is drawn
  698. x = e.getX();
  699. y = e.getY();
  700. if (!model.getSelectedCpsObjects().contains(tempCps) && !doMark) {
  701. controller.clearSelection();
  702. if (tempCps != null) {
  703. controller.addSelectedObject(tempCps);
  704. }
  705. }
  706. if (dragging) {
  707. try {
  708. dragged = true;
  709. float xDist, yDist; // Distance
  710. x = e.getX();
  711. y = e.getY();
  712. // Make sure its in bounds
  713. int scaleDiv2 = controller.getScaleDiv2();
  714. if (e.getX() < scaleDiv2)
  715. x = scaleDiv2;
  716. else if (e.getX() > this.getWidth() - scaleDiv2)
  717. x = this.getWidth() - scaleDiv2;
  718. if (e.getY() < scaleDiv2)
  719. y = scaleDiv2;
  720. else if (e.getY() > this.getHeight()
  721. - scaleDiv2)
  722. y = this.getHeight() - scaleDiv2;
  723. // Distance
  724. xDist = x - tempCps.getPosition().x;
  725. yDist = y - tempCps.getPosition().y;
  726. tempCps.setPosition(x, y); // Drag Position
  727. // ToolTipText Position and name
  728. toolTip = true;
  729. toolTipText = tempCps.getName() + ", " + tempCps.getId();
  730. toolTipPos.x = tempCps.getPosition().x
  731. - scaleDiv2;
  732. toolTipPos.y = tempCps.getPosition().y
  733. + scaleDiv2;
  734. // All Selected Objects
  735. for (AbstractCanvasObject cps : model.getSelectedCpsObjects()) {
  736. if (cps != tempCps) {
  737. x = (int) (cps.getPosition().x + xDist);
  738. y = (int) (cps.getPosition().y + yDist);
  739. // Make sure its in bounds
  740. if (x <= scaleDiv2)
  741. x = scaleDiv2;
  742. else if (x > this.getWidth()
  743. - scaleDiv2)
  744. x = this.getWidth() - scaleDiv2;
  745. if (y <= scaleDiv2)
  746. y = scaleDiv2;
  747. else if (y > this.getHeight()
  748. - scaleDiv2)
  749. y = this.getHeight() - scaleDiv2;
  750. cps.setPosition(x, y);
  751. }
  752. }
  753. /**
  754. * check if something might be replaced
  755. */
  756. if(model.getSelectedCpsObjects().size()==1)
  757. checkForReplacement(model.getObjectsOnCanvas(), tempCps, x, y);
  758. repaint();
  759. } catch (Exception eex) {
  760. }
  761. }
  762. // Mark Objects
  763. if (doMark) {
  764. tempSelected.clear();
  765. for (AbstractCanvasObject cps : model.getObjectsOnCanvas()) {
  766. int x1 = sx, x2 = x, y1 = sy, y2 = y;
  767. if (sx >= x) {
  768. x1 = x;
  769. x2 = sx;
  770. }
  771. if (sy >= y) {
  772. y1 = y;
  773. y2 = sy;
  774. }
  775. if (x1 <= cps.getPosition().x + model.getScaleDiv2()
  776. && y1 <= cps.getPosition().y + model.getScaleDiv2()
  777. && x2 >= cps.getPosition().x
  778. && y2 >= cps.getPosition().y) {
  779. tempSelected.add(cps);
  780. }
  781. }
  782. }
  783. repaint();
  784. }
  785. }
  786. @Override
  787. public void mouseMoved(MouseEvent e) {
  788. if(!disabled){
  789. x = e.getX();
  790. y = e.getY();
  791. // Everything for the tooltip :)
  792. boolean on = false;
  793. for (AbstractCanvasObject cps : model.getObjectsOnCanvas()) {
  794. cx = cps.getPosition().x - controller.getScaleDiv2();
  795. cy = cps.getPosition().y - controller.getScaleDiv2();
  796. on = setToolTipInfoAndPosition(on, cps);
  797. }
  798. if(on||(!on && toolTip))
  799. repaint();
  800. toolTip = on;
  801. }
  802. }
  803. /**
  804. * Draws or Deletes an Edge.
  805. */
  806. void drawDeleteEdge() {
  807. if (getMousePosition() != null) {
  808. boolean node = true;
  809. boolean newEdge = true;
  810. boolean onEdge = true;
  811. boolean deleteNode = false;
  812. Edge e = null;
  813. for (AbstractCanvasObject cps : model.getObjectsOnCanvas()) {
  814. cx = cps.getPosition().x - controller.getScaleDiv2();
  815. cy = cps.getPosition().y - controller.getScaleDiv2();
  816. if (x - controller.getScale() <= cx
  817. && y - controller.getScale() <= cy && x >= cx
  818. && y >= cy && cps != tempCps) {
  819. node = false;
  820. onEdge = false;
  821. for (Edge p : tempCps.getConnections()) {
  822. if ((p.getA() == tempCps && p.getB() == cps)
  823. || (p.getB() == tempCps && p.getA() == cps)) {
  824. newEdge = false;
  825. e = p;
  826. }
  827. }
  828. if (!newEdge) {
  829. controller.removeEdgesOnCanvas(e);
  830. // Node ohne Edge?
  831. if (e.getA().getClass() == Node.class
  832. && e.getA().getConnections().isEmpty()) {
  833. tempCps = e.getA();
  834. deleteNode = true;
  835. }
  836. if (e.getB().getClass() == Node.class
  837. && e.getB().getConnections().isEmpty()) {
  838. deleteNode = true;
  839. }
  840. } else {
  841. if(!(cps instanceof GroupNode || tempCps instanceof GroupNode)) {
  842. e = new Edge(cps, tempCps, model.getMaxCapacity());
  843. controller.addEdgeOnCanvas(e);
  844. }else if (cps instanceof GroupNode && !(tempCps instanceof GroupNode)){
  845. GroupNode thisUpperNode = (GroupNode)cps;
  846. Object[] possibilities = thisUpperNode.getNodes().stream().map(aCps -> new ACpsHandle(aCps)).filter(aCpsHandle -> !(aCpsHandle.object instanceof GroupNode)).toArray();
  847. if(possibilities.length != 0) {
  848. 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, "");
  849. if(selected != null) {
  850. e = new Edge(selected.object, tempCps, model.getMaxCapacity());
  851. controller.addEdgeOnCanvas(e);
  852. }
  853. }else {
  854. Node n = new Node("Node");
  855. n.setPosition(x, y);
  856. controller.addObjUpperNode(n, thisUpperNode);
  857. e = new Edge(n, tempCps, model.getMaxCapacity());
  858. controller.addEdgeOnCanvas(e);
  859. }
  860. }
  861. }
  862. }
  863. }
  864. // Edge auf eine Edge gezogen?
  865. if (onEdge && !checkForReplacement(x, y)) {
  866. Edge p = mousePositionOnEdge(x, y);
  867. if (p != null) {
  868. Edge e1;
  869. Edge e2;
  870. node = false;
  871. Node n = new Node("Node");
  872. n.setPosition(x, y);
  873. controller.addObjectCanvas(n);
  874. AbstractCanvasObject r, k;
  875. r = p.getA();
  876. k = p.getB();
  877. e = new Edge(n, tempCps, model.getMaxCapacity());
  878. e1 = new Edge(n, r, model.getMaxCapacity());
  879. e2 = new Edge(n, k, model.getMaxCapacity());
  880. controller.removeEdgesOnCanvas(p);
  881. controller.addEdgeOnCanvas(e);
  882. controller.addEdgeOnCanvas(e1);
  883. controller.addEdgeOnCanvas(e2);
  884. }
  885. }else{
  886. mayBeReplaced = null;
  887. }
  888. // ins leere Gedragged
  889. if (node && !checkForReplacement(x, y)) {
  890. Node n = new Node("Node");
  891. n.setPosition(x, y);
  892. controller.addObjectCanvas(n);
  893. e = new Edge(n, tempCps, model.getMaxCapacity());
  894. controller.addEdgeOnCanvas(e);
  895. }else{
  896. mayBeReplaced = null;
  897. }
  898. // Wenn ein Node ohne Connections da ist
  899. if (deleteNode) {
  900. controller.deleteCanvasObject(tempCps, true);
  901. tempCps = null;
  902. }
  903. }
  904. }
  905. /**
  906. * Checks if the mouse is on an Edge.
  907. *
  908. * @param x
  909. * Position of the Mouse
  910. * @param y
  911. * Position of the Mouse
  912. * @return CpsEdge the Mouse is on, null if the mouse is not on an Edge
  913. */
  914. private Edge mousePositionOnEdge(int x, int y) {
  915. x += controller.getScaleDiv2();
  916. y += controller.getScaleDiv2();
  917. for (Edge p : model.getEdgesOnCanvas()) {
  918. Line2D l = new Line2D.Float(p.getA().getPosition().x, p.getA()
  919. .getPosition().y, p.getB().getPosition().x, p.getB()
  920. .getPosition().y);
  921. int[] positions = determineMousePositionOnEdge(p);
  922. int lx = positions[0];
  923. int ly = positions[1];
  924. int hx = positions[2];
  925. int hy = positions[3];
  926. // distance from a point to a line and between both Objects
  927. if (l.ptLineDistSq(x - model.getScaleDiv2(),
  928. y - model.getScaleDiv2()) < 20
  929. && x > lx && x < hx && y > ly && y < hy) {
  930. return p;
  931. }
  932. }
  933. return null;
  934. }
  935. void updateLanguages() {
  936. itemCut.setText("Cut");
  937. itemCopy.setText("Copy");
  938. itemPaste.setText("Paste");
  939. itemDelete.setText("Delete");
  940. itemGroup.setText("Group");
  941. itemUngroup.setText("Ungroup");
  942. }
  943. /**
  944. * Set if Information should be shown.
  945. *
  946. * @param connection
  947. * boolean for conecction
  948. * @param object
  949. * boolean for objects
  950. * @param nodeOfnode
  951. */
  952. void setShowedInformation(boolean connection, boolean object,
  953. boolean border, boolean nodeOfnode) {
  954. showConnectionInformation = connection;
  955. showedInformation[1] = object;
  956. showedInformation[3] = border;
  957. showedInformation[4] = nodeOfnode;
  958. }
  959. /**
  960. * Returns if Information should be shown.
  961. *
  962. * @return Array of boolean [0] = connection, [1] = objects
  963. */
  964. boolean[] getShowedInformation() {
  965. return showedInformation;
  966. }
  967. /**
  968. * set toolTip
  969. *
  970. * @param bool
  971. */
  972. void setToolTip(boolean bool) {
  973. this.toolTip = bool;
  974. }
  975. /**
  976. * Set the Mouse
  977. *
  978. * @param x
  979. * @param y
  980. */
  981. void setXY(int x, int y) {
  982. this.x = x;
  983. this.y = y;
  984. }
  985. @Override
  986. public boolean checkForReplacement(int x, int y) {
  987. return checkForReplacement(model.getObjectsOnCanvas(), null, x, y);
  988. }
  989. @Override
  990. public void tryToAlignObjects(){
  991. /**
  992. * Align all Objects
  993. */
  994. for(AbstractCanvasObject cps: model.getObjectsOnCanvas())
  995. align(cps,3*model.getScaleDiv2());
  996. /**
  997. * AutoSave new Positons
  998. */
  999. try{
  1000. controller.autoSave();
  1001. } catch (IOException ex) {
  1002. System.err.println("AutoSave error by aligning");
  1003. ex.printStackTrace();
  1004. }
  1005. }
  1006. @Override
  1007. public void closeUpperNodeTab(int upperNodeId) {
  1008. JTabbedPane tabbedPaneInner = (JTabbedPane) getParent()
  1009. .getParent().getParent().getParent();
  1010. for (int i = 1; i < tabbedPaneInner.getTabCount(); i++) {
  1011. if (((GroupNodeCanvas) ((JScrollPane) tabbedPaneInner
  1012. .getComponentAt(i)).getViewport().getComponent(
  1013. 0)).upperNode.getId() == upperNodeId) {
  1014. tabbedPaneInner.remove(i);
  1015. break;
  1016. }
  1017. }
  1018. }
  1019. }