Skip to content

VelitaskPlagin

roosit edited this page Nov 15, 2026 · 5 revisions

VelitaskPlagin

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

package com.velitask.plugin.official;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Supplier;

import com.velitask.plugin.official.previews.AudioPreviewGenerator;
import com.velitask.plugin.official.previews.GeoPreviewGenerator;
import com.velitask.plugin.official.previews.ImagePreviewGenerator;
import com.velitask.plugin.official.previews.VideoPreviewGenerator;
import com.velitask.plugin.official.processing.BuiltinScenarios;
import com.velitask.plugin.official.slope.SlopeDetector;
import com.velitask.plugin.official.slope.SlopeGroup;
import com.velitask.plugin.official.slope.SlopeGroupAtom;
import com.velitask.sdk.IFileSource;
import com.velitask.sdk.IIndicator;
import com.velitask.sdk.IPlagin;
import com.velitask.sdk.SensorType;
import com.velitask.sdk.data.ISensor;
import com.velitask.sdk.data.SlopeSensorAtom;
import com.velitask.sdk.db.PluginDatabase;
import com.velitask.sdk.preview.IPreviewGeneratorProvider;
import com.velitask.sdk.preview.PreviewGenerator;
import com.velitask.sdk.scenario.IImportStep;
import com.velitask.sdk.scenario.IScenarioProvider;
import com.velitask.sdk.scenario.ImportPlan;

/*
 * Entry point of the plugin-official plugin: registers 38 built-in indicators,
 * import steps and plans, preview generators and, when a source is imported, computes
 * slope groups for the plugin database.
 */
public class VelitaskPlagin implements IPlagin, IScenarioProvider, IPreviewGeneratorProvider {

    /* The UID is made a constant so that other plugin classes can use it too. */
    public static final String UID = "com.velitask.plagin.official";

    /*
     * Stable plugin UID: the plugin is identified by it in projects, the registry,
     * DB metadata and localization keys. It must not be changed.
     */
    @Override
    public String getUID() {
        return UID;
    }

    /* Plugin version for the log and the plugin panel; it has nothing to do with the DB schema version. */
    @Override
    public String getVersion() {
        return "1.1.0";
    }

    /*
     * Version of the plugin DB schema. A new database runs only create.sql (a snapshot of this
     * version), an existing one is brought up to date by the chain upgrade-(old+1)..getDbVersion().
     */
    @Override
    public int getDbVersion() {
        return 1;
    }

    /* Additional locale: the Russian bundle is loaded even with an English interface. */
    @Override
    public String[] defineAdditionLocales() {
        return new String[]{"ru"};
    }

    /*
     * All 38 indicators in the order of display in the selection list: media, slider, sensor
     * data, charts, text ones, map and compass, then figures.
     */
    @Override
    public IIndicator[] defineIndicators() {
        return new IIndicator[]{
            new VideoIndicator(),
            new AudioIndicator(),
            new ImageIndicator(),
            new SliderIndicator(),
            new SpeedometerIndicator(),
            new DistanceTextIndicator(),
            new SlopeChartIndicator(),
            new SpeedChartIndicator(),
            new SlopeTextIndicator(),
            new SlopeSpeedIndicator(),
            new TemperatureTextIndicator(),
            new HeartTextIndicator(),
            new PowerTextIndicator(),
            new BalanceTextIndicator(),
            new GearsTextIndicator(),
            new GradeTextIndicator(),
            new GForceIndicator(),
            new GForceTextIndicator(),
            new AccelerometerTextIndicator(),
            new GyroscopeTextIndicator(),
            new OrientationTextIndicator(),
            new AttitudeTextIndicator(),
            new PedalEfficiencyTextIndicator(),
            new PedalSmoothnessTextIndicator(),
            new PedalDynamicsTextIndicator(),
            new LapTextIndicator(),
            new SpeedTextIndicator(),
            new CadenceTextIndicator(),
            new TimeTextIndicator(),
            new SubtitlesIndicator(),
            new TextIndicator(),
            new FileExtensionIndicator(),
            new LatLonTextIndicator(),
            new GeoMapIndicator(),
            new CompassIndicator(),
            new RectangleIndicator(),
            new EllipseIndicator(),
            new LineIndicator()
        };
    }

    /* Plugin import steps (pauses, filters, compression): the list is assembled by BuiltinScenarios. */
    @Override
    public List<Supplier<? extends IImportStep<?>>> defineImportSteps() {
        return BuiltinScenarios.steps();
    }

