-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcomponents.js
More file actions
11694 lines (9142 loc) · 364 KB
/
Copy pathcomponents.js
File metadata and controls
11694 lines (9142 loc) · 364 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Components used on the interface
*/
import {
showAlertToast,
showAlertModal,
getFileNameWithoutExtension,
secondsToFrames,
framesToSeconds,
formatSeconds,
showOverlappingTracksToast,
getRandomLetterNotIn,
clearEthogramTable,
showProcessIndicator,
hideProcessIndicator,
produceLabelText,
updateHotkeyDomElement,
showToastForBehaviorRecording,
showLastEditForFile,
handleBehaviorRecordByClick,
updateTracksFromToast,
updateTracksFromNameDropdown,
addEthogramRow,
updateZoomScaleDomEls,
getUserConfirmationOnModal,
hideAlertModal,
showPopover,
getRandomColors,
updateClassEls,
} from './helpers.js';
class Observation {
/**
*
* @param {Map} entries
*/
constructor(entries) {
// Check if the input is given and an instance of Map
if (entries && entries instanceof Map) {
this.entries = entries;
} else {
// If no input is given or it is not in correct format, initialize the instance
this.entries = new Map([
['index', null],
['subjectName', null],
['subjectId', null],
['subjectClass', null],
['action', null],
['targetName', null],
['targetId', null],
['targetClass', null],
['startFrame', null],
['endFrame', null],
]);
}
// Track the last update for undo functionality
this.lastUpdatedKeys = [];
}
get(key) {
return this.entries.get(key);
}
/**
* Updates the observation
* @param {Array} entries Array of key-value pairs
*/
update(...entries) {
let updatedKeys = [];
for (const [key, value] of entries) {
this.entries.set(key, value);
updatedKeys.push(key);
}
// Keep track of the last updated keys
this.lastUpdatedKeys.push(updatedKeys);
// Show the changes on the HTML element
this.show();
}
/**
* Undoes the last selection
* @param {...any} keys
*/
undo() {
// Undo the values of the saved keys from the last selection
const undoKeyArr = this.lastUpdatedKeys.pop();
// Set the given key's value to null
if (undoKeyArr) {
undoKeyArr.forEach(key => this.entries.set(key, null));
}
// Show the changes on the HTML element
this.show();
}
/**
* Gets the entries of an observation
* @returns {Map} - Map of entries
*/
getEntries() {
return this.entries;
}
/**
* Gets the last updated keys of an observation
* @returns {Array} - Last updated key strings
*/
getLastSelection() {
return this.lastUpdatedKeys;
}
/**
* Gets the index of an observation
* @returns {Number} - Index within the ethogram
*/
get index() {
return this.entries.get('index');
}
/**
* Gets the subject name of an observation
* @returns {String} - Subject name
*/
get subjectName() {
return this.entries.get('subjectName');
}
/**
* Gets the subject id of an observation
* @returns {Number}
*/
get subjectId() {
return this.entries.get('subjectId');
}
/**
* Gets the action of an observation
* @returns {String}
*/
get action() {
return this.entries.get('action');
}
/**
* Gets the target name of an observation
* @returns {String}
*/
get targetName() {
return this.entries.get('targetName');
}
/**
* Gets the target id of an observation
* @returns {Number}
*/
get targetId() {
return this.entries.get('targetId');
}
/**
* Gets the target class of an observation
* @returns {Number} - Target class ID
*/
get targetClass() {
return this.entries.get('targetClass');
}
/**
* Gets the starting frame of an observation
* @returns {Number}
*/
get startFrame() {
return this.entries.get('startFrame');
}
/**
* Gets the starting frame of an observation
* @returns {Number}
*/
get endFrame() {
return this.entries.get('endFrame');
}
/**
* Gets the subject ID of an observation
* @returns {Number} - Subject ID
*/
get subjectId() {
return this.entries.get('subjectId');
}
/**
* Gets the subject class of an observation
* @returns {Number} - Subject class ID
*/
get subjectClass() {
return this.entries.get('subjectClass');
}
/**
* Checks if the current observation is empty
* @returns - True if all values of the current observation is null
*/
isEmpty() {
return this.entries.values().every(value => value === null);
}
/**
* Shows the current observation on its associated HTML element
*/
show() {
// Get the HTML element for current observation
const divEl = document.getElementById('current-observation-div');
if (!divEl) return;
// Check whether the current observation is empty and no previous observation exists
if (Player.getCurrentObservation().isEmpty()) {
// Hide the div element
divEl.classList.add('d-none');
} else {
// Get the selection from the current observation
const subjectName = this.subjectName;
const action = this.action;
const targetName = this.targetName;
const startTime = this.startFrame;
const endTime = this.endFrame;
// Make the div element visible
divEl.classList.remove('d-none');
// Show the description of the observation (subject name, action, target name)
const descriptionEl = divEl.querySelector('#current-observation-description');
if (descriptionEl) {
// Show the fields which are not null
const selections = [subjectName, action, targetName].filter(selection => selection !== null);
descriptionEl.textContent = selections.join('-');
}
// Show the starting and ending time of the observation
const startTimeEl = divEl.querySelector('#current-observation-start');
if (startTimeEl) {
if (startTime !== null) {
startTimeEl.textContent = formatSeconds(framesToSeconds(startTime));
// Add starting frame to dataset to allow user to jump to that frame via clicking
startTimeEl.dataset.frameNumber = startTime;
}
}
// Show the starting and ending time of the observation
const endTimeEl = divEl.querySelector('#current-observation-end');
if (endTimeEl) {
// Hide the element by default
endTimeEl.classList.add('d-none');
// Check if end time is given
if (endTime !== null) {
// Make the element visible
endTimeEl.classList.remove('d-none');
// Convert frames to MM:SS
endTimeEl.textContent = formatSeconds(framesToSeconds(endTime));
// Add starting frame to dataset to allow user to jump to that frame via clicking
endTimeEl.dataset.frameNumber = endTime;
}
}
// Show the last selected action as a badge
const badgeEl = divEl.querySelector('#current-observation-badge');
if (badgeEl) {
// Determine the last selection
let lastSelection;
if (subjectName !== null) {
lastSelection = 'subject';
}
if (action !== null) {
lastSelection = 'action';
}
if (targetName !== null && endTime !== null) {
lastSelection = 'target';
}
badgeEl.textContent = lastSelection;
}
}
}
}
// Player
class Player {
// get the DOM element id and options for the video
domId;
options;
// Determine whether the operation system is MacOS
static onMacOS = window.electronAPI.getPlatform() === 'darwin';
static allInstances = []; // Save all instances of Players
static secondaryPlayers = [];
static mainPlayer;
static skipSeconds = 5;
// static frameRate = 29.97; // !!Get the frame rate dynamically instead of hard coding!!
static maxPlaybackRate = 2;
static minPlaybackRate = 0.25;
static individualNames; // Names of individual primates
static actionNameArr; // Names of actions
static labelingMode = false; // Boolean to activate hotkeys for recording behaviors
static isTyping = false;// Boolean to determine if user is typing in a text area or input
static pressedKeys = [];
static timeoutKeyPress = null;
static keyState = {}; // Track the state of each pressed key (to determine to combined key presses)
static statusUpdateFreq = 60000; // Set the update frequency for showing last modified times for file (in milliseconds)
static ethogramIntervalId;
static notesIntervalId;
static appVersion; // App version number
static zoomDragColor = 'yellow'; // Color for drawing a rectangle on a canvas for zooming into a video
static zoomScale = 2; // Zoom scale for the main player (2 -> 2x -> 200%)
static minZoomScale = 1; // Minimum zoom level
static maxZoomScale = 6; // Maximum zoom level
static zoomRequestId; // Request Id for zooming (to be used with requestAnimationFrame and cleared when the player is paused or ended)
static draggedDist = 0; // Actual distance in pixels for mouse drag to prevent clicks or accidental mouse moves from being registered as drags
static minDragDist = 10; // Threshold in pixels to register mouse drags
static mouseDragTimeThreshold = 1000; // Time in ms to check if the previous mouse down event is more than this threshold to prevent accidental clicks from being registered as drags
static mouseIsDown = false;
static lastMouseDownTime = 0;
static isResizing = false; // Set to true if user is resizing one of the tracking boxes on the canvas
static settingsModalId = 'settings-modal';
static snapshotModalId = 'snapshot-modal';
static drawnBBoxDivId = 'new-bounding-box-confirm-div'; // DOM ID for div for selecting properties of the user-drawn bounding box
static drawnBBoxClassInputId = 'class-choice-new-bbox'; // DOM ID for input element to change/assign class to the user-drawn bounding box
static drawnBoundingBox; // Holds the BoundingBox instance for user-drawn bounding box on the drawing canvas
static drawingMode = false; // Boolean to determine if user can draw new tracking boxes freely
static drawingCanvasId = 'main-drawing-canvas';
static activeBtnClass = 'text-info';
static toggleLabelingBtnId = 'toggle-labeling-mode-btn';
static toggleTrackingBtnId = 'toggle-tracking-btn';
static visibleTracks = true; // Flag to show/hide bounding boxes on the main canvas
static zoomingMode = false;
static resizedBBoxDivId = 'bounding-box-resize-confirm-div';
static jumpToFrameInputId = 'jump-to-frame-input';
static jumpToFrameBtnId = 'jump-to-frame-btn';
static areBoxesInteractive = false; // Tracks whether the bounding boxes on canvas are interactive/clickable
// Track the current observation for behavior recording
static currentObservation = new Observation();
// Username for saving to metadata of exported files
static username;
static setMouseDown() {
if (!Player.hasOwnProperty('mouseIsDown')) return;
Player.mouseIsDown = true;
}
static isMouseDown() {
return Player.mouseIsDown;
}
static resetMouseDown() {
if (!Player.hasOwnProperty('mouseIsDown')) return;
Player.mouseIsDown = false;
}
/**
* Gets the video with
* @returns
*/
getVideoWidth() {
return this.el?.videoWidth;
}
/**
* Gets the video height
* @returns
*/
getVideoHeight() {
return this.el?.videoHeight;
}
/**
* Sets the count for the running number of tracks per class across snapshots when exporting labels with snapshots is selected.
* @param {String | Number} classId Class ID
* @param {Number | String} runningCount Running count must be non-negative integer
* @returns {Number | undefined} Updated running count if the operation is successful, undefined otherwise.
*/
static setClassRunningCount(classId, runningCount) {
return Player.getMainPlayer?.().getTrackingMap?.()?.setClassRunningCount?.(classId, runningCount);
}
/**
* Gets the running counts of all classes across snapshots previously saved into the config file
* @returns {Number[] | undefined } Array of running counts or undefined in case of an error.
*/
static getClassRunningCounts() {
return Player.getMainPlayer?.().getTrackingMap?.()?.getClassRunningCounts?.();
}
/**
* Gets the bounding boxes under the mouse
* @param {Number} mouseX
* @param {Number} mouseY
* @param {BoundingBox[] | undefined} boxArr Array of boxes to search for. If undefined, bounding boxes in the current frame of the main player will be used.
* @returns {BoundingBox[] | undefined}
*/
static getBoxesUnderMouse(mouseX, mouseY, boxArr) {
if (typeof mouseX === 'undefined' || typeof mouseY === 'undefined') return;
if (mouseX === null || mouseY === null) return;
const boxesInFrame = Array.isArray(boxArr) ? boxArr : Player.getMainPlayer()?.getTrackingBoxesInFrame();
if (!Array.isArray(boxesInFrame)) return;
const boxesUnderMouse = [];
boxesInFrame.forEach(bBox => {
if ( !(bBox instanceof BoundingBox) ) return;
// Get the coordinates and dimensions and check the validity
const x = bBox.getX?.();
const y = bBox.getY?.();
const width = bBox.getWidth?.();
const height = bBox.getHeight?.();
for (const prop of [x, y, width, height]) {
if (!Number.isFinite(prop)) return;
}
// Check if the box is under the mouse
if ( !(mouseX >= x && mouseX <= x + width && mouseY >= y && mouseY <= y + height) ) return;
// Add the valid bBox to the array
boxesUnderMouse.push(bBox);
});
return boxesUnderMouse;
}
static getBoxesInFrame() {
return Player.getMainPlayer()?.getTrackingBoxesInFrame();
}
/**
* Detects whether the mouse is over any of the resizing handles of any of bounding boxes under the mouse
* @param {BoundingBox[]} bBoxes Bounding boxes under the mouse
* @param {Number} mouseX x-coordinate of mouse
* @param {Number} mouseY y-coordinate of mouse
* @returns {Object | undefined} result object
* @returns {Object | undefined} result.box Box object
* @returns {String | undefined} result.handleName Name of the resize handle
*/
static isMouseInResizeHandle(bBoxes, mouseX, mouseY) {
const result = { box: null, handleName: null };
// Check the validity
for (const inputVal of [ bBoxes, mouseX, mouseY ]) {
if (typeof inputVal === 'undefined' || inputVal === null) return;
}
// Check if array is given
if (!Array.isArray(bBoxes)) return result;
// Get the handle size in pixels for resizing rectangles
const handleSize = BoundingBox.getResizeHandleSize();
// Iterate over the bounding boxes
bBoxes.forEach(bBox => {
// Check the validity
if (!(bBox instanceof BoundingBox)) return;
// Get the handles
const handles = [
{ name: 'tl', x: bBox.getX(), y: bBox.getY() }, // Top-left
{ name: 'tr', x: bBox.getX() + bBox.getWidth(), y: bBox.getY() }, // Top-right
{ name: 'bl', x: bBox.getX(), y: bBox.getY() + bBox.getHeight() }, // Bottom-left
{ name: 'br', x: bBox.getX() + bBox.getWidth(), y: bBox.getY() + bBox.getHeight() }, // Bottom-right
{ name: 'tc', x: bBox.getX() + bBox.getWidth()/2, y: bBox.getY() }, // Top-center
{ name: 'bc', x: bBox.getX() + bBox.getWidth()/2, y: bBox.getY() + bBox.getHeight() }, // Bottom-center
{ name: 'rc', x: bBox.getX() + bBox.getWidth(), y: bBox.getY() + bBox.getHeight()/2 }, // Right-center
{ name: 'lc', x: bBox.getX(), y: bBox.getY() + bBox.getHeight()/2 } // Left-center
];
// Determine which handle the mouse is on
for (const handle of handles) {
if (
mouseX >= handle.x - handleSize/2 && mouseX <= handle.x + handleSize/2 &&
mouseY >= handle.y - handleSize/2 && mouseY <= handle.y + handleSize/2
) {
result.box = bBox;
result.handleName = handle.name;
}
}
});
// Return the result
return result;
// Check if mouse is inside the handle (located at right bottom corner of a tracking box)
// return (
// mouseX >= box.x + box.width - handleSize &&
// mouseX <= box.x + box.width + handleSize &&
// mouseY >= box.y + box.height - handleSize &&
// mouseY <= box.y + box.height + handleSize
// );
}
/**
* Imports a file containing individual names
* @param {import("original-fs").PathLike | undefined} filePath If file path is undefined, it will show a dialog to user for file selection
* @returns
*/
static async importNameFile(filePath) {
let userFilePath = filePath;
// If no argument is provided, show a dialog for file selection
if (!userFilePath) {
const dialogResp = await window.electronAPI.openSingleFile('individuals');
if (!dialogResp) {
showAlertToast('Please try again.', 'error', 'Invalid/Inaccessible File');
return;
} else if (dialogResp.canceled) {
return;
}
userFilePath = dialogResp.filePath
}
// Check validity of the chosen file path
if (!userFilePath) {
showAlertToast('Please try again.', 'error', 'File Import Failed');
return;
};
// Read the file
const readResponse = await window.electronAPI.readNameFile(userFilePath);
if (!readResponse) {
showAlertToast('Please try again.', 'error', 'File Import Failed');
return;
}
const { names: nameArr, reason: failureReason } = readResponse;
if (!nameArr && failureReason) {
showAlertToast(failureReason, 'error', 'File Import Failed');
return;
}
// Save names to Player object
const individualNames = Player.setIndividualNames(nameArr);
if (!individualNames) {
showAlertToast('Please try again.', 'error', 'Failed to Save Names');
return;
}
// Save names to config
Config.individualNames = individualNames;
const response = await Config.saveToFile();
if (!response) {
showAlertToast('Please try again.', 'error', 'File Import Failed');
return;
};
showAlertToast('Individual names imported!', 'success', 'File Imported');
}
/**
* Imports a file containing action types
* @param {import("original-fs").PathLike | undefined} filePath If file path is undefined, it will show a dialog to user for file selection
* @returns
*/
static async importActionFile(filePath) {
let userFilePath = filePath;
// If no argument is provided, show a dialog for file selection
if (!userFilePath) {
const dialogResp = await window.electronAPI.openSingleFile('actions');
if (!dialogResp) {
showAlertToast('Please try again.', 'error', 'Invalid/Inaccessible File');
return;
} else if (dialogResp.canceled) {
return;
}
userFilePath = dialogResp.filePath
}
// Check validity of the chosen file path
if (!userFilePath) {
showAlertToast('Please try again with a valid file!', 'error', 'File Import Failed');
return;
}
// Read the file
const readResponse = await window.electronAPI.readNameFile(userFilePath);
if (!readResponse) {
showAlertToast('Please try again.', 'error', 'File Import Failed');
return;
}
const { names: nameArr, reason: failureReason } = readResponse;
if (!nameArr && failureReason) {
showAlertToast(failureReason, 'error', 'File Import Failed');
return;
}
const actionNames = await Player.setActionNames(nameArr); // Save action types
if (!actionNames) {
showAlertToast('Please try again.', 'error', 'Failed to Save Names');
return;
}
// Save to config
Config.actionNames = nameArr;
const response = await Config.saveToFile();
if (!response) {
console.log('Action names could not be saved to config file!', 'error');
return;
}
showAlertToast('Action types imported!', 'success', 'File Imported')
}
/**
* Imports a tracking file
* @param {import("original-fs").PathLike | undefined} filePath If undefined, user will be shown a dialog for file selection
*/
static async importTrackingFile(filePath) {
// Warn if no video is opened yet
const mainPlayer = Player.getMainPlayer();
if (!mainPlayer) {
showAlertToast('Open the main video first!', 'warning', 'Tracking Unavailable');
return;
}
// Pause the player
mainPlayer.pause();
let userFilePath = filePath;
// If no argument is provided, show a dialog for file selection
if (!userFilePath) {
const dialogResp = await window.electronAPI.openSingleFile('tracking');
if (!dialogResp) {
showAlertToast('Please try again.', 'error', 'Invalid/Inaccessible File');
return;
} else if (dialogResp.canceled) {
return;
}
userFilePath = dialogResp.filePath
}
showProcessIndicator();
// Search for metadata file in the user data directory
let metadataRsp; // Object to hold response from metadata file reading function
const metadataFilePath = await window.electronAPI.findMetadataFile(mainPlayer.getSource());
if (metadataFilePath) {
metadataRsp = await window.electronAPI.readMetadataFile(metadataFilePath);
if (metadataRsp) {
if (metadataRsp.timestamp) {
Player.setCurrentTimeAll(metadataRsp.timestamp);
}
// Look for saved individual names first in metadata, then in config if no names in metadata
const nameArr = metadataRsp.individuals ?? Config.individualNames;
Player.setIndividualNames(nameArr);
}
}
const trackArr = await window.electronAPI.readTrackingFile(userFilePath);
if (!trackArr) {
showAlertToast('Could not process tracking file!', 'error');
hideProcessIndicator();
return;
}
// Set the tracking map
// const trackingMap = result.trackingMap;
// const firstAvailTrackIds = result.firstAvailTrackIds;
// const idMap = result.idMap;
mainPlayer.setTrackingMap({
tracks: trackArr,
classNames: metadataRsp?.classNames,
classColors: metadataRsp?.classColors,
});
// Get the video file name
const fileName = mainPlayer.getName();
// Copy tracking file to the user directory
const response = await window.electronAPI.copyToUserDataDir(userFilePath, `${fileName}_tracking.txt`);
// Show notification on success/error
if (!response) {
showAlertToast('Please try again.', 'error', 'Failed to Save Tracking Data');
hideProcessIndicator();
return;
}
// Show success
hideProcessIndicator();
showAlertToast('Tracking file processed!', 'success');
}
/**
* Imports a behavior file
* @param {import("original-fs").PathLike | undefined} filePath If undefined, user will be shown a dialog for file selection
*/
static async importBehaviorFile(filePath) {
// Check if the main video is opened
const mainPlayer = Player.getMainPlayer();
if (!mainPlayer) {
showAlertToast('Open the main video before importing behaviors!', 'warning');
return;
}
// Check if the Ethogram instance was initialized
const ethogram = mainPlayer.getEthogram();
if (!ethogram) {
console.log('No Behavior instance for this player could be found!');
return;
}
// ---------------------------------------------------------
// Handle importing a new ethogram when there is already one
// ---------------------------------------------------------
// Check if an ethogram file with non-zero observations is already saved
const mainVideoPath = mainPlayer.getSource();
const ethogramFilePath = await window.electronAPI.findBehaviorFile(mainVideoPath);
if (ethogramFilePath) {
// Read the ethogram file (get the array of observations, each as a Map)
try {
const obsArr = await window.electronAPI.readBehaviorFile(ethogramFilePath);
if (!obsArr) {
showAlertToast('Behavior file could not be read!', 'error');
return;
}
const obsCount = obsArr.length;
if (obsCount > 0) {
const recordText = obsCount === 1 ? 'record' : 'records';
const mainVideoName = mainPlayer.getName();
// Show modal
showAlertModal(
'Behavior File Overwrite',
[
`A record of behaviors with ${obsCount} ${recordText} is already linked to video <span class="badge text-bg-dark">${mainVideoName}</span>.`,
'Importing a new behavior file will overwrite the existing records. Are you sure you want to continue?'
]
);
// Get the user confirmation
const alertConfirmBtn = document.getElementById('alert-confirm-btn');
if (alertConfirmBtn) {
const confirmed = await getUserConfirmationOnModal(alertConfirmBtn);
// If the user cancels the importing process, do not proceed
if (!confirmed) return;
// Hide the modal for the alert
hideAlertModal();
}
}
} catch (err) {
showAlertToast(err, 'error');
return;
}
}
// ----------------------------------------------------------
// End of handling user confirmation for ethogram overwriting
// ----------------------------------------------------------
// If no argument is provided, show a dialog for file selection
let userFilePath = filePath;
if (!userFilePath) {
const dialogResp = await window.electronAPI.openSingleFile('behaviors');
if (!dialogResp) {
showAlertToast('Please try again.', 'error', 'Invalid/Inaccessible File');
return;
} else if (dialogResp.canceled) {
return;
}
userFilePath = dialogResp.filePath
try {
const obsArr = await window.electronAPI.readBehaviorFile(userFilePath);
// Check if the array is empty
const obsCount = obsArr.length;
if (obsCount === 0) {
showAlertToast('No valid record found!', 'error');
return;
}
// Remove the current observations in the ethogram
const isCleared = await ethogram.clear();
if (!isCleared) {
showAlertToast('Behaviors could not be updated! Please try again.', 'error');
return;
}
// Create an Observation instance for each Map instance in the array
// Add this Observation instance to the Ethogram
// Add a new row for each Observation into the HTML table for Ethogram
obsArr.forEach(obsMap => {
const newObs = new Observation(obsMap);
ethogram.add(newObs);
// Add a row for each observation in the HTML table for the ethogram
const hideAlert = true;
addEthogramRow(newObs, hideAlert);
});
} catch (err) {
showAlertToast(err, 'error');
}
}
}
constructor(domId, options) {
this.domId = domId;
this.mainPlayer = domId.includes('main');
this.el = document.getElementById(domId);
// Default setup options
this.el.controls = false;
this.el.autoplay = false;
this.el.preload = 'auto';
// Keep track of added events
this.events = [];
// Coordinates of rectangle for selecting a region for zoom
this.zoomRect = {
tempX: null, // Temporary top left x-coord (Before mouseup event and during mousemove event)
tempY: null,
tempWidth: null, // Temporary width
tempHeight: null,
startX: null, // Final top left x-coord (after mouseup event)
startY: null,
width: null, // Final width (after mouseup event)
height: null,
canvasWidth: null,
canvasHeight: null,
aspectRatio: null,
shouldHideEl: true,
shouldUpdate: false,
};
// Coordinates of rectangle for drawing a new tracking bounding box
this.drawingRect = {
tempX: null, // Temporary top left x-coord (Before mouseup event and during mousemove event)
tempY: null,
tempWidth: null, // Temporary width
tempHeight: null,
startX: null, // Final top left x-coord (after mouseup event)
startY: null,
width: null, // Final width (after mouseup event)
height: null,
canvasWidth: null,
canvasHeight: null,
aspectRatio: null,
shouldHideEl: true,
shouldUpdate: false,
}
this.instanceDrawnOnCanvas; // Holds the instance to handle the current user-drawable bounding box on canvas
// Add user options if provided
if (options !== undefined) {
this.options = options;
for (const option in options) {
this.el[option] = this.options[option]
}
}
// Keep track of whether video DOM element emitted an error
this.errorOnLoad = undefined;
// Handle errors
this.on('error', () => {
console.log('Video cannot be played!');
this.errorOnLoad = true;
this.hideSpinner();
});
// Show spinner when the video is loading
this.on('loadstart', () => {
this.showSpinner();
});
this.on('canplay', () => {
this.errorOnLoad = false;
});
this.on('canplaythrough', () => {
this.errorOnLoad = false;
this.hideSpinner();
});
if (this.mainPlayer) {
Player.mainPlayer = this;
this.ethogram = new Ethogram();
this.trackingMap = new TrackingMap();
this.metadata = new Metadata();
// Set up the play-pause btn
const playPauseButton = new Button('#play-pause-btn');
playPauseButton.setIcon('play_circle', 'size-48');
playPauseButton.on('click', () => Player.playPauseAll());
// Set up the mute button
const muteButton = new Button('#mute-btn');
muteButton.setIcon('volume_up');
muteButton.on('click', () => this.toggleMute());
// Set up the skip forward button
const forwardButton = new Button('#forward-btn');
forwardButton.on('click', () => Player.forwardAll());