Skip to content

SlopeTextIndicator

roosit edited this page Nov 15, 2026 · 5 revisions

SlopeTextIndicator

Up | Previous | Next | Русский

Full source with short explanations

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 SlopeTextIndicator.java: the production code stays clean, and the explanations live in the wiki.

package com.velitask.plugin.official;

import com.velitask.plugin.official.slope.SlopeGroupAtom;
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.SlopeSensorAtom;
import com.velitask.sdk.db.PluginDatabase;
import com.velitask.sdk.properties.DisplayConfig;
import com.velitask.sdk.properties.FontColorProperty;
import com.velitask.sdk.properties.IProperty;
import com.velitask.sdk.properties.PropertyGroup;
import com.velitask.sdk.properties.SlopeAtomProperty;
import com.velitask.sdk.properties.TextAlignProperty;
import com.velitask.sdk.properties.TextTemplateProperty;
import com.velitask.sdk.properties.measurement.MeasurementProperty;
import com.velitask.units.UnitKind;
import com.velitask.units.angle.Angle;
import com.velitask.units.format.UnitValue;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import org.abricos.core.state.maket.HorizontalAlign;
import org.abricos.core.state.maket.Maket;
import org.abricos.core.state.maket.VerticalAlign;

/* The "Slope Text" indicator: text about the current slope section by a configurable template. */
public class SlopeTextIndicator extends Indicator {

    /* Stable indicator name in the layer JSON. It must not be changed without a migration. */
    public static final String NAME = "slopeText";

    /* Prefix of the localization keys: Plugin.Indicator.slopeText. */
    private static final String KEY = _KEY + "." + NAME;

    /* Slope sensor (JSON "Slope"). */
    private final SlopeAtomProperty mSlope = new SlopeAtomProperty();

    /* Font and color of the text (JSON "font"). */
    private final FontColorProperty mText = new FontColorProperty();

    /* Text alignment in the layer (JSON "textAlign"), centered by default. */
    private final TextAlignProperty mTextAlign = new TextAlignProperty();

    /* Distance and elevation units (JSON "measurement"). */
    private final MeasurementProperty mUnits = new MeasurementProperty(
            UnitKind.DISTANCE, UnitKind.ALTITUDE
    );

    /* Text template (JSON "textTemplate"). */
    private final SlopeTextTemplateProperty mTemplate = new SlopeTextTemplateProperty();

    /* The template as the base TextTemplateProperty. */
    private TextTemplateProperty getTemplate() {
        return mTemplate;
    }

    @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 maket: layer 600x300 at the top left corner, margins 300 at the top and 100 on the right. */
    public void defineMaket(Maket maket) {
        maket.setVertical(VerticalAlign.TOP);
        maket.setHorizontal(HorizontalAlign.LEFT);
        maket.setLayerMargin(null, 300d, 100d, null);
        maket.setLayerSize(600d, 300d);
    }

    @Override
    /* The order of properties matches the order in JSON. */
    public IProperty[] defineProperties() {
        return new IProperty[]{mSlope, mText, mTextAlign, mUnits, getTemplate()};
    }

    @Override
    /* The alignment and the units are moved into the "Appearance" group. */
    public void configureDisplay(DisplayConfig config) {
        config.set(mTextAlign, PropertyGroup.APPEARANCE);
        config.set(mUnits, PropertyGroup.APPEARANCE);
    }

    @Override
    /* The "Short" and "Detailed" skins change only the text template. */
    public IndicatorSkin[] defineSkins() {
        return new IndicatorSkin[]{
            IndicatorSkin.builder("short", localized(KEY + ".skin.short"))
            .set(mTemplate.skinShort())
            .build(),
            IndicatorSkin.builder("detailed", localized(KEY + ".skin.detailed"))
            .set(mTemplate.skinDetailed())
            .build()
        };
    }

