-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathscript.js
More file actions
2244 lines (2019 loc) · 68.8 KB
/
script.js
File metadata and controls
2244 lines (2019 loc) · 68.8 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
var batteryLevel, winds = {}, memory = {}, _nowapp, fulsapp = false, appsHistory = [], nowwindow, appicns = {}, fileslist = [], badlaunch = false, initmenuload = true, fileTypeAssociations = {}, handlers = {}, Gtodo, notifLog = {}, initialization = false, onstartup = [], novaFeaturedImage = `Dev.png`, defAppsList = [
"store",
"files",
"settings",
"calculator",
"text",
"musicplr",
"camera",
"time",
"gallery",
"browser",
"studio"
], timeFormat, timetypecondition = true, genTaskBar, genDesktop, nonotif;
let currentImage = 1;
function setbgimagetourl(x) {
const img1 = document.getElementById('bgimage1');
const img2 = document.getElementById('bgimage2');
if (!img1 || !img2) return;
const activeImg = currentImage === 1 ? img1 : img2;
const nextImg = currentImage === 1 ? img2 : img1;
nextImg.style.opacity = 0;
const setImageSrc = (url) => {
nextImg.src = url;
nextImg.onload = async () => {
nextImg.style.opacity = 1;
activeImg.style.opacity = 0;
activeImg.classList.remove('current-bg');
nextImg.classList.add('current-bg');
currentImage = currentImage === 1 ? 2 : 1;
const wallpos = await getSetting("wallpaperPos") || "center";
document.getElementsByClassName("current-bg")[0].style.objectPosition = wallpos;
const wallsiz = await getSetting("wallpaperSiz") || "cover";
document.getElementsByClassName("current-bg")[0].style.objectFit = wallsiz;
};
};
if (x.startsWith('data:')) {
try {
const byteString = atob(x.split(',')[1]);
const mimeString = x.split(',')[0].split(':')[1].split(';')[0];
const arrayBuffer = new Uint8Array(byteString.length);
for (let i = 0; i < byteString.length; i++) {
arrayBuffer[i] = byteString.charCodeAt(i);
}
const blob = new Blob([arrayBuffer], { type: mimeString });
const blobUrl = URL.createObjectURL(blob);
setImageSrc(blobUrl);
setTimeout(() => URL.revokeObjectURL(blobUrl), 1000);
} catch (e) {
console.error("Failed to decode base64 string:", e);
}
} else {
setImageSrc(x);
}
(async () => {
})();
}
Object.defineProperty(window, 'nowapp', {
get() {
return _nowapp;
},
set(value) {
_nowapp = value;
}
});
function loginscreenbackbtn() {
document.getElementsByClassName("backbtnscont")[0].style.display = "none";
document.getElementsByClassName("userselect")[0].style.flex = "1";
document.getElementsByClassName("logincard")[0].style.flex = "0";
}
async function showloginmod() {
if (badlaunch) { return }
var imgprvtmp = gid("wallbgpreview");
imgprvtmp.src = novaFeaturedImage;
imgprvtmp.onload = function handler() {
imgprvtmp.onload = null;
imgprvtmp.decode().then(() => {
closeElementedis();
}).catch(() => {
closeElementedis();
});
};
document.getElementsByClassName("backbtnscont")[0].style.display = "none";
function createUserDivs(users) {
const usersChooser = document.getElementById('userschooser');
usersChooser.innerHTML = '';
users.forEach(async (cacusername) => {
const userDiv = document.createElement('div');
userDiv.className = 'user';
userDiv.tabIndex = 0;
const selectUser = async function () {
try {
await cleanupram();
CurrentUsername = cacusername;
let isdefaultpass = false;
try {
isdefaultpass = await checkPassword('nova');
} catch (err) {
console.error("Password check failed:", err);
}
if (isdefaultpass) {
gid('loginmod').close();
gid('edison').showModal();
startup();
} else {
console.log("Password check failed: ", isdefaultpass);
document.getElementsByClassName("backbtnscont")[0].style.display = "flex";
document.getElementsByClassName("userselect")[0].style.flex = "0";
document.getElementsByClassName("logincard")[0].style.flex = "1";
gid("loginform1").focus();
gid('loginmod').showModal()
}
} catch (err) { }
};
userDiv.onclick = selectUser;
userDiv.addEventListener("keydown", function (event) {
if (event.key === "Enter") {
selectUser();
}
});
const img = document.createElement('img');
img.className = 'icon';
sharedStore.get(cacusername, "icon").then((icon) => { img.src = icon });
const nameDiv = document.createElement('div');
nameDiv.className = 'name';
nameDiv.textContent = cacusername;
userDiv.appendChild(img);
userDiv.appendChild(nameDiv);
usersChooser.appendChild(userDiv);
});
}
let users = await sharedStore.getAllUsers();
createUserDivs(users);
if (users.length > 0) {
document.querySelector('.user').focus();
}
const now = new Date();
const hours = String(now.getHours()).padStart(2, '0');
const minutes = String(now.getMinutes()).padStart(2, '0');
document.getElementById('loginusselctime').textContent = `${hours}:${minutes}`;
gid('loginmod').showModal();
gid('loginform1').addEventListener("keydown", async function (event) {
if (event.key === 'Enter') {
event.preventDefault();
await checkifpassright();
}
});
}
function setsrtpprgbr(val) {
let progressBar = document.getElementById('progress-bar');
let width = val;
progressBar.style.width = width + '%';
}
async function loadFileTypeAssociations() {
const associations = await getSetting('fileTypeAssociations');
fileTypeAssociations = associations || {};
const associations2 = await getSetting('handlers');
handlers = associations2 || {};
cleanupInvalidAssociations();
}
function closeElementedis(element) {
if (!element) {
element = document.getElementById("edison");
}
element.classList.add("closeEffect");
setTimeout(function () {
element.close()
element.classList.remove("closeEffect");
}, 200);
}
async function startup() {
gid("edison").showModal();
gid('loginmod').close();
if (badlaunch) { return }
lethalpasswordtimes = false;
setsrtpprgbr(50);
const start = performance.now();
updateNavSize();
await updateMemoryData().then(async () => {
try {
setsrtpprgbr(70);
try {
qsetsRefresh()
timetypecondition = await getSetting("timefrmt") == '24 Hour' ? false : true;
} catch { }
gid('startupterms').innerHTML = "Initializing...";
updateTime();
setsrtpprgbr(80);
await checkdmode();
setsrtpprgbr(90);
await genTaskBar();
setsrtpprgbr(100);
gid('startupterms').innerHTML = "Startup completed";
await genDesktop();
closeElementedis();
let fetchupdatedataver;
async function fetchDataAndUpdate() {
let fetchupdatedata = await fetch("versions.json");
if (fetchupdatedata.ok) {
let fetchupdatedataver = await fetchupdatedata.json();
let lclver = await getSetting("versions", "defaultApps.json") || {};
let howmany = 0;
for (let item of Object.keys(fetchupdatedataver)) {
let local = lclver[item] || 6754999;
if (local && fetchupdatedataver[item] != local) {
initialization = 1;
await updateApp(item);
initialization = 0;
howmany++;
lclver[item] = fetchupdatedataver[item];
}
}
await setSetting("versions", lclver, "defaultApps.json")
if (howmany) toast(howmany + " default app(s) have been updated")
} else {
console.error("Failed to fetch data from the server.");
}
}
let shouldcheckupd = await getSetting("nvaupdcheck");
if (shouldcheckupd) await fetchDataAndUpdate();
removeInvalidMagicStrings();
function startUpdateTime() {
let now = new Date();
let delay = (60 - now.getSeconds()) * 1000;
setTimeout(function () {
updateTime();
setInterval(updateTime, 60000);
}, delay);
}
startUpdateTime();
await loadFileTypeAssociations();
await ensureAllSettingsFilesExist();
await loadSessionSettings();
const end = performance.now();
rllog(
`You are using \n\n%cNovaOS%c\n%cNovaOS is the web system made for you.%c\n\nStartup: ${(end - start).toFixed(2)}ms\nUsername: ${CurrentUsername}\n12hr Time format: ${timetypecondition}`,
'color: white; background-color: #101010; font-size: 2rem; padding: 0.7rem 1rem; border-radius: 1rem;',
'',
'padding:5px 0; padding-top:1rem;',
'color: lightgreen; font-size:70%;'
);
try {
console.log("889")
function runScriptsSequentially(scripts, delay) {
scripts.forEach((script, index) => {
setTimeout(script, index * delay);
});
}
runScriptsSequentially(onstartup, 1000)
// onstartup apps
let allOnstarts = await getSetting('RunOnStartup');
allOnstarts.forEach(item => {
openapp(0, item, {}, 1);
})
} catch (e) { }
} catch (err) { console.error("startup error:", err); }
})
}
function updateTime() {
const now = new Date();
let hours = now.getHours();
if (timetypecondition) {
// 12-hour format
const ampm = hours >= 12 ? 'PM' : 'AM';
hours = (hours % 12) || 12;
timeFormat = `${hours}:${now.getMinutes().toString().padStart(2, '0')} ${ampm}`;
} else {
// 24-hour format
timeFormat = `${hours.toString().padStart(2, '0')}:${now.getMinutes().toString().padStart(2, '0')}`;
}
const date = `${now.getDate().toString().padStart(2, '0')}-${(now.getMonth() + 1).toString().padStart(2, '0')}-${now.getFullYear()}`;
gid('time-display').innerText = timeFormat;
gid('date-display').innerText = date;
}
const jsonToDataURI = json => `data:application/json,${encodeURIComponent(JSON.stringify(json))}`;
async function openn() {
gid("strtsear").value = "";
gid("strtappsugs").style.display = "none";
let x = await getFileNamesByFolder("Apps/");
x.sort((a, b) => a.name.localeCompare(b.name));
if (x.length === 0 && initmenuload) {
initmenuload = false;
gid("appdmod").close();
let choicetoreinst = await justConfirm(
`Re-initialize OS?`,
`Did the OS initialization fail? If yes, we can re-initialize your OS and install all the default apps. \n\nNovaOS did not find any apps while the initial load of Nova Menu. \n\nRe-initializing your OS may delete your data.`
);
if (choicetoreinst) {
initializeOS();
}
return;
}
initmenuload = false;
let existingAppElements = [...gid("appsindeck").children];
let existingAppIds = new Set(existingAppElements.map((child) => child.dataset.appId));
let newAppIds = new Set(x.map((app) => app.id));
existingAppElements.forEach((element) => {
if (!newAppIds.has(element.dataset.appId)) {
element.remove();
}
});
Promise.all(
x.map(async (app) => {
if (existingAppIds.has(app.id)) return;
var appShortcutDiv = document.createElement("div");
appShortcutDiv.className = "app-shortcut ctxAvail tooltip sizableuielement";
appShortcutDiv.setAttribute("unid", app.id || '');
appShortcutDiv.dataset.appId = app.id;
appShortcutDiv.addEventListener("click", () => openfile(app.id));
var iconSpan = document.createElement("span");
iconSpan.classList.add("appicnspan");
iconSpan.innerHTML = "<span class='taskbarloader'></span>";
getAppIcon(false, app.id).then((appIcon) => {
iconSpan.innerHTML = appIcon;
insertSVG(appIcon, iconSpan);
});
function getapnme(x) {
return x.split(".")[0];
}
var nameSpan = document.createElement("span");
nameSpan.className = "appname";
nameSpan.textContent = getapnme(app.name);
appShortcutDiv.appendChild(iconSpan);
appShortcutDiv.appendChild(nameSpan);
gid("appsindeck").appendChild(appShortcutDiv);
})
)
.then(() => { })
.catch((error) => {
console.error("An error occurred:", error);
});
if (gid("closeallwinsbtn").checked) {
gid("closeallwinsbtn").checked = false;
}
if (!Object.keys(winds).length) {
gid("closeallwinsbtn").checked = true;
gid("closeallwinsbtn").setAttribute("disabled", true);
} else {
gid("closeallwinsbtn").setAttribute("disabled", false);
}
gid("appdmod").showModal();
}
async function loadrecentapps() {
gid("serrecentapps").innerHTML = ``
if (appsHistory.length < 1) {
gid("partrecentapps").style.display = "none";
gid("serrecentapps").innerHTML = `No recent apps`
return;
} else {
gid("partrecentapps").style.display = "block";
}
let x = await getFileNamesByFolder("Apps");
x.reverse();
Promise.all(x.map(async (app) => {
if (!appsHistory.includes(app.name)) {
return
}
var appShortcutDiv = document.createElement("div");
appShortcutDiv.className = "app-shortcut ctxAvail sizableuielement";
appShortcutDiv.setAttribute("unid", app.id || '');
appShortcutDiv.addEventListener("click", () => openapp(app.name, app.id));
var iconSpan = document.createElement("span");
iconSpan.classList.add("appicnspan");
if (!appicns[app.id]) {
const content = await getFileById(app.id);
const unshrunkContent = decodeBase64Content(content.content);
const tempElement = document.createElement('div');
tempElement.innerHTML = unshrunkContent;
const metaTags = tempElement.getElementsByTagName('meta');
let metaTagData = null;
Array.from(metaTags).forEach(tag => {
const tagName = tag.getAttribute('name');
const tagContent = tag.getAttribute('content');
if (tagName === 'nova-icon' && tagContent) {
metaTagData = tagContent;
}
});
if (typeof metaTagData === "string") {
if (containsSmallSVGElement(metaTagData)) {
iconSpan.innerHTML = metaTagData;
} else {
iconSpan.innerHTML = defaultAppIcon;
}
} else {
iconSpan.innerHTML = defaultAppIcon;
}
appicns[app.id] = iconSpan.innerHTML
} else {
iconSpan.innerHTML = appicns[app.id]
}
var nameSpan = document.createElement("span");
nameSpan.className = "appname";
nameSpan.textContent = basename(app.name);
appShortcutDiv.appendChild(iconSpan);
appShortcutDiv.appendChild(nameSpan);
gid("serrecentapps").appendChild(appShortcutDiv);
})).then(async () => {
gid("novamenusearchinp").focus();
}).catch((error) => {
console.error('An error occurred:', error);
});
}
function makedefic(str) {
if (!str) {
return 'app';
}
const words = str.split(/\s+/);
const result = words.map(word => {
const consonantPattern = /[^aeiouAEIOU\s]+/g;
const consonantMatches = word.match(consonantPattern);
if (consonantMatches && consonantMatches.length >= 2) {
return consonantMatches.slice(0, 2).map((letter, index) => index === 0 ? letter : letter.toLowerCase()).join('');
} else {
const firstLetter = word.charAt(0);
const firstConsonantIndex = word.search(consonantPattern);
if (firstConsonantIndex !== -1) {
return firstLetter + word.charAt(firstConsonantIndex).toLowerCase();
}
return firstLetter;
}
});
return result.join('').slice(0, 3);
} function updateBattery() {
var batteryPromise;
if ('getBattery' in navigator) {
batteryPromise = navigator.getBattery();
} else if ('battery' in navigator) {
batteryPromise = Promise.resolve(navigator.battery);
} else {
document.getElementById("batterydisdiv").style.display = "none";
return;
}
batteryPromise.then(function (battery) {
if (typeof battery.level !== 'number' || isNaN(battery.level)) {
document.getElementById("batterydisdiv").style.display = "none";
return;
}
var batteryLevel = Math.round(battery.level * 100);
var isCharging = !!battery.charging;
if ((batteryLevel === 100 && isCharging) || (batteryLevel === 0 && isCharging)) {
document.getElementById("batterydisdiv").style.display = "none";
} else {
document.getElementById("batterydisdiv").style.display = "flex";
}
let iconClass;
if (batteryLevel >= 75) {
iconClass = 'battery_full';
} else if (batteryLevel >= 25) {
iconClass = 'battery_5_bar';
} else if (batteryLevel >= 15) {
iconClass = 'battery_2_bar';
} else {
iconClass = 'battery_alert';
}
var batteryDisplayElement = document.getElementById('battery-display');
var batteryPDisplayElement = document.getElementById('battery-p-display');
if (batteryDisplayElement && batteryPDisplayElement) {
if (iconClass !== batteryDisplayElement.innerText || batteryPDisplayElement.innerText !== batteryLevel + "%") {
batteryDisplayElement.innerHTML = iconClass;
batteryPDisplayElement.innerHTML = batteryLevel + "%";
}
}
}).catch(function () {
document.getElementById("batterydisdiv").style.display = "none";
});
}
function clwin(x) {
snappingconthide();
const el = isElement(x) ? x : document.getElementById(x.startsWith("window") ? x : "window" + x);
const windKey = isElement(x) ? el.getAttribute("data-winuid") : x;
if (windKey) {
console.log(windKey)
URL.revokeObjectURL(winds[windKey].src)
delete winds[windKey];
}
loadtaskspanel()
if (!el) return;
el.classList.add("transp3");
setTimeout(() => {
el.classList.remove("transp3");
el.remove();
}, 700);
}
function getMetaTagContent(unshrunkContent, metaName, decode = false) {
const content = decode ? decodeBase64Content(unshrunkContent) : unshrunkContent;
const tempElement = document.createElement('div');
tempElement.innerHTML = content;
const metaTag = Array.from(tempElement.getElementsByTagName('meta')).find(tag =>
tag.getAttribute('name') === metaName && tag.getAttribute('content')
);
return metaTag ? metaTag.getAttribute('content') : null;
}
function getAppTheme(unshrunkContent) {
return getMetaTagContent(unshrunkContent, 'theme-color', true);
}
function getAppAspectRatio(unshrunkContent) {
const content = decodeBase64Content(unshrunkContent);
return content.includes("aspect-ratio") ? getMetaTagContent(content, 'aspect-ratio', false) : null;
}
async function getAppIcon(content, id, lazy = 0) {
try {
if (content, id == undefined) {
if (content == 'folder')
return `<svg xmlns="http://www.w3.org/2000/svg" height="24px" viewBox="0 -960 960 960" width="24px" fill="var(--col-txt1)"><path d="M160-160q-33 0-56.5-23.5T80-240v-480q0-33 23.5-56.5T160-800h207q16 0 30.5 6t25.5 17l57 57h360q17 0 28.5 11.5T880-680q0 17-11.5 28.5T840-640H447l-80-80H160v480l79-263q8-26 29.5-41.5T316-560h516q41 0 64.5 32.5T909-457l-72 240q-8 26-29.5 41.5T760-160H160Zm84-80h516l72-240H316l-72 240Zm-84-262v-218 218Zm84 262 72-240-72 240Z"/></svg>`;
return defaultAppIcon;
} else if (id == "info") {
return `<svg xmlns="http://www.w3.org/2000/svg" height="24px" viewBox="0 -960 960 960" width="24px" fill="var(--col-txt1)"><path d="M440-280h80v-240h-80v240Zm40-320q17 0 28.5-11.5T520-640q0-17-11.5-28.5T480-680q-17 0-28.5 11.5T440-640q0 17 11.5 28.5T480-600Zm0 520q-83 0-156-31.5T197-197q-54-54-85.5-127T80-480q0-83 31.5-156T197-763q54-54 127-85.5T480-880q83 0 156 31.5T763-763q54 54 85.5 127T880-480q0 83-31.5 156T763-197q-54 54-127 85.5T480-80Zm0-80q134 0 227-93t93-227q0-134-93-227t-227-93q-134 0-227 93t-93 227q0 134 93 227t227 93Zm0-320Z"/></svg>`
}
const withTimeout = (promise) =>
Promise.race([promise, new Promise((_, reject) => setTimeout(() => reject(), 3000))]);
const getAppIconFromRegistry = async (id, registry) => {
if (registry && registry.icon) {
appicns = registry.icon;
return appicns;
}
return null;
};
const saveIconToRegistry = async (id, iconContent, registry) => {
const updatedRegistry = {
...(registry || {}),
icon: iconContent
};
await setSetting(id, updatedRegistry, "AppRegistry.json");
};
try {
if (appicns[id]) return appicns[id];
if (lazy) return defaultAppIcon;
const registry = await getSetting(id, "AppRegistry.json") || {};
const cachedIcon = await getAppIconFromRegistry(id, registry);
if (cachedIcon) return cachedIcon;
if (!content) {
const file = await withTimeout(await getFileById(id));
if (!file || !file.content) throw new Error("File content unavailable " + id);
content = file.content;
}
const iconContent = await withTimeout(getMetaTagContent(content, 'nova-icon', true));
if (iconContent && containsSmallSVGElement(iconContent)) {
appicns[id] = iconContent;
await saveIconToRegistry(id, iconContent, registry);
return iconContent;
}
} catch (err) {
console.error("Error in getAppIcon:", err);
}
} catch (e) { }
const fallbackIcon = generateFallbackIcon(id);
appicns[id] = fallbackIcon;
return fallbackIcon;
}
async function generateFallbackIcon(id) {
const icondatatodo = await getFileNameByID(id) || id;
return `<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="115.24806" height="130.92446" viewBox="0,0,115.24806,130.92446"><g transform="translate(-182.39149,-114.49081)"><g stroke="none" stroke-miterlimit="10"><path d="M182.39149,245.41527v-130.83054h70.53005l44.68697,44.95618v85.87436z" fill="` + stringToPastelColor(icondatatodo) + `" stroke-width="none"/><path d="M252.60365,158.84688v-44.35607l45.03589,44.35607z" style="opacity: 0.7" fill="#dadada" stroke-width="0"/><text transform="translate(189,229) scale(0.9,0.9)" font-size="3rem" xml:space="preserve" fill="#dadada" style="opacity: 0.7" stroke-width="1" font-family="monospace" font-weight="normal" text-anchor="start"><tspan x="0" dy="0" fill="black">${makedefic(icondatatodo)}</tspan></text></g></g></svg>`;
}
async function applyIconPack(iconPack) {
try {
for (const namespace in handlers) {
const appID = handlers[namespace];
const iconSVG = iconPack[namespace];
if (!iconSVG) continue;
try {
const appicn = await getSetting(appID, "AppRegistry.json") || {};
appicn["icon"] = iconSVG;
await setSetting(appID, appicn, "AppRegistry.json");
console.log(`Icon set for app ${appID} from namespace ${namespace}`);
} catch (err) {
console.error(`Failed to set icon for app ${appID}`, err);
}
}
} catch (err) {
console.error("Failed to apply icon pack", err);
}
appicns = {};
gid("appsindeck").innerHTML = "";
genTaskBar();
genDesktop();
}
async function fetchData(url) {
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
const data = await response.text();
return data;
} catch (error) {
console.error("Error fetching data:", error.message);
const data = null;
return data;
}
}
var content;
function putwinontop(x) {
Object.keys(winds).forEach(wid => {
if (gid(`window${wid}`).style.zIndex)
winds[wid].zIndex = Number(gid(`window${wid}`).style.zIndex || 0);
else
return;
});
if (Object.keys(winds).length > 1) {
const windValues = Object.values(winds).map(wind => Number(wind.zIndex) || 0);
const maxWindValue = Math.max(...windValues);
document.getElementById(x).style.zIndex = maxWindValue + 1;
normalizeZIndexes(x);
} else {
document.getElementById(x).style.zIndex = 0;
}
if (typeof updateFocusedWindowBorder === "function") updateFocusedWindowBorder();
}
function isWinOnTop(x) {
const ourKey = x.replace(/^window/, '');
const maxKey = Object.keys(winds).reduce((a, b) => (Number(winds[a].zIndex) > Number(winds[b].zIndex) ? a : b));
return ourKey === maxKey;
}
function normalizeZIndexes(excludeWindowId = null) {
const windValues = Object.entries(winds)
.filter(([key]) => key !== excludeWindowId)
.map(([_, wind]) => Number(wind.zIndex) || 0);
const uniqueSorted = [...new Set(windValues)].sort((a, b) => a - b);
if (uniqueSorted.length === uniqueSorted[uniqueSorted.length - 1]) return;
const zIndexMap = uniqueSorted.reduce((map, value, index) => {
map[value] = index;
return map;
}, {});
winds = Object.keys(winds).reduce((normalizedWinds, key) => {
normalizedWinds[key] = {
...winds[key],
zIndex: key === excludeWindowId
? winds[key].zIndex
: zIndexMap[Number(winds[key].zIndex) || 0],
};
return normalizedWinds;
}, {});
}
function requestLocalFile() {
var requestID = genUID()
x = {
"appname": "files",
"type": "open",
"identifier": requestID
}
localStorage.setItem("todo", JSON.stringify(x))
openapp("files", 1)
}
function getMaxZIndex() {
const elements = document.querySelectorAll('.window');
let maxZIndex = 0;
elements.forEach(element => {
const zIndex = parseInt(window.getComputedStyle(element).zIndex);
if (zIndex > maxZIndex) {
maxZIndex = zIndex;
}
});
}
function folderExists(folderName) {
const parts = folderName.replace(/\/$/, '').split('/');
let current = memory.root;
for (let part of parts) {
part += '/';
if (!current[part]) {
return false;
}
current = current[part];
}
return true;
}
function isBase64(str) {
try {
function validateBase64(data) {
const base64Pattern = /^[A-Za-z0-9+/=]+$/;
if (!base64Pattern.test(data)) {
return false;
}
const padding = data.length % 4;
if (padding > 0) {
data += '='.repeat(4 - padding);
}
atob(data);
return true;
}
if (validateBase64(str)) {
return true;
}
const base64Prefix = 'data:';
const base64Delimiter = ';base64,';
if (str.startsWith(base64Prefix)) {
const delimiterIndex = str.indexOf(base64Delimiter);
if (delimiterIndex !== -1) {
const base64Data = str.substring(delimiterIndex + base64Delimiter.length);
return validateBase64(base64Data);
}
}
return false;
} catch (err) {
return false;
}
}
async function extractAndRegisterCapabilities(appId, content) {
try {
if (!content) {
content = await getFileById(appId);
content = content.content;
}
if (isBase64(content)) {
content = decodeBase64Content(content);
}
let parser = new DOMParser();
let doc = parser.parseFromString(content, "text/html");
let metaTag = doc.querySelector('meta[name="capabilities"]');
let capabilities = [];
if (metaTag) {
capabilities = metaTag.getAttribute("content").split(',').map(s => s.trim());
} else {
console.log(`No capabilities: ${appId}`);
}
let onlyDefPerms = false;
let totalperms = ['utility', 'sysUI'];
let metaTag2 = doc.querySelector('meta[name="permissions"]');
let requestedperms = [];
if (metaTag2) {
requestedperms = metaTag2.getAttribute("content").split(',').map(s => s.trim());
} else {
console.log(`No permissions: ${appId}`);
onlyDefPerms = true
}
function arraysEqualIgnoreOrder(arr1, arr2) {
if (arr1.length !== arr2.length) return false;
let sorted1 = [...arr1].sort();
let sorted2 = [...arr2].sort();
for (let i = 0; i < sorted1.length; i++) {
if (sorted1[i] !== sorted2[i]) return false;
}
return true;
}
onlyDefPerms = (onlyDefPerms) ? true : arraysEqualIgnoreOrder(requestedperms, totalperms);
if (onlyDefPerms) {
console.log("only def perms");
}
let permissions = Array.from(new Set([...totalperms, ...requestedperms]));
if (!onlyDefPerms) {
let modal = gid("AppInstDia");
gid("app_inst_dia_icon").innerHTML = await getAppIcon(0, appId);
gid("app_inst_mod_app_name").innerText = await getFileNameByID(appId);
let listelement = gid("app_inst_mod_li");
listelement.innerHTML = '';
if (capabilities.length > 0) {
let handlerList = capabilities.filter(c => !c.startsWith('.') && c !== 'onStartup').join(', ');
if (handlerList) {
let span = document.createElement("li");
span.innerHTML = `Function as ${handlerList}`;
listelement.appendChild(span);
}
let fileTypes = capabilities.filter(c => c.startsWith('.')).join(', ');
if (fileTypes) {
let span = document.createElement("li");
span.innerHTML = `Open ${fileTypes} by default`;
listelement.appendChild(span);
}
if (capabilities.includes('onStartup')) {
let span = document.createElement("li");
span.innerHTML = "Run during startup";
listelement.appendChild(span);
}
}
permissions.sort((a, b) => getNamespaceRisk(b) - getNamespaceRisk(a));
if (permissions.includes("unsandboxed")) {
let span = document.createElement("li");
span.innerHTML = describeNamespaces("unsandboxed").replace(/^./, c => c.toUpperCase());
span.innerHTML += `<small>Only recommended for apps you trust.</small>`;
listelement.appendChild(span);
} else {
permissions.forEach((perm) => {
let span = document.createElement("li");
span.innerHTML = describeNamespaces(perm).replace(/^./, c => c.toUpperCase());
listelement.appendChild(span);
});
}
let yesButton = gid("app_inst_mod_agbtn");
let noButton = gid("app_inst_mod_nobtn");
let condition = await new Promise((resolve) => {
if (initialization) {
resolve(true);
} else {
modal.showModal();
}
yesButton.onclick = () => {
modal.close();
resolve(true);
};
noButton.onclick = () => {
modal.close();
resolve(false);
};
});
if (!condition) return;
}
requestedperms.forEach((perm) => {
if (!totalperms.includes(perm)) {
totalperms.push(perm);
}
});
await registerApp(appId, capabilities);
let registry = {};
registry.perms = totalperms;
await setSetting(appId, registry, "AppRegistry.json");
} catch (error) {
console.error("Error extracting and registering capabilities:", error);
}
}
async function registerApp(appId, capabilities) {
for (let rawCapability of capabilities) {
let capability = rawCapability.trim();
if (capability === 'onStartup') continue;
if (capability.startsWith('.')) {
fileTypeAssociations[capability] = [appId];
} else {
handlers[capability] = appId;
}
}
await setSetting('fileTypeAssociations', fileTypeAssociations);
await setSetting('handlers', handlers);
if (capabilities.includes('onStartup')) {
let startupApps = await getSetting('RunOnStartup') || [];
if (!startupApps.includes(appId)) startupApps.push(appId);
await setSetting('RunOnStartup', startupApps);
}
if (!initialization)
notify(await getFileNameByID(appId) + " installed", "Registered " + capabilities.toString(), "NovaOS System");
return capabilities.toString();
}
async function cleanupInvalidAssociations() {
const validAppIds = await getAllValidAppIds();
let associationsChanged = false;
for (let fileType in fileTypeAssociations) {
const appId = fileTypeAssociations[fileType][0];
if (!validAppIds.includes(appId)) {
console.log(`Removing invalid file type association: ${fileType} for app ID ${appId}`);
delete fileTypeAssociations[fileType];
associationsChanged = true;
}
}
if (associationsChanged) {
await setSetting('fileTypeAssociations', fileTypeAssociations);
}
let registry = await getSetting('full', "AppRegistry.json");
for (let key in registry) {
if (!await window.parent.getFileNameByID(key)) {
window.parent.remSettingKey(key, "AppRegistry.json")
continue;
}
}
}
async function getAllValidAppIds() {
const appsFolder = await getFileNamesByFolder('Apps/');
return Object.keys(appsFolder || {}).map(appFileName => appsFolder[appFileName].id);
}
function makedialogclosable(ok) {
const myDialog = gid(ok);
if (!myDialog.__originalClose) {
myDialog.__originalClose = myDialog.close;
myDialog.close = function () {
console.log(342, ok)
this.classList.add("closeEffect");
function handler() {
myDialog.__originalClose();
myDialog.classList.remove("closeEffect");
};
setTimeout(handler, 200);
};
}
document.addEventListener('click', (event) => {
if (event.target === myDialog) {
myDialog.close();
}
});
}
function openModal(type, { title = '', message, options = null, status = null, preset = '' } = {}, registerRef = false) {
if (badlaunch) { return }
return new Promise((resolve) => {
const modal = document.createElement('dialog');
modal.classList.add('modal');
const modalItemsCont = document.createElement('div');
modalItemsCont.classList.add('modal-items');
const icon = document.createElement('span');
icon.classList.add('material-symbols-rounded');
let ic = "warning";
if (status === "success") ic = "check_circle";
else if (status === "failed") ic = "dangerous";
icon.textContent = ic;
icon.classList.add('modal-icon');
modalItemsCont.appendChild(icon);
if (title && title.length > 0) {
const h1 = document.createElement('h1');
h1.textContent = title;
modalItemsCont.appendChild(h1);
}
const p = document.createElement('p');
if (type === 'say' || type === 'confirm') {
p.innerHTML = `${message}`;