image.png

    1. 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}); }

    1. if (drawData.enabled) {
    2. if (this.data.drawData.enabled) {
    3. throw new Error('Drawing has been already started');
    4. } else if (!drawData.shapeType && !drawData.initialState) {
    5. throw new Error('A shape type is not specified');
    6. } else if (typeof drawData.numberOfPoints !== 'undefined') {
    7. if (drawData.shapeType === 'polygon' && drawData.numberOfPoints < 3) {
    8. throw new Error('A polygon consists of at least 3 points');
    9. } else if (drawData.shapeType === 'polyline' && drawData.numberOfPoints < 2) {
    10. throw new Error('A polyline consists of at least 2 points');
    11. }
    12. }
    13. }
    14. if (typeof drawData.redraw === 'number') {
    15. const clientID = drawData.redraw;
    16. const [state] = this.data.objects.filter((_state: any): boolean => _state.clientID === clientID);
    17. if (state) {
    18. this.data.drawData = { ...drawData };
    19. this.data.drawData.shapeType = state.shapeType;
    20. } else {
    21. return;
    22. }
    23. } else {
    24. this.data.drawData = { ...drawData };
    25. if (this.data.drawData.initialState) {
    26. this.data.drawData.shapeType = this.data.drawData.initialState.shapeType;
    27. }
    28. }
    29. // install default values for drawing method
    30. if (drawData.enabled) {
    31. console.log('drawData.shapeType:', drawData.shapeType);
    32. if (drawData.shapeType === 'rectangle') {
    33. this.data.drawData.rectDrawingMethod = drawData.rectDrawingMethod || RectDrawingMethod.CLASSIC;
    34. }
    35. // 添加circle
    36. if (drawData.shapeType === 'circle') {
    37. this.data.drawData.circleDrawingMethod = drawData.circleDrawingMethod || CircleDrawingMethod.CLASSIC;
    38. }
    39. if (drawData.shapeType === 'cuboid') {
    40. this.data.drawData.cuboidDrawingMethod = drawData.cuboidDrawingMethod || CuboidDrawingMethod.CLASSIC;
    41. }
    42. }
    43. console.log('==========');
    44. this.notify(UpdateReasons.DRAW);
    45. }
    1. 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;

    1. const ctx = this.bitmap.getContext('2d');
    2. if (ctx) {
    3. ctx.fillStyle = 'black';
    4. ctx.fillRect(0, 0, width, height);
    5. for (const state of states) {
    6. if (state.hidden || state.outside) continue;
    7. ctx.fillStyle = 'white';
    8. if (['rectangle', 'circle', 'polygon', 'cuboid'].includes(state.shapeType)) {
    9. let points = [];
    10. if (state.shapeType === 'rectangle') {
    11. points = [
    12. state.points[0], // xtl
    13. state.points[1], // ytl
    14. state.points[2], // xbr
    15. state.points[1], // ytl
    16. state.points[2], // xbr
    17. state.points[3], // ybr
    18. state.points[0], // xtl
    19. state.points[3], // ybr
    20. ];
    21. } else if (state.shapeType === 'circle') {
    22. points = [
    23. state.points[0], // xtl
    24. state.points[1], // ytl
    25. state.points[2], // xbr
    26. state.points[1], // ytl
    27. state.points[2], // xbr
    28. state.points[3], // ybr
    29. state.points[0], // xtl
    30. state.points[3], // ybr
    31. ];
    32. } else if (state.shapeType === 'cuboid') {
    33. points = [
    34. state.points[0],
    35. state.points[1],
    36. state.points[4],
    37. state.points[5],
    38. state.points[8],
    39. state.points[9],
    40. state.points[12],
    41. state.points[13],
    42. ];
    43. } else {
    44. points = [...state.points];
    45. }
    46. ctx.beginPath();
    47. ctx.moveTo(points[0], points[1]);
    48. for (let i = 0; i < points.length; i += 2) {
    49. ctx.lineTo(points[i], points[i + 1]);
    50. }
    51. ctx.closePath();
    52. ctx.fill();
    53. }
    54. if (state.shapeType === 'cuboid') {
    55. for (let i = 0; i < 5; i++) {
    56. const points = [
    57. state.points[(0 + i * 4) % 16],
    58. state.points[(1 + i * 4) % 16],
    59. state.points[(2 + i * 4) % 16],
    60. state.points[(3 + i * 4) % 16],
    61. state.points[(6 + i * 4) % 16],
    62. state.points[(7 + i * 4) % 16],
    63. state.points[(4 + i * 4) % 16],
    64. state.points[(5 + i * 4) % 16],
    65. ];
    66. ctx.beginPath();
    67. ctx.moveTo(points[0], points[1]);
    68. for (let j = 0; j < points.length; j += 2) {
    69. ctx.lineTo(points[j], points[j + 1]);
    70. }
    71. ctx.closePath();
    72. ctx.fill();
    73. }
    74. }
    75. }
    76. }
    77. }
    78. private updateObjects(states: any[]): void {
    79. for (const state of states) {
    80. const { clientID } = state;
    81. const drawnState = this.drawnStates[clientID];
    82. const shape = this.svgShapes[state.clientID];
    83. const text = this.svgTexts[state.clientID];
    84. const isInvisible = state.hidden || state.outside || this.isServiceHidden(state.clientID);
    85. if (drawnState.hidden !== state.hidden || drawnState.outside !== state.outside) {
    86. if (isInvisible) {
    87. (state.shapeType === 'points' ? shape.remember('_selectHandler').nested : shape).addClass(
    88. 'cvat_canvas_hidden',
    89. );
    90. if (text) {
    91. text.addClass('cvat_canvas_hidden');
    92. }
    93. } else {
    94. (state.shapeType === 'points' ? shape.remember('_selectHandler').nested : shape).removeClass(
    95. 'cvat_canvas_hidden',
    96. );
    97. if (text) {
    98. text.removeClass('cvat_canvas_hidden');
    99. this.updateTextPosition(text, shape);
    100. }
    101. }
    102. }
    103. if (drawnState.zOrder !== state.zOrder) {
    104. if (state.shapeType === 'points') {
    105. shape.remember('_selectHandler').nested.attr('data-z-order', state.zOrder);
    106. } else {
    107. shape.attr('data-z-order', state.zOrder);
    108. }
    109. }
    110. if (drawnState.occluded !== state.occluded) {
    111. if (state.occluded) {
    112. shape.addClass('cvat_canvas_shape_occluded');
    113. } else {
    114. shape.removeClass('cvat_canvas_shape_occluded');
    115. }
    116. }
    117. if (drawnState.pinned !== state.pinned && this.activeElement.clientID !== null) {
    118. const activeElement = { ...this.activeElement };
    119. this.deactivate();
    120. this.activate(activeElement);
    121. }
    122. if (
    123. state.points.length !== drawnState.points.length ||
    124. state.points.some((p: number, id: number): boolean => p !== drawnState.points[id])
    125. ) {
    126. const translatedPoints: number[] = this.translateToCanvas(state.points);
    127. if (state.shapeType === 'rectangle') {
    128. const [xtl, ytl, xbr, ybr] = translatedPoints;
    129. shape.attr({
    130. x: xtl,
    131. y: ytl,
    132. width: xbr - xtl,
    133. height: ybr - ytl,
    134. });
    135. } else if (state.shapeType === 'circle') {
    136. const [xtl, ytl, xbr, ybr] = translatedPoints;
    137. shape.attr({
    138. x: xtl,
    139. y: ytl,
    140. width: xbr - xtl,
    141. height: ybr - ytl,
    142. });
    143. } else {
    144. const stringified = this.stringifyToCanvas(translatedPoints);
    145. if (state.shapeType !== 'cuboid') {
    146. (shape as any).clear();
    147. }
    148. shape.attr('points', stringified);
    149. if (state.shapeType === 'points' && !isInvisible) {
    150. this.selectize(false, shape);
    151. this.setupPoints(shape as SVG.PolyLine, state);
    152. }
    153. }
    154. }
    155. const stateDescriptions = state.descriptions;
    156. const drawnStateDescriptions = drawnState.descriptions;
    157. if (
    158. drawnState.label.id !== state.label.id ||
    159. drawnStateDescriptions.length !== stateDescriptions.length ||
    160. drawnStateDescriptions.some((desc: string, id: number): boolean => desc !== stateDescriptions[id])
    161. ) {
    162. // need to remove created text and create it again
    163. if (text) {
    164. text.remove();
    165. this.svgTexts[state.clientID] = this.addText(state);
    166. }
    167. } else {
    168. // check if there are updates in attributes
    169. for (const attrID of Object.keys(state.attributes)) {
    170. if (state.attributes[attrID] !== drawnState.attributes[+attrID]) {
    171. if (text) {
    172. const [span] = text.node.querySelectorAll<SVGTSpanElement>(`[attrID="${attrID}"]`);
    173. if (span && span.textContent) {
    174. const prefix = span.textContent.split(':').slice(0, -1).join(':');
    175. span.textContent = `${prefix}: ${state.attributes[attrID]}`;
    176. }
    177. }
    178. }
    179. }
    180. }
    181. this.saveState(state);
    182. }
    183. }
    184. private addObjects(states: any[]): void {
    185. console.log('addObjects');
    186. const { displayAllText } = this.configuration;
    187. for (const state of states) {
    188. const points: number[] = state.points as number[];
    189. const translatedPoints: number[] = this.translateToCanvas(points);
    190. console.log('state.shapeType:', state.shapeType);
    191. // TODO: Use enums after typification cvat-core
    192. if (state.shapeType === 'rectangle') {
    193. this.svgShapes[state.clientID] = this.addRect(translatedPoints, state);
    194. } else if (state.shapeType === 'circle') {
    195. this.svgShapes[state.clientID] = this.addCircle(translatedPoints, state);
    196. } else {
    197. const stringified = this.stringifyToCanvas(translatedPoints);
    198. if (state.shapeType === 'polygon') {
    199. this.svgShapes[state.clientID] = this.addPolygon(stringified, state);
    200. } else if (state.shapeType === 'polyline') {
    201. this.svgShapes[state.clientID] = this.addPolyline(stringified, state);
    202. } else if (state.shapeType === 'points') {
    203. this.svgShapes[state.clientID] = this.addPoints(stringified, state);
    204. } else if (state.shapeType === 'cuboid') {
    205. this.svgShapes[state.clientID] = this.addCuboid(stringified, state);
    206. } else {
    207. continue;
    208. }
    209. }
    210. this.svgShapes[state.clientID].on('click.canvas', (): void => {
    211. this.canvas.dispatchEvent(
    212. new CustomEvent('canvas.clicked', {
    213. bubbles: false,
    214. cancelable: true,
    215. detail: {
    216. state,
    217. },
    218. }),
    219. );
    220. });
    221. if (displayAllText) {
    222. this.svgTexts[state.clientID] = this.addText(state);
    223. this.updateTextPosition(this.svgTexts[state.clientID], this.svgShapes[state.clientID]);
    224. }
    225. this.saveState(state);
    226. }
    227. }
    228. private activateShape(clientID: number): void {
    229. const [state] = this.controller.objects.filter((_state: any): boolean => _state.clientID === clientID);
    230. if (state && state.shapeType === 'points') {
    231. this.svgShapes[clientID]
    232. .remember('_selectHandler')
    233. .nested.style('pointer-events', this.stateIsLocked(state) ? 'none' : '');
    234. }
    235. if (!state || state.hidden || state.outside) {
    236. return;
    237. }
    238. const shape = this.svgShapes[clientID];
    239. let text = this.svgTexts[clientID];
    240. if (!text) {
    241. text = this.addText(state);
    242. this.svgTexts[state.clientID] = text;
    243. }
    244. this.updateTextPosition(text, shape);
    245. if (this.stateIsLocked(state)) {
    246. return;
    247. }
    248. shape.addClass('cvat_canvas_shape_activated');
    249. if (state.shapeType === 'points') {
    250. this.content.append(this.svgShapes[clientID].remember('_selectHandler').nested.node);
    251. } else {
    252. this.content.append(shape.node);
    253. }
    254. const { showProjections } = this.configuration;
    255. if (state.shapeType === 'cuboid' && showProjections) {
    256. (shape as any).attr('projections', true);
    257. }
    258. const hideText = (): void => {
    259. if (text) {
    260. text.addClass('cvat_canvas_hidden');
    261. }
    262. };
    263. const showText = (): void => {
    264. if (text) {
    265. text.removeClass('cvat_canvas_hidden');
    266. this.updateTextPosition(text, shape);
    267. }
    268. };
    269. if (!state.pinned) {
    270. shape.addClass('cvat_canvas_shape_draggable');
    271. (shape as any)
    272. .draggable()
    273. .on('dragstart', (): void => {
    274. this.mode = Mode.DRAG;
    275. hideText();
    276. })
    277. .on('dragend', (e: CustomEvent): void => {
    278. showText();
    279. this.mode = Mode.IDLE;
    280. const p1 = e.detail.handler.startPoints.point;
    281. const p2 = e.detail.p;
    282. const delta = 1;
    283. const { offset } = this.controller.geometry;
    284. const dx2 = (p1.x - p2.x) ** 2;
    285. const dy2 = (p1.y - p2.y) ** 2;
    286. if (Math.sqrt(dx2 + dy2) >= delta) {
    287. const points = pointsToNumberArray(
    288. shape.attr('points') || `${shape.attr('x')},${shape.attr('y')} ` +
    289. `${shape.attr('x') + shape.attr('width')},` +
    290. `${shape.attr('y') + shape.attr('height')}`,
    291. ).map((x: number): number => x - offset);
    292. this.drawnStates[state.clientID].points = points;
    293. this.canvas.dispatchEvent(
    294. new CustomEvent('canvas.dragshape', {
    295. bubbles: false,
    296. cancelable: true,
    297. detail: {
    298. id: state.clientID,
    299. },
    300. }),
    301. );
    302. this.onEditDone(state, points);
    303. }
    304. });
    305. }
    306. if (state.shapeType !== 'points') {
    307. this.selectize(true, shape);
    308. }
    309. const showDirection = (): void => {
    310. if (['polygon', 'polyline'].includes(state.shapeType)) {
    311. this.showDirection(state, shape as SVG.Polygon | SVG.PolyLine);
    312. }
    313. };
    314. const hideDirection = (): void => {
    315. if (['polygon', 'polyline'].includes(state.shapeType)) {
    316. this.hideDirection(shape as SVG.Polygon | SVG.PolyLine);
    317. }
    318. };
    319. showDirection();
    320. let shapeSizeElement: ShapeSizeElement | null = null;
    321. let resized = false;
    322. (shape as any)
    323. .resize({
    324. snapToGrid: 0.1,
    325. })
    326. .on('resizestart', (): void => {
    327. this.mode = Mode.RESIZE;
    328. resized = false;
    329. hideDirection();
    330. hideText();
    331. if (state.shapeType === 'rectangle') {
    332. shapeSizeElement = displayShapeSize(this.adoptedContent, this.adoptedText);
    333. }
    334. if (state.shapeType === 'circle') {
    335. shapeSizeElement = displayShapeSize(this.adoptedContent, this.adoptedText);
    336. }
    337. })
    338. .on('resizing', (): void => {
    339. resized = true;
    340. if (shapeSizeElement) {
    341. shapeSizeElement.update(shape);
    342. }
    343. })
    344. .on('resizedone', (): void => {
    345. if (shapeSizeElement) {
    346. shapeSizeElement.rm();
    347. }
    348. showDirection();
    349. showText();
    350. this.mode = Mode.IDLE;
    351. if (resized) {
    352. const { offset } = this.controller.geometry;
    353. const points = pointsToNumberArray(
    354. shape.attr('points') || `${shape.attr('x')},${shape.attr('y')} ` +
    355. `${shape.attr('x') + shape.attr('width')},` +
    356. `${shape.attr('y') + shape.attr('height')}`,
    357. ).map((x: number): number => x - offset);
    358. this.drawnStates[state.clientID].points = points;
    359. this.canvas.dispatchEvent(
    360. new CustomEvent('canvas.resizeshape', {
    361. bubbles: false,
    362. cancelable: true,
    363. detail: {
    364. id: state.clientID,
    365. },
    366. }),
    367. );
    368. this.onEditDone(state, points);
    369. }
    370. });
    371. this.canvas.dispatchEvent(
    372. new CustomEvent('canvas.activated', {
    373. bubbles: false,
    374. cancelable: true,
    375. detail: {
    376. state,
    377. },
    378. }),
    379. );
    380. }
    381. private addCircle(points: number[], state: any): SVG.Circle {
    382. console.log('addCircle');
    383. const [xtl, ytl, xbr, ybr] = points;
    384. console.log((xbr - xtl) / 2);
    385. const rect = this.adoptedContent
    386. .circle()
    387. .size(xbr - xtl, ybr - ytl)
    388. .attr({
    389. clientID: state.clientID,
    390. 'color-rendering': 'optimizeQuality',
    391. id: `cvat_canvas_shape_${state.clientID}`,
    392. fill: state.color,
    393. 'shape-rendering': 'geometricprecision',
    394. stroke: state.color,
    395. 'stroke-width': consts.BASE_STROKE_WIDTH / this.geometry.scale,
    396. 'data-z-order': state.zOrder,
    397. })
    398. .move(xtl, ytl)
    399. .addClass('cvat_canvas_shape');
    400. if (state.occluded) {
    401. rect.addClass('cvat_canvas_shape_occluded');
    402. }
    403. if (state.hidden || state.outside || this.isServiceHidden(state.clientID)) {
    404. rect.addClass('cvat_canvas_hidden');
    405. }
    406. return rect;
    407. }
    1. 3. drawHandler.ts

    import { DrawData, Geometry, RectDrawingMethod, CircleDrawingMethod, Configuration, CuboidDrawingMethod, } from ‘./canvasModel’;

    1. private getFinalCircleCoordinates(bbox: BBox): number[] {
    2. const frameWidth = this.geometry.image.width;
    3. const frameHeight = this.geometry.image.height;
    4. const { offset } = this.geometry;
    5. let [xtl, ytl, xbr, ybr] = [bbox.x, bbox.y, bbox.x + bbox.width, bbox.y + bbox.height].map(
    6. (coord: number): number => coord - offset,
    7. );
    8. xtl = Math.min(Math.max(xtl, 0), frameWidth);
    9. xbr = Math.min(Math.max(xbr, 0), frameWidth);
    10. ytl = Math.min(Math.max(ytl, 0), frameHeight);
    11. ybr = Math.min(Math.max(ybr, 0), frameHeight);
    12. return [xtl, ytl, xbr, ybr];
    13. }
    14. private drawCircle(): void {
    15. this.drawInstance = this.canvas.circle();
    16. this.drawInstance
    17. .on('drawstop', (e: Event): void => {
    18. const bbox = (e.target as SVGRectElement).getBBox();
    19. const [xtl, ytl, xbr, ybr] = this.getFinalCircleCoordinates(bbox);
    20. const { shapeType, redraw: clientID } = this.drawData;
    21. this.release();
    22. if (this.canceled) return;
    23. if ((xbr - xtl) * (ybr - ytl) >= consts.AREA_THRESHOLD) {
    24. this.onDrawDone(
    25. {
    26. clientID,
    27. shapeType,
    28. points: [xtl, ytl, xbr, ybr],
    29. },
    30. Date.now() - this.startTimestamp,
    31. );
    32. }
    33. })
    34. .on('drawupdate', (): void => {
    35. console.log(this.shapeSizeElement);
    36. this.shapeSizeElement.update(this.drawInstance);
    37. })
    38. .addClass('cvat_canvas_shape_drawing')
    39. .attr({
    40. 'stroke-width': consts.BASE_STROKE_WIDTH / this.geometry.scale,
    41. 'fill-opacity': this.configuration.creationOpacity,
    42. });
    43. }
    44. private startDraw(): void {
    45. // TODO: Use enums after typification cvat-core
    46. console.log('startDraw:', this.drawData.shapeType, this.drawData.initialState);
    47. if (this.drawData.initialState) {
    48. const { offset } = this.geometry;
    49. if (this.drawData.shapeType === 'rectangle') {
    50. const [xtl, ytl, xbr, ybr] = this.drawData.initialState.points.map(
    51. (coord: number): number => coord + offset,
    52. );
    53. this.pasteBox({
    54. x: xtl,
    55. y: ytl,
    56. width: xbr - xtl,
    57. height: ybr - ytl,
    58. });
    59. } if (this.drawData.shapeType === 'circle') {
    60. const [xtl, ytl, xbr, ybr] = this.drawData.initialState.points.map(
    61. (coord: number): number => coord + offset,
    62. );
    63. this.pasteBox({
    64. x: xtl,
    65. y: ytl,
    66. width: xbr - xtl,
    67. height: ybr - ytl,
    68. });
    69. } else {
    70. const points = this.drawData.initialState.points.map((coord: number): number => coord + offset);
    71. const stringifiedPoints = stringifyPoints(points);
    72. if (this.drawData.shapeType === 'polygon') {
    73. this.pastePolygon(stringifiedPoints);
    74. } else if (this.drawData.shapeType === 'polyline') {
    75. this.pastePolyline(stringifiedPoints);
    76. } else if (this.drawData.shapeType === 'points') {
    77. this.pastePoints(stringifiedPoints);
    78. } else if (this.drawData.shapeType === 'cuboid') {
    79. this.pasteCuboid(stringifiedPoints);
    80. }
    81. }
    82. this.setupPasteEvents();
    83. } else {
    84. if (this.drawData.shapeType === 'rectangle') {
    85. if (this.drawData.rectDrawingMethod === RectDrawingMethod.EXTREME_POINTS) {
    86. // draw box by extreme clicking
    87. this.drawBoxBy4Points();
    88. } else {
    89. // default box drawing
    90. this.drawBox();
    91. // Draw instance was initialized after drawBox();
    92. this.shapeSizeElement = displayShapeSize(this.canvas, this.text);
    93. }
    94. } else if (this.drawData.shapeType === 'circle') {
    95. this.drawCircle();
    96. this.shapeSizeElement = displayShapeSize(this.canvas, this.text);
    97. } else if (this.drawData.shapeType === 'polygon') {
    98. this.drawPolygon();
    99. } else if (this.drawData.shapeType === 'polyline') {
    100. this.drawPolyline();
    101. } else if (this.drawData.shapeType === 'points') {
    102. this.drawPoints();
    103. } else if (this.drawData.shapeType === 'cuboid') {
    104. if (this.drawData.cuboidDrawingMethod === CuboidDrawingMethod.CORNER_POINTS) {
    105. this.drawCuboidBy4Points();
    106. } else {
    107. this.drawCuboid();
    108. this.shapeSizeElement = displayShapeSize(this.canvas, this.text);
    109. }
    110. }
    111. this.setupDrawEvents();
    112. }
    113. this.startTimestamp = Date.now();
    114. this.initialized = true;
    115. }
    116. public configurate(configuration: Configuration): void {
    117. this.configuration = configuration;
    118. const isFillableRect = this.drawData &&
    119. this.drawData.shapeType === 'rectangle' &&
    120. (this.drawData.rectDrawingMethod === RectDrawingMethod.CLASSIC || this.drawData.initialState);
    121. const isFillableCircle = this.drawData &&
    122. this.drawData.shapeType === 'circle' &&
    123. (this.drawData.circleDrawingMethod === CircleDrawingMethod.CLASSIC || this.drawData.initialState);
    124. const isFillableCuboid = this.drawData &&
    125. this.drawData.shapeType === 'cuboid' &&
    126. (this.drawData.cuboidDrawingMethod === CuboidDrawingMethod.CLASSIC || this.drawData.initialState);
    127. const isFilalblePolygon = this.drawData && this.drawData.shapeType === 'polygon';
    128. if (this.drawInstance && (isFillableRect || isFillableCircle || isFillableCuboid || isFilalblePolygon)) {
    129. this.drawInstance.fill({ opacity: configuration.creationOpacity });
    130. }
    131. if (typeof configuration.autoborders === 'boolean') {
    132. this.autobordersEnabled = configuration.autoborders;
    133. if (this.drawInstance) {
    134. if (this.autobordersEnabled) {
    135. this.autoborderHandler.autoborder(true, this.drawInstance, this.drawData.redraw);
    136. } else {
    137. this.autoborderHandler.autoborder(false);
    138. }
    139. }
    140. }
    141. }
    142. public transform(geometry: Geometry): void {
    143. this.geometry = geometry;
    144. if (this.shapeSizeElement && this.drawInstance && this.drawData.shapeType === 'rectangle') {
    145. this.shapeSizeElement.update(this.drawInstance);
    146. }
    147. if (this.shapeSizeElement && this.drawInstance && this.drawData.shapeType === 'circle') {
    148. this.shapeSizeElement.update(this.drawInstance);
    149. }
    150. if (this.crosshair) {
    151. this.crosshair.scale(this.geometry.scale);
    152. }
    153. if (this.pointsGroup) {
    154. for (const point of this.pointsGroup.children()) {
    155. point.attr({
    156. 'stroke-width': consts.POINTS_STROKE_WIDTH / geometry.scale,
    157. r: consts.BASE_POINT_SIZE / geometry.scale,
    158. });
    159. }
    160. }
    161. if (this.drawInstance) {
    162. this.drawInstance.draw('transform');
    163. this.drawInstance.attr({
    164. 'stroke-width': consts.BASE_STROKE_WIDTH / geometry.scale,
    165. });
    166. const paintHandler = this.drawInstance.remember('_paintHandler');
    167. for (const point of (paintHandler as any).set.members) {
    168. point.attr('stroke-width', `${consts.POINTS_STROKE_WIDTH / geometry.scale}`);
    169. point.attr('r', `${consts.BASE_POINT_SIZE / geometry.scale}`);
    170. }
    171. }
    172. }
    1. 4. interactionHandler.ts

    private shouldRaiseEvent(ctrlKey: boolean): boolean { const { interactionData, interactionShapes, shapesWereUpdated } = this; const { minPosVertices, minNegVertices, enabled } = interactionData;

    1. const positiveShapes = interactionShapes.filter(
    2. (shape: SVG.Shape): boolean => (shape as any).attr('stroke') === 'green',
    3. );
    4. const negativeShapes = interactionShapes.filter(
    5. (shape: SVG.Shape): boolean => (shape as any).attr('stroke') !== 'green',
    6. );
    7. if (interactionData.shapeType === 'rectangle') {
    8. return enabled && !ctrlKey && !!interactionShapes.length;
    9. }
    10. if (interactionData.shapeType === 'circle') {
    11. return enabled && !ctrlKey && !!interactionShapes.length;
    12. }
    13. const minPosVerticesDefined = Number.isInteger(minPosVertices);
    14. const minNegVerticesDefined = Number.isInteger(minNegVertices) && minNegVertices >= 0;
    15. const minPosVerticesAchieved = !minPosVerticesDefined || minPosVertices <= positiveShapes.length;
    16. const minNegVerticesAchieved = !minNegVerticesDefined || minNegVertices <= negativeShapes.length;
    17. const minimumVerticesAchieved = minPosVerticesAchieved && minNegVerticesAchieved;
    18. return enabled && !ctrlKey && minimumVerticesAchieved && shapesWereUpdated;
    19. }
    20. private startInteraction(): void {
    21. if (this.interactionData.shapeType === 'rectangle') {
    22. this.interactRectangle(true);
    23. } else if (this.interactionData.shapeType === 'circle') {
    24. this.interactRectangle(true);
    25. } else if (this.interactionData.shapeType === 'points') {
    26. if (this.interactionData.startWithBox) {
    27. this.interactRectangle(false, (): void => this.interactPoints());
    28. } else {
    29. this.interactPoints();
    30. }
    31. } else {
    32. throw new Error('Interactor implementation supports only rectangle and points');
    33. }
    34. }
    1. 5. annotations-collection.js
    1. const {
    2. RectangleShape,
    3. CircleShape,
    4. PolygonShape,
    5. PolylineShape,
    6. PointsShape,
    7. CuboidShape,
    8. RectangleTrack,
    9. PolygonTrack,
    10. PolylineTrack,
    11. PointsTrack,
    12. CuboidTrack,
    13. Track,
    14. Shape,
    15. Tag,
    16. objectStateFactory,
    17. CircleTrack,
    18. } = require('./annotations-objects');
    19. function shapeFactory(shapeData, clientID, injection) {
    20. const { type } = shapeData;
    21. const color = colors[clientID % colors.length];
    22. let shapeModel = null;
    23. switch (type) {
    24. case 'rectangle':
    25. shapeModel = new RectangleShape(shapeData, clientID, color, injection);
    26. break;
    27. case 'circle':
    28. shapeModel = new CircleShape(shapeData, clientID, color, injection);
    29. break;
    30. case 'polygon':
    31. shapeModel = new PolygonShape(shapeData, clientID, color, injection);
    32. break;
    33. case 'polyline':
    34. shapeModel = new PolylineShape(shapeData, clientID, color, injection);
    35. break;
    36. case 'points':
    37. shapeModel = new PointsShape(shapeData, clientID, color, injection);
    38. break;
    39. case 'cuboid':
    40. shapeModel = new CuboidShape(shapeData, clientID, color, injection);
    41. break;
    42. default:
    43. throw new DataError(`An unexpected type of shape "${type}"`);
    44. }
    45. return shapeModel;
    46. }
    47. function trackFactory(trackData, clientID, injection) {
    48. if (trackData.shapes.length) {
    49. const { type } = trackData.shapes[0];
    50. const color = colors[clientID % colors.length];
    51. let trackModel = null;
    52. switch (type) {
    53. case 'rectangle':
    54. trackModel = new RectangleTrack(trackData, clientID, color, injection);
    55. break;
    56. case 'circle':
    57. trackModel = new CircleTrack(trackData, clientID, color, injection);
    58. break;
    59. case 'polygon':
    60. trackModel = new PolygonTrack(trackData, clientID, color, injection);
    61. break;
    62. case 'polyline':
    63. trackModel = new PolylineTrack(trackData, clientID, color, injection);
    64. break;
    65. case 'points':
    66. trackModel = new PointsTrack(trackData, clientID, color, injection);
    67. break;
    68. case 'cuboid':
    69. trackModel = new CuboidTrack(trackData, clientID, color, injection);
    70. break;
    71. default:
    72. throw new DataError(`An unexpected type of track "${type}"`);
    73. }
    74. return trackModel;
    75. }
    76. console.warn('The track without any shapes had been found. It was ignored.');
    77. return null;
    78. }
    1. 6. annotations-saver.js
    1. async save(onUpdateArg) {
    2. const onUpdate = typeof onUpdateArg === 'function' ? onUpdateArg : (message) => {
    3. console.log(message);
    4. };
    5. const exported = this.collection.export();
    6. const { flush } = this.collection;
    7. if (flush) {
    8. onUpdate('Created objects are being saved on the server');
    9. const indexes = this._receiveIndexes(exported);
    10. const savedData = await this._put({ ...exported, version: this.version });
    11. this.version = savedData.version;
    12. this.collection.flush = false;
    13. this._updateCreatedObjects(savedData, indexes);
    14. this._resetState();
    15. for (const type of Object.keys(this.initialObjects)) {
    16. for (const object of savedData[type]) {
    17. this.initialObjects[type][object.id] = object;
    18. }
    19. }
    20. } else {
    21. const { created, updated, deleted } = this._split(exported);
    22. onUpdate('Created objects are being saved on the server');
    23. console.log('created', created);
    24. if (created.shapes) {
    25. created.shapes.map((n) => {
    26. if (n.type === 'circle') {
    27. // @ts-ignore
    28. // eslint-disable-next-line prefer-destructuring
    29. n.rx = n.points[0];
    30. // @ts-ignore
    31. // eslint-disable-next-line prefer-destructuring
    32. n.ry = n.points[1];
    33. n.radius = (n.points[3] - n.points[0]) / 2;
    34. }
    35. });
    36. }
    37. const indexes = this._receiveIndexes(created);
    38. const createdData = await this._create({ ...created, version: this.version });
    39. this.version = createdData.version;
    40. this._updateCreatedObjects(createdData, indexes);
    41. for (const type of Object.keys(this.initialObjects)) {
    42. for (const object of createdData[type]) {
    43. this.initialObjects[type][object.id] = object;
    44. }
    45. }
    46. onUpdate('Updated objects are being saved on the server');
    47. this._receiveIndexes(updated);
    48. const updatedData = await this._update({ ...updated, version: this.version });
    49. this.version = updatedData.version;
    50. for (const type of Object.keys(this.initialObjects)) {
    51. for (const object of updatedData[type]) {
    52. this.initialObjects[type][object.id] = object;
    53. }
    54. }
    55. onUpdate('Deleted objects are being deleted from the server');
    56. this._receiveIndexes(deleted);
    57. const deletedData = await this._delete({ ...deleted, version: this.version });
    58. this._version = deletedData.version;
    59. for (const type of Object.keys(this.initialObjects)) {
    60. for (const object of deletedData[type]) {
    61. delete this.initialObjects[type][object.id];
    62. }
    63. }
    64. }
    65. this.hash = this._getHash();
    66. }
    67. hasUnsavedChanges() {
    68. return this._getHash() !== this.hash;
    69. }
    70. }
    1. 7. enum.js
    1. const ObjectShape = Object.freeze({
    2. RECTANGLE: 'rectangle',
    3. CIRCLE: 'circle',
    4. POLYGON: 'polygon',
    5. POLYLINE: 'polyline',
    6. POINTS: 'points',
    7. CUBOID: 'cuboid',
    8. });
    1. 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;

    1. &:hover:not(.cvat-disabled-canvas-control) {
    2. background: $header-color;
    3. transform: scale(0.75);
    4. }
    5. &:active:not(.cvat-disabled-canvas-control) {
    6. transform: scale(0.65);
    7. }
    8. > svg {
    9. transform: scale(0.8);
    10. }

    }

    1. 9. controls-side-bar.tsx

    import DrawCircleControl, { Props as DrawCircleControlProps } from ‘./draw-circle-control’;

    const ObservedDrawCircleControl = ControlVisibilityObserver(DrawCircleControl);

    1. <ObservedDrawCircleControl
    2. canvasInstance={canvasInstance}
    3. isDrawing={activeControl === ActiveControl.DRAW_CIRCLE}
    4. disabled={!labels.length}
    5. />
    1. 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’, }, } : {};

    1. const dynamicIconProps = isDrawing ?
    2. {
    3. className: 'cvat-draw-circle-control cvat-active-canvas-control',
    4. onClick: (): void => {
    5. canvasInstance.draw({ enabled: false });
    6. },
    7. } :
    8. {
    9. className: 'cvat-draw-circle-control',
    10. };
    11. return disabled ? (
    12. <Icon className='cvat-draw-circle-control cvat-disabled-canvas-control' component={CircleIcon} />
    13. ) : (
    14. <CustomPopover
    15. {...dynamcPopoverPros}
    16. overlayClassName='cvat-draw-shape-popover'
    17. placement='right'
    18. content={<DrawShapePopoverContainer shapeType={ShapeType.CIRCLE} />}
    19. >
    20. <Icon {...dynamicIconProps} component={CircleIcon} />
    21. </CustomPopover>
    22. );

    }

    export default React.memo(DrawCircleControl);

    1. 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;

    1. const is2D = jobInstance.task.dimension === DimensionType.DIM_2D;
    2. return (
    3. <div className='cvat-draw-shape-popover-content'>
    4. <Row justify='start'>
    5. <Col>
    6. <Text className='cvat-text-color' strong>{`Draw new ${shapeType}`}</Text>
    7. </Col>
    8. </Row>
    9. <Row justify='start'>
    10. <Col>
    11. <Text className='cvat-text-color'>Label</Text>
    12. </Col>
    13. </Row>
    14. <Row justify='center'>
    15. <Col span={24}>
    16. <LabelSelector
    17. style={{ width: '100%' }}
    18. labels={labels}
    19. value={selectedLabelID}
    20. onChange={onChangeLabel}
    21. />
    22. </Col>
    23. </Row>
    24. {is2D && shapeType === ShapeType.RECTANGLE && (
    25. <>
    26. <Row>
    27. <Col>
    28. <Text className='cvat-text-color'> Drawing method </Text>
    29. </Col>
    30. </Row>
    31. <Row justify='space-around'>
    32. <Col>
    33. <Radio.Group
    34. style={{ display: 'flex' }}
    35. value={rectDrawingMethod}
    36. onChange={onChangeRectDrawingMethod}
    37. >
    38. <Radio value={RectDrawingMethod.CLASSIC} style={{ width: 'auto' }}>
    39. By 2 Points
    40. </Radio>
    41. <Radio value={RectDrawingMethod.EXTREME_POINTS} style={{ width: 'auto' }}>
    42. By 4 Points
    43. </Radio>
    44. </Radio.Group>
    45. </Col>
    46. </Row>
    47. </>
    48. )}
    49. {is2D && shapeType === ShapeType.CIRCLE && (
    50. <>
    51. <Row>
    52. <Col>
    53. <Text className='cvat-text-color'> Drawing method </Text>
    54. </Col>
    55. </Row>
    56. <Row justify='space-around'>
    57. <Col>
    58. <Radio.Group
    59. style={{ display: 'flex' }}
    60. value={circleDrawingMethod}
    61. onChange={onChangeCircleDrawingMethod}
    62. >
    63. <Radio value={CircleDrawingMethod.CLASSIC} style={{ width: 'auto' }}>
    64. By 2 Points
    65. </Radio>
    66. <Radio value={CircleDrawingMethod.EXTREME_POINTS} style={{ width: 'auto' }}>
    67. By 4 Points
    68. </Radio>
    69. </Radio.Group>
    70. </Col>
    71. </Row>
    72. </>
    73. )}
    74. {is2D && shapeType === ShapeType.CUBOID && (
    75. <>
    76. <Row>
    77. <Col>
    78. <Text className='cvat-text-color'> Drawing method </Text>
    79. </Col>
    80. </Row>
    81. <Row justify='space-around'>
    82. <Col>
    83. <Radio.Group
    84. style={{ display: 'flex' }}
    85. value={cuboidDrawingMethod}
    86. onChange={onChangeCuboidDrawingMethod}
    87. >
    88. <Radio value={CuboidDrawingMethod.CLASSIC} style={{ width: 'auto' }}>
    89. From rectangle
    90. </Radio>
    91. <Radio value={CuboidDrawingMethod.CORNER_POINTS} style={{ width: 'auto' }}>
    92. By 4 Points
    93. </Radio>
    94. </Radio.Group>
    95. </Col>
    96. </Row>
    97. </>
    98. )}
    99. {is2D && shapeType !== ShapeType.RECTANGLE &&
    100. shapeType !== ShapeType.CIRCLE && shapeType !== ShapeType.CUBOID && (
    101. <Row justify='space-around' align='middle'>
    102. <Col span={14}>
    103. <Text className='cvat-text-color'> Number of points: </Text>
    104. </Col>
    105. <Col span={10}>
    106. <InputNumber
    107. onChange={(value: number | undefined | string | null) => {
    108. if (typeof value === 'undefined' || value === null) {
    109. onChangePoints(undefined);
    110. } else {
    111. onChangePoints(Math.floor(clamp(+value, minimumPoints, Number.MAX_SAFE_INTEGER)));
    112. }
    113. }}
    114. className='cvat-draw-shape-popover-points-selector'
    115. min={minimumPoints}
    116. value={numberOfPoints}
    117. step={1}
    118. />
    119. </Col>
    120. </Row>
    121. )}
    122. <Row justify='space-around'>
    123. <Col span={12}>
    124. <CVATTooltip title={`Press ${repeatShapeShortcut} to draw again`}>
    125. <Button onClick={onDrawShape}>Shape</Button>
    126. </CVATTooltip>
    127. </Col>
    128. {is2D && (
    129. <Col span={12}>
    130. <CVATTooltip title={`Press ${repeatShapeShortcut} to draw again`}>
    131. <Button onClick={onDrawTrack}>Track</Button>
    132. </CVATTooltip>
    133. </Col>
    134. )}
    135. </Row>
    136. </div>
    137. );

    }

    export default React.memo(DrawShapePopoverComponent);

    1. 12. tools-control.tsx
    1. private collectTrackerPortals(): React.ReactPortal[] {
    2. const { states, fetchAnnotations } = this.props;
    3. const { trackedShapes, activeTracker } = this.state;
    4. const trackedClientIDs = trackedShapes.map((trackedShape: TrackedShape) => trackedShape.clientID);
    5. const portals = !activeTracker ?
    6. [] :
    7. states
    8. .filter((objectState) => objectState.objectType === 'track' && (objectState.shapeType === 'rectangle' || objectState.shapeType === 'circle'))
    9. .map((objectState: any): React.ReactPortal | null => {
    10. const { clientID } = objectState;
    11. const selectorID = `#cvat-objects-sidebar-state-item-${clientID}`;
    12. let targetElement = window.document.querySelector(
    13. `${selectorID} .cvat-object-item-button-prev-keyframe`,
    14. ) as HTMLElement;
    15. const isTracked = trackedClientIDs.includes(clientID);
    16. if (targetElement) {
    17. targetElement = targetElement.parentElement?.parentElement as HTMLElement;
    18. return ReactDOM.createPortal(
    19. <Col>
    20. {isTracked ? (
    21. <CVATTooltip overlay='Disable tracking'>
    22. <EnvironmentFilled
    23. onClick={() => {
    24. const filteredStates = trackedShapes.filter(
    25. (trackedShape: TrackedShape) => trackedShape.clientID !== clientID,
    26. );
    27. /* eslint no-param-reassign: ["error", { "props": false }] */
    28. objectState.descriptions = [];
    29. objectState.save().then(() => {
    30. this.setState({
    31. trackedShapes: filteredStates,
    32. });
    33. });
    34. fetchAnnotations();
    35. }}
    36. />
    37. </CVATTooltip>
    38. ) : (
    39. <CVATTooltip overlay={`Enable tracking using ${activeTracker.name}`}>
    40. <EnvironmentOutlined
    41. onClick={() => {
    42. objectState.descriptions = [`Trackable (${activeTracker.name})`];
    43. objectState.save().then(() => {
    44. this.setState({
    45. trackedShapes: [
    46. ...trackedShapes,
    47. {
    48. clientID,
    49. serverlessState: null,
    50. shapePoints: objectState.points,
    51. trackerModel: activeTracker,
    52. },
    53. ],
    54. });
    55. });
    56. fetchAnnotations();
    57. }}
    58. />
    59. </CVATTooltip>
    60. )}
    61. </Col>,
    62. targetElement,
    63. );
    64. }
    65. return null;
    66. })
    67. .filter((portal: ReactPortal | null) => portal !== null);
    68. return portals as React.ReactPortal[];
    69. }
    1. 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’, }

    1. 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(); });

    1. 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): void; activate(clientID: number | null, attributeID?: number): void; rotate(rotationAngle: number): void; focus(clientID: number, padding?: number): void; fit(): void; grid(stepX: number, stepY: number): void;

    1. interact(interactionData: InteractionData): void;
    2. draw(drawData: DrawData): void;
    3. group(groupData: GroupData): void;
    4. split(splitData: SplitData): void;
    5. merge(mergeData: MergeData): void;
    6. select(objectState: any): void;
    7. fitCanvas(): void;
    8. bitmap(enable: boolean): void;
    9. selectRegion(enable: boolean): void;
    10. dragCanvas(enable: boolean): void;
    11. zoomCanvas(enable: boolean): void;
    12. mode(): Mode;
    13. cancel(): void;
    14. configure(configuration: Configuration): void;
    15. isAbleToChangeFrame(): boolean;
    16. readonly geometry: Geometry;

    }

    class CanvasImpl implements Canvas { private model: CanvasModel & Master; private controller: CanvasController; private view: CanvasView;

    1. public constructor() {
    2. this.model = new CanvasModelImpl();
    3. this.controller = new CanvasControllerImpl(this.model);
    4. this.view = new CanvasViewImpl(this.model, this.controller);
    5. }
    6. public html(): HTMLDivElement {
    7. return this.view.html();
    8. }
    9. public setup(frameData: any, objectStates: any[], zLayer = 0): void {
    10. this.model.setup(frameData, objectStates, zLayer);
    11. }
    12. public setupIssueRegions(issueRegions: Record<number, number[]>): void {
    13. this.model.setupIssueRegions(issueRegions);
    14. }
    15. public fitCanvas(): void {
    16. this.model.fitCanvas(this.view.html().clientWidth, this.view.html().clientHeight);
    17. }
    18. public bitmap(enable: boolean): void {
    19. this.model.bitmap(enable);
    20. }
    21. public selectRegion(enable: boolean): void {
    22. this.model.selectRegion(enable);
    23. }
    24. public dragCanvas(enable: boolean): void {
    25. this.model.dragCanvas(enable);
    26. }
    27. public zoomCanvas(enable: boolean): void {
    28. this.model.zoomCanvas(enable);
    29. }
    30. public activate(clientID: number | null, attributeID: number | null = null): void {
    31. this.model.activate(clientID, attributeID);
    32. }
    33. public rotate(rotationAngle: number): void {
    34. this.model.rotate(rotationAngle);
    35. }
    36. public focus(clientID: number, padding = 0): void {
    37. this.model.focus(clientID, padding);
    38. }
    39. public fit(): void {
    40. this.model.fit();
    41. }
    42. public grid(stepX: number, stepY: number): void {
    43. this.model.grid(stepX, stepY);
    44. }
    45. public interact(interactionData: InteractionData): void {
    46. this.model.interact(interactionData);
    47. }
    48. public draw(drawData: DrawData): void {
    49. this.model.draw(drawData);
    50. }
    51. public split(splitData: SplitData): void {
    52. this.model.split(splitData);
    53. }
    54. public group(groupData: GroupData): void {
    55. this.model.group(groupData);
    56. }
    57. public merge(mergeData: MergeData): void {
    58. this.model.merge(mergeData);
    59. }
    60. public select(objectState: any): void {
    61. this.model.select(objectState);
    62. }
    63. public mode(): Mode {
    64. return this.model.mode;
    65. }
    66. public cancel(): void {
    67. this.model.cancel();
    68. }
    69. public configure(configuration: Configuration): void {
    70. this.model.configure(configuration);
    71. }
    72. public isAbleToChangeFrame(): boolean {
    73. return this.model.isAbleToChangeFrame();
    74. }
    75. public get geometry(): Geometry {
    76. return this.model.geometry;
    77. }

    }

    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, };

    1. 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; };

    1. return shapes
    2. .filter((shape: InteractionResult): boolean => shape.button === button)
    3. .map((shape: InteractionResult): number[] => shape.points)
    4. .flat()
    5. .reduce(reducer, []);

    }

    export type InteractionData = _InteractionData; export type InteractionResult = _InteractionResult;

    export { Canvas, CanvasMode, CanvasVersion, RectDrawingMethod, CircleDrawingMethod, CuboidDrawingMethod, };

    1. 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 = null;

    function getStore(): Store { if (store === null) { store = getCVATStore(); } return store; }

    function receiveAnnotationsParameters(): AnnotationsParameters { if (store === null) { store = getCVATStore(); }

    1. const state: CombinedState = getStore().getState();
    2. const {
    3. annotation: {
    4. annotations: { filters },
    5. player: {
    6. frame: { number: frame },
    7. },
    8. job: { instance: jobInstance },
    9. },
    10. settings: {
    11. workspace: { showAllInterpolationTracks },
    12. },
    13. } = state;
    14. return {
    15. filters,
    16. frame,
    17. jobInstance,
    18. showAllInterpolationTracks,
    19. };

    }

    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); });

    1. return [minZ, maxZ];

    }

    async function jobInfoGenerator(job: any): Promise> { const { total } = await job.annotations.statistics(); return { ‘frame count’: job.stopFrame - job.startFrame + 1, ‘track count’: total.rectangle.shape + total.rectangle.track + total.polygon.shape + total.polygon.track + total.polyline.shape + total.polyline.track + total.points.shape + total.points.track + total.cuboid.shape + total.cuboid.track, ‘object count’: total.total, ‘box count’: total.rectangle.shape + total.rectangle.track, ‘polygon count’: total.polygon.shape + total.polygon.track, ‘polyline count’: total.polyline.shape + total.polyline.track, ‘points count’: total.points.shape + total.points.track, ‘cuboids count’: total.cuboid.shape + total.cuboid.track, ‘tag count’: total.tags, }; }

    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) => { try { await logger.save(); dispatch({ type: AnnotationActionTypes.SAVE_LOGS_SUCCESS, payload: {}, }); } catch (error) { dispatch({ type: AnnotationActionTypes.SAVE_LOGS_FAILED, payload: { error, }, }); } }; }

    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): Promise => { try { const { filters, frame, showAllInterpolationTracks, jobInstance, } = receiveAnnotationsParameters(); const states = await jobInstance.annotations.get(frame, showAllInterpolationTracks, filters); const history = await jobInstance.actions.get(); const [minZ, maxZ] = computeZRange(states);

    1. dispatch({
    2. type: AnnotationActionTypes.FETCH_ANNOTATIONS_SUCCESS,
    3. payload: {
    4. states,
    5. history,
    6. minZ,
    7. maxZ,
    8. },
    9. });
    10. } catch (error) {
    11. dispatch({
    12. type: AnnotationActionTypes.FETCH_ANNOTATIONS_FAILED,
    13. payload: {
    14. error,
    15. },
    16. });
    17. }
    18. };

    }

    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): Promise => { try { const { filters, frame, showAllInterpolationTracks, jobInstance, } = receiveAnnotationsParameters(); await jobInstance.annotations.clear(false, startFrame, endFrame, delTrackKeyframesOnly); await jobInstance.actions.clear(); const history = await jobInstance.actions.get(); const states = await jobInstance.annotations.get(frame, showAllInterpolationTracks, filters);

    1. dispatch({
    2. type: AnnotationActionTypes.REMOVE_JOB_ANNOTATIONS_SUCCESS,
    3. payload: {
    4. history,
    5. states,
    6. },
    7. });
    8. } catch (error) {
    9. dispatch({
    10. type: AnnotationActionTypes.REMOVE_JOB_ANNOTATIONS_FAILED,
    11. payload: {
    12. error,
    13. },
    14. });
    15. }
    16. };

    }

    export function uploadJobAnnotationsAsync(job: any, loader: any, file: File): ThunkAction { return async (dispatch: ActionCreator): Promise => { try { const state: CombinedState = getStore().getState(); const { filters, showAllInterpolationTracks } = receiveAnnotationsParameters();

    1. if (state.tasks.activities.loads[job.task.id]) {
    2. throw Error('Annotations is being uploaded for the task');
    3. }
    4. if (state.annotation.activities.loads[job.id]) {
    5. throw Error('Only one uploading of annotations for a job allowed at the same time');
    6. }
    7. dispatch({
    8. type: AnnotationActionTypes.UPLOAD_JOB_ANNOTATIONS,
    9. payload: {
    10. job,
    11. loader,
    12. },
    13. });
    14. const frame = state.annotation.player.frame.number;
    15. await job.annotations.upload(file, loader);
    16. await job.logger.log(LogType.uploadAnnotations, {
    17. ...(await jobInfoGenerator(job)),
    18. });
    19. await job.annotations.clear(true);
    20. await job.actions.clear();
    21. const history = await job.actions.get();
    22. // One more update to escape some problems
    23. // in canvas when shape with the same
    24. // clientID has different type (polygon, rectangle) for example
    25. dispatch({
    26. type: AnnotationActionTypes.UPLOAD_JOB_ANNOTATIONS_SUCCESS,
    27. payload: {
    28. job,
    29. states: [],
    30. history,
    31. },
    32. });
    33. const states = await job.annotations.get(frame, showAllInterpolationTracks, filters);
    34. setTimeout(() => {
    35. dispatch({
    36. type: AnnotationActionTypes.UPLOAD_JOB_ANNOTATIONS_SUCCESS,
    37. payload: {
    38. history,
    39. job,
    40. states,
    41. },
    42. });
    43. });
    44. } catch (error) {
    45. dispatch({
    46. type: AnnotationActionTypes.UPLOAD_JOB_ANNOTATIONS_FAILED,
    47. payload: {
    48. job,
    49. error,
    50. },
    51. });
    52. }
    53. };

    }

    export function collectStatisticsAsync(sessionInstance: any): ThunkAction { return async (dispatch: ActionCreator): Promise => { try { dispatch({ type: AnnotationActionTypes.COLLECT_STATISTICS, payload: {}, });

    1. const data = await sessionInstance.annotations.statistics();
    2. dispatch({
    3. type: AnnotationActionTypes.COLLECT_STATISTICS_SUCCESS,
    4. payload: {
    5. data,
    6. },
    7. });
    8. } catch (error) {
    9. dispatch({
    10. type: AnnotationActionTypes.COLLECT_STATISTICS_FAILED,
    11. payload: {
    12. error,
    13. },
    14. });
    15. }
    16. };

    }

    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): Promise => { try { const copy = { attributes: objectState.attributes, points: objectState.points, occluded: objectState.occluded, objectType: objectState.objectType !== ObjectType.TRACK ? objectState.objectType : ObjectType.SHAPE, shapeType: objectState.shapeType, label: objectState.label, zOrder: objectState.zOrder, frame: from, source: objectState.source, };

    1. await sessionInstance.logger.log(LogType.propagateObject, { count: to - from + 1 });
    2. const states = [];
    3. for (let frame = from; frame <= to; frame++) {
    4. copy.frame = frame;
    5. const newState = new cvat.classes.ObjectState(copy);
    6. states.push(newState);
    7. }
    8. await sessionInstance.annotations.put(states);
    9. const history = await sessionInstance.actions.get();
    10. dispatch({
    11. type: AnnotationActionTypes.PROPAGATE_OBJECT_SUCCESS,
    12. payload: {
    13. objectState,
    14. history,
    15. },
    16. });
    17. } catch (error) {
    18. dispatch({
    19. type: AnnotationActionTypes.PROPAGATE_OBJECT_FAILED,
    20. payload: {
    21. error,
    22. },
    23. });
    24. }
    25. };

    }

    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): Promise => { try { await sessionInstance.logger.log(LogType.deleteObject, { count: 1 }); const { frame } = receiveAnnotationsParameters();

            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): Promise => { const { annotations: { states: currentStates, zLayer: { cur: curZOrder }, }, predictor: { enabled, annotatedFrames }, } = getStore().getState().annotation;

        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): Promise => { const state: CombinedState = getStore().getState(); const { instance: job } = state.annotation.job; const { filters, frame, showAllInterpolationTracks } = receiveAnnotationsParameters();

        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): Promise => { try { const state = getStore().getState(); const { filters, showAllInterpolationTracks } = receiveAnnotationsParameters();

            // 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): Promise => { try { const state = getStore().getState(); const { filters, showAllInterpolationTracks } = receiveAnnotationsParameters();

            // 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): Promise => { const { jobInstance } = receiveAnnotationsParameters(); if (jobInstance) { await jobInstance.task.close(); }

        dispatch({
            type: AnnotationActionTypes.CLOSE_JOB,
        });
    };
    

    }

    export function getJobAsync(tid: number, jid: number, initialFrame: number, initialFilters: object[]): ThunkAction { return async (dispatch: ActionCreator): Promise => { try { const state: CombinedState = getStore().getState(); const filters = initialFilters; const { settings: { workspace: { showAllInterpolationTracks }, }, } = state;

            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): Promise => { const { filters, showAllInterpolationTracks } = receiveAnnotationsParameters();

        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): Promise => { const { jobInstance, filters, frame, showAllInterpolationTracks, } = receiveAnnotationsParameters();

        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): Promise => { try { const { filters, showAllInterpolationTracks } = receiveAnnotationsParameters(); await sessionInstance.annotations.put(statesToCreate); const states = await sessionInstance.annotations.get(frame, showAllInterpolationTracks, filters); const history = await sessionInstance.actions.get();

            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): Promise => { try { const { filters, showAllInterpolationTracks } = receiveAnnotationsParameters(); await sessionInstance.annotations.merge(statesToMerge); const states = await sessionInstance.annotations.get(frame, showAllInterpolationTracks, filters); const history = await sessionInstance.actions.get();

            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): Promise => { try { const { filters, showAllInterpolationTracks } = receiveAnnotationsParameters(); const reset = getStore().getState().annotation.annotations.resetGroupFlag;

            // 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): Promise => { const { filters, showAllInterpolationTracks } = receiveAnnotationsParameters(); try { await sessionInstance.annotations.split(stateToSplit, frame); const states = await sessionInstance.annotations.get(frame, showAllInterpolationTracks, filters); const history = await sessionInstance.actions.get();

            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): Promise => { const state: CombinedState = getStore().getState(); const groupStates = state.annotation.annotations.states.filter( (_state: any): boolean => _state.group.id === group, ); if (groupStates.length) { groupStates[0].group.color = color; dispatch(updateAnnotationsAsync(groupStates)); } else { dispatch(updateAnnotationsAsync([])); } }; }

    export function searchAnnotationsAsync(sessionInstance: any, frameFrom: number, frameTo: number): ThunkAction { return async (dispatch: ActionCreator): Promise => { try { const { filters } = receiveAnnotationsParameters(); const frame = await sessionInstance.annotations.search(filters, frameFrom, frameTo); if (frame !== null) { dispatch(changeFrameAsync(frame)); } } catch (error) { dispatch({ type: AnnotationActionTypes.SEARCH_ANNOTATIONS_FAILED, payload: { error, }, }); } }; }

    export function searchEmptyFrameAsync(sessionInstance: any, frameFrom: number, frameTo: number): ThunkAction { return async (dispatch: ActionCreator): Promise => { try { const frame = await sessionInstance.annotations.searchEmpty(frameFrom, frameTo); if (frame !== null) { dispatch(changeFrameAsync(frame)); } } catch (error) { dispatch({ type: AnnotationActionTypes.SEARCH_EMPTY_FRAME_FAILED, payload: { error, }, }); } }; }

    export function pasteShapeAsync(): ThunkAction { return async (dispatch: ActionCreator): Promise => { const { canvas: { instance: canvasInstance }, job: { instance: jobInstance }, player: { frame: { number: frameNumber }, }, drawing: { activeInitialState: initialState }, } = getStore().getState().annotation;

        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): Promise => { const { canvas: { instance: canvasInstance }, job: { labels, instance: jobInstance }, player: { frame: { number: frameNumber }, }, drawing: { activeInteractor, activeObjectType, activeLabelID, activeShapeType, activeNumOfPoints, activeRectDrawingMethod, activeCircleDrawingMethod, activeCuboidDrawingMethod, }, } = getStore().getState().annotation;

        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): Promise => { const { annotations: { activatedStateID, states }, canvas: { instance: canvasInstance }, } = getStore().getState().annotation;

        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): Promise => { const state: CombinedState = getStore().getState(); const { instance: job } = state.annotation.job; const { number: frameNumber } = state.annotation.player.frame;

        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; canvasInstance: Canvas | Canvas3d; shapeType: ShapeType; labels: any[]; jobInstance: any; }

    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 { private minimumPoints = 3;

    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; type CloudStoragePreview = 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; fetching: boolean; saving: boolean; }; player: { frame: { number: number; filename: string; hasRelatedContext: boolean; data: any | null; fetching: boolean; delay: number; changeTime: number | null; }; navigationBlocked: boolean; playing: boolean; frameAngles: number[]; contextImage: { fetching: boolean; data: string | null; hidden: boolean; }; }; drawing: { activeInteractor?: Model | OpenCVTool; activeShapeType: ShapeType; activeRectDrawingMethod?: RectDrawingMethod; activeCircleDrawingMethod?: CircleDrawingMethod; activeCuboidDrawingMethod?: CuboidDrawingMethod; activeNumOfPoints?: number; activeLabelID: number; activeObjectType: ObjectType; activeInitialState?: any; }; annotations: { activatedStateID: number | null; activatedAttributeID: number | null; collapsed: Record; collapsedAll: boolean; states: any[]; filters: any[]; resetGroupFlag: boolean; history: { undo: [string, number][]; redo: [string, number][]; }; saving: { forceExit: boolean; uploading: boolean; statuses: string[]; }; zLayer: { min: number; max: number; cur: number; }; }; propagate: { objectState: any | null; frames: number; }; statistics: { collecting: boolean; visible: boolean; data: any; }; colors: any[]; filtersPanelVisible: boolean; requestReviewDialogVisible: boolean; submitReviewDialogVisible: boolean; sidebarCollapsed: boolean; appearanceCollapsed: boolean; workspace: Workspace; predictor: PredictorState; }

    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’, }

    ```