Repository navigation
SpeedometerIndicator
Up | Previous | Next | Русский
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 stored in the working file SpeedometerIndicator.java: the production code stays clean and the explanations live in the wiki.
package com.velitask.plugin.official;
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.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 com.velitask.sdk.properties.TransparentColorProperty;
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;
/* A classic round speedometer: needle, scale and the speed number in the center. */
public class SpeedometerIndicator extends Indicator {
/* Stable indicator name in the layer JSON. It must not be changed without a migration. */
public static final String NAME = "speedometer";
/* Localization key prefix: Plugin.Indicator.speedometer. */
private static final String KEY = _KEY + "." + NAME;
/* Folder of the speedometer SVG resources inside the plugin resources. */
private static final String SVG_PATH = "svg/speedometer/";
/* Distance sensor (JSON key "Distance"). The instantaneous speed is taken from its atom. */
private final DistanceSensorProperty mDistance = new DistanceSensorProperty();
/* Scale options. JSON stores the index (ordinal); value is the scale maximum in km/h. */
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;
}
}
/* JSON key and part of the localization key of the scale setting. */
private static final String SPEED_SCALE = "speedScale";
/* Scale choice. The initial value SCALE_160 is set in the initializer block (index 2). */
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");
}
/* The labels of the choice items are the scale numbers themselves. */
@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 center number (JSON key "font"). The default size is 120. */
private final FontColorProperty mText = new FontColorProperty(120);
/* JSON key of the dial background. */
private static final String BACKGROUND = "background";
/* Background: color (204, 204, 204) and transparency 80 (out of 100). */
private final TransparentColorProperty mBackground = new TransparentColorProperty(
BACKGROUND,
localized(KEY + "." + BACKGROUND + ".title"),
new Color(204, 204, 204), 80
);
private static final String SCALE_COLOR = "scaleColor";
/* Color of the scale ticks and numbers. White by default. */
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. (204, 88, 84) by default. */
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";
/* Stroke of the needle and the center dot. White by default. */
private final ColorProperty mArrowStrokeColor = new ColorProperty(
Color.WHITE,
ARROW_STROKE_COLOR,
localized(KEY + "." + ARROW_STROKE_COLOR + ".title")
);
private static final String TAIL_COLOR = "tailColor";
/* Color of the "tail", the sector swept by the needle. (103, 136, 166) with alpha 178 by default. */
private final ColorProperty mTailColor = new ColorProperty(
new Color(0x67, 0x88, 0xa6, 0xb2),
TAIL_COLOR,
localized(KEY + "." + TAIL_COLOR + ".title")
);
/* Template of the center number. */
private final SpeedometerClassicTextTemplateProperty mTemplate = new SpeedometerClassicTextTemplateProperty();
/* The template as the base type; used in the property list and in the context. */
private TextTemplateProperty getTemplate() {
return mTemplate;
}
/* SVG parts of the dial. They are not saved in JSON; colors are substituted into the SVG by CSS selector via bind. */
private final SvgProperty mBgSvg = new SvgProperty("bgSvg", SVG_PATH + "background.svg")
.bind(".ring", "fill", mBackground.getColor());
/* Scale ticks (scale color). */
private final SvgProperty mDelimiterSvg = new SvgProperty("delimiterSvg", SVG_PATH + "delimiter.svg")
.bind(".tick", "fill", mScaleColor);
/* Scale numbers: one SVG for each SpeedScale, chosen by ordinal. */
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)
};
/* Needle: fill and stroke come from the settings. */
private final SvgProperty mArrowSvg = new SvgProperty("arrowSvg", SVG_PATH + "arrow.svg")
.bind(".arrow-body", "fill", mArrowFillColor)
.bind(".arrow-body", "stroke", mArrowStrokeColor);
/* Needle tail; drawn under the mask sector. */
private final SvgProperty mTailSvg = new SvgProperty("tailSvg", SVG_PATH + "arrow_tail.svg")
.bind(".tail", "stroke", mTailColor);
@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");
}
/* Default maket: layer 400 x 400, top/right alignment, margins (left, top, right, bottom) = null, null, 50, 50. */
@Override
public void defineMaket(Maket maket) {
maket.setVertical(VerticalAlign.TOP);
maket.setHorizontal(HorizontalAlign.RIGHT);
maket.setLayerMargin(null, null, 50d, 50d);
maket.setLayerSize(400d, 400d);
}
/* Order of properties = order in the settings panel and in JSON. */
@Override
public IProperty[] defineProperties() {
return new IProperty[]{
mDistance, mSpeedScale,
mText, getTemplate(),
mScaleColor,
mArrowFillColor, mArrowStrokeColor, mTailColor,
mBackground
};
}
/* The scale, colors and background are moved to the "Appearance" group. */
@Override
public void configureDisplay(DisplayConfig config) {
config.set(mSpeedScale, PropertyGroup.APPEARANCE);
config.set(mScaleColor, PropertyGroup.APPEARANCE);
config.set(mArrowFillColor, PropertyGroup.APPEARANCE);
config.set(mArrowStrokeColor, PropertyGroup.APPEARANCE);
config.set(mTailColor, PropertyGroup.APPEARANCE);
config.set(mBackground, PropertyGroup.APPEARANCE);
}
/* The only registered skin is "night" (dark colors). */
@Override
public IndicatorSkin[] defineSkins() {
return new IndicatorSkin[]{
IndicatorSkin.builder("night", localized(KEY + ".skin.night"))
.set(mText.getColor().skin(0xaa, 0xaa, 0xaa))
.set(mBackground.getColor().skin(0x11, 0x11, 0x11))
.set(mBackground.getTransparency().skin(33))
.set(mScaleColor.skin(0x88, 0x88, 0x88))
.set(mArrowFillColor.skin(0x55, 0x2b, 0x2a))
.set(mArrowStrokeColor.skin(0xaa, 0xaa, 0xaa))
.set(mTailColor.skin(0x33, 0x44, 0x55, 0xaa))
.build()
};
}
/* Drawing: background, tail, ticks, scale numbers, needle, center number. */
@Override
public void render(IndicatorContext indicatorContext) {
SpeedometerClassicContext ctx = (SpeedometerClassicContext) indicatorContext;
Graphics2D g = ctx.graphics;
/* The dial is a square on the shorter side of the layer, centered. */
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, ctx.background.alpha);
/* Without an atom the speed is treated as zero; the dial is still drawn. */
double speedKmh = 0;
DistanceSensorAtom atom = ctx.distance.queryAtom();
if (atom != null) {
/* The speed in the atom is stored in thousandths of km/h. */
speedKmh = atom.speed / 1000.0;
}
int scale = Math.max(1, ctx.speedScale.value);
/* A full turn corresponds to the scale maximum; above the maximum the needle stays at 360. */
double angleDeg = Math.min(speedKmh, scale) * 360.0 / scale;
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
renderTailArc(g, ctx.tailSvg, x, y, size, angleDeg);
ctx.delimiterSvg.render(g, x, y, size, size);
ctx.scaleSvg.render(g, x, y, size, size);
ctx.arrowSvg.render(g, x, y, size, size, angleDeg);
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
Font font = ctx.text.toFont(ctx.scale);
g.setFont(font);
g.setColor(ctx.text.color.value);
/* One value is passed to the template: the speed in km/h. */
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);
}
/* Draws the tail only in the sector starting at 270 degrees and spanning the needle angle; the rest is cut off by clip. */
private static void renderTailArc(Graphics2D g, SvgProperty.SvgContext tailSvg,
int x, int y, int size, double angleDeg) {
if (angleDeg <= 0) {
return;
}
if (angleDeg >= 360) {
tailSvg.render(g, x, y, size, size);
return;
}
float cx = x + size / 2f;
float cy = y + size / 2f;
float r = size;
Arc2D pie = new Arc2D.Float(
cx - r, cy - r,
2 * r, 2 * r,
270f, (float) -angleDeg,
Arc2D.PIE
);
Graphics2D g2 = (Graphics2D) g.create();
try {
g2.clip(pie);
tailSvg.render(g2, x, y, size, size);
} finally {
g2.dispose();
}
}
/* Number template. NAME inside the class is the inherited "textTemplate", so the localization keys are ...speedometer.textTemplate.* */
static class SpeedometerClassicTextTemplateProperty 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";
/* The default template from localization: {curr}. */
@Override
protected String defineTemplate() {
return localized(KEY_PROPERTY_TEMPLATE + ".default");
}
/* The only variable, curr, with the format %.0f. */
@Override
protected Var[] defineVars() {
return new Var[]{
new Var("curr", "%.0f", localized(KEY_PROPERTY_VAR_CURR))
};
}
/* A template variant with the %.1f format. Not connected in defineSkins(), unavailable to the user. */
public IndicatorSkinTransfer skinFloat() {
return skin(localized(KEY_PROPERTY_TEMPLATE + ".float"),
new Var[]{new Var("curr", "%.1f", localized(KEY_PROPERTY_VAR_CURR))});
}
}
/* Frame context: values of all properties at the moment of the frame being drawn. */
public class SpeedometerClassicContext extends IndicatorContext {
public final DistanceSensorProperty.SensorContext distance;
public final SpeedScale speedScale;
public final FontColorProperty.FontColorContext text;
public final TextTemplateProperty.TextTemplateContext template;
public final TransparentColorProperty.TransparentColorContext background;
public final SvgProperty.SvgContext bgSvg;
public final SvgProperty.SvgContext delimiterSvg;
public final SvgProperty.SvgContext scaleSvg;
public final SvgProperty.SvgContext arrowSvg;
public final SvgProperty.SvgContext tailSvg;
/* Property contexts are created per frame (createContext(frame)). */
public SpeedometerClassicContext(FrameContext frame) {
super(frame);
distance = mDistance.createContext(frame);
speedScale = mSpeedScale.get(frame);
text = mText.createContext(frame);
template = getTemplate().createContext(frame);
background = mBackground.createContext(frame);
bgSvg = mBgSvg.createContext(frame);
delimiterSvg = mDelimiterSvg.createContext(frame);
scaleSvg = scaleSvgFor(speedScale).createContext(frame);
arrowSvg = mArrowSvg.createContext(frame);
tailSvg = mTailSvg.createContext(frame);
}
/* The SVG with numbers is chosen by the scale ordinal. */
private SvgProperty scaleSvgFor(SpeedScale scale) {
return mScaleSvgs[scale.ordinal()];
}
}
/* Context factory, called for every frame. */
@Override
public IndicatorContext createContext(FrameContext frame) {
return new SpeedometerClassicContext(frame);
}
}SpeedometerIndicator draws a round analog speedometer: a dial with a scale, a needle, a filled sector (the "tail") from zero to the needle, and the speed number in the center. The speed comes from the distance sensor. The scale maximum is chosen from four options: 40, 80, 160 or 320 km/h. A single skin, night, is registered.
Data. DistanceSensorProperty (JSON key Distance) provides ctx.distance. render calls ctx.distance.queryAtom(), the sensor atom for the current frame time. The speed is taken from the atom.speed field without interpolation and divided by 1000.0: the atom stores it in thousandths of km/h. If there is no atom, the speed is treated as zero, but the dial is still drawn.
Settings. defineProperties() has nine properties in this order: Distance, speedScale, font, textTemplate, scaleColor, arrowFillColor, arrowStrokeColor, tailColor, background.
-
speedScaleis an anonymousEnumArrayProperty<SpeedScale>; the initial value isSCALE_160(index 2). -
fontis aFontColorPropertywith an initial size of 120. -
textTemplateis the nestedSpeedometerClassicTextTemplatePropertywith a single variablecurr(format%.0f, template{curr}). -
scaleColor,arrowFillColor,arrowStrokeColor,tailColorare fourColorPropertyinstances. -
backgroundis aTransparentColorProperty: color and transparency (initial values: color204, 204, 204, transparency 80).
The SVG parts (bgSvg, delimiterSvg, four scale*, arrowSvg, tailSvg) are SvgProperty instances that are not part of defineProperties() and are not saved in JSON. Colors are substituted into the SVG through bind(selector, attribute, property): the background color goes into .ring, the scale color into .tick and .number, the needle fill and stroke into .arrow-body, and the tail color into .tail.
In configureDisplay() the scale, four colors and background are moved to the "Appearance" group; the font, template and sensor stay in the main group.
Skin. defineSkins() returns one skin, night: text color 170, 170, 170, background color 17, 17, 17 with transparency 33, scale color 136, 136, 136, needle fill 85, 43, 42, needle stroke 170, 170, 170, tail 51, 68, 85 with alpha 170. The skin does not change the text template.
Drawing. The dial is a square with side min(width, height), centered in the layer. The layer order:
- the background (
bgSvg) with opacity(100 - transparency) / 100; - the tail:
renderTailArcdrawstailSvgthrough aclipof the sector that starts at 270° and spans the needle angle; - the ticks (
delimiterSvg); - the scale numbers (the SVG is chosen by
speedScale.ordinal()); - the needle (
arrowSvg), rotated by the angle; - the number: the template
makeText(speedKmh), the font takingctx.scaleinto account, centering byFontMetrics.
The needle angle is computed as min(speedKmh, scale) * 360 / scale, so a full turn corresponds to the scale maximum.
- A speed above the scale maximum limits only the angle: the needle stays at the maximum, while the center number stays real.
- Without an atom the indicator shows zero speed (the template number for
0) and does not skip drawing, unlike the text indicators. - The center number is always in km/h: the units setting (
MeasurementProperty) is not used in this indicator. - The template method
skinFloat()exists (format%.1f), but it is not connected indefineSkins(), so it is unavailable to the user. - SVG properties are not saved: the dial's look changes only through the colors and the scale.
- The tail is drawn with a sector radius equal to
size, so that the mask is guaranteed to cover the whole dial. - Renaming properties (
speedScale,scaleColorand others) breaks loading of saved projects: loading goes by name.