Class AbstractGraph<B>
- Type Parameters:
B- the type of buffer backing the graph (may be null if the graph does not use a RingBuffer): typically this isdouble[]but in some casesColor[],String[]orMeshLambertMaterial[]forPop2D,PopGraph2DorPopGraph3D, respectively.
- All Implemented Interfaces:
HasAllDragAndDropHandlers, HasAllFocusHandlers, HasAllGestureHandlers, HasAllKeyHandlers, HasAllMouseHandlers, HasAllTouchHandlers, HasBlurHandlers, HasClickHandlers, HasContextMenuHandlers, HasDoubleClickHandlers, HasDragEndHandlers, HasDragEnterHandlers, HasDragHandlers, HasDragLeaveHandlers, HasDragOverHandlers, HasDragStartHandlers, HasDropHandlers, HasFocusHandlers, HasGestureChangeHandlers, HasGestureEndHandlers, HasGestureStartHandlers, HasKeyDownHandlers, HasKeyPressHandlers, HasKeyUpHandlers, HasMouseDownHandlers, HasMouseMoveHandlers, HasMouseOutHandlers, HasMouseOverHandlers, HasMouseUpHandlers, HasMouseWheelHandlers, HasTouchCancelHandlers, HasTouchEndHandlers, HasTouchMoveHandlers, HasTouchStartHandlers, MouseDownHandler, MouseMoveHandler, MouseOutHandler, MouseUpHandler, MouseWheelHandler, TouchEndHandler, TouchMoveHandler, TouchStartHandler, HasAttachHandlers, EventHandler, HasHandlers, EventListener, AcceptsOneWidget, Focusable, HasFocus, HasOneWidget, HasVisibility, HasWidgets, HasWidgets.ForIsWidget, IsWidget, RequiresResize, SourcesClickEvents, SourcesFocusEvents, SourcesKeyboardEvents, SourcesMouseEvents, SourcesMouseWheelEvents, Iterable<Widget>, ContextMenu.Listener, ContextMenu.Provider, Tooltip.Provider
- Direct Known Subclasses:
GenericPopGraph, HistoGraph, LineGraph, ParaGraph, S3Graph
This class encapsulates common functionality required by a variety of concrete graph implementations: managing the canvas and its high-DPI scaling, calculating drawing bounds, handling user interactions (mouse and touch) for panning and zooming, integrating with shared UI utilities (tooltip and context menu), buffering historical data, and providing a comprehensive set of drawing helpers for frames, axes, ticks, levels, markers and primitive shapes.
Generic parameter
The type parameter <B> denotes the element type stored in an optional RingBuffer used for graphs that maintain historical data (for example time-series or trajectory graphs).
Primary responsibilities
- Allocate and manage a Canvas element and a wrapped 2D rendering context (MyContext2d) tuned for device pixel ratio (retina/high-DPI) support.
- Compute and maintain drawing bounds that leave room for frames, labels, ticks and tick labels while exposing helper methods to draw full graph frames (axes, tick marks, tick labels, grid levels and custom levels).
- Provide a pluggable styling model (GraphStyle) and helpers to render axes labels, graph title, and common primitives (lines, circles, filled paths, rectangles and vertical text).
- Offer a unified interaction model for shifting (panning) and zooming including mouse drag, mouse wheel, single- and multi-touch gestures, pinch-to-zoom, and inertial visual feedback via CSS classes and a scheduled timer.
- Integrate with shared UI widgets: Tooltip (for hover/touch info) and ContextMenu (for buffer size, log-scale and zoom actions). Subclasses and the owning AbstractView can extend and populate the context menu.
- Maintain an optional RingBuffer<B> for historical data and provide a small context menu for configuring buffer capacity. Subclasses may implement exporting of trajectory/history data when relevant.
Interfaces and Extension Points
AbstractGraph provides inner interfaces that concrete graphs and/or their containing view may implement to customize interaction behavior:
- Shifting — marker indicating the graph supports shifting. Implementing classes can provide custom shift behavior by implementing Shifter, and can optionally override mouse/touch handlers if they need finer control.
- Shifter — single method shift(int dx, int dy) used by the base class to move the view corner when panning. The default implementation in AbstractGraph updates the viewCorner constrained to valid extents.
- Zooming — marker indicating the graph supports zooming. It extends Zoomer and MouseWheelHandler. It documents a default ZOOM_INCR and ZOOM_MAX. Implementations can override zoom behaviour; otherwise the base-class provides sensible defaults.
- Zoomer — single method zoom(double zoom, int x, int y) used to apply zoom centered on a particular screen coordinate. Subclasses or the containing view can provide custom coordinate-space or content-level behavior by implementing Zoomer.
- HasLogScaleY — marker for graphs that may support logarithmic Y scaling; the graph will enable/disable the log-y context menu item appropriately.
- HasTrajectory — marker for graphs that can export trajectories; such graphs should implement an exportTrajectory(StringBuilder) routine.
Lifecycle
Typical lifecycle methods:
- onLoad() — allocates the LayoutPanel wrapper and Canvas, obtains shared Tooltip and ContextMenu instances and configures them, and sets the rendering scale based on device pixel ratio.
- onUnload() — removes and nulls references to DOM components and unregisters from shared widgets.
- activate() — attaches mouse and touch handlers for zooming and shifting depending on which interfaces are implemented and on the environment (e.g. special handling for ePub readers).
- deactivate() — removes all registered input handlers, closes tooltip and context menu, and cancels transient state.
- onResize() — closes transient UI (tooltip/context menu), updates the canvas coordinate space and recalculates drawing bounds.
Interaction semantics
- Mouse wheel: zooms with inertia. The wheel delta is converted to a multiplicative zoom factor (ZOOM_INCR ^ -deltaY) and the zoom center is the current mouse position. A CSS class is briefly applied while inertia is present.
- Mouse drag with left button: initiates panning (shifting) of the viewport when the graph implements Shifting. A CSS class is applied to indicate view movement while dragging.
- Touch: short taps and long touches are distinguished. Long single touches allow panning; two-finger long touches initiate pinch-to-zoom with the center of the pinch used as zoom focus. Touch handlers preventDefault() for panning and pinch gestures to avoid scrolling the page when interacting with the graph.
- All interactions are no-ops when a textual message is shown on the graph (hasMessage flag) to avoid conflicting updates.
Canvas & scaling
The canvas coordinate space is scaled by the detected device pixel ratio to support crisp rendering on high-DPI displays. updateCanvas() sets both the CSS pixel size and the coordinate space (scaled) size; note that setting these properties clears the canvas, so callers should repaint after resizing.
Painting and Helpers
Subclasses must implement export(MyContext2d) and typically override paint() to perform actual rendering. AbstractGraph provides:
- Utility primitives for drawing and filling complex paths efficiently (sketch/stroke/fill) with segmentation to avoid freezing the UI.
- Convenience methods for drawing frames, axis labels, ticks, tick labels (including percent/log formatting), grid levels, and custom level lines.
- Primitives for circles, lines, rectangles and vertical text.
- Coordinate conversion helpers to map browser coordinates to scaled [0..1] coordinates relative to the drawing bounds (convertToScaledCoordinates).
Bounds and layout
calcBounds computes the inner drawing rectangle available for graph content, factoring in style-determined padding, frame width, label space, tick length and tick label widths. adjustBoundsForLabels() and adjustBoundsForTickLabels() are used to reserve space for axis and tick labels. The bounds are used by frame and drawing methods to position elements consistently.
History & buffering
When a RingBuffer<B> is present, hasHistory() returns true and a small buffer-size submenu is added to the context menu to select capacities (5k, 10k, 50k, 100k). Subclasses that maintain historical data should manage insertion into the buffer and may use prependTime2Data helper to attach a timestamp to stored data points.
Tooltips and context menu
A shared Tooltip instance is used to provide hover/touch information. Context menu population is extensible — AbstractGraph populates buffer-size, log-Y toggle and zoom items when applicable and then delegates to the owning AbstractView for additional items.
Messages
displayMessage(String) can be used to render a centered textual message on the graph (e.g. "No Data" or "Paused"). When a message is displayed most interaction handlers become inert and painting/updates are suppressed until the message is cleared via clearMessage().
Utilities & Helper classes
- MyContext2d — a thin subclass of Context2d that exposes setLineDash for dashed lines.
- ZoomCommand — small Command implementation used by context menu items to apply zoom factors.
Notes and implementation details
- Drawing very large paths is split into segments (MAX_SEGEMENTS) and periodically closed/stroked to avoid performance bottlenecks and UI freezing.
- Many protected helper methods are provided so subclasses can reuse the standardized rendering behavior and visuals defined by GraphStyle.
- AbstractGraph intentionally separates coordinate-space transforms (via viewCorner and zoomFactor) from content rendering so subclasses can assume painting inside normalized bounds and apply their own content transforms as needed.
- Author:
- Christoph Hauert
- See Also:
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionstatic interfaceGraphs that support logarithmic scaling on the y-axis should implement this interface.static interfaceGraphs that show trajectories and support exporting their data should implement this interface.static classCreate custom Context2d that admits drawing dashed lines.static interfaceGraphs that support shifting of their view should implement this interface.static interfaceGraphs that support shifting should implement this interface.classThe zoom command for the context menu.static interfaceGraphs that support zooming should implement this interface.static interfaceGraphs that support zooming should implement this interface.Nested classes/interfaces inherited from class UIObject
UIObject.DebugIdImpl, UIObject.DebugIdImplEnabledNested classes/interfaces inherited from interface HasWidgets
HasWidgets.ForIsWidget -
Field Summary
FieldsModifier and TypeFieldDescriptionprotected Rectangle2DThe bounds of the displaying area.protected RingBuffer<B> The buffer to store historical data, if applicable.private ContextMenuThe context menu to set the buffer size for graphs with historical data.protected CanvasHandle to the canvas for drawing the graphics.protected String[]The array of colors used for drawing the graph.protected ContextMenuThe reference to the (shared) context menu.protected static final StringThe CSS class name for the view movement cursor.(package private) static final StringCSS class applied when the user is grabbing a node.(package private) static final StringCSS class applied when the user is dragging a node.(package private) static final StringCSS class applied when the user is zooming in.(package private) static final StringCSS class applied when the user is zooming out.protected static final intThe default buffer size.(package private) HandlerRegistrationThe handler forDoubleClickEvents.protected ElementHandle to the object's underlying DOM element.protected AbstractGraph.MyContext2dHandle to the graphical context for drawing on the canvas.protected booleanFlag to indicate whether the graph displays a message.protected booleanThe flag to indicate whether the graph supports zoom.protected booleanThe flag to indicate whether the left mouse button is pressed.protected LoggerLogger for keeping track of and reporting events and issues.(package private) ContextMenuCheckBoxItemThe menu item to toggle logarithmic scaling on the y-axis.protected String[]The array of colors used for markers.protected List<double[]> Markers for decorating the graph.private static final intThe maximum number of line segments to draw before returning control to the event loop.protected static final intThe minimum buffer size.static final intThe minimum time between updates in milliseconds.protected Module<?> The module backing the graph.(package private) HandlerRegistrationThe handler forMouseDownEvents.(package private) HandlerRegistrationThe handler forMouseMoveEvents.(package private) HandlerRegistrationThe handler forMouseOutEvents.(package private) HandlerRegistrationThe handler forMouseUpEvents.(package private) HandlerRegistrationThe handler forMouseWheelEvents.protected intThex-coordinate of the previous mouse or tap event.protected intThey-coordinate of the previous mouse or tap event.protected static final doubleConstant representing the numerical value of \(\pi/2\)protected doubleThe distance between the pinching gesture.protected intThex-coordinate of the center of the pinching gesture.protected intThey-coordinate of the center of the pinching gesture.protected doubleThe scale of this graph.(package private) AbstractGraph.ShifterThe controller for shifting this graph.protected GraphStyleThe style of the graph.protected TooltipThe reference to the (shared) tooltip.(package private) BasicTooltipProviderThe provider for tooltips.(package private) HandlerRegistrationThe handler forTouchEndEvents.protected doubleThe time when the previous touch ended.(package private) HandlerRegistrationThe handler forTouchMoveEvents.(package private) HandlerRegistrationThe handler forTouchStartEvents.private static final doubleConstant representing the numerical value of \(2 \pi\)protected doubleThe field to store the time of the last update.protected final AbstractView<?> The view of this graph.protected Point2DThe coordinates of the lower left corner visible on the canvas.(package private) LayoutPanelThe wrapper element which displays the canvas.(package private) AbstractGraph.ZoomerThe controller for zooming this graph.protected doubleThe current zoom level.protected TimerThe timer to remove the CSS classes.evoludo-cursorZoomInor.evoludo-cursorZoomIn, respectively, from the graph element after the inertia of zooming has worn off.(package private) ContextMenuItemThe context menu item to zoom in (enlarge) by a factor of2.(package private) ContextMenuItemThe context menu item to zoom out (reduce) by a factor of1/2.(package private) ContextMenuItemThe context menu item to reset the zoom level.Fields inherited from class UIObject
DEBUG_ID_PREFIX -
Constructor Summary
ConstructorsModifierConstructorDescriptionprotectedAbstractGraph(AbstractView<?> view, Module<?> module) Create the base class for graphs. -
Method Summary
Modifier and TypeMethodDescriptionvoidactivate()Perform necessary preparations to show the graph in the GUI.private voidaddBufferSizeMenu(ContextMenu menu) Add buffer size menu item to context menu if graph supports historical data.addContextMenuHandler(ContextMenuHandler handler) private voidaddLogScaleMenu(ContextMenu menu) Add logarithmic scale menu item to context menu if graph supports log scale ony-axis.private voidaddZoomMenu(ContextMenu menu) Add zoom menu items to context menu if graph supports zooming.private voidAdjust bounds to make room for axes labels.private voidAdjust bounds to make room for tick labels.voidautoscale(boolean x, boolean y) Set auto-scaling for horizontal and vertical axes.protected booleanCalculate bounds of drawing area.voidcalcBounds(int width, int height) Calculate bounds of drawing area.protected voidClear the canvas.voidClear the graph.voidClear the history of the graph (if there is one).voidClear the message.private voidclosePath(boolean fill) Helper method to close the path and draw (or fill) it.private double[]Compute the (possibly logarithmic) y-range for tick computations.private doublecomputeYVal(int n, double frac, double yrange, double ymin) Compute the y-value for tick numbern.booleancontains(int x, int y) Checks if the (browser) coordinates(x, y)are inside this graph.convertToScaledCoordinates(int x, int y) Convert the (browser) coordinates(x, y)to scaled coordinates in \([0,1]^2\).convertToScaledCoordinates(int x, int y, Point2D dest) Convert the (browser) coordinates(x, y)to scaled coordinates in \([0,1]^2\) and store indest.voidThe graph is removed from the GUI.booleandisplayMessage(String msg) Display messagemsgon the graph (no HTML formatting).booleandoUpdate()Determine whether it is time to update the display.private voiddrawCustomXLevels(double w, double h) Draw vertical guide lines at custom x positions.private voiddrawCustomYLevels(double w, double h) Draw horizontal guide lines at custom y positions.protected voiddrawFrame(int xLevels, int yLevels) Draw the frame of the graph including axes labels, ticks and tick marks, as applicable.protected voiddrawFrame(int xLevels, int yLevels, double gscale) Draw the frame of the graph including axes labels, ticks and tick marks, as applicable, after scaling the canvas bygscale.private voiddrawFrameBorder(double w, double h) Draw the bounding box of the graph frame.private voiddrawGraphLabel(double gscale) Draw the label shown inside the graph canvas.private voiddrawXAxisLabel(double w, double h) Draw the x-axis label.private voiddrawXLevels(int xLevels, double w, double h) Draw regular vertical guide lines, ticks, and labels.private voiddrawYAxisLabel(double w, double h) Draw the y-axis label, including positioning logic based on tick labels.private voiddrawYLevels(int yLevels, double w, double h) Draw the y-levels including ticks and tick labels.private voiddrawYTickLabel(double w, double level, int n, double yval) Draw the y-axis tick label at the specified screen level.abstract voidExport the graphical contextctx.protected voidFill the pathpath.protected voidfillCircle(double x, double y, double radius) Fill the circle with the center at(x,y)and radiusradius.protected voidfillCircle(Node2D node) Draw the filled 2D node.protected voidfillCircle(Point2D point, double radius) Draw a filled circle atpointwithradius.protected voidfillRect(double x, double y, double w, double h) Fill the rectangle with origin at(x,y), widthwand heighth.protected voidfillTextVertical(String msg, double x, double y) Draw filled text vertically starting at point(x,y)Return theRingBuffer<double[]>containing historical data, if applicable.Module<?> Get the module that backs the graph.getStyle()Get the graph style.booleanCheck whether the graph entertains a buffer with historical data.booleanCheck if the graph displays a message.voidinit()Initialize the graph.protected voidonLoad()voidonMouseDown(MouseDownEvent event) voidonMouseMove(MouseMoveEvent event) voidonMouseOut(MouseOutEvent event) voidonMouseUp(MouseUpEvent event) voidonMouseWheel(MouseWheelEvent event) voidonResize()voidonTouchEnd(TouchEndEvent event) voidonTouchMove(TouchMoveEvent event) voidonTouchStart(TouchStartEvent event) protected voidonUnload()voidpaint()Draw the graph.booleanpaint(boolean force) Draw the graph.booleanParse the arguments for the graph.voidpopulateContextMenuAt(ContextMenu menu, int x, int y) Populate context menumenuin listening widget at (relative) position(x,y).protected double[]prependTime2Data(double t, double[] data) Utility method to prepend time to data point.voidreset()Reset the graph.protected voidReset the transformation of the graphics context to the identity transform.protected voidsetBufferCapacity(int capacity) Sets the buffer capacity tocapacity, if applicable.voidAssign a list of colors to the graph.protected voidSet the font tocssfontin CSS format for drawing on the canvas.(package private) voidsetLogY(boolean logY) Set they-axis to logarithmic scale iflogYistrueand ifyMin ≥ 0.voidsetMarkers(List<double[]> markers) Assign a list of markers to the graph.voidsetMarkers(List<double[]> markers, String[] colors) Assign a list of markers with custom colors to the graph.protected voidsetStrokeStyleAt(int node) Set the stroke colour for node with indexnode.voidsetTooltipProvider(BasicTooltipProvider tooltipProvider) Set the provider for tooltips.voidshift(int dx, int dy) Shift the (zoomed) graph within the view port by(dx, dy).private voidDraw or fill (iffill == true) the pathpath.private voidsketchCircle(double x, double y, double radius) Helper method to create a path for a circle with the center at(x,y)and radiusradius.protected voidDraw the pathpath.protected voidstrokeCircle(double x, double y, double radius) Draw the circle with the center at(x,y)and radiusradius.protected voidstrokeCircle(Node2D node) Draw the outline of the 2D node.protected voidstrokeCircle(Point2D point, double radius) Draw the outline of a circle atpointwithradius.protected voidstrokeLine(double sx, double sy, double ex, double ey) Draw a line from point(sx,sy)to(ex,ey).protected voidstrokeLine(Point2D a, Point2D b) Draw a line from pointatob).protected voidstrokeRect(double x, double y, double w, double h) Draw the rectangle with origin at(x,y), widthwand heighth.private voidUpdate the canvas size and coordinate space dimensions.voidzoom()Reset zoom.voidzoom(double zoom) Adjust zoom level by the factorzoom.protected voidzoom(double zoom, double fx, double fy) Helper method to adjust zoom level with the zoom center at the scaled coordinates(fx, fy), specified as a fraction of the view port in horizontal and vertical directions, respectively.voidzoom(double zoom, int x, int y) Adjust zoom level by the factorzoomwith the center at coordinates(x,y)(in display coordinates as provided by event listeners).Methods inherited from class FocusPanel
addBlurHandler, addClickHandler, addClickListener, addDoubleClickHandler, addDragEndHandler, addDragEnterHandler, addDragHandler, addDragLeaveHandler, addDragOverHandler, addDragStartHandler, addDropHandler, addFocusHandler, addFocusListener, addGestureChangeHandler, addGestureEndHandler, addGestureStartHandler, addKeyboardListener, addKeyDownHandler, addKeyPressHandler, addKeyUpHandler, addMouseDownHandler, addMouseListener, addMouseMoveHandler, addMouseOutHandler, addMouseOverHandler, addMouseUpHandler, addMouseWheelHandler, addMouseWheelListener, addTouchCancelHandler, addTouchEndHandler, addTouchMoveHandler, addTouchStartHandler, getTabIndex, removeClickListener, removeFocusListener, removeKeyboardListener, removeMouseListener, removeMouseWheelListener, setAccessKey, setFocus, setTabIndexMethods inherited from class SimplePanel
add, getContainerElement, getWidget, iterator, remove, setWidget, setWidgetMethods inherited from class Panel
add, adopt, clear, doAttachChildren, doDetachChildren, orphan, removeMethods inherited from class Widget
addAttachHandler, addBitlessDomHandler, addDomHandler, addHandler, asWidget, asWidgetOrNull, createHandlerManager, delegateEvent, fireEvent, getHandlerCount, getLayoutData, getParent, isAttached, isOrWasAttached, onAttach, onBrowserEvent, onDetach, removeFromParent, setLayoutData, sinkEvents, unsinkEventsMethods inherited from class UIObject
addStyleDependentName, addStyleName, ensureDebugId, ensureDebugId, ensureDebugId, getAbsoluteLeft, getAbsoluteTop, getElement, getOffsetHeight, getOffsetWidth, getStyleElement, getStyleName, getStyleName, getStylePrimaryName, getStylePrimaryName, getTitle, isVisible, isVisible, onEnsureDebugId, removeStyleDependentName, removeStyleName, resolvePotentialElement, setElement, setElement, setHeight, setPixelSize, setSize, setStyleDependentName, setStyleName, setStyleName, setStyleName, setStyleName, setStylePrimaryName, setStylePrimaryName, setTitle, setVisible, setVisible, setWidth, sinkBitlessEvent, toStringMethods inherited from class Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, waitMethods inherited from interface ContextMenu.Listener
getAbsoluteLeft, getAbsoluteTopMethods inherited from interface HasHandlers
fireEventMethods inherited from interface HasTouchCancelHandlers
addTouchCancelHandlerMethods inherited from interface HasTouchEndHandlers
addTouchEndHandlerMethods inherited from interface HasTouchMoveHandlers
addTouchMoveHandlerMethods inherited from interface HasTouchStartHandlers
addTouchStartHandlerMethods inherited from interface Iterable
forEach, spliteratorMethods inherited from interface Tooltip.Provider
getTooltipAt
-
Field Details
-
doubleClickHandler
HandlerRegistration doubleClickHandlerThe handler forDoubleClickEvents. -
mouseOutHandler
HandlerRegistration mouseOutHandlerThe handler forMouseOutEvents. -
mouseDownHandler
HandlerRegistration mouseDownHandlerThe handler forMouseDownEvents. -
mouseUpHandler
HandlerRegistration mouseUpHandlerThe handler forMouseUpEvents. -
mouseMoveHandler
HandlerRegistration mouseMoveHandlerThe handler forMouseMoveEvents. -
mouseWheelHandler
HandlerRegistration mouseWheelHandlerThe handler forMouseWheelEvents. -
touchStartHandler
HandlerRegistration touchStartHandlerThe handler forTouchStartEvents. -
touchEndHandler
HandlerRegistration touchEndHandlerThe handler forTouchEndEvents. -
touchMoveHandler
HandlerRegistration touchMoveHandlerThe handler forTouchMoveEvents. -
zoomFactor
protected double zoomFactorThe current zoom level. -
viewCorner
The coordinates of the lower left corner visible on the canvas. -
view
The view of this graph. -
shifter
AbstractGraph.Shifter shifterThe controller for shifting this graph. -
zoomer
AbstractGraph.Zoomer zoomerThe controller for zooming this graph. -
contextMenu
The reference to the (shared) context menu. -
tooltip
The reference to the (shared) tooltip. -
tooltipProvider
BasicTooltipProvider tooltipProviderThe provider for tooltips. -
scale
protected double scaleThe scale of this graph. Used to translatewidthandheightinto canvas coordinates. For example, on retina displays the scale is typically2, i.e. two pixels per unit width or height.- See Also:
-
wrapper
LayoutPanel wrapperThe wrapper element which displays the canvas. Subclasses may use this to add further elements to the graph such as labels. -
logger
Logger for keeping track of and reporting events and issues. -
element
Handle to the object's underlying DOM element. -
canvas
Handle to the canvas for drawing the graphics. -
g
Handle to the graphical context for drawing on the canvas. -
colors
The array of colors used for drawing the graph. -
markers
Markers for decorating the graph. -
markerColors
The array of colors used for markers. -
module
The module backing the graph. -
bounds
The bounds of the displaying area. This excludes any frames and/or axes labels. -
style
The style of the graph. Includes labels, fonts, etc. -
buffer
The buffer to store historical data, if applicable. -
MIN_BUFFER_SIZE
protected static final int MIN_BUFFER_SIZEThe minimum buffer size.- See Also:
-
DEFAULT_BUFFER_SIZE
protected static final int DEFAULT_BUFFER_SIZEThe default buffer size. Must be at leastMIN_BUFFER_SIZE.- See Also:
-
MIN_MSEC_BETWEEN_UPDATES
public static final int MIN_MSEC_BETWEEN_UPDATESThe minimum time between updates in milliseconds.- See Also:
-
updatetime
protected double updatetimeThe field to store the time of the last update. -
CURSOR_GRAB_NODE_CLASS
CSS class applied when the user is grabbing a node.- See Also:
-
CURSOR_MOVE_NODE_CLASS
CSS class applied when the user is dragging a node.- See Also:
-
CURSOR_ZOOM_IN_CLASS
-
CURSOR_ZOOM_OUT_CLASS
-
bufferSizeMenu
The context menu to set the buffer size for graphs with historical data. -
hasZoom
protected boolean hasZoomThe flag to indicate whether the graph supports zoom. The default is no support. -
zoomResetMenu
ContextMenuItem zoomResetMenuThe context menu item to reset the zoom level. -
zoomInMenu
ContextMenuItem zoomInMenuThe context menu item to zoom in (enlarge) by a factor of2. -
zoomOutMenu
ContextMenuItem zoomOutMenuThe context menu item to zoom out (reduce) by a factor of1/2. -
logYMenu
ContextMenuCheckBoxItem logYMenuThe menu item to toggle logarithmic scaling on the y-axis. -
TWOPI
private static final double TWOPIConstant representing the numerical value of \(2 \pi\)- See Also:
-
PIHALF
protected static final double PIHALFConstant representing the numerical value of \(\pi/2\)- See Also:
-
MAX_SEGEMENTS
private static final int MAX_SEGEMENTSThe maximum number of line segments to draw before returning control to the event loop.- See Also:
-
hasMessage
protected boolean hasMessageFlag to indicate whether the graph displays a message. -
leftMouseButton
protected boolean leftMouseButtonThe flag to indicate whether the left mouse button is pressed. -
mouseX
protected int mouseXThex-coordinate of the previous mouse or tap event. -
mouseY
protected int mouseYThey-coordinate of the previous mouse or tap event. -
CSS_CURSOR_MOVE_VIEW
The CSS class name for the view movement cursor.- See Also:
-
touchEndTime
protected double touchEndTimeThe time when the previous touch ended. -
pinchX
protected int pinchXThex-coordinate of the center of the pinching gesture. -
pinchY
protected int pinchYThey-coordinate of the center of the pinching gesture. -
pinchDist
protected double pinchDistThe distance between the pinching gesture. -
zoomInertiaTimer
The timer to remove the CSS classes.evoludo-cursorZoomInor.evoludo-cursorZoomIn, respectively, from the graph element after the inertia of zooming has worn off.
-
-
Constructor Details
-
AbstractGraph
Create the base class for graphs. Allocates the canvas, retrieves the shared tooltip and context menu. Use the CSS classevoludo-Canvas2Dfor custom formatting of the canvas element.- Parameters:
view- the view of this graphmodule- the module backing the graph
-
-
Method Details
-
setTooltipProvider
Set the provider for tooltips.- Parameters:
tooltipProvider- the provider for tooltips
-
getBuffer
Return theRingBuffer<double[]>containing historical data, if applicable.- Returns:
- the buffer with historical data or
null
-
doUpdate
public boolean doUpdate()Determine whether it is time to update the display.- Returns:
trueif time to update graph
-
onLoad
-
onUnload
-
parse
Parse the arguments for the graph. Default implementation does nothing.- Parameters:
args- the arguments for the graph- Returns:
trueif parsing was successful
-
activate
public void activate()Perform necessary preparations to show the graph in the GUI. Attaches mouse and touch handlers for graphs that implementAbstractGraph.ZoomingorAbstractGraph.Shiftinginterfaces.- See Also:
-
deactivate
public void deactivate()The graph is removed from the GUI. Opportunity for some clean up. Removes all mouse and touch handlers from graph.- See Also:
-
onResize
public void onResize()- Specified by:
onResizein interfaceRequiresResize
-
updateCanvas
private void updateCanvas()Update the canvas size and coordinate space dimensions. IMPORTANT: Setting the canvas size or the coordinate space dimensions clears the canvas (even with no actual changes)! -
reset
public void reset()Reset the graph. Clear canvas and messages. -
init
public void init()Initialize the graph. Do not clear graph. -
paint
public void paint()Draw the graph. -
getModule
-
paint
public boolean paint(boolean force) Draw the graph. For re-drawing the graph, setforcetotrue.- Parameters:
force-trueto force re-drawing of graph- Returns:
trueif painting skipped
-
setMarkers
Assign a list of markers to the graph.- Parameters:
markers- the list of markers
-
setMarkers
-
setColors
Assign a list of colors to the graph.- Parameters:
colors- the list of colors
-
hasHistory
public boolean hasHistory()Check whether the graph entertains a buffer with historical data.- Returns:
trueif the graph stores the data history
-
clearHistory
public void clearHistory()Clear the history of the graph (if there is one). -
prependTime2Data
protected double[] prependTime2Data(double t, double[] data) Utility method to prepend time to data point.- Parameters:
t- the timedata- the data- Returns:
- the new data array including time
-
populateContextMenuAt
Populate context menumenuin listening widget at (relative) position(x,y).Adds buffer size menu and queries the view to add further functionality.
- Specified by:
populateContextMenuAtin interfaceContextMenu.Provider- Parameters:
menu- context menu entries are added herex- horizontal coordinate (relative to listening widget)y- horizontal coordinate (relative to listening widget)- See Also:
-
addBufferSizeMenu
Add buffer size menu item to context menu if graph supports historical data.- Parameters:
menu- the context menu to populate
-
addLogScaleMenu
Add logarithmic scale menu item to context menu if graph supports log scale ony-axis.- Parameters:
menu- the context menu to populate
-
addZoomMenu
Add zoom menu items to context menu if graph supports zooming.- Parameters:
menu- the context menu to populate
-
setLogY
void setLogY(boolean logY) Set they-axis to logarithmic scale iflogYistrueand ifyMin ≥ 0. IfyMin == 0it is increased to0.01 * yMax. IfyMin < 0logarithmic scale requests are ignored.- Parameters:
logY-trueto set logarithmic scale ony-axis
-
setBufferCapacity
protected void setBufferCapacity(int capacity) Sets the buffer capacity tocapacity, if applicable.- Parameters:
capacity- the new buffer capacity
-
contains
public boolean contains(int x, int y) Checks if the (browser) coordinates(x, y)are inside this graph. This is useful for controllers that may manage several graphs.- Parameters:
x- thex-coordinate to checky- they-coordinate to check- Returns:
trueif(x, y)is inside graph
-
convertToScaledCoordinates
Convert the (browser) coordinates(x, y)to scaled coordinates in \([0,1]^2\).- Parameters:
x- thex-coordinate to converty- they-coordinate to convert- Returns:
- the converted coordinates
-
convertToScaledCoordinates
Convert the (browser) coordinates(x, y)to scaled coordinates in \([0,1]^2\) and store indest.- Parameters:
x- thex-coordinate to converty- they-coordinate to convertdest- the point to save the converted coordinates- Returns:
- the converted coordinates
-
export
Export the graphical contextctx.- Parameters:
ctx- the graphical context to export
-
calcBounds
protected boolean calcBounds()Calculate bounds of drawing area. If element has never been visible its size is not yet known.- Returns:
trueif bounds are successfully calculated.
-
calcBounds
public void calcBounds(int width, int height) Calculate bounds of drawing area.- Parameters:
width- the width of the drawing areaheight- the height of the drawing area
-
adjustBoundsForLabels
private void adjustBoundsForLabels()Adjust bounds to make room for axes labels. -
adjustBoundsForTickLabels
private void adjustBoundsForTickLabels()Adjust bounds to make room for tick labels. -
drawFrame
protected void drawFrame(int xLevels, int yLevels) Draw the frame of the graph including axes labels, ticks and tick marks, as applicable.Implementation Note:
The top, left corner of the canvas is assumed to be at(0, 0). Flips the direction of they-axis.- Parameters:
xLevels- the number of vertical levelsyLevels- the number of horizontal levels- See Also:
-
drawFrame
protected void drawFrame(int xLevels, int yLevels, double gscale) Draw the frame of the graph including axes labels, ticks and tick marks, as applicable, after scaling the canvas bygscale.Implementation Note:
After scaling the origin(0, 0)is assumed to be in the bottom, left corner of the canvas.- Parameters:
xLevels- the number of vertical levelsyLevels- the number of horizontal levelsgscale- the scaling applied to the coordinate transformation
-
drawFrameBorder
private void drawFrameBorder(double w, double h) Draw the bounding box of the graph frame.- Parameters:
w- frame widthh- frame height
-
drawXLevels
private void drawXLevels(int xLevels, double w, double h) Draw regular vertical guide lines, ticks, and labels.- Parameters:
xLevels- number of levelsw- frame widthh- frame height
-
drawCustomXLevels
private void drawCustomXLevels(double w, double h) Draw vertical guide lines at custom x positions.- Parameters:
w- frame widthh- frame height
-
drawYLevels
private void drawYLevels(int yLevels, double w, double h) Draw the y-levels including ticks and tick labels.- Parameters:
yLevels- the number of horizontal levelsw- the width of the graphh- the height of the graph
-
computeYRange
private double[] computeYRange()Compute the (possibly logarithmic) y-range for tick computations.- Returns:
- array {ymin, yrange}
-
computeYVal
private double computeYVal(int n, double frac, double yrange, double ymin) Compute the y-value for tick numbern.- Parameters:
n- tick indexfrac- fractional spacing between ticksyrange- total y-range (possibly logarithmic)ymin- minimum y-value (possibly logarithmic)- Returns:
- the y-value represented by the tick
-
drawYTickLabel
private void drawYTickLabel(double w, double level, int n, double yval) Draw the y-axis tick label at the specified screen level.- Parameters:
w- frame widthlevel- screen y-position for the tickn- tick indexyval- y-value represented by the tick
-
drawCustomYLevels
private void drawCustomYLevels(double w, double h) Draw horizontal guide lines at custom y positions.- Parameters:
w- frame widthh- frame height
-
drawXAxisLabel
private void drawXAxisLabel(double w, double h) Draw the x-axis label.- Parameters:
w- frame widthh- frame height
-
drawYAxisLabel
private void drawYAxisLabel(double w, double h) Draw the y-axis label, including positioning logic based on tick labels.- Parameters:
w- frame widthh- frame height
-
drawGraphLabel
private void drawGraphLabel(double gscale) Draw the label shown inside the graph canvas.- Parameters:
gscale- current canvas scale factor
-
setFont
Set the font tocssfontin CSS format for drawing on the canvas.- Parameters:
cssfont- the font for drawing
-
setStrokeStyleAt
protected void setStrokeStyleAt(int node) Set the stroke colour for node with indexnode.- Parameters:
node- the index of the node
-
stroke
-
fill
-
sketch
Draw or fill (iffill == true) the pathpath.Implementation notes:
- Drawing too many segments at once becomes very slow (why?).
- Periodically closing and stroking the path is orders of magnitudes faster!
- This simple change renders freezing of the GUI essentially a non issue.
- SVG seems to be a stickler about opening and closing paths or empty paths (see Canvas2SVG.js)
- Parameters:
path- the path to draw (or fill)fill-trueto fill path
-
closePath
private void closePath(boolean fill) Helper method to close the path and draw (or fill) it.- Parameters:
fill-trueto fill path
-
strokeRect
protected void strokeRect(double x, double y, double w, double h) Draw the rectangle with origin at(x,y), widthwand heighth.- Parameters:
x- thex-coordinate of the originy- they-coordinate of the originw- the width of the rectangleh- the height of the rectangle
-
fillRect
protected void fillRect(double x, double y, double w, double h) Fill the rectangle with origin at(x,y), widthwand heighth.- Parameters:
x- thex-coordinate of the originy- they-coordinate of the originw- the width of the rectangleh- the height of the rectangle
-
strokeCircle
Draw the outline of the 2D node.- Parameters:
node- the node to draw
-
strokeCircle
Draw the outline of a circle atpointwithradius.- Parameters:
point- the node to drawradius- the radius of the circle
-
strokeCircle
protected void strokeCircle(double x, double y, double radius) Draw the circle with the center at(x,y)and radiusradius.- Parameters:
x- thex-coordinate of the centery- they-coordinate of the centerradius- the radius of the circle
-
fillCircle
-
fillCircle
Draw a filled circle atpointwithradius.- Parameters:
point- the node to drawradius- the radius of the circle
-
fillCircle
protected void fillCircle(double x, double y, double radius) Fill the circle with the center at(x,y)and radiusradius.- Parameters:
x- thex-coordinate of the centery- they-coordinate of the centerradius- the radius of the circle
-
sketchCircle
private void sketchCircle(double x, double y, double radius) Helper method to create a path for a circle with the center at(x,y)and radiusradius.- Parameters:
x- thex-coordinate of the centery- they-coordinate of the centerradius- the radius of the circle
-
strokeLine
-
strokeLine
protected void strokeLine(double sx, double sy, double ex, double ey) Draw a line from point(sx,sy)to(ex,ey).- Parameters:
sx- thex-coordinate of the start pointsy- they-coordinate of the start pointex- thex-coordinate of the end pointey- they-coordinate of the end point
-
fillTextVertical
Draw filled text vertically starting at point(x,y)- Parameters:
msg- the text to writex- thex-coordinate of the start pointy- they-coordinate of the start point
-
clearGraph
public void clearGraph()Clear the graph. -
clearCanvas
protected void clearCanvas()Clear the canvas.Implementation note:
Assumes scaled canvas coordinates, i.e. lower, left corner at(0,0). -
resetTransforms
protected void resetTransforms()Reset the transformation of the graphics context to the identity transform. -
displayMessage
Display messagemsgon the graph (no HTML formatting).Implementation note:
The message is centered and scaled such that it fills approximately two thirds of the width of the graph.- Parameters:
msg- the message to display- Returns:
trueif message displayed
-
clearMessage
public void clearMessage()Clear the message. -
hasMessage
public boolean hasMessage()Check if the graph displays a message.- Returns:
trueif message displayed
-
zoom
public void zoom()Reset zoom. Default implementation for graphs that implementZooming.- See Also:
-
zoom
public void zoom(double zoom) Adjust zoom level by the factorzoom. Default implementation for graphs that implementZooming.- Parameters:
zoom- the new zoom level- See Also:
-
zoom
public void zoom(double zoom, int x, int y) Adjust zoom level by the factorzoomwith the center at coordinates(x,y)(in display coordinates as provided by event listeners). Default implementation for graphs that implementZooming.- Parameters:
zoom- the new zoom levelx- thex-coordinate of the zoom centery- they-coordinate of the zoom center- See Also:
-
zoom
protected void zoom(double zoom, double fx, double fy) Helper method to adjust zoom level with the zoom center at the scaled coordinates(fx, fy), specified as a fraction of the view port in horizontal and vertical directions, respectively.- Parameters:
zoom- the new zoom levelfx- the scaledx-coordinate of the zoom centerfy- the scaledy-coordinate of the zoom center- See Also:
-
shift
public void shift(int dx, int dy) Shift the (zoomed) graph within the view port by(dx, dy). Default implementation for graphs that implementShifting.- Parameters:
dx- the horizontal shift of the graphdy- the vertical shift of the graph- See Also:
-
onMouseOut
If mouse leaves graph while shifting the view stop shifting. Mouse events are no longer received and hence it is impossible to track releasing or pressing mouse buttons.
- Specified by:
onMouseOutin interfaceMouseOutHandler
-
onMouseDown
If a node has been hit by a left-click, remember the node's index and the current mouse coordinates. This information might be used by subsequent
MouseMoveEvents.- Specified by:
onMouseDownin interfaceMouseDownHandler- See Also:
-
onMouseUp
Cancel all interactions with the graph and reset node and mouse information.
CSS Style Rules
- .evoludo-cursorMoveView
- removed from graph element.
- Specified by:
onMouseUpin interfaceMouseUpHandler- See Also:
-
onMouseMove
If the left mouse-key is pressed the graph is shifted within its viewport. Note this requires that the zoom level of the graph exceeds
1.CSS Style Rules
- .evoludo-cursorMoveView
- added to graph element when shifting the view.
- Specified by:
onMouseMovein interfaceMouseMoveHandler- See Also:
-
onMouseWheel
Adjusts the zoom level of the graph, while preserving the location of the mouse on the graph. The zooming has inertia.
CSS Style Rules
- .evoludo-cursorZoomIn
- added to graph element when zooming in and removed when inertia stops.
- .evoludo-cursorZoomOut
- added to graph element when zooming out and removed when inertia stops.
- Specified by:
onMouseWheelin interfaceMouseWheelHandler- See Also:
-
onTouchStart
The graph reacts to different kinds of touches: short touches or taps (
<250msec) and long touches (>250msec). Long touches trigger different actions depending on the number of fingers:- Single finger
- Initiate shifting the view
- Two fingers
- Initiate pinching zoom.
- Specified by:
onTouchStartin interfaceTouchStartHandler- See Also:
-
onTouchEnd
The number of touches on the graph changed.
- Specified by:
onTouchEndin interfaceTouchEndHandler
-
onTouchMove
The graph reacts to different kinds of touch moves:
- Move one finger
- Shift view
- Pinch two fingers
- Zoom view
- Specified by:
onTouchMovein interfaceTouchMoveHandler
-
addContextMenuHandler
- Specified by:
addContextMenuHandlerin interfaceHasContextMenuHandlers
-
getStyle
-
autoscale
public void autoscale(boolean x, boolean y) Set auto-scaling for horizontal and vertical axes.- Parameters:
x-trueto automatically scale thex-axisy-trueto automatically scale they-axis
-