-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathrenderer.js
More file actions
1917 lines (1457 loc) · 60.7 KB
/
Copy pathrenderer.js
File metadata and controls
1917 lines (1457 loc) · 60.7 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
/**
* Communication processes between modules to handle interactive bounding boxes
* -------------------------------
* - User clicks on a box
* - Toast with options showed
* with showToastForBehaviorRecording() in helpers.js
* - User confirms selection for recording behaviors
* with updateInteractionTable() in helpers.js via click event on #label-save-btn (renderer.js)
* - User confirms selection for editting track IDs
* with updateTrackingTable in helpers.js via click event on #tracking-edit-btn (renderer.js)
*
*/
/**
* Processes when the app window is refreshed
* --------------------------------
* Check for properties in the config file (saved in user directory)
* Load them if they exist
*
*
*
*/
/**
* Tracking file edits
* --------------------
* Create a copy of the opened tracking file
* Save the path of this file to config file
* Write tracking edits by the user to this file
* Save the state of tracking table to config file
* Read this file when app is restarted
* Populate tracking table with entries in the config
*
*/
/**
* Exporting modified tracking files automatically
* -----------------------------------------------
* Make user choose a folder for exported files (in the very beginning)
* Tracking file edits are saved to user data folder on the background
* Copy these file to the user folder at each edit with the metadata headers
* Show UI feedback about successful saving
*/
/**
* Opening a main video
* ---------------------
* Make sure all work is saved to export directory
* Search for previously opened tracking and behavior files linked to video in user data directory
* If there is any, load them
* If this is a different video, clear tracking and behavior maps/tables
*/
import {
Player,
Observation,
BoundingBox,
DrawnBoundingBox,
Hotkey,
Config
} from './components.js';
import {
// createSecondaryVideoDivs,
getFileNameWithoutExtension,
formatSeconds,
showAlertToast,
showAlertModal,
secondsToFrames,
framesToSeconds,
updatePlaybackRateList,
showShortcutsModal,
showNamesModal,
showHelpModal,
showProcessIndicator,
hideProcessIndicator,
addInfoRow,
handleKeyPress,
showToastForBehaviorRecording,
validateInputs,
loadSecondaryVideos,
dragElement,
getUserConfirmationOnModal,
showPopover,
updateClassEls,
} from './helpers.js';
// Save metadata before user quits the app
window.electronAPI.onAppQuit(async () => {
const metadata = Player.getMetadata();
if (metadata) {
// Show information
showAlertToast('Saving metadata before quitting...', 'info');
// Save metadata to file
const response = await metadata.writeToFile();
if (response) {
// Show information
showAlertToast('Quitting the app...', 'success', 'Metadata Saved');
} else {
// Show information
showAlertToast('Quitting the app...', 'error', 'Saving Metadata Failed');
}
}
// Introduce delay for better user experience
await new Promise(resolve => setTimeout(resolve, 500));
// Clear all intervals IDs
Player.resetEthogramInterval();
Player.resetNotesInterval();
// Signal to the main process to quit the app
await window.electronAPI.respondBeforeQuit();
});
// Validate form inputs
validateInputs();
// Get the current version and write it to HTML elements and save to Player instance
const currentVersion = await window.electronAPI.getVersion();
if (currentVersion) {
const versionInfoEls = document.querySelectorAll('.version-info');
versionInfoEls.forEach(el => {
el.textContent = `v${currentVersion}`;
});
Player.setAppVersion(currentVersion);
}
// Listen for key press for playback and other app shortcuts
// Behavior recording shortcuts are handled separately
document.addEventListener('keydown', handleKeyPress, true);
// If a path was saved to config file, get the videos from that
// let experimentPath = await window.electronAPI.getExperimentDirPath();
// const config = await Config.fromFile();
const confResp = await window.electronAPI.getFromConfig();
const confData = (confResp instanceof Object) ? confResp : {};
const config = new Config(confData);
console.log('Config instance: ', config);
if (config instanceof Config) {
// Check if app has just been updated
const isUpdated = Config.version ? Player.getAppVersion() !== Config.version : true;
// Show release notes if the app has just been updated
if (isUpdated) {
const releaseNotesModalEl = document.getElementById('release-notes-modal');
if (releaseNotesModalEl) {
const modal = bootstrap.Modal.getOrCreateInstance(releaseNotesModalEl);
modal.show();
}
// Update config
Config.version = Player.getAppVersion();
const response = await Config.saveToFile();
if (!response) {
console.log('App version could not be saved to config file!', 'error');
}
}
// Add export directory path to the settings menu
const exportDirPathInputEl = document.getElementById('change-export-dir-input');
const openExportDirBtn = document.querySelector('#open-export-dir-btn');
if (exportDirPathInputEl && Config.exportDirPath) {
exportDirPathInputEl.value = Config.exportDirPath;
openExportDirBtn.dataset.path = Config.exportDirPath;
}
// Add zoom scale (in percentage) to the settings menu
const zoomScaleInputEl = document.getElementById('change-zoom-scale-input');
const configZoomScale = Config.zoomScale;
if (zoomScaleInputEl && configZoomScale) {
zoomScaleInputEl.value = configZoomScale;
await Player.setZoomScale(configZoomScale);
}
// Check if username and export folder was chosen
// for saving modified tracking/behavior files automatically
if (Config.username) {
// Save username from config to Player
Player.setUsername(Config.username);
// Otherwise, prompt user to choose one
} else {
// Ask for a username and export directory path
const modalBootstrap = bootstrap.Modal.getOrCreateInstance('#username-modal');
// Show modal (inputs in modal will be validated by validateInput() funcion)
modalBootstrap.show();
}
if (Config.boundingBoxLineWidth) {
await BoundingBox.setLineWidth(Config.boundingBoxLineWidth);
}
if (Config.boundingBoxOpacity) {
await BoundingBox.setOpacity(Config.boundingBoxOpacity);
}
// Check if individual names, actions and shortcuts were already saved into config file before
if (Config.shortcuts) {
Hotkey.setHotkeysFromObjectArr(Config.shortcuts);
} else {
// Create the default hotkeys
Hotkey.createDefaultHotkeys();
}
if (Config.actionNames) {
await Player.setActionNames(Config.actionNames);
}
if (Config.skipSeconds) {
await Player.setSkipSeconds(Config.skipSeconds);
}
if (Config.autoUpdateStatus) {
await Player.setAutoUpdateStatus(Config.autoUpdateStatus);
}
// Check if main video path is saved in config file
if (Config.mainVideoPath) {
const mainPlayerSrc = Config.mainVideoPath;
// Load the main video
try {
await Player.loadMainPlayer(mainPlayerSrc);
} catch (error) {
console.log(error);
}
}
if (Config.secondaryVideoPaths) {
await loadSecondaryVideos(Config.secondaryVideoPaths);
}
}
// Handle reloading the window
const relaunchBtn = document.getElementById('relaunch-btn');
if (relaunchBtn) {
relaunchBtn.addEventListener('click', async () => await window.electronAPI.relaunch());
}
// Handle changing username
const changeUsernameBtn = document.getElementById('change-username-btn');
if (changeUsernameBtn) {
changeUsernameBtn.addEventListener('click', async () => {
const changeUsernameInput = document.getElementById('change-username-input');
if (changeUsernameInput) {
const newUsername = changeUsernameInput.value;
if (newUsername === '' || typeof newUsername === 'undefined' || newUsername === null ) {
showAlertToast('Please enter a valid username!', 'error');
return;
}
// Update the username
Player.setUsername(newUsername);
// Update the config file
const response = await Config.saveToFile();
if (!response) {
showAlertToast(`Failed to set username to <span class="badge text-bg-success">${newUsername}</span>. Please try again.`, 'error');
return;
}
showAlertToast(`Username set to <span class="badge text-bg-success">${newUsername}</span>`, 'success');
}
});
}
// Handle changing export directory
const changeExportDirBtn = document.getElementById('change-export-dir-btn');
if (changeExportDirBtn) {
changeExportDirBtn.addEventListener('click', async () => {
const dialogResp = await window.electronAPI.openDirectory();
if (!dialogResp) return;
// Check if directory selection is canceled by the user
if (dialogResp.canceled) {
showAlertToast(`Export directory selection canceled!`, 'info');
return;
}
// Check if the selected directory is accessible
const exportDirPath = dialogResp.dirPath;
if (!exportDirPath) {
// Show alert
showAlertToast(`Selection <span class="badge text-bg-dark">${exportDirPath}</span> could not be read!`, 'error', 'Export Directory Inaccessible');
return;
}
// Update config
Config.exportDirPath = exportDirPath;
const response = await Config.saveToFile();
// Show error for writing to config
if (!response) {
showAlertToast(`Selected directory <span class="badge text-bg-dark">${exportDirPath}</span> could not be saved! Please try again.`, 'error', 'Export Directory Change Unsuccessful');
return;
}
// Check if the selected directory was saved to config successfully
// Add export directory path to the menu
const exportDirPathInputEl = document.getElementById('change-export-dir-input');
if (exportDirPathInputEl) {
exportDirPathInputEl.value = exportDirPath;
}
// Add path to HTML element for opening the directory with OS file manager
const openExportDirPathEl = document.getElementById('open-export-dir-btn');
if (openExportDirPathEl) {
openExportDirPathEl.dataset.path = exportDirPath;
}
// Show success for writing to config
showAlertToast(`New directory: <span class="badge text-bg-success">${exportDirPath}</span>`, 'success', 'Export Directory Changed');
});
}
// Handle toggling tracking frames
const toggleTrackingBtn = document.getElementById(Player.toggleTrackingBtnId);
if (toggleTrackingBtn) {
toggleTrackingBtn.addEventListener('click', Player.toggleTracking);
}
// Handle saving modified tracking file
const outputTrackingFile = document.getElementById('save-tracking-file-btn');
if (outputTrackingFile) {
const mainPlayer = Player.getMainPlayer();
outputTrackingFile.addEventListener('click' , async () => {
const tracks = mainPlayer.getTrackingMap().getTracks();
if (tracks) {
const mainVideoFileName = await getFileNameWithoutExtension(mainPlayer.getSource());
if (mainVideoFileName) {
const individualNamesArr = Player.getIndividualNames();
const output = await window.electronAPI.outputTrackingFile(tracks, mainVideoFileName, individualNamesArr);
}
}
})
}
// Handle showing list of keyboard shortcuts
const showKeyboardShortcutsBtn = document.getElementById('show-keyboard-shortcuts-btn');
if (showKeyboardShortcutsBtn) {
showKeyboardShortcutsBtn.addEventListener('click', () => showShortcutsModal(Player.getHotkeys()))
}
// Handle showing help
const showHelpBtn = document.getElementById('show-help-btn');
if (showHelpBtn) {
showHelpBtn.addEventListener('click', showHelpModal);
// Only play videos in the help modal when user is hovering over them
// const helpModalEl = document.getElementById('help-modal');
// if (helpModalEl) {
// const helpVideoEls = helpModalEl.querySelectorAll('.help-video');
// helpVideoEls.forEach(video => {
// video.addEventListener('mouseenter', () => video.play());
// video.addEventListener('mouseleave', () => video.pause());
// })
// }
}
// Handle showing feedback modal
// const showFeedbackBtn = document.getElementById('show-feedback-btn');
// if (showFeedbackBtn) {
// showFeedbackBtn.addEventListener('click', () => {
// const feedbackModalEl = document.getElementById('feedback-modal');
// if (feedbackModalEl) {
// const modal = bootstrap.Modal.getOrCreateInstance(feedbackModalEl);
// modal.show();
// }
// });
// }
// Handle showing individual names modal
const showNamesBtn = document.getElementById('show-names-btn');
if (showNamesBtn) {
showNamesBtn.addEventListener('click', showNamesModal)
}
// Handle opening secondary views
const openSecondaryVideosBtn = document.getElementById('open-secondary-videos-btn');
if (openSecondaryVideosBtn) {
openSecondaryVideosBtn.addEventListener('click', async () => {
const mainPlayer = Player.getMainPlayer();
if (!mainPlayer) {
showAlertToast(
'Please open the main video first!',
'warning',
'Secondary Views Disabled'
);
return;
}
// Pause main player
mainPlayer.pause();
// Get the secondary video file paths
const videoSrcArr = await window.electronAPI.openMultipleVideos();
// Load the secondary videos
await loadSecondaryVideos(videoSrcArr);
// Save/update the secondary video paths to the config file
await Player.saveSecondaryVideosToConfig();
});
}
// Adjust column size of secondary videos by user input
const secondaryVidColSizeBtn = document.getElementById('secondary-video-colsize-btn');
if (secondaryVidColSizeBtn) {
secondaryVidColSizeBtn.addEventListener('click', () => {
// Get the secondary row
const secondaryVideoRow = document.getElementById('secondary-video-row');
// Get the status of view type (grid or list)
const buttonIcon = secondaryVidColSizeBtn.querySelector('span');
const tooltip = bootstrap.Tooltip.getInstance(secondaryVidColSizeBtn);
if (buttonIcon.dataset.viewType === 'grid') {
secondaryVideoRow.classList.replace('row-cols-1', 'row-cols-2'); // Adjust column numbers
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
} else if (buttonIcon.dataset.viewType === 'list') {
secondaryVideoRow.classList.replace('row-cols-2', 'row-cols-1'); // Adjust column numbers
buttonIcon.textContent = 'grid_view' // Change the icon to grid view
tooltip.setContent({ '.tooltip-inner': 'Grid view' }); // Change the tooltip
buttonIcon.dataset.viewType = 'grid' // Update dataset
}
});
}
// Handle entering labeling mode (to activate keyboard shortcuts for recording observations)
const labelingModeBtn = document.getElementById(Player.toggleLabelingBtnId);
if (labelingModeBtn) {
labelingModeBtn.addEventListener('click', Player.toggleLabelingMode);
}
// Handle entering zooming mode
const zoomingModeBtn = document.getElementById('toggle-zooming-mode-btn');
if (zoomingModeBtn) {
zoomingModeBtn.addEventListener('click', Player.toggleZoomingMode);
}
// Handle saving tracking table to file
// Handle saving interaction table to file
const saveTrackingTableBtn = document.getElementById('save-tracking-table-btn');
const trackingTable = document.getElementById('tracking-table');
if (saveTrackingTableBtn && trackingTable) {
saveTrackingTableBtn.addEventListener('click', async () => {
// File delimiter for output file
const fileDelimiter = ' ';
// Initialize array for expanded table content
// It is required to pass on the main process to save the file
let tableContentArr = []
// Iterate over table cells to format them
for (let row of trackingTable.rows) {
const timeStartCell = row.querySelector('.edit-start');
const timeEndCell = row.querySelector('.edit-end');
const oldIdCell = row.querySelector('.old-id');
const newIdCell = row.querySelector('.new-id');
const typeCell = row.querySelector('.edit-type');
if (timeStartCell && timeEndCell && oldIdCell && newIdCell && typeCell) {
// Get the values of cells saved in datasets
const startFrame = row.dataset.editStartFrame;
const endFrame = row.dataset.editEndFrame;
// const editType = row.dataset.editType.value;
// const oldId = row.dataset.oldId.value;
// const newId = row.dataset.newId.value;
let rowContentArr = [];
rowContentArr.push(startFrame, endFrame)
// Add space between the cells
tableContentArr.push(rowContentArr.join(fileDelimiter));
}
}
// Save the tracking table to file
const mainPlayerSrc = Player.getMainPlayer().getSource();
const mainVideoFileName = await getFileNameWithoutExtension(mainPlayerSrc);
const tableContent = tableContentArr.join('\n');
const output = await window.electronAPI.outputTrackingTable(tableContent, mainVideoFileName);
});
}
// Handle saving interaction table to file
const exportBehaviorsBtn = document.getElementById('export-ethogram-btn');
const ethogramTableEl = document.getElementById('behavior-table');
if (exportBehaviorsBtn && ethogramTableEl) {
exportBehaviorsBtn.addEventListener('click', async () => {
// Get the main player
const mainPlayer = Player.getMainPlayer();
if (!mainPlayer) return;
// Export the behavior records to a CSV file named after experiment/video name
const ethogram = mainPlayer.getEthogram();
if (!ethogram) return;
// Get all observations in the ethogram as Objects
const obsArr = ethogram.getAllAsObjects()
// Get the video name without extension
const fileName = mainPlayer.getName();
// Get the username
const username = Player.getUsername();
// Get the video frame rate
const videoFPS = mainPlayer.getFrameRate();
// Do not write metadata by default
const withMetadata = false;
// Attempt to export the ethogram to a CSV file
const response = await window.electronAPI.exportBehaviors(obsArr, fileName, videoFPS, username, withMetadata);
// Handle the intentional cancellation by users quitely
if (response.canceled) return;
// Show failure
if (!response) {
showAlertToast(
`Behaviors could <strong>NOT</strong> be exported! Please try again.`,
'error',
'Behaviors Export Failed'
);
return;
}
// Show success
if (response.filePath) {
// Construct the badge for file path
const filePathHtml = `<span class="badge text-bg-success">${response.filePath}<span>`;
showAlertToast(`Behaviors exported to: ${filePathHtml}`, 'success', `Behaviors Exported`);
return;
}
});
}
// Handle settings button
const settingsModal = document.getElementById(Player.settingsModalId);
const showSettingsBtn = document.getElementById('show-settings-btn');
if (showSettingsBtn) {
showSettingsBtn.addEventListener('click', () => {
if (!settingsModal) return;
updateClassEls();
const modalBootstrap = bootstrap.Modal.getOrCreateInstance(settingsModal);
modalBootstrap.show();
});
}
// Handle assigning class names to individuals on settings modal
const assignClassNamesToIndivsnBtn = settingsModal.querySelector('#assign-class-names-to-indivs-settings-btn');
if (assignClassNamesToIndivsnBtn) {
assignClassNamesToIndivsnBtn.addEventListener('click', async (e) => await Player.handleAssignClassNamesBtnClick(e));
}
const clearAppDataBtn = document.getElementById('clear-app-data-btn');
if (clearAppDataBtn) {
// Remove the config file from user folder
clearAppDataBtn.addEventListener('click', async() => {
// Hide the settings modal
const settingsModalEl = document.getElementById(Player.settingsModalId);
if (settingsModalEl) {
const settingsModal = bootstrap.Modal.getOrCreateInstance(settingsModalEl);
settingsModal.hide();
}
// Show alert modal
showAlertModal(
'Proceed with Caution',
[
`This will result in losing all unexported work! The exported files will remain. This action cannot be undone.`,
'Are you sure you want to continue?'
]
);
// Get user confirmation
const alertConfirmBtn = document.getElementById('alert-confirm-btn');
if (alertConfirmBtn) {
const confirmed = await getUserConfirmationOnModal(alertConfirmBtn);
// Do NOT proceed if not confirmed
if (!confirmed) return;
// Clear the app data folder and its contents
const response = await window.electronAPI.clearAppData();
if (response) {
showAlertToast('Quitting...', 'success', 'App Data Cleared');
await window.electronAPI.exit();
}
}
});
}
// Handle opening name file with a list of the names of individuals
const importNameFileBtn = document.getElementById('open-name-list-file-btn');
if (importNameFileBtn) {
importNameFileBtn.addEventListener('click', async () => await Player.importNameFile());
}
// Handle opening tracking file
const importTrackingFileBtn = document.getElementById('import-tracking-file-btn');
if (importTrackingFileBtn) {
importTrackingFileBtn.addEventListener('click', async() => await Player.importTrackingFile());
}
// Handle opening action types file
const importActionFileBtn = document.getElementById('open-action-types-btn');
if (importActionFileBtn) {
importActionFileBtn.addEventListener('click', async() => await Player.importActionFile());
}
// Handle tracking and interaction nav tab clicks (sync toast and table nav active states)
const trackingToastTabBtn = document.getElementById('tracking-toast-tab');
if (trackingToastTabBtn) {
trackingToastTabBtn.addEventListener('click', () => {
const trackingTableTab = document.getElementById('tracking-table-tab');
if (trackingTableTab) trackingTable.click();
});
}
const interactionToastTabBtn = document.getElementById('interaction-toast-tab');
if (interactionToastTabBtn) {
interactionToastTabBtn.addEventListener('click', () => {
const interactionTableTab = document.getElementById('interaction-table-tab');
if (interactionTableTab) interactionTableTab.click();
});
}
// // Handle showing seconds or frames for time
// const timeFormatButtons = document.querySelectorAll('.time-format-btn');
// if (timeFormatButtons) {
// timeFormatButtons.forEach(button => {button.addEventListener('click', toggleTimeFormat)});
// }
// Handle exporting notes
const notesExportBtn = document.getElementById('export-notes-btn');
if (notesExportBtn) {
notesExportBtn.addEventListener('click', async () => {
const mainPlayer = Player.getMainPlayer();
if (!mainPlayer) return;
const notesTextArea = document.getElementById('notes-text-area');
if (!notesTextArea) return;
const text = notesTextArea.value;
if (!text) return;
const fileName = mainPlayer.getName();
if (!fileName) return;
const username = Player.getUsername();
const response = await window.electronAPI.exportNotes(text, fileName, username);
// Handle the intentional cancellation by users quitely
if (response.canceled) return;
// Show failure
if (!response) {
showAlertToast(
`Notes could <strong>NOT</strong> be exported! Please try again.`,
'error',
'Notes Export Failed'
);
return;
}
// Show success
if (response.filePath) {
// Construct the badge for file path
const filePathHtml = `<span class="badge text-bg-success">${response.filePath}<span>`;
showAlertToast(`Notes exported to: ${filePathHtml}!`, 'success', `Notes Exported`);
return;
}
})
}
// Keep track of interval ID for updating save status for notes
let notesIntervalId;
const notesTextAreaEl = document.getElementById('notes-text-area');
if (notesTextAreaEl) {
// Handle saving edits to notes
notesTextAreaEl.addEventListener('input', async () => {
// Check if the main player exists
const mainPlayer = Player.getMainPlayer();
if (!mainPlayer) return;
// Check if the file name exists
const fileName = mainPlayer.getName();
if (!fileName) return;
// Get the note content
const text = notesTextAreaEl.value;
// Get the username
const username = Player.getUsername();
// Save changes to a file in the user data directory
const filePath = await window.electronAPI.writeNotesToFile(text, fileName, username);
if (filePath) {
// Show last edit time
Player.showLastEditForNotes(filePath);
}
});
// // Disable/enable labeling when notes DOM element is focused/blurred
// notesTextAreaEl.addEventListener('focus', () => {
// Player.setTypingStatus(true);
// });
// notesTextAreaEl.addEventListener('blur', () => {
// Player.setTypingStatus(false);
// });
}
// Handle opening interaction labeling file
// const openInteractionFileBtn = document.getElementById('open-interaction-file-btn');
// if (openInteractionFileBtn) {
// openInteractionFileBtn.addEventListener('click', async () => {
// const = await window.electronAPI.openSingleFile('interactions');
// if () {
// const observations = await window.electronAPI.readInteractionFile();
// if (observations) {
// observations.forEach(observation => {
// addInteractionRow(interactionTable, observation)
// })
// }
// }
// })
// }
// Handle overlapping track selection button
const overlappingTracksSelectBtn = document.getElementById('overlapping-track-select-btn');
if (overlappingTracksSelectBtn) {
overlappingTracksSelectBtn.addEventListener('click', (event) => {
const trackSelect = document.getElementById('overlapping-track-select');
if (trackSelect) {
// Show warning if no track id is selected
if (trackSelect.selectedIndex === 0) {
const alertDiv = document.getElementById('overlapping-toast-alert-div');
if (alertDiv) {
alertDiv.textContent = 'A track ID must be selected!';
alertDiv.classList.remove('d-none');
}
} else {
const selectedOption = trackSelect.options[trackSelect.selectedIndex];
// Get the selected track id and class
const classId = selectedOption.dataset.classId;
const trackId = selectedOption.value;
// Find the selection in boxes in the current frame
const mainPlayer = Player.getMainPlayer();
if (mainPlayer) {
const boxesInFrame = mainPlayer.getTrackingBoxesInFrame();
if (boxesInFrame) {
const selectedBox = boxesInFrame.filter(box => box.getClassId() === classId && box.getTrackId() === trackId)[0]
if (selectedBox) {
const toastEl = document.getElementById('overlapping-tracks-toast');
const toastBootstrap = bootstrap.Toast.getOrCreateInstance(toastEl);
toastBootstrap.dispose();
// Show the toast for recording a behavior
showToastForBehaviorRecording({
event: event,
clickedBBox: selectedBox,
timestamp: mainPlayer.getCurrentTime(),
frameNumber: mainPlayer.getCurrentFrame()
});
}
}
}
return {classId: classId, trackId: trackId}
}
}
} )
}
// Handle canceling adding an action to table
// const cancelActionSaveBtn = document.getElementById('cancel-label-save-btn');
// if (cancelActionSaveBtn) {
// // Clear toast content
// const actionTab = toast.querySelector('#interaction-toast-tab');
// if (actionTab) {
// actionTab.dataset.obsStatus = 'new';
// }
// // Remove the incomplete observation from table
// // Dispose toast
// }
/**
* Change time format to frames to seconds (MM:SS) and vice versa
*/
function toggleTimeFormat() {
const timeFormatButtons = document.querySelectorAll('.time-format-btn');
// Get the time format status (frames or seconds)
const currentFormat = this.dataset.timeFormat;
// const tooltip = bootstrap.Tooltip.getInstance(this);
let iconText;
let timeFormat;
let tooltipTitle;
// Get the cells with time in them (either frame numbers or minutes:seconds)
const timeCells = document.querySelectorAll('.time-cell');
if (currentFormat === 'frames') {
timeFormat = 'seconds';
iconText = 'timer_off';
tooltipTitle = 'Hide seconds';
if (timeCells.length > 0) {
// Convert frames to seconds
timeCells.forEach(cell => {
if (cell.dataset.frameNumber) {
cell.textContent = formatSeconds(framesToSeconds(cell.dataset.frameNumber));
} else {
cell.textContent = '-'; // If no data is on the cell element yet
}
})
}
} else if (currentFormat === 'seconds') {
timeFormat = 'frames';
iconText = 'timer';
tooltipTitle = 'Show seconds';
if (timeCells.length > 0) {
// Convert seconds to frames
timeCells.forEach(cell => {
if (cell.dataset.frameNumber) {
cell.textContent = cell.dataset.frameNumber;
} else {
cell.textContent = '-'; // If no data is on the cell element yet
}
})
}
}
// Update the button status
if (timeFormatButtons) {
timeFormatButtons.forEach(button => {
button.dataset.timeFormat = timeFormat; // Update the time format status
button.querySelector('span').textContent = iconText; // Change the icon
const tooltip = bootstrap.Tooltip.getInstance(button);
tooltip.setContent({ '.tooltip-inner': tooltipTitle })
})
}
}
function resizeMainPanel(arg) {
const secondaryPanelEl = document.getElementById('secondary-video-col');
if (secondaryPanelEl) {
const currentClassName = secondaryPanelEl.className;
let secondaryColSize = parseInt(currentClassName.match(/\d+/)[0]); // Get the current column size of the secondary panel
const minColSize = 3;
const maxColSize = 6;
if (arg === 'enlarge') {
if (secondaryColSize > minColSize && secondaryColSize < 12) {
// Decrease the secondary column size
secondaryColSize = secondaryColSize - 1;
} else {
// Place the secondary panel below main panel if user enlarges the main panel too much
secondaryColSize = 12;
}
} else if (arg === 'shrink') {
if (secondaryColSize < maxColSize) {
secondaryColSize = secondaryColSize + 1; // Increase the secondary column size
} else if (secondaryColSize === 12) {
// Place the secondary panel to the right of the main panel if user shrinks the main panel too much
secondaryColSize = 3;
}
} else if (arg === 'reset') {
secondaryColSize = 4;
}
const newClassName = `col-${secondaryColSize}`
secondaryPanelEl.classList.remove(currentClassName) // Remove the old class (e.g. col-4)
secondaryPanelEl.classList.add(newClassName) // Add the new class (e.g. col-3)
}