Repository navigation
EN SpeedometerIndicator
Below is the full source of the class in documentation form. The comments inside the block explain the purpose of the parts of the class, but they are not kept in the working file SpeedometerIndicator.java: the production code stays clean, and the explanations live in the wiki. The format in which the indicator is saved is described on the SpeedometerIndicator JSON page.
package com.velitask.plugin.example;
import com.velitask.sdk.FrameContext;
import com.velitask.sdk.Indicator;
import com.velitask.sdk.IndicatorContext;
import com.velitask.sdk.IndicatorSkin;
import com.velitask.sdk.IndicatorSkinTransfer;
import com.velitask.sdk.data.DistanceSensorAtom;
import com.velitask.sdk.properties.ColorProperty;
import com.velitask.sdk.properties.DisplayConfig;
import com.velitask.sdk.properties.DistanceSensorProperty;
import com.velitask.sdk.properties.DoubleProperty;
import com.velitask.sdk.properties.EnumArrayProperty;
import com.velitask.sdk.properties.FontColorProperty;
import com.velitask.sdk.properties.IProperty;
import com.velitask.sdk.properties.PropertyGroup;
import com.velitask.sdk.properties.SvgProperty;
import com.velitask.sdk.properties.TextTemplateProperty;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.geom.Arc2D;
import java.awt.geom.Rectangle2D;
import org.abricos.core.state.maket.HorizontalAlign;
import org.abricos.core.state.maket.Maket;
import org.abricos.core.state.maket.VerticalAlign;
/* Circular speedometer: needle, scale and the speed number in the center. */
public class SpeedometerIndicator extends Indicator {
/* Indicator name in the layer JSON. It must not be changed without a migration. */
public static final String NAME = "speedometer";
/* Localization key prefix: PluginExample.Indicator.speedometer. */
private static final String KEY = Plagin.KEY_INDICATOR + "." + NAME;
/* Distance sensor (JSON key Distance): the speed is taken from its atom. */
private final DistanceSensorProperty mDistance = new DistanceSensorProperty();
/* Scale maximum options; the order defines the saved speedScale index. */
public static enum SpeedScale {
SCALE_40(40),
SCALE_80(80),
SCALE_160(160),
SCALE_320(320);
public final int value;
SpeedScale(int value) {
this.value = value;
}
}
private static final String SPEED_SCALE = "speedScale";
/* Scale choice, 160 by default (index 2). Option labels: 40, 80, 160, 320. */
private final EnumArrayProperty<SpeedScale> mSpeedScale = new EnumArrayProperty<>(SpeedScale.class) {
{
set(SpeedScale.SCALE_160);
}
@Override
public String getName() {
return SPEED_SCALE;
}
@Override
public String getTitle() {
return localized(KEY + "." + SPEED_SCALE + ".title");
}
@Override
protected String[] defineTitles() {
SpeedScale[] vs = SpeedScale.values();
String[] t = new String[vs.length];
for (int i = 0; i < vs.length; i++) {
t[i] = String.valueOf(vs[i].value);
}
return t;
}
};
/* Font and color of the number in the center (JSON key font). */
private final FontColorProperty mText = new FontColorProperty();
private static final String BG_COLOR = "bgColor";
/* Background color: gray, alpha 51 of 255. */
private final ColorProperty mBgColor = new ColorProperty(
new Color(204, 204, 204, 51),
BG_COLOR,
localized(KEY + "." + BG_COLOR + ".title"));
private static final String SCALE_COLOR = "scaleColor";
/* Color of the scale ticks and numbers. */
private final ColorProperty mScaleColor = new ColorProperty(
Color.WHITE,
SCALE_COLOR,
localized(KEY + "." + SCALE_COLOR + ".title"));
private static final String ARROW_FILL_COLOR = "arrowFillColor";
/* Needle fill; with alpha 112 of 255 it also colors the tail arc. */
private final ColorProperty mArrowFillColor = new ColorProperty(
new Color(0xcc, 0x58, 0x54),
ARROW_FILL_COLOR,
localized(KEY + "." + ARROW_FILL_COLOR + ".title"));
private static final String ARROW_STROKE_COLOR = "arrowStrokeColor";
/* Needle stroke and the color of the center dot. */
private final ColorProperty mArrowStrokeColor = new ColorProperty(
Color.WHITE,
ARROW_STROKE_COLOR,
localized(KEY + "." + ARROW_STROKE_COLOR + ".title"));
/* Needle stroke width; the default value is 2.5. */
private final DoubleProperty mArrowStrokeWidth = new DoubleProperty() {
@Override
public String getName() {
return "arrowStrokeWidth";
}
@Override
public String getTitle() {
return localized(KEY + ".arrowStrokeWidth.title");
}
@Override
public Double getDefault() {
return 2.5;
}
};
/* Template of the number in the center (JSON key textTemplate). */
private final SpeedometerTextTemplateProperty mTemplate = new SpeedometerTextTemplateProperty();
private TextTemplateProperty getTemplate() {
return mTemplate;
}
/*
* SVG parts of the dial. They are not part of defineProperties() and are not saved to JSON;
* bind substitutes the property value into an attribute of the SVG element with the given CSS class.
*/
private static final String SVG_PATH = "svg/speedometer/";
private final SvgProperty mBgSvg = new SvgProperty("BgSvg", SVG_PATH + "background.svg")
.bind(".ring", "fill", mBgColor);
private final SvgProperty mDelimiterSvg = new SvgProperty("delimiterSvg", SVG_PATH + "delimiter.svg")
.bind(".tick-major", "stroke", mScaleColor)
.bind(".tick-minor", "stroke", mScaleColor);
/* Four variants of the scale numbers; the index matches the SpeedScale order. */
private final SvgProperty[] mScaleSvgs = new SvgProperty[] {
new SvgProperty("scale40", SVG_PATH + "numeric_40.svg")
.bind(".number", "fill", mScaleColor),
new SvgProperty("scale80", SVG_PATH + "numeric_80.svg")
.bind(".number", "fill", mScaleColor),
new SvgProperty("scale160", SVG_PATH + "numeric_160.svg")
.bind(".number", "fill", mScaleColor),
new SvgProperty("scale320", SVG_PATH + "numeric_320.svg")
.bind(".number", "fill", mScaleColor), };
private final SvgProperty mArrowSvg = new SvgProperty("ArrowSvg", SVG_PATH + "arrow.svg")
.bind(".arrow-body", "fill", mArrowFillColor)
.bind(".arrow-body", "stroke", mArrowStrokeColor)
.bind(".arrow-body", "stroke-width", mArrowStrokeWidth)
.bind(".arrow-hub", "fill", mArrowStrokeColor);
@Override
public String getName() {
return NAME;
}
@Override
public String getTitle() {
return localized(KEY + ".title");
}
@Override
public String getDescription() {
return localized(KEY + ".description");
}
@Override
public String getTags() {
return localized(KEY + ".tags");
}
@Override
/* Default placement: top-right corner, 500x500, right and bottom margins of 50. */
public void defineMaket(Maket maket) {
maket.setVertical(VerticalAlign.TOP);
maket.setHorizontal(HorizontalAlign.RIGHT);
maket.setLayerMargin(null, null, 50d, 50d);
maket.setLayerSize(500d, 500d);
}
@Override
/* Properties in UI and JSON order. */
public IProperty[] defineProperties() {
return new IProperty[] {
mDistance, mSpeedScale,
mText, getTemplate(),
mBgColor, mScaleColor,
mArrowFillColor, mArrowStrokeColor, mArrowStrokeWidth
};
}
@Override
/* The scale, colors and stroke width are moved to the "Appearance" group. */
public void configureDisplay(DisplayConfig config) {
config.set(mSpeedScale, PropertyGroup.APPEARANCE);
config.set(mBgColor, PropertyGroup.APPEARANCE);
config.set(mScaleColor, PropertyGroup.APPEARANCE);
config.set(mArrowFillColor, PropertyGroup.APPEARANCE);
config.set(mArrowStrokeColor, PropertyGroup.APPEARANCE);
config.set(mArrowStrokeWidth, PropertyGroup.APPEARANCE);
}
@Override
/* Two skins: night and racing. They do not change the text template or the stroke width. */
public IndicatorSkin[] defineSkins() {
return new IndicatorSkin[] {
IndicatorSkin.builder("night", localized(KEY + ".skin.night"))
.set(mText.getColor().skin(0xaa, 0xaa, 0xaa))
.set(mBgColor.skin(0x11, 0x11, 0x11, 0xaa))
.set(mScaleColor.skin(0x88, 0x88, 0x88))
.set(mArrowFillColor.skin(0x55, 0x2b, 0x2a))
.set(mArrowStrokeColor.skin(0xaa, 0xaa, 0xaa))
.build(),
IndicatorSkin.builder("racing", localized(KEY + ".skin.racing"))
.set(mText.getColor().skin(0xff, 0xff, 0x00))
.set(mBgColor.skin(0x11, 0x11, 0x11, 0xcc))
.set(mScaleColor.skin(0xff, 0xff, 0x00))
.set(mArrowFillColor.skin(0xff, 0x30, 0x30))
.set(mArrowStrokeColor.skin(0xff, 0xff, 0x00))
.build()
};
}
@Override
/* Frame rendering: the dial is a square centered in the layer. */
public void render(IndicatorContext indicatorContext) {
SpeedometerContext ctx = (SpeedometerContext) indicatorContext;
Graphics2D g = ctx.graphics;
int size = Math.min(ctx.width, ctx.height);
int x = (ctx.width - size) / 2;
int y = (ctx.height - size) / 2;
ctx.bgSvg.render(g, x, y, size, size);
/* Speed from the atom for the frame time; without an atom it stays 0. */
double speedKmh = 0;
DistanceSensorAtom atom = ctx.distance.queryAtom();
if (atom != null) {
speedKmh = atom.speed / 1000.0;
}
/* A full needle turn equals the scale maximum; above the maximum the angle does not grow. */
int scale = Math.max(1, ctx.speedScale.value);
double angleDeg = Math.min(speedKmh, scale) * 360.0 / scale;
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
/* Tail arc under the needle (needle fill color, alpha 112). */
drawArrowTailArc(g, x, y, size, angleDeg, withAlpha(ctx.arrowFill.value, 112));
ctx.delimiterSvg.render(g, x, y, size, size);
ctx.scaleSvg.render(g, x, y, size, size);
/* The needle, rotated by the angle. */
ctx.arrowSvg.render(g, x, y, size, size, angleDeg);
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
/* Number in the center: font scaled to the frame, centered using FontMetrics. */
Font font = ctx.text.toFont(ctx.scale);
g.setFont(font);
g.setColor(ctx.text.color.value);
String text = ctx.template.makeText(speedKmh);
FontMetrics fm = g.getFontMetrics(font);
Rectangle2D r = fm.getStringBounds(text, g);
int tx = (ctx.width - (int) r.getWidth()) / 2;
int ty = (ctx.height - (int) r.getHeight()) / 2 + fm.getAscent();
g.drawString(text, tx, ty);
}
/* Arc from 12 o'clock clockwise by the needle angle. */
private static void drawArrowTailArc(Graphics2D g, int x, int y, int size,
double angleDeg, Color color) {
if (angleDeg <= 0) {
return;
}
float thickness = size * 5f / 200f;
float arcRadius = size * 82.5f / 200f;
float inset = size / 2f - arcRadius;
Arc2D arc = new Arc2D.Float(
x + inset, y + inset,
size - 2 * inset, size - 2 * inset,
90f, (float) -angleDeg, Arc2D.OPEN);
Graphics2D g2 = (Graphics2D) g.create();
try {
g2.setStroke(new BasicStroke(thickness, BasicStroke.CAP_BUTT, BasicStroke.JOIN_ROUND));
g2.setColor(color);
g2.draw(arc);
} finally {
g2.dispose();
}
}
/* A copy of the color with a different alpha (0..255). */
private static Color withAlpha(Color c, int alpha) {
return new Color(c.getRed(), c.getGreen(), c.getBlue(), Math.max(0, Math.min(255, alpha)));
}
/* Number template: one variable curr, format %.0f. */
static class SpeedometerTextTemplateProperty extends TextTemplateProperty {
private static final String KEY_PROPERTY = KEY + "." + NAME;
private static final String KEY_PROPERTY_TEMPLATE = KEY_PROPERTY + ".template";
private static final String KEY_PROPERTY_VAR = KEY_PROPERTY + ".var";
private static final String KEY_PROPERTY_VAR_CURR = KEY_PROPERTY_VAR + ".curr";
@Override
protected String defineTemplate() {
return localized(KEY_PROPERTY_TEMPLATE + ".default");
}
@Override
protected Var[] defineVars() {
return new Var[] {
new Var("curr", "%.0f", localized(KEY_PROPERTY_VAR_CURR))
};
}
/* A variant with one decimal place (%.1f) is declared, but no skin uses it. */
public IndicatorSkinTransfer skinFloat() {
return skin(localized(KEY_PROPERTY_TEMPLATE + ".float"),
new Var[] { new Var("curr", "%.1f", localized(KEY_PROPERTY_VAR_CURR)) });
}
}
/* Frame context: property snapshots and ready SVGs for rendering. */
public class SpeedometerContext extends IndicatorContext {
public final DistanceSensorProperty.SensorContext distance;
public final SpeedScale speedScale;
public final FontColorProperty.FontColorContext text;
public final ColorProperty.ColorContext arrowFill;
public final TextTemplateProperty.TextTemplateContext template;
public final SvgProperty.SvgContext bgSvg;
public final SvgProperty.SvgContext delimiterSvg;
public final SvgProperty.SvgContext scaleSvg;
public final SvgProperty.SvgContext arrowSvg;
public SpeedometerContext(FrameContext frame) {
super(frame);
distance = mDistance.createContext(frame);
speedScale = mSpeedScale.get(frame);
text = mText.createContext(frame);
arrowFill = mArrowFillColor.createContext(frame);
template = getTemplate().createContext(frame);
bgSvg = mBgSvg.createContext(frame);
delimiterSvg = mDelimiterSvg.createContext(frame);
/* The scale numbers are chosen by the current SpeedScale. */
scaleSvg = scaleSvgFor(speedScale).createContext(frame);
arrowSvg = mArrowSvg.createContext(frame);
}
private SvgProperty scaleSvgFor(SpeedScale scale) {
return mScaleSvgs[scale.ordinal()];
}
}
@Override
/* Frame context factory. */
public IndicatorContext createContext(FrameContext frame) {
return new SpeedometerContext(frame);
}
}SpeedometerIndicator draws a circular speedometer: a dial with a scale, a needle, a "tail" arc from zero to the needle, and the speed number in the center. The speed is taken from the distance sensor. The scale maximum is chosen from four options: 40, 80, 160 or 320 km/h. There are two skins: night ("Night") and racing ("Racing").
This is an example of an indicator whose graphics are assembled from SVG files: the user's colors are substituted into the SVG through bind(...), while the Java code is responsible for the rendering order, the needle angle and the number in the center. The SVG files are described on the Resources page.
Data. DistanceSensorProperty (JSON key Distance) provides the object ctx.distance in the frame context. render calls ctx.distance.queryAtom() — the DistanceSensorAtom atom for the time of the current frame. The field atom.speed is divided by 1000.0 and treated as the speed in km/h. If there is no atom, the speed is zero, but the dial is still drawn. The needle angle is min(speedKmh, scale) * 360 / scale: a full turn corresponds to the scale maximum.
Settings. defineProperties() has nine properties in the order Distance, speedScale, font, textTemplate, bgColor, scaleColor, arrowFillColor, arrowStrokeColor, arrowStrokeWidth.
-
speedScale— an anonymousEnumArrayProperty<SpeedScale>; the initial value isSCALE_160(index 2), the option labels are the numbers40,80,160,320. -
font— aFontColorPropertywith default settings (Dialog, plain, size 48, white); the font color is a nestedColorProperty. -
textTemplate— a nestedSpeedometerTextTemplateProperty(TextTemplateProperty) with one variablecurr, format%.0f, template{curr}. -
bgColor,scaleColor,arrowFillColor,arrowStrokeColor— fourColorPropertyobjects. Initial values: background204, 204, 204with alpha51, white scale, needle fill204, 88, 84, white stroke. -
arrowStrokeWidth— an anonymousDoublePropertywith the initial value2.5.
The SvgProperty objects (mBgSvg, mDelimiterSvg, the four mScaleSvgs, mArrowSvg) are not part of defineProperties() and are not saved to JSON. The bind(selector, attribute, property) bindings: background — .ring (fill), ticks — .tick-major and .tick-minor (stroke), scale numbers — .number (fill), needle — .arrow-body (fill, stroke and stroke-width) and .arrow-hub (fill with the stroke color).
In configureDisplay() the scale, the four colors and the stroke width are moved to the "Appearance" group; the sensor, font and template stay in the main group. defineMaket() sets the default placement: top-right corner, size 500 × 500, right and bottom margins of 50.
Skins. defineSkins() returns two skins; both change the font color, background color, scale color, and the needle fill and stroke; the skins do not change the text template or the stroke width.
| Skin | Font color | Background | Scale | Needle fill | Needle stroke |
|---|---|---|---|---|---|
night ("Night") |
170, 170, 170 |
17, 17, 17, alpha 170
|
136, 136, 136 |
85, 43, 42 |
170, 170, 170 |
racing ("Racing") |
255, 255, 0 |
17, 17, 17, alpha 204
|
255, 255, 0 |
255, 48, 48 |
255, 255, 0 |
Frame context. createContext(FrameContext frame) creates a SpeedometerContext. The constructor calls super(frame), the sensor and the properties create their context through createContext(frame), and the scale is read through mSpeedScale.get(frame). The needed SVG with the scale numbers is chosen by speedScale.ordinal(), so the order of SpeedScale and the order of mScaleSvgs must match.
Rendering. The dial is a square with side min(width, height), centered in the layer. The order:
- the background (
bgSvg); - the tail arc:
drawArrowTailArcdraws anArc2Dfrom 12 o'clock clockwise by the needle angle, in the needle fill color with alpha112; the arc thickness and radius are proportional to the dial size; - the ticks (
delimiterSvg); - the scale numbers (
scaleSvg); - the needle (
arrowSvg), rotated by the angle; - the number: text from the template
makeText(speedKmh), the font scaled byctx.scale, centered usingFontMetrics.
- A speed above the scale maximum limits only the angle: the needle stays at the maximum, while the number in the center remains the real one.
- Without an atom the indicator shows zero (the number by the template for
0) and does not skip rendering. - The number in the center is always in km/h: the indicator has no unit selection.
- The
skinFloat()method inSpeedometerTextTemplatePropertyis declared (format%.1f), but no skin connects it, so it is unavailable to the user. - The
arrowStrokeWidthstroke width affects the needle stroke in the SVG, but not the tail arc: its thickness is calculated from the dial size. - The tail arc is painted in the needle fill color with a fixed transparency; there is no separate setting for the tail color. The file
arrow_tail.svgis in the resources but is not used by the code. - The
SvgPropertyproperties are not saved: the dial's appearance changes only through colors, scale and stroke width. - Adding a new scale requires three consistent edits: a
SpeedScaleelement, a new SVG with the numbers, and an element of themScaleSvgsarray at the same position. - Renaming properties (
speedScale,bgColor, etc.) breaks loading of saved projects: loading goes by names.