-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathrenderer.js
More file actions
3455 lines (3241 loc) · 128 KB
/
renderer.js
File metadata and controls
3455 lines (3241 loc) · 128 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
// Lightbox ultra-légère pour images Markdown (initialisation après DOM prêt)
function initMarkdownLightbox() {
const mdLightbox = document.getElementById('mdLightbox');
const mdLightboxImg = document.getElementById('mdLightboxImg');
const detailsLong = document.getElementById('detailsLong');
if (mdLightbox && mdLightboxImg && detailsLong) {
detailsLong.addEventListener('click', e => {
const t = e.target;
if (t && t.tagName === 'IMG') {
mdLightboxImg.src = t.src;
mdLightbox.style.display = 'flex';
}
});
mdLightbox.addEventListener('click', () => {
mdLightbox.style.display = 'none';
mdLightboxImg.src = '';
});
}
}
const loadedIcons = new Set();
const scrollShell = document.querySelector('.scroll-shell');
const appConstants = window.constants || {};
const VISIBLE_COUNT = typeof appConstants.VISIBLE_COUNT === 'number' ? appConstants.VISIBLE_COUNT : 50;
const CATEGORY_ICON_MAP = appConstants.CATEGORY_ICON_MAP || {};
const appUtils = window.utils || {};
const appPreferences = window.preferences || {};
const AM_INSTALLER_COMMAND = 'wget -q https://raw.githubusercontent.com/ivan-hc/AM/main/AM-INSTALLER && chmod a+x ./AM-INSTALLER && ./AM-INSTALLER && rm ./AM-INSTALLER';
const PM_DOCS_URL = 'https://github.com/ivan-hc/AM#installation';
const getThemePref = typeof appPreferences.getThemePref === 'function'
? appPreferences.getThemePref
: () => {
try { return localStorage.getItem('themePref') || 'system'; }
catch (_) { return 'system'; }
};
const applyThemePreference = typeof appPreferences.applyThemePreference === 'function'
? appPreferences.applyThemePreference
: () => {
const pref = getThemePref();
const root = document.documentElement;
root.classList.remove('theme-light','theme-dark');
if (pref === 'light') root.classList.add('theme-light');
else if (pref === 'dark') root.classList.add('theme-dark');
};
const loadOpenExternalPref = typeof appPreferences.loadOpenExternalPref === 'function'
? appPreferences.loadOpenExternalPref
: () => {
try { return localStorage.getItem('openExternalLinks') === '1'; }
catch (_) { return false; }
};
const saveOpenExternalPref = typeof appPreferences.saveOpenExternalPref === 'function'
? appPreferences.saveOpenExternalPref
: (val) => {
try { localStorage.setItem('openExternalLinks', val ? '1' : '0'); }
catch (_) {}
};
const getIconUrl = typeof appUtils.getIconUrl === 'function'
? appUtils.getIconUrl
: (name) => `appicon://${name}.png`;
const debounce = typeof appUtils.debounce === 'function'
? appUtils.debounce
: (fn, delay) => {
let timer;
return (...args) => {
clearTimeout(timer);
timer = setTimeout(() => fn(...args), delay);
};
};
function getThemeVar(name, fallback) {
try {
const value = getComputedStyle(document.documentElement).getPropertyValue(name);
return value && value.trim() ? value.trim() : fallback;
} catch (_) {
return fallback;
}
}
function applyViewModeClass() {
document.body.classList.remove('view-list','view-grid','view-icons','view-cards');
if (state.viewMode === 'list') document.body.classList.add('view-list');
else if (state.viewMode === 'icons') document.body.classList.add('view-icons');
else if (state.viewMode === 'cards') document.body.classList.add('view-cards');
else document.body.classList.add('view-grid');
try { refreshAllSandboxBadges(); } catch (_) {}
}
let appListVirtual = [];
let currentEndVirtual = VISIBLE_COUNT;
let lastTileObserver = null;
let setAppListImpl = function(list) {
appListVirtual = list;
currentEndVirtual = VISIBLE_COUNT;
if (scrollShell) scrollShell.scrollTop = 0;
renderVirtualList();
};
function setAppList(list) {
return setAppListImpl(list);
}
function renderVirtualList() {
if (!appsDiv) return;
appsDiv.innerHTML = '';
const useSkeleton = appListVirtual.length > 50;
if (useSkeleton) {
const viewClass = 'view-' + (state.viewMode || 'grid');
const fragment = document.createDocumentFragment();
for (let i = 0; i < appListVirtual.length; i++) {
const skel = document.createElement('div');
skel.className = 'app-tile-skeleton ' + viewClass;
skel.dataset.index = i;
fragment.appendChild(skel);
}
appsDiv.appendChild(fragment);
if (window.skeletonObserver) window.skeletonObserver.disconnect();
window.skeletonObserver = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (!entry.isIntersecting) return;
if (entry.target.classList.contains('hydrated')) return;
const idx = parseInt(entry.target.dataset.index, 10);
if (Number.isNaN(idx)) return;
const realTile = buildTile(appListVirtual[idx]);
realTile.classList.add('hydrated');
entry.target.replaceWith(realTile);
try { window.skeletonObserver.observe(realTile); } catch (_) {}
});
}, { root: scrollShell, threshold: 0.1 });
const tiles = appsDiv.querySelectorAll('.app-tile-skeleton');
tiles.forEach(tile => window.skeletonObserver && window.skeletonObserver.observe(tile));
return;
}
const end = Math.min(currentEndVirtual, appListVirtual.length);
const fragment = document.createDocumentFragment();
for (let i = 0; i < end; i++) {
fragment.appendChild(buildTile(appListVirtual[i]));
}
appsDiv.appendChild(fragment);
if (lastTileObserver) lastTileObserver.disconnect();
if (end < appListVirtual.length) {
const tiles = appsDiv.querySelectorAll('.app-tile');
const toObserve = Array.from(tiles).slice(-3);
if (toObserve.length) {
try {
lastTileObserver = new IntersectionObserver((entries) => {
if (entries.some(e => e.isIntersecting)) {
lastTileObserver.disconnect();
currentEndVirtual = Math.min(currentEndVirtual + VISIBLE_COUNT, appListVirtual.length);
renderVirtualList();
}
}, { root: scrollShell, threshold: 0.1 });
toObserve.forEach(tile => lastTileObserver.observe(tile));
} catch(_) {}
}
}
// --- Spacer pour scroll cohérent ---
let spacer = appsDiv.querySelector('.app-list-spacer');
if (!spacer) {
spacer = document.createElement('div');
spacer.className = 'app-list-spacer';
spacer.style.width = '100%';
spacer.style.pointerEvents = 'none';
appsDiv.appendChild(spacer);
}
// Calculer la hauteur moyenne d'une tuile (sur le lot affiché)
let tileHeight = 120; // fallback par défaut
const firstTile = appsDiv.querySelector('.app-tile');
if (firstTile) {
tileHeight = firstTile.offsetHeight || tileHeight;
}
const missing = appListVirtual.length - end;
spacer.style.height = (missing > 0 ? (missing * tileHeight) : 0) + 'px';
// --- Fin spacer ---
}
// --- Intégration du prompt mot de passe sudo ---
if (window.electronAPI && window.electronAPI.onPasswordPrompt) {
window.electronAPI.onPasswordPrompt(async (data) => {
if (!window.ui || !window.ui.passwordPrompt || typeof window.ui.passwordPrompt.promptPassword !== 'function') return;
const password = await window.ui.passwordPrompt.promptPassword();
window.electronAPI.sendPassword({ id: data && data.id, password });
});
}
// ...existing code...
function createInstalledSection(sectionKey) {
const section = document.createElement('div');
section.className = 'installed-section';
const title = document.createElement('h4');
title.textContent = t(sectionKey === 'sandboxed' ? 'installed.section.sandboxed' : 'installed.section.others');
section.appendChild(title);
return section;
}
function buildTile(item){
if (item && item.__section) {
return createInstalledSection(item.__section);
}
const { name, installed, desc } = typeof item === 'string' ? { name: item, installed: false, desc: null } : item;
const label = name.charAt(0).toUpperCase() + name.slice(1);
const version = item?.version ? String(item.version) : null;
let shortDesc = desc || (installed ? 'Déjà présente localement.' : 'Disponible pour installation.');
if (shortDesc.length > 110) shortDesc = shortDesc.slice(0,107).trim() + '…';
let actionsHTML = '';
if (state.viewMode === 'list') {
if (!installed) {
let btnLabel = 'Installer';
let actionAttr = 'install';
let disabledAttr = '';
if (activeInstallSession.id && !activeInstallSession.done && activeInstallSession.name === name){
btnLabel = 'Installation… ✕';
actionAttr = 'cancel-install';
} else {
const pos = getQueuePosition(name);
if (pos !== -1) { btnLabel = 'En file (#'+pos+') ✕'; actionAttr='remove-queue'; }
}
actionsHTML = `<div class="actions"><button class="inline-action install" data-action="${actionAttr}" data-app="${name}"${disabledAttr}>${btnLabel}</button></div>`;
} else {
actionsHTML = `<div class="actions">`;
actionsHTML += `<button class="inline-action uninstall" data-action="uninstall" data-app="${name}">${t('details.uninstall')}</button>`;
actionsHTML += `</div>`;
}
}
let stateBadge = '';
if (state.viewMode !== 'list' && !installed) {
if (activeInstallSession.id && !activeInstallSession.done && activeInstallSession.name === name) {
stateBadge = ' <span class="install-state-badge installing" data-state="installing">Installation…<button class="queue-remove-badge inline-action" data-action="cancel-install" data-app="'+name+'" title="Annuler" aria-label="Annuler">✕</button></span>';
} else {
const pos = getQueuePosition(name);
if (pos !== -1) stateBadge = ' <span class="install-state-badge queued" data-state="queued">En file (#'+pos+')<button class="queue-remove-badge inline-action" data-action="remove-queue" data-app="'+name+'" title="Retirer de la file" aria-label="Retirer">✕</button></span>';
}
}
const tile = document.createElement('div');
tile.className = 'app-tile';
tile.setAttribute('data-app', name);
const isSandboxedTile = installed && isAppSandboxed(name);
const badgeSymbol = isSandboxedTile ? '🔒' : '✓';
const badgeHTML = installed
? `<span class="installed-badge" aria-label="Installée" title="Installée" style="position:absolute;top:2px;right:2px;">${badgeSymbol}</span>`
: '';
tile.innerHTML = `
<div class="tile-icon" style="position:relative;display:inline-block;">
<img data-src="${getIconUrl(name)}" alt="${label}" loading="lazy" decoding="async"${state.viewMode==='icons' ? ' class="icon-mode"' : ''} onerror="this.onerror=null; this.src='https://raw.githubusercontent.com/Portable-Linux-Apps/Portable-Linux-Apps.github.io/main/icons/${name}.png'; setTimeout(()=>{ if(this.naturalWidth<=1) this.src='https://raw.githubusercontent.com/Portable-Linux-Apps/Portable-Linux-Apps.github.io/main/icons/blank.png'; },1200);">
${badgeHTML}
</div>
<div class="tile-text">
<div class="tile-name">${label}${version? ` <span class\"tile-version\">${version}</span>`: ''}${stateBadge}</div>
<div class="tile-short">${shortDesc}</div>
</div>
${actionsHTML ? actionsHTML : ''}`;
applySandboxBadgeToIcon(tile.querySelector('.tile-icon'), isAppSandboxed(name));
const img = tile.querySelector('img');
if (img) {
const iconUrl = img.getAttribute('data-src');
if (iconUrl && loadedIcons.has(iconUrl)) {
img.src = iconUrl;
img.removeAttribute('data-src');
} else if (iconUrl) {
img.classList.add('img-loading');
img.addEventListener('load', () => {
img.classList.remove('img-loading');
loadedIcons.add(iconUrl);
}, { once:true });
img.addEventListener('error', () => { img.classList.remove('img-loading'); }, { once:true });
if (iconObserver) iconObserver.observe(img); else { img.src = iconUrl; img.removeAttribute('data-src'); }
if (buildTile._count === undefined) buildTile._count = 0;
if (buildTile._count < 48) {
try { img.setAttribute('fetchpriority','high'); } catch(_){ }
}
buildTile._count++;
}
}
tile.tabIndex = 0; // navigation clavier
tile.addEventListener('click', (ev) => {
if (ev.target.closest('.inline-action')) return; // ne pas ouvrir si clic sur bouton d'action
showDetails(name);
});
tile.addEventListener('keydown', (ev) => {
if (ev.key === 'Enter' || ev.key === ' ') {
if (ev.target.closest('.inline-action')) return;
ev.preventDefault();
showDetails(name);
}
});
return tile;
}
// ...existing code...
// Active/désactive les animations globales selon l'état
function setAnimationsActive(active) {
document.body.classList.toggle('animations-active', !!active);
}
// Désactiver les animations au démarrage
setAnimationsActive(false);
// Animations globales
// ...existing code...
function initXtermLog() {
if (!xtermLogDiv) xtermLogDiv = document.getElementById('xtermLog');
if (!xtermLogDiv) return;
if (!xterm) {
try {
const { Terminal } = require('@xterm/xterm');
const { FitAddon } = require('@xterm/addon-fit');
xterm = new Terminal({
fontSize: 13,
fontFamily: 'monospace',
theme: { background: '#181c20' },
convertEol: true,
scrollback: 2000,
disableStdin: true,
cursorBlink: false
});
xtermFit = new FitAddon();
xterm.loadAddon(xtermFit);
xterm.open(xtermLogDiv);
window.addEventListener('resize', ()=>xtermFit.fit());
xtermFit.fit();
} catch (_err) {
xterm = null;
xtermFit = null;
if (xtermLogDiv) xtermLogDiv.style.display = 'none';
if (installStreamLog) installStreamLog.style.display = '';
return;
}
} else {
xterm.clear();
xtermFit && xtermFit.fit();
}
xtermLogDiv.style.display = '';
if (installStreamLog) installStreamLog.style.display = 'none';
}
// --- xterm.js pour affichage terminal natif ---
let xterm = null;
let xtermFit = null;
let xtermLogDiv = null;
// Contrôles fenêtre
document.addEventListener('click', (e) => {
const b = e.target.closest('.win-btn');
if (!b) return;
const act = b.getAttribute('data-action');
if (!act) return;
try { window.electronAPI.windowControl(act); } catch(_) {}
});
// Classe d'environnement de bureau
(() => {
try {
const de = (window.electronAPI?.desktopEnv && window.electronAPI.desktopEnv()) || 'generic';
document.documentElement.classList.add('de-' + de);
} catch(_) {}
})();
const modeMenuBtn = document.getElementById('modeMenuBtn');
const modeMenu = document.getElementById('modeMenu');
const modeOptions = () => Array.from(document.querySelectorAll('.mode-option'));
const disableGpuCheckbox = document.getElementById('disableGpuCheckbox');
const state = {
allApps: [], // [{name, installed}]
filtered: [],
activeCategory: 'all',
viewMode: localStorage.getItem('viewMode') || 'grid',
lastRenderKey: '',
currentDetailsApp: null,
renderVersion: 0,
lastScrollY: 0,
installed: new Set() // ensemble des noms installés (lowercase)
};
let virtualListApi = null;
let pmPopupCtrl = null;
let pmPopupStatus = null;
let pmAutoInstallRunning = false;
const toast = document.getElementById('toast');
const toastFallbackApi = (() => {
let hideTimer = null;
function fallbackShow(message) {
if (!toast) return;
toast.textContent = message;
toast.hidden = false;
if (hideTimer) clearTimeout(hideTimer);
hideTimer = setTimeout(() => {
toast.hidden = true;
hideTimer = null;
}, 2300);
}
function fallbackHide() {
if (!toast) return;
toast.hidden = true;
if (hideTimer) {
clearTimeout(hideTimer);
hideTimer = null;
}
}
return { showToast: fallbackShow, hideToast: fallbackHide };
})();
const toastModule = typeof window.ui?.toast?.init === 'function'
? window.ui.toast.init({ element: toast, duration: 2300 })
: null;
const showToast = toastModule?.showToast || toastFallbackApi.showToast;
const defaultApplySearch = () => {};
let applySearch = defaultApplySearch;
let scheduledInstalledResort = null;
function scheduleInstalledResort() {
if (state.activeCategory !== 'installed') return;
if (scheduledInstalledResort !== null) return;
scheduledInstalledResort = setTimeout(() => {
scheduledInstalledResort = null;
if (state.activeCategory !== 'installed') return;
try {
applySearch();
} catch (_) {}
}, 150);
}
// --- (Ré)ajout gestion changement de mode d'affichage ---
function updateModeMenuUI() {
// Mettre à jour états pressed
modeOptions().forEach(opt => {
const m = opt.getAttribute('data-mode');
const active = m === state.viewMode;
opt.setAttribute('aria-pressed', active ? 'true' : 'false');
});
// Changer l'icône du bouton principal selon mode
const iconMap = { grid:'▦', list:'≣', icons:'◻︎', cards:'🂠' };
if (modeMenuBtn) modeMenuBtn.textContent = iconMap[state.viewMode] || '▦';
// Mettre à jour la classe du body selon le mode
applyViewModeClass();
}
if (modeMenuBtn && modeMenu) {
modeMenuBtn.addEventListener('click', (e) => {
e.stopPropagation();
const open = !modeMenu.hidden;
if (open) {
modeMenu.hidden = true;
modeMenuBtn.setAttribute('aria-expanded','false');
} else {
updateModeMenuUI();
modeMenu.hidden = false;
modeMenuBtn.setAttribute('aria-expanded','true');
}
});
document.addEventListener('click', (ev) => {
if (modeMenu.hidden) return;
if (ev.target === modeMenu || modeMenu.contains(ev.target) || ev.target === modeMenuBtn) return;
modeMenu.hidden = true;
modeMenuBtn.setAttribute('aria-expanded','false');
});
// Ajout : gestion du clic sur les options de mode d'affichage
modeOptions().forEach(opt => {
opt.addEventListener('click', (e) => {
const mode = opt.getAttribute('data-mode');
if (!mode) return;
state.viewMode = mode;
localStorage.setItem('viewMode', mode);
updateModeMenuUI();
modeMenu.hidden = true;
modeMenuBtn.setAttribute('aria-expanded','false');
});
});
}
function startUpdateTimer() {
const timer = document.querySelector('.update-timer');
if (!timer) return;
// Ne pas réinitialiser si déjà en cours
if (updateTimerStart === null) updateTimerStart = Date.now();
if (updateTimerInterval) return;
const updateTimerText = () => {
const elapsed = Math.max(0, Math.floor((Date.now() - updateTimerStart) / 1000));
if (elapsed < 60) {
timer.textContent = `${elapsed}s`;
} else {
const min = Math.floor(elapsed / 60);
const sec = String(elapsed % 60).padStart(2, '0');
timer.textContent = `${min}:${sec}`;
}
};
updateTimerText();
updateTimerInterval = setInterval(updateTimerText, 1000);
}
function stopUpdateTimer() {
if (updateTimerInterval) clearInterval(updateTimerInterval);
updateTimerInterval = null;
updateTimerStart = null;
}
updateModeMenuUI();
const appsDiv = document.getElementById('apps');
// --- Références DOM rétablies après nettoyage catégories ---
const appDetailsSection = document.getElementById('appDetails');
const backToListBtn = document.getElementById('backToListBtn');
const detailsIcon = document.getElementById('detailsIcon');
const detailsName = document.getElementById('detailsName');
const detailsLong = document.getElementById('detailsLong');
const detailsInstallBtn = document.getElementById('detailsInstallBtn');
const detailsUninstallBtn = document.getElementById('detailsUninstallBtn');
const detailsGallery = document.getElementById('detailsGallery');
const detailsGalleryInner = document.getElementById('detailsGalleryInner');
// Éléments streaming installation
// Galerie supprimée : toutes les images sont dans la description
const installStream = document.getElementById('installStream');
const installStreamStatus = document.getElementById('installStreamStatus');
const installStreamElapsed = document.getElementById('installStreamElapsed');
// Log, compteur de lignes et bouton log supprimés de l'UI
const installProgressBar = document.getElementById('installStreamProgressBar');
const installProgressPercentLabel = document.getElementById('installStreamProgressPercent');
const installProgressEtaLabel = document.getElementById('installStreamEta');
const sandboxOpenBtn = document.getElementById('sandboxOpenBtn');
const sandboxButtonStatus = document.getElementById('sandboxButtonStatus');
const sandboxModal = document.getElementById('sandboxModal');
const sandboxCloseBtn = document.getElementById('sandboxCloseBtn');
const sandboxCard = document.getElementById('sandboxCard');
const sandboxStatusBadge = document.getElementById('sandboxStatusBadge');
const sandboxRefreshBtn = document.getElementById('sandboxRefreshBtn');
const sandboxConfigureBtn = document.getElementById('sandboxConfigureBtn');
const sandboxDisableBtn = document.getElementById('sandboxDisableBtn');
const sandboxDepsAlert = document.getElementById('sandboxDepsAlert');
const sandboxInstallDepsBtn = document.getElementById('sandboxInstallDepsBtn');
const sandboxUnavailable = document.getElementById('sandboxUnavailable');
const sandboxInstallAppBtn = document.getElementById('sandboxInstallAppBtn');
const sandboxForm = document.getElementById('sandboxForm');
const sandboxCustomPathInput = document.getElementById('sandboxCustomPath');
const sandboxLog = document.getElementById('sandboxLog');
const sandboxSummary = document.getElementById('sandboxSummary');
const sandboxSummaryList = document.getElementById('sandboxSummaryList');
const sandboxSummaryEmpty = document.getElementById('sandboxSummaryEmpty');
const sandboxLogSection = document.getElementById('sandboxLogSection');
const sandboxLogToggle = document.getElementById('sandboxLogToggle');
const nonAppimageModal = document.getElementById('nonAppimageModal');
const nonAppimageCloseBtn = document.getElementById('nonAppimageClose');
const nonAppimageDismissBtn = document.getElementById('nonAppimageDismiss');
const nonAppimageMessage = document.getElementById('nonAppimageMessage');
const SANDBOX_DIR_VALUES = ['desktop','documents','downloads','games','music','pictures','videos'];
const SANDBOX_DIR_LABEL_KEYS = {
desktop: 'sandbox.dir.desktop',
documents: 'sandbox.dir.documents',
downloads: 'sandbox.dir.downloads',
games: 'sandbox.dir.games',
music: 'sandbox.dir.music',
pictures: 'sandbox.dir.pictures',
videos: 'sandbox.dir.videos'
};
const SANDBOX_PREFS_KEY = 'sandboxSharePrefs';
let sandboxSharePrefs = loadSandboxSharePrefs();
const sandboxedApps = new Map();
let sandboxSweepToken = 0;
const sandboxState = {
currentApp: null,
info: null,
depsReady: false,
busy: false,
pendingAction: null,
logBuffer: '',
supported: true
};
renderSandboxCard();
// Mémoire de la session d'installation en cours
let activeInstallSession = {
id: null,
name: null,
start: 0,
lines: [], // tableau de chaînes
done: false,
success: null,
code: null
};
// File d'attente séquentielle
const installQueue = []; // noms d'apps en attente (FIFO)
let detailsApi = null;
function ensureDetailsApi() {
if (detailsApi) return detailsApi;
const initFn = window.features?.details?.init;
if (typeof initFn !== 'function') return null;
detailsApi = initFn({
state,
activeInstallSession,
getIconUrl,
showToast,
translate: t,
enqueueInstall,
removeFromQueue,
refreshAllInstallButtons,
setAppList,
loadApps,
openActionConfirm,
rerenderActiveCategory,
scrollShell,
appsContainer: appsDiv,
getActiveInstallSession: () => activeInstallSession,
applyDetailsSandboxBadge,
elements: {
appDetailsSection,
backToListBtn,
detailsIcon,
detailsName,
detailsLong,
detailsInstallBtn,
detailsUninstallBtn,
installStream,
installStreamElapsed,
installProgressBar,
installProgressPercentLabel,
installProgressEtaLabel
}
}) || null;
return detailsApi;
}
function resetSandboxLog() {
if (!sandboxLog) return;
sandboxState.logBuffer = '';
sandboxLog.textContent = t('sandbox.logEmpty') || '…';
}
function appendSandboxLog(chunk) {
if (!sandboxLog || typeof chunk !== 'string') return;
sandboxState.logBuffer += chunk;
const sanitized = stripAnsiSequences(sandboxState.logBuffer || '');
const text = sanitized.trim() || t('sandbox.logEmpty') || '…';
sandboxLog.textContent = text;
sandboxLog.scrollTop = sandboxLog.scrollHeight;
}
function isSandboxLogExpanded() {
return !!(sandboxLog && !sandboxLog.hidden);
}
function setSandboxLogExpanded(expanded) {
if (!sandboxLog || !sandboxLogToggle) return;
const next = !!expanded;
sandboxLog.hidden = !next;
sandboxLogToggle.setAttribute('aria-expanded', String(next));
if (sandboxLogSection) {
sandboxLogSection.dataset.open = next ? 'true' : 'false';
}
}
setSandboxLogExpanded(false);
function inferAppImageFromInfo(appName, info) {
if (!info) return null;
// isAppImage est définitif quand c'est un boolean (détecté via magic bytes ou sandboxé)
if (typeof info.isAppImage === 'boolean') return info.isAppImage;
const target = typeof info.appName === 'string' ? info.appName.toLowerCase() : '';
if (target && appName && target !== appName.toLowerCase()) return null;
const execPath = typeof info.execPath === 'string' ? info.execPath.toLowerCase() : '';
if (!execPath) return null;
// Fallback sur l'extension si pas de détection magic bytes
return execPath.endsWith('.appimage');
}
function isSandboxSupported(appName, info = sandboxState.info) {
if (!appName) return false;
// Si on n'a pas encore d'info (chargement en cours), on ne sait pas encore
if (!info || Object.keys(info).length === 0) return true;
const inferred = inferAppImageFromInfo(appName, info);
// Vérifier si l'app est installée via appman (pas juste si un exécutable existe)
const installedViaAppman = isAppInstalledInList(appName);
// Si l'app N'EST PAS installée via appman, on ne bloque pas
// (un exécutable système du même nom ne devrait pas bloquer le sandboxing futur)
if (!installedViaAppman) return true;
// Si on a une détection définitive et l'app est installée via appman, on l'utilise
if (inferred !== null) return inferred;
// App installée via appman mais pas de détection possible → probablement pas un AppImage
return false;
}
function isAppInstalledInList(appName) {
if (!appName) return false;
const lower = appName.toLowerCase();
if (state?.installed instanceof Set && state.installed.has(lower)) return true;
if (!Array.isArray(state?.allApps)) return false;
const entry = state.allApps.find((app) => app && typeof app.name === 'string' && app.name.toLowerCase() === lower);
return !!entry?.installed;
}
function openSandboxModal() {
if (!sandboxModal || !sandboxState.currentApp) return;
sandboxModal.hidden = false;
}
function closeSandboxModal() {
if (!sandboxModal || sandboxModal.hidden) return;
sandboxModal.hidden = true;
}
function showNonAppimageModal(appName) {
if (!nonAppimageModal) return;
if (nonAppimageMessage) {
nonAppimageMessage.textContent = t('sandbox.unsupported.desc', { name: appName || '—' });
}
nonAppimageModal.hidden = false;
setTimeout(() => {
try { nonAppimageDismissBtn?.focus(); }
catch (_) {}
}, 30);
}
function closeNonAppimageModal() {
if (!nonAppimageModal || nonAppimageModal.hidden) return;
nonAppimageModal.hidden = true;
}
function setSandboxBusy(flag) {
sandboxState.busy = !!flag;
renderSandboxCard();
}
function updateSandboxActionStyles(isSandboxed) {
if (!sandboxConfigureBtn || !sandboxDisableBtn) return;
if (isSandboxed) {
sandboxConfigureBtn.classList.remove('btn-primary');
sandboxConfigureBtn.classList.add('btn-outline');
sandboxDisableBtn.classList.add('btn-primary');
sandboxDisableBtn.classList.remove('btn-outline');
} else {
sandboxConfigureBtn.classList.add('btn-primary');
sandboxConfigureBtn.classList.remove('btn-outline');
sandboxDisableBtn.classList.remove('btn-primary');
sandboxDisableBtn.classList.add('btn-outline');
}
}
function renderSandboxCard() {
if (!sandboxCard) return;
if (!sandboxState.currentApp) {
sandboxCard.hidden = true;
if (sandboxOpenBtn) sandboxOpenBtn.disabled = true;
if (sandboxButtonStatus) {
sandboxButtonStatus.dataset.status = 'unknown';
sandboxButtonStatus.textContent = '—';
}
return;
}
sandboxCard.hidden = false;
if (sandboxOpenBtn) {
sandboxOpenBtn.disabled = false;
}
const info = sandboxState.info || {};
const installedFromInfo = typeof info.installed === 'boolean' ? info.installed : null;
const installedFromList = isAppInstalledInList(sandboxState.currentApp);
const installedFromDetailsBtn = detailsInstallBtn ? detailsInstallBtn.hidden : null;
const installedFlag = (installedFromInfo === true)
? true
: (installedFromInfo === false)
? false
: (installedFromList || installedFromDetailsBtn === true);
const sandboxEligible = isSandboxSupported(sandboxState.currentApp, info);
sandboxState.supported = sandboxEligible;
if (sandboxOpenBtn) {
const titleKey = sandboxEligible ? 'sandbox.title' : 'sandbox.unsupported.title';
sandboxOpenBtn.title = t(titleKey);
}
const statusKey = sandboxState.busy
? 'busy'
: (!sandboxEligible
? 'unsupported'
: (info.sandboxed ? 'active' : (installedFlag ? 'inactive' : 'unknown')));
const statusLabel = t(`sandbox.status.${statusKey}`) || statusKey;
if (sandboxStatusBadge) {
sandboxStatusBadge.dataset.status = statusKey;
sandboxStatusBadge.textContent = statusLabel;
}
if (sandboxButtonStatus) {
sandboxButtonStatus.dataset.status = statusKey;
sandboxButtonStatus.textContent = statusLabel;
}
if (sandboxUnavailable) sandboxUnavailable.hidden = !!installedFlag;
if (sandboxInstallAppBtn) {
sandboxInstallAppBtn.disabled = sandboxState.busy || installedFlag;
sandboxInstallAppBtn.hidden = installedFlag;
}
if (sandboxDepsAlert) sandboxDepsAlert.hidden = sandboxState.depsReady || !sandboxEligible;
const isSandboxed = !!info.sandboxed;
if (sandboxInstallDepsBtn) sandboxInstallDepsBtn.disabled = sandboxState.busy || !sandboxEligible;
if (sandboxConfigureBtn) sandboxConfigureBtn.disabled = sandboxState.busy || !info.installed || !sandboxState.depsReady || isSandboxed || !sandboxEligible;
if (sandboxDisableBtn) sandboxDisableBtn.disabled = sandboxState.busy || !isSandboxed || !sandboxEligible;
if (sandboxRefreshBtn) sandboxRefreshBtn.disabled = sandboxState.busy;
updateSandboxActionStyles(isSandboxed);
renderSandboxSummary();
}
async function refreshSandboxInfo(appName = sandboxState.currentApp) {
if (!sandboxCard) return;
if (!appName) {
sandboxState.info = null;
sandboxCard.hidden = true;
return;
}
sandboxState.currentApp = appName;
sandboxCard.hidden = false;
setSandboxBusy(true);
try {
const response = await window.electronAPI.getSandboxInfo(appName);
const info = response?.info || { installed: false, sandboxed: false };
const depsFromInfo = typeof info?.dependenciesReady === 'boolean' ? info.dependenciesReady : null;
const depsFromResponse = !!(response?.dependencies && (response.dependencies.hasSas || response.dependencies.hasAisap));
const depsFlag = depsFromInfo !== null ? depsFromInfo : depsFromResponse;
const listInstalled = isAppInstalledInList(appName);
if (!info.installed && listInstalled) info.installed = true;
info.dependenciesReady = depsFlag;
sandboxState.info = info;
sandboxState.depsReady = !!depsFlag;
setAppSandboxState(appName, !!info.sandboxed);
renderSandboxCard();
} catch (error) {
appendSandboxLog(`\n${error?.message || 'IPC error'}\n`);
} finally {
setSandboxBusy(false);
}
}
function collectSandboxFormValues() {
const shareDirs = {};
let hasSelection = false;
if (sandboxForm) {
SANDBOX_DIR_VALUES.forEach((dir) => {
const input = sandboxForm.querySelector(`input[value="${dir}"]`);
const checked = !!(input && input.checked);
shareDirs[dir] = checked;
if (checked) hasSelection = true;
});
}
const customPath = (sandboxCustomPathInput?.value || '').trim();
const configureDirs = hasSelection || !!customPath;
return { shareDirs, customPath, configureDirs };
}
function loadSandboxSharePrefs() {
try {
const raw = localStorage.getItem(SANDBOX_PREFS_KEY);
if (!raw) return {};
const parsed = JSON.parse(raw);
return parsed && typeof parsed === 'object' ? parsed : {};
} catch (_) {
return {};
}
}
function persistSandboxSharePrefs() {
try {
localStorage.setItem(SANDBOX_PREFS_KEY, JSON.stringify(sandboxSharePrefs));
} catch (_) {}
}
function getSandboxSharePrefs(appName) {
if (!appName) return null;
const key = appName.toLowerCase();
return sandboxSharePrefs[key] || null;
}
function rememberSandboxSharePrefs(appName, data) {
if (!appName || !data) return;
const key = appName.toLowerCase();
const nextPrefs = { shareDirs: {}, customPath: data.customPath || '' };
SANDBOX_DIR_VALUES.forEach((dir) => {
nextPrefs.shareDirs[dir] = !!data.shareDirs?.[dir];
});
sandboxSharePrefs[key] = nextPrefs;
persistSandboxSharePrefs();
}
function applySandboxPrefsToForm(appName) {
if (!sandboxForm) return;
const prefs = getSandboxSharePrefs(appName);
SANDBOX_DIR_VALUES.forEach((dir) => {
const input = sandboxForm.querySelector(`input[value="${dir}"]`);
if (input) input.checked = !!(prefs?.shareDirs?.[dir]);
});
if (sandboxCustomPathInput) sandboxCustomPathInput.value = prefs?.customPath || '';
}
function getSandboxSummaryEntries(prefs) {
if (!prefs || typeof prefs !== 'object') return [];
const entries = [];
SANDBOX_DIR_VALUES.forEach((dir) => {
if (prefs.shareDirs && prefs.shareDirs[dir]) entries.push({ type: 'dir', value: dir });
});
if (prefs.customPath) entries.push({ type: 'custom', value: prefs.customPath });
return entries;
}
function renderSandboxSummary() {
if (!sandboxSummary) return;
const hasApp = !!sandboxState.currentApp;
const isSandboxed = !!(sandboxState.info && sandboxState.info.sandboxed);
const prefs = getSandboxSharePrefs(sandboxState.currentApp);
const entries = getSandboxSummaryEntries(prefs);
const shouldShow = hasApp && isSandboxed;
sandboxSummary.hidden = !shouldShow;
if (!sandboxSummaryList) return;
if (!shouldShow) {
sandboxSummaryList.innerHTML = '';
sandboxSummaryList.hidden = true;
if (sandboxSummaryEmpty) sandboxSummaryEmpty.hidden = false;
return;
}
sandboxSummaryList.innerHTML = '';
if (!entries.length) {
sandboxSummaryList.hidden = true;
if (sandboxSummaryEmpty) sandboxSummaryEmpty.hidden = false;
return;
}
const fragment = document.createDocumentFragment();
entries.forEach((entry) => {
const li = document.createElement('li');
li.className = 'sandbox-summary-item';
if (entry.type === 'dir') {
li.textContent = t(SANDBOX_DIR_LABEL_KEYS[entry.value]) || entry.value;
} else if (entry.type === 'custom') {
const label = document.createElement('span');
label.className = 'sandbox-summary-label';
label.textContent = t('sandbox.summary.custom');
const path = document.createElement('code');
path.className = 'sandbox-summary-path';
path.textContent = entry.value;
li.append(label, path);
}
fragment.appendChild(li);
});
sandboxSummaryList.hidden = false;
sandboxSummaryList.appendChild(fragment);
if (sandboxSummaryEmpty) sandboxSummaryEmpty.hidden = true;
}
function isAppSandboxed(appName) {
if (!appName) return false;
return sandboxedApps.get(appName.toLowerCase()) === true;
}
function setAppSandboxState(appName, active) {
if (!appName) return;
const key = appName.toLowerCase();
const nextState = !!active;
const prevState = sandboxedApps.has(key);
if (nextState === prevState) {
return;
}
if (nextState) sandboxedApps.set(key, true);
else sandboxedApps.delete(key);
refreshSandboxBadgesForApp(appName);
scheduleInstalledResort();
}
function cleanupSandboxCache() {
if (!sandboxedApps.size || !(state.installed instanceof Set)) return;
sandboxedApps.forEach((_, key) => {
if (!state.installed.has(key)) sandboxedApps.delete(key);
});
}
function applySandboxBadgeToIcon(iconWrapper, isActive) {
if (!iconWrapper) return;
const badge = iconWrapper.querySelector('.installed-badge');
if (!badge) return;
const label = isActive ? t('sandbox.status.active') : 'Installée';
const symbol = isActive ? '🔒' : '✓';
badge.textContent = symbol;
badge.setAttribute('aria-label', label);
badge.title = label;
}
function refreshSandboxBadgesForApp(appName) {
if (!appName) return;
const lower = appName.toLowerCase();
const active = isAppSandboxed(appName);
document.querySelectorAll('.app-tile').forEach(tile => {
const tileName = (tile.getAttribute('data-app') || '').toLowerCase();
if (tileName !== lower) return;
const iconWrapper = tile.querySelector('.tile-icon');
applySandboxBadgeToIcon(iconWrapper, active);