1、Tutorial #23 GEF In Depth,Randy Hudson Pratik Shah IBM Rational Software Research Triangle Park, NC,2,Agenda,Start things off What is GEF? GEF Demo Draw2d Overview Example GEF Overview Break Hands-on Activity: Shapes Example,3,Starting things off,This is an interactive session: feel free to ask ques
2、tions Goals for this tutorial Introduce GEF and Draw2d Highlight main features Show how to find answers easily Provide hands-on experience Steer you around common mistakes Tell us about your GEF Plans Level of experience with GEF?,4,Before we begin,Newer version of these slides are available GEF Hom
3、e Page - Click on Documentation http:/www.eclipse.org/gef/reference/articles.html Youre going to need: Eclipse 3.1M5a GEF SDK 3.1M5 Files for tutorial: unzip into your workspace before launching Eclipse, and then from within Eclipse, Import - Existing Project Into Workspace http:/www.eclipse.org/gef
4、/conference/activity.zip We have CDs,5,What is GEF?,Interaction Layer Model-to-View mapping Workbench Integration,Rendering Layout Scaling,Native (SWT) Layer,6,GEF Components & Dependencies,GEF,ui.views,RCP,Platform Runtime,7,GEF Demo,Features Move, Resize, Create, Bend, Connect Delete, Undo, Redo,
5、Direct-editing Overview & Zooming Palette Viewer and workbench view Palette Customization Rulers & Guides Snap-To-Grid or Geometry Shortest Path Connection Router Keyboard Accessibility Directed Graph Layout,8,Draw2d Overview,Draw2d : SWT : Swing : AWT Lightweight Toolkit built on top of SWT Concept
6、s borrowed from Swing and others Built to support GEF function,9,Contents,FigureCanvas,Draw2D Lightweight System,Figure,SWT Canvas,LWS,EventDispatcher,UpdateManager,Content Root,Figure,Figure,Root Figure,10,Simple lightweight container: building block Fonts, Colors, Opacity, Borders, Layouts, Visibi
7、lity, Bounds, Tool-tip Inherit parents font and color (RootFigure gets it from the Canvas) Can be non-rectangular Can be nested,Figures,Client Area (children paint here),Bounds,Insets,11,Hello World,Display d = new Display(); Shell shell = new Shell(d); shell.setLayout(new FillLayout();FigureCanvas
8、canvas = new FigureCanvas(shell); canvas.setContents(new Label(“Hello World“);shell.setText(“draw2d”); shell.open(); while (!shell.isDisposed()while (!d.readAndDispatch()d.sleep();,123456789 10 11 12,12,Painting and Finding Figures,Figures form a tree Painting is pre-order, “LTR” Parents clip childr
9、en Last painted is “on top” Hit-testing is the opposite,1,3,6,4,5,1,2,2,3,4,5,6,13,Painting continued,Override paintFigure(), not paint() You dont have to worry about maintaining the state of the Graphics object; change settings as you please Order of painting: parent figure, children figures, paren
10、ts border Request repaint() when any property that affects the appearance is changed Double-buffered painting (no flicker),14,LayoutManagers,Responsibilities Position a Figures children: IFigure#setBounds() Provide the preferred sizes based on children and layout Only invalid figures will layout Hin
11、ts passed during size calculations -1 means not confined in that direction AbstractHintLayout caches sizes based on hints Scrollbars visibility determined by preferred size Constraint SWTs LayoutData Example: XYLayout uses Rectangle constraints,15,Layout Managers in Draw2d,Top,BorderLayout,FlowLayou
12、t,Bottom,Left,Right,Center,1,2,3,4,ToolbarLayout,XYLayout,12,8,20,10,30,20,27,14,1,2,3,16,Using Layout Mangers,Layouts place children within the parents “client area” Borders can be used to modify the client area The included layouts can get you far Nest Layouts/Figures to get results Layout Manager
13、s must not be shared Borders may be shared (singletons),17,User Interaction Scenario in Draw2d,FigureCanvas,LWS,SWT EventDispatcher,Root Figure,Content Root,Figure,Deferred UpdateManager,Contents,Figure,Figure,Figure,Figure,2. Listener notifies,1. interacts with,3. delegates to,4. dispatches figure
14、events,5B. revalidates and marks roots as invalid,5A. requests repaint of dirty region,6. validates invalid figures then paints dirty region,18,Coordinate Systems,By default, bounds of parent and children use same coordinates Relative Coordinates useLocalCoordinates() Child positioned relative to pa
15、rents client area Scaling and Translation Viewport Zoom Converting coordinates translateToParent() Translate to parents coordinate system translateFromParent() Translate from parents coordinate system to childs translateToAbsolute() & translateToRelative(),19,Displaying Text,org.eclipse.draw2d.Label
16、 Icon + Text Truncation, Alignment Tip: Use ImageFigure if you only have Images Improved “Rich” Text features in 3.1 org.eclipse.draw2d.text package Content which wraps itself like a paragraph Margins, borders and padding Mixing non-textual components with text API for finding offset based info BiDi
17、 Arabic, Hebrew, etc.,20,Connection extends IFigure,Just Figures with special behavior Render a PointList managed by a ConnectionRouter Have a source and target ConnectionAnchor Define the start and end points of the connection Return locations using absolute coordinates #getLocation(referencePoint)
18、 Context sensitive (ChopBoxAnchor or EllipseAnchor) Routers Responsible for setting all points in a connection May use routing constraints such as Bendpoint Examples: Fan, Bendpoint, Manhattan, ShortestPath,21,Connections continued,Connection can have children too Arrowheads, Labels, etc. Delegating
19、Layout Locator constraints position each child Connections set their own bounds after validating Do not call setBounds() on connections,22,Fig 1,Fig 2,Midpoint,Endpoint,u,v,PolygonDecoration,Anchor Location,PolylineConnection,Labels placed using ConnectionLocators,Connections et al,23,Avoiding Commo
20、n Mistakes,Do not modify Objects returned by reference (e.g., bounds) Use revalidate() and repaint() appropriately Polyline is not a regular Shape Know your coordinate systems Use LineBorder as a debugging tool Cant ask for preferred sizes without Fonts news:/news.eclipse.org,24,Draw2d Exercise,Buil
21、d the following representation of a UML Class Use only the provided classes: ToolbarLayout LineBorder MarginBorder Label (not SWTs) ColorConstants Pack the SWT shell to auto-size Figure structure:,class,heading,attributes,methods,attr1,attr2,method,method,25,The Solution,26,The GEF plug-in,Interacti
22、on Layer Model-to-View mapping Workbench Integration,27,What Problems does GEF Solve?,Display a Model graphically Allow the User to interact with that model Process user input from Mouse & Keyboard Interpret that input Provide hooks for updating the model Make it undo/redo-able Provide useful Workbe
23、nch function Actions and Menus Toolbars, Contributions Keybindings Where Can I use GEF? EditorParts, Views Anywhere in the Workbench,28,Displaying a Model Graphically,Figures are not your model Lots of models to choose from (EMF, DOM) GEF works with any model Model requirements: Notification mechani
24、sm Persist and restore state Commands which operate on the model,29,Displaying a Model Graphically,GraphicalViewer Viewer = Adapter for a Control Manages Draw2ds Figures Construct a Viewer and Canvas TreeViewer uses Tree Set the model input for the ViewerNext: Map the Model into Figures,30,Populatin
25、g a Viewer,Model,GraphicalViewer,EditParts,Figures,EditPart Factory,31,Graphical EditParts and Containment,Model Root (Diagram),“Diagram” EditPart,Children,fig,fig,fig,32,Extending AbstractGraphicalEditPart,createFigure() Just builds the figure refreshVisuals() Reflect the models state in the view g
26、etModelChildren() Determines children to createLooking ahead: Changing the model Responding to model changes,33,Connection EditParts,Similarities to children parts: Return a list of model objects: getModelSource/TargetConnections() Factory can create the Connection PartsDifferences: An anchor must b
27、e set for the source and target Target may come before Source Figure gets added to the Connection LayerNodeEditPart Interface Connection must have a direction,34,More about EditParts,Deciding on Model EditPart mapping Unit of “interaction” Selection is comprised of EditParts Can it be deleted? Graph
28、ical vs. Tree Viewers The Root EditPart,35,Editing: Putting the “E” in GEF,Model,GraphicalViewer,EditParts,Figures,36,Editing and Tools,SWT Events,Requests,Commands,showFeedback() eraseFeedback() getCommand(),SWT Canvas,37,EditParts and EditPolicies,EditPolicies are installed and maintained by their
29、 host part EditPart responsibility is keep view up-to-date EditPolicies handle editing tasks Avoid limitations of single inheritance Separate unrelated editing tasks Allows editing behavior to be dynamic Keyed using Strings (“Roles”) May contribute to feedback, commands, targeting, etc. Tip: Unexecu
30、tableCommand vs. null Examples: BendpointEditPolicy, SelectionEditPolicy, etc. Pattern used: “Pool of Responsibility”,38,Responding to Model changes,Extend activate() to hook listeners Extend deactivate() to unhook listeners Depending on the type of change Add, remove, or reorder Children Update Con
31、nections Update the view,39,Building a GEF Application,Step 1: Model,Step 2: View,Step 3: Controller,Step 4: “Editor”,40,The Big Picture,6. modifies,Palette,Tool1,Tool2,Tool3,Active Tool,1. acts on,2. events,5. execute,3. request,4. command,CommandStack,Command,Command,Command,Command,EditDomain,41,
32、GEF Conventions and Patterns,Tools to interpret mouse and keyboard Requests to encapsulate interactions Tip: performRequest() for REQ_DIRECT_EDITING and REQ_OPEN Absolute coordinates Edit Policies for separation of concerns Command pattern for undo/redo Use of IAdaptable,42,Palette,PaletteViewer: Ju
33、st another GraphicalViewer Tip: #saveState(IMemento) Palette Model Templates vs. Tools Drawers, Groups and Stacks Permissions PaletteViewerProvider Add drag source listener for DND Fly-out Palette and PaletteView GraphicalEditorWithFlyoutPalette PalettePage FlyoutPreferences,43,Properties View,Imple
34、ment IPropertySource on The EditPart The Model Or make the model IAdaptable A Custom adapter for combining multiple sources GEF provides undo/redo support via commands UndoablePropertySheetEntry Auto-Wraps IPropertySource changes in a Command,44,Outline View,Use the provided TreeViewer class Extend
35、AbstractTreeEditPart Use SelectionSynchronizer with multiple viewers Editor actions can be reused in the outline Use ScrollableThumbnail as an Overview,45,Actions,Editors ActionRegistry Actions updated as needed Editor does the listening, not the actions Its just a Map ActionBarContributor One for a
36、ll editor instances Declared in plugin.xml Use RetargetActions,46,Accessibility,Eclipse is accessible GEF is accessible IAdaptable#getAdapter(Class) AccessibleEditPart Magnifier and Screen reader API Focus indication (Selection Edit Policies) Default keyboard handlers Accessible Tools AccessibleAnch
37、orProvider AccessibleHandleProvider,47,Auto-Scrolling,During drag operations, including native DND Search from target part upwards AutoExposeHelper #detect(Point) #step(Point) Not just for scrolling Expanding Page-flipping Related: ExposeHelper Programmatically “reveal” an EditPart,48,Zooming,ZoomMa
38、nager Use a Scalable RootEditPart Tip: available as a property on the viewer Action Contributions Zoom-In & Zoom-Out Actions ZoomComboContributionItem Ctrl + MouseWheel (in 3.1) MouseWheelZoomHandler,49,BREAK 10 minutes,50,Set-up,Install Eclipse 3.1M5a and GEF SDK 3.1M5 Start with a clean workspace
39、Unzip activity.zip into your workspace before launching Eclipse, and then from within Eclipse, Import - Existing Project Into Workspace http:/www.eclipse.org/gef/conference/activity.zip Switch to the Java Perspective,51,Hands-on Activity: Shapes Example,Create your own plug-in Based on the simple Sh
40、apes example contributed by Elias Volanakis Skeleton provided for the plug-in,52,Model,Provided! So are the Commands ModelElement implements IPropertySource and Serializable,53,View,Available in Draw2d Basic Shapes: RectangleFigure and Ellipse,54,Controller,ConnectionEditPart (AbstractConnectionEdit
41、Part),ShapeEditPart (AbstractGraphicalEditPart),ShapeDiagramEditPart (AbstractGraphicalEditPart),ShapeEditPartFactory,55,ShapeDiagramEditPart,Listen to the model only when the EditPart is active activate() deactivate() propertyChange() createFigure() FreeformLayer with FreeformLayout if you want to
42、scroll into negative co-ordinates; Figure with XYLayout otherwise getModelChildren() createEditPolicies() COMPONENT_ROLE: RootComponentEditPolicy (provided by GEF) to prevent deletion of the content EditPart LAYOUT_ROLE: Subclass XYLayoutEditPolicy For creating, moving and resizing children createCh
43、ildEditPolicy() : default will do,56,ShapeEditPart,Listen to the model for changes Create RectangleFigure or Ellipse based on the model instance Implement NodeEditPart to support connections ChopboxAnchor or EllipseAnchor (return the same anchor in all methods) Edit Policies COMPONENT_ROLE: Sub-clas
44、s ComponentEditPolicy to provide delete support GRAPHICAL_NODE_ROLE: Sub-class GraphicalNodeEditPolicy getModelSourceConnections() and getModelTargetConnections() refreshVisuals() (GraphicalEditPart)getParent().setLayoutConstraint(),57,ConnectionEditPart,Listen to model for changes Create figure Pol
45、ylineConnection with a target decoration and proper lineStyle Edit Policies CONNECTION_ENDPOINTS_ROLE: ConnectionEndpointEditPolicy (provided by GEF) to select the connections endpoints CONNECTION_ROLE: Sub-class ConnectionEditPolicy to support delete,58,Bring It All Together - ShapesEditor,Function
46、ality not related to GEF is provided Weve added TODO:Tutorial to mark missing functionality Constructor: Provide a new DefaultEditDomain configureGraphicalViewer() RootEditPart EditPartFactory initializeGraphicalViewer() Set the viewers contents Palette getPaletteRoot() and getPalettePreferences() D
47、elegate to ShapesEditorPaletteFactory,59,Bring It All Together - ShapesEditorPaletteFactory,createPalettePreferences() ShapesPlugin#getDefault()#getPreferenceStore() createPaletteRoot() Tools Group has PanningSelectionToolEntry, MarqueeToolEntry and ConnectionCreationToolEntry Shapes Drawer has Comb
48、inedTemplateCreationEntry for the two shapes The templates can be null for now (used for DND) Tip: Do not forget to provide a default tool (usually Selection),60,Test Drive,Launch the Runtime Workbench Run menu - Debug - Click on Entire Application - Click New Test functionality Create a Simple Proj
49、ect and a new Shapes example using the wizard Click and drop from palette (notice drag and drop doesnt work yet) Select, move, resize, connect parts Properties View Select a shape and hit . (the period key); then try / (the slash key) Bring up the Palette View Right-click on the palette Drag the sha
50、pes into negative region From here, well incrementally add desired features,61,(Native) Drag-n-Drop from Palette,Add DragSourceListener to the Palette and DropTargetListener to the graphical viewer ShapesEditor createPaletteViewerProvider() - TemplateTransferDragSourceListener initializeGraphicalViewer() TemplateTransferDropTargetListener ShapesEditorPaletteFactory Change CombinedTemplateCreationEntries to return the model classes as templates Sub-class TemplateTransferDropTargetListener to provide the CreationFactory: use SimpleFactory,