3.2 Introduction to Draw2D

 < Day Day Up > 



3.2 Introduction to Draw2D

Draw2D provides the lightweight graphical system that GEF depends on for its display. It is packaged in Eclipse as a separate plug-in, org.eclipse.draw2d. Draw2D is hosted in a SWT canvas heavyweight control and manages the painting and mouse events that occur in the host canvas by delegating them to Draw2D figures. Figures are analogous to windows in a heavyweight graphics system. They can have arbitrary, nonrectangular shapes and can be nested in order to compose complex scenes or custom controls.

Figures can be transparent or opaque, and can be ordered into layers, thus allowing parts of a diagram to be hidden or excluded from certain operations. Draw2D is a standalone graphics library that can be used by itself to create graphical views in Eclipse. A complete coverage of Draw2D in depth is beyond the scope of this book. Instead, we discuss some key Draw2D concepts and focus on the Draw2D features and classes that are most important to GEF developers.

3.2.1 What is a lightweight system?

A lightweight system is a graphics systems that is hosted inside a single heavyweight control. The graphics objects in the lightweight system, known as figures in Draw2D, are treated as if they are normal windows. They can have focus and selection, get mouse events, have their own coordinate system, and have a cursor. They each get a graphics context for rendering. The advantage of lightweight systems is that they are much more flexible than the native windowing system, which is generally composed of rectangular components. They allow you to create and manipulate arbitrarily shaped graphics objects. Because they simulate a heavyweight graphics system within a single heavyweight window, they allow you to create a graphically complex display without consuming a lot of system resources.

3.2.2 Architectural overview

As we said earlier, Draw2D is a self-contained graphics library and can be used independently of GEF or even of Eclipse. You can see the basic structure of a standalone Draw2D application in Example 3-1.

Example 3-1: A standalone Draw2D application

start example
 Shell shell = new Shell(); shell.open(); shell.setText("A Draw2d application"); LightweightSystem lws = new LightweightSystem(shell); // add your application's root figure IFigure panel = new Figure(); panel.setLayoutManager(new FlowLayout()); lws.setContents(panel); ... // add your application's figures here panel.add(...); while (!shell.isDisposed ()) { if (!display.readAndDispatch ())    display.sleep (); } 
end example

Tip 

When you create a standalone Draw2D application, you need to make sure that your operating system is able to locate the SWT native library. For instance, on Microsoft Windows, make sure that the following file is added to your class path: ECLIPSE_HOME\plugins\org.eclipse.swt.win32_2.1.1\os\win32\x86swt32.dll

In Example 3-1 on page 94, the shell serves as the SWT canvas that is needed to host Draw2D. The LightweightSystem class provides the bridge between SWT and Draw2D by routing mouse and paint events to the figures it contains. A root figure is then added to the LightweightSystem. The root figure is configured with a layout manager which controls the layout of any child figures that are subsequently added to it.

3.2.3 Figures

In this section we go into more detail on the capabilities of figures in general, and introduce some of the specialized figures that Draw2D provides.

Methods

Everything that is visible in a Draw2D window is drawn on a figure. The figure class contains a number of methods that provide the following functionality:

  • Registering or deregistering listeners on a figure; the figure will notify listeners of mouse events within the figure

  • Structural events, for structural changes in the figures hierarchy, and for movement or resizing of the figure

  • Specifying the cursor to display when the mouse passes over it

  • Operations to manage the figure's place in the figure hierarchy, including adding and removing children and accessing them or its parent figure

  • Accessors for:

    • The figure's layout manager

    • The figure's size and location

    • The tooltips

  • Setting and getting focus

  • Specifying the figure's transparency and visibility

  • Performing coordinate conversion, intersection, and hit testing

  • Painting

  • Validating

Subclasses

Draw2D provides many subclasses of figure that provide useful additional functionality. We describe some of these in the following sections.

Shapes

Subclasses of the Shape class contain non-rectangular figures that know how to fill themselves and provide a border of configurable width and line style, and include support for XOR drawing. Some examples are the Ellipse, Polyline, Polygon, Rectangle, Rounded rectangle, and Triangle classes.

Widgets

Draw2D includes figures which allow you to create lightweight widgets that can be used when you need an input control within your Draw2D application. These include various buttons, Checkbox, and the text entry figure, Label.

Layers and panes

These are figures designed to host child figures. They providing scaling, scrolling, and the ability to place figures into different layers.

The graphics context

Figures have a paint method that is called by the LightweightSystem when the figure needs to be rendered. Each figure gets a graphical context, an instance of the Graphics class, that is passed as argument to the figure's paint method. The graphics context supports graphics operations, including drawing and filling shapes and drawing text. It also maintains the graphics state that influences these operations, such as the current font, background and foreground colors, etc. This analogous to many other graphics systems.

3.2.4 Mechanism

This section introduces the core classes of the Draw2D architecture.

LightweightSystem

