Skip to content

SlopeTextIndicator

roosit edited this page Oct 16, 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 stored 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.db.SensorDataManager;
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 using a configurable template. */
public class SlopeTextIndicator extends Indicator {

    /* Stable name of the indicator 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();

    {
        /* The "slope" manager: the slope atom whose window contains the given time. */
        mSlope.addManager(
                new SensorDataManager.Builder<>("slope", mSlope.getAtomClass())
                        .table(SlopeAtomProperty.TABLE_NAME)
                        .byTime()
                        .build()
        );
    }

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

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

    /* Units of distance and altitude (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: a 600x300 layer 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 the properties matches the order in JSON. */
    public IProperty[] defineProperties() {
        return new IProperty[]{mSlope, mText, mTextAlign, mUnits, getTemplate()};
    }

    @Override
    /* Alignment and units are placed in 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 a frame: the slope atom, its group, 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. No data - draw nothing. */
        SlopeSensorAtom atom = ctx.slope.queryAtom("slope", ctx.slope.rawTime);
        if (atom == null) {
            return;
        }

        /* The slope group that the current distance falls into. No group - draw nothing. */
        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 - distanceParts, altitudes - 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 percent of the group (stored x100 in the group). */
        double pc = Angle.slopePercentToPercent(group.slopePercent);

        /*
         * The order of the values strictly matches the order of the variables in defineVars().
         * The up and down variables 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 smoothing. */
        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);

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

    /* The 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 text template of the indicator: 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. Order = the order of the 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"))
            };
        }

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

        /* 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
    /* Factory of the frame context. */
    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 (JSON name slopeText, interface title "Slope Text") outputs text about the current slope section using a template: the section type (uphill, downhill, flat), the slope percent, the distance covered inside the section, its length, its elevation change and the current elevation, the climb and the descent.

How it works

Data

  • The sensor is SlopeAtomProperty (JSON key Slope, "Slope" in the interface). The current atom is requested by the slope manager (byTime): ctx.slope.queryAtom("slope", ctx.slope.rawTime); it is interpolated to the moment of the frame. The sensor is ctx.slope.sensorId.
  • A slope section is a row of the plugin table slope_groups (see SlopeGroupAtom). The queryGroupForAtom query looks for the group of the sensor where distance <= atom.distance < distance + distanceDelta. The groups are built by VelitaskPlagin.onSourceImported through SlopeDetector when a source is imported.
  • From the atom these 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 with ctx.units.distanceParts(mm), altitudes with ctx.units.altitudeParts(mm); both functions return a pair "value, unit label". With the measurement system "From global settings" the distance unit is chosen automatically to fit the magnitude, and the altitude is shown in meters or feet according to the global setting.

Settings

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

In configureDisplay only textAlign and measurement are placed in 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 formats of the variables stay default):

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

Template variables - the order strictly matches the order of the makeText arguments:

Variable Format Meaning
type %s Section type as a word: "Uphill", "Downhill", "Flat".
typec %s ↑, ↓ or an empty string for flat.
pc %.1f group.slopePercent / 100 - the slope percent of the group, signed.
curr %.3f Distance covered from the start of the group to the current point.
currUnit %s Unit label for curr.
length %.2f Length of the group (distanceDelta).
lengthUnit %s Unit label for length.
height %.0f Elevation change of the group (elevationDelta), signed.
heightUnit %s Unit label for height.
ele %.0f Elevation of the current point.
eleUnit %s Unit label of the elevation.
eleCurr %.1f Absolute value of the elevation change from the start of the group to the current point.
up %.0f Accumulated climb of the atom (eleUp).
down %.0f Accumulated descent of the atom (abs(eleDown)), without the 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. Smoothing 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) - as one line, without wrapping.

Features and limitations

  • 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 are not supported by the template; long text may go beyond the layer bounds.
  • The up and down variables are taken from the accumulated values of the atom, not from 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 labels currUnit and lengthUnit may differ.
  • The sign of pc and height. On a downhill 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