    @Override
    /* Drawing the frame: the slope atom, its group, the values in the selected units, the text. */
    public void render(IndicatorContext indicatorContext) {
        SlopeTextContext ctx = (SlopeTextContext) indicatorContext;
        Graphics2D g = ctx.graphics;

        /* The slope atom for the current moment; in a recording pause, the last atom before the pause. No data: nothing is drawn. */
        SlopeSensorAtom atom = ctx.slope.queryAtomOrBefore();
        if (atom == null) {
            return;
        }

        /* The slope group that the current distance falls into. No group: nothing is drawn. */
        SlopeGroupAtom group = queryGroupForAtom(ctx.db, ctx.slope.sensorId, atom);
        if (group == null) {
            return;
        }

        /* Covered inside the group: from the start of the group to the current point (in mm). */
        long distanceSlope = atom.distance - group.distance;
        long elevationSlope = atom.elevation - group.elevation;

        /*
         * Values for the template converted to the selected units:
         * distances through distanceParts, elevations through altitudeParts.
         */
        UnitValue currV = ctx.units.distanceParts(distanceSlope);
        UnitValue lengthV = ctx.units.distanceParts(group.distanceDelta);
        UnitValue heightV = ctx.units.altitudeParts(group.elevationDelta);
        UnitValue eleV = ctx.units.altitudeParts(atom.elevation);
        UnitValue eleCurrV = ctx.units.altitudeParts(Math.abs(elevationSlope));
        UnitValue upV = ctx.units.altitudeParts(atom.eleUp);
        UnitValue downV = ctx.units.altitudeParts(Math.abs(atom.eleDown));

        /* Section type: as a word and as an arrow. */
        String type = slopeTypeToString(group.slopeType);
        String typec = slopeTypeCToString(group.slopeType);
        /* Slope percentage of the group (stored x100 in the group). */
        double pc = Angle.slopePercentToPercent(group.slopePercent);

        /*
         * The order of values strictly matches the order of variables in defineVars().
         * The variables up and down are taken from the accumulated values of the atom.
         */
        String text = ctx.template.makeText(
                type, typec, pc,
                currV.value(), currV.unit(),
                lengthV.value(), lengthV.unit(),
                heightV.value(), heightV.unit(),
                eleV.value(), eleV.unit(),
                eleCurrV.value(),
                upV.value(),
                downV.value()
        );

        /* Text antialiasing. */
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                RenderingHints.VALUE_ANTIALIAS_ON);

        /* The font is scaled together with the frame. */
        Font font = ctx.text.toFont(ctx.scale);
        g.setFont(font);
        g.setColor(ctx.text.color.value);

