-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathhelpers.js
More file actions
4802 lines (3697 loc) · 156 KB
/
Copy pathhelpers.js
File metadata and controls
4802 lines (3697 loc) · 156 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
/**
* Helper functions
*/
// const fs = require('node:fs');
// const path = require('node:path');
// const bootstrap = require('bootstrap');
import { Player, Observation, Hotkey, BoundingBox, Config } from './components.js';
// Offset in pixels for drawing highlight rectangles on canvas around selected tracking boxes
// const offsetHighlight = 5;
/**
*
* @param {Array} objects
* @param {*} field
* @returns - Unique values in specified field
*/
function getUniqueFieldValues(objects, field) {
const uniqueValues = new Set();
objects.forEach(object => {
uniqueValues.add(object[field]);
});
return Array.from(uniqueValues);
}
/**
* Displays toast elements for alerts
* @param {String} message Alert message to be shown
* @param {String | undefined } type Success, error, warning or undefined (for info) to style the toast element accordingly
* @param {String} title Title of the alert
*/
function showAlertToast(message, type, title) {
const toastEl = document.getElementById('alert-toast');
if (!toastEl) return;
const toastBootstrap = bootstrap.Toast.getOrCreateInstance(toastEl);
const toastBody = toastEl.querySelector('.toast-body');
const toastMessage = toastEl.querySelector('.toast-message');
const toastIcon = toastEl.querySelector('.toast-icon');
if (!toastIcon) return;
const toastHeader = toastEl.querySelector('.toast-header');
const alertTitle = toastEl.querySelector('.alert-title');
const closeBtn = toastEl.querySelector('#no-header-toast-close-btn');
if (type === 'success') {
toastIcon.textContent = 'check_circle';
toastIcon.classList.remove('text-danger', 'text-info', 'text-warning');
toastIcon.classList.add('text-success');
} else if (type === 'error') {
toastIcon.textContent = 'error';
toastIcon.classList.remove('text-success', 'text-info', 'text-warning');
toastIcon.classList.add('text-danger');
} else if (type === 'warning') {
toastIcon.textContent = 'warning';
toastIcon.classList.remove('text-danger', 'text-success', 'text-info');
toastIcon.classList.add('text-warning');
} else {
toastIcon.textContent = 'info';
toastIcon.classList.remove('text-danger', 'text-success', 'text-warning');
toastIcon.classList.add('text-info');
}
if (toastBody) {
toastBody.insertBefore(toastIcon, toastMessage);
}
// Show the close button in the simplied toast by default
if (closeBtn) closeBtn.classList.remove('d-none');
// Hide the header by default
if (toastHeader) {
toastHeader.classList.add('d-none');
if (title && alertTitle) {
// Move the icon to the header
const firstChild = toastHeader.firstChild;
toastHeader.insertBefore(toastIcon, firstChild);
// Show the title and header element
alertTitle.textContent = title;
toastHeader.classList.remove('d-none');
// Hide close button in the simplified toast to prevent duplication
if (closeBtn) closeBtn.classList.add('d-none');
}
}
toastMessage.innerHTML = message;
toastBootstrap.show();
}
/**
* Shows a popover over the given DOM element
* @param {Object} options
* @param {Boolean | undefined} options.onCanvas If true, shows the popover over main canvas and ignores "domEl" argument
* @param {Number | undefined} options.x X-coordinate for the DOM element's origin (i.e. style.left). Mandatory if onCanvas is true
* @param {Number | undefined} options.y Y-coordinate for the DOM element's origin (i.e. style.top). Mandatory if onCanvas is true
* @param {Element} options.domEl DOM element for the popover
* @param {String} options.title Title of the popover
* @param {String} options.content Content of the popover
* @param {String | undefined} options.placement Location of popover relative to the DOM element. Should be either "top", "bottom", "right" or "left".
* @param {Number | undefined} options.hideTimeout Timeout in milliseconds for hiding the popover
* @param {String | undefined} options.customClass Class name for styling. Overrides "type" if both are given.
* @param {Number[] | undefined} options.offset Offset of the popover relative to its target [skidding, distance]
* @param {String | undefined} options.type Type of the alert for styling. Should be either "success", "error", "info", "warning" or "response". The default value is "info". If "response" is selected, it will show confirmation/cancellation buttons to get user feedback and ignore hideTimeout option.
*/
function showPopover(options) {
const {
onCanvas = false, x, y, title, content,
placement, hideTimeout, offset,
customClass, type, showResponseBtn
} = options;
// Determine the DOM element depending on whether the popover should be shown on the main canvas
let domEl = options.domEl;
if (onCanvas) {
// Check if the coordinates are given
for (const coord of [x, y]) {
if (coord === null || typeof coord === 'undefined' ||
Number.isNaN(coord) || !Number.isFinite(coord)
) {
console.log('X and Y coordinates must be provided to display a popover on the main canvas');
return;
}
}
const mainCanvas = Player.getMainCanvas();
if (!mainCanvas) return;
const canvasRect = mainCanvas.getBoundingClientRect();
if (!canvasRect) return;
const widthRatio = mainCanvas.width / mainCanvas.clientWidth;
const heightRatio = mainCanvas.height / mainCanvas.clientHeight;
domEl = document.getElementById('alert-popover-canvas-div');
domEl.style.left = parseFloat(x) / widthRatio - canvasRect.left + 'px';
domEl.style.top = parseFloat(y) / heightRatio + 'px';
domEl.style.width = '20px';
domEl.style.height = '20px';
domEl.classList.remove('d-none');
}
const prevPopover = bootstrap.Popover.getInstance(domEl);
if (prevPopover) {
prevPopover.dispose();
}
// Determine the popover class for styling depending on the type
let popoverClass;
switch (type) {
case 'success':
popoverClass = 'success-subtle-popover';
break;
case 'error':
popoverClass = 'error-popover';
break;
case 'warning':
popoverClass = 'warning-subtle-popover';
break;
case 'response':
popoverClass = 'primary-popover';
break;
default:
popoverClass = 'info-subtle-popover';
}
// Add confirmation/cancellation buttons to the content if they should be shown
const isResponse = type === 'response';
const responseBtnHtml = `<div id="new-bounding-box-response-div" class="mt-1 d-flex justify-content-start align-items-center"><a role="button" class="btn btn-sm btn-secondary me-1 confirm-btn">Dismiss</a><a role="button" class="btn btn-sm btn-success dismiss-btn">Confirm</a></div>`
// Create the Popover instance
const popover = new bootstrap.Popover(domEl, {
container: 'body',
content: content + (isResponse ? responseBtnHtml : ''),
placement: placement ?? 'top',
title: title,
customClass: customClass ?? popoverClass,
trigger: 'manual',
offset: offset ?? [0, 8],
html: true
});
// Show the popover
popover.show();
// Hide the popover if user is not expected to interact with the popover
if (!isResponse) {
setTimeout(() => {
popover.hide();
}, hideTimeout ?? 3000);
}
}
/**
*
* @param {String} title Title of the modal
* @param {String[]} messages Alert message array
* @param {Boolean | undefined} hideConfirmBtn True if confirmation button must be hidden
* @param {String | undefined} confirmBtnText Text for the confirmation button
* @param {Boolean | undefined} hideCancelBtn True if cancellation button must be hidden
* @param {String | undefined} cancelBtnText Text for the cancellation button
*
*/
function showAlertModal(title, messages, hideConfirmBtn, confirmBtnText, hideCancelBtn, cancelBtnText) {
const modal = document.getElementById('alert-modal');
const modalBootstrap = bootstrap.Modal.getOrCreateInstance(modal);
const modalTitle = modal.querySelector('.modal-title');
const modalBody = modal.querySelector('.modal-body');
const confirmBtn = modal.querySelector('#alert-confirm-btn');
const cancelBtn = modal.querySelector('#alert-cancel-btn');
// Show cancel button by default
cancelBtn.classList.remove('d-none');
// Hide cancel and/or confirm button if necessary
if (hideCancelBtn) {
cancelBtn.classList.add('d-none');
} else {
cancelBtn.classList.remove('d-none');
}
if (hideConfirmBtn) {
confirmBtn.classList.add('d-none');
} else{
confirmBtn.classList.remove('d-none');
}
// Default text for confirm button
confirmBtn.textContent = confirmBtnText ? confirmBtnText : 'Continue';
// Default text for cancel button
cancelBtn.textContent = cancelBtnText ? cancelBtnText : 'Cancel';
// Add the title
modalTitle.textContent = title;
// Reset modal's content
modalBody.textContent = '';
// Add a paragraph to modal body for each argument for message
messages.forEach(message => {
const paragraph = document.createElement('p');
paragraph.innerHTML = message;
modalBody.append(paragraph);
});
modalBootstrap.show();
}
/**
* Hide the alert modal
*/
function hideAlertModal() {
const modal = document.getElementById('alert-modal');
const modalBootstrap = bootstrap.Modal.getOrCreateInstance(modal);
modalBootstrap.hide();
}
/**
*
* @param {*} videoDirPath
* @returns - Video file names without the extension
*/
function getVideoFilePaths(videoDirPath) {
const files = fs.readdirSync(videoDirPath, (err, files) => {
if (err) {
console.error('Error reading directory:', err);
return;
}
});
// Filter files with the .mp4 extension (more to be added)
const videoFiles = files.filter(file => path.extname(file).toLowerCase() === '.mp4');
return videoFiles
}
/**
*
* @param {*} minutesString - MM:SS
* @returns - seconds in total
*/
function formatMinutes(minutesString) {
const splitStrArray = minutesString.split(':');
if (splitStrArray.length === 2) {
const minutes = Number(splitStrArray[0]);
const seconds = Number(splitStrArray[1]);
return minutes * 60 + seconds; // return total time
}
}
function minutesToFrames(minutesString, frameRate) {
const splitStrArray = minutesString.split(':');
if (splitStrArray.length === 2) {
const minutes = Number(splitStrArray[0]);
const seconds = Number(splitStrArray[1]);
const totalSeconds = minutes * 60 + seconds;
// Convert seconds to frame numbers
return secondsToFrames(totalSeconds, frameRate)
}
}
function secondsToFrames(seconds, frameRate = Player.getMainPlayer?.()?.getFrameRate?.()) {
const parsedSeconds = parseFloat(seconds);
if (!Number.isFinite(parsedSeconds)) return;
const parsedFrameRate = parseFloat(frameRate ?? Player.getMainPlayer?.()?.getFrameRate?.());
if (!Number.isFinite(parsedFrameRate)) return;
const frames = Math.round(parsedSeconds * parsedFrameRate);
return frames;
}
/**
* Coverts frame number to seconds for a given frame rate
* @param {Number | String} frames Frame number
* @param {Number | String} frameRate Frame rate of the video
* @returns {Number} Returns the result in seconds
*/
function framesToSeconds(frames, frameRate) {
if (!frames) return;
if (!Number.isSafeInteger(parseInt(frames))) return;
if (!frameRate) {
frameRate = Player.getMainPlayer().getFrameRate();
}
const seconds = parseInt(frames) / parseFloat(frameRate);
return seconds;
}
/**
* @param {*} secondsString
* @returns - MM:SS
*/
function formatSeconds(secondsString) {
const seconds = parseFloat(secondsString);
let minutes = Math.floor(seconds / 60);
let remainingSeconds = Math.floor(seconds % 60);
// Add leading zero if needed
minutes = (minutes < 10 ? '0' : '') + minutes;
remainingSeconds = (remainingSeconds < 10 ? '0' : '') + remainingSeconds;
// Return the formatted time
return minutes + ':' + remainingSeconds;
}
function getFrameFromVideo(videoElement) {
const canvas = document.createElement('canvas');
canvas.width = videoElement.videoWidth;
canvas.height = videoElement.videoHeight;
const context = canvas.getContext('2d');
context.drawImage(videoElement, 0, 0, canvas.width, canvas.height);
return canvas.toDataURL();
}
async function createVideoDivs(domElRow, filePaths) {
const numberOfVideos = filePaths.length;
const columnClass = 'col-4';
for (let i = 0; i < numberOfVideos; i++) {
const fileName = await getFileNameWithoutExtension(filePaths[i])
const videoColDiv = [
`<div class="${columnClass} border rounded p-2">`,
'<div class="d-flex justify-content-between">',
`<small>${fileName}</small>`,
'<btn class="btn btn-sm btn-player-frame">Main</btn>',
'</div>',
'<div class="position-relative">',
`<video id="video-${i}" class="video-selection" width="320" height="180" src="${filePaths[i]}" preload="metadata">`,
'Your browser does not support the video tag.',
'</video>',
'<div class="video-spinner spinner-grow text-primary position-absolute start-50 bottom-50 d-none" role="status">',
'<span class="visually-hidden">Loading...</span>',
'</div>',
'</div>',
'</div>'
].join('')
// Add this div to the secondary video row
domElRow.innerHTML += videoColDiv;
}
return domElRow.querySelectorAll('video');
}
/**
* Loads the secondary videos
* @param {String[]} videoSrcArr - Array of secondary video source paths
*/
async function loadSecondaryVideos(videoSrcArr) {
if (!videoSrcArr) return;
if (!Array.isArray(videoSrcArr) || videoSrcArr.length < 1) return;
const openSecondaryVideosBtn = document.getElementById('open-secondary-videos-btn');
if (!openSecondaryVideosBtn) return;
const secondaryVideoRow = document.querySelector('#secondary-video-row');
if (!secondaryVideoRow) return;
// Filter video sources that are already opened
let filteredArr = [];
for (const videoSrc of videoSrcArr) {
// Get the video file name to construct DOM IDs
const videoFileName = await getFileNameWithoutExtension(videoSrc);
if (!videoFileName) return;
const isDuplicate = Player.getSecondaryPlayers().filter(player => player.getName() === videoFileName).length > 0;
if (!isDuplicate) {
filteredArr.push({src: videoSrc, name: videoFileName});
}
}
if (filteredArr.length < 1) {
showAlertToast('Selected videos already opened!', 'info');
return;
}
// Set the number of columns depending on the number of players
const rowColsNumber = filteredArr.length === 1 ? 'row-cols-1' : 'row-cols-2';
secondaryVideoRow.classList.add(rowColsNumber);
// Get the button for changing column number
const secondaryVidColSizeBtn = document.getElementById('secondary-video-colsize-btn');
if (secondaryVidColSizeBtn) {
const buttonIcon = secondaryVidColSizeBtn.querySelector('span');
const tooltip = bootstrap.Tooltip.getOrCreateInstance(secondaryVidColSizeBtn);
if (rowColsNumber === 'row-cols-1') {
buttonIcon.textContent = 'grid_view'; // Change the icon to list view
tooltip.setContent({ '.tooltip-inner': 'Grid view' }); // Change the tooltip
buttonIcon.dataset.viewType = 'grid'; // Update dataset
} else {
buttonIcon.textContent = 'view_list' // Change the icon to list view
tooltip.setContent({ '.tooltip-inner': 'List view' }); // Change the tooltip
buttonIcon.dataset.viewType = 'list' // Update dataset
}
}
// Create secondary video HTML divs
// const secondaryVideoElList = await createSecondaryVideoDivs(videoSrcArr);\
const filteredDomIdArr = [];
for (const obj of filteredArr) {
// Get the video name and source
const videoName = obj.name;
const videoSrc = obj.src;
const domId = `video_${videoName}`;
filteredDomIdArr.push(domId);
// Construct the column HTML
const videoColEl = document.createElement('div');
videoColEl.classList.add('col');
const videoContainerEl = document.createElement('div');
videoContainerEl.classList.add('ratio', 'ratio-16x9', 'video-container');
const spinnerEl = document.createElement('div');
spinnerEl.classList.add('position-absolute', 'spinner-parent-div');
const videoEl = document.createElement('video');
videoEl.id = domId;
videoEl.classList.add('secondary-video');
videoEl.src = videoSrc;
videoEl.textContent = 'Your browser does not support the video tag.';
const buttonDivEl = document.createElement('div');
buttonDivEl.classList.add('overlay', 'px-2');
const videoTitleEl = document.createElement('small');
videoTitleEl.classList.add('secondary-video-title');
videoTitleEl.textContent = videoName;
const disposeBtnEl = document.createElement('button');
disposeBtnEl.type = 'button';
disposeBtnEl.classList.add('btn', 'btn-sm', 'btn-icon-small', 'btn-dispose-player');
const btnIconEl = document.createElement('span');
btnIconEl.classList.add('material-symbols-rounded', 'dark');
btnIconEl.textContent = 'close';
disposeBtnEl.append(btnIconEl);
buttonDivEl.append(videoTitleEl, disposeBtnEl);
videoContainerEl.append(spinnerEl, videoEl, buttonDivEl)
videoColEl.append(videoContainerEl);
secondaryVideoRow.append(videoColEl);
// const videoColDiv = [
// `<div class="col">`,
// '<div class="ratio ratio-16x9 video-container">',
// '<div class="position-absolute spinner-parent-div"></div>',
// `<video id="${domId}" class="secondary-video" src="${videoSrc}">`,
// 'Your browser does not support the video tag.',
// '</video>',
// '<div class="overlay px-2">',
// // '<div class="d-flex justify-content-between">',
// `<small class="secondary-video-title">${videoName}</small>`,
// '<button type="button" class="btn btn-sm btn-icon-small btn-dispose-player">',
// '<span class="material-symbols-rounded dark">close</span>',
// '</button>',
// // '</div>',
// '</div>',
// '</div>',
// '</div>'
// ].join('');
// // Add this div to the secondary video row
// secondaryVideoRow.innerHTML += videoColDiv;
}
const videoElArr = filteredDomIdArr.map(domId => secondaryVideoRow.querySelector(`#${domId}`));
if (videoElArr.length < 1) return;
for (const videoEl of videoElArr) {
const player = new Player(videoEl.id);
player.setSource(videoEl.src);
try {
await player.load();
player.mute();
player.setCurrentTime(Player.getMainPlayer().getCurrentTime());
player.setPlaybackRate(Player.getMainPlayer().getPlaybackRate());
await player.setName();
// // Set frame rate and dismiss button
// player.on('loadeddata', async () => {
// // Set frame rate
// await player.setFrameRate();
// // Dispose player if close button is clicked
// const playerColDiv = player.el.parentNode.parentNode;
// if (playerColDiv) {
// const disposeButton = playerColDiv.querySelector('.btn-dispose-player');
// if (disposeButton) {
// disposeButton.addEventListener('click', () => player.dispose());
// }
// }
// });
} catch (error) {
showAlertModal(
'Unsupported Video Type',
[
'Selected video is not supported!',
'Please try again with another video.'
],
true,
'Continue',
false,
'Dismiss'
);
// videoEl.parentElement.parentElement.classList.add('d-none');
videoEl.parentNode.parentNode.remove();
Player.delete(player);
return;
}
// videoEl.parentElement.parentElement.classList.remove('d-none');
}
// If there are valid videos, show grid view button and move button for opening videos to upper bar
if (Player.getSecondaryPlayers().length > 0) {
// Show the column sizing button
const colSizeBtn = document.getElementById('secondary-video-colsize-btn');
if (colSizeBtn) colSizeBtn.classList.remove('d-none');
// Move the button for opening videos to the control bar above
const openBtnDiv = document.querySelector('#secondary-videos-control-div .button-div')
if (!openBtnDiv) return;
openBtnDiv.prepend(openSecondaryVideosBtn);
openSecondaryVideosBtn.classList.remove('mt-3');
openSecondaryVideosBtn.classList.replace('btn-icon-large', 'btn-icon-small');
// Hide the information text
const infoTextEl = document.getElementById('secondary-video-info-text');
if (infoTextEl) infoTextEl.classList.add('d-none');
secondaryVideoRow.classList.remove('d-none');
}
}
// async function createSecondaryVideoDivs(videoFilePaths) {
// if (!videoFilePaths) return;
// const numberOfVideos = videoFilePaths.length;
// const secondaryVideoRow = document.querySelector('#secondary-video-row');
// for (let i = 0; i < numberOfVideos; i++) {
// const videoFileName = await getFileNameWithoutExtension(videoFilePaths[i]);
// if (!videoFileName) return;
// // Don't proceed if the the same video has already been opened
// const domId = `video_${videoFileName}`;
// const isDuplicate = Player.getSecondaryPlayers().filter(player => player.domId === domId).length > 0;
// if (isDuplicate) return;
// // Set the column size for each secondary player
// const columnSize = "col";
// // Construct the column HTML
// const videoColDiv = [
// `<div class="${columnSize}">`,
// '<div class="ratio ratio-16x9 video-container">',
// '<div class="position-absolute spinner-parent-div"></div>',
// `<video id="${domId}" class="secondary-video" src="${videoFilePaths[i]}">`,
// 'Your browser does not support the video tag.',
// '</video>',
// '<div class="overlay px-2">',
// // '<div class="d-flex justify-content-between">',
// `<small class="secondary-video-title">${videoFileName}</small>`,
// '<button type="button" class="btn btn-sm btn-icon-small btn-dispose-player">',
// '<span class="material-symbols-rounded dark">close</span>',
// '</button>',
// // '</div>',
// '</div>',
// '</div>',
// '</div>'
// ].join('')
// // Add this div to the secondary video row
// secondaryVideoRow.innerHTML += videoColDiv;
// }
// return document.querySelectorAll('.secondary-video');
// }
async function getFileNameWithoutExtension(filePath) {
const fileName = await window.electronAPI.getFileNameWithoutExtension(filePath);
return fileName
}
function showOverlappingTracksToast(boxesUnderMouse) {
const toastEl = document.getElementById('overlapping-tracks-toast');
if (toastEl) {
const toastBootstrap = bootstrap.Toast.getOrCreateInstance(toastEl);
// Show choices for overlapping boxes
const trackSelect = toastEl.querySelector('#overlapping-track-select');
if (trackSelect) {
// Clear previous options
trackSelect.options.length = 0;
// Add default object option
const defaultOption = document.createElement("option");
defaultOption.text = 'Choose a subject ID';
defaultOption.selected = true;
trackSelect.add(defaultOption);
// Add objects on the current frame as options
boxesUnderMouse.forEach(rectangle => {
// Check the validity of the rectangle
const labelText = produceLabelText(rectangle);
if (!labelText) return;
const option = document.createElement("option");
option.text = labelText;
option.dataset.classId = rectangle['classId'];
option.value = rectangle['trackId'];
trackSelect.add(option);
});
toastBootstrap.show();
}
}
}
/**
* Produce a label string from a bounding box object
* @param {BoundingBox} bBox
* @returns
*/
function produceLabelText(bBox) {
// Check the validity of the object
if (!(bBox instanceof BoundingBox)) return;
// Check if the class and track IDs are valid
const classId = bBox.getClassId();
const trackId = bBox.getTrackId();
for (const idStr of [ classId, trackId ]) {
if (typeof idStr === 'undefined' || idStr === null) return;
}
// Start constructing label with class and track IDs
let labelText = classId + '–' + trackId;
// If there are individual names
const individualNames = Player.getIndividualNames();
if (Array.isArray(individualNames) && individualNames.length > 0) {
// Get the name order from the bounding box and check its validity
const nameOrder = bBox.getNameOrder();
// Add the name to the label if the name order is valid and the name exists in the individual names list
const validNameOrder = typeof nameOrder !== 'undefined' && nameOrder !== null && nameOrder >= 0 && nameOrder < individualNames.length;
const subjectName = individualNames[nameOrder];
if (subjectName) {
labelText += '–' + subjectName;
}
}
// Add class name if it exists
const className = Player.getClassName(classId);
if (className) {
labelText += ' | ' + className;
}
return labelText;
}
/**
*
* @param {Object} options
* @param {Event} options.event
* @param {BoundingBox} options.clickedBBox
* @param {String | Number} options.timestamp
* @param {String | Number} options.frameNumber
* @returns
*/
function showToastForBehaviorRecording (options) {
// If this is a new observation (i.e. no subject and actions are selected)
// Show the clicked subject and action options
// Save the user choice to the Current Observation object
// Listen for undo key and also show undo button
// If this is not a new observation (i.e. subject and action are already selected)
// Listen for user clicks on the whole video frame (to provide no target option)
// Show the clicked target option
// Show also no target option if user clicks outside of a tracking box
// Listen for undo key and also show undo button
// Update the current observation
// Save the user choice to the Ethogram
const { event, clickedBBox, timestamp, frameNumber } = options;
// Check if toast element exists
const toastEl = document.getElementById('labeling-toast');
if (!toastEl) return;
// Get the relevant DOM elements
const toastBootstrap = bootstrap.Toast.getOrCreateInstance(toastEl);
const trackingInfoEl = toastEl.querySelector('#tracking-info-text');
const toastTitle = toastEl.querySelector('.toast-title');
const toastAlert = toastEl.querySelector('#toast-alert');
const behaviorTab = toastEl.querySelector('#behavior-toast-tab');
const trackingTab = toastEl.querySelector('#tracking-toast-tab');
const timeStampDiv = toastEl.querySelector('#toast-timestamp');
const subjectSelect = toastEl.querySelector('#subject-select');
const targetSelect = toastEl.querySelector('#target-select');
const actionSelect = toastEl.querySelector('#action-select');
const nameEditSelect = toastEl.querySelector('#name-edit-select'); // Selection for editing the individual name in a track
const nameEditDiv = toastEl.querySelector('#name-edit-div'); // Input group div for name edit
const classEditSelect = toastEl.querySelector('#class-edit-select'); // Selection for editing the class of a track
const classEditDiv = toastEl.querySelector('#class-edit-div'); // Input group div for class edit
const firstAvailTrackIdInputEl = toastEl.querySelector('#next-unused-track-id');
const behaviorRecordBtn = toastEl.querySelector('#label-save-btn');
// Check if DOM elements within the toast exist
if (!subjectSelect || !actionSelect || !targetSelect || !nameEditSelect ||
!nameEditDiv || !classEditSelect || !classEditDiv || !behaviorRecordBtn ||
!behaviorTab || !trackingTab
) return;
// Fill the timestamp element with the time of the start of the current observation
timeStampDiv.textContent = formatSeconds(timestamp);
// Add a title
// TODO: Add observation ID to the title
if (toastTitle) toastTitle.textContent = 'Observation'
const classMap = Player.getClassMap();
if (!classMap || !(classMap instanceof Map)) return;
// Show track information on the tracking tab
if (trackingInfoEl) {
trackingInfoEl.textContent = 'Selection: ' + produceLabelText(clickedBBox);
}
// Get the actions and individuals
const actionNames = Player.getActionNames();
const individualNames = Player.getIndividualNames();
// Determine if any action is imported
const anyAction = Array.isArray(actionNames) && actionNames.length > 0;
// Hide the toast alert by default
toastAlert.classList.add('d-none');
// Fill elements for editing names of clicked bounding boxes
// Hide and disable name edit selection by default
// activate only if tracking box contains a name
nameEditDiv.classList.add('d-none');
nameEditSelect.disabled = true;
// Make the div for selection visible
nameEditDiv.classList.remove('d-none');
// Enable name select element
nameEditSelect.disabled = false;
// Clear previous options
nameEditSelect.options.length = 0;
classEditSelect.options.length = 0;
// Add all individual names to the options for editing tracks
individualNames?.forEach?.(name => {
const option = document.createElement('option');
option.text = name;
option.value = individualNames.indexOf(name); // Order of name in the individual list file
option.dataset.trackId = clickedBBox.trackId;
option.dataset.classId = clickedBBox.classId;
option.dataset.nameOrder = individualNames.indexOf(name);
nameEditSelect.add(option);
});
// Add all class names to the options for editing tracks
classMap.values().forEach(classObj => {
const classId = classObj.id;
if (!classId) return;
const className = classObj.name;
const option = document.createElement('option');
option.text = className ? classId + '–' + className : classId; // Display the class name if available
option.value = classId; // Order of name in the individual list file
option.dataset.trackId = clickedBBox.trackId; // Add track ID to dataset
option.dataset.classId = clickedBBox.classId; // Add class ID to dataset
classEditSelect.add(option);
});
// Change the title for name edit div depending on existence of a name for the clicked individual
// Check if clicked rectangle includes an individual name
const clickedNameOrder = clickedBBox.getNameOrder?.();
const validClickedNameOrder = typeof clickedNameOrder !== 'undefined' && clickedNameOrder !== null;
// If clicked rectangle has no individual name assigned by the model, show an option to add it
nameEditDiv.querySelector('.description').textContent = validClickedNameOrder ? 'Change name' : 'Add name';
// Check if main player is initialized
const mainPlayer = Player.getMainPlayer();
if (!mainPlayer) return;
// Assign the value for the first available track ID input element
if (firstAvailTrackIdInputEl) {
// const firstAvailTrackId = mainPlayer.getFirstAvailTrackIds().get(clickedBBox.classId);
const firstAvailTrackId = Player.getFirstAvailTrackId(clickedBBox.getClassId?.());
if (typeof firstAvailTrackId !== 'undefined') {
firstAvailTrackIdInputEl.value = firstAvailTrackId;
}
}
// Check if current observation is initialized
const currentObs = Player.getCurrentObservation();
if (!currentObs) return;
// Check if the behaviors are initialized
const ethogram = mainPlayer.getEthogram();
if (!ethogram) {
console.log('No record of behaviors was found!');
return;
}
// Save information about clicked rectangle
toastEl.dataset.clickedTrackId = clickedBBox.getTrackId?.();
toastEl.dataset.clickedClassId = clickedBBox.getClassId?.();
toastEl.dataset.timestamp = timestamp;
toastEl.dataset.frameNumber = frameNumber;
toastEl.dataset.clickedNameOrder = 'none'; // Assign none to clickedNameOrder by default
if (validClickedNameOrder) {
toastEl.dataset.clickedNameOrder = clickedNameOrder; // If clicked rectangle has a name assigned to the model or user before, use it
}
// Get the undo Hotkey
const undoHotkey = Hotkey.findOne({category: 'labeling', name: 'undo'});
/**
* Forces user to add names to unidentified tracks before recording an observation
* @param {String | undefined} trackSpecies Which class to apply. Applies to all class by default. Can be "box", "primate".
* @returns {Boolean} True if popover has been shown, False otherwise
*/
function showPopoverForUnnamedTrack(trackSpecies) {
// Determine if the clicked track is identified as a box
const isBoxClicked = Player.getClassName(clickedBBox.getClassId?.()) === 'box';
// Return if the input class and clicked class do not match - i.e. do not show a popover
if (trackSpecies) {
if (trackSpecies.toLowerCase() === 'box' && !isBoxClicked) {
return;
}
if (trackSpecies.toLowerCase() === 'primate' && isBoxClicked) {
return;
}
}
if (!clickedBBox.hasOwnProperty('nameOrder')) {
// Get the canvas element
const canvas = mainPlayer.getCanvas();
if (!canvas) return;
// Get the mouse position
const canvasRect = canvas.getBoundingClientRect();
const mouseX = event.clientX - canvasRect.left;
const mouseY = event.clientY - canvasRect.top;
// Show a popover over the unnamed tracking box
const popoverDivEl = document.getElementById('popover-canvas-div');
if (popoverDivEl) {
popoverDivEl.style.left = mouseX + 'px';
popoverDivEl.style.top = mouseY + 'px';
popoverDivEl.style.width = '20px';
popoverDivEl.style.height = '20px';
popoverDivEl.classList.remove('d-none');
}
const popover = new bootstrap.Popover(popoverDivEl, {
container: 'body',
content: 'Assign a name to proceed!',
});