The LightweightSystem class is the heart of Draw2D. It performs the mapping between an SWT canvas and the Draw2D system that is hosted within it. It contains three main components:

  • The root figure: This is an instance of the LightweightSystem$RootFigure class; this top level figure is the parent of your application's root figure. It inherits some of the graphical environment of the hosting SWT Canvas, such as font, background, and foreground colors.

  • The event dispatcher: The SWTEventDispatcher class translates SWT events to the corresponding Draw2D events in the root figure. It tracks which figure has focus, which figure is being targeted by mouse events, and handles tooltip activation. It provides support for figures that want to capture the mouse.

  • The update manager: The update manager is responsible for painting and updating Draw2D figures. The LightweightSystem calls the update manager's performUpdate() method when a paint request is received from the underlying SWT canvas. The update manager typically maintains a worklist of figures that are invalid or need repainting. The update manager tries to coalesce its work lists so that it can be as efficient as possible. The default update manager, DeferredUpdateManager, allows updates to be performed asynchronously by queuing work on the Display's user interface thread.

The main processes in a figure's life cycle are painting and validating. Draw2D asks a figure to render itself by calling the figures paint methods. The paint() method invokes three more specific paint methods:

  • paintfigure() — The figure should render itself.

  • paintclientarea() — The figure should render its children.

  • paintborder() — The figure should render its border, if any. Clipping is used to protect the border.

Validating occurs when a figure's size or location needs to be calculated:

  • validate — Asks the figure's layout manager to re-layout its children.

  • revalidate — Calls invalidate; adds a figure and its predecessors to the update manager's invalid list.

3.2.5 Major features

In the following sections we summarize some of the main features and functionality provided by Draw2D.

Borders

It is frequently necessary to provide a visual border to figures. The Draw2D package contains several classes, derived from the Border class, which provide a variety of border effects:

  • GroupBoxBorder — Creates a labeled border similar to group boxes in native window systems

  • TitleBarBorder — Creates a titled border that resembles a titled window

  • CompoundBorder — A border composed of two borders

  • FrameBorder — Similar to TitleBarBorder; can be used to create figures with titles

  • FocusBorder — Surrounds a figure with a focus rectangle

  • LineBorder — Creates an outline around a figure of the width you specify

  • MarginBorder — A border for creating padding around the edges of a figure

  • SchemeBorder — A base class for borders whose borders simulate shadows and highlights

  • ButtonBorder — Used with a Clickable figure to create lightweight button-like controls

  • SimpleLoweredBorder and SimpleRaisedBorder

Examples of some of these border types are illustrated in Figure 3-5.

click to expand
Figure 3-5: Some Draw2D border types

The Insets class is used to represent the space within a figure that is allocated to the border. Notice that the border does not have to be symmetrical. It can be occupy any combination of a figure's edges, and can be a different size on any edge. The paint method clips the client area so that painting is constrained to the area of the figure inside the inset. The border, when present, is the last part of the figure to be painted.

Layouts

LayoutManagers are used to manage the position and size of a figure's child figures. They interrogate each child figure to obtain its preferred size, and then apply some layout algorithm to calculate the final size and placement of the child figures. LayoutManagers also support constraints, which are data attached to each figure that gives additional guidance to the layout manager. The figure has accessor methods for its constraints, and the layout manager maintains a map of constraints for the figures it is managing.

The constraint accessors use the Object type for constraints since the type of the constraint depends on the layout manager being used. For instance, the XYLayout layout manager requires that the figures it manages have a constraint of type Rectangle, and the DelegatingLayout manager expects its figures to have a constraint which implements the Locator interface. All Draw2D layout managers derive from the AbstractLayout abstract class.

These are some of the provided layout managers:

  • FlowLayout — Lays out its children into either rows or columns, which is configurable either by using the constructor:

        public FlowLayout(boolean isHorizontal) 

    or by calling the method:

        setHorizontal(isHorizontal) 

    The manager causes its children to wrap when the current row or column is full. There are also methods to control the alignment and spacing of rows in both the major and minor axes.

  • DelegatingLayout — Delegates the layout of its child figures to the child figures' locators. The children must provide a Locator subclass as their constraint.

  • XYLayout — Places its children at the location and dimensions specified for the child. The child's constraint must be a Rectangle object that specifies this information.

Draw2D provides a scrollable pane via the ScrollPane class. To implement this functionality it uses the ScrollPaneLayout, which manages the layout of the scroll bars and Viewport that comprise the ScrollPane. In addition the Viewport uses the ViewportLayout manager to manage the viewport's visible region and maintain the scroll position state.

Layers

Layers are transparent figures intended specifically for use in LayerPanes. They override the figure's containsPoint() and findFigureAt() methods so that hit testing will "pass through" the layer. The FreeformLayer class adds additional specialization to Layer to provide a layer that can extend indefinitely in all four directions.

Note 

The term "Freeform", when used in Draw2D class names, indicates that the class supports figures that can expand in all directions — that is, they do not have a fixed size or origin, which also implies that the child figures can have negative coordinates. Some examples are the FreeformLayer, FreeformLayeredPane, and ScalableFreeformLayeredPane classes.