    /* Import plans: its own set of steps for each kind of source. */
    @Override
    public List<ImportPlan> defineImportPlans() {
        return BuiltinScenarios.plans();
    }

    /* Preview generators: video, images, audio and geo track. */
    @Override
    public List<PreviewGenerator> definePreviewGenerators() {
        return List.of(
                new VideoPreviewGenerator(),
                new ImagePreviewGenerator(),
                new AudioPreviewGenerator(),
                new GeoPreviewGenerator());
    }

    /*
     * Hook after a source import. If it has a slope sensor, builds
     * slope groups (climb / descent / flat) and saves them into the plugin tables.
     */
    @Override
    public void onSourceImported(IFileSource source, PluginDatabase db) {
        if (source == null || db == null) {
            return;
        }
        /* Without a slope sensor the analytics is not needed. */
        ISensor slopeSensor = source.getSensorList().getBySensorType(SensorType.SLOPE);
        if (slopeSensor == null) {
            return;
        }

        /*
         * Idempotence: before recalculation the old groups and links
         * of this sensor_id are deleted.
         */
        db.execute(
                "DELETE FROM ${table:slope_atom_groups}"
                + " WHERE group_id IN ("
                + "   SELECT id FROM ${table:slope_groups} WHERE sensor_id = ?"
                + " )",
                slopeSensor.getId()
        );
        db.execute(
                "DELETE FROM ${table:slope_groups} WHERE sensor_id = ?",
                slopeSensor.getId()
        );

        /*
         * All slope atoms of the sensor by ascending timeRaw. Direct SQL is needed:
         * the fields slopeType, slopePercent and segmentStart are not available through the standard SDK wrappers.
         */
        List<SlopeSensorAtom> atoms = db.queryList(
                "SELECT data_id AS id, measureIndex AS \"index\","
                + "       timeRaw, duration,"
                + "       distance, distanceDelta, distanceSlope,"
                + "       elevation, elevationDelta,"
                + "       eleUp, eleUpDelta, eleDown, eleDownDelta,"
                + "       slopeType, slopePercent, segmentStart"
                + " FROM sensors_slope_data"
                + " WHERE sensor_id = ?"
                + " ORDER BY timeRaw",
                SlopeSensorAtom.class,
                slopeSensor.getId()
        );
        if (atoms == null || atoms.isEmpty()) {
            return;
        }

        /* SlopeDetector glues a sequence of atoms into groups by slope type. */
        SlopeDetector detector = new SlopeDetector();
        for (SlopeSensorAtom a : atoms) {
            detector.add(a);
        }

        /*
         * For each group: the summary record SlopeGroupAtom -> INSERT into slope_groups
         * -> reading the group id -> accumulating atom_id / group_id pairs.
         */
        List<SlopeGroup> groups = detector.getGroups();
        int measureIndex = 0;
        List<Object[]> atomGroupRows = new ArrayList<>();
        for (SlopeGroup group : groups) {
            SlopeGroupAtom row = group.buildAtom(slopeSensor.getId(), measureIndex++);
            db.execute(
                    "INSERT INTO ${table:slope_groups}"
                    + " (sensor_id, measureIndex, timeRaw, duration,"
                    + "  distance, distanceDelta, elevation, elevationDelta,"
                    + "  eleUp, eleDown, slopeType, slopePercent)"
                    + " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
                    row.sensor_id, row.measureIndex, row.timeRaw, row.duration,
                    row.distance, row.distanceDelta, row.elevation, row.elevationDelta,
                    row.eleUp, row.eleDown, row.slopeType, row.slopePercent
            );
            Long groupId = db.queryValue(
                    "SELECT id FROM ${table:slope_groups}"
                    + " WHERE sensor_id = ? AND measureIndex = ?",
                    Long.class,
                    row.sensor_id, row.measureIndex
            );
            if (groupId == null) {
                continue;
            }
            group.setId(groupId);
            for (SlopeSensorAtom a : group.getList()) {
                atomGroupRows.add(new Object[]{a.id, groupId});
            }
        }

        /* All atom -> group links in one batchInsert: on long tracks this is faster than inserting row by row. */
        if (!atomGroupRows.isEmpty()) {
            db.batchInsert(
                    "INSERT INTO ${table:slope_atom_groups} (atom_id, group_id) VALUES (?, ?)",
                    atomGroupRows
            );
        }
    }

}

