forked from openframeworks/projectGenerator
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
1571 lines (1377 loc) · 51.4 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const fs = require('fs');
const path = require('path');
const moniker = require('moniker');
const process = require('process');
const os = require("os");
const exec = require('child_process').exec;
const {
app,
BrowserWindow,
dialog,
ipcMain,
Menu,
crashReporter,
shell,
} = require('electron');
//---------------------------------------------------------
// Report crashes to our server.
crashReporter.start({
uploadToServer: false,
productName: 'openFrameworks ProjectGenerator frontend',
});
// Debugging: start the Electron PG from the terminal to see the messages from console.log()
// Example: /path/to/PG/Contents/MacOS/Electron /path/to/PG/Contents/Ressources/app
// Note: app.js's console.log is also visible from the WebKit inspector. (look for mainWindow.openDevTools() below )
//--------------------------------------------------------- load settings
/**
* @typedef {{
* defaultOfPath: string,
* advancedMode: boolean,
* defaultPlatform: string,
* showConsole: boolean,
* showDeveloperTools: boolean,
* defaultRelativeProjectPath: string,
* useDictionaryNameGenerator: boolean
* }} Settings
*/
/** @type Settings */
let settings = {};
/** @type Settings */
const templateSettings = {
defaultOfPath: "",
advancedMode: false,
defaultPlatform: '',
showConsole: false,
showDeveloperTools: false,
defaultRelativeProjectPath: "apps/myApps",
useDictionaryNameGenerator: true
};
/**
* Determines the current platform based on process information.
* @returns {string} The platform identifier.
*/
function getCurrentPlatform() {
let platform = "unknown";
if (/^win/.test(process.platform)) {
platform = 'windows';
} else if (process.platform === "darwin") {
platform = 'osx';
} else if (process.platform === "linux") {
if (process.arch === 'ia32') {
platform = 'linux';
} else if (process.arch === 'arm') {
if (os.cpus()[0].model.indexOf('ARMv6') === 0) {
platform = 'linuxarmv6l';
} else {
platform = 'linuxaarch64';
}
} else if (process.arch === 'x64') {
platform = 'linux64';
} else {
platform = 'linux';
}
}
return platform;
}
const hostplatform = getCurrentPlatform();
/**
* Determines the default template for a given platform.
* @param {string} platformId - The platform identifier.
* @returns {string} The default template for the platform.
*/
function getDefaultTemplateForPlatform(platformId) {
const defaultTemplates = {
"osx": "OS X (Xcode)",
"vs": "Windows (Visual Studio)",
"msys2": "Windows (msys2/mingw)",
"ios": "iOS (Xcode)",
"macos": "Mega iOS/tvOS/macOS (Xcode)",
"android": "Android (Android Studio)",
"linux64": "Linux 64 (VS Code/Make)",
"linuxarmv6l": "Arm 32 (VS Code/Make)",
"linuxaarch64": "Arm 64 (VS Code/Make)",
"vscode": "VS Code",
"vs2019": "Windows (Visual Studio 2019)",
};
return defaultTemplates[platformId] || "Unknown Template";
}
// Example usage:
const platformId = getCurrentPlatform();
const defaultTemplate = getDefaultTemplateForPlatform(platformId);
console.log(`Detected platform: ${platformId}`);
console.log(`Default template: ${defaultTemplate}`);
try {
const settingsJsonString = fs.readFileSync(path.resolve(__dirname, 'settings.json'), 'utf-8');
settings = JSON.parse(settingsJsonString);
console.log(settings);
if (!settings.defaultPlatform) {
settings.defaultPlatform = getDefaultTemplateForPlatform(getCurrentPlatform());
}
} catch (e) {
// automatic platform detection
let myPlatform = "Unknown";
if (/^win/.test(process.platform)) {
myPlatform = 'vs';
}
// TODO: make the difference between osx and ios
else if (process.platform === "darwin") {
myPlatform = 'osx';
} else if (process.platform === "linux") {
myPlatform = 'linux';
if (process.arch === 'ia32') {
myPlatform = 'linux';
} else if (process.arch === 'arm') {
if (os.cpus()[0].model.indexOf('ARMv6') == 0) {
myPlatform = 'linuxarmv6l';
} else {
myPlatform = 'linuxaarch64';
}
} else if (process.arch === 'x64') {
myPlatform = 'linux64';
}
}
settings = {
defaultOfPath: "",
advancedMode: false,
defaultPlatform: myPlatform,
showConsole: false,
showDeveloperTools: false,
defaultRelativeProjectPath: "apps/myApps",
useDictionaryNameGenerator: true,
};
}
for(const key in templateSettings) {
if(!settings.hasOwnProperty(key)) {
settings[key] = templateSettings[key];
}
}
console.log("detected platform: " + hostplatform + " in " + __dirname);
const randomName = moniker.choose();
console.log(`Randomly generated name: ${randomName}`);
// Get the current working directory
const currentDir = process.cwd();
console.log(`Current working directory: ${currentDir}`);
// Get the platform information
const platform = os.platform();
console.log(`Operating system platform: ${platform}`);
// // Read a file using fs
// const filePath = path.join(__dirname, 'example.txt');
// fs.readFile(filePath, 'utf8', (err, data) => {
// if (err) {
// console.error(`Error reading file: ${err.message}`);
// } else {
// console.log(`File contents: ${data}`);
// }
// });
// Execute a shell command using exec
exec('ls', (error, stdout, stderr) => {
if (error) {
console.error(`Error executing command: ${error.message}`);
return;
}
if (stderr) {
console.error(`Error in command output: ${stderr}`);
return;
}
console.log(`Command output: ${stdout}`);
});
// hide some addons, per https://github.com/openframeworks/projectGenerator/issues/62
const addonsToSkip = [
"ofxiOS",
"ofxMultiTouch",
"ofxEmscripten",
"ofxAccelerometer",
"ofxAndroid"
];
const platforms = {
"osx": "OS X (Xcode)",
"vs": "Windows (Visual Studio)",
"msys2": "Windows (msys2/mingw)",
"ios": "iOS (Xcode)",
"macos": "Mega iOS/tvOS/macOS (Xcode)",
"android": "Android (Android Studio)",
"linux64": "Linux 64 (VS Code/Make)",
"linuxarmv6l": "Arm 32 (VS Code/Make)",
"linuxaarch64": "Arm 64 (VS Code/Make)",
"vscode": "VS Code"
};
const bUseMoniker = settings["useDictionaryNameGenerator"];
const templates = {
"emscripten": "Emscripten",
"gitignore": "Git Ignore",
"gl3.1": "Open GL 3.1",
"gl3.2": "Open GL 3.2",
"gl3.3": "Open GL 3.3",
"gl4.0": "Open GL 4.0",
"gl4.1": "Open GL 4.1",
"gl4.2": "Open GL 4.2",
"gl4.3": "Open GL 4.3",
"gl4.4": "Open GL 4.4",
"gl4.5": "Open GL 4.5",
"gles2": "Open GL ES 2",
"linux": "Linux", // !!??
"msys2": "MSYS2/MinGW project template",
"nofmod": "OSX application with no FMOD linking",
"nowindow": "No window application",
"tvOS": "Apple tvOS template",
"unittest": "Unit test no window application",
"vscode": "Visual Studio Code",
"vs2019": "Visual Studio 2019",
};
let defaultOfPath = settings["defaultOfPath"];
if (!path.isAbsolute(defaultOfPath)) {
// todo: this needs to be PLATFORM specific b/c of where things are placed.
// arturo, this may differ on linux, if putting ../ in settings doesn't work for the default path
// take a look at this...
if (hostplatform == "windows" || hostplatform == "linux" || hostplatform == "linux64" ){
defaultOfPath = path.resolve(path.join(path.join(__dirname, "../../../"), defaultOfPath));
} else if(hostplatform == "osx"){
defaultOfPath = path.resolve(path.join(path.join(__dirname, "../../../"), defaultOfPath));
}
settings["defaultOfPath"] = defaultOfPath || "";
}
// now, let's look for a folder called mySketch, and keep counting until we find one that doesn't exist
const startingProject = getStartingProjectName();
//---------------------------------------------------------
// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is GCed.
let mainWindow = null;
// Quit when all windows are closed.
app.on('window-all-closed', () => {
app.quit();
process.exit();
});
/**
* @param {Date} date
* @returns {string}
*/
function formatDate(date){
//get the year
const year = date.getFullYear().toString().substring(2, 4);
//get the month
const month = (date.getMonth() + 1).toString().padStart(2, '0');
//get the day
const day = date.getDate().toString().padStart(2, '0');;
//return the string "MMddyy"
return month + day + year;
}
/**
* @param {number} num
* @returns {string}
*/
function toLetters(num) {
const mod = num % 26;
let pow = (num / 26) | 0;
const out = mod ? String.fromCharCode(96 + (num % 26)) : (--pow, 'z');
return pow ? toLetters(pow) + out : out;
}
//-------------------------------------------------------- window
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
app.on('ready', () => {
// Create the browser window.
mainWindow = new BrowserWindow({
width: 600,
height: 800,
resizable: true, // TODO: fix to false, true for debug
frame: false,
webPreferences: {
//preload: path.join(__dirname, 'preload.js'),
nodeIntegration: true,
contextIsolation: false,
}
});
// and load the index.html of the app.
mainWindow.loadFile(path.join(__dirname, 'index.html'));
// Open the devtools.
if (settings["showDeveloperTools"]) {
mainWindow.webContents.openDevTools();
}
//when the window is loaded send the defaults
mainWindow.webContents.on('did-finish-load', () => {
//refreshAddonList();
mainWindow.webContents.send('cwd', app.getAppPath());
mainWindow.webContents.send('cwd', __dirname);
mainWindow.webContents.send('cwd', process.resourcesPath);
mainWindow.webContents.send('setStartingProject', startingProject);
mainWindow.webContents.send('setDefaults', settings);
mainWindow.webContents.send('setup', '');
mainWindow.webContents.send('checkOfPathAfterSetup', '');
});
// Emitted when the window is closed.
mainWindow.on('closed', () => {
mainWindow = null;
app.quit();
process.exit();
// Dereference the window object, usually you would store windows
// in an array if your app supports multi windows, this is the time
// when you should delete the corresponding element.
});
const isMac = process.platform === 'darwin'
const menuTemplate = [
...(isMac ? [{
label: app.name,
submenu: [
{ role: 'about' },
{ type: 'separator' },
{ role: 'services' },
{ type: 'separator' },
{ role: 'hide' },
{ role: 'hideOthers' },
{ role: 'unhide' },
{ type: 'separator' },
{ role: 'quit' }
]
}] : []),
{
label: 'File',
submenu: [
isMac ? { role: 'close' } : { role: 'quit' }
]
}, {
label: 'View',
submenu: [
{ role: 'reload' },
{ role: 'forceReload' },
{ role: 'toggleDevTools' },
{ type: 'separator' },
{ role: 'resetZoom' },
{ role: 'zoomIn' },
{ role: 'zoomOut' },
{ type: 'separator' },
{ role: 'togglefullscreen' }
]
}, {
label: 'Edit',
submenu: [
{ role: 'undo' },
{ role: 'redo' },
{ type: 'separator' },
{ role: 'cut' },
{ role: 'copy' },
{ role: 'paste' },
...(isMac ? [
{ role: 'pasteAndMatchStyle' },
{ role: 'delete' },
{ role: 'selectAll' },
{ type: 'separator' },
{
label: 'Speech',
submenu: [
{ role: 'startSpeaking' },
{ role: 'stopSpeaking' }
]
}
] : [
{ role: 'delete' },
{ type: 'separator' },
{ role: 'selectAll' }
])
]
}, {
label: 'Window',
submenu: [
{ role: 'minimize' },
{ role: 'zoom' },
...(isMac ? [
{ type: 'separator' },
{ role: 'front' },
{ type: 'separator' },
{ role: 'window' }
] : [
{ role: 'close' }
])
]
},
];
// @ts-ignore
const menuV = Menu.buildFromTemplate(menuTemplate); // TODO: correct this
Menu.setApplicationMenu(menuV);
});
/**
* @returns {{path: string, name: string}}
*/
function getStartingProjectName() {
const {
defaultOfPath,
defaultRelativeProjectPath
} = settings;
console.log(defaultOfPath, defaultRelativeProjectPath);
const defaultPathForProjects = path.join(defaultOfPath, defaultRelativeProjectPath);
const goodName = getGoodSketchName(defaultPathForProjects);
return {
path: defaultPathForProjects,
name: goodName
};
}
/**
* @param {Electron.IpcMainEvent} event
* @param {string} ofPathValue
*/
function refreshAddonList(event, ofPathValue) {
try {
console.log("in refreshAddonList " + ofPathValue);
// Define the path to the addons directory
const addonsPath = path.join(ofPathValue, "addons");
// Get the list of directories in the addons folder
let addons = getDirectories(addonsPath, "ofx");
// Filter out any addons that are in the addonsToSkip list
if (addons) {
if (addons.length > 0) {
addons = addons.filter((addon) => addonsToSkip.indexOf(addon) === -1);
}
}
console.log("Reloading the addons folder, these were found:");
console.log(addons);
// Send the list of addons to the renderer process
event.sender.send('setAddons', addons);
event.returnValue = true;
} catch (error) {
// Log the error
console.error("Error in refreshAddonList:", error);
// Send an error message to the renderer process
event.sender.send('sendUIMessage', {
type: 'error',
message: 'An error occurred while refreshing the addon list. Please check the console for more details.',
error: error.message,
});
// Return false as the operation was unsuccessful
event.returnValue = false;
}
}
/**
* @param {Electron.IpcMainEvent} event
* @param {string} ofPathValue
*/
function refreshPlatformList(event, ofPathValue) {
const folders = getDirectories(path.join(ofPathValue, "scripts", "templates"));
console.log("Reloading the templates folder, these were found:");
console.log(folders);
const platformsWeHave = {};
const templatesWeHave = {};
if (folders == null) {
//do something
} else {
// check all folder name under /scripts/templates
for (const id in folders) {
const key = folders[id];
if (platforms[key]) {
// this folder is for platform
console.log("Found platform, key " + key + " has value " + platforms[key]);
platformsWeHave[key] = platforms[key];
} else {
// this folder is for template
if(templates[key]){
console.log("Found template folder, key " + key + " has value " + templates[key]);
templatesWeHave[key] = templates[key];
} else {
// Unofficial folder name, maybe user's custom template?
// We use folder name for both of key and value
console.log("Found unofficial folder, key " + key + " has value " + key);
templatesWeHave[key] = key;
}
}
}
}
// saninty check...
// for(const key in platformsWeHave){
// console.log("key " + key + " has value " + platformsWeHave[key]);
// }
mainWindow.webContents.send('setPlatforms', platformsWeHave);
mainWindow.webContents.send('setTemplates', templatesWeHave);
}
/**
* @param {string} currentProjectPath
* @returns {string}
*/
function getGoodSketchName(currentProjectPath) {
let goodName = "mySketch";
try {
if (bUseMoniker) {
const projectNames = new moniker.Dictionary();
projectNames.read(path.join(__dirname, 'static', 'data', 'sketchAdjectives.txt'));
while (true) {
if (fs.existsSync(path.join(currentProjectPath, goodName))) {
console.log("«" + goodName + "» already exists, generating a new name...");
const adjective = projectNames.choose();
console.log(adjective);
goodName = "my" + adjective.charAt(0).toUpperCase() + adjective.slice(1) + "Sketch";
} else {
break;
}
}
} else {
const date = new Date();
const formattedDate = formatDate(date);
goodName = "sketch_" + formattedDate;
let count = 1;
while (true) {
if (fs.existsSync(path.join(currentProjectPath, goodName))) {
console.log("«" + goodName + "» already exists, generating a new name...");
goodName = "sketch_" + formattedDate + toLetters(count);
count++;
} else {
break;
}
}
}
} catch (error) {
console.error("Error in getGoodSketchName:", error);
goodName = "mySketch_Fallback"; // Fallback name in case of an error
}
return goodName;
}
/**
* @param {string} srcpath
* @param {string} [acceptedPrefix]
* @returns {string[] | null}
*/
function getDirectories(srcpath, acceptedPrefix) {
// because this is called at a different time, fs and path
// seemed to be "bad" for some reason...
// that's why I am making temp ones here.
// console.log(path);
try {
return fs.readdirSync(srcpath).filter((file) => {
//console.log(srcpath);
//console.log(file);
try{
const joinedPath = path.join(srcpath, file);
if ((acceptedPrefix == null || file.substring(0, acceptedPrefix.length) == acceptedPrefix) && joinedPath !== null) {
// only accept folders (potential addons)
return fs.statSync(joinedPath).isDirectory();
}
} catch(e) {
}
});
} catch (e) {
console.log(e);
return null;
// if (e.code === 'ENOENT') {
// console.log("This doesn't seem to be a valid addons folder:\n" + srcpath);
// mainWindow.webContents.send('sendUIMessage', "No addons were found in " + srcpath + ".\nIs the OF path correct?");
// } else {
// throw e;
// }
}
}
// todo: default directories
//----------------------------------------------------------- ipc
ipcMain.on('isOFProjectFolder', (event, project) => {
const {
projectPath,
projectName
} = project;
const folder = path.join(projectPath, projectName);
try {
const tmpFiles = fs.readdirSync(folder);
if (!tmpFiles || tmpFiles.length <= 1) {
return false;
} // we need at least 2 files/folders within
// todo: also check for config.make & addons.make ?
let foundSrcFolder = false;
let foundAddons = false;
let foundConfig = false;
tmpFiles.forEach((el, i) => {
if (el == 'src') {
foundSrcFolder = true;
}
if (el == 'addons.make') {
foundAddons = true;
}
if(el == 'config.make'){
foundConfig = true;
}
});
if (foundSrcFolder) {
event.sender.send('setGenerateMode', 'updateMode');
if (foundAddons) {
let projectAddons = fs.readFileSync(path.resolve(folder, 'addons.make')).toString().split("\n");
projectAddons = projectAddons.filter((el) => {
if (el === '' || el === 'addons') {
return false;
} // eleminates these items
else {
return true;
}
});
// remove comments
projectAddons = projectAddons.map((element) => element.split('#')[0]);
// console.log('addons', projectAddons);
event.sender.send('selectAddons', projectAddons);
} else {
event.sender.send('selectAddons', {});
}
if(foundConfig){
let projectExtra = fs.readFileSync(path.resolve(folder, 'config.make')).toString().split("\n");
projectExtra = projectExtra.filter((el) => {
if (el === '' || el[0] === '#') {
return false;
} // eleminates these items
else {
console.log("got a good element " + el );
return true;
}
});
//read the valid lines
let extraSrcPathsCount = 0;
projectExtra.forEach((el, i) => {
//remove spaces
const line = el.replace(/ /g, '');
//split either on = or +=
let splitter = "+=";
let n = line.indexOf(splitter);
let macro, value;
if( n != -1 ){
macro = line.substring(0, n);
value = line.substring(n + splitter.length);
} else {
splitter = "=";
n = line.indexOf(splitter);
if( n != -1 ){
macro = line.substring(0, n);
value = line.substring(n + splitter.length);
}
}
if( macro != null && value != null && macro.length && value.length) {
// this is where you can do things with the macro/values from the config.make file
console.log("Reading config pair. Macro: " + macro + " Value: " + value);
if(macro.startsWith('PROJECT_EXTERNAL_SOURCE_PATHS')) {
event.sender.send('setSourceExtraPath', [value, extraSrcPathsCount]);
extraSrcPathsCount++;
}
}
});
}
} else {
event.sender.send('setGenerateMode', 'createMode');
}
/*if (joinedPath != null){
// only accept folders (potential addons)
return fs.statSync(joinedPath).isDirectory();
}*/
} catch (e) { // error reading dir
event.sender.send('setGenerateMode', 'createMode');
if (e.code === 'ENOENT') { // it's not a directory
return false;
} else {
throw e;
}
}
});
ipcMain.on('refreshAddonList', refreshAddonList);
ipcMain.on('refreshPlatformList', refreshPlatformList);
ipcMain.on('refreshTemplateList', (event, arg) => {
console.log("refreshTemplateList");
const { selectedPlatforms, ofPath, bMulti } = arg;
const supportedPlatforms = [];
try {
for (const template in templates) {
const configFilePath = path.join(ofPath, "scripts", "templates", template, "template.config");
if (fs.existsSync(configFilePath)) {
const lineByLine = require('n-readlines');
const liner = new lineByLine(configFilePath);
let line;
let bFindPLATOFORMS = false;
while (line = liner.next()) {
let line_st = line.toString();
if (line_st.includes('PLATFORMS')) {
line_st = line_st.replace('PLATFORMS', '');
line_st = line_st.replace('=', '');
let platforms = line_st.trim().split(' ');
supportedPlatforms[template] = platforms;
bFindPLATOFORMS = true;
break;
}
}
if (!bFindPLATOFORMS) {
supportedPlatforms[template] = 'enable';
}
} else {
supportedPlatforms[template] = 'enable';
}
}
const invalidTemplateList = [];
for (const template in supportedPlatforms) {
const platforms = supportedPlatforms[template];
if (platforms !== 'enable') {
const bValidTemplate = selectedPlatforms.every(p => platforms.indexOf(p) > -1);
if (!bValidTemplate) {
console.log("Selected platform [" + selectedPlatforms + "] does not support template " + template);
invalidTemplateList.push(template);
}
}
}
const returnArg = { invalidTemplateList, bMulti };
mainWindow.webContents.send('enableTemplate', returnArg);
} catch (error) {
console.error("Error in processing templates:", error);
}
}); // This closing was missing
ipcMain.on('getRandomSketchName', (event, projectPath) => {
const goodName = getGoodSketchName(projectPath);
event.returnValue = { randomisedSketchName: goodName, generateMode: 'createMode' };
//event.sender.send('setRandomisedSketchName', goodName);
// event.sender.send('setGenerateMode', 'createMode'); // it's a new sketch name, we are in create mode
});
function getPgPath() {
let pgApp = "";
try {
if (hostplatform == "linux" || hostplatform == "linux64") { // ???: when appear there linux64?
pgApp = path.join(defaultOfPath, "apps/projectGenerator/commandLine/bin/projectGenerator");
//pgApp = "projectGenerator";
} else {
pgApp = path.normalize(path.join(__dirname, "app", "projectGenerator"));
}
if (hostplatform == 'osx' || hostplatform == 'linux' || hostplatform == 'linux64') {
pgApp = pgApp.replace(/ /g, '\\ ');
} else {
pgApp = "\"" + pgApp + "\"";
}
} catch (error) {
console.error("Error determining project generator path:", error);
pgApp = ""; // Return an empty string or some default path in case of error
}
return pgApp;
}
/** @typedef {{
* updatePath: string,
* platformList: Array<string>,
* templateList: Array<string>,
* ofPath: string,
* updateRecursive: boolean,
* verbose: boolean
* }} UpdateArgument */
/**
* @param {Electron.IpcMainEvent} event
* @param {UpdateArgument} update
*/
function updateFunction(event, update) {
console.log(update);
let updatePathString = "";
let pathString = "";
let platformString = "";
let templateString = "";
let recursiveString = "";
let verboseString = "";
const {
updatePath,
platformList,
templateList,
ofPath,
updateRecursive,
verbose
} = update;
if (updatePath != null) {
updatePathString = `"${updatePath}"`;
}
if (platformList != null) {
platformString = `-p"${platformList.join(",")}"`;
}
if (templateList != null) {
const uniqueTemplates = [...new Set(templateList)];
templateString = `-t"${uniqueTemplates.join(",")}"`;
}
if (ofPath != null) {
pathString = `-o"${ofPath}"`;
}
if (updateRecursive == true) {
recursiveString = "-r";
}
if (verbose == true) {
verboseString = "-v";
}
const pgApp = getPgPath();
const wholeString = [
pgApp,
recursiveString,
verboseString,
pathString,
platformString,
templateString,
updatePathString
].join(" ");
exec(wholeString, { maxBuffer : Infinity }, (error, stdout, stderr) => {
if (error === null) {
event.sender.send('consoleMessage', "<strong>" + wholeString + "</strong><br>" + stdout);
event.sender.send('sendUIMessage',
'<strong>Success!</strong><br>' +
'Updating your project was successful! <a href="file:///' + updatePath + '" class="monospace" data-toggle="external_target">' + updatePath + '</a><br><br>' +
'<button class="btn btn-default console-feature" onclick="$(\'#fullConsoleOutput\').toggle();">Show full log</button><br>' +
'<div id="fullConsoleOutput"><br><textarea class="selectable">' + stdout + '\n\n\n(command used:' + wholeString + ')\n\n\n</textarea></div>'
);
//
event.sender.send('updateCompleted', true);
} else {
event.sender.send('consoleMessage', "<strong>" + wholeString + "</strong><br>" + error.message);
event.sender.send('sendUIMessage',
'<strong>Error...</strong><br>' +
'There was a problem updating your project... <span class="monospace">' + updatePath + '</span>' +
'<div id="fullConsoleOutput" class="not-hidden"><br><textarea class="selectable">' + error.message + '\n\n\n(command used:' + wholeString + ')\n\n\n</textarea></div>'
);
}
});
console.log(wholeString);
//console.log(__dirname);
}
ipcMain.on('update', updateFunction);
/** @typedef {{
* projectName: string,
* projectPath: string,
* sourcePath: string,
* platformList: Array<string>,
* templateList: Array<string>,
* addonList: Array<string>,
* ofPath: string,
* verbose: boolean,
* }} GenerateArgument */
/**
* @param {Electron.IpcMainEvent} event
* @param {GenerateArgument} generate
*/
function generateFunction(event, generate) {
let projectString = "";
let pathString = "";
let addonString = "";
let platformString = "";
let templateString = "";
let verboseString = "";
let sourceExtraString = "";
const {
platformList,
templateList,
addonList,
ofPath,
sourcePath,
verbose,
projectPath,
projectName,
} = generate;
if (platformList != null) {
platformString = `-p"${platformList.join(",")}"`;
}
if (templateList != null) {
templateString = `-t"${templateList.join(",")}"`;
}
if (addonList != null &&
Array.isArray(addonList) &&
addonList.length > 0)
{
addonString = `-a"${addonList.join(",")}"`;
} else {
addonString = '-a" "';