The ConnectionLayer class implements a FreeformLayer that is designed to contain connections. It Insures that any Connection figures added to the layer will have their connection router set correctly to the layer's connection router. Similarly, when the layer's connection router is changed, it will update the connection router of all its connection figures.

LayerPanes are figures designed to contain layers (they can only contain layers). The layers in a LayerPane are stored in a map whose key is typically a String. LayerPanes contain methods to add, insert, remove, and reorder the layers they contain.

Two subclasses of LayerPane provide additional flexibility. The FreeformLayeredPane provides a set of layers that can expand in all directions. The ScalableFreeformLayeredPane adds support for zooming.

Finally, the ScalableLayeredPane provides a LayerPane that is scalable but is not free form but instead has a finite, fixed size.

Locators

Implementors of the Locator interface are used in Draw2D to position figures. The interface consists of a single method:

    void relocate(IFigure target) 

Subclasses of ConnectionLocator are used for locating figures that are attached to a Connection. These can be used for placing arrowheads on the ends of connections or placing labels or other decorations or annotations on a Connection. The locator ensures that the figure stays "attached" to the Connection in the designated location as the Connection is moved.

Available locators include:

  • ArrowLocator — This locator is used to position decorations, such as arrowheads, on the ends of connections. Any figure that implements RotatableDecoration can be located. Implementors of RotatableDecoration are given a position and a reference point so that they can rotate their visual representation based on the angle of the connection they are decorating.

  • BendpointLocator — This locator is used to position bendpoint handles on a Connection

  • MidpointLocator — This locator is used to place figures at the midpoint of a Connection

  • ConnectionEndpointLocator — This locator is used to locate a figure near either the start or end of a connection.

  • RelativeLocator — This locator is used to locate a figure using a 0 to 1 floating point value representing its affinity for the a weighting of the figure's affinity for the upper left corner (0) or lower right corner (1) of a reference figure. This class is generally intended for calculating the placement of handles.

Connection anchors

Draw2D provides classes that provide various styles of anchor points, which are used to represent the ends of a connection. The basic function of these classes is to contain the location of a Connection's endpoints and to register listeners that will be notified if the end of a connection is moved.

The AbstractConnectionAnchor class is the base class for anchors whose position is associated with a figure. It notifies its listeners when the figure it is associated with is moved.

Available anchors include:

  • ChopboxAnchor — A ChopboxAnchor is located at the point on the figure's border where the Connection would intersect the figure, if the connection continued to the figure's center point.

  • LabelAnchor — LabelAnchor is a subclass of ChopboxAnchor that is designed solely for node figures that are Draw2D Labels. Rather than projecting the connection to the center of the figure, the location of the anchor depends on the center of the Label's icon.

  • EllipseAnchor — The EllipseAnchor is a variant of the ChopboxAnchor (but it is not a subclass). It locates the anchor on the edge of an elliptical figure at the point where a connection to the center of the node would intersect the edge.

  • XYAnchor — The XYAnchor is used for anchors that are placed at a fixed position.

Connection routers

Connection routers are used to calculate the path that a connection takes in getting from one anchor to the other. AbstractRouter is the base class for connection routers that implement the ConnectionRouter interface. Available connection routers include:

  • NullConnectionRouter — By default this simply draws a straight line between the anchors of a connection. This is shown in Figure 3-6 using a diagram created using the logic sample application.However Draw2D also provides more sophisticated routers that use different criteria to determine the path that a connection will take.


    Figure 3-6: NullConnectionRouter

  • AutomaticRouter — This provides a base class for routers that want to prevent two connections from overlaying each other. For instance its FanRouter subclass spreads two connections which have the same starting and ending points so that they are not superimposed.

  • BendpointConnectionRouter — The BendpointConnectionRouter shown in Figure 3-7, allows the user to manually insert bendpoints into a connection. The connection is routed to follow a set of points that the user specifies by manually dragging the Connection's segments.


    Figure 3-7: Bendpoint router

  • ManhattanConnectionRouter — The ManhattanConnectionRouter (Figure 3-8) routes a connection using only vertical and horizontal line segments. It also maintains separation between Connections that would otherwise overlap.


    Figure 3-8: Manhattan router

Summary of Draw2D's support for connections

Many of the features in Draw2D that we have discussed are part of Draw2D's support for connections. It is worthwhile to summarize this set of features:

  • PolylineConnection, a polyline figure that listens for anchor movement and supports start and end-point decorations, and has an associated connection router

  • A connection layer exclusively for drawing connections

  • Anchors for specifying and tracking the connection points of connections

  • Routers to determine the path of connections

  • Locators to find the ends and midpoint of connections, and more specialized ones to support connections with multiple bendpoints

  • Rotatable decorations to place decorations on connections that can realign themselves as the angle of the connection changes.



 < Day Day Up > 



Eclipse Development using the Graphical Editing Framework and the Eclipse Modeling Framework
Eclipse Development Using the Graphical Editing Framework And the Eclipse Modeling Framework
ISBN: 0738453161
EAN: 2147483647
Year: 2004
Pages: 70
Authors: IBM Redbooks

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net