forked from asoronow/belljar
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.js
1066 lines (1029 loc) · 34.3 KB
/
main.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
"use strict";
var __awaiter =
(this && this.__awaiter) ||
function (thisArg, _arguments, P, generator) {
function adopt(value) {
return value instanceof P
? value
: new P(function (resolve) {
resolve(value);
});
}
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) {
try {
step(generator.next(value));
} catch (e) {
reject(e);
}
}
function rejected(value) {
try {
step(generator["throw"](value));
} catch (e) {
reject(e);
}
}
function step(result) {
result.done
? resolve(result.value)
: adopt(result.value).then(fulfilled, rejected);
}
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var url = require("url");
const util = require("util");
const os = require("os");
const { app, BrowserWindow, ipcMain, dialog, shell } = require("electron");
const { promisify } = require("util");
const { PythonShell } = require("python-shell");
const path = require("path");
const fs = require("fs");
const tar = require("tar");
const mv = promisify(fs.rename);
const exec = promisify(require("child_process").exec);
const stream = require("stream");
const https = require("https");
const semver = require("semver");
const serverFetch = require("node-fetch");
const { spawn } = require("child_process");
const axios = require("axios");
const remoteMain = require("@electron/remote/main");
const ws = require("windows-shortcuts");
const fsExt = require('fs-ext');
var appDir = app.getAppPath();
var win = null;
var logWin = null;
var isQuitting = false;
var log = console.log;
console.log = function () {
var args = Array.from(arguments);
let timestamp = new Date()
.toISOString()
.replace(/T/, " ")
.replace(/\..+/, "");
let prefix = `[${timestamp}]`;
let message = [prefix, ...args];
log.apply(console, message);
try {
logWin.webContents.send("log", message.join(" "));
} catch (error) {
// do nothing window was closed
}
};
// Path variables for easy management of execution
const homeDir = path.join(app.getPath("home"), "ImSwitch");
// Make a constant with the cwd for running python commands
const envPath = path.join(homeDir, "benv");
// Path to our python files
const CURRENT_VERSION_TAG = getVersion();
const GITHUB_API_RELEASES =
"https://api.github.com/repos/openuc2/imswitch/releases/latest";
const serverFetchTimedOut = (url, options = {}, time = 1000) => {
return new Promise((resolve, reject) => {
serverFetch(url, options).then(resolve).catch(reject);
if (time) {
const e = new Error("Server Timeout: " + url);
setTimeout(reject, time, e);
}
});
};
async function checkForUpdates() {
try {
const GITHUB_API_RELEASES =
"https://api.github.com/repos/openuc2/imswitchinstaller/releases/latest";
const CURRENT_VERSION_TAG = "current-version-tag"; // Define your current version tag
const response = await axios.get(GITHUB_API_RELEASES);
if (response.status !== 200) {
throw new Error(`GitHub API response status: ${response.status}`);
}
const data = response.data;
const latestVersionTag = data.tag_name;
//if (semver.valid(latestVersionTag) && semver.gt(latestVersionTag, CURRENT_VERSION_TAG)) {
const userResponse = await dialog.showMessageBox({
type: "info",
title: "Update Available",
message: "A new version of the ImSwitch Installer is available.",
detail: `The latest version is ${latestVersionTag}. Would you like to download it?`,
buttons: ["Yes", "No"],
defaultId: 0,
cancelId: 1,
});
if (userResponse.response === 0) {
shell.openExternal(data.html_url); // URL to the latest release page
}
/*} else {
console.log('No updates available.');
}*/
} catch (error) {
console.error("Failed to check for updates:", error);
dialog.showErrorBox(
"Update Check Failed",
"There was an error checking for updates. Please try again later."
);
}
}
// Promise version of file moving
function move(o, t) {
return new Promise((resolve, reject) => {
// move o to t, wrapped as promise
const original = o;
const target = t;
mv(original, target).then(() => {
resolve(0);
});
});
}
function createLogFile(message) {
const logPath = path.join(homeDir, "imswitch.log");
fs.appendFileSync(logPath, message);
}
// Convert fs.unlink into a Promise-based function
const unlinkAsync = util.promisify(fs.unlink);
const TIMEOUT = 30000;
//https://stackoverflow.com/questions/11944932/how-to-download-a-file-with-node-js-without-using-third-party-libraries
function downloadFile(url, dest) {
const uri = new URL(url);
console.log("Download file: ", uri.pathname);
if (!dest) {
dest = basename(uri.pathname);
}
const pkg = url.toLowerCase().startsWith("https:") ? https : http;
// check if file exists, if so, return a promise that resolves immediately
if (fs.existsSync && fs.existsSync(dest)) {
console.log(`${dest} already exists`);
return Promise.resolve();
}
return new Promise((resolve, reject) => {
console.log("Downloading: ", url);
const request = pkg.get(uri.href).on("response", (res) => {
if (res.statusCode === 200) {
console.log("Status 200");
const file = fs.createWriteStream(dest, { flags: "wx" });
res
.on("end", () => {
file.end();
console.log(`${uri.pathname} downloaded to: ${dest}`);
resolve();
})
.on("error", (err) => {
file.destroy();
fs.unlink(dest, () => reject(err));
log.error(err);
})
.pipe(file);
} else if (res.statusCode === 302 || res.statusCode === 301) {
// Recursively follow redirects, only a 200 will resolve.
console.log("Redirecting to: ", res.headers.location);
downloadFile(res.headers.location, dest).then(() => resolve());
} else {
reject(
new Error(
`Download request failed, response status: ${res.statusCode} ${res.statusMessage}`
)
);
}
});
request.setTimeout(TIMEOUT, function () {
request.abort();
reject(new Error(`Request timeout after ${TIMEOUT / 1000.0}s`));
});
});
}
// Delete a file safely
function deleteFile(file) {
return new Promise((resolve, reject) => {
fs.unlinkSync(file);
resolve(true);
});
}
function getVersion() {
// get version from package.json
const packageJson = require(path.join(appDir, "package.json"));
return packageJson.version;
}
// const osxURL = "https://github.com/conda-forge/miniforge/releases/latest/download/Miniforge3-$(uname)-$(uname -m).sh"
function setupMamba(win) {
return new Promise((resolve, reject) => {
let miniforgeURL = "";
let miniforgeScriptName = "";
if (os.platform == "darwin" && os.arch == "arm64") {
let miniforgeScriptName = `Miniforge3-${os.platform()}-${os.arch()}.sh`;
miniforgeURL = `https://github.com/conda-forge/miniforge/releases/latest/download/${miniforgeScriptName}`;
} else if (os.platform == "darwin" && os.arch == "x64") {
miniforgeScriptName = `Mambaforge-23.11.0-0-MacOSX-x86_64.sh`;
miniforgeURL =
"https://github.com/conda-forge/miniforge/releases/download/23.11.0-0/Mambaforge-23.11.0-0-MacOSX-x86_64.sh";
} else if (os.platform == "win32") {
miniforgeScriptName = `Miniforge3-Windows-x86_64.exe`;
miniforgeURL = `https://github.com/conda-forge/miniforge/releases/latest/download/${miniforgeScriptName}`;
}
if (!fs.existsSync(path.join(homeDir, "miniforge"))) {
win.webContents.send("updateStatus", "Setting up Mamba via Miniforge...");
console.log("Setting up Mamba via Miniforge...");
downloadFile(miniforgeURL, path.join(homeDir, miniforgeScriptName), win)
.then(() => {
console.log("Setting up Mamba via Miniforge...");
win.webContents.send(
"updateStatus",
"Installing Mamba locally in: " + homeDir
);
const scriptPath = path.join(homeDir, miniforgeScriptName);
let installCommand = `bash ${scriptPath} -b -p ${homeDir}/miniforge`;
if (os.platform() === "win32") {
// Silent installation for Windows
installCommand = `${scriptPath} /InstallationType=JustMe /RegisterPython=0 /AddToPath=0 /S /D=${homeDir}\\miniforge`;
}
const fd = fs.openSync(scriptPath, "r+");
fsExt.flock(fd, "exnb", (err) => {
if (err) {
if (err.code === "EWOULDBLOCK") {
console.error(
"The file will be used in a different process already?."
);
return;
}
throw err;
}
exec(installCommand, (error, stdout, stderr) => {
if (error) {
win.webContents.send(
"updateStatus",
"Error in installing Miniforge."
);
console.error(`exec error: ${error}`);
console.error(stderr);
return reject(error);
}
win.webContents.send(
"updateStatus",
"Miniforge installed successfully."
);
console.log(stdout);
resolve(true);
});
fsExt.flock(fd, "un", (err) => {
if (err) throw err;
fs.closeSync(fd);
});
});
})
.catch((error) => {
console.error("Download error:", error);
reject(error);
});
} else {
// Check if Miniforge is already set up
if (os.platform == "win32") {
if (fs.existsSync(path.join(homeDir, "miniforge"))) {
resolve(true);
} else {
resolve(false);
}
} else {
if (fs.existsSync(path.join(homeDir, "miniforge", "bin", "mamba"))) {
resolve(true);
} else {
resolve(false);
}
}
}
});
}
function setupPython(win) {
const bucketParentPath = "https://storage.googleapis.com/belljar_updates";
const linuxURL = `${bucketParentPath}/cpython-3.10.13+20230826-x86_64-unknown-linux-gnu-install_only.tar.gz`;
const winURL = `${bucketParentPath}/cpython-3.10.13+20230826-x86_64-pc-windows-msvc-shared-install_only.tar.gz`;
const osxURL = `${bucketParentPath}/cpython-3.10.13+20230826-aarch64-apple-darwin-install_only.tar.gz`;
const osxIntelURL = `${bucketParentPath}/cpython-3.10.13+20230826-x86_64-apple-darwin-install_only.tar.gz`;
return new Promise((resolve, reject) => {
if (!fs.existsSync(path.join(homeDir, "python"))) {
win.webContents.send("updateStatus", "Settting up python...");
switch (process.platform) {
case "win32":
// Download and extract python to the home directory
downloadFile(
winURL,
path.join(
homeDir,
"cpython-3.10.13+20230826-x86_64-pc-windows-msvc-shared-install_only.tar.gz"
),
win
)
.then(() => {
// Extract the tarball
tar
.x({
cwd: homeDir,
preservePaths: true,
file: path.join(
homeDir,
"cpython-3.10.13+20230826-x86_64-pc-windows-msvc-shared-install_only.tar.gz"
),
})
.then(() => {
win.webContents.send("updateStatus", "Extracted python...");
resolve(true);
});
})
.catch((err) => {
console.log(err);
});
break;
case "linux":
downloadFile(
linuxURL,
path.join(
homeDir,
"cpython-3.10.13+20230826-x86_64-unknown-linux-gnu-install_only.tar.gz"
),
win
).then(() => {
tar
.x({
cwd: homeDir,
preservePaths: true,
file: path.join(
homeDir,
"cpython-3.10.13+20230826-x86_64-unknown-linux-gnu-install_only.tar.gz"
),
})
.then(() => {
win.webContents.send("updateStatus", "Extracted python...");
resolve(true);
});
});
break;
case "darwin":
// Check if we are on intel or arm
if (process.arch === "x64") {
downloadFile(
osxIntelURL,
path.join(
homeDir,
"cpython-3.10.13+20230826-x86_64-apple-darwin-install_only.tar.gz"
),
win
).then(() => {
tar
.x({
cwd: homeDir,
preservePaths: true,
file: path.join(
homeDir,
"cpython-3.10.13+20230826-x86_64-apple-darwin-install_only.tar.gz"
),
})
.then(() => {
win.webContents.send("updateStatus", "Extracted python...");
resolve(true);
});
});
} else {
downloadFile(
osxURL,
path.join(
homeDir,
"cpython-3.10.13+20230826-aarch64-apple-darwin-install_only.tar.gz"
),
win
).then(() => {
tar
.x({
cwd: homeDir,
preservePaths: true,
file: path.join(
homeDir,
"cpython-3.10.13+20230826-aarch64-apple-darwin-install_only.tar.gz"
),
})
.then(() => {
win.webContents.send("updateStatus", "Extracted python...");
resolve(true);
});
});
}
break;
default:
// If we don't have a supported platform, just resolve
resolve(true);
break;
}
} else {
// Double check that the environment is setup by confirming if the benv folder exists
if (!fs.existsSync(envPath)) {
resolve(true);
} else {
resolve(false);
}
}
});
}
// Download the required tar files from the bucket
function downloadResources(win, fresh) {
// Download the tar files into the homeDir and extract them to their respective folders
const currnet_versions = {
nrrd: "v91",
models: "v93",
embeddings: "v6",
};
return new Promise((resolve, reject) => {
const bucketParentPath = "https://storage.googleapis.com/belljar_updates";
const embeddingsLink = `${bucketParentPath}/embeddings-v6.tar.gz`;
const modelsLink = `${bucketParentPath}/models-v93.tar.gz`; // Update to v7
const nrrdLink = `${bucketParentPath}/nrrd-v91.tar.gz`;
const requiredDirs = ["models", "embeddings", "nrrd"];
if (!fresh) {
var downloading = [];
var total = 0;
// check the manifest.json and compare versions
// if the versions are different, delete the dir and download
const manifestPath = path.join(homeDir, "manifest.json");
// Make sure the manifest exists and if not lets make one and then delte all these dirs and redownload
if (!fs.existsSync(manifestPath)) {
// Create manifest from current versions
fs.writeFileSync(
manifestPath,
JSON.stringify(currnet_versions, null, 2)
);
// Delete existing
downloading.push("models");
downloading.push("embeddings");
downloading.push("nrrd");
}
const manifest = require(manifestPath);
// check if each directory exists and its not empty
for (let i = 0; i < requiredDirs.length; i++) {
const dir = requiredDirs[i];
if (
!fs.existsSync(path.join(homeDir, dir)) ||
fs.readdirSync(path.join(homeDir, dir)).length === 0
) {
// make sure we are not already downloading this dir
if (downloading.indexOf(dir) === -1) {
downloading.push(dir);
}
}
}
for (const [key, value] of Object.entries(currnet_versions)) {
if (manifest[key] !== value) {
downloading.push(key);
}
}
if (downloading.indexOf("models") === -1) {
// Check in the models dir if chaosdruid.pt exists do nothing, otherwise delete the dir and download
if (!fs.existsSync(path.join(homeDir, "models/chaosdruid.pt"))) {
downloading.push("models");
// Delete existing
if (fs.existsSync(path.join(homeDir, "models"))) {
fs.rm(path.join(homeDir, "models"), { recursive: true });
}
}
}
// Delete and update manifest
if (downloading.length > 0) {
fs.writeFileSync(
manifestPath,
JSON.stringify(currnet_versions, null, 2)
);
}
downloading.reduce((promiseChain, dir, i) => {
return promiseChain
.then(() => {
win.webContents.send(
"updateStatus",
`Redownloading ${dir}...this may take a while`
);
if (fs.existsSync(path.join(homeDir, dir))) {
fs.rmSync(path.join(homeDir, dir), { recursive: true });
}
let downloadPath = "";
switch (dir) {
case "models":
downloadPath = modelsLink;
break;
case "embeddings":
downloadPath = embeddingsLink;
break;
case "nrrd":
downloadPath = nrrdLink;
break;
default:
break;
}
return downloadFile(
downloadPath,
path.join(homeDir, `${dir}.tar.gz`),
win
);
})
.then(() => {
return tar.x({
cwd: homeDir,
preservePaths: true,
file: path.join(homeDir, `${dir}.tar.gz`),
});
})
.then(() => {
return deleteFile(path.join(homeDir, `${dir}.tar.gz`));
})
.then(() => {
win.webContents.send("updateStatus", `Downloaded ${dir}`);
total++;
if (downloading.length === total) {
resolve(true);
}
});
}, Promise.resolve());
if (downloading.length === 0) {
resolve(true);
}
} else {
// Since we are doing a fresh install, we need to ensure no remnants of the old install are left or partially downloaded
// Check if these directories exist, if they do, we don't need to download any files
let allDirsExist = true;
requiredDirs.forEach((dir) => {
if (!fs.existsSync(path.join(homeDir, dir))) {
allDirsExist = false;
}
});
// Creat the manifest
fs.writeFileSync(
path.join(homeDir, "manifest.json"),
JSON.stringify(currnet_versions, null, 2)
);
if (!allDirsExist) {
// Something is missing, delete everything and download again
requiredDirs.forEach((dir) => {
if (fs.existsSync(path.join(homeDir, dir))) {
fs.rmSync(path.join(homeDir, dir), { recursive: true });
}
});
// Download the embeddings
downloadFile(
embeddingsLink,
path.join(homeDir, "embeddings.tar.gz"),
win
).then(() => {
// Extract the embeddings
tar
.x({
cwd: homeDir,
preservePaths: true,
file: path.join(homeDir, "embeddings.tar.gz"),
})
.then(() => {
// Delete the tar file
deleteFile(path.join(homeDir, "embeddings.tar.gz")).then(() => {
// Download the models
downloadFile(
modelsLink,
path.join(homeDir, "models.tar.gz"),
win
).then(() => {
// Extract the models
tar
.x({
cwd: homeDir,
preservePaths: true,
file: path.join(homeDir, "models.tar.gz"),
})
.then(() => {
// Delete the tar file
deleteFile(path.join(homeDir, "models.tar.gz")).then(
() => {
// Download the nrrd
downloadFile(
nrrdLink,
path.join(homeDir, "nrrd.tar.gz"),
win
).then(() => {
// Extract the nrrd
tar
.x({
cwd: homeDir,
preservePaths: true,
file: path.join(homeDir, "nrrd.tar.gz"),
})
.then(() => {
// Delete the tar file
deleteFile(
path.join(homeDir, "nrrd.tar.gz")
).then(() => {
resolve(true);
});
});
});
}
);
});
});
});
});
});
} else {
resolve(true);
}
}
});
}
function setupMambaEnv(win) {
const envName = "imswitch";
var miniforgePath, mambaPath, pipPath, imswitchPath, pythonPath;
if (os.platform == "win32") {
miniforgePath = path.join(homeDir, "miniforge");
mambaPath = path.join(miniforgePath, "condabin", "mamba");
pipPath = path.join(miniforgePath, "Scripts", "pip"); // Adjust for Windows if necessary
pythonPath = path.join(miniforgePath, "python");
imswitchPath = path.join(miniforgePath, "Lib", "site-packages", "imswitch");
} else {
miniforgePath = path.join(homeDir, "miniforge");
mambaPath = path.join(miniforgePath, "bin", "mamba");
pipPath = path.join(miniforgePath, "bin", "pip");
pythonPath = path.join(miniforgePath, "bin", "python");
imswitchPath = path.join(miniforgePath, "site-packages", "imswitch");
}
/*
Install git via mamba
*/
win.webContents.send("updateStatus", "Installing git with mamba...");
runCommand(`${mambaPath}`, [`install`, `git`, `-y`], win).then(() => {
win.webContents.send("updateStatus", "Installing git via mamba...");
return runCommand(`${mambaPath}`, [`install`, `git`], win);
});
/*
Install UC2-REST and ImSwitch from github master
*/
if (
!fs.existsSync(path.join(miniforgePath)) ||
!fs.existsSync(path.join(imswitchPath))
) {
// win.webContents.send("updateStatus", "Creating Mamba environment...");
// runCommand(`${mambaPath}`, [`create`, `-n`, `${envName}`, '-y'], win)
//runCommand(`${mambaPath} create -n ${envName} -y`)
// .then(() => {
win.webContents.send(
"updateStatus",
"Installing UC2-REST packages with pip. This may take a while..."
);
runCommand(
`${pipPath}`,
[`install`, `https://github.com/openUC2/UC2-REST/archive/master.zip`],
win
)
.then(() => {
win.webContents.send(
"updateStatus",
"Installing UC2-ImSwitch packages with pip. This may take a while..."
);
return runCommand(
`${pipPath}`,
[`install`, `https://github.com/openUC2/ImSwitch/archive/master.zip`],
win
);
})
.then(() => {
// create an icon
// for windows
if (os.platform == "win32") {
const iconPath = path.join(homeDir, "build", "icon.ico");
const args = "-m imswitch";
const shortcutPath = path.join(
require("os").homedir(),
"Desktop",
"ImSwitchUC2.lnk"
);
ws.create(
shortcutPath,
{
pythonPath,
args,
icon: iconPath,
},
(err) => {
if (err) {
console.error("Failed to create shortcut:", err);
} else {
console.log("Shortcut created successfully!");
}
}
);
} else if (os.platform == "darwin") {
// TODO: Not working yet
const appPath = "/Applications/ImSwitch.app"; // Path to your application
const desktopPath = path.join(require("os").homedir(), "Desktop");
const shortcutCommand = `osascript -e 'tell application "Finder" to make alias file to POSIX file "${appPath}" at POSIX file "${desktopPath}"'`;
exec(shortcutCommand, (error, stdout, stderr) => {
if (error) {
console.error(`exec error: ${error}`);
return;
}
console.log("Shortcut created on desktop");
});
}
})
.then(() => {
win.webContents.send("updateStatus", "Setup complete!");
win.loadFile("pages/index.html");
})
.catch((error) => {
console.log("An error occurred during setup:", error);
win.webContents.send("updateStatus", "An error occurred during setup.");
});
} else {
win.webContents.send("updateStatus", "Setup complete!");
win.loadFile("pages/index.html");
}
}
function runCommand(command, args, win) {
return new Promise((resolve, reject) => {
console.log("Executing: " + command + " " + args.join(" "));
// Spawn the process
const process = spawn(command, args);
// Handle standard output
process.stdout.on("data", (data) => {
console.log(`stdout: ${data}`);
win.webContents.send("commandOutput", data.toString());
});
// Handle standard error
process.stderr.on("data", (data) => {
console.error(`stderr: ${data}`);
win.webContents.send("commandError", data.toString());
});
// Handle error
process.on("error", (error) => {
console.error(`exec error: ${error}`);
reject(error);
});
// Handle process exit
process.on("close", (code) => {
console.log(`child process exited with code ${code}`);
if (code === 0) {
resolve();
} else {
reject(new Error(`Process exited with code ${code}`));
}
});
});
}
function runCommandExec(command, win) {
console.log("Executing: " + command);
return new Promise((resolve, reject) => {
exec(command, (error, stdout, stderr) => {
if (error) {
console.error(`exec error: ${error}`);
console.log(`Error: ${error.message}`);
return reject(error);
}
if (stderr) {
console.error(`stderr: ${stderr}`);
console.log(`Standard Error: ${stderr}`);
}
console.log(stdout);
console.log("commandOutput" + stdout);
resolve(stdout);
});
});
}
// Ensure all required directories exist and if not, download them
function fixMissingDirectories(win) {
return new Promise((resolve, reject) => {
win.webContents.send("updateStatus", "Checking for updatess...");
downloadResources(win, false).then(() => {
resolve(true);
});
});
}
// Makes the local user writable folder
// TODO: Version checking to see if we need to update the files
function checkLocalDir() {
if (!fs.existsSync(homeDir)) {
fs.mkdirSync(homeDir, {
recursive: true,
});
}
}
function createWindow() {
const win = new BrowserWindow({
width: 1250,
height: 750,
resizable: true,
autoHideMenuBar: true,
webPreferences: { nodeIntegration: true, contextIsolation: false },
});
remoteMain.enable(win.webContents);
// Start with the load screen
win.loadFile("pages/loading.html");
return win;
}
function createLogWindow() {
const logWin = new BrowserWindow({
width: 500,
height: 250,
resizable: true,
autoHideMenuBar: true,
webPreferences: { nodeIntegration: true, contextIsolation: false },
closeable: false,
});
logWin.loadFile("pages/log.html");
return logWin;
}
app.on("ready", () => {
win = createWindow();
logWin = createLogWindow();
// Uncomment if you want tools on launch
// win.webContents.toggleDevTools()
win.on("close", function (e) {
const choice = dialog.showMessageBoxSync(win, {
type: "question",
buttons: ["Yes", "Cancel"],
title: "Confrim Quit",
message:
"Are you sure you want to quit? Quitting will kill all running processes.",
});
if (choice === 1) {
e.preventDefault();
} else {
try {
logWin.webContents.send("savelogs", []);
logWin.close();
} catch (error) {
// do nothing window was closed
}
}
});
checkForUpdates();
win.webContents.once("did-finish-load", () => {
// Make a directory to house enviornment, settings, etc.yarn
checkLocalDir();
// Setup python for running the pipeline
//setupPython(win)
setupMamba(win)
.then((installed) => {
// If we just installed python, we need to continue the complete
// setup of the enviornment
if (installed) {
//setupEnvironment(win);
setupMambaEnv(win);
} else {
// Otherwise, we can just update the dependencies
updatePythonDependencies(win).then(() => {
// Check for new patch
// Check if any directories are missing
fixMissingDirectories(win).then(() => {
win.loadFile("pages/index.html");
});
});
}
})
.catch((error) => {
// Python install failed
console.log(error);
});
});
});
app.whenReady().then(() => {
app.on("activate", function () {
if (BrowserWindow.getAllWindows().length === 0) createWindow();
});
});
app.on("window-all-closed", function () {
app.quit();
});
ipcMain.on("getVersion", (event) => {
event.sender.send("version", getVersion());
});
// Handlers
// Directories
ipcMain.on("openDialog", function (event, data) {
let window = BrowserWindow.getFocusedWindow();
dialog
.showOpenDialog(window, {
properties: ["openDirectory"],
})
.then((result) => {
// Check for a valid result
if (!result.canceled) {
// console.log(result.filePaths)
// Send back the dir and whether this is input or output
event.sender.send("returnPath", [result.filePaths[0], data]);
}
})
.catch((err) => {
console.log(err);
});
});
// Files
ipcMain.on("openFileDialog", function (event, data) {
let window = BrowserWindow.getFocusedWindow();
dialog
.showOpenDialog(window, {
properties: ["openFile"],
})
.then((result) => {
// Check for a valid result
if (!result.canceled) {
// console.log(result.filePaths)
// Send back the dir and whether this is input or output
event.sender.send("returnPath", [result.filePaths[0], data]);
}
})
.catch((err) => {
console.log(err);
});
});
// downloadHIK
ipcMain.on("downloadHIK", function (event, data) {
console.log("Downloading HIK");
// if windows we need to download the windows version
if (os.platform == "win32") {
const hikURL =
"https://www.hikrobotics.com/cn2/source/support/software/MVS_STD_4.3.0_23.1225.zip";
shell.openExternal(hikURL);
}
// if linux we need to download the linux version
if (os.platform == "linux") {
const hikURL =
"https://www.hikrobotics.com/cn2/source/support/software/MVS_STD_4.3.0_23.1225.zip";
shell.openExternal(hikURL);
}
// if mac we need to download the mac version
if (os.platform == "darwin") {
const hikURL =
"https://www.hikrobotics.com/en2/Hikrobotics/Machine%20Vision/02%20Support/01%20Software/MVS_STD_GML_V2.0.0_221024.zip";
shell.openExternal(hikURL);
}
});
// downloadDaheng
ipcMain.on("downloadDaheng", function (event, data) {
console.log("Downloading Daheng");
const dahengURL =
"https://dahengimaging.com/downloads/Galaxy_Windows_EN_32bits-64bits_1.24.2308.9101.zip";
shell.openExternal(dahengURL);
});