001/* 002 * @(#)GraphLayout.java 1.0 2007/04/11 003 * 004 * 005 * Institut d'Investigaci� en Intel.lig?ncia Artificial (IIIA) 006 * 007 */ 008 009/* 010 *----------------------------------------------------------------------------- 011 * 012 * Copyright 2007 by the 013 * Institut d'Investigaci� en Intel.lig?ncia Artificial, CSIC, Catalonia, EU 014 * http://www.iiia.csic.es 015 * 016 * This file is part of InfoVisual Toolkit 017 * 018 * InfoVisual Toolkit is free software; you can redistribute it and/or modify 019 * it under the terms of the GNU General Public License as published by 020 * the Free Software Foundation; either version 2 of the License, or 021 * (at your option) any later version. 022 * 023 * InfoVisual Toolkit is distributed in the hope that it will be useful, 024 * but WITHOUT ANY WARRANTY; without even the implied warranty of 025 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 026 * GNU General Public License for more details. 027 * 028 * You should have received a copy of the GNU General Public License 029 * along with iForecast; if not, write to the Free Software 030 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 031 * 032 *----------------------------------------------------------------------------- 033 */ 034 035package es.ucm.fdi.gaia.jcolibri.extensions.visualization.infovisual; 036 037 038import java.awt.Dimension; 039import java.awt.Graphics2D; 040import java.awt.GridBagConstraints; 041import java.awt.GridBagLayout; 042import java.awt.Insets; 043import java.awt.event.ActionEvent; 044import java.awt.event.ActionListener; 045import java.awt.image.BufferedImage; 046import java.io.File; 047import java.io.IOException; 048import java.util.Iterator; 049 050import javax.imageio.ImageIO; 051import javax.swing.BorderFactory; 052import javax.swing.JButton; 053import javax.swing.JFileChooser; 054import javax.swing.JPanel; 055 056/* 057 * From prefuse ( http://prefuse.org/ ). 058 */ 059import prefuse.Constants; 060import prefuse.Display; 061import prefuse.Visualization; 062import prefuse.action.ActionList; 063import prefuse.action.RepaintAction; 064import prefuse.action.assignment.ColorAction; 065import prefuse.action.assignment.DataColorAction; 066import prefuse.action.filter.GraphDistanceFilter; 067import prefuse.action.layout.graph.ForceDirectedLayout; 068import prefuse.activity.Activity; 069import prefuse.controls.DragControl; 070import prefuse.controls.FocusControl; 071import prefuse.controls.NeighborHighlightControl; 072import prefuse.controls.PanControl; 073import prefuse.controls.ZoomControl; 074import prefuse.controls.ZoomToFitControl; 075import prefuse.data.Graph; 076import prefuse.data.Table; 077import prefuse.data.Tuple; 078import prefuse.data.event.TupleSetListener; 079import prefuse.data.io.DataIOException; 080import prefuse.data.io.GraphMLReader; 081import prefuse.data.query.SearchQueryBinding; 082import prefuse.data.search.PrefixSearchTupleSet; 083import prefuse.data.search.SearchTupleSet; 084import prefuse.data.tuple.TupleSet; 085import prefuse.render.DefaultRendererFactory; 086import prefuse.render.EdgeRenderer; 087import prefuse.render.LabelRenderer; 088import prefuse.render.PolygonRenderer; 089import prefuse.util.ColorLib; 090import prefuse.util.force.Force; 091import prefuse.util.force.ForceSimulator; 092import prefuse.util.force.SpringForce; 093import prefuse.util.io.IOLib; 094import prefuse.util.io.SimpleFileFilter; 095import prefuse.util.ui.JSearchPanel; 096import prefuse.visual.VisualGraph; 097import prefuse.visual.VisualItem; 098 099public class GraphLayout extends JPanel { 100 101 //--------------------------------------------------------------- 102 // PROPERTIES of the Class. 103 //--------------------------------------------------------------- 104 105 /** 106 * 107 */ 108 private static final long serialVersionUID = 1L; 109 110 111/** Label Constants. */ 112 private static final String GRAPH = "graph"; 113 private static final String NODES = "graph.nodes"; 114 private static final String EDGES = "graph.edges"; 115 116 /** The Visualization Object. */ 117 public static Visualization vis; 118 119 public VisualGraph vg; 120 121 public Display dis; 122 123 /** The Distance Filter. */ 124 private GraphDistanceFilter filter; 125 126 /** The force simulator */ 127 private ForceSimulator fsim; 128 129 JSearchPanel spanel; 130 131 final JButton stop; 132 133 //--------------------------------------------------------------- 134 // CONSTRUCTORS of the Class. 135 //--------------------------------------------------------------- 136 137 /** 138 * empty constructor. 139 */ 140 public GraphLayout (){ 141 this(getGraph(), false, false, true, true); 142 } 143 144 /** 145 * receiving graph file as a parameter. 146 */ 147 public GraphLayout (String graphFile){ 148 this(getGraph(graphFile), true, true, false, true); 149 } 150 151 /** 152 * . 153 */ 154 public GraphLayout (String graphFile, boolean withSearchControl, boolean withEdgeLines, boolean withEdgeControl, boolean highLight){ 155 this(getGraph(graphFile), withSearchControl, withEdgeLines, withEdgeControl, highLight); 156 } 157 158 /** 159 * Main Class constructor. 160 */ 161 162 public GraphLayout (Graph graph, boolean withSearchControl, boolean withEdgeLines, boolean withEdgeControl, boolean highLight){ 163 164 // -- The visualization -------------------------------------------- 165 166 // add the graph to the visualization as the data group "graph" 167 // nodes and edges are accessible as "graph.nodes" and "graph.edges" 168 vis = new Visualization(); 169 vg = vis.addGraph(GRAPH, graph); 170 vis.setInteractive(EDGES, null, false); 171 172 // -- The renderers and renderer factory --------------------------- 173 174 // draw the "name" label for NodeItems 175 LabelRenderer nodeR = new LabelRenderer("name"); 176 nodeR.setRoundedCorner(8, 8); // round the corners 177 178 // draw Arrows in Edges 179 EdgeRenderer edgeR = new EdgeRenderer(Constants.EDGE_TYPE_LINE, Constants.EDGE_ARROW_FORWARD); 180 edgeR.setArrowHeadSize(6,6); 181 182 // create a new default renderer factory 183 DefaultRendererFactory drf = new DefaultRendererFactory(nodeR,edgeR); 184 185 // draw groups as polygons with curved edges 186 PolygonRenderer polyR = new PolygonRenderer(Constants.POLY_TYPE_CURVE); 187 polyR.setCurveSlack(0.15f); 188 drf.add("ingroup('aggregates')", polyR); 189 190 vis.setRendererFactory(drf); 191 192 // fix selected focus nodes 193 TupleSet focusGroup = vis.getGroup(Visualization.FOCUS_ITEMS); 194 focusGroup.addTupleSetListener(new TupleSetListener() { 195 public void tupleSetChanged(TupleSet ts, Tuple[] add, Tuple[] rem) 196 { 197 for ( int i=0; i<rem.length; ++i ) 198 ((VisualItem)rem[i]).setFixed(false); 199 for ( int i=0; i<add.length; ++i ) { 200 ((VisualItem)add[i]).setFixed(false); 201 ((VisualItem)add[i]).setFixed(true); 202 } 203 if ( ts.getTupleCount() == 0 ) { 204 ts.addTuple(rem[0]); 205 ((VisualItem)rem[0]).setFixed(false); 206 } 207 vis.run("draw"); 208 } 209 }); 210 211 // -- The processing actions --------------------------------------- 212 213 ColorAction nodeColor = getNodeColors(NODES); 214 if (nodeColor != null){ 215 if (highLight){ 216 nodeColor.add(VisualItem.FIXED, ColorLib.rgb(255,100,100)); 217 nodeColor.add(VisualItem.HIGHLIGHT, ColorLib.rgb(255,200,125)); 218 } 219 if (withSearchControl) nodeColor.add("ingroup('_search_')", ColorLib.rgb(150,240,150)); 220 } 221 222 223 // create an action list containing all color assignments 224 ActionList draw = new ActionList(); 225 226 // controlling graph exansion distance 227 if (withEdgeControl){ 228 filter = new GraphDistanceFilter(GRAPH, 1); 229 draw.add(filter); 230 } 231 232 if (nodeColor!=null) draw.add(nodeColor); 233 234 // use black for node text 235 draw.add(new ColorAction(NODES, VisualItem.TEXTCOLOR, ColorLib.gray(0))); 236 237 // Adding gray boundaries to nodes 238 draw.add(new ColorAction(NODES, VisualItem.STROKECOLOR, ColorLib.gray(100))); 239 240 // use light grey for edge lines 241 if (withEdgeLines) draw.add(new ColorAction(EDGES, VisualItem.STROKECOLOR, ColorLib.gray(200))); 242 243 DataColorAction edgeColor = getEdgeColors(EDGES); 244 if (edgeColor!=null) draw.add(edgeColor); 245 246 247/* 248 ColorAction aStroke = new ColorAction(AGGR, VisualItem.STROKECOLOR); 249 aStroke.setDefaultColor(ColorLib.gray(200)); 250 aStroke.add("_hover", ColorLib.rgb(255,100,100)); 251 252 int[] groupsPalette = new int[] { 253 ColorLib.rgba(255,200,200,150), 254 ColorLib.rgba(200,255,200,150), 255 ColorLib.rgba(200,200,255,150) 256 }; 257 ColorAction aFill = new DataColorAction(AGGR, "id", 258 Constants.NOMINAL, VisualItem.FILLCOLOR, groupsPalette); 259 260 draw.add(aStroke); 261 draw.add(aFill); 262*/ 263 264 265 // create an action list with an animated layout 266 ActionList layout = new ActionList(Activity.INFINITY); 267 268 ForceDirectedLayout fdl = getForceDirectedLayout(GRAPH); 269 fsim = fdl.getForceSimulator(); 270 271 layout.add(fdl); 272 if (nodeColor!=null) layout.add(nodeColor); 273 if (edgeColor!=null) layout.add(edgeColor); 274 275 layout.add(new RepaintAction()); 276 277 // add the actions to the visualization 278 vis.putAction("draw", draw); 279 vis.putAction("layout", layout); 280 281 vis.runAfter("draw", "layout"); 282 283 // Selecting the first node of the list 284 setFocus(0); 285 286 // -- The display and interactive controls ------------------------- 287 288 dis = new Display(vis); 289 dis.setSize(700, 600); // set display size 290 dis.pan(350, 300); 291 if (highLight) dis.addControlListener(new FocusControl(1)); 292 dis.addControlListener(new DragControl()); 293 dis.addControlListener(new PanControl()); 294 dis.addControlListener(new ZoomControl()); 295 dis.addControlListener(new ZoomToFitControl()); 296// d.addControlListener(new ToolTipControl("relType")); 297 if (highLight) dis.addControlListener(new NeighborHighlightControl()); 298 299 setLayout( new GridBagLayout()); 300 GridBagConstraints constraints = new GridBagConstraints(); 301 constraints.insets = new Insets(5,5,0,5); 302 constraints.weightx = 1.0; 303 constraints.weighty = 1.0; 304 constraints.fill = GridBagConstraints.BOTH; 305 constraints.gridwidth = GridBagConstraints.REMAINDER; 306 constraints.anchor = GridBagConstraints.CENTER; 307 this.add(dis, constraints); 308 309 if (withSearchControl){ 310 // controlling search result 311 SearchTupleSet search = new PrefixSearchTupleSet();//MyPrefixSearchTupleSet(); 312 vis.addFocusGroup(Visualization.SEARCH_ITEMS, search); 313 search.addTupleSetListener(new TupleSetListener() { 314 public void tupleSetChanged(TupleSet t, Tuple[] add, Tuple[] rem) { 315 vis.run("draw"); 316 vis.repaint(); 317 } 318 }); 319 addSearchPanel(); 320 } 321 322 constraints.insets = new Insets(5,5,5,5); 323 constraints.weighty = 0.0; 324 constraints.weightx = 0.0; 325 constraints.fill = GridBagConstraints.NONE; 326 constraints.anchor = GridBagConstraints.WEST; 327 constraints.gridwidth = 1; 328 329 // Loading new data 330 final JButton load = new JButton("Load"); 331 this.add(load, constraints); 332 load.addActionListener(new ActionListener() { 333 public void actionPerformed(ActionEvent e) { 334 setGraph(getGraph()); 335 } 336 }); 337 338 // Managing Layout activity 339 stop = new JButton("Stop"); 340 this.add(stop, constraints); 341 stop.addActionListener(new ActionListener() { 342 public void actionPerformed(ActionEvent e) { 343 if (e.getActionCommand().equals("Stop")){ 344 stop.setText("Run"); 345 vis.cancel("layout"); 346 }else{ 347 stop.setText("Stop"); 348 vis.run("layout"); 349 } 350 } 351 }); 352 353 // adding export button 354 final JButton export = new JButton("Export"); 355 if (!withSearchControl) constraints.gridwidth = GridBagConstraints.REMAINDER; 356 this.add(export, constraints); 357 export.addActionListener(new ActionListener() { 358 public void actionPerformed(ActionEvent e) { 359 storeImage(); 360 } 361 }); 362 363 // allowing focus changes (using info from search panel) 364 if (withSearchControl){ 365 final JButton focus = new JButton("Focus"); 366 constraints.gridwidth = GridBagConstraints.REMAINDER; 367 this.add(focus, constraints); 368 focus.addActionListener(new ActionListener() { 369 public void actionPerformed(ActionEvent e) { 370 boolean first = true; 371 for (Iterator<?> it=vis.getGroup(Visualization.SEARCH_ITEMS).tuples();it.hasNext(); ) { 372 VisualItem item = (VisualItem) it.next(); 373 if (first){ 374 vis.getGroup(Visualization.FOCUS_ITEMS).setTuple(item); 375 first = false; 376 }else{ 377 vis.getGroup(Visualization.FOCUS_ITEMS).addTuple(item); 378 } 379 item.setFixed(false); 380// System.out.println("Object: "+((VisualItem) it.next()).getRow()); 381 } 382 vis.repaint(); 383 } 384 }); 385 } 386 387 388 // assign the colors 389 vis.run("draw"); 390 // start up the animated layout 391 vis.run("layout"); 392 393 } 394 395 /** 396 * Returns the graph object asking for a file. 397 */ 398 public static Graph getGraph(){ 399 JPanel view = new JPanel(); 400 return IOLib.getGraphFile(view); 401 } 402 403 /** 404 * Returns the graph object given a path. 405 */ 406 public static Graph getGraph(String graphFile){ 407 408 Graph graph = null; 409 try { 410 graph = new GraphMLReader().readGraph(graphFile); 411 } catch ( DataIOException e ) { 412 e.printStackTrace(); 413 System.err.println("Error loading graph. Exiting..."); 414 System.exit(1); 415 } 416 return graph; 417 } 418 419 /** 420 * Updating the graph 421 */ 422 public void setGraph(Graph g){ 423 vis.cancel("layout"); 424 vis.removeGroup(GRAPH); 425 vis.getGroup(Visualization.SEARCH_ITEMS).clear(); 426 this.remove(spanel); 427 428 vis.addGraph(GRAPH, g); 429 addSearchPanel(); 430 vis.setInteractive(EDGES, null, false); 431 setFocus(0); 432 stop.setText("Stop"); 433 vis.run("layout"); 434 435 } 436 437 /** 438 * Returns actions associated to nodes. 439 * The default is no action. 440 */ 441 public ColorAction getNodeColors(String label){ 442 return new ColorAction(label, 443 VisualItem.FILLCOLOR, ColorLib.rgb(190,190,255)); 444 } 445 446 /** 447 * Returns actions associated to edges. 448 * The default is no action. 449 */ 450 public DataColorAction getEdgeColors(String label){ 451 return null; 452 } 453 454 /** 455 * Returns the Forces model Layout. 456 */ 457 public ForceDirectedLayout getForceDirectedLayout(String group){ 458 return new ForceDirectedLayout(group); 459 } 460 461 /** 462 * Changes the expansion Distance. 463 */ 464 public void setDistance(int dist){ 465 filter.setDistance(dist); 466 vis.run("draw"); 467 } 468 469 /** 470 * Changes the default Spring distance force. 471 */ 472 public void setSpringForce(float val){ 473 Force force = fsim.getForces()[2]; 474 force.setParameter (SpringForce.SPRING_LENGTH,val); 475 vis.run("draw"); 476 } 477 478 /** 479 * Changes the graph focus 480 */ 481 public void setFocus(int nodeID){ 482 VisualItem f = (VisualItem)vg.getNode(nodeID); 483 vis.getGroup(Visualization.FOCUS_ITEMS).setTuple(f); 484 f.setFixed(false); 485 } 486 487 /** 488 * Changes the default Spring distance force. 489 */ 490 public void storeImage() { 491 //create the image 492 Dimension dim = dis.getSize(); 493 BufferedImage image = new BufferedImage( 494 (int)dim.getWidth() 495 ,(int)dim.getHeight() 496 ,BufferedImage.TYPE_INT_RGB 497 ); 498 Graphics2D imageGenerator = (Graphics2D)image.getGraphics(); 499 500 //draw the components 501 dis.paintComponent(imageGenerator); 502 503 //save the image 504 try { 505 File file = askForFile(); 506 if (file!=null) ImageIO.write(image,"png",file); 507 } catch ( IOException e ) { 508 System.err.println("Error exporting graph."); 509 } 510 511 } 512 513 public File askForFile(){ 514 JFileChooser jfc = new JFileChooser(); 515 jfc.setDialogType(JFileChooser.SAVE_DIALOG); 516 jfc.setDialogTitle("Choose Export File"); 517 jfc.setAcceptAllFileFilterUsed(false); 518 jfc.setFileFilter(new SimpleFileFilter("png","Portable N Graphics (*.png)")); 519 520 int retval = jfc.showSaveDialog(this); 521 if (retval != JFileChooser.APPROVE_OPTION) 522 return null; 523 524 return jfc.getSelectedFile(); 525 526 } 527 528 public void addSearchPanel(){ 529 // create a search panel for the graph 530 SearchQueryBinding sq = new SearchQueryBinding( 531 (Table)vis.getGroup(NODES), "name", 532 (SearchTupleSet)vis.getGroup(Visualization.SEARCH_ITEMS)); 533 spanel = sq.createSearchPanel(); 534 spanel.setShowResultCount(true); 535 spanel.setBorder(BorderFactory.createEmptyBorder(5,5,4,0)); 536 537 GridBagConstraints constraints = new GridBagConstraints(); 538 constraints.insets = new Insets(0,5,5,5); 539 constraints.weightx = 1.0; 540 constraints.weighty = 0.0; 541 constraints.fill = GridBagConstraints.BOTH; 542 constraints.gridwidth = GridBagConstraints.REMAINDER; 543 constraints.anchor = GridBagConstraints.CENTER; 544 this.add(spanel, constraints,1); 545 } 546 547}