-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.js
More file actions
executable file
·1149 lines (1085 loc) · 42.4 KB
/
main.js
File metadata and controls
executable file
·1149 lines (1085 loc) · 42.4 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
// Fixe les variables d'environnement terminal si absentes (utile pour AppImage)
if (!process.env.TERM) process.env.TERM = 'xterm-256color';
if (!process.env.COLORTERM) process.env.COLORTERM = 'truecolor';
// Ajoute XDG_BIN_HOME au PATH si absent
const xdgBinHome = process.env.XDG_BIN_HOME || (process.env.HOME ? `${process.env.HOME}/.local/bin` : null);
if (xdgBinHome && !process.env.PATH.split(':').includes(xdgBinHome)) {
process.env.PATH = `${process.env.PATH}:${xdgBinHome}`;
}
const { app, BrowserWindow, ipcMain, Menu, protocol, shell } = require('electron');
const path = require('path');
const fs = require('fs');
const os = require('os');
const { exec, spawn } = require('child_process');
const { registerCategoryHandlers } = require('./src/main/categories');
const { initTray, destroyTray } = require('./src/main/tray');
const { detectPackageManager, invalidatePackageManagerCache } = require('./src/main/packageManager');
const { createIconCacheManager } = require('./src/main/iconCache');
const { installAppManAuto } = require('./src/main/appManAuto');
const fsp = fs.promises;
const SANDBOX_DIR_KEYS = ['desktop', 'documents', 'downloads', 'games', 'music', 'pictures', 'videos'];
const SANDBOX_MARKER = 'aisap-am sandboxing script';
const iconCacheManager = createIconCacheManager(app);
registerCategoryHandlers(ipcMain);
// --- Single instance lock ---
const gotTheLock = app.requestSingleInstanceLock();
if (!gotTheLock) {
app.quit();
process.exit(0);
} else {
app.on('second-instance', (event, commandLine, workingDirectory) => {
// Quelqu'un a essayé de lancer une deuxième instance, on focus la fenêtre existante
if (mainWindow) {
if (mainWindow.isMinimized()) mainWindow.restore();
mainWindow.show();
mainWindow.focus();
// Forcer au premier plan temporairement
mainWindow.setAlwaysOnTop(true);
setTimeout(() => {
if (mainWindow) mainWindow.setAlwaysOnTop(false);
}, 100);
}
});
}
// --- Gestion accélération GPU (doit être AVANT app.whenReady) ---
// Vérifier d'abord les arguments de ligne de commande
const hasDisableGpuFlag = process.argv.includes('--disable-gpu');
let disableGpuPref = false;
try {
const prefPath = path.join(app.getPath('userData'), 'gpu-pref.json');
console.log('[GPU DEBUG] Checking GPU pref file at:', prefPath);
if (fs.existsSync(prefPath)) {
const raw = fs.readFileSync(prefPath, 'utf8');
console.log('[GPU DEBUG] File content:', raw);
disableGpuPref = JSON.parse(raw).disableGpu === true;
console.log('[GPU DEBUG] disableGpuPref parsed to:', disableGpuPref);
} else {
console.log('[GPU DEBUG] File does not exist');
}
} catch(e){
console.log('[GPU DEBUG] Error reading GPU pref:', e);
}
// Désactiver GPU si demandé par flag CLI ou par préférence
const shouldDisableGpu = hasDisableGpuFlag || disableGpuPref;
if (shouldDisableGpu && typeof app.disableHardwareAcceleration === 'function') {
console.log('[GPU DEBUG] Calling app.disableHardwareAcceleration() - reason:', hasDisableGpuFlag ? 'CLI flag' : 'user preference');
app.disableHardwareAcceleration();
} else {
console.log('[GPU DEBUG] NOT calling app.disableHardwareAcceleration(), shouldDisable:', shouldDisableGpu, 'function exists:', typeof app.disableHardwareAcceleration === 'function');
// Supprimer les erreurs VSync bénignes quand le GPU est activé
app.commandLine.appendSwitch('disable-gpu-vsync');
app.commandLine.appendSwitch('disable-frame-rate-limit');
}
const errorLogPath = path.join(app.getPath('userData'), 'error.log');
function logGlobalError(err) {
const msg = `[${new Date().toISOString()}] ${err && err.stack ? err.stack : err}`;
try { fs.appendFileSync(errorLogPath, msg + '\n'); } catch(e) {}
console.error(msg);
}
process.on('uncaughtException', logGlobalError);
process.on('unhandledRejection', logGlobalError);
// Vérifier si app.setName ou équivalent existe et remplacer par 'AM-GUI' si besoin
if (app.setName) {
app.setName('AM-GUI');
}
let mainWindow = null;
const activeInstalls = new Map();
const activeUpdates = new Map();
const passwordWaiters = new Map();
async function isExecutableFile(filePath) {
if (!filePath) return false;
try {
const stats = await fsp.stat(filePath);
if (!stats.isFile()) return false;
await fsp.access(filePath, fs.constants.X_OK);
return true;
} catch (_) {
return false;
}
}
async function resolveCommandPath(binName) {
if (!binName || typeof binName !== 'string') return null;
const trimmed = binName.trim();
if (!trimmed) return null;
if (trimmed.includes(path.sep)) {
if (await isExecutableFile(trimmed)) return trimmed;
}
const envPath = process.env.PATH || '';
const pathEntries = envPath.split(path.delimiter).filter(Boolean);
for (const entry of pathEntries) {
const candidate = path.join(entry, trimmed);
if (await isExecutableFile(candidate)) return candidate;
}
const homeDir = os.homedir();
const candidates = new Set([
path.join(homeDir, '.local/bin', trimmed),
path.join(homeDir, 'bin', trimmed),
path.join(homeDir, 'Applications', 'bin', trimmed),
path.join(homeDir, 'Applications', trimmed, trimmed),
path.join(homeDir, 'Applications', trimmed, `${trimmed}.sh`),
path.join(homeDir, 'Applications', trimmed, `${trimmed}.AppImage`)
]);
for (const candidate of candidates) {
if (await isExecutableFile(candidate)) return candidate;
}
return null;
}
async function isSandboxWrapper(execPath) {
if (!execPath) return false;
try {
const handle = await fsp.open(execPath, 'r');
const buffer = Buffer.alloc(4096);
const { bytesRead } = await handle.read(buffer, 0, buffer.length, 0);
await handle.close();
if (!bytesRead) return false;
const snippet = buffer.slice(0, bytesRead).toString('utf8');
return snippet.includes(SANDBOX_MARKER);
} catch (_) {
return false;
}
}
async function detectAppImageFromPath(execPath) {
if (!execPath) return null;
try {
const handle = await fsp.open(execPath, 'r');
const buffer = Buffer.alloc(16);
const { bytesRead } = await handle.read(buffer, 0, buffer.length, 0);
await handle.close();
if (bytesRead < 12) return null;
const isElf = buffer[0] === 0x7f && buffer[1] === 0x45 && buffer[2] === 0x4c && buffer[3] === 0x46;
if (!isElf) return null;
const hasAppImageMagic = buffer[8] === 0x41 && buffer[9] === 0x49 && buffer[10] === 0x02;
return hasAppImageMagic;
} catch (_) {
return null;
}
}
async function detectSandboxDependencies() {
const [sasPath, aisapPath] = await Promise.all([
resolveCommandPath('sas'),
resolveCommandPath('aisap')
]);
const result = { hasSas: !!sasPath, hasAisap: !!aisapPath };
return result;
}
function getForbiddenSandboxPaths() {
const homeDir = os.homedir();
const dataDir = process.env.XDG_DATA_HOME || path.join(homeDir, '.local/share');
const configDir = process.env.XDG_CONFIG_HOME || path.join(homeDir, '.config');
const binDir = process.env.XDG_BIN_HOME || path.join(homeDir, '.local/bin');
return new Set([
path.resolve('/'),
path.resolve('/home'),
path.resolve(homeDir),
path.resolve(dataDir),
path.resolve(configDir),
path.resolve(binDir)
]);
}
function normalizeCustomSandboxPath(input) {
if (!input || typeof input !== 'string') return '';
let candidate = input.trim();
if (!candidate) return '';
if (candidate.startsWith('~/')) {
candidate = path.join(os.homedir(), candidate.slice(2));
} else if (candidate === '~') {
candidate = os.homedir();
}
return path.resolve(candidate);
}
async function validateCustomSandboxPath(input) {
const normalized = normalizeCustomSandboxPath(input);
if (!normalized) return { ok: true, value: '' };
const forbidden = getForbiddenSandboxPaths();
if (forbidden.has(path.normalize(normalized))) {
return { ok: false, error: 'forbidden-path' };
}
try {
await fsp.stat(normalized);
} catch (_) {
return { ok: false, error: 'missing-path' };
}
return { ok: true, value: normalized };
}
function buildSandboxAnswerScript(shouldConfigure, dirSelections, customPath) {
if (!shouldConfigure) return 'n\n';
const answers = ['y'];
SANDBOX_DIR_KEYS.forEach((key) => {
answers.push(dirSelections[key] ? 'y' : 'n');
});
if (customPath) {
answers.push('y');
answers.push(customPath);
} else {
answers.push('n');
}
return answers.map((ans) => `${ans ?? ''}\n`).join('');
}
function runSandboxTask(sender, { pm, action, args, stdinScript, appName }) {
return new Promise((resolve) => {
const pty = require('node-pty');
const id = `${action}-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 7)}`;
const env = Object.assign({}, process.env, {
TERM: 'xterm',
COLS: '80',
ROWS: '30',
FORCE_COLOR: '1'
});
let child;
try {
child = pty.spawn(pm, args, {
name: 'xterm-color',
cols: 80,
rows: 30,
cwd: process.cwd(),
env
});
} catch (err) {
invalidatePackageManagerCache();
return resolve({ ok: false, error: err?.message || 'Unable to start sandbox command.', id });
}
let settled = false;
let output = '';
const passwordRegex = /\[sudo\]|mot de passe.*:|password.*:/i;
const send = (payload) => {
if (!sender) return;
try {
sender.send('sandbox-progress', Object.assign({ id, action, appName }, payload));
} catch (_) {}
};
const finish = (result) => {
if (settled) return;
settled = true;
passwordWaiters.delete(id);
resolve(result);
};
send({ kind: 'start' });
passwordWaiters.set(id, (password) => {
if (typeof password === 'string') {
try { child.write(password + '\n'); }
catch (_) {}
} else {
try { child.kill('SIGKILL'); }
catch (_) {}
}
});
child.onData((txt) => {
output += txt;
send({ kind: 'data', chunk: txt });
if (passwordRegex.test(txt)) {
try { sender?.send('password-prompt', { id }); }
catch (_) {}
}
});
child.onExit((evt) => {
const code = typeof evt?.exitCode === 'number' ? evt.exitCode : evt?.code;
const success = code === 0;
send({ kind: 'done', code, success });
finish({ ok: success, code, output, id });
});
child.on?.('error', (err) => {
const message = err?.message || '';
const code = err?.code || '';
// node-pty may emit EIO when the PTY closes normally; treat it as benign.
if (code === 'EIO' || /EIO/.test(message)) {
send({ kind: 'debug', message: 'Sandbox PTY closed (EIO)' });
return;
}
invalidatePackageManagerCache();
send({ kind: 'error', message: message || 'Sandbox command failed.' });
finish({ ok: false, error: message || 'Sandbox command failed.', output, id });
});
if (stdinScript) {
setTimeout(() => {
try { child.write(stdinScript); }
catch (_) {}
}, 120);
}
});
}
// IPC pour lire/écrire la préférence GPU
ipcMain.handle('get-gpu-pref', async () => {
try {
const prefPath = path.join(app.getPath('userData'), 'gpu-pref.json');
if (fs.existsSync(prefPath)) {
const raw = fs.readFileSync(prefPath, 'utf8');
return JSON.parse(raw).disableGpu === true;
}
} catch(_){ }
return false;
});
ipcMain.handle('set-gpu-pref', async (_event, val) => {
try {
const prefPath = path.join(app.getPath('userData'), 'gpu-pref.json');
fs.writeFileSync(prefPath, JSON.stringify({ disableGpu: !!val }));
return { ok:true };
} catch(e){ return { ok:false, error: e.message||String(e) }; }
});
// IPC pour redémarrer l'application (utilisé après changement GPU)
ipcMain.handle('restart-app', async () => {
app.relaunch();
app.quit();
});
function createWindow () {
// Détection simple de l'environnement de bureau pour stylage léger
function detectDesktopEnv() {
const env = process.env;
const xdg = (env.XDG_CURRENT_DESKTOP || '').toLowerCase();
const session = (env.DESKTOP_SESSION || '').toLowerCase();
if (xdg.includes('gnome') || session.includes('gnome')) return 'gnome';
if (xdg.includes('kde') || xdg.includes('plasma') || session.includes('plasma') || session.includes('kde')) return 'plasma';
if (xdg.includes('xfce') || session.includes('xfce')) return 'xfce';
if (xdg.includes('cinnamon') || session.includes('cinnamon')) return 'cinnamon';
if (xdg.includes('unity') || session.includes('unity')) return 'unity';
return 'generic';
}
const deTag = detectDesktopEnv();
const sysLocale = process.env.LC_ALL || process.env.LC_MESSAGES || process.env.LANG || ((app.getLocale && typeof app.getLocale === 'function') ? app.getLocale() : 'en');
// Icône PNG
const iconPath = path.join(__dirname, 'AM-GUI.png');
const win = new BrowserWindow({
width: 1100,
height: 750,
frame: false, // retour à la barre personnalisée
title: 'AM-GUI',
icon: iconPath,
backgroundColor: '#f6f8fa',
webPreferences: {
preload: path.join(__dirname, 'preload.js'),
contextIsolation: true,
additionalArguments: [ `--de=${deTag}`, `--locale=${sysLocale}` ]
}
});
// Supprimer la barre de menu par défaut (File, Edit, View, etc.)
try { Menu.setApplicationMenu(null); } catch(_) {}
// Cacher la barre au cas où certaines plateformes la garderaient
win.setMenuBarVisibility(false);
win.loadFile('index.html');
// Forcer un titre vide après affichage (on affiche le faux header)
win.once('ready-to-show', () => {
// Le titre est déjà défini à la création, inutile de le modifier
});
// Raccourci clavier manuel pour ouvrir DevTools (menu supprimé)
win.webContents.on('before-input-event', (event, input) => {
if (input.control && input.shift && input.key && input.key.toLowerCase() === 'i') {
win.webContents.openDevTools({ mode: 'detach' });
}
});
// Menu contextuel (clic droit) basique pour copier / coller
win.webContents.on('context-menu', (event, params) => {
const { selectionText, isEditable } = params;
const hasSelection = selectionText && selectionText.trim().length > 0;
const template = [];
if (isEditable) {
template.push(
{ role: 'undo', label: 'Annuler' },
{ role: 'redo', label: 'Rétablir' },
{ type: 'separator' },
{ role: 'cut', label: 'Couper' },
{ role: 'copy', label: 'Copier' },
{ role: 'paste', label: 'Coller' },
{ role: 'delete', label: 'Supprimer' },
{ type: 'separator' },
{ role: 'selectAll', label: 'Tout sélectionner' }
);
} else if (hasSelection) {
template.push(
{ role: 'copy', label: 'Copier' },
{ type: 'separator' },
{ role: 'selectAll', label: 'Tout sélectionner' }
);
} else {
// Conserver une option sélectionner tout même sans sélection
template.push({ role: 'selectAll', label: 'Tout sélectionner' });
}
template.push({ type: 'separator' }, { role: 'toggleDevTools', label: 'Outils de développement' });
const menu = Menu.buildFromTemplate(template);
menu.popup({ window: win });
});
// Gestion de la fermeture : demander confirmation si une installation est en cours
win.on('close', (event) => {
// Vérifier s'il y a une installation active
if (activeInstalls.size > 0) {
event.preventDefault();
// Envoyer un message au renderer pour afficher la modale de confirmation
win.webContents.send('before-close');
}
});
mainWindow = win;
return win;
}
app.whenReady().then(() => {
try { iconCacheManager.registerProtocol(protocol); } catch(e) { console.warn('Protocole appicon échec:', e); }
const win = createWindow();
try { initTray(win); } catch(e) { console.warn('initTray échec:', e); }
});
app.on('before-quit', () => { try { destroyTray(); } catch(_) {} });
// IPC: purge complète du cache d'icônes
ipcMain.handle('purge-icons-cache', async () => iconCacheManager.purgeCache());
// Ouvrir une URL dans le navigateur externe
ipcMain.handle('open-external', async (_event, url) => {
try {
// validation basique
if (!url || typeof url !== 'string') return { ok: false, error: 'invalid url' };
// Autoriser seulement http/https
if (!/^https?:\/\//i.test(url)) return { ok: false, error: 'scheme not allowed' };
await shell.openExternal(url);
return { ok: true };
} catch (e) {
return { ok: false, error: e && e.message ? e.message : String(e) };
}
});
// Action générique: install / uninstall / update (simple)
ipcMain.handle('am-action', async (event, action, software) => {
const pm = await detectPackageManager();
if (!pm) return "Aucun gestionnaire 'am' ou 'appman' trouvé";
if (action === '__update_all__') {
return new Promise((resolve) => {
const child = spawn(pm, ['-u']);
let stdoutBuf = '';
let stderrBuf = '';
const killTimer = setTimeout(() => { try { child.kill('SIGTERM'); } catch(_){} }, 5*60*1000);
child.stdout.on('data', d => { stdoutBuf += d.toString(); });
child.stderr.on('data', d => { stderrBuf += d.toString(); });
child.on('close', (code) => {
clearTimeout(killTimer);
if (code === 0) return resolve(stdoutBuf || '');
resolve(stderrBuf || stdoutBuf || `Processus terminé avec code ${code}`);
});
child.on('error', (err) => {
clearTimeout(killTimer);
invalidatePackageManagerCache();
resolve(err.message || 'Erreur inconnue');
});
});
}
// Pour install/désinstall, utiliser node-pty pour la gestion du mot de passe
let args;
if (action === 'install') args = ['-i', software];
else if (action === 'uninstall') args = ['-R', software];
else return `Action inconnue: ${action}`;
return new Promise((resolve) => {
try {
const pty = require('node-pty');
const env = Object.assign({}, process.env, {
TERM: 'xterm',
COLS: '80',
ROWS: '30',
FORCE_COLOR: '1',
});
const child = pty.spawn(pm, args, {
name: 'xterm-color',
cols: 80,
rows: 30,
cwd: process.cwd(),
env
});
let output = '';
let done = false;
const id = Date.now().toString(36) + '-' + Math.random().toString(36).slice(2,8);
// Gestion du prompt mot de passe sudo
passwordWaiters.set(id, (password) => {
if (typeof password === 'string') {
try { child.write(password + '\n'); } catch(_) {}
} else {
try { child.kill('SIGKILL'); } catch(_) {}
}
});
child.onData((txt) => {
output += txt;
if (/\[sudo\]|mot de passe.*:|password.*:/i.test(txt)) {
// Demander le mot de passe au renderer via IPC
if (event.sender) event.sender.send('password-prompt', { id });
}
});
child.onExit((evt) => {
if (done) return;
done = true;
passwordWaiters.delete(id);
resolve(output);
});
child.on?.('error', (err) => {
if (done) return;
done = true;
passwordWaiters.delete(id);
invalidatePackageManagerCache();
resolve(err?.message || 'Erreur inconnue');
});
} catch (e) {
invalidatePackageManagerCache();
return resolve(e && e.message ? e.message : String(e));
}
});
});
// --- Installation streaming (Étapes 1 & 2) ---
// Fournit un suivi ligne à ligne pour l'installation d'un paquet.
// Retourne { id } immédiatement, puis envoie des événements 'install-progress'
// { id, kind:'start', name }
// { id, kind:'line', line }
// { id, kind:'done', code, success, duration, output }
// { id, kind:'error', message }
// Ajout : gestion du prompt mot de passe sudo
ipcMain.on('password-response', (event, payload) => {
if (!payload || !payload.id) return;
const waiter = passwordWaiters.get(payload.id);
if (waiter) {
waiter(payload.password);
passwordWaiters.delete(payload.id);
}
});
ipcMain.handle('install-start', async (event, name) => {
console.log('IPC install-start reçu pour', name);
const pm = await detectPackageManager();
// Log le lancement du processus
console.log('Processus lancé:', pm, ['-i', name]);
if (!pm) return { error: "Aucun gestionnaire 'am' ou 'appman' trouvé" };
if (!name || typeof name !== 'string') return { error: 'Nom invalide' };
const id = Date.now().toString(36) + '-' + Math.random().toString(36).slice(2,8);
let output = '';
const startedAt = Date.now();
let stdoutRemainder = '';
let stderrRemainder = '';
const pty = require('node-pty');
const env = Object.assign({}, process.env, {
TERM: 'xterm',
COLS: '80',
ROWS: '30',
FORCE_COLOR: '1',
// Ajoute d'autres variables si besoin
});
let child;
try {
child = pty.spawn(pm, ['-i', name], {
name: 'xterm-color',
cols: 80,
rows: 30,
cwd: process.cwd(),
env
});
} catch (err) {
invalidatePackageManagerCache();
return { error: err?.message || 'Impossible de démarrer le processus.' };
}
activeInstalls.set(id, child);
console.log('[ACTIVE-INSTALLS] Ajout process id:', id);
const wc = event.sender;
const send = (payload) => { try { wc.send('install-progress', Object.assign({ id }, payload)); } catch(_) {} };
send({ kind:'start', name });
const killTimer = setTimeout(() => { try { child.kill('SIGTERM'); } catch(_){} }, 10*60*1000); // 10 min sécurité
function flushLines(chunk, isErr){
// Log chaque chunk reçu du processus
const txt = chunk.toString();
output += txt;
// Détection du prompt mot de passe sudo
if (/\[sudo\]|mot de passe.*:|password.*:/i.test(txt)) {
// Demander le mot de passe au renderer via IPC
wc.send('password-prompt', { id });
// Attendre la réponse avant d'envoyer le mot de passe au process
passwordWaiters.set(id, (password) => {
if (typeof password === 'string') {
try { child.write(password + '\n'); } catch(_) {}
} else {
// Si annulé, tuer le process
try { child.kill('SIGKILL'); } catch(_) {}
}
});
}
// Envoi du chunk brut pour affichage terminal fidèle
send({ kind: 'line', raw: txt, stream: isErr ? 'stderr' : 'stdout' });
// Ancien découpage en lignes pour prompts interactifs
let buffer = (isErr ? stderrRemainder : stdoutRemainder) + txt;
const lines = buffer.split(/\r?\n/);
if (lines.length > 1) {
// conserver la dernière partielle
if (isErr) stderrRemainder = lines.pop(); else stdoutRemainder = lines.pop();
for (let idx = 0; idx < lines.length; idx++) {
const line = lines[idx].trim();
if (!line) continue;
// Détection du prompt de choix interactif (évite de matcher la ligne concaténée avec la réponse)
if ((/Choose which version|Which version you choose.*press ENTER|Please choose/i.test(line)) && !/\?\d+$/.test(line)) {
// Collecter toutes les options numérotées dans les lignes suivantes jusqu'à la fin du buffer
const options = [];
for (let j = idx + 1; j < lines.length; j++) {
let l = lines[j].trim();
if (!l || /^[-=]+$/.test(l)) continue;
if (l.includes('|')) {
// Colonnes détectées : logique inchangée
const parts = l.split('|').map(p => p.trim());
parts.forEach(part => {
if (/^\s*\d+[\.|\)]/.test(part)) options.push(part);
});
} else {
// Pas de colonne : possibilité d'ajouter la ligne suivante
if (/^\s*\d+[\.|\)]/.test(l)) {
let opt = l;
// Vérifier si la ligne suivante existe et ne commence pas par un chiffre
if (j + 1 < lines.length) {
let next = lines[j + 1].trim();
if (next && !/^\s*\d+[\.|\)]/.test(next) && !/^[-=]+$/.test(next)) {
opt += ' ' + next;
j++; // Sauter la ligne suivante
}
}
options.push(opt);
}
}
}
// Trier les options par numéro croissant
options.sort((a, b) => {
const na = parseInt(a.match(/\d+/)?.[0] || '0', 10);
const nb = parseInt(b.match(/\d+/)?.[0] || '0', 10);
return na - nb;
});
console.log('[CHOICE-PROMPT] prompt:', line, 'options:', options);
send({ kind:'choice-prompt', options, prompt: line });
}
}
} else {
if (isErr) stderrRemainder = lines[0]; else stdoutRemainder = lines[0];
}
}
// node-pty : toute la sortie arrive sur onData (stdout+stderr)
child.onData((d) => flushLines(d, false));
child.onExit((evt) => {
clearTimeout(killTimer);
// Log de sortie du process
console.log('[PTY] Process terminé pour id:', id, 'code:', evt.exitCode, 'durée:', (Date.now() - startedAt), 'ms');
// Émettre éventuelles dernières lignes partielles
if (stdoutRemainder && stdoutRemainder.trim()) send({ kind:'line', line: stdoutRemainder.trim(), stream:'stdout' });
if (stderrRemainder && stderrRemainder.trim()) send({ kind:'line', line: stderrRemainder.trim(), stream:'stderr' });
// Vérifier que le process est bien terminé avant suppression
if (activeInstalls.has(id)) {
activeInstalls.delete(id);
console.log('[ACTIVE-INSTALLS] Suppression process id:', id);
} else {
console.warn('[ACTIVE-INSTALLS] Tentative de suppression d’un process déjà supprimé pour id:', id);
}
const duration = Date.now() - startedAt;
const code = evt.exitCode;
const success = code === 0;
send({ kind:'done', code, success, duration, output });
});
child.on?.('error', (err) => {
clearTimeout(killTimer);
invalidatePackageManagerCache();
try { activeInstalls.delete(id); } catch(_){ }
send({ kind:'error', message: err?.message || 'Erreur processus' });
});
return { id };
});
// Annulation forcée d'une installation en cours
ipcMain.handle('install-cancel', async (event, installId) => {
if (!installId) return { ok:false, error:'ID manquant' };
const child = activeInstalls.get(installId);
if (!child) return { ok:false, error:'Processus introuvable' };
try {
// Annulation immédiate demandée: SIGKILL (destruction directe)
// NOTE: Pas de nettoyage applicatif dans l'outil am/appman si transaction partielle.
child.kill('SIGKILL');
// Émettre un événement immédiat de type 'cancelled' (le close suivra quand le process aura réellement quitté)
try { event.sender.send('install-progress', { id: installId, kind:'cancelled' }); } catch(_){ }
return { ok:true };
} catch(e){
return { ok:false, error: e.message || 'Annulation échouée' };
}
});
ipcMain.handle('updates-start', async (event) => {
const pm = await detectPackageManager();
if (!pm) return { error: "Aucun gestionnaire 'am' ou 'appman' trouvé" };
const id = Date.now().toString(36) + '-' + Math.random().toString(36).slice(2,8);
let child;
let output = '';
const pty = require('node-pty');
const env = Object.assign({}, process.env, {
TERM: 'xterm',
COLS: '80',
ROWS: '30',
FORCE_COLOR: '1'
});
try {
child = pty.spawn(pm, ['-u'], {
name: 'xterm-color',
cols: 80,
rows: 30,
cwd: process.cwd(),
env
});
} catch (err) {
invalidatePackageManagerCache();
return { error: err?.message || 'Impossible de démarrer la mise à jour.' };
}
activeUpdates.set(id, child);
const wc = event.sender;
const send = (payload) => {
try { wc.send('updates-progress', Object.assign({ id }, payload)); }
catch(_) {}
};
send({ kind: 'start' });
const killTimer = setTimeout(() => { try { child.kill('SIGTERM'); } catch(_){} }, 10 * 60 * 1000);
passwordWaiters.set(id, (password) => {
if (typeof password === 'string') {
try { child.write(password + '\n'); } catch(_) {}
} else {
try { child.kill('SIGKILL'); } catch(_) {}
}
});
child.onData((txt) => {
output += txt;
send({ kind: 'data', chunk: txt });
if (/\[sudo\]|mot de passe.*:|password.*:/i.test(txt)) {
try { wc.send('password-prompt', { id }); }
catch(_) {}
}
});
const cleanup = () => {
clearTimeout(killTimer);
activeUpdates.delete(id);
passwordWaiters.delete(id);
};
child.onExit((evt) => {
cleanup();
send({ kind: 'done', code: evt?.exitCode ?? evt?.code ?? null, signal: evt?.signal ?? null, success: (evt?.exitCode ?? evt?.code ?? 0) === 0, output });
});
child.on?.('error', (err) => {
const message = err?.message || '';
const code = err?.code || '';
// node-pty may emit EIO when the PTY closes normally; treat it as benign.
if (code === 'EIO' || /EIO/.test(message)) {
return;
}
cleanup();
invalidatePackageManagerCache();
send({ kind: 'error', message: message || 'Erreur inconnue', output });
});
return { id };
});
ipcMain.handle('updates-cancel', async (_event, id) => {
if (!id) return { ok: false, error: 'missing-id' };
const proc = activeUpdates.get(id);
if (!proc) return { ok: false, error: 'not-found' };
try { proc.kill('SIGTERM'); }
catch(_) {}
activeUpdates.delete(id);
passwordWaiters.delete(id);
return { ok: true };
});
ipcMain.handle('install-send-choice', async (_event, installId, choice) => {
if (!installId) return { ok:false, error: 'ID manquant' };
const child = activeInstalls.get(installId);
if (!child) return { ok:false, error: 'Processus introuvable' };
const normalizedChoice = (() => {
if (typeof choice === 'number' && Number.isFinite(choice)) return String(choice);
if (typeof choice === 'string') return choice.trim();
return '';
})();
if (!normalizedChoice) return { ok:false, error: 'Choix invalide' };
try {
child.write(normalizedChoice + '\n');
return { ok:true };
} catch (err) {
return { ok:false, error: err?.message || 'Échec envoi du choix' };
}
});
ipcMain.handle('install-appman-auto', async () => {
try {
const result = await installAppManAuto();
invalidatePackageManagerCache();
return { ok: true, result };
} catch (error) {
return { ok: false, error: error?.message || 'Installation AppMan échouée.' };
}
});
// Liste détaillée: distingue installées vs catalogue
ipcMain.handle('list-apps-detailed', async () => {
const pm = await detectPackageManager();
if (!pm) {
return { installed: [], all: [], pmFound: false, error: "Aucun gestionnaire 'am' ou 'appman' détecté dans le PATH." };
}
// We call both `pm -l` (catalog) and `pm -f` (installed files list). Some pm implementations
// (notably appman) print only a summary in `-l` and not the installed items — `-f` contains
// the actual list of installed programs. Run both and merge results.
const listCmd = `${pm} -l`;
const installedCmd = `${pm} -f`;
const execPromise = (cmd) => new Promise(res => {
exec(cmd, (err, stdout) => res({ err, stdout: stdout || '' }));
});
return new Promise(async (resolve) => {
try {
const [listRes, instRes] = await Promise.all([execPromise(listCmd), execPromise(installedCmd)]);
if ((listRes.err && listRes.err.code === 127) || (instRes.err && instRes.err.code === 127)) {
invalidatePackageManagerCache();
}
if ((listRes.err || !listRes.stdout) && (instRes.err || !instRes.stdout)) {
return resolve({ installed: [], all: [], pmFound: true, error: 'Échec exécution commande liste.' });
}
const catalogSet = new Set();
const catalogDesc = new Map();
const installedFromCatalog = new Set();
const installedSet = new Set();
const installedDesc = new Map();
const diamondSet = new Set(); // apps that were listed with leading '◆' in catalog output
// Parse catalog from -l output. Instead of relying on any fixed
// language header, we simply treat the block of ◆ entries that appears
// before the first blank line as the "installed" list. Once we hit a
// blank line after having seen at least one ◆ entry, further ◆ lines
// belong to the catalog proper. This handles translations and avoids
// accidentally turning the summary text into an app name.
try {
const lines = (listRes.stdout || '').split('\n');
let inCatalog = false;
let seenAppEntry = false;
const ignoreNamePatterns = [
/^YOU/i,
/^-/,
/^TOTAL/i,
/^\*has/i
];
// curEntry tracks the current ◆ entry so continuation lines can be
// appended to its description (descriptions can span multiple lines).
let curName = null;
let curDesc = null;
let curInCatalog = false;
const flushEntry = () => {
if (!curName) return;
if (!curInCatalog) {
installedFromCatalog.add(curName);
if (curDesc) installedDesc.set(curName, curDesc);
} else {
catalogSet.add(curName);
if (curDesc) catalogDesc.set(curName, curDesc);
}
diamondSet.add(curName);
curName = null;
curDesc = null;
};
for (const raw of lines) {
const line = raw.trim();
if (line === '') {
// blank line: if we've already scanned at least one ◆ entry and
// we're not yet in the catalog, switch to catalog mode. Subsequent
// ◆ entries will then be catalog items.
if (seenAppEntry && !inCatalog) {
flushEntry();
inCatalog = true;
} else {
flushEntry();
}
continue;
}
if (line.startsWith('\u25c6')) {
flushEntry();
const rest = line.slice(1).trim();
const colonIdx = rest.indexOf(':');
let left = rest;
let desc = null;
if (colonIdx !== -1) {
left = rest.slice(0, colonIdx).trim();
desc = rest.slice(colonIdx + 1).trim() || null;
}
const name = left.split(/\s+/)[0].trim();
if (ignoreNamePatterns.some(re => re.test(name))) continue;
curName = name;
curDesc = desc;
curInCatalog = inCatalog;
seenAppEntry = true;
} else if (curName && curInCatalog) {
// continuation line: append to current catalog entry description
curDesc = curDesc ? curDesc + ' ' + line : line;
}
}
flushEntry(); // flush the last entry
} catch (e) {
// ignore parse errors from catalog
}
// Parse installed list from -f output (appman -f prints installed programs)
// Example -f lines:
// "◆ pycharm | 2025.2.2 | appimage | 823 MiB"
try {
const lines = (instRes.stdout || '').split('\n');
const ignoreNamePatterns = [
/^YOU/i,
/^-/,
/^TOTAL/i,
/^\*has/i
];
let versionColIdx = 2; // par défaut, colonne 3 (0-based)
let headerParsed = false;
for (const raw of lines) {
let line = raw.trim();
if (!line) continue;
if (line.startsWith('APPNAME') || line.startsWith('- APPNAME')) {
// Détecter la colonne version dynamiquement
const headerCols = line.replace(/^- /, '').split('|').map(s => s.trim());
versionColIdx = headerCols.findIndex(col => col.toLowerCase().startsWith('version'));
headerParsed = true;
continue;
}
if (line.startsWith('-------')) continue; // ignorer la ligne de séparation
if (line.startsWith('\u25c6')) line = line.slice(1).trim();
if (!line) continue;
// Try to parse "name | ... | version | ..." separated by |
if (line.includes('|')) {
const cols = line.split('|').map(s => s.trim()).filter(Boolean);
const name = cols[0] ? cols[0].split(/\s+/)[0].trim() : null;
const version = (typeof versionColIdx === 'number' && versionColIdx >= 0 && versionColIdx < cols.length) ? cols[versionColIdx] : null;
if (name && !ignoreNamePatterns.some(re => re.test(name))) {
installedSet.add(name);
if (version) installedDesc.set(name, version);
}
} else {
// Fallback: first token is name, second token may be version
const parts = line.split(/\s+/).filter(Boolean);
const name = parts[0] || null;
const version = parts[1] || null;
if (name && !ignoreNamePatterns.some(re => re.test(name))) {
installedSet.add(name);
if (version) installedDesc.set(name, version);
}
}
}
} catch (e) {
// ignore parse errors from installed
}
// if -f output looks broken (empty or contains every catalog entry),
// fall back on the subset gathered from the catalog parsing.
if ((installedSet.size === 0 && installedFromCatalog.size > 0) ||
(catalogSet.size > 0 && installedSet.size >= catalogSet.size)) {