-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrenderer.js
1423 lines (1248 loc) · 55.1 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 marked = require('marked');
const path = require('path');
// Auto-update event handling
let updateAvailable = false;
let updateDownloaded = false;
let updateInfo = null;
ipcRenderer.on('update-status', (event, status) => {
const quickUpdateBtn = document.getElementById('quickUpdateBtn');
switch (status.status) {
case 'checking':
updateButtonStatus(quickUpdateBtn, 'Checking for updates...');
break;
case 'available':
updateAvailable = true;
updateInfo = status;
updateButtonStatus(quickUpdateBtn, `Update ${status.version} available`);
showUpdateNotification(status);
break;
case 'not-available':
updateButtonStatus(quickUpdateBtn, 'No updates available');
setTimeout(() => {
clearButtonStatus(quickUpdateBtn);
}, 3000);
break;
case 'downloading':
const progress = Math.round(status.progress.percent);
updateButtonStatus(quickUpdateBtn, `Downloading: ${progress}%`);
break;
case 'downloaded':
updateDownloaded = true;
updateButtonStatus(quickUpdateBtn, 'Update ready to install');
showInstallNotification(status);
break;
case 'error':
updateButtonStatus(quickUpdateBtn, `Error: ${status.error}`);
setTimeout(() => {
clearButtonStatus(quickUpdateBtn);
}, 5000);
break;
}
});
function showUpdateNotification(info) {
const notification = document.createElement('div');
notification.className = 'update-notification';
notification.innerHTML = `
<div class="notification-content">
<h3>Update Available: ${info.version}</h3>
<p>${info.releaseNotes ? marked.parse(info.releaseNotes) : 'A new version is available.'}</p>
<div class="notification-actions">
<button class="action-button" onclick="downloadUpdate()">Download Update</button>
<button class="action-button secondary" onclick="this.parentElement.parentElement.parentElement.remove()">Later</button>
</div>
</div>
`;
document.body.appendChild(notification);
}
function showInstallNotification(info) {
const notification = document.createElement('div');
notification.className = 'update-notification';
notification.innerHTML = `
<div class="notification-content">
<h3>Update Ready to Install</h3>
<p>Version ${info.version} has been downloaded and is ready to install.</p>
<div class="notification-actions">
<button class="action-button" onclick="installUpdate()">Install and Restart</button>
<button class="action-button secondary" onclick="this.parentElement.parentElement.parentElement.remove()">Later</button>
</div>
</div>
`;
document.body.appendChild(notification);
}
async function checkForUpdates() {
try {
await ipcRenderer.invoke('check-for-updates');
} catch (error) {
console.error('Error checking for updates:', error);
}
}
async function downloadUpdate() {
if (!updateAvailable) return;
const quickUpdateBtn = document.getElementById('quickUpdateBtn');
try {
updateButtonStatus(quickUpdateBtn, 'Starting download...');
await ipcRenderer.invoke('download-update');
} catch (error) {
console.error('Error downloading update:', error);
updateButtonStatus(quickUpdateBtn, 'Download failed');
setTimeout(() => {
clearButtonStatus(quickUpdateBtn);
}, 3000);
}
}
function installUpdate() {
if (!updateDownloaded) return;
ipcRenderer.invoke('quit-and-install');
}
// Check for updates when the app starts
setTimeout(checkForUpdates, 3000);
// Theme handling
const themeToggle = document.getElementById('themeToggle');
let currentTheme = localStorage.getItem('theme') || 'light';
document.documentElement.setAttribute('data-theme', currentTheme);
themeToggle.addEventListener('click', () => {
currentTheme = currentTheme === 'light' ? 'dark' : 'light';
document.documentElement.setAttribute('data-theme', currentTheme);
localStorage.setItem('theme', currentTheme);
});
// Window control buttons
document.getElementById('closeBtn').addEventListener('click', () => ipcRenderer.invoke('close-window'));
document.getElementById('minimizeBtn').addEventListener('click', () => ipcRenderer.invoke('minimize-window'));
document.getElementById('maximizeBtn').addEventListener('click', () => ipcRenderer.invoke('maximize-window'));
// Navigation
const navItems = document.querySelectorAll('.nav-item');
const views = document.querySelectorAll('.view');
navItems.forEach(item => {
item.addEventListener('click', () => {
const viewId = item.dataset.view;
navItems.forEach(nav => nav.classList.remove('active'));
item.classList.add('active');
views.forEach(view => {
view.classList.remove('active');
if (view.id === viewId) {
view.classList.add('active');
}
});
});
});
// Helper functions for button status
function updateButtonStatus(button, text) {
const statusText = button.querySelector('.status-text');
if (statusText) {
statusText.textContent = text;
button.classList.remove('return-to-center');
button.classList.add('has-status');
// For quick action buttons
if (button.classList.contains('quick-action-button')) {
const contentWrapper = button.querySelector('.content-wrapper');
if (contentWrapper) {
contentWrapper.style.transition = 'all 0.3s cubic-bezier(0.4, 0, 0.2, 1)';
}
}
// For install buttons
else if (button.classList.contains('install-button')) {
const buttonText = button.querySelector('.button-text');
if (buttonText) {
buttonText.style.opacity = '0';
}
}
}
}
function clearButtonStatus(button) {
const statusText = button.querySelector('.status-text');
if (statusText) {
button.classList.add('return-to-center');
button.classList.remove('has-status');
// For quick action buttons
if (button.classList.contains('quick-action-button')) {
// Wait for transition to complete before clearing text
setTimeout(() => {
statusText.textContent = '';
button.classList.remove('return-to-center');
}, 300);
}
// For install buttons
else if (button.classList.contains('install-button')) {
const buttonText = button.querySelector('.button-text');
if (buttonText) {
buttonText.style.opacity = '1';
setTimeout(() => {
statusText.textContent = '';
}, 300);
}
}
}
}
function setButtonLoading(button, isLoading) {
if (isLoading) {
button.classList.add('loading');
button.disabled = true;
// For quick action buttons
if (button.classList.contains('quick-action-button')) {
const contentWrapper = button.querySelector('.content-wrapper');
if (contentWrapper) {
contentWrapper.style.opacity = '0.5';
}
}
// For install buttons
else if (button.classList.contains('install-button')) {
const buttonText = button.querySelector('.button-text');
if (buttonText) {
buttonText.style.opacity = '0';
}
}
} else {
button.classList.remove('loading');
button.disabled = false;
// For quick action buttons
if (button.classList.contains('quick-action-button')) {
const contentWrapper = button.querySelector('.content-wrapper');
if (contentWrapper) {
contentWrapper.style.opacity = '1';
}
}
// For install buttons
else if (button.classList.contains('install-button')) {
const buttonText = button.querySelector('.button-text');
if (buttonText) {
buttonText.style.opacity = '1';
}
}
}
}
// Helper function to wait for Pinokio to be ready
async function waitForPinokio(maxAttempts = 30) {
for (let i = 0; i < maxAttempts; i++) {
try {
const response = await fetch('http://localhost/pinokio/info');
if (!response.ok) {
await new Promise(resolve => setTimeout(resolve, 1000));
continue;
}
const data = await response.json();
if (!data || !data.version || !data.version.pinokio) {
await new Promise(resolve => setTimeout(resolve, 1000));
continue;
}
const version = data.version.pinokio;
const versionParts = version.split('.');
if (versionParts.length === 3) {
const versionNum = parseInt(versionParts[0]) * 1000000 +
parseInt(versionParts[1]) * 1000 +
parseInt(versionParts[2]);
if (versionNum >= 3002200) {
return { success: true, version };
}
return { success: false, error: `Version 3.2.200 or higher required (current: ${version})` };
}
return { success: false, error: 'Invalid version format' };
} catch (error) {
await new Promise(resolve => setTimeout(resolve, 1000));
}
}
return { success: false, error: 'Timed out waiting for Pinokio' };
}
// Quick action buttons
document.getElementById('launchPinokioBtn').addEventListener('click', async () => {
const button = document.getElementById('launchPinokioBtn');
try {
setButtonLoading(button, true);
updateButtonStatus(button, 'Launching Pinokio...');
await ipcRenderer.invoke('launch-pinokio');
let attempts = 0;
const maxAttempts = 30;
while (attempts < maxAttempts) {
try {
updateButtonStatus(button, 'Waiting for Pinokio to start...');
const pinokioStatus = await waitForPinokio(1);
if (pinokioStatus.success) {
updateButtonStatus(button, `Pinokio ${pinokioStatus.version} is now running!`);
setButtonLoading(button, false);
setTimeout(() => {
clearButtonStatus(button);
window.location.reload();
}, 2000);
return;
}
} catch (error) {
// Keep waiting
}
await new Promise(resolve => setTimeout(resolve, 1000));
attempts++;
}
throw new Error('Timed out waiting for Pinokio to start');
} catch (error) {
updateButtonStatus(button, 'Failed to launch: ' + error.message);
setButtonLoading(button, false);
setTimeout(() => {
clearButtonStatus(button);
}, 3000);
}
});
document.getElementById('quickUpdateBtn').addEventListener('click', async () => {
const button = document.getElementById('quickUpdateBtn');
try {
button.classList.add('loading');
updateButtonStatus(button, 'Checking latest stable version...');
const latestRelease = await ipcRenderer.invoke('get-latest-release');
const systemArch = await ipcRenderer.invoke('get-system-arch');
updateButtonStatus(button, `Found version ${latestRelease.tag_name}`);
await new Promise(resolve => setTimeout(resolve, 1000));
const asset = latestRelease.assets.find(a => a.name.includes(systemArch));
if (!asset) {
throw new Error('No compatible version found');
}
let progress = 0;
const progressInterval = setInterval(() => {
progress += Math.random() * 15;
if (progress > 100) {
clearInterval(progressInterval);
progress = 100;
}
updateButtonStatus(button, `Downloading ${latestRelease.tag_name} (${Math.floor(progress)}%)`);
}, 500);
await ipcRenderer.invoke('install-version', {
url: asset.browser_download_url,
filename: asset.name
});
clearInterval(progressInterval);
updateButtonStatus(button, 'Running installer...');
await new Promise(resolve => setTimeout(resolve, 1500));
updateButtonStatus(button, 'Waiting for Pinokio to restart...');
const pinokioStatus = await waitForPinokio();
if (pinokioStatus.success) {
updateButtonStatus(button, 'Update completed successfully!');
button.classList.remove('loading');
await new Promise(resolve => setTimeout(resolve, 2000));
clearButtonStatus(button);
// Wait for status to clear before reloading
await new Promise(resolve => setTimeout(resolve, 300));
window.location.reload();
} else {
throw new Error(pinokioStatus.error);
}
} catch (error) {
updateButtonStatus(button, 'Update failed: ' + error.message);
button.classList.remove('loading');
setTimeout(() => {
clearButtonStatus(button);
}, 3000);
}
});
document.getElementById('experimentalUpdateBtn').addEventListener('click', async () => {
const button = document.getElementById('experimentalUpdateBtn');
try {
button.classList.add('loading');
updateButtonStatus(button, 'Checking experimental releases...');
const experimentalReleases = await ipcRenderer.invoke('get-experimental-releases');
const systemArch = await ipcRenderer.invoke('get-system-arch');
if (!experimentalReleases || experimentalReleases.length === 0) {
throw new Error('No experimental releases available');
}
const latestExperimental = experimentalReleases[0];
updateButtonStatus(button, `Found version ${latestExperimental.tag_name}`);
await new Promise(resolve => setTimeout(resolve, 1000));
const asset = latestExperimental.assets.find(a => a.name.includes(systemArch));
if (!asset) {
throw new Error('No compatible experimental version found');
}
let progress = 0;
const progressInterval = setInterval(() => {
progress += Math.random() * 15;
if (progress > 100) {
clearInterval(progressInterval);
progress = 100;
}
updateButtonStatus(button, `Downloading ${latestExperimental.tag_name} (${Math.floor(progress)}%)`);
}, 500);
await ipcRenderer.invoke('install-version', {
url: asset.browser_download_url,
filename: asset.name
});
clearInterval(progressInterval);
updateButtonStatus(button, 'Running installer...');
await new Promise(resolve => setTimeout(resolve, 1500));
updateButtonStatus(button, 'Waiting for Pinokio to restart...');
const pinokioStatus = await waitForPinokio();
if (pinokioStatus.success) {
updateButtonStatus(button, 'Experimental update completed!');
button.classList.remove('loading');
await new Promise(resolve => setTimeout(resolve, 2000));
clearButtonStatus(button);
// Wait for status to clear before reloading
await new Promise(resolve => setTimeout(resolve, 300));
window.location.reload();
} else {
throw new Error(pinokioStatus.error);
}
} catch (error) {
updateButtonStatus(button, 'Update failed: ' + error.message);
button.classList.remove('loading');
setTimeout(() => {
clearButtonStatus(button);
}, 3000);
}
});
// Variables for update functionality
let selectedVersion = null;
const installButton = document.getElementById('installButton');
const updatesList = document.getElementById('updatesList');
const checkUpdatesBtn = document.getElementById('checkUpdatesBtn');
// Format bytes to human readable size
function formatBytes(bytes, decimals = 2) {
if (bytes === 0) return '0 Bytes';
const k = 1024;
const dm = decimals < 0 ? 0 : decimals;
const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
}
// Format memory usage
function formatMemoryUsage(used, total) {
const percentage = ((used / total) * 100).toFixed(1);
return `${formatBytes(used)} / ${formatBytes(total)} (${percentage}%)`;
}
// App initialization
let appConfig = null;
async function initializeApp() {
try {
const config = await ipcRenderer.invoke('get-app-config');
appConfig = config;
if (!config.initialized) {
document.getElementById('initOverlay').classList.add('active');
}
} catch (error) {
console.error('Error loading app config:', error);
}
}
// Handle initialization form
document.getElementById('initializeApp').addEventListener('click', async () => {
const pinokioPath = document.getElementById('pinokioPath').value;
try {
const result = await ipcRenderer.invoke('initialize-app', {
pinokioPath
});
if (result.success) {
appConfig = result.config;
document.getElementById('initOverlay').classList.remove('active');
updateAllInfo();
} else {
alert('Failed to initialize: ' + result.error);
}
} catch (error) {
alert('Failed to initialize: ' + error.message);
}
});
document.getElementById('browsePinokioPath').addEventListener('click', async () => {
const result = await ipcRenderer.invoke('browse-directory');
if (result) {
document.getElementById('pinokioPath').value = result;
}
});
// Update system information without relying on Pinokio
async function updateSystemInfo() {
try {
// Get system info directly from OS
const sysInfo = await ipcRenderer.invoke('get-system-info');
await ipcRenderer.invoke('update-system-cache', sysInfo);
// Update basic information
document.getElementById('platform').textContent = sysInfo.platform;
document.getElementById('arch').textContent = sysInfo.arch;
// Try to get Pinokio-specific info
try {
const response = await fetch('http://localhost/pinokio/info');
const pinokioInfo = await response.json();
document.getElementById('pinokioVersion').textContent = pinokioInfo.version.pinokio;
document.getElementById('installPath').textContent = pinokioInfo.home;
// Cache the Pinokio info
await ipcRenderer.invoke('update-pinokio-cache', {
version: pinokioInfo.version.pinokio,
home: pinokioInfo.home
});
// Remove warning if it exists
const warningDiv = document.querySelector('.pinokio-warning');
if (warningDiv) {
warningDiv.remove();
}
} catch (error) {
// Get the cached values from config
const config = await ipcRenderer.invoke('get-app-config');
// Display cached values with indicator
document.getElementById('pinokioVersion').textContent =
`${config.cache.pinokioVersion || 'Not Available'} ${config.cache.pinokioVersion ? '(cached)' : ''}`;
document.getElementById('installPath').textContent =
`${config.pinokioPath} (cached)`;
// Show warning about Pinokio not running
showPinokioOfflineWarning();
}
// Update all hardware info
updateCPUInfo(sysInfo.cpu);
updateMemoryInfo(sysInfo.memory);
updateGPUInfo(sysInfo.graphics);
updateDisplayInfo(sysInfo.graphics);
} catch (error) {
console.error('Error updating system info:', error);
}
}
function showPinokioOfflineWarning() {
let warningDiv = document.querySelector('.pinokio-warning');
if (!warningDiv) {
warningDiv = document.createElement('div');
warningDiv.className = 'warning-box pinokio-warning';
document.querySelector('#overview .card').insertBefore(warningDiv, document.querySelector('#overview .info-grid'));
}
warningDiv.innerHTML = `
<h3>⚠️ Pinokio Not Running</h3>
<p>Some information may not be up to date because Pinokio is not running or the version installed doesn't support the API (3.2.200 or higher required).</p>
<p>You can:</p>
<ol>
<li>Launch Pinokio to get real-time information</li>
<li>Update to a supported version using the Experimental Update button</li>
<li>Continue using the app with potentially outdated information</li>
</ol>
<div class="action-group">
<button class="action-button" onclick="document.getElementById('launchPinokioBtn').click()">Launch Pinokio</button>
<button class="action-button" onclick="document.getElementById('experimentalUpdateBtn').click()">Update Pinokio</button>
</div>
`;
}
// Function to display cached storage values
async function displayCachedStorage() {
const storageInfo = document.getElementById('storageInfo');
const config = await ipcRenderer.invoke('get-app-config');
const cachedStorage = config.cache.lastStorageCalculation;
if (cachedStorage) {
let html = `
<div class="storage-overview">
<div class="info-item total-storage">
<div class="info-label">Total Storage Usage (cached)</div>
<div class="info-value">${formatBytes(cachedStorage.totalSize)} / ${formatBytes(cachedStorage.systemDriveSize.total)}
(${((cachedStorage.totalSize / cachedStorage.systemDriveSize.total) * 100).toFixed(1)}%)</div>
<div class="storage-bar">
<div class="storage-bar-fill" style="width: ${((cachedStorage.totalSize / cachedStorage.systemDriveSize.total) * 100)}%"></div>
</div>
<small>Last updated: ${new Date(cachedStorage.timestamp).toLocaleString()}</small>
</div>
</div>
<div class="storage-folders">
`;
// Add folder breakdown from cache
if (cachedStorage.folderSizes) {
cachedStorage.folderSizes.forEach(folder => {
html += `
<div class="folder-item">
<div class="folder-content">
<div class="folder-info">
<div class="folder-name">
<span class="folder-icon">${folder.icon}</span>
${folder.name}
</div>
<div class="folder-size">${formatBytes(folder.size)} (${folder.percentage}%)</div>
</div>
${folder.subDirs ? `
<button class="expand-button" data-folder="api">
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<polyline points="6 9 12 15 18 9"></polyline>
</svg>
</button>
` : ''}
</div>
${folder.subDirs ? `
<div class="apps-list" data-folder="api">
${folder.subDirs.map(subDir => `
<div class="app-item">
<div class="app-content">
<div class="app-info">
<div class="app-name">
<span class="folder-icon">📦</span>
${subDir.name}
</div>
<div class="app-size">${formatBytes(subDir.size)} (${subDir.percentage}%)</div>
</div>
</div>
</div>
`).join('')}
</div>
` : ''}
</div>
`;
});
}
html += `</div>`;
storageInfo.innerHTML = html;
// Add click handlers for expand buttons
document.querySelectorAll('[data-folder="api"].expand-button').forEach(btn => {
btn.onclick = () => {
const appsList = btn.closest('.folder-item').querySelector('.apps-list');
const isExpanded = appsList.classList.toggle('expanded');
btn.classList.toggle('expanded', isExpanded);
};
});
}
}
// Update the storage information section
async function updateStorageInfo(skipCachedDisplay = false) {
const storageInfo = document.getElementById('storageInfo');
const recalculateBtn = document.getElementById('recalculateStorage');
if (!appConfig?.initialized) {
showNotInitializedWarning(storageInfo);
return;
}
// Show cached values first if this isn't triggered by the recalculate button
if (!skipCachedDisplay) {
await displayCachedStorage();
}
try {
recalculateBtn.classList.add('loading');
recalculateBtn.disabled = true;
recalculateBtn.textContent = 'Calculating...';
let pinokioPath = appConfig.pinokioPath;
let usingCachedPath = true;
// Try to get updated path from Pinokio if running
try {
const response = await fetch('http://localhost/pinokio/info');
const data = await response.json();
pinokioPath = data.home;
usingCachedPath = false;
} catch (error) {
// Show warning that we're using saved path
showPinokioOfflineWarning();
}
// Get system drive info
const systemDriveSize = await ipcRenderer.invoke('get-drive-info', pinokioPath.split(':')[0]);
// Define base folders to check with icons
const folders = [
{ name: 'Cache', path: '\\cache', icon: '📁' },
{ name: 'Bin', path: '\\bin', icon: '🗑️' },
{ name: 'Drive', path: '\\drive', icon: '💾' },
{ name: 'API', path: '\\api', icon: '🔌' },
{ name: 'Logs', path: '\\logs', icon: '📝' }
];
// Get total size of Pinokio directory and individual folders
const pinokioSize = await ipcRenderer.invoke('get-directory-size', pinokioPath);
const usagePercentage = (pinokioSize / systemDriveSize.total) * 100;
// Calculate sizes for all folders
const folderSizes = await Promise.all(
folders.map(async folder => {
const folderPath = pinokioPath + folder.path;
const size = await ipcRenderer.invoke('get-directory-size', folderPath);
// If this is the API folder, get its subdirectories
if (folder.name === 'API') {
try {
const subDirs = await ipcRenderer.invoke('get-subdirectories', folderPath);
const subDirSizes = await Promise.all(
subDirs.map(async dir => {
const subDirSize = await ipcRenderer.invoke('get-directory-size', `${folderPath}\\${dir}`);
return {
name: dir,
size: subDirSize,
percentage: ((subDirSize / size) * 100).toFixed(1)
};
})
);
return { ...folder, size, percentage: ((size / pinokioSize) * 100).toFixed(1), subDirs: subDirSizes };
} catch (error) {
console.error('Error getting API subdirectories:', error);
return { ...folder, size, percentage: ((size / pinokioSize) * 100).toFixed(1), subDirs: [] };
}
}
return {
...folder,
size,
percentage: ((size / pinokioSize) * 100).toFixed(1)
};
})
);
// Cache the storage calculation results
await ipcRenderer.invoke('update-storage-cache', {
totalSize: pinokioSize,
systemDriveSize: systemDriveSize,
folderSizes,
timestamp: Date.now()
});
// Build the HTML
let html = `
<div class="storage-overview">
<div class="info-item total-storage">
<div class="info-label">Total Storage Usage ${usingCachedPath ? '(using cached path)' : ''}</div>
<div class="info-value">${formatBytes(pinokioSize)} / ${formatBytes(systemDriveSize.total)} (${usagePercentage.toFixed(1)}%)</div>
<div class="storage-bar">
<div class="storage-bar-fill" style="width: ${usagePercentage}%"></div>
</div>
</div>
</div>
<div class="storage-folders">
`;
// Add folder breakdown
folderSizes.forEach(folder => {
html += `
<div class="folder-item">
<div class="folder-content">
<div class="folder-info">
<div class="folder-name">
<span class="folder-icon">${folder.icon}</span>
${folder.name}
</div>
<div class="folder-size">${formatBytes(folder.size)} (${folder.percentage}%)</div>
</div>
${folder.subDirs ? `
<button class="expand-button" data-folder="api">
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<polyline points="6 9 12 15 18 9"></polyline>
</svg>
</button>
` : ''}
</div>
${folder.subDirs ? `
<div class="apps-list" data-folder="api">
${folder.subDirs.map(subDir => `
<div class="app-item">
<div class="app-content">
<div class="app-info">
<div class="app-name">
<span class="folder-icon">📦</span>
${subDir.name}
</div>
<div class="app-size">${formatBytes(subDir.size)} (${subDir.percentage}%)</div>
</div>
</div>
</div>
`).join('')}
</div>
` : ''}
</div>
`;
});
html += `
</div>
`;
storageInfo.innerHTML = html;
// Add click handlers for expand buttons
document.querySelectorAll('[data-folder="api"].expand-button').forEach(btn => {
btn.onclick = () => {
const appsList = btn.closest('.folder-item').querySelector('.apps-list');
const isExpanded = appsList.classList.toggle('expanded');
btn.classList.toggle('expanded', isExpanded);
};
});
// Remove any existing warning
const warningDiv = document.querySelector('#storage .warning-box');
if (warningDiv) {
warningDiv.remove();
}
} catch (error) {
console.error('Error updating storage info:', error);
if (!skipCachedDisplay) {
// Only show cached values if we haven't already
await displayCachedStorage();
}
let warningDiv = document.querySelector('#storage .warning-box');
if (!warningDiv) {
warningDiv = document.createElement('div');
warningDiv.className = 'warning-box';
document.querySelector('#storage .card').insertBefore(warningDiv, storageInfo);
}
if (error.message === 'Failed to fetch' || error.message.includes('ECONNREFUSED')) {
warningDiv.innerHTML = `
<h3>⚠️ Using Saved Path</h3>
<p>Calculating storage based on saved Pinokio path: ${appConfig.pinokioPath}</p>
<p>Note: This information might not be accurate if Pinokio's location has changed.</p>
`;
} else {
warningDiv.innerHTML = `
<h3>⚠️ Error Calculating Storage</h3>
<p>An error occurred while calculating storage usage:</p>
<div class="code-block">${error.message}</div>
`;
}
} finally {
recalculateBtn.classList.remove('loading');
recalculateBtn.disabled = false;
recalculateBtn.textContent = 'Recalculate';
}
}
function showNotInitializedWarning(container) {
const warningDiv = document.createElement('div');
warningDiv.className = 'warning-box not-initialized';
warningDiv.innerHTML = `
<h3>⚠️ App Not Initialized</h3>
<p>Please initialize the app with your Pinokio installation path to use this feature.</p>
<button class="action-button" onclick="document.getElementById('initOverlay').classList.add('active')">Initialize Now</button>
`;
container.parentElement.insertBefore(warningDiv, container);
container.innerHTML = `
<div class="info-item">
<div class="info-value">Initialize app to view storage information</div>
<div class="storage-bar">
<div class="storage-bar-fill" style="width: 0%"></div>
</div>
</div>
`;
}
// Function to update all information
async function updateAllInfo() {
await updateSystemInfo();
loadUpdates();
// Only show cached storage values, don't recalculate
await displayCachedStorage();
}
// Update memory information
function updateMemoryInfo() {
ipcRenderer.invoke('get-system-info')
.then(sysInfo => {
const memoryInfo = document.getElementById('memoryInfo');
const memUsage = formatMemoryUsage(sysInfo.memory.used, sysInfo.memory.total);
const memPercentage = (sysInfo.memory.used / sysInfo.memory.total) * 100;
memoryInfo.innerHTML = `
<div class="info-item">
<div class="info-label">Memory Usage</div>
<div class="info-value">${memUsage}</div>
<div class="storage-bar">
<div class="storage-bar-fill" style="width: ${memPercentage}%"></div>
</div>
</div>
`;
})
.catch(error => console.error('Error updating memory info:', error));
}
function updateCPUInfo(cpuInfo) {
const cpuInfoElement = document.getElementById('cpuInfo');
cpuInfoElement.innerHTML = `
<div class="info-item">
<div class="info-label">Processor</div>
<div class="info-value">${cpuInfo.brand}</div>
</div>
<div class="info-item">
<div class="info-label">Cores</div>
<div class="info-value">${cpuInfo.cores} (${cpuInfo.physicalCores} Physical)</div>
</div>
<div class="info-item">
<div class="info-label">Speed</div>
<div class="info-value">${cpuInfo.speed} GHz</div>
</div>
<div class="info-item">
<div class="info-label">Socket</div>
<div class="info-value">${cpuInfo.socket}</div>
</div>
`;
}
function updateGPUInfo(gpuInfo) {
const gpuInfoElement = document.getElementById('gpuInfo');
gpuInfoElement.innerHTML = gpuInfo.controllers.map(gpu => `
<div class="gpu-card">
<div class="gpu-icon">GPU</div>
<div>
<div class="version-tag">${gpu.model}</div>
<div class="version-type">VRAM: ${formatBytes(gpu.vram * 1024 * 1024)}</div>
</div>
</div>
`).join('');
}
function updateDisplayInfo(displayInfo) {
const displayInfoElement = document.getElementById('displayInfo');
displayInfoElement.innerHTML = displayInfo.displays.map(display => `
<div class="info-item">
<div class="info-label">${display.model}</div>
<div class="info-value">
${display.currentResX}x${display.currentResY} @ ${display.currentRefreshRate}Hz
${display.main ? '(Main Display)' : ''}
</div>
</div>
`).join('');
}
// Cache for version data
let versionCache = {
data: null,
lastUpdate: 0,
updateInterval: 60000 // 1 minute
};
async function loadUpdates(forceRefresh = false) {
try {
const now = Date.now();
const refreshButton = document.getElementById('refreshUpdates');
// Use cached data if available and not forcing refresh
if (!forceRefresh && versionCache.data && (now - versionCache.lastUpdate) < versionCache.updateInterval) {
updateUpdatesList(versionCache.data);
return;
}
if (refreshButton) {
refreshButton.classList.add('spinning');
}
const [currentVersion, latestRelease, experimentalReleases, systemArch] = await Promise.all([
ipcRenderer.invoke('get-current-version'),
ipcRenderer.invoke('get-latest-release'),
ipcRenderer.invoke('get-experimental-releases'),
ipcRenderer.invoke('get-system-arch')
]);
// Cache the results
versionCache.data = { currentVersion, latestRelease, experimentalReleases, systemArch };
versionCache.lastUpdate = now;
updateUpdatesList(versionCache.data);
} catch (error) {
console.error('Error loading updates:', error);
updatesList.innerHTML = `<div class="error">Error loading updates: ${error.message}</div>`;