-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrenderer.js
5200 lines (4374 loc) · 162 KB
/
renderer.js
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
const { ipcRenderer } = require("electron");
const path = require("path");
const { Titlebar, TitlebarColor } = require("custom-electron-titlebar");
const logger = require('./logger');
const fs = require('fs').promises;
const clipGrid = document.getElementById("clip-grid");
const fullscreenPlayer = document.getElementById("fullscreen-player");
const videoPlayer = document.getElementById("video-player");
const clipTitle = document.getElementById("clip-title");
const progressBarContainer = document.getElementById("progress-bar-container");
const progressBar = document.getElementById("progress-bar");
const trimStart = document.getElementById("trim-start");
const trimEnd = document.getElementById("trim-end");
const playhead = document.getElementById("playhead");
const loadingOverlay = document.getElementById("loading-overlay");
const playerOverlay = document.getElementById("player-overlay");
const videoClickTarget = document.getElementById("video-click-target");
const MAX_FRAME_RATE = 10;
const IDLE_TIMEOUT = 5 * 60 * 1000; // 5 minutes in milliseconds
const volumeButton = document.getElementById("volume-button");
const volumeSlider = document.getElementById("volume-slider");
const volumeContainer = document.getElementById("volume-container");
const speedButton = document.getElementById("speed-button");
const speedSlider = document.getElementById("speed-slider");
const speedContainer = document.getElementById("speed-container");
const speedText = document.getElementById("speed-text");
const volumeIcons = {
normal: `<svg xmlns="http://www.w3.org/2000/svg" height="24px" viewBox="0 -960 960 960" width="24px" fill="#e8eaed"><path d="M760-481q0-83-44-151.5T598-735q-15-7-22-21.5t-2-29.5q6-16 21.5-23t31.5 0q97 43 155 131.5T840-481q0 108-58 196.5T627-153q-16 7-31.5 0T574-176q-5-15 2-29.5t22-21.5q74-34 118-102.5T760-481ZM280-360H160q-17 0-28.5-11.5T120-400v-160q0-17 11.5-28.5T160-600h120l132-132q19-19 43.5-8.5T480-703v446q0 27-24.5 37.5T412-228L280-360Zm380-120q0 42-19 79.5T591-339q-10 6-20.5.5T560-356v-250q0-12 10.5-17.5t20.5.5q31 25 50 63t19 80ZM400-606l-86 86H200v80h114l86 86v-252ZM300-480Z"/></svg>`,
muted: `<svg xmlns="http://www.w3.org/2000/svg" height="24px" viewBox="0 -960 960 960" width="24px" fill="#e8eaed"><path d="m720-424-76 76q-11 11-28 11t-28-11q-11-11-11-28t11-28l76-76-76-76q-11-11-11-28t11-28q11-11 28-11t28 11l76 76 76-76q11-11 28-11t28 11q11 11 11 28t-11 28l-76 76 76 76q11 11 11 28t-11 28q-11 11-28 11t-28-11l-76-76Zm-440 64H160q-17 0-28.5-11.5T120-400v-160q0-17 11.5-28.5T160-600h120l132-132q19-19 43.5-8.5T480-703v446q0 27-24.5 37.5T412-228L280-360Zm120-246-86 86H200v80h114l86 86v-252ZM300-480Z"/></svg>`,
low: `<svg xmlns="http://www.w3.org/2000/svg" height="24px" viewBox="0 -960 960 960" width="24px" fill="#e8eaed"><path d="M360-360H240q-17 0-28.5-11.5T200-400v-160q0-17 11.5-28.5T240-600h120l132-132q19-19 43.5-8.5T560-703v446q0 27-24.5 37.5T492-228L360-360Zm380-120q0 42-19 79.5T671-339q-10 6-20.5.5T640-356v-250q0-12 10.5-17.5t20.5.5q31 25 50 63t19 80ZM480-606l-86 86H280v80h114l86 86v-252ZM380-480Z"/></svg>`,
high: `<svg xmlns="http://www.w3.org/2000/svg" height="24px" viewBox="0 -960 960 960" width="24px" fill="#e8eaed"><path d="M760-440h-80q-17 0-28.5-11.5T640-480q0-17 11.5-28.5T680-520h80q17 0 28.5 11.5T800-480q0 17-11.5 28.5T760-440ZM584-288q10-14 26-16t30 8l64 48q14 10 16 26t-8 30q-10 14-26 16t-30-8l-64-48q-14-10-16-26t8-30Zm120-424-64 48q-14 10-30 8t-26-16q-10-14-8-30t16-26l64-48q14-10 30-8t26 16q10 14 8 30t-16 26ZM280-360H160q-17 0-28.5-11.5T120-400v-160q0-17 11.5-28.5T160-600h120l132-132q19-19 43.5-8.5T480-703v446q0 27-24.5 37.5T412-228L280-360Zm120-246-86 86H200v80h114l86 86v-252ZM300-480Z"/></svg>`
};
const THUMBNAIL_RETRY_DELAY = 2000; // 2 seconds
const THUMBNAIL_INIT_DELAY = 1000; // 1 second delay before first validation
let audioContext, gainNode;
let initialPlaybackTime = 0;
let lastActivityTime = Date.now();
let currentClipList = [];
let currentClip = null;
let trimStartTime = 0;
let trimEndTime = 0;
let isDragging = null;
let isDraggingTrim = false;
let dragStartX = 0;
let dragThreshold = 5; // pixels
let lastMousePosition = { x: 0, y: 0 };
let isMouseDown = false;
let clipLocation;
let isLoading = false;
let currentCleanup = null;
let allClips = [];
let contextMenuClip = null;
let isTagsDropdownOpen = false;
let isFrameStepping = false;
let frameStepDirection = 0;
let lastFrameStepTime = 0;
let pendingFrameStep = false;
let controlsTimeout;
let isMouseOverControls = false;
let isRendering = false;
let deletionTooltip = null;
let deletionTimeout = null;
let settings;
let discordPresenceInterval;
let clipStartTime;
let elapsedTime = 0;
let loadingScreen;
let processingTimeout = null;
let activePreview = null;
let previewCleanupTimeout = null;
let isGeneratingThumbnails = false;
let currentGenerationTotal = 0;
let completedThumbnails = 0;
let thumbnailGenerationStartTime = 0;
let selectedClips = new Set();
let selectionStartIndex = -1;
let selectedTags = new Set();
let volumeStartTime = 0;
let volumeEndTime = 0;
let volumeLevel = 0; // Volume level for the range
let isVolumeDragging = null;
let volumeStartElement = null;
let volumeEndElement = null;
let volumeRegionElement = null;
let volumeDragControl = null;
let isVolumeControlsVisible = false;
let savedTagSelections = new Set(); // Permanent selections that are saved
let temporaryTagSelections = new Set(); // Temporary (Ctrl+click) selections
let isInTemporaryMode = false; // Whether we're in temporary selection mode
const previewElement = document.getElementById('timeline-preview');
previewElement.style.display = 'none';;
// Create a temporary video element for previews
const tempVideo = document.createElement('video');
tempVideo.crossOrigin = 'anonymous';
tempVideo.preload = 'auto';
tempVideo.muted = true;
tempVideo.style.display = 'none'; // Hide the temp video
document.body.appendChild(tempVideo); // Add to DOM
ipcRenderer.on('log', (event, { type, message }) => {
console[type](`[Main Process] ${message}`);
});
const settingsModal = document.createElement("div");
settingsModal.id = "settingsModal";
settingsModal.className = "settings-modal";
settingsModal.innerHTML = `
<div class="settings-modal-content">
<div class="settings-tabs">
<div class="settings-tab active" data-tab="general">General</div>
<div class="settings-tab" data-tab="exportImport">Export/Import</div>
<div class="settings-tab" data-tab="about">About</div>
</div>
<div class="settings-tab-content active" data-tab="general">
<div class="settings-group">
<h3 class="settings-group-title">Clip Library Location</h3>
<div class="settings-item">
<div class="settings-item-info">
<div class="settings-item-title">Current Location</div>
<div class="settings-item-description" id="currentClipLocation">Loading...</div>
</div>
<div class="settings-control">
<button id="changeLocationBtn" class="settings-button settings-button-primary">Change Location</button>
</div>
</div>
</div>
<div class="settings-group">
<h3 class="settings-group-title">Playback</h3>
<div class="settings-item">
<div class="settings-item-info">
<div class="settings-item-title">Preview Volume</div>
<div class="settings-item-description">Set the default volume for clip previews</div>
</div>
<div class="settings-control">
<input type="range" id="previewVolumeSlider" class="settings-range" min="0" max="1" step="0.01" value="0.1">
<span id="previewVolumeValue">10%</span>
</div>
</div>
</div>
<div class="settings-group">
<h3 class="settings-group-title">Integration</h3>
<div class="settings-item">
<div class="settings-item-info">
<div class="settings-item-title">Discord Rich Presence</div>
<div class="settings-item-description">Show your current activity in Discord</div>
</div>
<div class="settings-control">
<label class="settings-switch">
<input type="checkbox" id="enableDiscordRPC">
<span class="settings-switch-slider"></span>
</label>
</div>
</div>
</div>
<div class="settings-group">
<h3 class="settings-group-title">Tag Management</h3>
<div class="settings-item">
<div class="settings-item-info">
<div class="settings-item-title">Manage Tags</div>
<div class="settings-item-description">Edit and organize your clip tags</div>
</div>
<div class="settings-control">
<button id="manageTagsBtn" class="settings-button settings-button-secondary">Manage Tags</button>
</div>
</div>
</div>
</div>
<div class="settings-tab-content" data-tab="exportImport">
<div class="settings-group">
<h3 class="settings-group-title">Export Settings</h3>
<div class="settings-item">
<div class="settings-item-info">
<div class="settings-item-title">Export Quality</div>
<div class="settings-item-description">Choose the default quality for exported clips</div>
</div>
<div class="settings-control">
<select id="exportQuality" class="settings-select">
<option value="discord">Discord (~10MB)</option>
<option value="high">High Quality (~30MB)</option>
<option value="lossless">Lossless</option>
</select>
</div>
</div>
</div>
<div class="settings-group">
<h3 class="settings-group-title">Import Options</h3>
<div class="settings-item">
<div class="settings-item-info">
<div class="settings-item-title">Import from SteelSeries</div>
<div class="settings-item-description">Select your SteelSeries Moments folder</div>
</div>
<div class="settings-control">
<button id="importSteelSeriesBtn" class="settings-button settings-button-primary">Import Clips</button>
</div>
</div>
</div>
</div>
<div class="settings-tab-content" data-tab="about">
<div class="settings-group">
<div class="settings-item">
<div class="settings-item-info">
<div class="settings-item-title">Clip Library</div>
<div class="settings-item-description">A modern, fast, and efficient way to manage your clip collection.</div>
</div>
</div>
</div>
<div class="settings-version">
<p>Version: <span id="app-version">Loading...</span></p>
</div>
</div>
<div class="settings-footer">
<button id="closeSettingsBtn" class="settings-save-button">
Save Settings
</button>
</div>
</div>
`;
const container = document.querySelector('.cet-container') || document.body;
container.appendChild(settingsModal);
const closeSettingsBtn = document.getElementById("closeSettingsBtn");
const currentClipLocationSpan = document.getElementById("currentClipLocation");
async function fetchSettings() {
settings = await ipcRenderer.invoke('get-settings');
logger.info('Fetched settings:', settings); // Log the fetched settings
// Set defaults if not present
if (settings.previewVolume === undefined) settings.previewVolume = 0.1;
if (settings.exportQuality === undefined) settings.exportQuality = 'discord';
await ipcRenderer.invoke('save-settings', settings);
logger.info('Settings after defaults:', settings); // Log after setting defaults
return settings;
}
async function loadClips() {
try {
logger.info("Loading clips...");
clipLocation = await ipcRenderer.invoke("get-clip-location");
currentClipLocationSpan.textContent = clipLocation;
allClips = await ipcRenderer.invoke("get-clips");
logger.info("Clips received:", allClips.length);
// Load tags for each clip in smaller batches
const TAG_BATCH_SIZE = 50;
for (let i = 0; i < allClips.length; i += TAG_BATCH_SIZE) {
const batch = allClips.slice(i, i + TAG_BATCH_SIZE);
await Promise.all(batch.map(async (clip) => {
clip.tags = await ipcRenderer.invoke("get-clip-tags", clip.originalName);
}));
// Small delay between tag batches
if (i + TAG_BATCH_SIZE < allClips.length) {
await new Promise(resolve => setTimeout(resolve, 10));
}
}
allClips = removeDuplicates(allClips);
allClips.sort((a, b) => b.createdAt - a.createdAt);
await loadTagPreferences(); // This will set up selectedTags
filterClips(); // This will set currentClipList correctly
logger.info("Initial currentClipList length:", currentClipList.length);
updateClipCounter(currentClipList.length);
renderClips(currentClipList);
setupClipTitleEditing();
validateClipLists();
updateFilterDropdown();
logger.info("Clips loaded and rendered.");
hideLoadingScreen();
// Start thumbnail validation after a short delay
setTimeout(() => {
startThumbnailValidation();
}, 1000);
} catch (error) {
logger.error("Error loading clips:", error);
clipGrid.innerHTML = `<p class="error-message">Error loading clips. Please check your clip location in settings.</p>`;
currentClipLocationSpan.textContent = "Error: Unable to load location";
hideThumbnailGenerationText();
hideLoadingScreen();
}
}
async function startThumbnailValidation() {
logger.info("Starting thumbnail validation for clips:", allClips.length);
await new Promise(resolve => setTimeout(resolve, THUMBNAIL_INIT_DELAY));
try {
let timeoutId;
const createTimeout = () => {
if (timeoutId) clearTimeout(timeoutId);
return new Promise((_, reject) => {
timeoutId = setTimeout(() => {
reject(new Error("Thumbnail generation timeout"));
}, 30000);
});
};
let currentTimeout = createTimeout();
// Add this line to collect pending clips
const pendingClips = new Set(allClips.map(clip => clip.originalName));
const generationPromise = new Promise((resolve) => {
ipcRenderer.invoke("generate-thumbnails-progressively", Array.from(pendingClips))
.then((result) => {
if (result.needsGeneration > 0) {
showThumbnailGenerationText(result.needsGeneration);
ipcRenderer.on("thumbnail-progress", (event, { current, total, clipName }) => {
currentTimeout = createTimeout();
if (isGeneratingThumbnails) {
updateThumbnailGenerationText(total - current);
}
// Remove from pending set when processed
pendingClips.delete(clipName);
ipcRenderer.invoke("get-thumbnail-path", clipName).then(thumbnailPath => {
if (thumbnailPath) {
updateClipThumbnail(clipName, thumbnailPath);
}
});
});
ipcRenderer.once("thumbnail-generation-complete", () => {
// Check if any clips were missed
if (pendingClips.size > 0) {
// Process any remaining clips
ipcRenderer.invoke("generate-thumbnails-progressively", Array.from(pendingClips));
}
clearTimeout(timeoutId);
hideThumbnailGenerationText();
resolve(result);
});
} else {
hideThumbnailGenerationText();
resolve(result);
}
});
});
await Promise.race([generationPromise, currentTimeout]);
} catch (error) {
logger.error("Error during thumbnail validation:", error);
hideThumbnailGenerationText();
setTimeout(() => {
startThumbnailValidation();
}, THUMBNAIL_RETRY_DELAY);
}
}
function hideLoadingScreen() {
if (loadingScreen) {
// Add the fade-out class to trigger the animations
loadingScreen.classList.add('fade-out');
// Remove the element after the animation completes
setTimeout(() => {
loadingScreen.style.display = 'none';
}, 1000); // Match this with the animation duration (1s)
}
}
async function updateVersionDisplay() {
try {
const version = await ipcRenderer.invoke('get-app-version');
const versionElement = document.getElementById('app-version');
if (versionElement) {
versionElement.textContent = `Version: ${version}`;
}
} catch (error) {
logger.error('Failed to get app version:', error);
}
}
async function addNewClipToLibrary(fileName) {
try {
// First check if the file exists
const clipPath = path.join(settings.clipLocation, fileName);
try {
await fs.access(clipPath);
} catch (error) {
logger.info(`File no longer exists, skipping: ${fileName}`);
return;
}
const newClipInfo = await ipcRenderer.invoke('get-new-clip-info', fileName);
// Check if the clip already exists in allClips
const existingClipIndex = allClips.findIndex(clip => clip.originalName === newClipInfo.originalName);
if (existingClipIndex === -1) {
// If it doesn't exist, add it to allClips
allClips.unshift(newClipInfo);
// Create clip element with a loading thumbnail first
const newClipElement = await createClipElement({
...newClipInfo,
thumbnailPath: "assets/loading-thumbnail.gif"
});
clipGrid.insertBefore(newClipElement, clipGrid.firstChild);
// Force a clean state for the new clip
const clipElement = clipGrid.querySelector(`[data-original-name="${newClipInfo.originalName}"]`);
if (clipElement) {
clipElement.dataset.trimStart = undefined;
clipElement.dataset.trimEnd = undefined;
}
// Generate thumbnail in the background without waiting
setTimeout(async () => {
try {
await ipcRenderer.invoke("generate-thumbnails-progressively", [fileName]);
} catch (error) {
logger.error("Error in background thumbnail generation:", error);
}
}, 1000); // Give a slight delay to ensure file is fully written
} else {
// If it exists, update the existing clip info
allClips[existingClipIndex] = newClipInfo;
const existingElement = clipGrid.querySelector(`[data-original-name="${newClipInfo.originalName}"]`);
if (existingElement) {
const updatedElement = await createClipElement(newClipInfo);
existingElement.replaceWith(updatedElement);
}
}
updateFilterDropdown();
} catch (error) {
// Only log as info if it's a file not found error, otherwise log as error
if (error.code === 'ENOENT') {
logger.info(`Skipping non-existent file: ${fileName}`);
} else {
logger.error("Error adding new clip to library:", error);
}
}
}
ipcRenderer.on('new-clip-added', async (event, fileName) => {
// Wait for settings to be loaded if they haven't been yet
if (!settings) {
try {
settings = await ipcRenderer.invoke('get-settings');
} catch (error) {
logger.error('Failed to load settings:', error);
return;
}
}
await addNewClipToLibrary(fileName);
updateFilterDropdown();
});
ipcRenderer.on("thumbnail-validation-start", (event, { total }) => {
// Always reset state when validation starts
isGeneratingThumbnails = false;
currentGenerationTotal = 0;
completedThumbnails = 0;
thumbnailGenerationStartTime = null;
if (total > 0) {
showThumbnailGenerationText(total);
}
});
ipcRenderer.on("thumbnail-progress", (event, { current, total, clipName }) => {
if (isGeneratingThumbnails) {
updateThumbnailGenerationText(total - current);
}
logger.info(`Thumbnail generation progress: (${current}/${total}) - Processing: ${clipName}`);
});
ipcRenderer.on("thumbnail-generation-complete", () => {
hideThumbnailGenerationText();
isGeneratingThumbnails = false;
// Clear any existing timeouts here as well
if (window.thumbnailGenerationTimeout) {
clearTimeout(window.thumbnailGenerationTimeout);
window.thumbnailGenerationTimeout = null;
}
});
function showThumbnailGenerationText(totalToGenerate) {
if (totalToGenerate <= 0) return;
// Reset all state variables
isGeneratingThumbnails = true;
currentGenerationTotal = totalToGenerate;
completedThumbnails = 0;
thumbnailGenerationStartTime = Date.now();
let textElement = document.getElementById("thumbnail-generation-text");
if (!textElement) {
textElement = document.createElement("div");
textElement.id = "thumbnail-generation-text";
textElement.style.position = "fixed";
textElement.style.top = "100px";
textElement.style.left = "50%";
textElement.style.transform = "translateX(-50%)";
textElement.style.backgroundColor = "rgba(0, 0, 0, 0.7)";
textElement.style.color = "white";
textElement.style.padding = "10px 20px";
textElement.style.borderRadius = "20px";
textElement.style.zIndex = "10000";
textElement.style.fontWeight = "normal";
textElement.style.display = "block";
document.body.appendChild(textElement);
}
updateThumbnailGenerationText(totalToGenerate);
}
function updateClipCounter(count) {
const counter = document.getElementById('clip-counter');
if (counter) {
counter.textContent = `Clips: ${count}`;
}
}
function updateThumbnailGenerationText(remaining) {
if (!isGeneratingThumbnails) return;
const textElement = document.getElementById("thumbnail-generation-text");
if (!textElement) return;
textElement.style.display = "block";
if (remaining <= 0) {
hideThumbnailGenerationText();
return;
}
completedThumbnails = currentGenerationTotal - remaining;
const percentage = Math.round((completedThumbnails / currentGenerationTotal) * 100);
// Calculate time estimate based on actual progress
let estimatedTimeRemaining = 0;
if (completedThumbnails > 0) {
const elapsedTime = (Date.now() - thumbnailGenerationStartTime) / 1000; // in seconds
const averageTimePerThumbnail = elapsedTime / completedThumbnails;
// Calculate remaining time and convert to minutes, rounding up
estimatedTimeRemaining = Math.ceil((averageTimePerThumbnail * remaining) / 60);
// Ensure we show at least 1 minute if there's any time remaining
if (remaining > 0 && estimatedTimeRemaining === 0) {
estimatedTimeRemaining = 1;
}
}
textElement.textContent = `Generating thumbnails... ${completedThumbnails}/${currentGenerationTotal} (${percentage}%) - Est. ${estimatedTimeRemaining} min remaining`;
}
function hideThumbnailGenerationText() {
const textElement = document.getElementById("thumbnail-generation-text");
if (textElement) {
textElement.remove();
}
isGeneratingThumbnails = false;
currentGenerationTotal = 0;
completedThumbnails = 0;
}
window.addEventListener('beforeunload', () => {
if (window.thumbnailGenerationTimeout) {
clearTimeout(window.thumbnailGenerationTimeout);
}
hideThumbnailGenerationText();
});
ipcRenderer.on("thumbnail-generation-failed", (event, { clipName, error }) => {
logger.error(`Failed to generate thumbnail for ${clipName}: ${error}`);
});
ipcRenderer.on("thumbnail-generated", (event, { clipName, thumbnailPath }) => {
updateClipThumbnail(clipName, thumbnailPath);
});
async function getFfmpegVersion() {
try {
await ipcRenderer.invoke('get-ffmpeg-version');
} catch (error) {
logger.error('Failed to get FFmpeg version:', error);
}
}
function updateClipThumbnail(clipName, thumbnailPath) {
const clipElement = document.querySelector(
`.clip-item[data-original-name="${clipName}"]`
);
if (clipElement) {
const imgElement = clipElement.querySelector("img");
if (imgElement) {
// Create a new image element
const newImg = new Image();
newImg.onload = () => {
// Only replace the src after the new image has loaded
imgElement.src = newImg.src;
};
// Add cache busting and random number to ensure unique URL
newImg.src = `file://${thumbnailPath}?t=${Date.now()}-${Math.random()}`;
} else {
logger.warn(`Image element not found for clip: ${clipName}`);
}
} else {
logger.warn(`Clip element not found for: ${clipName}`);
}
}
async function renderClips(clips) {
if (isRendering) {
logger.info("Render already in progress, skipping");
return;
}
isRendering = true;
logger.info("Rendering clips. Input length:", clips.length);
clipGrid.innerHTML = ""; // Clear the grid
clips = removeDuplicates(clips);
logger.info("Clips to render after removing duplicates:", clips.length);
const clipPromises = clips.map(createClipElement);
const clipElements = await Promise.all(clipPromises);
clipElements.forEach((clipElement) => {
clipGrid.appendChild(clipElement);
const clip = clips.find(c => c.originalName === clipElement.dataset.originalName);
if (clip) {
updateClipTags(clip);
}
});
setupTooltips();
currentClipList = clips;
addHoverEffect();
document.querySelectorAll('.clip-item').forEach(card => {
card.addEventListener('mouseenter', handleMouseEnter);
card.addEventListener('mouseleave', handleMouseLeave);
});
logger.info("Rendered clips count:", clipGrid.children.length);
isRendering = false;
}
let currentHoveredCard = null;
function handleOnMouseMove(e) {
if (!currentHoveredCard) return;
const rect = currentHoveredCard.getBoundingClientRect();
const x = e.clientX - rect.left;
const y = e.clientY - rect.top;
const centerX = rect.width / 2;
const centerY = rect.height / 2;
const tiltX = (y - centerY) / centerY;
const tiltY = (centerX - x) / centerX;
requestAnimationFrame(() => {
if (currentHoveredCard) {
currentHoveredCard.style.setProperty("--mouse-x", `${x}px`);
currentHoveredCard.style.setProperty("--mouse-y", `${y}px`);
currentHoveredCard.style.setProperty("--tilt-x", `${tiltX * 5}deg`);
currentHoveredCard.style.setProperty("--tilt-y", `${tiltY * 5}deg`);
}
});
}
function handleMouseEnter(e) {
currentHoveredCard = e.currentTarget;
}
function handleMouseLeave(e) {
const card = e.currentTarget;
card.style.setProperty("--tilt-x", "0deg");
card.style.setProperty("--tilt-y", "0deg");
currentHoveredCard = null;
}
function addHoverEffect() {
const wrapper = document.getElementById("clip-grid");
wrapper.addEventListener("mousemove", handleOnMouseMove);
}
function setupSearch() {
const searchInput = document.getElementById("search-input");
searchInput.addEventListener("input", debounce(performSearch, 300));
}
function performSearch() {
const searchDisplay = document.getElementById('search-display');
if (!searchDisplay) return;
const searchText = searchDisplay.innerText.trim().toLowerCase();
const searchTerms = parseSearchTerms(searchText);
// Start with all clips
let filteredClips = [...allClips];
// Apply search terms if they exist
if (searchTerms.tags.length > 0 || searchTerms.text.length > 0) {
filteredClips = filteredClips.filter(clip => {
// Check tag matches
const hasMatchingTags = searchTerms.tags.length === 0 ||
searchTerms.tags.every(searchTag =>
clip.tags.some(clipTag =>
clipTag.toLowerCase().includes(searchTag.toLowerCase().substring(1))
)
);
// Check text matches
const hasMatchingText = searchTerms.text.length === 0 ||
searchTerms.text.every(word =>
clip.customName.toLowerCase().includes(word) ||
clip.originalName.toLowerCase().includes(word)
);
return hasMatchingTags && hasMatchingText;
});
}
// Apply tag filter from dropdown
if (selectedTags.size > 0) {
filteredClips = filteredClips.filter(clip => {
if (selectedTags.has('Untagged')) {
if (!clip.tags || clip.tags.length === 0) {
return true;
}
}
return clip.tags && clip.tags.some(tag => selectedTags.has(tag));
});
}
// Remove duplicates
currentClipList = filteredClips.filter((clip, index, self) =>
index === self.findIndex((t) => t.originalName === clip.originalName)
);
// Sort by creation date
currentClipList.sort((a, b) => b.createdAt - a.createdAt);
renderClips(currentClipList);
updateClipCounter(currentClipList.length);
if (currentClip) {
updateNavigationButtons();
}
}
function parseSearchTerms(searchText) {
const terms = searchText.split(/\s+/).filter(term => term.length > 0);
return {
// Get all terms that start with @ (tags)
tags: terms.filter(term => term.startsWith('@')),
// Get all other terms (regular search)
text: terms.filter(term => !term.startsWith('@'))
};
}
// Debounce function to limit how often the search is performed
function debounce(func, delay) {
let debounceTimer;
return function () {
const context = this;
const args = arguments;
clearTimeout(debounceTimer);
debounceTimer = setTimeout(() => func.apply(context, args), delay);
};
}
function setupContextMenu() {
const contextMenu = document.getElementById("context-menu");
const contextMenuExport = document.getElementById("context-menu-export");
const contextMenuDelete = document.getElementById("context-menu-delete");
const contextMenuTags = document.getElementById("context-menu-tags");
const tagsDropdown = document.getElementById("tags-dropdown");
const tagSearchInput = document.getElementById("tag-search-input");
const addTagButton = document.getElementById("add-tag-button");
if (
!contextMenu ||
!contextMenuExport ||
!contextMenuDelete) {
logger.error("One or more context menu elements not found");
return;
}
document.addEventListener("click", (e) => {
if (!contextMenu.contains(e.target)) {
contextMenu.style.display = "none";
isTagsDropdownOpen = false;
tagsDropdown.style.display = "none";
}
});
contextMenuExport.addEventListener("click", () => {
logger.info("Export clicked for clip:", contextMenuClip?.originalName);
if (contextMenuClip) {
exportClipFromContextMenu(contextMenuClip);
}
contextMenu.style.display = "none";
});
contextMenuTags.addEventListener("click", (e) => {
e.stopPropagation();
isTagsDropdownOpen = !isTagsDropdownOpen;
const tagsDropdown = document.getElementById("tags-dropdown");
tagsDropdown.style.display = isTagsDropdownOpen ? "block" : "none";
if (isTagsDropdownOpen) {
const tagSearchInput = document.getElementById("tag-search-input");
tagSearchInput.focus();
updateTagList();
}
});
addTagButton.addEventListener("click", () => {
const tagSearchInput = document.getElementById("tag-search-input");
const newTag = tagSearchInput.value.trim();
if (newTag && !globalTags.includes(newTag)) {
addGlobalTag(newTag);
if (contextMenuClip) {
toggleClipTag(contextMenuClip, newTag);
}
tagSearchInput.value = "";
updateTagList();
}
});
tagSearchInput.addEventListener("input", updateTagList);
tagSearchInput.addEventListener("keydown", (e) => {
if (e.key === "Enter") {
e.preventDefault();
const searchTerm = tagSearchInput.value.trim().toLowerCase();
// Find the closest matching tag
const matchingTag = globalTags.find(tag =>
tag.toLowerCase() === searchTerm ||
tag.toLowerCase().startsWith(searchTerm)
);
if (matchingTag && contextMenuClip) {
toggleClipTag(contextMenuClip, matchingTag);
tagSearchInput.value = "";
updateTagList();
}
}
});
tagsDropdown.addEventListener("click", (e) => {
e.stopPropagation();
});
contextMenuDelete.addEventListener("click", async () => {
logger.info("Delete clicked for clip:", contextMenuClip?.originalName);
if (contextMenuClip) {
await confirmAndDeleteClip(contextMenuClip);
}
contextMenu.style.display = "none";
});
// Close context menu when clicking outside
document.addEventListener("click", () => {
contextMenu.style.display = "none";
});
}
document.getElementById('manageTagsBtn').addEventListener('click', openTagManagement);
let isTagManagementOpen = false;
function openTagManagement() {
if (isTagManagementOpen) {
logger.info("Tag management modal is already open");
return;
}
const existingModal = document.getElementById('tagManagementModal');
if (existingModal) {
existingModal.remove();
}
const container = document.querySelector('.cet-container') || document.body;
const modal = document.createElement('div');
modal.id = 'tagManagementModal';
modal.className = 'tagManagement-modal';
modal.innerHTML = `
<div class="tagManagement-content">
<div class="tagManagement-header">
<h2 class="tagManagement-title">Tag Management</h2>
</div>
<div class="tagManagement-search">
<input type="text"
class="tagManagement-searchInput"
placeholder="Search tags..."
id="tagManagementSearch">
</div>
<div class="tagManagement-list" id="tagManagementList">
${globalTags.length === 0 ?
'<div class="tagManagement-noTags">No tags created yet. Add your first tag below!</div>' :
''}
</div>
<div class="tagManagement-footer">
<button class="tagManagement-addBtn" id="tagManagementAddBtn">
Add New Tag
</button>
<button class="tagManagement-closeBtn" id="tagManagementCloseBtn">
Close
</button>
</div>
</div>
`;
container.appendChild(modal);
modal.style.display = 'block';
isTagManagementOpen = true;
// Render initial tags
renderTagList(globalTags);
// Setup event listeners
const searchInput = document.getElementById('tagManagementSearch');
const closeBtn = document.getElementById('tagManagementCloseBtn');
const addBtn = document.getElementById('tagManagementAddBtn');
searchInput.addEventListener('input', (e) => {
const searchTerm = e.target.value.toLowerCase();
const filteredTags = globalTags.filter(tag =>
tag.toLowerCase().includes(searchTerm)
);
renderTagList(filteredTags);
});
addBtn.addEventListener('click', () => {
addNewTag();
});
closeBtn.addEventListener('click', closeTagManagement);
// Close on click outside
modal.addEventListener('click', (e) => {
if (e.target === modal) {
closeTagManagement();
}
});
// Close on Escape key
document.addEventListener('keydown', handleEscapeKey);
}
function renderTagList(tags) {
const listElement = document.getElementById('tagManagementList');
if (!listElement) return;
listElement.innerHTML = tags.length === 0 ?
'<div class="tagManagement-noTags">No tags found</div>' :
tags.map(tag => `
<div class="tagManagement-item" data-tag="${tag}">
<input type="text"
class="tagManagement-input"
value="${tag}"
data-original="${tag}">
<button class="tagManagement-deleteBtn">Delete</button>
</div>
`).join('');
// Add event listeners for input changes and delete buttons