
- canvasModel.ts ``` export enum CircleDrawingMethod { CLASSIC = ‘By 2 points’, }
export interface DrawData { enabled: boolean; shapeType?: string; rectDrawingMethod?: RectDrawingMethod; circleDrawingMethod?: CircleDrawingMethod; cuboidDrawingMethod?: CuboidDrawingMethod; numberOfPoints?: number; initialState?: any; crosshair?: boolean; redraw?: number; }
public draw(drawData: DrawData): void {
if (![Mode.IDLE, Mode.DRAW].includes(this.data.mode)) {
throw Error(Canvas is busy. Action: ${this.data.mode});
}
if (drawData.enabled) {if (this.data.drawData.enabled) {throw new Error('Drawing has been already started');} else if (!drawData.shapeType && !drawData.initialState) {throw new Error('A shape type is not specified');} else if (typeof drawData.numberOfPoints !== 'undefined') {if (drawData.shapeType === 'polygon' && drawData.numberOfPoints < 3) {throw new Error('A polygon consists of at least 3 points');} else if (drawData.shapeType === 'polyline' && drawData.numberOfPoints < 2) {throw new Error('A polyline consists of at least 2 points');}}}if (typeof drawData.redraw === 'number') {const clientID = drawData.redraw;const [state] = this.data.objects.filter((_state: any): boolean => _state.clientID === clientID);if (state) {this.data.drawData = { ...drawData };this.data.drawData.shapeType = state.shapeType;} else {return;}} else {this.data.drawData = { ...drawData };if (this.data.drawData.initialState) {this.data.drawData.shapeType = this.data.drawData.initialState.shapeType;}}// install default values for drawing methodif (drawData.enabled) {console.log('drawData.shapeType:', drawData.shapeType);if (drawData.shapeType === 'rectangle') {this.data.drawData.rectDrawingMethod = drawData.rectDrawingMethod || RectDrawingMethod.CLASSIC;}// 添加circleif (drawData.shapeType === 'circle') {this.data.drawData.circleDrawingMethod = drawData.circleDrawingMethod || CircleDrawingMethod.CLASSIC;}if (drawData.shapeType === 'cuboid') {this.data.drawData.cuboidDrawingMethod = drawData.cuboidDrawingMethod || CuboidDrawingMethod.CLASSIC;}}console.log('==========');this.notify(UpdateReasons.DRAW);}
2. canvasView.ts
private redrawBitmap(): void {
const width = +this.background.style.width.slice(0, -2);
const height = +this.background.style.height.slice(0, -2);
this.bitmap.setAttribute(‘width’, ${width}px);
this.bitmap.setAttribute(‘height’, ${height}px);
const states = this.controller.objects;
const ctx = this.bitmap.getContext('2d');if (ctx) {ctx.fillStyle = 'black';ctx.fillRect(0, 0, width, height);for (const state of states) {if (state.hidden || state.outside) continue;ctx.fillStyle = 'white';if (['rectangle', 'circle', 'polygon', 'cuboid'].includes(state.shapeType)) {let points = [];if (state.shapeType === 'rectangle') {points = [state.points[0], // xtlstate.points[1], // ytlstate.points[2], // xbrstate.points[1], // ytlstate.points[2], // xbrstate.points[3], // ybrstate.points[0], // xtlstate.points[3], // ybr];} else if (state.shapeType === 'circle') {points = [state.points[0], // xtlstate.points[1], // ytlstate.points[2], // xbrstate.points[1], // ytlstate.points[2], // xbrstate.points[3], // ybrstate.points[0], // xtlstate.points[3], // ybr];} else if (state.shapeType === 'cuboid') {points = [state.points[0],state.points[1],state.points[4],state.points[5],state.points[8],state.points[9],state.points[12],state.points[13],];} else {points = [...state.points];}ctx.beginPath();ctx.moveTo(points[0], points[1]);for (let i = 0; i < points.length; i += 2) {ctx.lineTo(points[i], points[i + 1]);}ctx.closePath();ctx.fill();}if (state.shapeType === 'cuboid') {for (let i = 0; i < 5; i++) {const points = [state.points[(0 + i * 4) % 16],state.points[(1 + i * 4) % 16],state.points[(2 + i * 4) % 16],state.points[(3 + i * 4) % 16],state.points[(6 + i * 4) % 16],state.points[(7 + i * 4) % 16],state.points[(4 + i * 4) % 16],state.points[(5 + i * 4) % 16],];ctx.beginPath();ctx.moveTo(points[0], points[1]);for (let j = 0; j < points.length; j += 2) {ctx.lineTo(points[j], points[j + 1]);}ctx.closePath();ctx.fill();}}}}}private updateObjects(states: any[]): void {for (const state of states) {const { clientID } = state;const drawnState = this.drawnStates[clientID];const shape = this.svgShapes[state.clientID];const text = this.svgTexts[state.clientID];const isInvisible = state.hidden || state.outside || this.isServiceHidden(state.clientID);if (drawnState.hidden !== state.hidden || drawnState.outside !== state.outside) {if (isInvisible) {(state.shapeType === 'points' ? shape.remember('_selectHandler').nested : shape).addClass('cvat_canvas_hidden',);if (text) {text.addClass('cvat_canvas_hidden');}} else {(state.shapeType === 'points' ? shape.remember('_selectHandler').nested : shape).removeClass('cvat_canvas_hidden',);if (text) {text.removeClass('cvat_canvas_hidden');this.updateTextPosition(text, shape);}}}if (drawnState.zOrder !== state.zOrder) {if (state.shapeType === 'points') {shape.remember('_selectHandler').nested.attr('data-z-order', state.zOrder);} else {shape.attr('data-z-order', state.zOrder);}}if (drawnState.occluded !== state.occluded) {if (state.occluded) {shape.addClass('cvat_canvas_shape_occluded');} else {shape.removeClass('cvat_canvas_shape_occluded');}}if (drawnState.pinned !== state.pinned && this.activeElement.clientID !== null) {const activeElement = { ...this.activeElement };this.deactivate();this.activate(activeElement);}if (state.points.length !== drawnState.points.length ||state.points.some((p: number, id: number): boolean => p !== drawnState.points[id])) {const translatedPoints: number[] = this.translateToCanvas(state.points);if (state.shapeType === 'rectangle') {const [xtl, ytl, xbr, ybr] = translatedPoints;shape.attr({x: xtl,y: ytl,width: xbr - xtl,height: ybr - ytl,});} else if (state.shapeType === 'circle') {const [xtl, ytl, xbr, ybr] = translatedPoints;shape.attr({x: xtl,y: ytl,width: xbr - xtl,height: ybr - ytl,});} else {const stringified = this.stringifyToCanvas(translatedPoints);if (state.shapeType !== 'cuboid') {(shape as any).clear();}shape.attr('points', stringified);if (state.shapeType === 'points' && !isInvisible) {this.selectize(false, shape);this.setupPoints(shape as SVG.PolyLine, state);}}}const stateDescriptions = state.descriptions;const drawnStateDescriptions = drawnState.descriptions;if (drawnState.label.id !== state.label.id ||drawnStateDescriptions.length !== stateDescriptions.length ||drawnStateDescriptions.some((desc: string, id: number): boolean => desc !== stateDescriptions[id])) {// need to remove created text and create it againif (text) {text.remove();this.svgTexts[state.clientID] = this.addText(state);}} else {// check if there are updates in attributesfor (const attrID of Object.keys(state.attributes)) {if (state.attributes[attrID] !== drawnState.attributes[+attrID]) {if (text) {const [span] = text.node.querySelectorAll<SVGTSpanElement>(`[attrID="${attrID}"]`);if (span && span.textContent) {const prefix = span.textContent.split(':').slice(0, -1).join(':');span.textContent = `${prefix}: ${state.attributes[attrID]}`;}}}}}this.saveState(state);}}private addObjects(states: any[]): void {console.log('addObjects');const { displayAllText } = this.configuration;for (const state of states) {const points: number[] = state.points as number[];const translatedPoints: number[] = this.translateToCanvas(points);console.log('state.shapeType:', state.shapeType);// TODO: Use enums after typification cvat-coreif (state.shapeType === 'rectangle') {this.svgShapes[state.clientID] = this.addRect(translatedPoints, state);} else if (state.shapeType === 'circle') {this.svgShapes[state.clientID] = this.addCircle(translatedPoints, state);} else {const stringified = this.stringifyToCanvas(translatedPoints);if (state.shapeType === 'polygon') {this.svgShapes[state.clientID] = this.addPolygon(stringified, state);} else if (state.shapeType === 'polyline') {this.svgShapes[state.clientID] = this.addPolyline(stringified, state);} else if (state.shapeType === 'points') {this.svgShapes[state.clientID] = this.addPoints(stringified, state);} else if (state.shapeType === 'cuboid') {this.svgShapes[state.clientID] = this.addCuboid(stringified, state);} else {continue;}}this.svgShapes[state.clientID].on('click.canvas', (): void => {this.canvas.dispatchEvent(new CustomEvent('canvas.clicked', {bubbles: false,cancelable: true,detail: {state,},}),);});if (displayAllText) {this.svgTexts[state.clientID] = this.addText(state);this.updateTextPosition(this.svgTexts[state.clientID], this.svgShapes[state.clientID]);}this.saveState(state);}}private activateShape(clientID: number): void {const [state] = this.controller.objects.filter((_state: any): boolean => _state.clientID === clientID);if (state && state.shapeType === 'points') {this.svgShapes[clientID].remember('_selectHandler').nested.style('pointer-events', this.stateIsLocked(state) ? 'none' : '');}if (!state || state.hidden || state.outside) {return;}const shape = this.svgShapes[clientID];let text = this.svgTexts[clientID];if (!text) {text = this.addText(state);this.svgTexts[state.clientID] = text;}this.updateTextPosition(text, shape);if (this.stateIsLocked(state)) {return;}shape.addClass('cvat_canvas_shape_activated');if (state.shapeType === 'points') {this.content.append(this.svgShapes[clientID].remember('_selectHandler').nested.node);} else {this.content.append(shape.node);}const { showProjections } = this.configuration;if (state.shapeType === 'cuboid' && showProjections) {(shape as any).attr('projections', true);}const hideText = (): void => {if (text) {text.addClass('cvat_canvas_hidden');}};const showText = (): void => {if (text) {text.removeClass('cvat_canvas_hidden');this.updateTextPosition(text, shape);}};if (!state.pinned) {shape.addClass('cvat_canvas_shape_draggable');(shape as any).draggable().on('dragstart', (): void => {this.mode = Mode.DRAG;hideText();}).on('dragend', (e: CustomEvent): void => {showText();this.mode = Mode.IDLE;const p1 = e.detail.handler.startPoints.point;const p2 = e.detail.p;const delta = 1;const { offset } = this.controller.geometry;const dx2 = (p1.x - p2.x) ** 2;const dy2 = (p1.y - p2.y) ** 2;if (Math.sqrt(dx2 + dy2) >= delta) {const points = pointsToNumberArray(shape.attr('points') || `${shape.attr('x')},${shape.attr('y')} ` +`${shape.attr('x') + shape.attr('width')},` +`${shape.attr('y') + shape.attr('height')}`,).map((x: number): number => x - offset);this.drawnStates[state.clientID].points = points;this.canvas.dispatchEvent(new CustomEvent('canvas.dragshape', {bubbles: false,cancelable: true,detail: {id: state.clientID,},}),);this.onEditDone(state, points);}});}if (state.shapeType !== 'points') {this.selectize(true, shape);}const showDirection = (): void => {if (['polygon', 'polyline'].includes(state.shapeType)) {this.showDirection(state, shape as SVG.Polygon | SVG.PolyLine);}};const hideDirection = (): void => {if (['polygon', 'polyline'].includes(state.shapeType)) {this.hideDirection(shape as SVG.Polygon | SVG.PolyLine);}};showDirection();let shapeSizeElement: ShapeSizeElement | null = null;let resized = false;(shape as any).resize({snapToGrid: 0.1,}).on('resizestart', (): void => {this.mode = Mode.RESIZE;resized = false;hideDirection();hideText();if (state.shapeType === 'rectangle') {shapeSizeElement = displayShapeSize(this.adoptedContent, this.adoptedText);}if (state.shapeType === 'circle') {shapeSizeElement = displayShapeSize(this.adoptedContent, this.adoptedText);}}).on('resizing', (): void => {resized = true;if (shapeSizeElement) {shapeSizeElement.update(shape);}}).on('resizedone', (): void => {if (shapeSizeElement) {shapeSizeElement.rm();}showDirection();showText();this.mode = Mode.IDLE;if (resized) {const { offset } = this.controller.geometry;const points = pointsToNumberArray(shape.attr('points') || `${shape.attr('x')},${shape.attr('y')} ` +`${shape.attr('x') + shape.attr('width')},` +`${shape.attr('y') + shape.attr('height')}`,).map((x: number): number => x - offset);this.drawnStates[state.clientID].points = points;this.canvas.dispatchEvent(new CustomEvent('canvas.resizeshape', {bubbles: false,cancelable: true,detail: {id: state.clientID,},}),);this.onEditDone(state, points);}});this.canvas.dispatchEvent(new CustomEvent('canvas.activated', {bubbles: false,cancelable: true,detail: {state,},}),);}private addCircle(points: number[], state: any): SVG.Circle {console.log('addCircle');const [xtl, ytl, xbr, ybr] = points;console.log((xbr - xtl) / 2);const rect = this.adoptedContent.circle().size(xbr - xtl, ybr - ytl).attr({clientID: state.clientID,'color-rendering': 'optimizeQuality',id: `cvat_canvas_shape_${state.clientID}`,fill: state.color,'shape-rendering': 'geometricprecision',stroke: state.color,'stroke-width': consts.BASE_STROKE_WIDTH / this.geometry.scale,'data-z-order': state.zOrder,}).move(xtl, ytl).addClass('cvat_canvas_shape');if (state.occluded) {rect.addClass('cvat_canvas_shape_occluded');}if (state.hidden || state.outside || this.isServiceHidden(state.clientID)) {rect.addClass('cvat_canvas_hidden');}return rect;}
3. drawHandler.ts
import { DrawData, Geometry, RectDrawingMethod, CircleDrawingMethod, Configuration, CuboidDrawingMethod, } from ‘./canvasModel’;
private getFinalCircleCoordinates(bbox: BBox): number[] {const frameWidth = this.geometry.image.width;const frameHeight = this.geometry.image.height;const { offset } = this.geometry;let [xtl, ytl, xbr, ybr] = [bbox.x, bbox.y, bbox.x + bbox.width, bbox.y + bbox.height].map((coord: number): number => coord - offset,);xtl = Math.min(Math.max(xtl, 0), frameWidth);xbr = Math.min(Math.max(xbr, 0), frameWidth);ytl = Math.min(Math.max(ytl, 0), frameHeight);ybr = Math.min(Math.max(ybr, 0), frameHeight);return [xtl, ytl, xbr, ybr];}private drawCircle(): void {this.drawInstance = this.canvas.circle();this.drawInstance.on('drawstop', (e: Event): void => {const bbox = (e.target as SVGRectElement).getBBox();const [xtl, ytl, xbr, ybr] = this.getFinalCircleCoordinates(bbox);const { shapeType, redraw: clientID } = this.drawData;this.release();if (this.canceled) return;if ((xbr - xtl) * (ybr - ytl) >= consts.AREA_THRESHOLD) {this.onDrawDone({clientID,shapeType,points: [xtl, ytl, xbr, ybr],},Date.now() - this.startTimestamp,);}}).on('drawupdate', (): void => {console.log(this.shapeSizeElement);this.shapeSizeElement.update(this.drawInstance);}).addClass('cvat_canvas_shape_drawing').attr({'stroke-width': consts.BASE_STROKE_WIDTH / this.geometry.scale,'fill-opacity': this.configuration.creationOpacity,});}private startDraw(): void {// TODO: Use enums after typification cvat-coreconsole.log('startDraw:', this.drawData.shapeType, this.drawData.initialState);if (this.drawData.initialState) {const { offset } = this.geometry;if (this.drawData.shapeType === 'rectangle') {const [xtl, ytl, xbr, ybr] = this.drawData.initialState.points.map((coord: number): number => coord + offset,);this.pasteBox({x: xtl,y: ytl,width: xbr - xtl,height: ybr - ytl,});} if (this.drawData.shapeType === 'circle') {const [xtl, ytl, xbr, ybr] = this.drawData.initialState.points.map((coord: number): number => coord + offset,);this.pasteBox({x: xtl,y: ytl,width: xbr - xtl,height: ybr - ytl,});} else {const points = this.drawData.initialState.points.map((coord: number): number => coord + offset);const stringifiedPoints = stringifyPoints(points);if (this.drawData.shapeType === 'polygon') {this.pastePolygon(stringifiedPoints);} else if (this.drawData.shapeType === 'polyline') {this.pastePolyline(stringifiedPoints);} else if (this.drawData.shapeType === 'points') {this.pastePoints(stringifiedPoints);} else if (this.drawData.shapeType === 'cuboid') {this.pasteCuboid(stringifiedPoints);}}this.setupPasteEvents();} else {if (this.drawData.shapeType === 'rectangle') {if (this.drawData.rectDrawingMethod === RectDrawingMethod.EXTREME_POINTS) {// draw box by extreme clickingthis.drawBoxBy4Points();} else {// default box drawingthis.drawBox();// Draw instance was initialized after drawBox();this.shapeSizeElement = displayShapeSize(this.canvas, this.text);}} else if (this.drawData.shapeType === 'circle') {this.drawCircle();this.shapeSizeElement = displayShapeSize(this.canvas, this.text);} else if (this.drawData.shapeType === 'polygon') {this.drawPolygon();} else if (this.drawData.shapeType === 'polyline') {this.drawPolyline();} else if (this.drawData.shapeType === 'points') {this.drawPoints();} else if (this.drawData.shapeType === 'cuboid') {if (this.drawData.cuboidDrawingMethod === CuboidDrawingMethod.CORNER_POINTS) {this.drawCuboidBy4Points();} else {this.drawCuboid();this.shapeSizeElement = displayShapeSize(this.canvas, this.text);}}this.setupDrawEvents();}this.startTimestamp = Date.now();this.initialized = true;}public configurate(configuration: Configuration): void {this.configuration = configuration;const isFillableRect = this.drawData &&this.drawData.shapeType === 'rectangle' &&(this.drawData.rectDrawingMethod === RectDrawingMethod.CLASSIC || this.drawData.initialState);const isFillableCircle = this.drawData &&this.drawData.shapeType === 'circle' &&(this.drawData.circleDrawingMethod === CircleDrawingMethod.CLASSIC || this.drawData.initialState);const isFillableCuboid = this.drawData &&this.drawData.shapeType === 'cuboid' &&(this.drawData.cuboidDrawingMethod === CuboidDrawingMethod.CLASSIC || this.drawData.initialState);const isFilalblePolygon = this.drawData && this.drawData.shapeType === 'polygon';if (this.drawInstance && (isFillableRect || isFillableCircle || isFillableCuboid || isFilalblePolygon)) {this.drawInstance.fill({ opacity: configuration.creationOpacity });}if (typeof configuration.autoborders === 'boolean') {this.autobordersEnabled = configuration.autoborders;if (this.drawInstance) {if (this.autobordersEnabled) {this.autoborderHandler.autoborder(true, this.drawInstance, this.drawData.redraw);} else {this.autoborderHandler.autoborder(false);}}}}public transform(geometry: Geometry): void {this.geometry = geometry;if (this.shapeSizeElement && this.drawInstance && this.drawData.shapeType === 'rectangle') {this.shapeSizeElement.update(this.drawInstance);}if (this.shapeSizeElement && this.drawInstance && this.drawData.shapeType === 'circle') {this.shapeSizeElement.update(this.drawInstance);}if (this.crosshair) {this.crosshair.scale(this.geometry.scale);}if (this.pointsGroup) {for (const point of this.pointsGroup.children()) {point.attr({'stroke-width': consts.POINTS_STROKE_WIDTH / geometry.scale,r: consts.BASE_POINT_SIZE / geometry.scale,});}}if (this.drawInstance) {this.drawInstance.draw('transform');this.drawInstance.attr({'stroke-width': consts.BASE_STROKE_WIDTH / geometry.scale,});const paintHandler = this.drawInstance.remember('_paintHandler');for (const point of (paintHandler as any).set.members) {point.attr('stroke-width', `${consts.POINTS_STROKE_WIDTH / geometry.scale}`);point.attr('r', `${consts.BASE_POINT_SIZE / geometry.scale}`);}}}
4. interactionHandler.ts
private shouldRaiseEvent(ctrlKey: boolean): boolean { const { interactionData, interactionShapes, shapesWereUpdated } = this; const { minPosVertices, minNegVertices, enabled } = interactionData;
const positiveShapes = interactionShapes.filter((shape: SVG.Shape): boolean => (shape as any).attr('stroke') === 'green',);const negativeShapes = interactionShapes.filter((shape: SVG.Shape): boolean => (shape as any).attr('stroke') !== 'green',);if (interactionData.shapeType === 'rectangle') {return enabled && !ctrlKey && !!interactionShapes.length;}if (interactionData.shapeType === 'circle') {return enabled && !ctrlKey && !!interactionShapes.length;}const minPosVerticesDefined = Number.isInteger(minPosVertices);const minNegVerticesDefined = Number.isInteger(minNegVertices) && minNegVertices >= 0;const minPosVerticesAchieved = !minPosVerticesDefined || minPosVertices <= positiveShapes.length;const minNegVerticesAchieved = !minNegVerticesDefined || minNegVertices <= negativeShapes.length;const minimumVerticesAchieved = minPosVerticesAchieved && minNegVerticesAchieved;return enabled && !ctrlKey && minimumVerticesAchieved && shapesWereUpdated;}private startInteraction(): void {if (this.interactionData.shapeType === 'rectangle') {this.interactRectangle(true);} else if (this.interactionData.shapeType === 'circle') {this.interactRectangle(true);} else if (this.interactionData.shapeType === 'points') {if (this.interactionData.startWithBox) {this.interactRectangle(false, (): void => this.interactPoints());} else {this.interactPoints();}} else {throw new Error('Interactor implementation supports only rectangle and points');}}
5. annotations-collection.js
const {RectangleShape,CircleShape,PolygonShape,PolylineShape,PointsShape,CuboidShape,RectangleTrack,PolygonTrack,PolylineTrack,PointsTrack,CuboidTrack,Track,Shape,Tag,objectStateFactory,CircleTrack,} = require('./annotations-objects');function shapeFactory(shapeData, clientID, injection) {const { type } = shapeData;const color = colors[clientID % colors.length];let shapeModel = null;switch (type) {case 'rectangle':shapeModel = new RectangleShape(shapeData, clientID, color, injection);break;case 'circle':shapeModel = new CircleShape(shapeData, clientID, color, injection);break;case 'polygon':shapeModel = new PolygonShape(shapeData, clientID, color, injection);break;case 'polyline':shapeModel = new PolylineShape(shapeData, clientID, color, injection);break;case 'points':shapeModel = new PointsShape(shapeData, clientID, color, injection);break;case 'cuboid':shapeModel = new CuboidShape(shapeData, clientID, color, injection);break;default:throw new DataError(`An unexpected type of shape "${type}"`);}return shapeModel;}function trackFactory(trackData, clientID, injection) {if (trackData.shapes.length) {const { type } = trackData.shapes[0];const color = colors[clientID % colors.length];let trackModel = null;switch (type) {case 'rectangle':trackModel = new RectangleTrack(trackData, clientID, color, injection);break;case 'circle':trackModel = new CircleTrack(trackData, clientID, color, injection);break;case 'polygon':trackModel = new PolygonTrack(trackData, clientID, color, injection);break;case 'polyline':trackModel = new PolylineTrack(trackData, clientID, color, injection);break;case 'points':trackModel = new PointsTrack(trackData, clientID, color, injection);break;case 'cuboid':trackModel = new CuboidTrack(trackData, clientID, color, injection);break;default:throw new DataError(`An unexpected type of track "${type}"`);}return trackModel;}console.warn('The track without any shapes had been found. It was ignored.');return null;}
6. annotations-saver.js
async save(onUpdateArg) {const onUpdate = typeof onUpdateArg === 'function' ? onUpdateArg : (message) => {console.log(message);};const exported = this.collection.export();const { flush } = this.collection;if (flush) {onUpdate('Created objects are being saved on the server');const indexes = this._receiveIndexes(exported);const savedData = await this._put({ ...exported, version: this.version });this.version = savedData.version;this.collection.flush = false;this._updateCreatedObjects(savedData, indexes);this._resetState();for (const type of Object.keys(this.initialObjects)) {for (const object of savedData[type]) {this.initialObjects[type][object.id] = object;}}} else {const { created, updated, deleted } = this._split(exported);onUpdate('Created objects are being saved on the server');console.log('created', created);if (created.shapes) {created.shapes.map((n) => {if (n.type === 'circle') {// @ts-ignore// eslint-disable-next-line prefer-destructuringn.rx = n.points[0];// @ts-ignore// eslint-disable-next-line prefer-destructuringn.ry = n.points[1];n.radius = (n.points[3] - n.points[0]) / 2;}});}const indexes = this._receiveIndexes(created);const createdData = await this._create({ ...created, version: this.version });this.version = createdData.version;this._updateCreatedObjects(createdData, indexes);for (const type of Object.keys(this.initialObjects)) {for (const object of createdData[type]) {this.initialObjects[type][object.id] = object;}}onUpdate('Updated objects are being saved on the server');this._receiveIndexes(updated);const updatedData = await this._update({ ...updated, version: this.version });this.version = updatedData.version;for (const type of Object.keys(this.initialObjects)) {for (const object of updatedData[type]) {this.initialObjects[type][object.id] = object;}}onUpdate('Deleted objects are being deleted from the server');this._receiveIndexes(deleted);const deletedData = await this._delete({ ...deleted, version: this.version });this._version = deletedData.version;for (const type of Object.keys(this.initialObjects)) {for (const object of deletedData[type]) {delete this.initialObjects[type][object.id];}}}this.hash = this._getHash();}hasUnsavedChanges() {return this._getHash() !== this.hash;}}
7. enum.js
const ObjectShape = Object.freeze({RECTANGLE: 'rectangle',CIRCLE: 'circle',POLYGON: 'polygon',POLYLINE: 'polyline',POINTS: 'points',CUBOID: 'cuboid',});
8. styles.scss
.cvat-cursor-control, .cvat-move-control, .cvat-rotate-canvas-control, .cvat-fit-control, .cvat-resize-control, .cvat-draw-rectangle-control, .cvat-draw-circle-control, .cvat-draw-polygon-control, .cvat-draw-polyline-control, .cvat-draw-points-control, .cvat-draw-cuboid-control, .cvat-setup-tag-control, .cvat-merge-control, .cvat-group-control, .cvat-split-track-control, .cvat-issue-control, .cvat-tools-control, .cvat-extra-controls-control, .cvat-opencv-control { border-radius: 3.3px; transform: scale(0.65); padding: 2px;
&:hover:not(.cvat-disabled-canvas-control) {background: $header-color;transform: scale(0.75);}&:active:not(.cvat-disabled-canvas-control) {transform: scale(0.65);}> svg {transform: scale(0.8);}
}
9. controls-side-bar.tsx
import DrawCircleControl, { Props as DrawCircleControlProps } from ‘./draw-circle-control’;
const ObservedDrawCircleControl = ControlVisibilityObserver
<ObservedDrawCircleControlcanvasInstance={canvasInstance}isDrawing={activeControl === ActiveControl.DRAW_CIRCLE}disabled={!labels.length}/>
10. draw-circle-control.tsx
// Copyright (C) 2020-2021 Intel Corporation // // SPDX-License-Identifier: MIT
import React from ‘react’; import Popover from ‘antd/lib/popover’; import Icon from ‘@ant-design/icons’;
import { Canvas } from ‘cvat-canvas-wrapper’; import { CircleIcon } from ‘icons’; import { ShapeType } from ‘reducers/interfaces’;
import DrawShapePopoverContainer from ‘containers/annotation-page/standard-workspace/controls-side-bar/draw-shape-popover’; import withVisibilityHandling from ‘./handle-popover-visibility’;
export interface Props { canvasInstance: Canvas; isDrawing: boolean; disabled?: boolean; }
const CustomPopover = withVisibilityHandling(Popover, ‘draw-circle’); function DrawCircleControl(props: Props): JSX.Element { const { canvasInstance, isDrawing, disabled } = props; const dynamcPopoverPros = isDrawing ? { overlayStyle: { display: ‘none’, }, } : {};
const dynamicIconProps = isDrawing ?{className: 'cvat-draw-circle-control cvat-active-canvas-control',onClick: (): void => {canvasInstance.draw({ enabled: false });},} :{className: 'cvat-draw-circle-control',};return disabled ? (<Icon className='cvat-draw-circle-control cvat-disabled-canvas-control' component={CircleIcon} />) : (<CustomPopover{...dynamcPopoverPros}overlayClassName='cvat-draw-shape-popover'placement='right'content={<DrawShapePopoverContainer shapeType={ShapeType.CIRCLE} />}><Icon {...dynamicIconProps} component={CircleIcon} /></CustomPopover>);
}
export default React.memo(DrawCircleControl);
11. draw-shape-popover.tsx
// Copyright (C) 2020-2021 Intel Corporation // // SPDX-License-Identifier: MIT
import React from ‘react’; import { Row, Col } from ‘antd/lib/grid’; import Button from ‘antd/lib/button’; import InputNumber from ‘antd/lib/input-number’; import Radio, { RadioChangeEvent } from ‘antd/lib/radio’; import Text from ‘antd/lib/typography/Text’; import { RectDrawingMethod, CuboidDrawingMethod, CircleDrawingMethod } from ‘cvat-canvas-wrapper’;
import { DimensionType, ShapeType } from ‘reducers/interfaces’; import { clamp } from ‘utils/math’; import LabelSelector from ‘components/label-selector/label-selector’; import CVATTooltip from ‘components/common/cvat-tooltip’;
interface Props { shapeType: ShapeType; labels: any[]; minimumPoints: number; rectDrawingMethod?: RectDrawingMethod; circleDrawingMethod?: CircleDrawingMethod; cuboidDrawingMethod?: CuboidDrawingMethod; numberOfPoints?: number; selectedLabelID: number; repeatShapeShortcut: string; onChangeLabel(value: string): void; onChangePoints(value: number | undefined): void; onChangeRectDrawingMethod(event: RadioChangeEvent): void; onChangeCircleDrawingMethod(event: CircleDrawingMethod): void; onChangeCuboidDrawingMethod(event: RadioChangeEvent): void; onDrawTrack(): void; onDrawShape(): void; jobInstance: any; }
function DrawShapePopoverComponent(props: Props): JSX.Element { const { labels, shapeType, minimumPoints, selectedLabelID, numberOfPoints, rectDrawingMethod, circleDrawingMethod, cuboidDrawingMethod, repeatShapeShortcut, onDrawTrack, onDrawShape, onChangeLabel, onChangePoints, onChangeRectDrawingMethod, onChangeCircleDrawingMethod, onChangeCuboidDrawingMethod, jobInstance, } = props;
const is2D = jobInstance.task.dimension === DimensionType.DIM_2D;return (<div className='cvat-draw-shape-popover-content'><Row justify='start'><Col><Text className='cvat-text-color' strong>{`Draw new ${shapeType}`}</Text></Col></Row><Row justify='start'><Col><Text className='cvat-text-color'>Label</Text></Col></Row><Row justify='center'><Col span={24}><LabelSelectorstyle={{ width: '100%' }}labels={labels}value={selectedLabelID}onChange={onChangeLabel}/></Col></Row>{is2D && shapeType === ShapeType.RECTANGLE && (<><Row><Col><Text className='cvat-text-color'> Drawing method </Text></Col></Row><Row justify='space-around'><Col><Radio.Groupstyle={{ display: 'flex' }}value={rectDrawingMethod}onChange={onChangeRectDrawingMethod}><Radio value={RectDrawingMethod.CLASSIC} style={{ width: 'auto' }}>By 2 Points</Radio><Radio value={RectDrawingMethod.EXTREME_POINTS} style={{ width: 'auto' }}>By 4 Points</Radio></Radio.Group></Col></Row></>)}{is2D && shapeType === ShapeType.CIRCLE && (<><Row><Col><Text className='cvat-text-color'> Drawing method </Text></Col></Row><Row justify='space-around'><Col><Radio.Groupstyle={{ display: 'flex' }}value={circleDrawingMethod}onChange={onChangeCircleDrawingMethod}><Radio value={CircleDrawingMethod.CLASSIC} style={{ width: 'auto' }}>By 2 Points</Radio><Radio value={CircleDrawingMethod.EXTREME_POINTS} style={{ width: 'auto' }}>By 4 Points</Radio></Radio.Group></Col></Row></>)}{is2D && shapeType === ShapeType.CUBOID && (<><Row><Col><Text className='cvat-text-color'> Drawing method </Text></Col></Row><Row justify='space-around'><Col><Radio.Groupstyle={{ display: 'flex' }}value={cuboidDrawingMethod}onChange={onChangeCuboidDrawingMethod}><Radio value={CuboidDrawingMethod.CLASSIC} style={{ width: 'auto' }}>From rectangle</Radio><Radio value={CuboidDrawingMethod.CORNER_POINTS} style={{ width: 'auto' }}>By 4 Points</Radio></Radio.Group></Col></Row></>)}{is2D && shapeType !== ShapeType.RECTANGLE &&shapeType !== ShapeType.CIRCLE && shapeType !== ShapeType.CUBOID && (<Row justify='space-around' align='middle'><Col span={14}><Text className='cvat-text-color'> Number of points: </Text></Col><Col span={10}><InputNumberonChange={(value: number | undefined | string | null) => {if (typeof value === 'undefined' || value === null) {onChangePoints(undefined);} else {onChangePoints(Math.floor(clamp(+value, minimumPoints, Number.MAX_SAFE_INTEGER)));}}}className='cvat-draw-shape-popover-points-selector'min={minimumPoints}value={numberOfPoints}step={1}/></Col></Row>)}<Row justify='space-around'><Col span={12}><CVATTooltip title={`Press ${repeatShapeShortcut} to draw again`}><Button onClick={onDrawShape}>Shape</Button></CVATTooltip></Col>{is2D && (<Col span={12}><CVATTooltip title={`Press ${repeatShapeShortcut} to draw again`}><Button onClick={onDrawTrack}>Track</Button></CVATTooltip></Col>)}</Row></div>);
}
export default React.memo(DrawShapePopoverComponent);
12. tools-control.tsx
private collectTrackerPortals(): React.ReactPortal[] {const { states, fetchAnnotations } = this.props;const { trackedShapes, activeTracker } = this.state;const trackedClientIDs = trackedShapes.map((trackedShape: TrackedShape) => trackedShape.clientID);const portals = !activeTracker ?[] :states.filter((objectState) => objectState.objectType === 'track' && (objectState.shapeType === 'rectangle' || objectState.shapeType === 'circle')).map((objectState: any): React.ReactPortal | null => {const { clientID } = objectState;const selectorID = `#cvat-objects-sidebar-state-item-${clientID}`;let targetElement = window.document.querySelector(`${selectorID} .cvat-object-item-button-prev-keyframe`,) as HTMLElement;const isTracked = trackedClientIDs.includes(clientID);if (targetElement) {targetElement = targetElement.parentElement?.parentElement as HTMLElement;return ReactDOM.createPortal(<Col>{isTracked ? (<CVATTooltip overlay='Disable tracking'><EnvironmentFilledonClick={() => {const filteredStates = trackedShapes.filter((trackedShape: TrackedShape) => trackedShape.clientID !== clientID,);/* eslint no-param-reassign: ["error", { "props": false }] */objectState.descriptions = [];objectState.save().then(() => {this.setState({trackedShapes: filteredStates,});});fetchAnnotations();}}/></CVATTooltip>) : (<CVATTooltip overlay={`Enable tracking using ${activeTracker.name}`}><EnvironmentOutlinedonClick={() => {objectState.descriptions = [`Trackable (${activeTracker.name})`];objectState.save().then(() => {this.setState({trackedShapes: [...trackedShapes,{clientID,serverlessState: null,shapePoints: objectState.points,trackerModel: activeTracker,},],});});fetchAnnotations();}}/></CVATTooltip>)}</Col>,targetElement,);}return null;}).filter((portal: ReactPortal | null) => portal !== null);return portals as React.ReactPortal[];}
13. interface.ts
export enum ActiveControl { CURSOR = ‘cursor’, DRAG_CANVAS = ‘drag_canvas’, ZOOM_CANVAS = ‘zoom_canvas’, DRAW_RECTANGLE = ‘draw_rectangle’, DRAW_CIRCLE = ‘draw_circle’, DRAW_POLYGON = ‘draw_polygon’, DRAW_POLYLINE = ‘draw_polyline’, DRAW_POINTS = ‘draw_points’, DRAW_CUBOID = ‘draw_cuboid’, MERGE = ‘merge’, GROUP = ‘group’, SPLIT = ‘split’, EDIT = ‘edit’, OPEN_ISSUE = ‘open_issue’, AI_TOOLS = ‘ai_tools’, PHOTO_CONTEXT = ‘PHOTO_CONTEXT’, OPENCV_TOOLS = ‘opencv_tools’, }
export enum ShapeType { RECTANGLE = ‘rectangle’, CIRCLE = ‘circle’, POLYGON = ‘polygon’, POLYLINE = ‘polyline’, POINTS = ‘points’, CUBOID = ‘cuboid’, }
14. commands_review_pipline.js
Cypress.Commands.add(‘createIssueFromControlButton’, (createIssueParams) => { cy.get(‘.cvat-issue-control’).click().should(‘have.class’, ‘cvat-active-canvas-control’); if (createIssueParams.type === ‘rectangle’) { cy.get(‘.cvat-canvas-container’) .trigger(‘mousedown’, createIssueParams.firstX, createIssueParams.firstY, { button: 0 }) .trigger(‘mousemove’, createIssueParams.secondX, createIssueParams.secondY) .trigger(‘mouseup’); } else if (createIssueParams.type === ‘circle’) { cy.get(‘.cvat-canvas-container’) .trigger(‘mousedown’, createIssueParams.firstX, createIssueParams.firstY, { button: 0 }) .trigger(‘mousemove’, createIssueParams.secondX, createIssueParams.secondY) .trigger(‘mouseup’); } else if (createIssueParams.type === ‘point’) { cy.get(‘.cvat-canvas-container’) .trigger(‘mousedown’, createIssueParams.firstX, createIssueParams.firstY, { button: 0 }) .trigger(‘mouseup’); } cy.get(‘.cvat-create-issue-dialog’).within(() => { cy.get(‘#issue_description’).type(createIssueParams.description); cy.get(‘[type=”submit”]’).click(); }); cy.checkIssueRegion(); });
15.canvas.ts
// Copyright (C) 2019-2021 Intel Corporation // // SPDX-License-Identifier: MIT
import { Mode, DrawData, MergeData, SplitData, GroupData, InteractionData as _InteractionData, InteractionResult as _InteractionResult, CanvasModel, CanvasModelImpl, RectDrawingMethod, CircleDrawingMethod, CuboidDrawingMethod, Configuration, Geometry, } from ‘./canvasModel’; import { Master } from ‘./master’; import { CanvasController, CanvasControllerImpl } from ‘./canvasController’; import { CanvasView, CanvasViewImpl } from ‘./canvasView’;
import ‘../scss/canvas.scss’; import pjson from ‘../../package.json’;
const CanvasVersion = pjson.version;
interface Canvas {
html(): HTMLDivElement;
setup(frameData: any, objectStates: any[], zLayer?: number): void;
setupIssueRegions(issueRegions: Record
interact(interactionData: InteractionData): void;draw(drawData: DrawData): void;group(groupData: GroupData): void;split(splitData: SplitData): void;merge(mergeData: MergeData): void;select(objectState: any): void;fitCanvas(): void;bitmap(enable: boolean): void;selectRegion(enable: boolean): void;dragCanvas(enable: boolean): void;zoomCanvas(enable: boolean): void;mode(): Mode;cancel(): void;configure(configuration: Configuration): void;isAbleToChangeFrame(): boolean;readonly geometry: Geometry;
}
class CanvasImpl implements Canvas { private model: CanvasModel & Master; private controller: CanvasController; private view: CanvasView;
public constructor() {this.model = new CanvasModelImpl();this.controller = new CanvasControllerImpl(this.model);this.view = new CanvasViewImpl(this.model, this.controller);}public html(): HTMLDivElement {return this.view.html();}public setup(frameData: any, objectStates: any[], zLayer = 0): void {this.model.setup(frameData, objectStates, zLayer);}public setupIssueRegions(issueRegions: Record<number, number[]>): void {this.model.setupIssueRegions(issueRegions);}public fitCanvas(): void {this.model.fitCanvas(this.view.html().clientWidth, this.view.html().clientHeight);}public bitmap(enable: boolean): void {this.model.bitmap(enable);}public selectRegion(enable: boolean): void {this.model.selectRegion(enable);}public dragCanvas(enable: boolean): void {this.model.dragCanvas(enable);}public zoomCanvas(enable: boolean): void {this.model.zoomCanvas(enable);}public activate(clientID: number | null, attributeID: number | null = null): void {this.model.activate(clientID, attributeID);}public rotate(rotationAngle: number): void {this.model.rotate(rotationAngle);}public focus(clientID: number, padding = 0): void {this.model.focus(clientID, padding);}public fit(): void {this.model.fit();}public grid(stepX: number, stepY: number): void {this.model.grid(stepX, stepY);}public interact(interactionData: InteractionData): void {this.model.interact(interactionData);}public draw(drawData: DrawData): void {this.model.draw(drawData);}public split(splitData: SplitData): void {this.model.split(splitData);}public group(groupData: GroupData): void {this.model.group(groupData);}public merge(mergeData: MergeData): void {this.model.merge(mergeData);}public select(objectState: any): void {this.model.select(objectState);}public mode(): Mode {return this.model.mode;}public cancel(): void {this.model.cancel();}public configure(configuration: Configuration): void {this.model.configure(configuration);}public isAbleToChangeFrame(): boolean {return this.model.isAbleToChangeFrame();}public get geometry(): Geometry {return this.model.geometry;}
}
export type InteractionData = _InteractionData; export type InteractionResult = _InteractionResult;
export { // eslint-disable-next-line max-len CanvasImpl as Canvas, CanvasVersion, RectDrawingMethod, CircleDrawingMethod, CuboidDrawingMethod, Mode as CanvasMode, };
16.cvat-canvas-wrapper.ts
// Copyright (C) 2021 Intel Corporation // // SPDX-License-Identifier: MIT // Copyright (C) 2020-2021 Intel Corporation // // SPDX-License-Identifier: MIT
import { Canvas, CanvasMode, CanvasVersion, RectDrawingMethod, CircleDrawingMethod, CuboidDrawingMethod, InteractionData as _InteractionData, InteractionResult as _InteractionResult, } from ‘cvat-canvas/src/typescript/canvas’;
export function convertShapesForInteractor(shapes: InteractionResult[], button: number): number[][] { const reducer = (acc: number[][], _: number, index: number, array: number[]): number[][] => { if (!(index % 2)) { // 0, 2, 4 acc.push([array[index], array[index + 1]]); } return acc; };
return shapes.filter((shape: InteractionResult): boolean => shape.button === button).map((shape: InteractionResult): number[] => shape.points).flat().reduce(reducer, []);
}
export type InteractionData = _InteractionData; export type InteractionResult = _InteractionResult;
export { Canvas, CanvasMode, CanvasVersion, RectDrawingMethod, CircleDrawingMethod, CuboidDrawingMethod, };
17.annotation-actions.ts
// Copyright (C) 2020-2021 Intel Corporation // // SPDX-License-Identifier: MIT
import { ActionCreator, AnyAction, Dispatch, Store, } from ‘redux’; import { ThunkAction } from ‘utils/redux’; import { RectDrawingMethod, CircleDrawingMethod, CuboidDrawingMethod, Canvas, } from ‘cvat-canvas-wrapper’; import getCore from ‘cvat-core-wrapper’; import logger, { LogType } from ‘cvat-logger’; import { getCVATStore } from ‘cvat-store’; import { ActiveControl, CombinedState, ContextMenuType, DimensionType, FrameSpeed, Model, ObjectType, OpenCVTool, Rotation, ShapeType, Task, Workspace, } from ‘reducers/interfaces’;
interface AnnotationsParameters { filters: string[]; frame: number; showAllInterpolationTracks: boolean; jobInstance: any; }
const cvat = getCore();
let store: null | Store
function getStore(): Store
function receiveAnnotationsParameters(): AnnotationsParameters { if (store === null) { store = getCVATStore(); }
const state: CombinedState = getStore().getState();const {annotation: {annotations: { filters },player: {frame: { number: frame },},job: { instance: jobInstance },},settings: {workspace: { showAllInterpolationTracks },},} = state;return {filters,frame,jobInstance,showAllInterpolationTracks,};
}
export function computeZRange(states: any[]): number[] { const filteredStates = states.filter((state: any): any => state.objectType !== ObjectType.TAG); let minZ = filteredStates.length ? filteredStates[0].zOrder : 0; let maxZ = filteredStates.length ? filteredStates[0].zOrder : 0; filteredStates.forEach((state: any): void => { minZ = Math.min(minZ, state.zOrder); maxZ = Math.max(maxZ, state.zOrder); });
return [minZ, maxZ];
}
async function jobInfoGenerator(job: any): Promise
export enum AnnotationActionTypes { GET_JOB = ‘GET_JOB’, GET_JOB_SUCCESS = ‘GET_JOB_SUCCESS’, GET_JOB_FAILED = ‘GET_JOB_FAILED’, CLOSE_JOB = ‘CLOSE_JOB’, CHANGE_FRAME = ‘CHANGE_FRAME’, CHANGE_FRAME_SUCCESS = ‘CHANGE_FRAME_SUCCESS’, CHANGE_FRAME_FAILED = ‘CHANGE_FRAME_FAILED’, SAVE_ANNOTATIONS = ‘SAVE_ANNOTATIONS’, SAVE_ANNOTATIONS_SUCCESS = ‘SAVE_ANNOTATIONS_SUCCESS’, SAVE_ANNOTATIONS_FAILED = ‘SAVE_ANNOTATIONS_FAILED’, SAVE_UPDATE_ANNOTATIONS_STATUS = ‘SAVE_UPDATE_ANNOTATIONS_STATUS’, SWITCH_PLAY = ‘SWITCH_PLAY’, CONFIRM_CANVAS_READY = ‘CONFIRM_CANVAS_READY’, DRAG_CANVAS = ‘DRAG_CANVAS’, ZOOM_CANVAS = ‘ZOOM_CANVAS’, SELECT_ISSUE_POSITION = ‘SELECT_ISSUE_POSITION’, MERGE_OBJECTS = ‘MERGE_OBJECTS’, GROUP_OBJECTS = ‘GROUP_OBJECTS’, SPLIT_TRACK = ‘SPLIT_TRACK’, COPY_SHAPE = ‘COPY_SHAPE’, PASTE_SHAPE = ‘PASTE_SHAPE’, EDIT_SHAPE = ‘EDIT_SHAPE’, REPEAT_DRAW_SHAPE = ‘REPEAT_DRAW_SHAPE’, SHAPE_DRAWN = ‘SHAPE_DRAWN’, RESET_CANVAS = ‘RESET_CANVAS’, REMEMBER_CREATED_OBJECT = ‘REMEMBER_CREATED_OBJECT’, UPDATE_ANNOTATIONS_SUCCESS = ‘UPDATE_ANNOTATIONS_SUCCESS’, UPDATE_ANNOTATIONS_FAILED = ‘UPDATE_ANNOTATIONS_FAILED’, CREATE_ANNOTATIONS_SUCCESS = ‘CREATE_ANNOTATIONS_SUCCESS’, CREATE_ANNOTATIONS_FAILED = ‘CREATE_ANNOTATIONS_FAILED’, MERGE_ANNOTATIONS_SUCCESS = ‘MERGE_ANNOTATIONS_SUCCESS’, MERGE_ANNOTATIONS_FAILED = ‘MERGE_ANNOTATIONS_FAILED’, RESET_ANNOTATIONS_GROUP = ‘RESET_ANNOTATIONS_GROUP’, GROUP_ANNOTATIONS = ‘GROUP_ANNOTATIONS’, GROUP_ANNOTATIONS_SUCCESS = ‘GROUP_ANNOTATIONS_SUCCESS’, GROUP_ANNOTATIONS_FAILED = ‘GROUP_ANNOTATIONS_FAILED’, SPLIT_ANNOTATIONS_SUCCESS = ‘SPLIT_ANNOTATIONS_SUCCESS’, SPLIT_ANNOTATIONS_FAILED = ‘SPLIT_ANNOTATIONS_FAILED’, COLLAPSE_SIDEBAR = ‘COLLAPSE_SIDEBAR’, COLLAPSE_APPEARANCE = ‘COLLAPSE_APPEARANCE’, COLLAPSE_OBJECT_ITEMS = ‘COLLAPSE_OBJECT_ITEMS’, ACTIVATE_OBJECT = ‘ACTIVATE_OBJECT’, REMOVE_OBJECT_SUCCESS = ‘REMOVE_OBJECT_SUCCESS’, REMOVE_OBJECT_FAILED = ‘REMOVE_OBJECT_FAILED’, PROPAGATE_OBJECT = ‘PROPAGATE_OBJECT’, PROPAGATE_OBJECT_SUCCESS = ‘PROPAGATE_OBJECT_SUCCESS’, PROPAGATE_OBJECT_FAILED = ‘PROPAGATE_OBJECT_FAILED’, CHANGE_PROPAGATE_FRAMES = ‘CHANGE_PROPAGATE_FRAMES’, SWITCH_SHOWING_STATISTICS = ‘SWITCH_SHOWING_STATISTICS’, SWITCH_SHOWING_FILTERS = ‘SWITCH_SHOWING_FILTERS’, COLLECT_STATISTICS = ‘COLLECT_STATISTICS’, COLLECT_STATISTICS_SUCCESS = ‘COLLECT_STATISTICS_SUCCESS’, COLLECT_STATISTICS_FAILED = ‘COLLECT_STATISTICS_FAILED’, UPLOAD_JOB_ANNOTATIONS = ‘UPLOAD_JOB_ANNOTATIONS’, UPLOAD_JOB_ANNOTATIONS_SUCCESS = ‘UPLOAD_JOB_ANNOTATIONS_SUCCESS’, UPLOAD_JOB_ANNOTATIONS_FAILED = ‘UPLOAD_JOB_ANNOTATIONS_FAILED’, REMOVE_JOB_ANNOTATIONS_SUCCESS = ‘REMOVE_JOB_ANNOTATIONS_SUCCESS’, REMOVE_JOB_ANNOTATIONS_FAILED = ‘REMOVE_JOB_ANNOTATIONS_FAILED’, UPDATE_CANVAS_CONTEXT_MENU = ‘UPDATE_CANVAS_CONTEXT_MENU’, UNDO_ACTION_SUCCESS = ‘UNDO_ACTION_SUCCESS’, UNDO_ACTION_FAILED = ‘UNDO_ACTION_FAILED’, REDO_ACTION_SUCCESS = ‘REDO_ACTION_SUCCESS’, REDO_ACTION_FAILED = ‘REDO_ACTION_FAILED’, CHANGE_ANNOTATIONS_FILTERS = ‘CHANGE_ANNOTATIONS_FILTERS’, FETCH_ANNOTATIONS_SUCCESS = ‘FETCH_ANNOTATIONS_SUCCESS’, FETCH_ANNOTATIONS_FAILED = ‘FETCH_ANNOTATIONS_FAILED’, ROTATE_FRAME = ‘ROTATE_FRAME’, SWITCH_Z_LAYER = ‘SWITCH_Z_LAYER’, ADD_Z_LAYER = ‘ADD_Z_LAYER’, SEARCH_ANNOTATIONS_FAILED = ‘SEARCH_ANNOTATIONS_FAILED’, SEARCH_EMPTY_FRAME_FAILED = ‘SEARCH_EMPTY_FRAME_FAILED’, CHANGE_WORKSPACE = ‘CHANGE_WORKSPACE’, SAVE_LOGS_SUCCESS = ‘SAVE_LOGS_SUCCESS’, SAVE_LOGS_FAILED = ‘SAVE_LOGS_FAILED’, INTERACT_WITH_CANVAS = ‘INTERACT_WITH_CANVAS’, GET_DATA_FAILED = ‘GET_DATA_FAILED’, SWITCH_REQUEST_REVIEW_DIALOG = ‘SWITCH_REQUEST_REVIEW_DIALOG’, SWITCH_SUBMIT_REVIEW_DIALOG = ‘SWITCH_SUBMIT_REVIEW_DIALOG’, SET_FORCE_EXIT_ANNOTATION_PAGE_FLAG = ‘SET_FORCE_EXIT_ANNOTATION_PAGE_FLAG’, UPDATE_PREDICTOR_STATE = ‘UPDATE_PREDICTOR_STATE’, GET_PREDICTIONS = ‘GET_PREDICTIONS’, GET_PREDICTIONS_FAILED = ‘GET_PREDICTIONS_FAILED’, GET_PREDICTIONS_SUCCESS = ‘GET_PREDICTIONS_SUCCESS’, HIDE_SHOW_CONTEXT_IMAGE = ‘HIDE_SHOW_CONTEXT_IMAGE’, GET_CONTEXT_IMAGE = ‘GET_CONTEXT_IMAGE’, GET_CONTEXT_IMAGE_SUCCESS = ‘GET_CONTEXT_IMAGE_SUCCESS’, GET_CONTEXT_IMAGE_FAILED = ‘GET_CONTEXT_IMAGE_FAILED’, SWITCH_NAVIGATION_BLOCKED = ‘SWITCH_NAVIGATION_BLOCKED’, }
export function saveLogsAsync(): ThunkAction {
return async (dispatch: ActionCreator
export function changeWorkspace(workspace: Workspace): AnyAction { return { type: AnnotationActionTypes.CHANGE_WORKSPACE, payload: { workspace, }, }; }
export function getDataFailed(error: any): AnyAction { return { type: AnnotationActionTypes.GET_DATA_FAILED, payload: { error, }, }; }
export function addZLayer(): AnyAction { return { type: AnnotationActionTypes.ADD_Z_LAYER, payload: {}, }; }
export function switchZLayer(cur: number): AnyAction { return { type: AnnotationActionTypes.SWITCH_Z_LAYER, payload: { cur, }, }; }
export function fetchAnnotationsAsync(): ThunkAction {
return async (dispatch: ActionCreator
dispatch({type: AnnotationActionTypes.FETCH_ANNOTATIONS_SUCCESS,payload: {states,history,minZ,maxZ,},});} catch (error) {dispatch({type: AnnotationActionTypes.FETCH_ANNOTATIONS_FAILED,payload: {error,},});}};
}
export function changeAnnotationsFilters(filters: any[]): AnyAction { return { type: AnnotationActionTypes.CHANGE_ANNOTATIONS_FILTERS, payload: { filters }, }; }
export function updateCanvasContextMenu( visible: boolean, left: number, top: number, pointID: number | null = null, type?: ContextMenuType, ): AnyAction { return { type: AnnotationActionTypes.UPDATE_CANVAS_CONTEXT_MENU, payload: { visible, left, top, type, pointID, }, }; }
export function removeAnnotationsAsync(
startFrame: number, endFrame: number, delTrackKeyframesOnly: boolean,
): ThunkAction {
return async (dispatch: ActionCreator
dispatch({type: AnnotationActionTypes.REMOVE_JOB_ANNOTATIONS_SUCCESS,payload: {history,states,},});} catch (error) {dispatch({type: AnnotationActionTypes.REMOVE_JOB_ANNOTATIONS_FAILED,payload: {error,},});}};
}
export function uploadJobAnnotationsAsync(job: any, loader: any, file: File): ThunkAction {
return async (dispatch: ActionCreator
if (state.tasks.activities.loads[job.task.id]) {throw Error('Annotations is being uploaded for the task');}if (state.annotation.activities.loads[job.id]) {throw Error('Only one uploading of annotations for a job allowed at the same time');}dispatch({type: AnnotationActionTypes.UPLOAD_JOB_ANNOTATIONS,payload: {job,loader,},});const frame = state.annotation.player.frame.number;await job.annotations.upload(file, loader);await job.logger.log(LogType.uploadAnnotations, {...(await jobInfoGenerator(job)),});await job.annotations.clear(true);await job.actions.clear();const history = await job.actions.get();// One more update to escape some problems// in canvas when shape with the same// clientID has different type (polygon, rectangle) for exampledispatch({type: AnnotationActionTypes.UPLOAD_JOB_ANNOTATIONS_SUCCESS,payload: {job,states: [],history,},});const states = await job.annotations.get(frame, showAllInterpolationTracks, filters);setTimeout(() => {dispatch({type: AnnotationActionTypes.UPLOAD_JOB_ANNOTATIONS_SUCCESS,payload: {history,job,states,},});});} catch (error) {dispatch({type: AnnotationActionTypes.UPLOAD_JOB_ANNOTATIONS_FAILED,payload: {job,error,},});}};
}
export function collectStatisticsAsync(sessionInstance: any): ThunkAction {
return async (dispatch: ActionCreator
const data = await sessionInstance.annotations.statistics();dispatch({type: AnnotationActionTypes.COLLECT_STATISTICS_SUCCESS,payload: {data,},});} catch (error) {dispatch({type: AnnotationActionTypes.COLLECT_STATISTICS_FAILED,payload: {error,},});}};
}
export function showStatistics(visible: boolean): AnyAction { return { type: AnnotationActionTypes.SWITCH_SHOWING_STATISTICS, payload: { visible, }, }; } export function showFilters(visible: boolean): AnyAction { return { type: AnnotationActionTypes.SWITCH_SHOWING_FILTERS, payload: { visible, }, }; }
export function propagateObjectAsync(sessionInstance: any, objectState: any, from: number, to: number): ThunkAction {
return async (dispatch: ActionCreator
await sessionInstance.logger.log(LogType.propagateObject, { count: to - from + 1 });const states = [];for (let frame = from; frame <= to; frame++) {copy.frame = frame;const newState = new cvat.classes.ObjectState(copy);states.push(newState);}await sessionInstance.annotations.put(states);const history = await sessionInstance.actions.get();dispatch({type: AnnotationActionTypes.PROPAGATE_OBJECT_SUCCESS,payload: {objectState,history,},});} catch (error) {dispatch({type: AnnotationActionTypes.PROPAGATE_OBJECT_FAILED,payload: {error,},});}};
}
export function propagateObject(objectState: any | null): AnyAction { return { type: AnnotationActionTypes.PROPAGATE_OBJECT, payload: { objectState, }, }; }
export function changePropagateFrames(frames: number): AnyAction { return { type: AnnotationActionTypes.CHANGE_PROPAGATE_FRAMES, payload: { frames, }, }; }
export function removeObjectAsync(sessionInstance: any, objectState: any, force: boolean): ThunkAction {
return async (dispatch: ActionCreator
const removed = await objectState.delete(frame, force);
const history = await sessionInstance.actions.get();
if (removed) {
dispatch({
type: AnnotationActionTypes.REMOVE_OBJECT_SUCCESS,
payload: {
objectState,
history,
},
});
} else {
throw new Error('Could not remove the locked object');
}
} catch (error) {
dispatch({
type: AnnotationActionTypes.REMOVE_OBJECT_FAILED,
payload: {
error,
},
});
}
};
}
export function editShape(enabled: boolean): AnyAction { return { type: AnnotationActionTypes.EDIT_SHAPE, payload: { enabled, }, }; }
export function copyShape(objectState: any): AnyAction { const job = getStore().getState().annotation.job.instance; job.logger.log(LogType.copyObject, { count: 1 });
return {
type: AnnotationActionTypes.COPY_SHAPE,
payload: {
objectState,
},
};
}
export function activateObject(activatedStateID: number | null, activatedAttributeID: number | null): AnyAction { return { type: AnnotationActionTypes.ACTIVATE_OBJECT, payload: { activatedStateID, activatedAttributeID, }, }; }
export function collapseSidebar(): AnyAction { return { type: AnnotationActionTypes.COLLAPSE_SIDEBAR, payload: {}, }; }
export function collapseAppearance(): AnyAction { return { type: AnnotationActionTypes.COLLAPSE_APPEARANCE, payload: {}, }; }
export function collapseObjectItems(states: any[], collapsed: boolean): AnyAction { return { type: AnnotationActionTypes.COLLAPSE_OBJECT_ITEMS, payload: { states, collapsed, }, }; }
export function switchPlay(playing: boolean): AnyAction { return { type: AnnotationActionTypes.SWITCH_PLAY, payload: { playing, }, }; }
export function getPredictionsAsync(): ThunkAction {
return async (dispatch: ActionCreator
const {
filters, frame, showAllInterpolationTracks, jobInstance: job,
} = receiveAnnotationsParameters();
if (!enabled || currentStates.length || annotatedFrames.includes(frame)) return;
dispatch({
type: AnnotationActionTypes.GET_PREDICTIONS,
payload: {},
});
let annotations = [];
try {
annotations = await job.predictor.predict(frame);
// current frame could be changed during a request above, need to fetch it from store again
const { number: currentFrame } = getStore().getState().annotation.player.frame;
if (frame !== currentFrame || annotations === null) {
// another request has already been sent or user went to another frame
// we do not need dispatch predictions success action
return;
}
annotations = annotations.map(
(data: any): any => new cvat.classes.ObjectState({
shapeType: data.type,
label: job.task.labels.filter((label: any): boolean => label.id === data.label)[0],
points: data.points,
objectType: ObjectType.SHAPE,
frame,
occluded: false,
source: 'auto',
attributes: {},
zOrder: curZOrder,
}),
);
dispatch({
type: AnnotationActionTypes.GET_PREDICTIONS_SUCCESS,
payload: { frame },
});
} catch (error) {
dispatch({
type: AnnotationActionTypes.GET_PREDICTIONS_FAILED,
payload: {
error,
},
});
}
try {
await job.annotations.put(annotations);
const states = await job.annotations.get(frame, showAllInterpolationTracks, filters);
const history = await job.actions.get();
dispatch({
type: AnnotationActionTypes.CREATE_ANNOTATIONS_SUCCESS,
payload: {
states,
history,
},
});
} catch (error) {
dispatch({
type: AnnotationActionTypes.CREATE_ANNOTATIONS_FAILED,
payload: {
error,
},
});
}
};
}
export function changeFrameAsync(
toFrame: number,
fillBuffer?: boolean,
frameStep?: number,
forceUpdate?: boolean,
): ThunkAction {
return async (dispatch: ActionCreator
try {
if (toFrame < job.startFrame || toFrame > job.stopFrame) {
throw Error(`Required frame ${toFrame} is out of the current job`);
}
if (toFrame === frame && !forceUpdate) {
dispatch({
type: AnnotationActionTypes.CHANGE_FRAME_SUCCESS,
payload: {
number: state.annotation.player.frame.number,
data: state.annotation.player.frame.data,
filename: state.annotation.player.frame.filename,
hasRelatedContext: state.annotation.player.frame.hasRelatedContext,
delay: state.annotation.player.frame.delay,
changeTime: state.annotation.player.frame.changeTime,
states: state.annotation.annotations.states,
minZ: state.annotation.annotations.zLayer.min,
maxZ: state.annotation.annotations.zLayer.max,
curZ: state.annotation.annotations.zLayer.cur,
},
});
return;
}
// Start async requests
dispatch({
type: AnnotationActionTypes.CHANGE_FRAME,
payload: {},
});
await job.logger.log(LogType.changeFrame, {
from: frame,
to: toFrame,
});
const data = await job.frames.get(toFrame, fillBuffer, frameStep);
const states = await job.annotations.get(toFrame, showAllInterpolationTracks, filters);
const [minZ, maxZ] = computeZRange(states);
const currentTime = new Date().getTime();
let frameSpeed;
switch (state.settings.player.frameSpeed) {
case FrameSpeed.Fast: {
frameSpeed = (FrameSpeed.Fast as number) / 2;
break;
}
case FrameSpeed.Fastest: {
frameSpeed = (FrameSpeed.Fastest as number) / 3;
break;
}
default: {
frameSpeed = state.settings.player.frameSpeed as number;
}
}
const delay = Math.max(
0,
Math.round(1000 / frameSpeed) - currentTime + (state.annotation.player.frame.changeTime as number),
);
dispatch({
type: AnnotationActionTypes.CHANGE_FRAME_SUCCESS,
payload: {
number: toFrame,
data,
filename: data.filename,
hasRelatedContext: data.hasRelatedContext,
states,
minZ,
maxZ,
curZ: maxZ,
changeTime: currentTime + delay,
delay,
},
});
dispatch(getPredictionsAsync());
} catch (error) {
if (error !== 'not needed') {
dispatch({
type: AnnotationActionTypes.CHANGE_FRAME_FAILED,
payload: {
number: toFrame,
error,
},
});
}
}
};
}
export function undoActionAsync(sessionInstance: any, frame: number): ThunkAction {
return async (dispatch: ActionCreator
// TODO: use affected IDs as an optimization
const [undo] = state.annotation.annotations.history.undo.slice(-1);
const undoLog = await sessionInstance.logger.log(
LogType.undoAction,
{
name: undo[0],
frame: undo[1],
count: 1,
},
true,
);
await sessionInstance.actions.undo();
const history = await sessionInstance.actions.get();
const states = await sessionInstance.annotations.get(frame, showAllInterpolationTracks, filters);
const [minZ, maxZ] = computeZRange(states);
await undoLog.close();
dispatch({
type: AnnotationActionTypes.UNDO_ACTION_SUCCESS,
payload: {
history,
states,
minZ,
maxZ,
},
});
const undoOnFrame = undo[1];
if (frame !== undoOnFrame) {
dispatch(changeFrameAsync(undoOnFrame));
}
} catch (error) {
dispatch({
type: AnnotationActionTypes.UNDO_ACTION_FAILED,
payload: {
error,
},
});
}
};
}
export function redoActionAsync(sessionInstance: any, frame: number): ThunkAction {
return async (dispatch: ActionCreator
// TODO: use affected IDs as an optimization
const [redo] = state.annotation.annotations.history.redo.slice(-1);
const redoLog = await sessionInstance.logger.log(
LogType.redoAction,
{
name: redo[0],
frame: redo[1],
count: 1,
},
true,
);
await sessionInstance.actions.redo();
const history = await sessionInstance.actions.get();
const states = await sessionInstance.annotations.get(frame, showAllInterpolationTracks, filters);
const [minZ, maxZ] = computeZRange(states);
await redoLog.close();
dispatch({
type: AnnotationActionTypes.REDO_ACTION_SUCCESS,
payload: {
history,
states,
minZ,
maxZ,
},
});
const redoOnFrame = redo[1];
if (frame !== redoOnFrame) {
dispatch(changeFrameAsync(redoOnFrame));
}
} catch (error) {
dispatch({
type: AnnotationActionTypes.REDO_ACTION_FAILED,
payload: {
error,
},
});
}
};
}
export function rotateCurrentFrame(rotation: Rotation): AnyAction { const state: CombinedState = getStore().getState(); const { annotation: { player: { frame: { number: frameNumber }, frameAngles, }, job: { instance: job, instance: { startFrame }, }, }, settings: { player: { rotateAll }, }, } = state;
const frameAngle = (frameAngles[frameNumber - startFrame] + (rotation === Rotation.CLOCKWISE90 ? 90 : 270)) % 360;
job.logger.log(LogType.rotateImage, { angle: frameAngle });
return {
type: AnnotationActionTypes.ROTATE_FRAME,
payload: {
offset: frameNumber - state.annotation.job.instance.startFrame,
angle: frameAngle,
rotateAll,
},
};
}
export function dragCanvas(enabled: boolean): AnyAction { return { type: AnnotationActionTypes.DRAG_CANVAS, payload: { enabled, }, }; }
export function zoomCanvas(enabled: boolean): AnyAction { return { type: AnnotationActionTypes.ZOOM_CANVAS, payload: { enabled, }, }; }
export function resetCanvas(): AnyAction { return { type: AnnotationActionTypes.RESET_CANVAS, payload: {}, }; }
export function confirmCanvasReady(): AnyAction { return { type: AnnotationActionTypes.CONFIRM_CANVAS_READY, payload: {}, }; }
export function closeJob(): ThunkAction {
return async (dispatch: ActionCreator
dispatch({
type: AnnotationActionTypes.CLOSE_JOB,
});
};
}
export function getJobAsync(tid: number, jid: number, initialFrame: number, initialFilters: object[]): ThunkAction {
return async (dispatch: ActionCreator
dispatch({
type: AnnotationActionTypes.GET_JOB,
payload: {
requestedId: jid,
},
});
const loadJobEvent = await logger.log(
LogType.loadJob,
{
task_id: tid,
job_id: jid,
},
true,
);
// Check state if the task is already there
let task = state.tasks.current
.filter((_task: Task) => _task.instance.id === tid)
.map((_task: Task) => _task.instance)[0];
// If there aren't the task, get it from the server
if (!task) {
[task] = await cvat.tasks.get({ id: tid });
}
// Finally get the job from the task
const job = task.jobs.filter((_job: any) => _job.id === jid)[0];
if (!job) {
throw new Error(`Task ${tid} doesn't contain the job ${jid}`);
}
const frameNumber = Math.max(Math.min(job.stopFrame, initialFrame), job.startFrame);
const frameData = await job.frames.get(frameNumber);
// call first getting of frame data before rendering interface
// to load and decode first chunk
try {
await frameData.data();
} catch (error) {
dispatch({
type: AnnotationActionTypes.GET_DATA_FAILED,
payload: {
error,
},
});
}
const states = await job.annotations.get(frameNumber, showAllInterpolationTracks, filters);
const issues = await job.issues();
const reviews = await job.reviews();
const [minZ, maxZ] = computeZRange(states);
const colors = [...cvat.enums.colors];
loadJobEvent.close(await jobInfoGenerator(job));
const openTime = Date.now();
dispatch({
type: AnnotationActionTypes.GET_JOB_SUCCESS,
payload: {
openTime,
job,
issues,
reviews,
states,
frameNumber,
frameFilename: frameData.filename,
frameHasRelatedContext: frameData.hasRelatedContext,
frameData,
colors,
filters,
minZ,
maxZ,
},
});
if (job.task.dimension === DimensionType.DIM_3D) {
const workspace = Workspace.STANDARD3D;
dispatch(changeWorkspace(workspace));
}
const updatePredictorStatus = async (): Promise<void> => {
// get current job
const currentState: CombinedState = getStore().getState();
const { openTime: currentOpenTime, instance: currentJob } = currentState.annotation.job;
if (currentJob === null || currentJob.id !== job.id || currentOpenTime !== openTime) {
// the job was closed, changed or reopened
return;
}
try {
const status = await job.predictor.status();
dispatch({
type: AnnotationActionTypes.UPDATE_PREDICTOR_STATE,
payload: status,
});
setTimeout(updatePredictorStatus, 60 * 1000);
} catch (error) {
dispatch({
type: AnnotationActionTypes.UPDATE_PREDICTOR_STATE,
payload: { error },
});
setTimeout(updatePredictorStatus, 20 * 1000);
}
};
if (state.plugins.list.PREDICT && job.task.projectId !== null) {
updatePredictorStatus();
}
dispatch(changeFrameAsync(frameNumber, false));
} catch (error) {
dispatch({
type: AnnotationActionTypes.GET_JOB_FAILED,
payload: {
error,
},
});
}
};
}
export function saveAnnotationsAsync(sessionInstance: any, afterSave?: () => void): ThunkAction {
return async (dispatch: ActionCreator
dispatch({
type: AnnotationActionTypes.SAVE_ANNOTATIONS,
payload: {},
});
try {
const saveJobEvent = await sessionInstance.logger.log(LogType.saveJob, {}, true);
await sessionInstance.annotations.save((status: string) => {
dispatch({
type: AnnotationActionTypes.SAVE_UPDATE_ANNOTATIONS_STATUS,
payload: {
status,
},
});
});
await saveJobEvent.close();
await sessionInstance.logger.log(LogType.sendTaskInfo, await jobInfoGenerator(sessionInstance));
dispatch(saveLogsAsync());
const { frame } = receiveAnnotationsParameters();
const states = await sessionInstance.annotations.get(frame, showAllInterpolationTracks, filters);
if (typeof afterSave === 'function') {
afterSave();
}
dispatch({
type: AnnotationActionTypes.SAVE_ANNOTATIONS_SUCCESS,
payload: {
states,
},
});
} catch (error) {
dispatch({
type: AnnotationActionTypes.SAVE_ANNOTATIONS_FAILED,
payload: {
error,
},
});
}
};
}
// used to reproduce the latest drawing (in case of tags just creating) by using N export function rememberObject(createParams: { activeObjectType?: ObjectType; activeLabelID?: number; activeShapeType?: ShapeType; activeNumOfPoints?: number; activeRectDrawingMethod?: RectDrawingMethod; activeCircleDrawingMethod?: CircleDrawingMethod; activeCuboidDrawingMethod?: CuboidDrawingMethod; }): AnyAction { return { type: AnnotationActionTypes.REMEMBER_CREATED_OBJECT, payload: createParams, }; }
export function shapeDrawn(): AnyAction { return { type: AnnotationActionTypes.SHAPE_DRAWN, payload: {}, }; }
export function selectIssuePosition(enabled: boolean): AnyAction { return { type: AnnotationActionTypes.SELECT_ISSUE_POSITION, payload: { enabled, }, }; }
export function mergeObjects(enabled: boolean): AnyAction { return { type: AnnotationActionTypes.MERGE_OBJECTS, payload: { enabled, }, }; }
export function groupObjects(enabled: boolean): AnyAction { return { type: AnnotationActionTypes.GROUP_OBJECTS, payload: { enabled, }, }; }
export function splitTrack(enabled: boolean): AnyAction { return { type: AnnotationActionTypes.SPLIT_TRACK, payload: { enabled, }, }; }
export function updateAnnotationsAsync(statesToUpdate: any[]): ThunkAction {
return async (dispatch: ActionCreator
try {
if (statesToUpdate.some((state: any): boolean => state.updateFlags.zOrder)) {
// deactivate object to visualize changes immediately (UX)
dispatch(activateObject(null, null));
}
const promises = statesToUpdate.map((objectState: any): Promise<any> => objectState.save());
const states = await Promise.all(promises);
const history = await jobInstance.actions.get();
const [minZ, maxZ] = computeZRange(states);
dispatch({
type: AnnotationActionTypes.UPDATE_ANNOTATIONS_SUCCESS,
payload: {
states,
history,
minZ,
maxZ,
},
});
} catch (error) {
const states = await jobInstance.annotations.get(frame, showAllInterpolationTracks, filters);
dispatch({
type: AnnotationActionTypes.UPDATE_ANNOTATIONS_FAILED,
payload: {
error,
states,
},
});
}
};
}
export function createAnnotationsAsync(sessionInstance: any, frame: number, statesToCreate: any[]): ThunkAction {
return async (dispatch: ActionCreator
dispatch({
type: AnnotationActionTypes.CREATE_ANNOTATIONS_SUCCESS,
payload: {
states,
history,
},
});
} catch (error) {
dispatch({
type: AnnotationActionTypes.CREATE_ANNOTATIONS_FAILED,
payload: {
error,
},
});
}
};
}
export function mergeAnnotationsAsync(sessionInstance: any, frame: number, statesToMerge: any[]): ThunkAction {
return async (dispatch: ActionCreator
dispatch({
type: AnnotationActionTypes.MERGE_ANNOTATIONS_SUCCESS,
payload: {
states,
history,
},
});
} catch (error) {
dispatch({
type: AnnotationActionTypes.MERGE_ANNOTATIONS_FAILED,
payload: {
error,
},
});
}
};
}
export function resetAnnotationsGroup(): AnyAction { return { type: AnnotationActionTypes.RESET_ANNOTATIONS_GROUP, payload: {}, }; }
export function groupAnnotationsAsync(sessionInstance: any, frame: number, statesToGroup: any[]): ThunkAction {
return async (dispatch: ActionCreator
// The action below set resetFlag to false
dispatch({
type: AnnotationActionTypes.GROUP_ANNOTATIONS,
payload: {},
});
await sessionInstance.annotations.group(statesToGroup, reset);
const states = await sessionInstance.annotations.get(frame, showAllInterpolationTracks, filters);
const history = await sessionInstance.actions.get();
dispatch({
type: AnnotationActionTypes.GROUP_ANNOTATIONS_SUCCESS,
payload: {
states,
history,
},
});
} catch (error) {
dispatch({
type: AnnotationActionTypes.GROUP_ANNOTATIONS_FAILED,
payload: {
error,
},
});
}
};
}
export function splitAnnotationsAsync(sessionInstance: any, frame: number, stateToSplit: any): ThunkAction {
return async (dispatch: ActionCreator
dispatch({
type: AnnotationActionTypes.SPLIT_ANNOTATIONS_SUCCESS,
payload: {
states,
history,
},
});
} catch (error) {
dispatch({
type: AnnotationActionTypes.SPLIT_ANNOTATIONS_FAILED,
payload: {
error,
},
});
}
};
}
export function changeGroupColorAsync(group: number, color: string): ThunkAction {
return async (dispatch: ActionCreator
export function searchAnnotationsAsync(sessionInstance: any, frameFrom: number, frameTo: number): ThunkAction {
return async (dispatch: ActionCreator
export function searchEmptyFrameAsync(sessionInstance: any, frameFrom: number, frameTo: number): ThunkAction {
return async (dispatch: ActionCreator
export function pasteShapeAsync(): ThunkAction {
return async (dispatch: ActionCreator
if (initialState) {
let activeControl = ActiveControl.CURSOR;
if (initialState.shapeType === ShapeType.RECTANGLE) {
activeControl = ActiveControl.DRAW_RECTANGLE;
} else if (initialState.shapeType === ShapeType.POINTS) {
activeControl = ActiveControl.DRAW_POINTS;
} else if (initialState.shapeType === ShapeType.POLYGON) {
activeControl = ActiveControl.DRAW_POLYGON;
} else if (initialState.shapeType === ShapeType.POLYLINE) {
activeControl = ActiveControl.DRAW_POLYLINE;
} else if (initialState.shapeType === ShapeType.CUBOID) {
activeControl = ActiveControl.DRAW_CUBOID;
}
dispatch({
type: AnnotationActionTypes.PASTE_SHAPE,
payload: {
activeControl,
},
});
if (canvasInstance instanceof Canvas) {
canvasInstance.cancel();
}
if (initialState.objectType === ObjectType.TAG) {
const objectState = new cvat.classes.ObjectState({
objectType: ObjectType.TAG,
label: initialState.label,
attributes: initialState.attributes,
frame: frameNumber,
});
dispatch(createAnnotationsAsync(jobInstance, frameNumber, [objectState]));
} else {
canvasInstance.draw({
enabled: true,
initialState,
});
}
}
};
}
export function interactWithCanvas(activeInteractor: Model | OpenCVTool, activeLabelID: number): AnyAction { return { type: AnnotationActionTypes.INTERACT_WITH_CANVAS, payload: { activeInteractor, activeLabelID, }, }; }
export function repeatDrawShapeAsync(): ThunkAction {
return async (dispatch: ActionCreator
let activeControl = ActiveControl.CURSOR;
if (activeInteractor && canvasInstance instanceof Canvas) {
if (activeInteractor.type === 'tracker') {
canvasInstance.interact({
enabled: true,
shapeType: 'rectangle',
});
dispatch(interactWithCanvas(activeInteractor, activeLabelID));
} else {
canvasInstance.interact({
enabled: true,
shapeType: 'points',
...activeInteractor.params.canvas,
});
dispatch(interactWithCanvas(activeInteractor, activeLabelID));
}
return;
}
if (activeShapeType === ShapeType.RECTANGLE) {
activeControl = ActiveControl.DRAW_RECTANGLE;
} else if (activeShapeType === ShapeType.POINTS) {
activeControl = ActiveControl.DRAW_POINTS;
} else if (activeShapeType === ShapeType.POLYGON) {
activeControl = ActiveControl.DRAW_POLYGON;
} else if (activeShapeType === ShapeType.POLYLINE) {
activeControl = ActiveControl.DRAW_POLYLINE;
} else if (activeShapeType === ShapeType.CUBOID) {
activeControl = ActiveControl.DRAW_CUBOID;
}
dispatch({
type: AnnotationActionTypes.REPEAT_DRAW_SHAPE,
payload: {
activeControl,
},
});
if (canvasInstance instanceof Canvas) {
canvasInstance.cancel();
}
if (activeObjectType === ObjectType.TAG) {
const objectState = new cvat.classes.ObjectState({
objectType: ObjectType.TAG,
label: labels.filter((label: any) => label.id === activeLabelID)[0],
frame: frameNumber,
});
dispatch(createAnnotationsAsync(jobInstance, frameNumber, [objectState]));
} else {
canvasInstance.draw({
enabled: true,
rectDrawingMethod: activeRectDrawingMethod,
circleDrawingMethod: activeCircleDrawingMethod,
cuboidDrawingMethod: activeCuboidDrawingMethod,
numberOfPoints: activeNumOfPoints,
shapeType: activeShapeType,
crosshair: [ShapeType.RECTANGLE, ShapeType.CUBOID].includes(activeShapeType),
});
}
};
}
export function redrawShapeAsync(): ThunkAction {
return async (dispatch: ActionCreator
if (activatedStateID !== null) {
const [state] = states.filter((_state: any): boolean => _state.clientID === activatedStateID);
if (state && state.objectType !== ObjectType.TAG) {
let activeControl = ActiveControl.CURSOR;
if (state.shapeType === ShapeType.RECTANGLE) {
activeControl = ActiveControl.DRAW_RECTANGLE;
} else if (state.shapeType === ShapeType.POINTS) {
activeControl = ActiveControl.DRAW_POINTS;
} else if (state.shapeType === ShapeType.POLYGON) {
activeControl = ActiveControl.DRAW_POLYGON;
} else if (state.shapeType === ShapeType.POLYLINE) {
activeControl = ActiveControl.DRAW_POLYLINE;
} else if (state.shapeType === ShapeType.CUBOID) {
activeControl = ActiveControl.DRAW_CUBOID;
}
dispatch({
type: AnnotationActionTypes.REPEAT_DRAW_SHAPE,
payload: {
activeControl,
},
});
if (canvasInstance instanceof Canvas) {
canvasInstance.cancel();
}
canvasInstance.draw({
enabled: true,
redraw: activatedStateID,
shapeType: state.shapeType,
crosshair: [ShapeType.RECTANGLE, ShapeType.CUBOID].includes(state.shapeType),
});
}
}
};
}
export function switchRequestReviewDialog(visible: boolean): AnyAction { return { type: AnnotationActionTypes.SWITCH_REQUEST_REVIEW_DIALOG, payload: { visible, }, }; }
export function switchSubmitReviewDialog(visible: boolean): AnyAction { return { type: AnnotationActionTypes.SWITCH_SUBMIT_REVIEW_DIALOG, payload: { visible, }, }; }
export function setForceExitAnnotationFlag(forceExit: boolean): AnyAction { return { type: AnnotationActionTypes.SET_FORCE_EXIT_ANNOTATION_PAGE_FLAG, payload: { forceExit, }, }; }
export function switchPredictor(predictorEnabled: boolean): AnyAction { return { type: AnnotationActionTypes.UPDATE_PREDICTOR_STATE, payload: { enabled: predictorEnabled, }, }; } export function hideShowContextImage(hidden: boolean): AnyAction { return { type: AnnotationActionTypes.HIDE_SHOW_CONTEXT_IMAGE, payload: { hidden, }, }; }
export function getContextImageAsync(): ThunkAction {
return async (dispatch: ActionCreator
try {
dispatch({
type: AnnotationActionTypes.GET_CONTEXT_IMAGE,
payload: {},
});
const contextImageData = await job.frames.contextImage(job.task.id, frameNumber);
dispatch({
type: AnnotationActionTypes.GET_CONTEXT_IMAGE_SUCCESS,
payload: { contextImageData },
});
} catch (error) {
dispatch({
type: AnnotationActionTypes.GET_CONTEXT_IMAGE_FAILED,
payload: { error },
});
}
};
}
export function switchNavigationBlocked(navigationBlocked: boolean): AnyAction { return { type: AnnotationActionTypes.SWITCH_NAVIGATION_BLOCKED, payload: { navigationBlocked, }, }; }
18. draw-shape-popover.tsx(src/containers)
// Copyright (C) 2020-2021 Intel Corporation // // SPDX-License-Identifier: MIT
import React from ‘react’; import { connect } from ‘react-redux’; import { RadioChangeEvent } from ‘antd/lib/radio’;
import { CombinedState, ShapeType, ObjectType } from ‘reducers/interfaces’; import { rememberObject } from ‘actions/annotation-actions’; import { Canvas, RectDrawingMethod, CircleDrawingMethod, CuboidDrawingMethod, } from ‘cvat-canvas-wrapper’; import { Canvas3d } from ‘cvat-canvas3d-wrapper’; import DrawShapePopoverComponent from ‘components/annotation-page/standard-workspace/controls-side-bar/draw-shape-popover’;
interface OwnProps { shapeType: ShapeType; }
interface DispatchToProps { onDrawStart( shapeType: ShapeType, labelID: number, objectType: ObjectType, points?: number, rectDrawingMethod?: RectDrawingMethod, circleDrawingMethod?: CircleDrawingMethod, cuboidDrawingMethod?: CuboidDrawingMethod, ): void; }
interface StateToProps {
normalizedKeyMap: Record
function mapDispatchToProps(dispatch: any): DispatchToProps { return { onDrawStart( shapeType: ShapeType, labelID: number, objectType: ObjectType, points?: number, rectDrawingMethod?: RectDrawingMethod, circleDrawingMethod?: CircleDrawingMethod, cuboidDrawingMethod?: CuboidDrawingMethod, ): void { dispatch( rememberObject({ activeObjectType: objectType, activeShapeType: shapeType, activeLabelID: labelID, activeNumOfPoints: points, activeRectDrawingMethod: rectDrawingMethod, activeCircleDrawingMethod: circleDrawingMethod, activeCuboidDrawingMethod: cuboidDrawingMethod, }), ); }, }; }
function mapStateToProps(state: CombinedState, own: OwnProps): StateToProps { const { annotation: { canvas: { instance: canvasInstance }, job: { labels, instance: jobInstance }, }, shortcuts: { normalizedKeyMap }, } = state;
return {
...own,
canvasInstance,
labels,
normalizedKeyMap,
jobInstance,
};
}
type Props = StateToProps & DispatchToProps;
interface State { rectDrawingMethod?: RectDrawingMethod; circleDrawingMethod?: CircleDrawingMethod; cuboidDrawingMethod?: CuboidDrawingMethod; numberOfPoints?: number; selectedLabelID: number; }
class DrawShapePopoverContainer extends React.PureComponent
constructor(props: Props) {
super(props);
const { shapeType } = props;
const defaultLabelID = props.labels.length ? props.labels[0].id : null;
const defaultRectDrawingMethod = RectDrawingMethod.CLASSIC;
const defaultCuboidDrawingMethod = CuboidDrawingMethod.CLASSIC;
this.state = {
selectedLabelID: defaultLabelID,
rectDrawingMethod: shapeType === ShapeType.RECTANGLE ? defaultRectDrawingMethod : undefined,
circleDrawingMethod: CircleDrawingMethod.CLASSIC,
cuboidDrawingMethod: shapeType === ShapeType.CUBOID ? defaultCuboidDrawingMethod : undefined,
};
if (shapeType === ShapeType.POLYGON) {
this.minimumPoints = 3;
}
if (shapeType === ShapeType.POLYLINE) {
this.minimumPoints = 2;
}
if (shapeType === ShapeType.POINTS) {
this.minimumPoints = 1;
}
}
private onDraw(objectType: ObjectType): void {
const { canvasInstance, shapeType, onDrawStart } = this.props;
const {
rectDrawingMethod, circleDrawingMethod, cuboidDrawingMethod, numberOfPoints, selectedLabelID,
} = this.state;
canvasInstance.cancel();
canvasInstance.draw({
enabled: true,
rectDrawingMethod,
circleDrawingMethod,
cuboidDrawingMethod,
numberOfPoints,
shapeType,
crosshair: [ShapeType.RECTANGLE, ShapeType.CUBOID].includes(shapeType),
});
// eslint-disable-next-line max-len
onDrawStart(shapeType, selectedLabelID, objectType, numberOfPoints, rectDrawingMethod, circleDrawingMethod, cuboidDrawingMethod);
}
private onChangeRectDrawingMethod = (event: RadioChangeEvent): void => {
this.setState({
rectDrawingMethod: event.target.value,
});
};
private onChangeCircleDrawingMethod = (event: CircleDrawingMethod): void => {
this.setState({
circleDrawingMethod: event.target.value,
});
};
private onChangeCuboidDrawingMethod = (event: RadioChangeEvent): void => {
this.setState({
cuboidDrawingMethod: event.target.value,
});
};
private onDrawShape = (): void => {
this.onDraw(ObjectType.SHAPE);
};
private onDrawTrack = (): void => {
this.onDraw(ObjectType.TRACK);
};
private onChangePoints = (value: number | undefined): void => {
this.setState({
numberOfPoints: value,
});
};
private onChangeLabel = (value: any): void => {
this.setState({
selectedLabelID: value.id,
});
};
public render(): JSX.Element {
const {
rectDrawingMethod, circleDrawingMethod, cuboidDrawingMethod, selectedLabelID, numberOfPoints,
} = this.state;
const {
normalizedKeyMap, labels, shapeType, jobInstance,
} = this.props;
return (
<DrawShapePopoverComponent
jobInstance={jobInstance}
labels={labels}
shapeType={shapeType}
minimumPoints={this.minimumPoints}
selectedLabelID={selectedLabelID}
numberOfPoints={numberOfPoints}
rectDrawingMethod={rectDrawingMethod}
circleDrawingMethod={circleDrawingMethod}
cuboidDrawingMethod={cuboidDrawingMethod}
repeatShapeShortcut={normalizedKeyMap.SWITCH_DRAW_MODE}
onChangeLabel={this.onChangeLabel}
onChangePoints={this.onChangePoints}
onChangeRectDrawingMethod={this.onChangeRectDrawingMethod}
onChangeCircleDrawingMethod={this.onChangeCircleDrawingMethod}
onChangeCuboidDrawingMethod={this.onChangeCuboidDrawingMethod}
onDrawTrack={this.onDrawTrack}
onDrawShape={this.onDrawShape}
/>
);
}
}
export default connect(mapStateToProps, mapDispatchToProps)(DrawShapePopoverContainer);
19. interfaces.ts
// Copyright (C) 2020-2021 Intel Corporation // // SPDX-License-Identifier: MIT
import { Canvas3d } from ‘cvat-canvas3d/src/typescript/canvas3d’; import { Canvas, RectDrawingMethod, CuboidDrawingMethod, CircleDrawingMethod, } from ‘cvat-canvas-wrapper’; import { IntelligentScissors } from ‘utils/opencv-wrapper/intelligent-scissors’; import { KeyMap } from ‘utils/mousetrap-react’;
export type StringObject = {
[index: string]: string;
};
export interface AuthState { initialized: boolean; fetching: boolean; user: any; authActionsFetching: boolean; authActionsInitialized: boolean; showChangePasswordDialog: boolean; allowChangePassword: boolean; allowResetPassword: boolean; }
export interface ProjectsQuery { page: number; id: number | null; search: string | null; owner: string | null; name: string | null; status: string | null; assignee: string | null; [key: string]: string | boolean | number | null | undefined; }
export interface Project { instance: any; preview: string; }
export interface ProjectsState { initialized: boolean; fetching: boolean; count: number; current: Project[]; gettingQuery: ProjectsQuery; activities: { creates: { id: null | number; error: string; }; deletes: { [projectId: number]: boolean; // deleted (deleting if in dictionary) }; }; }
export interface TasksQuery { page: number; id: number | null; search: string | null; owner: string | null; assignee: string | null; name: string | null; status: string | null; mode: string | null; [key: string]: string | number | null; }
export interface Task { instance: any; // cvat-core instance preview: string; }
export interface TasksState { importing: boolean; initialized: boolean; fetching: boolean; updating: boolean; hideEmpty: boolean; moveTask: { modalVisible: boolean; taskId: number | null; }; gettingQuery: TasksQuery; count: number; current: Task[]; activities: { loads: { // only one loading simultaneously [tid: number]: string; // loader name }; deletes: { [tid: number]: boolean; // deleted (deleting if in dictionary) }; creates: { taskId: number | null; status: string; error: string; }; backups: {
[tid: number]: boolean;
};
};
}
export interface ExportState { tasks: {
[tid: number]: string[];
};
projects: {
[pid: number]: string[];
};
instance: any;
modalVisible: boolean;
}
export interface FormatsState { annotationFormats: any; fetching: boolean; initialized: boolean; }
export interface CloudStoragesQuery { page: number; id: number | null; search: string | null; owner: string | null; displayName: string | null; description: string | null; resourceName: string | null; providerType: string | null; credentialsType: string | null; [key: string]: string | number | null | undefined; }
interface CloudStorageAdditional {
fetching: boolean;
initialized: boolean;
status: string | null;
preview: string;
}
type CloudStorageStatus = Pick
export type CloudStorage = any;
export interface CloudStoragesState { initialized: boolean; fetching: boolean; count: number; current: CloudStorage[]; statuses: {
[index: number]: CloudStorageStatus;
};
previews: {
[index: number]: CloudStoragePreview;
};
gettingQuery: CloudStoragesQuery;
activities: {
creates: {
attaching: boolean;
id: null | number;
error: string;
};
updates: {
updating: boolean;
cloudStorageID: null | number;
error: string;
};
deletes: {
[cloudStorageID: number]: boolean;
};
contentLoads: {
cloudStorageID: number | null;
content: any | null;
fetching: boolean;
error: string;
};
};
}
export enum SupportedPlugins { GIT_INTEGRATION = ‘GIT_INTEGRATION’, ANALYTICS = ‘ANALYTICS’, MODELS = ‘MODELS’, PREDICT = ‘PREDICT’, }
export type PluginsList = {
[name in SupportedPlugins]: boolean;
};
export interface PluginsState { fetching: boolean; initialized: boolean; list: PluginsList; }
export interface AboutState { server: any; packageVersion: { core: string; canvas: string; ui: string; }; fetching: boolean; initialized: boolean; }
export interface UserAgreement { name: string; displayText: string; url: string; required: boolean; }
export interface UserAgreementsState { list: UserAgreement[]; fetching: boolean; initialized: boolean; }
export interface ShareFileInfo { // get this data from cvat-core name: string; type: ‘DIR’ | ‘REG’; }
export interface ShareItem { name: string; type: ‘DIR’ | ‘REG’; children: ShareItem[]; }
export interface ShareState { root: ShareItem; }
export interface Model {
id: string;
name: string;
labels: string[];
framework: string;
description: string;
type: string;
onChangeToolsBlockerState: (event: string) => void;
tip: {
message: string;
gif: string;
};
params: {
canvas: Record
export type OpenCVTool = IntelligentScissors;
export interface ToolsBlockerState { algorithmsLocked?: boolean; buttonVisible?: boolean; }
export enum TaskStatus { ANNOTATION = ‘annotation’, REVIEW = ‘validation’, COMPLETED = ‘completed’, }
export enum RQStatus { unknown = ‘unknown’, queued = ‘queued’, started = ‘started’, finished = ‘finished’, failed = ‘failed’, }
export interface ActiveInference { status: RQStatus; progress: number; error: string; id: string; }
export interface ModelsState { initialized: boolean; fetching: boolean; creatingStatus: string; interactors: Model[]; detectors: Model[]; trackers: Model[]; reid: Model[]; inferences: {
[index: number]: ActiveInference;
};
visibleRunWindows: boolean;
activeRunTask: any;
}
export interface ErrorState { message: string; reason: string; className?: string; }
export interface NotificationsState { errors: { auth: { authorized: null | ErrorState; login: null | ErrorState; logout: null | ErrorState; register: null | ErrorState; changePassword: null | ErrorState; requestPasswordReset: null | ErrorState; resetPassword: null | ErrorState; loadAuthActions: null | ErrorState; }; projects: { fetching: null | ErrorState; updating: null | ErrorState; deleting: null | ErrorState; creating: null | ErrorState; }; tasks: { fetching: null | ErrorState; updating: null | ErrorState; dumping: null | ErrorState; loading: null | ErrorState; exportingAsDataset: null | ErrorState; deleting: null | ErrorState; creating: null | ErrorState; exporting: null | ErrorState; importing: null | ErrorState; moving: null | ErrorState; }; formats: { fetching: null | ErrorState; }; users: { fetching: null | ErrorState; }; about: { fetching: null | ErrorState; }; share: { fetching: null | ErrorState; }; models: { starting: null | ErrorState; fetching: null | ErrorState; canceling: null | ErrorState; metaFetching: null | ErrorState; inferenceStatusFetching: null | ErrorState; }; annotation: { saving: null | ErrorState; jobFetching: null | ErrorState; frameFetching: null | ErrorState; contextImageFetching: null | ErrorState; changingLabelColor: null | ErrorState; updating: null | ErrorState; creating: null | ErrorState; merging: null | ErrorState; grouping: null | ErrorState; splitting: null | ErrorState; removing: null | ErrorState; propagating: null | ErrorState; collectingStatistics: null | ErrorState; savingJob: null | ErrorState; uploadAnnotations: null | ErrorState; removeAnnotations: null | ErrorState; fetchingAnnotations: null | ErrorState; undo: null | ErrorState; redo: null | ErrorState; search: null | ErrorState; searchEmptyFrame: null | ErrorState; savingLogs: null | ErrorState; }; boundaries: { resetError: null | ErrorState; }; userAgreements: { fetching: null | ErrorState; }; review: { initialization: null | ErrorState; finishingIssue: null | ErrorState; resolvingIssue: null | ErrorState; reopeningIssue: null | ErrorState; commentingIssue: null | ErrorState; submittingReview: null | ErrorState; }; predictor: { prediction: null | ErrorState; }; cloudStorages: { creating: null | ErrorState; fetching: null | ErrorState; updating: null | ErrorState; deleting: null | ErrorState; }; }; messages: { tasks: { loadingDone: string; importingDone: string; movingDone: string; }; models: { inferenceDone: string; }; auth: { changePasswordDone: string; registerDone: string; requestPasswordResetDone: string; resetPasswordDone: string; }; }; }
export enum ActiveControl { CURSOR = ‘cursor’, DRAG_CANVAS = ‘drag_canvas’, ZOOM_CANVAS = ‘zoom_canvas’, DRAW_RECTANGLE = ‘draw_rectangle’, DRAW_CIRCLE = ‘draw_circle’, DRAW_POLYGON = ‘draw_polygon’, DRAW_POLYLINE = ‘draw_polyline’, DRAW_POINTS = ‘draw_points’, DRAW_CUBOID = ‘draw_cuboid’, MERGE = ‘merge’, GROUP = ‘group’, SPLIT = ‘split’, EDIT = ‘edit’, OPEN_ISSUE = ‘open_issue’, AI_TOOLS = ‘ai_tools’, PHOTO_CONTEXT = ‘PHOTO_CONTEXT’, OPENCV_TOOLS = ‘opencv_tools’, }
export enum ShapeType { RECTANGLE = ‘rectangle’, CIRCLE = ‘circle’, POLYGON = ‘polygon’, POLYLINE = ‘polyline’, POINTS = ‘points’, CUBOID = ‘cuboid’, }
export enum ObjectType { SHAPE = ‘shape’, TRACK = ‘track’, TAG = ‘tag’, }
export enum StatesOrdering { ID_DESCENT = ‘ID - descent’, ID_ASCENT = ‘ID - ascent’, UPDATED = ‘Updated time’, }
export enum ContextMenuType { CANVAS_SHAPE = ‘canvas_shape’, CANVAS_SHAPE_POINT = ‘canvas_shape_point’, }
export enum Rotation { ANTICLOCKWISE90, CLOCKWISE90, }
export interface PredictorState { timeRemaining: number; progress: number; projectScore: number; message: string; error: Error | null; enabled: boolean; fetching: boolean; annotationAmount: number; mediaAmount: number; annotatedFrames: number[]; }
export interface AnnotationState {
activities: {
loads: {
// only one loading simultaneously
[jid: number]: string; // loader name
};
};
canvas: {
contextMenu: {
visible: boolean;
top: number;
left: number;
type: ContextMenuType;
pointID: number | null;
clientID: number | null;
};
instance: Canvas | Canvas3d;
ready: boolean;
activeControl: ActiveControl;
};
job: {
openTime: null | number;
labels: any[];
requestedId: number | null;
instance: any | null | undefined;
attributes: Record
export enum Workspace { STANDARD3D = ‘Standard 3D’, STANDARD = ‘Standard’, ATTRIBUTE_ANNOTATION = ‘Attribute annotation’, TAG_ANNOTATION = ‘Tag annotation’, REVIEW_WORKSPACE = ‘Review’, }
export enum GridColor { White = ‘White’, Black = ‘Black’, Red = ‘Red’, Green = ‘Green’, Blue = ‘Blue’, }
export enum FrameSpeed { Fastest = 100, Fast = 50, Usual = 25, Slow = 15, Slower = 12, Slowest = 1, }
export enum ColorBy { INSTANCE = ‘Instance’, GROUP = ‘Group’, LABEL = ‘Label’, }
export interface PlayerSettingsState { canvasBackgroundColor: string; frameStep: number; frameSpeed: FrameSpeed; resetZoom: boolean; rotateAll: boolean; grid: boolean; gridSize: number; gridColor: GridColor; gridOpacity: number; // in % brightnessLevel: number; contrastLevel: number; saturationLevel: number; }
export interface WorkspaceSettingsState { autoSave: boolean; autoSaveInterval: number; // in ms aamZoomMargin: number; automaticBordering: boolean; showObjectsTextAlways: boolean; showAllInterpolationTracks: boolean; intelligentPolygonCrop: boolean; defaultApproxPolyAccuracy: number; toolsBlockerState: ToolsBlockerState; }
export interface ShapesSettingsState { colorBy: ColorBy; opacity: number; selectedOpacity: number; outlined: boolean; outlineColor: string; showBitmap: boolean; showProjections: boolean; }
export interface SettingsState { shapes: ShapesSettingsState; workspace: WorkspaceSettingsState; player: PlayerSettingsState; showDialog: boolean; }
export interface ShortcutsState {
visibleShortcutsHelp: boolean;
keyMap: KeyMap;
normalizedKeyMap: Record
export enum ReviewStatus { ACCEPTED = ‘accepted’, REJECTED = ‘rejected’, REVIEW_FURTHER = ‘review_further’, }
export interface ReviewState { reviews: any[]; issues: any[]; frameIssues: any[]; latestComments: string[]; activeReview: any | null; newIssuePosition: number[] | null; issuesHidden: boolean; fetching: { reviewId: number | null; issueId: number | null; }; }
export interface CombinedState { auth: AuthState; projects: ProjectsState; tasks: TasksState; about: AboutState; share: ShareState; formats: FormatsState; userAgreements: UserAgreementsState; plugins: PluginsState; models: ModelsState; notifications: NotificationsState; annotation: AnnotationState; settings: SettingsState; shortcuts: ShortcutsState; review: ReviewState; export: ExportState; cloudStorages: CloudStoragesState; }
export enum DimensionType { DIM_3D = ‘3d’, DIM_2D = ‘2d’, }
```