        /* Text output taking the alignment into account. */
        ctx.textAlign.drawText(g, text, ctx.width, ctx.height);
    }

    /* One group whose distance range [distance, distance + distanceDelta) contains the distance of the atom. */
    private static SlopeGroupAtom queryGroupForAtom(PluginDatabase db, long sensorId, SlopeSensorAtom atom) {
        if (db == null) {
            return null;
        }
        return db.query(
                "SELECT * FROM ${table:slope_groups}"
                + " WHERE sensor_id = ?"
                + " AND distance <= ?"
                + " AND ? < (distance + distanceDelta)"
                + " LIMIT 1",
                SlopeGroupAtom.class,
                sensorId, atom.distance, atom.distance
        );
    }

    /* Slope type as a word: "Uphill", "Downhill", "Flat" (localized). */
    private String slopeTypeToString(int type) {
        return switch (type) {
            case SlopeSensorAtom.TYPE_UP ->
                localized(KEY + ".type.up");
            case SlopeSensorAtom.TYPE_DOWN ->
                localized(KEY + ".type.down");
            default ->
                localized(KEY + ".type.plain");
        };
    }

    /* Slope type as an arrow; an empty string for flat. */
    private String slopeTypeCToString(int type) {
        return switch (type) {
            case SlopeSensorAtom.TYPE_UP ->
                "↑";
            case SlopeSensorAtom.TYPE_DOWN ->
                "↓";
            default ->
                "";
        };
    }

    /* The indicator text template: the default value and the list of variables with formats. */
    static class SlopeTextTemplateProperty 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";

        @Override
        /* The default template is taken from the localization. */
        protected String defineTemplate() {
            return localized(KEY_PROPERTY_TEMPLATE + ".default");
        }

        @Override
        /* Template variables and their default formats. The order = the order of makeText arguments. */
        protected Var[] defineVars() {
            return new Var[]{
                new Var("type", "%s", localized(KEY_PROPERTY_VAR + ".type")),
                new Var("typec", "%s", localized(KEY_PROPERTY_VAR + ".typec")),
                new Var("pc", "%.1f", localized(KEY_PROPERTY_VAR + ".pc")),
                new Var("curr", "%.3f", localized(KEY_PROPERTY_VAR + ".curr")),
                new Var("currUnit", "%s", localized(KEY_PROPERTY_VAR + ".currUnit")),
                new Var("length", "%.2f", localized(KEY_PROPERTY_VAR + ".length")),
                new Var("lengthUnit", "%s", localized(KEY_PROPERTY_VAR + ".lengthUnit")),
                new Var("height", "%.0f", localized(KEY_PROPERTY_VAR + ".height")),
                new Var("heightUnit", "%s", localized(KEY_PROPERTY_VAR + ".heightUnit")),
                new Var("ele", "%.0f", localized(KEY_PROPERTY_VAR + ".ele")),
                new Var("eleUnit", "%s", localized(KEY_PROPERTY_VAR + ".eleUnit")),
                new Var("eleCurr", "%.1f", localized(KEY_PROPERTY_VAR + ".eleCurr")),
                new Var("up", "%.0f", localized(KEY_PROPERTY_VAR + ".up")),
                new Var("down", "%.0f", localized(KEY_PROPERTY_VAR + ".down"))
            };
        }

        /* The template of the "Short" skin. */
        public IndicatorSkinTransfer skinShort() {
            return skin(localized(KEY_PROPERTY_TEMPLATE + ".short"));
        }

        /* The template of the "Detailed" skin. */
        public IndicatorSkinTransfer skinDetailed() {
            return skin(localized(KEY_PROPERTY_TEMPLATE + ".detailed"));
        }
    }

    /* Property values for the current frame. Created in createContext(frame). */
    public class SlopeTextContext extends IndicatorContext {

        public final SlopeAtomProperty.SensorContext slope;
        public final FontColorProperty.FontColorContext text;
        public final TextAlignProperty.TextAlignContext textAlign;
        public final TextTemplateProperty.TextTemplateContext template;
        public final MeasurementProperty.Context units;

        public SlopeTextContext(FrameContext frame) {
            super(frame);
            slope = mSlope.createContext(frame);
            text = mText.createContext(frame);
            textAlign = mTextAlign.createContext(frame);
            template = getTemplate().createContext(frame);
            units = mUnits.createContext(frame);
        }
    }

    @Override
    /* Frame context factory. */
    public IndicatorContext createContext(FrameContext frame) {
        return new SlopeTextContext(frame);
    }
}

The save format of the indicator is described on the page SlopeTextIndicator JSON. The user guide: Slope Text.

Purpose

SlopeTextIndicator (the JSON name is slopeText, the interface title is "Slope Text") outputs text about the current slope section by a template: the section type (climb, descent, flat), the slope percentage, the distance covered inside the section, its length, the elevation difference and the current elevation, the gain and the loss.

How it works

