KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > objectweb > jac > ide > diagrams > DiagramView


1 /*
2   Copyright (C) 2002-2003 Renaud Pawlak <renaud@aopsys.com>
3
4   This program is free software; you can redistribute it and/or modify
5   it under the terms of the GNU Lesser General Public License as
6   published by the Free Software Foundation; either version 2 of the
7   License, or (at your option) any later version.
8
9   This program is distributed in the hope that it will be useful,
10   but WITHOUT ANY WARRANTY; without even the implied warranty of
11   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12   GNU Lesser General Public License for more details.
13
14   You should have received a copy of the GNU Lesser General Public
15   License along with this program; if not, write to the Free Software
16   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
17 */

18
19 package org.objectweb.jac.ide.diagrams;
20
21 import CH.ifa.draw.framework.Drawing;
22 import CH.ifa.draw.framework.DrawingEditor;
23 import CH.ifa.draw.framework.DrawingView;
24 import CH.ifa.draw.framework.Figure;
25 import CH.ifa.draw.framework.FigureEnumeration;
26 import CH.ifa.draw.framework.Tool;
27 import CH.ifa.draw.framework.ViewChangeListener;
28 import CH.ifa.draw.standard.ChangeAttributeCommand;
29 import CH.ifa.draw.standard.ChopBoxConnector;
30 import CH.ifa.draw.standard.StandardDrawing;
31 import CH.ifa.draw.util.ColorMap;
32 import CH.ifa.draw.util.CommandChoice;
33 import CH.ifa.draw.util.Filler;
34 import CH.ifa.draw.util.PaletteButton;
35 import CH.ifa.draw.util.PaletteListener;
36 import CH.ifa.draw.util.StandardVersionControlStrategy;
37 import CH.ifa.draw.util.VersionControlStrategy;
38 import CH.ifa.draw.util.VersionManagement;
39 import CH.ifa.draw.util.VersionRequester;
40 import java.awt.BorderLayout JavaDoc;
41 import java.awt.Component JavaDoc;
42 import java.awt.Point JavaDoc;
43 import java.awt.datatransfer.Transferable JavaDoc;
44 import java.awt.dnd.DnDConstants JavaDoc;
45 import java.awt.dnd.DropTarget JavaDoc;
46 import java.awt.dnd.DropTargetDragEvent JavaDoc;
47 import java.awt.dnd.DropTargetDropEvent JavaDoc;
48 import java.awt.dnd.DropTargetEvent JavaDoc;
49 import java.awt.dnd.DropTargetListener JavaDoc;
50 import java.awt.event.ActionEvent JavaDoc;
51 import java.awt.event.ActionListener JavaDoc;
52 import java.awt.event.KeyAdapter JavaDoc;
53 import java.awt.event.KeyEvent JavaDoc;
54 import java.awt.event.MouseAdapter JavaDoc;
55 import java.awt.event.MouseEvent JavaDoc;
56 import java.util.Iterator JavaDoc;
57 import java.util.List JavaDoc;
58 import java.util.Vector JavaDoc;
59 import javax.swing.JComboBox JavaDoc;
60 import javax.swing.JLabel JavaDoc;
61 import javax.swing.JPanel JavaDoc;
62 import javax.swing.JScrollPane JavaDoc;
63 import org.objectweb.jac.aspects.gui.CollectionUpdate;
64 import org.objectweb.jac.aspects.gui.DisplayContext;
65 import org.objectweb.jac.aspects.gui.EventHandler;
66 import org.objectweb.jac.aspects.gui.GuiAC;
67 import org.objectweb.jac.aspects.gui.Transfer;
68 import org.objectweb.jac.aspects.gui.Utils;
69 import org.objectweb.jac.aspects.gui.ViewFactory;
70 import org.objectweb.jac.aspects.gui.swing.AbstractView;
71 import org.objectweb.jac.aspects.gui.swing.SwingEvents;
72 import org.objectweb.jac.core.rtti.ClassRepository;
73 import org.objectweb.jac.core.rtti.CollectionItem;
74 import org.objectweb.jac.ide.Aspect;
75 import org.objectweb.jac.ide.Class;
76 import org.objectweb.jac.ide.Diagram;
77 import org.objectweb.jac.ide.InheritanceLink;
78 import org.objectweb.jac.ide.Link;
79 import org.objectweb.jac.ide.ModelElement;
80 import org.objectweb.jac.ide.Package;
81 import org.objectweb.jac.ide.RelationLink;
82 import org.objectweb.jac.ide.RelationRole;
83 import org.objectweb.jac.ide.TypedElement;
84 import org.objectweb.jac.util.Log;
85 import org.objectweb.jac.util.Strings;
86
87 public class DiagramView extends AbstractView
88     implements DrawingEditor, PaletteListener, VersionRequester,
89               CollectionUpdate, DropTargetListener JavaDoc
90 {
91     static public boolean init = false;
92
93     protected Diagram diagram;
94
95     public DiagramView(ViewFactory factory, DisplayContext context,
96                        Object JavaDoc diagram) {
97         super(factory,context);
98         new DropTarget JavaDoc(this, // component
99
DnDConstants.ACTION_COPY_OR_MOVE, // actions
100
this); // DropTargetListener
101
this.diagram = (Diagram)diagram;
102         init();
103         Utils.registerCollection(diagram,"figures",this);
104     }
105
106     public void close(boolean validate) {
107         Log.trace("diagram","CLOSING DIAGRAM "+this);
108         super.close(validate);
109         FigureEnumeration figures = fDrawing.figures();
110         while (figures.hasMoreElements()) {
111             Figure f = figures.nextFigure();
112             if (f instanceof ModelElementFigure)
113                 ((ModelElementFigure)f).close();
114         }
115         Utils.unregisterCollection(diagram,"figures",this);
116     }
117
118     public Object JavaDoc getSubstance() {
119         return diagram;
120     }
121
122     public final Diagram getDiagram() {
123         return diagram;
124     }
125
126     /**
127      * Add a figure for a class at a given location
128      * @param cl the class to add a figure for
129      * @param location where to put the class figure
130      */

131     public void addClass(Class JavaDoc cl, Point JavaDoc location) {
132         Diagram diagram = (Diagram)getSubstance();
133         if (diagram.contains(cl))
134             return;
135         ClassFigure cf = null;
136         org.objectweb.jac.ide.ClassFigure figure = new org.objectweb.jac.ide.ClassFigure(cl);
137         Log.trace("diagram","diagram = "+diagram);
138         diagram.addFigure(figure);
139         Log.trace("diagram","creating new figure "+figure+","+
140                   diagram.getContainer());
141         cf = new ClassFigure(figure,diagram.getContainer(),
142                              view());
143         (view().add(cf)).displayBox(location,location);
144     }
145
146     /**
147      * Import all relations and inheritance links between a class with
148      * other classes on the diagram
149      * @param cl the class to import relations for
150      */

151     public void importRelations(Class JavaDoc cl) {
152         Iterator JavaDoc it = diagram.getMissingRelations(cl).iterator();
153         while (it.hasNext()) {
154             Link relation = (Link)it.next();
155             try {
156                 if (relation instanceof RelationLink)
157                     importRelation((RelationLink)relation);
158                 else if (relation instanceof InheritanceLink)
159                     importInheritance((InheritanceLink)relation);
160             } catch (Exception JavaDoc e) {
161                  Log.warning(e.getMessage());
162             }
163         }
164     }
165
166     /**
167      * Import a relation in the diagram.
168      * @param relation the relation to import
169      * @throws Exception if both classes of the relation are not on the diagram
170      */

171     public void importRelation(RelationLink relation) throws Exception JavaDoc {
172         ClassFigure endFig = findClass((Class JavaDoc)relation.getEnd());
173         if (endFig==null) {
174             throw new Exception JavaDoc("Cannot import relation "+GuiAC.toString(relation)+
175                                 " since "+GuiAC.toString(relation.getEnd())+
176                                 " is not on the diagram");
177         }
178         ClassFigure startFig = findClass((Class JavaDoc)relation.getStart());
179         if (startFig==null) {
180             throw new Exception JavaDoc("Cannot import relation "+GuiAC.toString(relation)+
181                                 " since "+GuiAC.toString(relation.getStart())+
182                                 " is not on the diagram");
183         }
184
185         org.objectweb.jac.ide.LinkFigure linkFig = new org.objectweb.jac.ide.LinkFigure(relation);
186         diagram.addFigure(linkFig);
187       
188         RelationLinkFigure relf = new RelationLinkFigure();
189         relf.setLinkFigure(linkFig);
190
191         relf.startPoint(startFig.center());
192         relf.endPoint(endFig.center());
193         relf.connectStart(startFig.connectorAt(startFig.center()));
194         relf.connectEnd(endFig.connectorAt(endFig.center()));
195
196         relf.updateConnection();
197       
198         view().add(relf);
199         if (relation.getName()!=null && !relation.getName().equals(""))
200             view().add(relf.createName());
201         if (relation.getEndRole()!=null && !relation.getEndRole().equals(""))
202             view().add(relf.createEndRole());
203         if (relation.getStartRole()!=null && !relation.getStartRole().equals(""))
204             view().add(relf.createStartRole());
205         String JavaDoc startCardinality = relation.startRole().getCardinality();
206         if (startCardinality!=null && !startCardinality.equals(""))
207             view().add(relf.createStartCardinality());
208         String JavaDoc endCardinality = relation.endRole().getCardinality();
209         if (endCardinality!=null && !endCardinality.equals(""))
210             view().add(relf.createEndCardinality());
211       
212         Utils.registerObject(relation,relf);
213     }
214
215     /**
216      * Import an inheritance link in the diagram. An exception
217      * @param inheritance the inheritance link to import
218      */

219     public void importInheritance(InheritanceLink inheritance) throws Exception JavaDoc {
220         ClassFigure endFig = findClass((Class JavaDoc)inheritance.getEnd());
221         ClassFigure startFig = findClass((Class JavaDoc)inheritance.getStart());
222       
223         org.objectweb.jac.ide.LinkFigure linkFig = new org.objectweb.jac.ide.LinkFigure(inheritance);
224         diagram.addFigure(linkFig);
225       
226         InheritanceLinkFigure relf = new InheritanceLinkFigure();
227         relf.setLinkFigure(linkFig);
228
229         relf.startPoint(startFig.center());
230         relf.endPoint(endFig.center());
231         relf.connectStart(startFig.connectorAt(startFig.center()));
232         relf.connectEnd(endFig.connectorAt(endFig.center()));
233
234         relf.updateConnection();
235       
236         view().add(relf);
237       
238         Utils.registerObject(inheritance,relf);
239     }
240
241     /**
242      * Create a RelationLink between two classes.
243      *
244      * @param source start class of the link
245      * @param target end class of the link
246      * @param linkFigure the figure that represents the relation
247      * @param isAggregation wether the relation is an aggregation
248      */

249     public void createRelation(Class JavaDoc source, Class JavaDoc target,
250                                RelationLinkFigure linkFigure,
251                                boolean isAggregation) {
252         Log.trace("figures","creating a new relation link between "+
253                   source+" and "+target);
254
255         RelationLink rel = new RelationLink(source,target);
256         rel.setAggregation(isAggregation);
257         Log.trace("diagram","1. end="+rel.getEnd()+"===> substance="+target);
258         org.objectweb.jac.ide.LinkFigure linkFig = new org.objectweb.jac.ide.LinkFigure(rel);
259         linkFigure.setLinkFigure(linkFig);
260         view().add(linkFigure.createName());
261         view().add(linkFigure.createEndRole());
262         view().add(linkFigure.createStartRole());
263         view().add(linkFigure.createStartCardinality());
264         view().add(linkFigure.createEndCardinality());
265       
266         Log.trace("diagram","2. end="+rel.getEnd());
267
268         if (source==target) {
269             Point JavaDoc c = linkFigure.endFigure().center();
270             linkFig.addPoint(1,new Point JavaDoc(c.x+100,c.y));
271             linkFig.addPoint(1,new Point JavaDoc(c.x+100,c.y+100));
272             linkFig.addPoint(1,new Point JavaDoc(c.x,c.y+100));
273         }
274       
275         diagram.addFigure(linkFig);
276
277         Utils.registerObject(rel,linkFigure);
278         Log.trace("diagram","3. end="+rel.getEnd());
279     }
280
281     // drop listener interface
282
public void drop(DropTargetDropEvent JavaDoc e) {
283         try {
284             Transferable JavaDoc tr = e.getTransferable();
285             List JavaDoc transfered = Transfer.getTransferedWrappees(tr);
286             Object JavaDoc o = transfered.get(0);
287             Point JavaDoc location = e.getLocation();
288             Point JavaDoc offset = scrollPane.getViewport().getViewPosition();
289             location.translate((int)offset.getX(),(int)offset.getY());
290             Log.trace("gui.dnd","drop event: "+o);
291             if (o==null)
292                 return;
293             if (o instanceof Class JavaDoc) {
294                 addClass((Class JavaDoc)o,location);
295             } else if (o instanceof RelationRole) {
296                 importRelation((RelationLink)((RelationRole)o).getLink());
297             }
298
299         } catch(Exception JavaDoc ex) {
300             ex.printStackTrace();
301         }
302     }
303     public void dragEnter(DropTargetDragEvent JavaDoc e) { }
304     public void dragExit(DropTargetEvent JavaDoc e) { }
305     public void dragOver(DropTargetDragEvent JavaDoc e) { }
306     public void dropActionChanged(DropTargetDragEvent JavaDoc e) { }
307     // end of drop listener interface
308

309     public void figureSelectionChanged(DrawingView view) {
310         if (view.selection().size() > 0) {
311             Figure f = (Figure)view.selection().get(0);
312
313             Log.trace("figures","figure "+f+" selected");
314
315             if (f instanceof Selectable) {
316                 ((Selectable)f).onSelect(getContext());
317             }
318
319             if (f instanceof ClassFigure) {
320                 CollectionItem coll = ClassRepository.get().getClass(Package JavaDoc.class)
321                     .getCollection("classes");
322                 EventHandler.get().onSelection(
323                     getContext(),coll,((ClassFigure)f).getSubstance(),null,null);
324
325             } else if (f instanceof InstanceFigure) {
326                 CollectionItem coll = ClassRepository.get().getClass(Package JavaDoc.class)
327                     .getCollection("instances");
328                 EventHandler.get().onSelection(
329                     getContext(),coll,((InstanceFigure)f).getSubstance(),null,null);
330
331             } else if (f instanceof GenericObjectFigure) {
332
333                 Log.trace("figures","generic object");
334                 EventHandler.get().onSelection(
335                     getContext(),
336                     ((GenericObjectFigure)f).getCollection(),
337                     ((GenericObjectFigure)f).getSubstance(),null,null);
338
339             } else if (f instanceof RelationLinkFigure ||
340                        f instanceof AttachedTextFigure) {
341             
342                 RelationLink rel = (RelationLink)
343                     ((ModelElementFigure)f).getSubstance();
344                 Class JavaDoc cl = (Class JavaDoc)rel.getStart();
345                 CollectionItem coll = ClassRepository.get().getClass(Package JavaDoc.class)
346                     .getCollection("classes");
347                 EventHandler.get().onSelection(getContext(),coll,cl,null,null);
348                 coll = ClassRepository.get().getClass(Class JavaDoc.class)
349                     .getCollection("relationRoles");
350                 EventHandler.get().onSelection(getContext(),coll,
351                                                rel.getStartRole(),null,null);
352                 //((RelationLinkFigure)f).selectAll(view);
353

354             } else if (f instanceof PointcutLinkFigure) {
355             
356                 org.objectweb.jac.ide.PointcutLink rel = (org.objectweb.jac.ide.PointcutLink)
357                     ((PointcutLinkFigure)f).getSubstance();
358                 org.objectweb.jac.ide.Aspect aspect = (org.objectweb.jac.ide.Aspect)rel.getStart();
359                 CollectionItem coll = ClassRepository.get().getClass(Package JavaDoc.class)
360                     .getCollection("aspects");
361                 EventHandler.get().onSelection(getContext(),coll,aspect,null,null);
362                 coll = ClassRepository.get().getClass(Aspect.class)
363                     .getCollection("pointcutLinks");
364                 EventHandler.get().onSelection(getContext(),coll,rel,null,null);
365                 //((PointcutLinkFigure)f).selectAll(view);
366
}
367         }
368         // update(getGraphics());
369
}
370
371     private transient Drawing fDrawing;
372     private transient Tool fTool;
373    
374     private transient DrawingView fView;
375     private transient ToolButton fSelectedToolButton;
376    
377     static String JavaDoc fgUntitled = "untitled";
378    
379     ToolPalette classPalette;
380     ToolPalette aspectPalette;
381     ToolPalette instancePalette;
382     ToolPalette groupPalette;
383     ToolPalette currentPalette;
384
385     /**
386      * Find the figure of a given class in the default drawing.
387      * @param cl the Class to search for
388      * @return a ModelElementFigure that matches cl, or null if none is found.
389      */

390     public ClassFigure findClass(Class JavaDoc cl) {
391         return (ClassFigure)findFigure(view().drawing(),cl);
392     }
393
394     /**
395      * Find the figure of a given model element
396      * @param drawing the Drawing to search the figure into
397      * @param cl the Class to search for
398      * @return a ModelElementFigure that matches cl, or null if none is found.
399      */

400     public ClassFigure findClass(Drawing drawing, Class JavaDoc cl) {
401         return (ClassFigure)findFigure(drawing,cl);
402     }
403
404     /**
405      * Find the figure of a given model element.
406      * @param drawing the Drawing to search the figure into
407      * @param element the ModelElement to search for
408      * @return a ModelElementFigure that matches element, or null if none is found.
409      */

410     public ModelElementFigure findFigure(Drawing drawing, ModelElement element) {
411         FigureEnumeration figs = drawing.figures();
412         while(figs.hasMoreElements()) {
413             Figure fig = figs.nextFigure();
414             if( (fig instanceof ModelElementFigure) &&
415                 ((ModelElementFigure)fig).getSubstance() == element) {
416                 return (ModelElementFigure)fig;
417             }
418         }
419         return null;
420     }
421
422     /**
423      * Find the figure of a given TypedElement
424      */

425     public Figure findElement(TypedElement te) {
426         FigureEnumeration figs = view().drawing().figures();
427         while(figs.hasMoreElements()) {
428             Figure fig = figs.nextFigure();
429             if( (fig instanceof ModelElementFigure) &&
430                 ((ModelElementFigure)fig).getSubstance() == te) {
431                 return fig;
432             }
433         }
434         return null;
435     }
436
437     /**
438      * Find the figure of a given ModelElement
439      */

440     public Figure findElement(ModelElement element) {
441         FigureEnumeration figs = view().drawing().figures();
442         while(figs.hasMoreElements()) {
443             Figure fig = figs.nextFigure();
444             if( (fig instanceof ModelElementFigure) &&
445                 ((ModelElementFigure)fig).getSubstance() == element) {
446                 return fig;
447             }
448         }
449         return null;
450     }
451    
452     JScrollPane JavaDoc scrollPane;
453     /**
454      * Initializes the applet and creates its contents.
455      */

456     public void init() {
457         //DiagramView.display = display;
458
//diagramViews.add(this);
459

460         getVersionControlStrategy().assertCompatibleVersion();
461         
462         setLayout(new BorderLayout JavaDoc());
463
464         fView = createDrawingView();
465
466         try {
467             buildClassBar();
468         } catch (Exception JavaDoc e) {
469             e.printStackTrace();
470         }
471
472         scrollPane = new JScrollPane JavaDoc((Component JavaDoc)view());
473         add("Center", scrollPane);
474         JPanel JavaDoc buttonPalette = createButtonPanel();
475         createButtons(buttonPalette);
476         add("North", buttonPalette);
477         setToolBar(buildClassBar());
478
479         initDrawing();
480         // JFC should have its own internal double buffering...
481
//setBufferedDisplayUpdate();
482
//setupAttributes();
483
load();
484         //((JComponent)drawing()).setMinimumSize(new Dimension(2000,2000));
485
}
486
487     public void addViewChangeListener(ViewChangeListener vsl) {
488     }
489
490     public void removeViewChangeListener(ViewChangeListener vsl) {
491     }
492
493
494     /**
495      * Creates the color choice for the given attribute.
496      */

497     protected JComboBox JavaDoc createColorChoice(String JavaDoc attribute) {
498         CommandChoice choice = new CommandChoice();
499         for (int i = 0; i < ColorMap.size(); i++)
500             choice.addItem(
501                 new ChangeAttributeCommand(
502                     ColorMap.name(i),
503                     attribute,
504                     ColorMap.color(i),
505                     this
506                 )
507                     );
508         return choice;
509     }
510
511     /**
512      * Creates the buttons panel.
513      */

514     protected JPanel JavaDoc createButtonPanel() {
515         JPanel JavaDoc panel = new JPanel JavaDoc();
516         panel.setLayout(new PaletteLayout(2, new Point JavaDoc(2,2), false));
517         return panel;
518     }
519
520     /**
521      * Sets the tool bar containing tool buttons.
522      */

523     void setToolBar(ToolPalette newPalette) {
524         if (currentPalette != null) {
525             remove(currentPalette);
526         }
527         add(BorderLayout.WEST, newPalette);
528         currentPalette = newPalette;
529         validate();
530     }
531
532     ToolPalette buildClassBar() {
533         Log.trace("diagram","BUILDING CLASS BAR");
534         classPalette = new ToolPalette();
535
536         classPalette.setDefaultToolButton(
537             classPalette.addToolButton(this, "icon_selection", "Selection Tool",
538                                        createSelectionTool()));
539
540         classPalette.addToolButton(this, "icon_text", "Text Tool",
541                                    new TextTool(this, new TextFigure()));
542         classPalette.addToolButton(this, "icon_class", "Create a new class",
543                                    new NewClassFigureCreationTool(this,getContext()));
544         classPalette.addToolButton(this, "icon_import_class", "Add an existing class",
545                                    new ClassFigureCreationTool(this,getContext()));
546         try {
547             classPalette.addToolButton(this, "icon_see_relation", "Show existing relation",
548                                        new RelationLinkShowTool(this,getContext()));
549         } catch (ClassNotFoundException JavaDoc e) {
550             e.printStackTrace();
551         }
552         classPalette.addToolButton(this, "icon_relation", "New relation link",
553                                    new RelationLinkCreationTool(this));
554         classPalette.addToolButton(this, "icon_add_point", "Add a point",
555                                    new ConnectionTool(this, new RelationLinkFigure()));
556         classPalette.addToolButton(this, "icon_inheritance", "Inheritance link",
557                                    new InheritanceLinkCreationTool(this));
558         classPalette.addToolButton(this, "icon_field", "Create new attribute",
559                                    new FieldCreationTool(this,getContext()));
560         classPalette.addToolButton(this, "icon_method", "Create new method",
561                                    new MethodCreationTool(this,getContext()));
562         return classPalette;
563     }
564
565     ToolPalette buildAspectBar() {
566         Log.trace("diagram","BUILDING ASPECT BAR");
567       
568         aspectPalette = new ToolPalette();
569       
570         aspectPalette.setDefaultToolButton(
571             aspectPalette.addToolButton(this, "icon_selection", "Selection Tool",
572                                         createSelectionTool()));
573       
574         aspectPalette.addToolButton(this, "icon_text", "Text Tool",
575                                     new TextTool(this, new TextFigure()));
576         aspectPalette.addToolButton(this, "icon_aspect", "Create a new aspect",
577                                     new NewAspectFigureCreationTool(this,getContext()));
578         aspectPalette.addToolButton(this, "icon_import_aspect", "Add an existing aspect",
579                                     new AspectFigureCreationTool(this,getContext()));
580         aspectPalette.addToolButton(this, "icon_pointcut", "New pointcut link",
581                                     new PointcutLinkCreationTool(this, new PointcutLinkFigure()));
582         aspectPalette.addToolButton(this, "icon_see_pointcut", "Show existing pointcut",
583                                     new PointcutLinkShowTool(this,getContext()));
584         aspectPalette.addToolButton(this, "icon_add_point", "Add a point",
585                                     new ConnectionTool(this, new RelationLinkFigure()));
586         aspectPalette.addToolButton(this, "icon_field", "Create new attribute",
587                                     new FieldCreationTool(this,getContext()));
588         aspectPalette.addToolButton(this, "icon_method", "Create new configuration method",
589                                     new MethodCreationTool(this,getContext()));
590         aspectPalette.addToolButton(this, "icon_aspect_method","Create new aspect method",
591                                     new MethodCreationTool(this,getContext()));
592         return aspectPalette;
593     }
594
595     ToolPalette buildInstanceBar() {
596         Log.trace("diagram","BUILDING INSTANCE BAR");
597          
598         instancePalette = new ToolPalette();
599       
600         instancePalette.setDefaultToolButton(
601             instancePalette.addToolButton(this, "icon_selection", "Selection Tool",
602                                           createSelectionTool()));
603         instancePalette.addToolButton(this, "icon_text", "Text Tool",
604                                       new TextTool(this, new TextFigure()));
605         instancePalette.addToolButton(this, "icon_instance", "Create a new instance",
606                                       new NewInstanceFigureCreationTool(this,getContext()));
607         instancePalette.addToolButton(this, "icon_import_instance", "Add an existing instance",
608                                       new InstanceFigureCreationTool(this,getContext()));
609         return instancePalette;
610     }
611
612     ToolPalette buildGroupBar() {
613         Log.trace("diagram","BUILDING GROUP BAR");
614          
615         groupPalette = new ToolPalette();
616
617         groupPalette.setDefaultToolButton(
618             groupPalette.addToolButton(this,"icon_selection", "Selection Tool",
619                                        createSelectionTool()));
620         groupPalette.addToolButton(this,"icon_text", "Text Tool",
621                                    new TextTool(this, new TextFigure()));
622         groupPalette.addToolButton(this, "icon_group", "Create a new group",
623                                    new NewInstanceFigureCreationTool(this,getContext()));
624         groupPalette.addToolButton(this, "icon_import_group", "Add an existing group",
625                                    new GroupFigureShowTool(this,getContext()));
626         return groupPalette;
627     }
628
629     /**
630      * Creates the buttons shown in the buttons panel. Override to
631      * add additional buttons.
632      * @param panel the buttons panel.
633      */

634     protected void createButtons(JPanel JavaDoc panel) {
635         panel.add(new Filler(24,20));
636         JLabel JavaDoc title = new JLabel JavaDoc(GuiAC.toString(diagram)+" diagram ");
637         panel.add(title);
638
639         panel.add(new Filler(6,20));
640
641         JComboBox JavaDoc combo = new JComboBox JavaDoc(new Object JavaDoc[] {
642             "class mode",
643             "aspect mode",
644             "instance mode",
645             "group mode"}
646         );
647
648         combo.addActionListener(
649             new ActionListener JavaDoc() {
650                     public void actionPerformed(ActionEvent JavaDoc event) {
651                         JComboBox JavaDoc cb = (JComboBox JavaDoc)event.getSource();
652                         String JavaDoc command = (String JavaDoc)cb.getSelectedItem();
653                         if (command.equals("class mode")) {
654                             setToolBar(buildClassBar());
655                         } else if (command.equals("aspect mode")) {
656                             setToolBar(buildAspectBar());
657                         } else if (command.equals("instance mode")) {
658                             setToolBar(buildInstanceBar());
659                         } else if (command.equals("group mode")) {
660                             setToolBar(buildGroupBar());
661                         }
662                         setSelected(currentPalette.getDefaultToolButton());
663                     }
664                 }
665         );
666
667         panel.add(combo);
668         coord = new JLabel JavaDoc("(--,--)");
669         panel.add(coord);
670     }
671
672     JLabel JavaDoc coord;
673     public void setCoord(int x, int y) {
674         coord.setText("("+x+","+y+")");
675     }
676
677     /**
678      * Creates the tools palette.
679      */

680     protected JPanel JavaDoc createToolPalette() {
681         JPanel JavaDoc palette = new JPanel JavaDoc();
682         palette.setLayout(new PaletteLayout(2,new Point JavaDoc(2,2)));
683         return palette;
684     }
685
686     /**
687      * Creates the selection tool used in this editor. Override to use
688      * a custom selection tool.
689      */

690     protected Tool createSelectionTool() {
691         return new SelectionTool(this,getContext());
692     }
693
694     /**
695      * Creates the drawing used in this application.
696      * You need to override this method to use a Drawing
697      * subclass in your application. By default a standard
698      * Drawing is returned.
699      */

700     protected Drawing createDrawing() {
701         return new StandardDrawing();
702     }
703
704     /**
705      * Creates the drawing view used in this application.
706      * You need to override this method to use a DrawingView
707      * subclass in your application. By default a standard
708      * DrawingView is returned.
709      */

710     protected DrawingView createDrawingView() {
711         IDEDrawingView view = new IDEDrawingView(this, 2000, 2000);
712         view.addMouseListener(
713             new MouseAdapter JavaDoc() {
714                     public void mousePressed(MouseEvent JavaDoc e) {
715                         // Show popup menu
716
if (e.isPopupTrigger()) {
717                             Figure figure = drawing().findFigure(e.getX(), e.getY());
718                             if (figure instanceof ModelElementFigure) {
719                                 ModelElement element =
720                                     ((ModelElementFigure)figure).getSubstance();
721                                 if (figure instanceof ClassFigure) {
722                                     Figure memberFigure = figure.findFigureInside(e.getX(), e.getY());
723                                     if (memberFigure instanceof MemberFigure) {
724                                         SwingEvents.showObjectsMenu(
725                                             getContext(),
726                                             new Object JavaDoc[] {((ClassFigure)figure).getClassFig(),
727                                                           element,
728                                                           ((MemberFigure)memberFigure).getSubstance()},
729                                             e);
730                                     } else {
731                                         SwingEvents.showObjectsMenu(
732                                             getContext(), new Object JavaDoc[] {((ClassFigure)figure).getClassFig(),element}, e);
733                                     }
734                                 } else {
735                                     SwingEvents.showObjectMenu(getContext(), element, e);
736                                 }
737                             }
738                         }
739                     }
740                 }
741         );
742
743         view.addKeyListener(
744             new KeyAdapter JavaDoc() {
745                     public void keyPressed(KeyEvent JavaDoc e) {
746                         int code = e.getKeyCode();
747                         if ((code == KeyEvent.VK_BACK_SPACE) ||
748                             (code == KeyEvent.VK_DELETE))
749                         {
750                             Log.trace("ide.diagram","DELETE");
751                             Vector JavaDoc selection = view().selection();
752                             for (int i=0; i<selection.size(); i++) {
753                                 Figure figure = (Figure)selection.get(i);
754                                 if (figure instanceof ClassFigure ||
755                                     figure instanceof LinkFigure) {
756                                     Log.trace("ide.diagram","removing "+figure);
757                                     ModelElement element =
758                                         ((ModelElementFigure)figure).getSubstance();
759                                     diagram.removeElement(element);
760                                 }
761                                 if (e.isControlDown()) {
762                                     Log.trace("ide.diagram","DELETE REAL");
763                                     if (figure instanceof ClassFigure) {
764                                         Class JavaDoc cl =
765                                             (Class JavaDoc)((ModelElementFigure)figure).getSubstance();
766                                         cl.getContainer().removeClass(cl);
767                                     } else if (figure instanceof RelationLinkFigure) {
768                                         RelationLink link =
769                                             (RelationLink)((ModelElementFigure)figure).getSubstance();
770                                         link.setStart(null);
771                                         link.setEnd(null);
772                                     } else if (figure instanceof InheritanceLinkFigure) {
773                                         InheritanceLink link =
774                                             (InheritanceLink)((ModelElementFigure)figure).getSubstance();
775                                         ((Class JavaDoc)link.getStart()).setSuperClass(null);
776                                     }
777                                 }
778                             }
779                             view().clearSelection();
780                         }
781                     }
782                 }
783         );
784         return view;
785     }
786
787     /**
788      * Handles a user selection in the palette.
789      * @see PaletteListener
790      */

791     public void paletteUserSelected(PaletteButton button) {
792         ToolButton toolButton = (ToolButton)button;
793         Log.trace("palette","paletteUserSelected "+toolButton.getTool());
794         setTool(toolButton.getTool(), toolButton.getName());
795         setSelected(toolButton);
796     }
797
798     /**
799      * Handles when the mouse enters or leaves a palette button.
800      * @see PaletteListener
801      */

802     public void paletteUserOver(PaletteButton button, boolean inside) {
803         if (inside) {
804             showStatus(((ToolButton)button).name());
805         } else {
806             if(fSelectedToolButton==null) {
807                 showStatus("");
808             } else {
809                 showStatus(fSelectedToolButton.name());
810             }
811         }
812     }
813
814     /**
815      * Gets the current drawing.
816      * @see DrawingEditor
817      */

818     public Drawing drawing() {
819         return fDrawing;
820     }
821
822     /**
823      * Gets the current tool.
824      * @see DrawingEditor
825      */

826     public Tool tool() {
827         return fTool;
828     }
829
830     /**
831      * Gets the current drawing view.
832      * @see DrawingEditor
833      */

834     public DrawingView view() {
835         return fView;
836     }
837
838     public DrawingView[] views() {
839         return new DrawingView[] { view() } ;
840     }
841
842     /**
843      * Sets the default tool of the editor.
844      * @see DrawingEditor
845      */

846     public void toolDone() {
847         if (currentPalette!=null) {
848             ToolButton button = currentPalette.getDefaultToolButton();
849             if (button!=null) {
850                 setTool(button.getTool(), button.getName());
851                 setSelected(button);
852             }
853         }
854     }
855
856     public void viewSelectionChanged(DrawingView oldView, DrawingView newView) {
857     }
858
859     private void initDrawing() {
860         fDrawing = createDrawing();
861         view().setDrawing(fDrawing);
862         toolDone();
863     }
864
865     private void setTool(Tool t, String JavaDoc name) {
866         Log.trace("palette","setTool "+t+" current="+fTool);
867         if (fTool != null) {
868             fTool.deactivate();
869         }
870         fTool = t;
871         if (fTool != null) {
872             showStatus(name);
873             fTool.activate();
874         }
875     }
876
877     private void setSelected(ToolButton button) {
878         if (fSelectedToolButton != null) {
879             fSelectedToolButton.reset();
880         }
881         fSelectedToolButton = button;
882         if (fSelectedToolButton != null) {
883             fSelectedToolButton.select();
884         }
885     }
886
887     protected VersionControlStrategy getVersionControlStrategy() {
888         return new StandardVersionControlStrategy(this);
889     }
890
891     /**
892      * Subclasses should override this method to specify to which versions of
893      * JHotDraw they are compatible. A string array is returned so it is possible
894      * to specify several version numbers of JHotDraw to which the application
895      * is compatible with.
896      *
897      * @return all versions number of JHotDraw the application is compatible with.
898      */

899     public String JavaDoc[] getRequiredVersions() {
900         String JavaDoc[] requiredVersions = new String JavaDoc[1];
901         // return the version of the package we are in
902
requiredVersions[0] =
903             VersionManagement.getPackageVersion(DiagramView.class.getPackage());
904         return requiredVersions;
905     }
906
907     /**
908      * Initialize from the org.objectweb.jac.ide.Diagram
909      */

910     public void load() {
911         toolDone();
912
913         if (diagram == null) {
914             Log.error("no diagram");
915             return;
916         }
917
918         init=true;
919
920         try {
921             Log.trace("diagram","initializing drawing");
922             fDrawing.release();
923             fDrawing = new StandardDrawing();
924             Vector JavaDoc links = new Vector JavaDoc();
925             Vector JavaDoc ilinks = new Vector JavaDoc();
926             Iterator JavaDoc i = getDiagram().getFigures().iterator();
927             while (i.hasNext()) {
928                 Object JavaDoc figure = i.next();
929                 try {
930                     if (figure instanceof org.objectweb.jac.ide.ClassFigure) {
931                         if (((org.objectweb.jac.ide.ClassFigure)figure).getCl()
932                             instanceof org.objectweb.jac.ide.Aspect) {
933                             fDrawing.add(
934                                 new AspectFigure((org.objectweb.jac.ide.ClassFigure)figure,
935                                                  getDiagram().getContainer(),
936                                                  view()));
937                         } else {
938                             fDrawing.add(
939                                 new ClassFigure((org.objectweb.jac.ide.ClassFigure)figure,
940                                                 getDiagram().getContainer(),
941                                                 view()));
942                         }
943                     } else if (figure instanceof org.objectweb.jac.ide.LinkFigure) {
944                         Figure linkFigure = null;
945                         Link link = ((org.objectweb.jac.ide.LinkFigure)figure).getLink();
946                         if (link instanceof org.objectweb.jac.ide.RelationLink) {
947                             linkFigure =
948                                 new RelationLinkFigure((org.objectweb.jac.ide.LinkFigure)figure);
949                         } else if (link instanceof org.objectweb.jac.ide.PointcutLink) {
950                             linkFigure =
951                                 new PointcutLinkFigure((org.objectweb.jac.ide.LinkFigure)figure);
952                         } else if (link instanceof org.objectweb.jac.ide.InheritanceLink) {
953                             linkFigure =
954                                 new InheritanceLinkFigure((org.objectweb.jac.ide.LinkFigure)figure);
955                         }
956                         links.add(linkFigure);
957                     }
958                 } catch(Exception JavaDoc e) {
959                     Log.error("cannot load figure "+figure);
960                     e.printStackTrace();
961                 }
962             }
963
964             // connect links
965
i = links.iterator();
966             while (i.hasNext()) {
967                 LinkFigure linkFigure = (LinkFigure)i.next();
968                 Log.trace("diagram","importing link "+linkFigure);
969                 Link link = (Link)linkFigure.getSubstance();
970                 ClassFigure start = findClass(fDrawing,(Class JavaDoc)link.getStart());
971                 Log.trace("diagram","link start "+link.getStart()+" -> "+start);
972                 if (start!=null) {
973                     linkFigure.connectStart(new ChopBoxConnector(start));
974                     linkFigure.startPoint(start.getCorner().x,start.getCorner().y);
975                 }
976                 ClassFigure end = findClass(fDrawing,(Class JavaDoc)link.getEnd());
977                 Log.trace("diagram","link end "+link.getEnd()+" -> "+end);
978                 if (end!=null) {
979                     linkFigure.connectEnd(new ChopBoxConnector(end));
980                     linkFigure.endPoint(end.getCorner().x,end.getCorner().y);
981                 }
982                 if (start!=null && end!=null)
983                     linkFigure.updateConnection();
984                 if (start!=null && end!=null) {
985                     fDrawing.add(linkFigure);
986                     linkFigure.load(fDrawing);
987                 } else {
988                     Log.warning("diagram",
989                                 "Bad link: start = "+link.getStart()+" -> "+start+
990                                 "; end = "+link.getEnd()+" -> "+end);
991                 }
992             }
993
994             // connect ilinks
995
/*i = ilinks.iterator();
996               while (i.hasNext()) {
997               InheritanceLinkFigure linkFigure
998               = (InheritanceLinkFigure)i.next();
999               Log.trace("diagram","importing link "+linkFigure);
1000              Link link = (Link)linkFigure.getLinkFigure().getLink();
1001              ClassFigure start = findClass(fDrawing,(Class)link.getStart());
1002              Log.trace("diagram","link start "+link.getStart()+" -> "+start);
1003              if (start!=null) {
1004              linkFigure.connectStart(new ChopBoxConnector(start));
1005              linkFigure.startPoint(start.getCorner().x,start.getCorner().y);
1006              }
1007              ClassFigure end = findClass(fDrawing,(Class)link.getEnd());
1008              Log.trace("diagram","link start "+link.getEnd()+" -> "+end);
1009              if (end!=null) {
1010              linkFigure.connectEnd(new ChopBoxConnector(end));
1011              linkFigure.endPoint(end.getCorner().x,end.getCorner().y);
1012              }
1013              linkFigure.updateConnection();
1014              fDrawing.add(linkFigure);
1015              linkFigure.load(fDrawing);
1016              }*/

1017
1018            Log.trace("diagram","sets the drawing");
1019            view().setDrawing(fDrawing);
1020            toolDone();
1021        } catch (Exception JavaDoc e) {
1022            initDrawing();
1023            e.printStackTrace();
1024            showStatus("Error:" + e);
1025        } finally {
1026            init=false;
1027        }
1028    }
1029
1030    public void showStatus(String JavaDoc msg) {
1031        if (getContext()!=null) {
1032            getContext().getCustomizedView().showStatus(msg);
1033        }
1034        if (!Strings.isEmpty(msg))
1035            Log.trace("diagram","Status: "+msg);
1036    }
1037
1038    public String JavaDoc toString() {
1039        return Strings.hex(this);
1040    }
1041
1042    // CollectionUpdate interface
1043

1044    public void onChange(Object JavaDoc substance,
1045                         CollectionItem collection, Object JavaDoc value,
1046                         Object JavaDoc param) {
1047    }
1048
1049    public void onAdd(Object JavaDoc substance,
1050                      CollectionItem collection, Object JavaDoc value,
1051                      Object JavaDoc added, Object JavaDoc param) {
1052    }
1053
1054    public void onRemove(Object JavaDoc substance, CollectionItem collection, Object JavaDoc value,
1055                         Object JavaDoc removed, Object JavaDoc param) {
1056        Log.trace("diagram.remove","onRemove "+removed);
1057        org.objectweb.jac.ide.Figure removedFigure = (org.objectweb.jac.ide.Figure)removed;
1058        ModelElementFigure figure = findFigure(fDrawing,removedFigure.getElement());
1059        Log.trace("diagram.remove","figure = "+figure);
1060        if (figure!=null) {
1061            Figure fig = fDrawing.remove((Figure)figure);
1062            view().removeFromSelection(figure);
1063            Log.trace("diagram.remove","removed "+fig);
1064            view().repairDamage();
1065        }
1066    }
1067
1068}
1069
Popular Tags