-
-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathmain.mjs
1756 lines (1621 loc) · 58.7 KB
/
main.mjs
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
// main.js
// Modules to control application life and create native browser window
import {app, BrowserWindow, globalShortcut, screen, Notification, ipcMain, nativeTheme, dialog, Menu} from 'electron';
import {shell as outside} from 'electron';
import {execFile as child} from 'child_process'; //check the subroutines for execFile and spawn
import {spawn as spawner} from 'child_process';
import log from 'electron-log';
import path from 'node:path';
import * as fs from 'node:fs';
import fse from 'fs-extra/esm';
import Store from 'electron-store';
/* import {crypto} from 'node:crypto'; */
import sharp from 'sharp';
import {dree} from 'dree';
import { fileURLToPath } from 'url';
const crypto = await import('node:crypto');
const __filename = fileURLToPath(import.meta.url); // get the resolved path to the file
const __dirname = path.dirname(__filename); // get the name of the directory
/*
TODO remove this shit
var child = require('child_process').execFile;
var spawner = require('child_process').spawn; */
/* const path = require('path') */
/* const fs = require('fs')
const fse = require('fs-extra') */
/* const store = require('electron-store'); //https://github.com/sindresorhus/electron-store#readme */
/* const sharp = require('sharp');
const dree = require('dree'); */
//const outside = require('electron').shell;
/* const crypto = require('crypto'); */
app.commandLine.appendSwitch('enable-gpu') //enable acceleration
//app.commandLine.appendSwitch('disable-features', 'WidgetLayering'); //minor fixes for console layering not working as intended
const hash = crypto.createHash('sha256');
//hash.digest('base64');
//Log setups
log.transports.file.level = 'info'
log.transports.console.level = 'info'
var subproc
const dreeOptions = {
stat:false,
followLinks:false,
hash:true,
sizeInBytes: false,
size: false,
extensions: ["glb"],
normalize:true,
excludeEmptyDirectories:true
}
const _microblends = 0
const _decals = 1
const _jsons = 2
var customModels
var userResourcesPath = '/_Migrate/'
var userRScheme = [
'mblend',
'decals',
'jsons'
]
var userRfiles = {
masks : 'masklist',
microblends : 'mbcustom',
mat_template : 'material_template'
}
var objwkitto = {}
const schema = {
maskformat:{
type: 'string',
default: 'png'
},
legacymaterial:{
type:'boolean',
default: false
},
usermigration:{
type:'boolean',
default: false
},
flipmasks:{
type:'boolean',
default: false
},
flipnorm:{
type:'boolean',
default: false
},
workspace:{
type:'number',
default: 0
},
paths:{
type:'object',
default : {
depot: '',
game:'',
lastmod: '',
wcli:''
}
},
editorCfg : {
type:'object',
default: {
layer:{
tiles:{
default: 150.0,
value: 150.0
}
},
mblend:{
tiles:{
default: 150.0,
value: 150.0
},
contrast:{
default: 1.0,
value: 1.0
},
normal:{
default: 2.0,
value: 2.0
}
},
skipImport:false,
switchTransparency:true
}
}
};
const wolvenkitPrefFile = path.join(app.getPath('appData'),'REDModding/WolvenKit/config.json');
const preferences = new Store({schema,
beforeEachMigration: (store, context) => {
log.info(`[main-config] migrate from ${context.fromVersion} → ${context.toVersion}`)
},
migrations: {
'<=1.6.2': store => {
if (store.has('unbundle') && (!store.has('pathfix'))){
let fixstring = store.get('unbundle')
store.set('unbundle',fixstring.replace(/\\base$/,''))
store.set('pathfix','1')
}else{
store.set('unbundle','');
store.set('pathfix','0');
}
},
'1.6.3': store =>{
if (store.has("pathfix")){
store.delete('pathfix')
}
store.set('legacymaterial',false)
},
'1.6.6': store =>{
store.set('game','')
store.set('depot','')
},
'1.6.7': store =>{
if (store.get('depot')==''){
//preparing for the switch from the unbundle folder, to the depot one
if (store.has("unbundle")){
let fixVal = store.get('unbundle')
store.set('depot', fixVal)
}
}
store.set('flipmasks',false)
store.set('flipnorm',false)
},
'1.6.8': store =>{
store.set('workspace', 0),
store.set({
editorCfg:{
layer:{
tiles:{
default: 150.0,
value: 150.0
}
},
mblend:{
tiles:{
default: 150.0,
value: 150.0
},
contrast:{
default: 1.0,
value: 1.0
},
normal:{
default: 2.0,
value:2.0
}
}
}
})
var fixGamePath = store.get('game');
store.set({
paths:{
depot: store.get('depot'),
game:fixGamePath,
lastmod: '',
wcli: store.get('wcli')
}
})
if (store.has("depot")){
store.delete("depot");
}
if (store.has("game")){
store.delete("game")
}
if (store.has("unbundle")){
store.delete("unbundle")
}
if (store.has("wcli")){
store.delete("wcli")
}
},
'1.6.8-beta8': store=>{
store.set('editorCfg.skipImport',false);
},
'1.6.8-rc1': store=>{
store.set('editorCfg.switchTransparency',true);
}
}
});
var spotfolder={
base: "archive/pc/content",
pl: "archive/pc/ep1"
}
/* var archives={
engine : "basegame_1_engine.archive",
nightcity : "basegame_3_nightcity.archive",
appearances : "basegame_4_appearance.archive",
gamedata : "basegame_4_gamedata.archive"
} */
preferences.watch = true
var mainWindow,aimWindow; //check variable name
var mljson = app.commandLine.getSwitchValue("open")
if (mljson ==''){
mljson = app.commandLine.getSwitchValue("o")
}
var wkitto = app.commandLine.getSwitchValue("wkit")
var dev = app.commandLine.getSwitchValue("dev")
var lastMicroConf = {}
//register the application name
if (process.platform === 'win32'){ app.setAppUserModelId(app.name); }
/*Read the custom Microblends from the resource list*/
/*Write the custom Microblends to the resource list*/
function MuWriting(contenuto){
return new Promise((resolve,reject) =>{
let app_custom_json = path.join(app.getAppPath(),userRScheme[_jsons],`/${userRfiles.microblends}.json`)/* application file */
let bk_custom_json = path.join(app.getPath('userData'),userResourcesPath,userRScheme[_jsons],`/${userRfiles.microblends}.json`) /* application file */
fs.writeFile(app_custom_json,contenuto,(err) =>{
if (err) {
reject()
}else{
fs.copyFile(app_custom_json,bk_custom_json,fs.constants.COPYFILE_FICLONE,(err) =>{
if (err) {
mainWindow.webContents.send('preload:logEntry', "it's impossible to create the copy backup",true)
}
resolve(true)
})
}
})
})
}
//simple promise to read files
function fileOpener(target=''){
return new Promise((resolve,reject)=>{
fs.readFile(target,(err,filecontent) =>{
if (err) {
mainWindow.webContents.send('preload:logEntry',`Error when trying to read ${target} file`,true);
reject()
}else{
mainWindow.webContents.send('preload:logEntry',`File ${target} opened`,false);
resolve(filecontent)
}
})
})
}
async function fqfnFile(event,arg){
//fully qualified file name resource pointer
if ((arg.hasOwnProperty('extension') ) && (arg.hasOwnProperty('path'))){
let seenPath = path.dirname(arg.path);
const {canceled,filePaths } = await dialog.showOpenDialog({title:`Select the .${arg.extension} file`, properties: ['openFile'], defaultPath:path.join(preferences.get('paths.depot'),seenPath ), filters: [
{ name: 'specific type', extensions: [arg.extension] }] });
if (canceled){
return
}else{
return filePaths[0]
}
}else{
return
}
}
function JsonResourceRead(UserResource){
return new Promise((resolve,reject) =>{
let app_custom_json = path.join(app.getAppPath(),userRScheme[_jsons],`/${UserResource}.json`)/* application file */
fs.readFile(app_custom_json,(err,filecontent) =>{
if (err) {
reject()
}else{
try{
let strutcontent = JSON.parse(filecontent)
resolve(strutcontent)
}catch(err){
reject()
}
}
})
})
}
function customResource(){
let pathMigration = path.join(app.getPath('userData'),userResourcesPath)
try {
if (!fs.existsSync(pathMigration)){
fs.mkdir(pathMigration, { recursive: true }, (err) => {
if (err) dialog.showErrorBox("The migration folder isn't accessible, trying to create one : -",err.message)
})
}
userRScheme.forEach((item, i) => {
let dirToMake = path.join(pathMigration,item)
if (!fs.existsSync(dirToMake)){
fs.mkdir(dirToMake, { recursive: true }, (err) => {
if (err) dialog.showErrorBox(`The ${dirToMake} folder isn't accessible, trying to create one : - ${err.message}`)
})
}
});
// The check succeeded
} catch (error) {
// The check failed
dialog.showErrorBox("The migration folder isn't accessible, trying to create one",error)
}
}
function SaveCustom(){
let toMigration = path.join(app.getPath('userData'),userResourcesPath)
let applicationDest = app.getAppPath()
try {
if (!fs.existsSync(toMigration)){
//nothing to Save, the folder to migrate isn't there
customResource()
}
userRScheme.forEach((item, i) => {
let dirToSaveTo = path.join(toMigration,item)
switch (item){
case 'decals':
fse.copySync(path.join(applicationDest,"/images/","cpsource"),dirToSaveTo)
break
case 'mblend':
fse.copySync(path.join(applicationDest,"/images/",item),dirToSaveTo)
break
case 'jsons':
fse.copySync(path.join(applicationDest,item,"mbcustom.json"),path.join(dirToSaveTo,`${userRfiles.microblends}.json`))
break
}
})
new Notification({title:'Save custom datas',body: "The custom datas in MLSB have been restored" }).show()
}catch(error){
dialog.showErrorBox("Saving Error",error)
}
}
//port datas from the previous version of MLSB
function restoreCustom(){
let fromMigration = path.join(app.getPath('userData'),userResourcesPath)
let applicationDest = app.getAppPath()
try {
if (!fs.existsSync(fromMigration)){
//nothing to restore, the folder three will be created
}else{
userRScheme.forEach((item, i) => {
let dirToVerify = path.join(fromMigration,item)
switch (item){
case 'decals':
fse.copySync(dirToVerify,path.join(applicationDest,"images","cpsource"))
break
case 'mblend':
fse.copySync(dirToVerify,path.join(applicationDest,"images",item))
break
case 'jsons':
fse.copySync(path.join(dirToVerify,`${userRfiles.microblends}.json`),path.join(applicationDest,item,"mbcustom.json"))
break
}
})
new Notification({title:'Restore custom datas',body: "The datas you had saved in your resource folder are now restored" }).show()
}
}catch(error){
dialog.showErrorBox("Restore Error ",error)
}
}
async function dirOpen(event,arg) {
const {canceled,filePaths } = await dialog.showOpenDialog({title:arg.title, properties: ['openDirectory'], defaultPath:path.normalize(arg.path)})
if (canceled){
return
}else{
return filePaths[0]
}
}
//Verify the folders to restore Materials from
customResource()
const createModal = (htmlFile, parentWindow, width, height, title='MlsetupBuilder', preferences,frameless=true) => {
let modal = new BrowserWindow({
width: width,
height: height,
modal: true,
parent: parentWindow,
webPreferences: preferences,
title: title
})
modal.menuBarVisible=false
modal.minimizable=false
modal.loadFile(htmlFile)
modal.once('ready-to-show', () => {
modal.show()
})
return modal;
}
const childWindow = (htmlFile, parentWindow, width, height, title='MlsetupBuilder', preferences, ico='') => {
let mywin = new BrowserWindow({
width: width,
height: height,
modal: false,
icon: ico,
parent: parentWindow,
webPreferences: preferences,
title: title,
alwaysOnTop : false
})
mywin.menuBarVisible=false
mywin.minimizable=true
mywin.loadFile(htmlFile)
mywin.once('ready-to-show', () => {
mywin.show()
})
return mywin;
}
const isMac = process.platform === 'darwin'
var wcliExecutable = new RegExp(/.+WolvenKit\.CLI\.exe$/)
var normals = new RegExp(/.+n\d{2}\.(xbm|png|dds)$/)
var buildMenu = wcliExecutable.test(preferences.get('paths.wcli'),'i');
function openSettings(){
createModal("apps/prefs.html",mainWindow,800,350,'Preferences', {preload: path.join(__dirname, 'apps/preloadpref.js')} );
}
const template = [
// { role: 'appMenu' }
...(isMac ? [{
label: app.name,
submenu: [{ role: 'about' },{ type: 'separator' },{ role: 'services' },{ type: 'separator' },{ role: 'hide' },{ role: 'hideOthers' },{ role: 'unhide' },{ type: 'separator' },{ role: 'quit' }]
}] : []),
// { role: 'fileMenu' }
{
label: 'File',
submenu: [
{
label: 'Mlsetup',
submenu: [
{label: 'Import', accelerator:'Ctrl+i', click: () =>{
mainWindow.webContents.send('preload:activate',"#importLink")
}},
{label: 'Export',accelerator: 'Ctrl+e', click: () =>{
mainWindow.webContents.send('preload:activate','#exportversions')
}}
]
},
{
label: 'Recent',
submenu:[]
},
{ type: 'separator' },
{label: '&Preferences', click: () =>{ openSettings() }},
{ type: 'separator' },
isMac ? { role: 'close' } : { role: 'quit' }
]
},
{
label: 'Edit',
submenu: [
{ role: 'undo' },
{ role: 'redo' },
{ type: 'separator' },
{ role: 'cut' },
{ role: 'copy' },
{ role: 'paste' },
...(isMac ? [
{ role: 'pasteAndMatchStyle' },{ role: 'delete' },{ type: 'separator' },{label: 'Speech',submenu: [{ role: 'startSpeaking' },{ role: 'stopSpeaking' }]}
] : [
{ role: 'delete' }
])
]
},
...(buildMenu ? [
{id:99, label: 'Build', submenu:[ {
label:'Repository',
click: () =>{
mainWindow.webContents.send('preload:openModal','uncook')
}
}, {
label:'Microblends',
click: () =>{
mainWindow.webContents.send('preload:openModal','micro')
}
}] }
] : [
{id:99, label: 'Build', submenu:[{label:'Setup first Wolvenkit CLI', enabled:false}] }
]),
// { role: 'viewMenu' }
{
label: 'View',
submenu: [
{label: 'Material Composer',accelerator: 'Ctrl+K',click:()=>{
childWindow("apps/materials.html",mainWindow,1200,800,'Material Composer', {preload: path.join(__dirname, 'apps/preloadmats.js')} );
}},
{label: 'Hairs tool',accelerator: 'Ctrl+H',click:()=>{ mainWindow.webContents.send('preload:openModal','hairs')}},
{label:'Microblend Lab',accelerator: 'Ctrl+B',click:()=>{ mainWindow.webContents.send('preload:openModal','micromanager')}},
{label:'Logs',click:()=>{ mainWindow.webContents.send('preload:openModal','log')}},
{label:'Websocket communicator', click: ()=>childWindow("apps/websocket.html",mainWindow,600,400,'Websocket communicator',{preload: path.join(__dirname,'apps/preloadws.js')})},
{type: 'separator' },{ role: 'reload' },{ role: 'forceReload' },{ type: 'separator' },{ role: 'resetZoom' },{ role: 'zoomIn' },{ role: 'zoomOut' },{ type: 'separator' },{ role: 'togglefullscreen' },{ role: 'toggleDevTools' },
]
},
{ label:'Utils',
submenu: [
{id:98,label:'My resources',click:()=>{
outside.openPath(path.join(app.getPath('userData'),userResourcesPath));
}},
{type: 'separator' },
{label:'Save custom resources',click:()=>{SaveCustom()}},
{label:'Restore custom resources',click:()=>{restoreCustom()}}
]
},
{ role: 'windowMenu' },
{
role: 'help',
submenu: [
{ label:'Documentation',
accelerator: 'F1',
click:()=>{
mainWindow.webContents.send('preload:openModal','help')
}
},
{ label:'Download Wolvenkit.CLI',
click:()=>{
//Download the stable version
mainWindow.webContents.downloadURL(`https://github.com/WolvenKit/WolvenKit/releases/download/8.14.0/WolvenKit.Console-8.14.0.zip`);
}
},
{
label:'Github Repository',
click:()=>{
outside.openExternal("https://github.com/Neurolinked/MlsetupBuilder");
}
},
{ type: 'separator' },
{
label:'Donations',
click:()=>{
outside.openExternal("https://ko-fi.com/neurolinked99888");
}
},
{ type: 'separator' },
{ label:'License',click: () =>{
mainWindow.webContents.send('preload:openModal','license')
}
}
]
}
]
const menu = Menu.buildFromTemplate(template)
Menu.setApplicationMenu(menu)
function createWindow (width,height) {
width = parseInt((width/100)*95)
// Create the browser window.
mainWindow = new BrowserWindow({
width: width,
height: height,
webPreferences: {
additionalArguments: [`--nonce=${hash.digest('base64')}`],
preload: path.join(__dirname, 'preload.js'),
webgl:true,
}
})
// and load the index.html of the app.
mainWindow.loadFile('index.html')
nativeTheme.themeSource = 'dark';
// Open the DevTools.
if (dev){
mainWindow.webContents.openDevTools()
}
}
const prefupdate = preferences.onDidAnyChange(()=>{
mainWindow.webContents.send('preload:upd_config',preferences.store)
})
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.whenReady().then(() => {
// Create a window that fills the screen's available work area.
const primaryDisplay = screen.getPrimaryDisplay()
const { width, height } = primaryDisplay.workAreaSize
createWindow(width,height)
app.on('activate', function () {
// On macOS it's common to re-create a window in the app when the
// dock icon is clicked and there are no other windows open.
if (BrowserWindow.getAllWindows().length === 0) createWindow(width,height)
})
const dotNetCorePath = `C:\\Program Files\\dotnet\\shared\\Microsoft.NETCore.App`;
fs.access(dotNetCorePath,fs.constants.R_OK,(error)=>{
if (error){
setTimeout(()=>{
mainWindow.webContents.send('preload:logEntry', "Yo Choom upgrade your Chrome!, you don't have .Net Core Framework 8.x.x on you. You cheap newbie !! to hit The Streets you need to Chippin' In!",true);
},3000);
}else{
//Some .Net is installed
try {
let matchDotNet = false;
const files = fs.readdir(dotNetCorePath, { withFileTypes: true },(err,files)=>{
if (err){
setTimeout(()=>{
mainWindow.webContents.send('preload:logEntry', error,true);
},3000);
}
for (const file of files){
if ((file.name.match(/^8\.+/)) && file.isDirectory() ){
matchDotNet = true;
}
}
if (!matchDotNet){
setTimeout(()=>{
mainWindow.webContents.send('preload:logEntry', "Choom you have some Chrome but not the right retroWare for the Job, you need .Net Core Framework 8.x.x to unCook datas. Got and get it!",true);
},3000);
}
});
} catch (error) {
console.log(error);
}
}
});
})
// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', function () {
if (process.platform !== 'darwin') app.quit()
})
app.on('browser-window-focus', () => {
globalShortcut.register("CommandOrControl+W", () => {
//stuff here
})
/*
globalShortcut.register("CommandOrControl+A",() => {
mainWindow.webContents.send('preload:activate', '#applytoMyLayer')
})
*/
})
app.on('browser-window-blur', () => {
globalShortcut.unregisterAll()
})
ipcMain.on('main:aimMicros',(event,configurations) =>{
lastMicroConf = configurations
aimWindow = createModal("apps/aiming.html",mainWindow,1380,802,'Microblends aiming', {preload: path.join(__dirname, 'apps/preloadaim.js')});
})
ipcMain.on('main:reloadAim',()=>{
aimWindow.webContents.send('preload:configure',lastMicroConf)
});
ipcMain.on('main:clickMenu',(event,menuVoice)=>{
if (menuVoice=='preferences'){
openSettings();
}
});
ipcMain.on('main:giveModels',(event) => {
//read custom models json file and try to inject it in the main body
fs.readFile(path.join(app.getPath('userData'),'customModels.json'),(err,contenutofile) =>{
if (err) {
event.returnValue = []
}else{
try{
customModels = JSON.parse(contenutofile)
event.returnValue = customModels
}catch(err){
mainWindow.webContents.send('preload:logEntry', "Not a readable content for the file of the custom models",true)
event.returnValue = []
}
}
})
})
async function AfileRead(userpath,flags,noRepo){
return new Promise((resolve, reject) => {
var modPath = preferences.get('paths.lastmod')
var hasDepot
if ((modPath!==undefined) && (modPath!='')){
var hasDepot = preferences.get('paths.lastmod')!=preferences.get('paths.depot') ? true : false
}else{
hasDepot = false;
}
var whereLoadFrom
if (/^[\w|\W]:\\.+/.test(userpath) || noRepo){
//custom loading
whereLoadFrom = path.normalize(userpath)
}else{
if (preferences.get('paths.depot')==''){
log.warn(`The Depot preference isn't configured`)
mainWindow.webContents.send('preload:logEntry', `No Depot setup, go to Preferences window and fix it`);
reject('No Depot');
}
whereLoadFrom = path.join(preferences.get('paths.depot'),userpath)
}
fs.readFile(whereLoadFrom,flags,(err,contentfile) =>{
if (err) {
if (err.code=='ENOENT'){
if (hasDepot){
mainWindow.webContents.send('preload:logEntry', `Missing file - ${whereLoadFrom}`,true);
mainWindow.webContents.send('preload:logEntry',`Trying in the last Mod Folder`);
fs.readFile(whereLoadFrom,flags,(err,contenutofile) =>{
if (err){
if (err.code=='ENOENT'){
if (whereLoadFrom){
mainWindow.webContents.send('preload:logEntry', `File not found in: ${whereLoadFrom}`,true)
}else{
mainWindow.webContents.send('preload:logEntry', `The searched file does not exists also in the Mod Path ${whereLoadFrom}`,true)
}
}
if (whereLoadFrom.match(new RegExp(/.+\.glb$/))){
mainWindow.webContents.send('preload:request_uncook')
}
reject(err);
}else{
mainWindow.webContents.send('preload:logEntry', 'File found in the Last Mod Folder, Yay!')
resolve(contenutofile)
}
})
}else{
//Extract the needed files
if (whereLoadFrom.match(new RegExp(/.+\.glb$/)) || whereLoadFrom.match(new RegExp(/.+\.Material\.json$/)) ){
mainWindow.webContents.send('preload:request_uncook')
}
reject(err);
}
}
reject(err);
mainWindow.webContents.send('preload:logEntry', `File opening error ${err.message}`)
}
mainWindow.webContents.send('preload:logEntry', `File loaded: ${whereLoadFrom}`);
resolve(contentfile);
})
})
}
ipcMain.handle('main:fileReading',async(event,path,flags,noRepo)=>{
const result = await AfileRead(path,flags,noRepo);
return result;
});
//read file on disk
ipcMain.on('main:asyncReadFile',(event,percorso,flags,no_repo)=>{
var modPath = preferences.get('paths.lastmod')
var hasDepot
if ((modPath!==undefined) && (modPath!='')){
var hasDepot = preferences.get('paths.lastmod')!=preferences.get('paths.depot') ? true : false
}else{
hasDepot = false;
}
var whereLoadFrom
if (/^[\w|\W]:\\.+/.test(percorso) || no_repo){
//custom loading
whereLoadFrom = path.normalize(percorso)
}else{
if (preferences.get('paths.depot')==''){
log.warn(`The Depot preference isn't configured`)
event.reply('preload:logEntry', `No Depot setup, go to Preferences window and fix it`);
event.returnValue = '';
return
}
whereLoadFrom = path.join(preferences.get('paths.depot'),percorso)
}
var a3dMatModel = whereLoadFrom.search(/^.+\.glb$/g)>-1 ? whereLoadFrom: ``; //path of the hypotethical material file
fs.readFile(whereLoadFrom,flags,(err,contenutofile) =>{
if (err) {
if (err.code=='ENOENT'){
if (hasDepot){
event.reply('preload:logEntry', `Missing file - ${whereLoadFrom}`,true);
event.reply('preload:logEntry',`Trying in the last Mod Folder`);
whereLoadFrom = path.join(preferences.get('paths.lastmod'),percorso)
fs.readFile(whereLoadFrom,flags,(err,contenutofile) =>{
if (err){
if (err.code=='ENOENT'){
if (whereLoadFrom){
event.reply('preload:logEntry', `File not found in: ${whereLoadFrom}`,true)
}else{
dialog.showErrorBox("File opening error",`The searched file does not exists also in the Depot ${whereLoadFrom}`)
event.reply('preload:logEntry', `Missing file - ${whereLoadFrom}`,true)
}
}
contenutofile=""
a3dMatModel="";
if (whereLoadFrom.match(new RegExp(/.+\.glb$/))){
mainWindow.webContents.send('preload:request_uncook')
}
}else{
event.reply('preload:logEntry', 'File found in the Last Mod Folder, Yay!')
}
})
}else{
if (normals.test(whereLoadFrom)){
event.reply('preload:logEntry', 'File not found in : '+whereLoadFrom,true)
}else{
a3dMatModel="";
if (whereLoadFrom.match(new RegExp(/.+\.glb$/))){
dialog.showErrorBox("File opening error","The searched file does not exists \n"+whereLoadFrom)
}
event.reply('preload:logEntry', 'Missing file - '+whereLoadFrom,true)
}
contenutofile = ""
if (whereLoadFrom.match(new RegExp(/.+\.glb$/)) || whereLoadFrom.match(new RegExp(/.+\.Material\.json$/)) ){
mainWindow.webContents.send('preload:request_uncook')
}
}
}else{
event.reply('preload:logEntry', `File opening error ${err.message}`)
a3dMatModel="";
}
contenutofile=""
}else{
event.reply('preload:logEntry', `File loaded: ${whereLoadFrom}`)
}
event.returnValue = contenutofile
})
})
//restored arguments reading
ipcMain.on('main:handle_args', (event, payload) => {
if (mljson!=""){
fs.stat(mljson,'utf8',function(err, stat) {
if (err) {
if (err.code=='ENOENT'){
dialog.showErrorBox("File opening error","The searched file does not exists")
}else{
dialog.showErrorBox("File opening error",err.message)
}
return
}else{
var mlsetup_content = ""
fs.readFile(mljson,'utf8',(err,data) =>{
try {
mlsetup_content = JSON.parse(data)
} catch(e) {
dialog.showErrorBox("File error","Reading error: wrong json file format")
mlsetup_content = ""
}
event.reply('preload:load_source',mlsetup_content, mljson)
})
}
})
}
//manage features for WolvenkitCLI
if (wkitto!=''){
if (/^\d+\.\d+\.\d+(-\w+)?\.\d{4}-\d{2}-\d{2}$/.test(wkitto)){
objwkitto={
full:wkitto,
major:Number(wkitto.split('.')[0]),
minor:Number(wkitto.split('.')[1]),
patches:Number(wkitto.split('.')[2].split('-')[0])
}
event.reply('preload:logEntry', 'MlsetupBuilder is working as Wolvenkit plugin')
event.reply('preload:wkitBuild',JSON.stringify(objwkitto))
}else if (/^\d+\.\d+\.\d+$/.test(wkitto)){
objwkitto={
full:wkitto,
major:Number(wkitto.split('.')[0]),
minor:Number(wkitto.split('.')[1]),
patches:Number(wkitto.split('.')[2])
}
event.reply('preload:logEntry', 'MlsetupBuilder is working as Wolvenkit plugin')
event.reply('preload:wkitBuild',JSON.stringify(objwkitto))
}else if (/^\d+\.\d+-rc\d+$/.test(wkitto)){
objwkitto={
full:wkitto,
major:Number(wkitto.split('.')[0]),
minor:Number(wkitto.split('.')[1].split('-')[0]),
patches:0
}
event.reply('preload:logEntry', 'MlsetupBuilder is working as Wolvenkit plugin')
event.reply('preload:wkitBuild',JSON.stringify(objwkitto))
}
}
})
//setup the version of the software where needed
ipcMain.on('main:getversion',(event, arg) =>{
event.reply('preload:setversion',app.getVersion())
/*
Since it's the first operation requested from the renderer
And it's expected the store to be already initialized, i will
test the values for Depot and Game Archives and if they are empty
i will look for the Wolvenkit configuration file, to setup the
preferences
*/
if (preferences.get('paths.depot')==""){
fs.readFile(path.normalize(wolvenkitPrefFile),(err,wolvenkitConfigHandle)=>{
if (err){
event.reply('preload:logEntry',`No traces of Wolvenkit installation`,false);
}else{
try {
var WolvenkitConfig = JSON.parse(wolvenkitConfigHandle)
if (WolvenkitConfig.hasOwnProperty('MaterialRepositoryPath')){
preferences.set(`paths.depot`,WolvenkitConfig.MaterialRepositoryPath);
}
if ((WolvenkitConfig.hasOwnProperty('CP77ExecutablePath')) && (preferences.get(`paths.game`)=='')) {
preferences.set(`paths.game`,WolvenkitConfig.CP77ExecutablePath.replace("\\bin\\x64\\Cyberpunk2077.exe",""))
}
} catch (error) {
event.reply('preload:logEntry',`The file is there, but i got an error:${error}`,false);
}
}
})
}
})
ipcMain.handle('main:fileCatch',fqfnFile)
ipcMain.handle('main:folderSetup',dirOpen)
//write the configuration file after the selection of the directory in the
//preference interface window
ipcMain.on('main:setupUnbundle',(event, arg) => {
const result = dialog.showOpenDialog({title:'Choose the unbundle folder', properties: ['openDirectory'],defaultPath:arg }).then(result => {
if (!result.canceled){
if (result!=undefined){
event.reply('preload:upd_config',{'value':result.filePaths[0],'id':'prefxunbundle'})
}else{
console.log('errore')
}
}
}).catch(err => {
dialog.showErrorBox("Preferences error",err.message)
})
})
ipcMain.on('main:pickWkitPorject',(ev)=>{
const result = dialog.showOpenDialog({
title:'Choose a Wolvenkit Project file',