Data

  • The sensor is SlopeAtomProperty (JSON key Slope, "Slope" in the interface). The current atom is requested with the standard SDK method ctx.slope.queryAtomOrBefore(): the atom that covers the frame time, and in a recording pause the last atom before the pause (the indicator no longer registers its own slope data manager). Outside the recording there is no atom. The sensor is ctx.slope.sensorId.
  • The slope section is a row of the plugin table slope_groups (see SlopeGroupAtom). The query queryGroupForAtom looks for a group of the sensor with distance <= atom.distance < distance + distanceDelta. The groups are built by VelitaskPlagin.onSourceImported through SlopeDetector when a source is imported.
  • From the atom are taken: distance, elevation, eleUp, eleDown. From the group: distance, elevation, distanceDelta, elevationDelta, slopeType, slopePercent.
  • Units: all lengths are stored in millimeters. Distances are converted by ctx.units.distanceParts(mm), elevations by ctx.units.altitudeParts(mm); both functions return a "value, unit caption" pair. With the measurement system "from global settings" the distance unit is chosen automatically for the magnitude, and the elevation is output in meters or feet by the global setting.

Settings

JSON key SDK type Default Role
Slope SlopeAtomProperty not selected The slope source and sensor.
font FontColorProperty Dialog, plain, 48, white The font and the color of the text.
textAlign TextAlignProperty 4 (centered) The position of the text in the layer (0..8).
measurement MeasurementProperty (distance, altitude) system 0 (from global settings) The distance and elevation units.
textTemplate SlopeTextTemplateProperty the localized template The text and the formats of the variables.

In configureDisplay only textAlign and measurement are moved into the "Appearance" group.

The default template is taken from the localization key textTemplate.template.default; in the English locale it is {type} {pc}% ({curr}{currUnit} / {length}{lengthUnit}).

The skins change only the text template (the variable formats stay default):

Skin Template (English locale)
"Short" (short) {typec} {pc}%
"Detailed" (detailed) {type} {pc}% ele:{ele}{eleUnit} up:{up}{eleUnit} down:{down}{eleUnit}

The template variables: the order strictly matches the order of the makeText arguments:

Variable Format Value
type %s The section type as a word: "Uphill", "Downhill", "Flat".
typec %s ↑, ↓ or an empty string for flat.
pc %.1f group.slopePercent / 100: the signed slope percentage of the group.
curr %.3f The distance covered from the start of the group to the current point.
currUnit %s The unit caption for curr.
length %.2f The length of the group (distanceDelta).
lengthUnit %s The unit caption for length.
height %.0f The elevation difference of the group (elevationDelta), signed.
heightUnit %s The unit caption for height.
ele %.0f The elevation of the current point.
eleUnit %s The elevation unit caption.
eleCurr %.1f The absolute value of the elevation change from the start of the group to the current point.
up %.0f The accumulated elevation gain of the atom (eleUp).
down %.0f The accumulated elevation loss of the atom (abs(eleDown)), without a minus sign.

Drawing

  1. No atom or no group: the frame stays empty.
  2. The values are collected and passed to ctx.template.makeText(...).
  3. Antialiasing is turned on, the font (ctx.text.toFont(ctx.scale)) and the color (ctx.text.color.value) are set.
  4. The text is output with ctx.textAlign.drawText(g, text, ctx.width, ctx.height): on one line, without wrapping.

Features and limitations

  • Pauses. In a recording pause (a stop, a device auto-pause) the atom is the last one before the pause, and the text stays on the values before it. Slope groups are not glued across a pause (see SlopeDetector), so a new group starts after the pause.
  • Dependence on groups. If there are no records in slope_groups for the sensor (the source was imported before the plugin appeared or without a slope sensor), the indicator draws nothing.
  • Single-line text. Line breaks by the template are not supported; a long text can go beyond the bounds of the layer.
  • The variables up and down are taken from the accumulated values of the atom, not of the group, and have no separate unit variable: the detailed skin uses {eleUnit}.
  • Different units for curr and length. The unit of each value is chosen separately, so the captions currUnit and lengthUnit can differ.
  • The sign of pc and height. On a descent both values are negative; eleCurr and down are always positive.
  • Changing the skin overwrites the text template; a custom template entered earlier is lost.

Clone this wiki locally