Purpose

VelitaskPlagin is the entry point of the plugin-official plugin. It implements the IPlagin contract: it sets the UID and the version, declares the Russian locale, registers 38 built-in indicators, the import steps and plans, the preview generators and, when a source with a slope sensor is imported, computes slope groups (climbs, descents, flat sections) for the plugin's own database.

Every registered indicator has its own pages: the code walkthrough is in the table of contents Code, the description and the settings are in the overview Indicators.

How it works

Registration and identification. getUID() returns the stable identifier com.velitask.plagin.official: it is written in saved projects, the plugin registry, the DB metadata and the localization keys, so it must not be changed. getVersion() returns 1.1.0: this is a string for the log and the plugin panel, it is not connected with the DB schema version. defineIndicators() is called once when the plugin is loaded and returns 38 indicators; the order of the array is kept in the selection list. The UID constant is public so that other plugin classes can refer to the identifier.

Import scenarios. The class additionally implements IScenarioProvider. defineImportSteps() returns the factories of 26 steps (pauses, filters, data compression), defineImportPlans() returns 7 import plans: GPX, FIT, TCX, TMG, GoPro, DJI and DJI SRT; both lists are assembled by BuiltinScenarios. A plan sets for each kind of source which steps are applied to each sensor and with which values. The steps and plans appeared in version 1.1.0.

Previews. The class implements IPreviewGeneratorProvider: definePreviewGenerators() returns four thumbnail generators: VideoPreviewGenerator, ImagePreviewGenerator, AudioPreviewGenerator and GeoPreviewGenerator. The former thumbnail templates thumbnail-*.vttp were removed from the resources.

Localization. defineAdditionLocales() returns "ru": the Russian strings are loaded regardless of the interface language. The string files lie in the localization/ folder of the plugin resources, the application finds them by this path, and a separate manifest attribute is not needed (more in Resources).

Plugin DB. getDbVersion() returns 1. The method getMinSupportedDbVersion() is not overridden, the default value 1 applies (all saved versions are supported). The file sql/setup/create.sql is a full snapshot of the schema of the current version. If there is no saved version for the plugin in the project, only create.sql is run, and the version is recorded as equal to getDbVersion(). If an older version is saved, upgrade-(old+1) ... upgrade-getDbVersion() are run in order, each step in its own transaction; there are no such files now. The DB schema has not changed since version 1.0.2: getDbVersion() is still 1. A released upgrade-N.sql is not edited: any schema change gets a new number. If the database could not be brought to the needed version, the plugin is disconnected from the project, the project opens without it, an entry goes to the application log, and the attempt is repeated at the next opening. The plugin tables: slope_groups (aggregates of sections by sensor_id) and slope_atom_groups (the atom_id to group_id link).

Slope analytics on import. The hook onSourceImported(source, db) is called after the import of every source. If there is no slope sensor, the method returns at once. Otherwise it:

  1. deletes the former groups and links of this sensor_id (a repeated import gives the same result);
  2. reads the slope atoms from sensors_slope_data by direct SQL, because the fields slopeType, slopePercent and segmentStart are needed (a sign of the start of a recording segment: SlopeDetector uses it not to glue a group across a pause);
  3. runs the atoms through SlopeDetector, which gathers them into groups;
  4. for each group builds a summary record SlopeGroupAtom (the method buildAtom of the class SlopeGroup), inserts it into slope_groups and reads the assigned id;
  5. writes the atom to group links into slope_atom_groups with one batchInsert.

Features and limitations

  • The processing is idempotent by sensor_id: the classification algorithm is deterministic, a repeated import of the same source overwrites the groups with the same result.
  • If the source has no slope sensor or no atoms, onSourceImported does nothing.
  • The hook runs synchronously, without a progress report; on long tracks the insertion time is noticeable.
  • batchInsert for the atom to group links is important: row-by-row INSERT on thousands of atoms is significantly slower.
  • The SQL uses the substitution ${table:slope_groups}: the runtime replaces it with the table name with the plugin prefix, which excludes collisions with other plugins.
  • The helper classes SlopeDetector, SlopeGroup and SlopeGroupAtom have their own pages: SlopeDetector, SlopeGroup, SlopeGroupAtom. The use of groups by indicators is described in SlopeChartIndicator, SlopeTextIndicator and SlopeSpeedIndicator.

Clone this wiki locally