-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
7322 lines (6588 loc) · 240 KB
/
Copy pathmain.js
File metadata and controls
7322 lines (6588 loc) · 240 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
// "electron": "^27.0.3",
//npm start
//npx electronmon .
//npm cache verify --force
//build: https://program-life.com/2041
//installer: npx electron-builder --mac --x64
//portable: npx electron-builder --mac --x64 --dir
//installer: npx electron-builder --win --x64
//portable: npx electron-builder --win --x64 --dir
//npm run build:win
//npm version prerelease --preid=beta
//npm version prerelease --preid=alpha
//npm version patch :1.0.0 → 1.0.1
//npm version minor :1.0.0 → 1.1.0
//npm version major :1.0.0 → 2.0.0
const path = require("path");
const fs = require("fs");
const os = require("os");
const sharp = require("sharp");
//const { mode } = require("simple-statistics");
const { parse } = require("csv-parse/sync");
const { stringify } = require("csv-stringify/sync");
const ProgressBar = require("electron-progressbar");
const prompt = require("electron-prompt");
const JSZip = require('jszip');
const zlib = require('zlib');
const { PassThrough } = require('stream');
const https = require('https');
const { autoUpdater} = require('electron-updater');
const { app, BrowserWindow, Menu, ipcMain, dialog, shell, screen, session, protocol } = require("electron");
const { LevelCompilerCore } = require("./LC_modules/LevelCompilerCore.js");
const { Project } = require("./LC_modules/Project.js");
const lcfnc = require("./LC_modules/lcfnc.js");
const { LevelCompilerAge } = require("./LC_modules/LevelCompilerAge.js");
const { LevelCompilerPlot } = require("./LC_modules/LevelCompilerPlot.js");
const { UndoManager } = require("./LC_modules/UndoManager.js");
const { Trinity } = require("./LC_modules/Trinity.js");
const { Section } = require("./LC_modules/Section.js");
const { Marker } = require("./LC_modules/Marker.js");
const {
WINDOW_TYPES,
clearWindow,
createWindow,
getAllWindows,
getWindow,
hasWindow,
setWindow,
} = require("./main/windows.js");
const { send, availableMemory, contextIsolated } = require("process");
const { Worker } = require('worker_threads');
const { isString } = require("util");
const { resolve } = require("dns");
const { rejects } = require("assert");
const { resolveObjectURL } = require("buffer");
const { encode, decode } = require("@msgpack/msgpack");
//mode properties
const isMac = process.platform === "darwin";
const isDev = false;//process.env.NODE_ENV !== "development"; //const isDev = false;
let isEditMode = false;
const isShowMinorError = false;
let isPlotterClose = true; //because plotter is hide by close button
//main properties
let LCCore = new LevelCompilerCore();
let LCAge = new LevelCompilerAge();;
let LCPlot = new LevelCompilerPlot();
const history = new UndoManager();
history.setInitialState(LCCore.exportSerialisedModel());
let labelerHistory = null;
let tempCore = null; //for labeler
let viewerCore = null; //for floating viewer
let globalPath = {
saveModelPath:null,
dataPaths:[], //{type:[lcmodel, csvmodel, csvage, csvplot], path:""}
};
let mainSettings = {isAutoUpdateDownload: true};
let globalTempData = null;
let sendBuffer = null;
let e2eCloseDialogResponse = null;
let e2eDialogResponses = [];
let e2eDialogLog = [];
let e2eOpenDialogResponse = {
file: null,
folder: null,
};
let isMainWindowClosing = false;
let suppressCoreAlertRenderer = false;
function withSuppressedCoreAlertRenderer(action) {
const previousValue = suppressCoreAlertRenderer;
suppressCoreAlertRenderer = true;
try {
return action();
} finally {
suppressCoreAlertRenderer = previousValue;
}
}
function closeProgress(progress) {
if (!progress) {
return null;
}
try {
if (typeof progress.isCompleted === "function" && !progress.isCompleted()) {
progress.setCompleted();
}
} catch (_) {}
try {
if (typeof progress.close === "function") {
progress.close();
}
} catch (_) {}
return null;
}
function closeGlobalProgressBar() {
progressBar = closeProgress(progressBar);
return true;
}
function getRendererDeveloperMode() {
const rendererSettings = getSettings("settingsRenderer");
return rendererSettings?.developer?.mode ?? "user";
}
function isRootDeveloperMode() {
return getRendererDeveloperMode() === "root";
}
function resetTransientAppState() {
globalTempData = null;
sendBuffer = null;
tempCore = null;
viewerCore = null;
labelerHistory = null;
}
function recordE2EDialog(options) {
if (process.env.LC_E2E !== "1") {
return;
}
e2eDialogLog.push({
title: options?.title ?? null,
message: options?.message ?? null,
buttons: Array.isArray(options?.buttons) ? [...options.buttons] : [],
});
}
async function showMessageBoxWithE2E(window, options) {
recordE2EDialog(options);
if (process.env.LC_E2E === "1" && e2eDialogResponses.length > 0) {
return { response: e2eDialogResponses.shift() };
}
return dialog.showMessageBox(window, options);
}
//windows
let mainWindow = null;
let finderWindow = null;
let dividerWindow = null;
let converterWindow = null;
let labelerWindow = null;
let settingsWindow = null;
let imageViewerWindow = null;
let plotWindow = null;
let progressBar = null;
// Stage 2 of the main-process refactor introduces a shared window store.
// Existing local variables remain in place temporarily, and later steps
// will switch callers over incrementally.
void WINDOW_TYPES;
void getAllWindows;
function syncLegacyWindowRef(type, windowRef) {
switch (type) {
case WINDOW_TYPES.MAIN:
mainWindow = windowRef;
break;
case WINDOW_TYPES.FINDER:
finderWindow = windowRef;
break;
case WINDOW_TYPES.DIVIDER:
dividerWindow = windowRef;
break;
case WINDOW_TYPES.CONVERTER:
converterWindow = windowRef;
break;
case WINDOW_TYPES.LABELER:
labelerWindow = windowRef;
break;
case WINDOW_TYPES.SETTINGS:
settingsWindow = windowRef;
break;
case WINDOW_TYPES.IMAGE_VIEWER:
imageViewerWindow = windowRef;
break;
case WINDOW_TYPES.PLOTTER:
plotWindow = windowRef;
break;
default:
break;
}
}
function getManagedWindow(type) {
return getWindow(type);
}
function setManagedWindow(type, windowRef) {
const storedWindow = setWindow(type, windowRef);
syncLegacyWindowRef(type, storedWindow);
return storedWindow;
}
function clearManagedWindow(type) {
syncLegacyWindowRef(type, null);
clearWindow(type);
}
function hasManagedWindow(type) {
return hasWindow(type);
}
function sendToManagedWindow(type, channel, payload = null) {
const currentWindow = getManagedWindow(type);
if (!currentWindow || currentWindow.isDestroyed()) {
return false;
}
const { webContents } = currentWindow;
if (!webContents || webContents.isDestroyed()) {
return false;
}
webContents.send(channel, payload);
return true;
}
function getMainWindow() {
return getManagedWindow(WINDOW_TYPES.MAIN);
}
function setMainWindow(windowRef) {
return setManagedWindow(WINDOW_TYPES.MAIN, windowRef);
}
function clearMainWindow() {
clearManagedWindow(WINDOW_TYPES.MAIN);
}
function hasMainWindow() {
return hasManagedWindow(WINDOW_TYPES.MAIN);
}
function getFinderWindow() {
return getManagedWindow(WINDOW_TYPES.FINDER);
}
function setFinderWindow(windowRef) {
return setManagedWindow(WINDOW_TYPES.FINDER, windowRef);
}
function clearFinderWindow() {
clearManagedWindow(WINDOW_TYPES.FINDER);
}
function hasFinderWindow() {
return hasManagedWindow(WINDOW_TYPES.FINDER);
}
function getDividerWindow() {
return getManagedWindow(WINDOW_TYPES.DIVIDER);
}
function setDividerWindow(windowRef) {
return setManagedWindow(WINDOW_TYPES.DIVIDER, windowRef);
}
function clearDividerWindow() {
clearManagedWindow(WINDOW_TYPES.DIVIDER);
}
function hasDividerWindow() {
return hasManagedWindow(WINDOW_TYPES.DIVIDER);
}
function getConverterWindow() {
return getManagedWindow(WINDOW_TYPES.CONVERTER);
}
function setConverterWindow(windowRef) {
return setManagedWindow(WINDOW_TYPES.CONVERTER, windowRef);
}
function clearConverterWindow() {
clearManagedWindow(WINDOW_TYPES.CONVERTER);
}
function hasConverterWindow() {
return hasManagedWindow(WINDOW_TYPES.CONVERTER);
}
function getLabelerWindow() {
return getManagedWindow(WINDOW_TYPES.LABELER);
}
function setLabelerWindow(windowRef) {
return setManagedWindow(WINDOW_TYPES.LABELER, windowRef);
}
function clearLabelerWindow() {
clearManagedWindow(WINDOW_TYPES.LABELER);
}
function hasLabelerWindow() {
return hasManagedWindow(WINDOW_TYPES.LABELER);
}
function getSettingsWindow() {
return getManagedWindow(WINDOW_TYPES.SETTINGS);
}
function setSettingsWindow(windowRef) {
return setManagedWindow(WINDOW_TYPES.SETTINGS, windowRef);
}
function clearSettingsWindow() {
clearManagedWindow(WINDOW_TYPES.SETTINGS);
}
function hasSettingsWindow() {
return hasManagedWindow(WINDOW_TYPES.SETTINGS);
}
function getImageViewerWindow() {
return getManagedWindow(WINDOW_TYPES.IMAGE_VIEWER);
}
function setImageViewerWindow(windowRef) {
return setManagedWindow(WINDOW_TYPES.IMAGE_VIEWER, windowRef);
}
function clearImageViewerWindow() {
clearManagedWindow(WINDOW_TYPES.IMAGE_VIEWER);
}
function hasImageViewerWindow() {
return hasManagedWindow(WINDOW_TYPES.IMAGE_VIEWER);
}
function getPlotterWindow() {
return getManagedWindow(WINDOW_TYPES.PLOTTER);
}
function setPlotterWindow(windowRef) {
return setManagedWindow(WINDOW_TYPES.PLOTTER, windowRef);
}
function clearPlotterWindow() {
clearManagedWindow(WINDOW_TYPES.PLOTTER);
}
function hasPlotterWindow() {
return hasManagedWindow(WINDOW_TYPES.PLOTTER);
}
function getAboutWindow() {
return getManagedWindow(WINDOW_TYPES.ABOUT);
}
function setAboutWindow(windowRef) {
return setManagedWindow(WINDOW_TYPES.ABOUT, windowRef);
}
function clearAboutWindow() {
clearManagedWindow(WINDOW_TYPES.ABOUT);
}
function hasAboutWindow() {
return hasManagedWindow(WINDOW_TYPES.ABOUT);
}
function closeConverterWindow() {
if (!hasConverterWindow()) {
return false;
}
const currentConverterWindow = getConverterWindow();
currentConverterWindow.removeAllListeners("close");
currentConverterWindow.close();
clearConverterWindow();
return true;
}
function closePlotterWindow() {
if (!hasPlotterWindow()) {
return false;
}
const currentPlotterWindow = getPlotterWindow();
currentPlotterWindow.removeAllListeners("close");
currentPlotterWindow.close();
clearPlotterWindow();
return true;
}
function closeDividerWindow() {
if (!hasDividerWindow()) {
return false;
}
const currentDividerWindow = getDividerWindow();
currentDividerWindow.removeAllListeners("close");
currentDividerWindow.close();
clearDividerWindow();
return true;
}
function closeFinderWindow() {
if (!hasFinderWindow()) {
return false;
}
const currentFinderWindow = getFinderWindow();
currentFinderWindow.removeAllListeners("close");
currentFinderWindow.close();
clearFinderWindow();
return true;
}
function openSettingsWindow({
browserWindowOptions = {},
onExisting = null,
onReadyToShow = null,
} = {}) {
if (hasSettingsWindow()) {
const settingsWindow = getSettingsWindow();
settingsWindow.focus();
if (typeof onExisting === "function") {
onExisting(settingsWindow);
}
return settingsWindow;
}
const settingsWindow = setSettingsWindow(createWindow(WINDOW_TYPES.SETTINGS, {
browserWindowOptions,
}));
settingsWindow.on("closed", () => {
clearSettingsWindow();
sendToMainWindow("SettingsClosed", "");
});
settingsWindow.once("ready-to-show", () => {
settingsWindow.show();
settingsWindow.setAlwaysOnTop(true, "floating");
if (typeof onReadyToShow === "function") {
onReadyToShow(settingsWindow);
}
});
return settingsWindow;
}
function openConverterWindow({
browserWindowOptions = {},
onExisting = null,
onReadyToShow = null,
onDidFinishLoad = null,
} = {}) {
if (hasConverterWindow()) {
const converterWindow = getConverterWindow();
converterWindow.focus();
if (typeof onExisting === "function") {
onExisting(converterWindow);
}
return converterWindow;
}
const converterWindow = setConverterWindow(createWindow(WINDOW_TYPES.CONVERTER, {
browserWindowOptions,
}));
converterWindow.on("closed", () => {
clearConverterWindow();
sendToMainWindow("ConverterClosed", "");
});
converterWindow.once("ready-to-show", () => {
converterWindow.show();
if (typeof onReadyToShow === "function") {
onReadyToShow(converterWindow);
}
});
converterWindow.webContents.once("did-finish-load", () => {
if (typeof onDidFinishLoad === "function") {
onDidFinishLoad(converterWindow);
}
});
return converterWindow;
}
function sendToMainWindow(channel, payload = null) {
return sendToManagedWindow(WINDOW_TYPES.MAIN, channel, payload);
}
function sendToFinderWindow(channel, payload = null) {
return sendToManagedWindow(WINDOW_TYPES.FINDER, channel, payload);
}
function sendToConverterWindow(channel, payload = null) {
return sendToManagedWindow(WINDOW_TYPES.CONVERTER, channel, payload);
}
function sendToSettingsWindow(channel, payload = null) {
return sendToManagedWindow(WINDOW_TYPES.SETTINGS, channel, payload);
}
function sendToImageViewerWindow(channel, payload = null) {
return sendToManagedWindow(WINDOW_TYPES.IMAGE_VIEWER, channel, payload);
}
function sendToLabelerWindow(channel, payload = null) {
return sendToManagedWindow(WINDOW_TYPES.LABELER, channel, payload);
}
function sendToPlotterWindow(channel, payload = null) {
return sendToManagedWindow(WINDOW_TYPES.PLOTTER, channel, payload);
}
function closeChildWindows() {
if (hasFinderWindow()) {
getFinderWindow().close();
}
if (hasDividerWindow()) {
getDividerWindow().close();
}
if (hasConverterWindow()) {
getConverterWindow().close();
}
if (hasLabelerWindow()) {
getLabelerWindow().close();
}
if (hasImageViewerWindow()) {
getImageViewerWindow().close();
}
if (hasSettingsWindow()) {
getSettingsWindow().close();
}
if (hasPlotterWindow()) {
getPlotterWindow().close();
}
}
function createMainWIndow() {
const mainWindow = setMainWindow(createWindow(WINDOW_TYPES.MAIN, { isDev }));
//open devtools if in dev env
if (isDev) {
mainWindow.webContents.openDevTools();
}
mainWindow.on('close', (event) => {
if (isMainWindowClosing) {
closeChildWindows();
return;
}
const historyList = history.getHistory();
const lastAction = historyList[historyList.length-1];
if(historyList.length>0 && !lastAction.name.includes("export lcmodel")){
event.preventDefault();
void (async () => {
const options = {
type: "question",
buttons: ["No", "Yes"],
defaultId: 0,
title: "Unsaved Changes",
message: "Unsaved changes to the model. Do you really want to exit?",
};
recordE2EDialog(options);
const response =
process.env.LC_E2E === "1" && e2eCloseDialogResponse !== null
? { response: e2eCloseDialogResponse }
: await showMessageBoxWithE2E(null, options);
e2eCloseDialogResponse = null;
console.log(response)
if(response.response === 0){
return;
}
isMainWindowClosing = true;
closeChildWindows();
if (hasMainWindow()) {
getMainWindow().close();
}
})();
return;
}
isMainWindowClosing = true;
closeChildWindows();
});
mainWindow.on("closed", () => {
clearMainWindow();
isMainWindowClosing = false;
});
//initialise
LCCore = initialiseLCCore();
//Implement menu
menuRebuild();
//===================================================================================================================================
//===================================================================================================================================
//IPC from renderer
//============================================================================================
//Initialise and load model data
ipcMain.handle("InitialiseCorrelationModel", async (_e) => {
//initialise
LCCore = initialiseLCCore();
history.setInitialState(LCCore.exportSerialisedModel());
resetTransientAppState();
const zipped = await zipData(LCCore.exportSerialisedModel());
console.log("MAIN: Project correlation data is initialised.");
return zipped;
});
ipcMain.handle("InitialiseAgeModel", async (_e) => {
//initialise
LCAge = new LevelCompilerAge();
LCCore.calcMarkerAges(LCAge);
resetTransientAppState();
console.log("MAIN: Project age data is initialised.");
return;
});
ipcMain.handle("initialisePlotDataCollection", async (_e) => {
//import modeln
LCPlot = initialiseLCPlotData();
//for mainwindow
getMainWindow().webContents.send("initialiseLCPlotData");
console.log("MAIN: Renderer LCPlot is initialised.");
//for plotter
const zipped = await zipData(LCPlot);
if (zipped && hasPlotterWindow()) {
sendToPlotterWindow("importedData", zipped);
console.log("MAIN: Plotter LCPlot is initialised.");
}
console.log("MAIN: ALL LCPlot is initialised.")
});
ipcMain.handle("InitialisePaths", async (_e) => {
//import modeln
initialiseGlobalPath();
resetTransientAppState();
console.log("MAIN: Paths are initialised.");
return;
});
//============================================================================================
//register and load model data
ipcMain.handle("RegisterModelFromCsv", async (_e, payload) => {
const { modelPath: model_path } = payload;
//get file path
let results = path.parse(model_path);
const fullpath = path.join(results.dir, results.base);
const result = registerModelFromCsv(fullpath);
return result
});
ipcMain.handle("RegistertAgeFromCsv", async (_e, payload) => {
const { agePath: age_path } = payload;
try {
//get file path
let results = path.parse(age_path);
const fullpath = path.join(results.dir, results.base);
//register
const res = registerAgeFromCsv(fullpath);
if(res==true){
//apply latest age model to the depth model
let model_name = null;
LCAge.AgeModels.forEach((model) => {
if (model.id == LCAge.selected_id) {
model_name = model.name;
}
});
return { id: LCAge.selected_id, name: model_name};
}
} catch (error) {
console.error("MAINE: Age model register error.");
console.log(error);
return null;
}
});
ipcMain.handle("RegisterLCmodel", async (_e, payload) => {
const { modelPath: model_path } = payload;
try {
//get file path
let results = path.parse(model_path);
const fullpath = path.join(results.dir, results.base);
const registeredAgeList = await registerLCModel(fullpath);
return registeredAgeList;
}catch(err){
console.log("MAIN: Failed to load LC model.",err);
return false
}
});
ipcMain.handle("LoadModelFromLCCore", async (_e) => {
//import model
try{
const zipped = await zipData(LCCore.exportSerialisedModel());
console.log("MAIN: Load correlation model.");
return zipped;
}catch(err){
console.error("MAIN: Failed to zip: ", err);
return null;
}
});
ipcMain.handle("LoadAgeFromLCAge", async (_e, payload) => {
const { ageId: age_id } = payload;
//apply latest age model to the depth model
let model_name = null;
//set new id
LCAge.selected_id = age_id;
//get model name
const ageModel = LCAge.getModelData();
if (ageModel == null) {
return null;
}
//load
model_name = ageModel.name;
//load ages into LCCore
LCCore.calcMarkerAges(LCAge);
//if(LCPlot.data_collections.length>0){
//const res = LCPlot.calcDataCollectionPosition(LCCore, LCAge);
//}
//LCAge.checkAges();
if(LCAge.unreliable_ids.length>0){
let txt = "Age model contains inverted chronological order.";
if(LCAge.use_unreliable_data==true){
txt +=" The Ages were forcibly calculated including inverted data.";
}else{
txt +=" The ages were calculated excluding inverted data.";
}
const err = {
status: 'Infomation',
statusDetails: txt,
hasError: false,
errorDetails: null,
}
getMainWindow().webContents.send("AlertRenderer", err);
}
//send data
try{
const zipped = await zipData(LCCore.exportSerialisedModel());
if(LCPlot.data_collections.length>0){
//initialise view
sendToPlotterWindow("initialiseSendData");
}
console.log("MAIN: Load age model into LCCore. id: " + LCAge.selected_id + " name:" + model_name);
return zipped;
}catch(err){
console.error("MAIN: Failed to zip: ", err);
return null;
}
});
ipcMain.handle("MirrorAgeList", async (_e) => {
let registeredAgeList = [];
for (let i = 0; i < LCAge.AgeModels.length; i++) {
//make new collection
const model_name = LCAge.AgeModels[i].name;
const model_id = LCAge.AgeModels[i].id;
registeredAgeList.push({ id: model_id, name: model_name});
}
console.log("MAIN: Mirrored age list");
return registeredAgeList;
});
ipcMain.handle("Reregister", async (_e) => {
const tempPath = JSON.parse(JSON.stringify(globalPath));
initialiseGlobalPath();
//re register LCModel
let targetList = tempPath.dataPaths.filter(item=>item.type=="lcmodel");
for(const data of targetList){
const fullpath = data.path;
if(fullpath !== undefined){
await registerLCModel(fullpath);
}
}
//re register CSV model
targetList = tempPath.dataPaths.filter(item=>item.type=="csvmodel");
for(const data of targetList){
const fullpath = data.path;
if(fullpath !== undefined){
const result = registerModelFromCsv(fullpath);
}
}
//calc
LCCore.calcCompositeDepth();
LCCore.calcEventFreeDepth();
//re register CsvAge
targetList = tempPath.dataPaths.filter(item=>item.type=="csvage");
for(const data of targetList){
const fullpath = data.path;
console.log(fullpath)
if(fullpath !== undefined){
const result = registerAgeFromCsv(fullpath);
}
}
//re register Images
targetList = tempPath.dataPaths.filter(item=>item.type=="core_images" || item.type=="image_source");
for(const data of targetList){
const fullpath = data.path;
if(fullpath !== undefined){
registerCoreImage(fullpath, data.type, null, {
sourceId: data.sourceId ?? "source_1",
label: data.label ?? "Image 1",
});
}
}
console.log("MAIN: Reload all model data.")
return ;
});
//============================================================================================
//file process
ipcMain.handle("getFilePath", async (_e, pathData) => {
//import modeln
let results = path.parse(pathData);
console.log(results)
results.fullpath = path.join(results.dir, results.base);
results.imagepath = path.join(results.dir, results.name+".jpg");//force to rename for labeler
return results;
});
ipcMain.handle("CheckImagesInDir", async (_e, payload) => {
const { fileName: name, projectName = null, sourceId = null } = payload;
let targetList = getRegisteredImageSources("core_images", sourceId);
//mainWindow.webContents.send("rendererLog", targetList);
let result = false;
for(const target of targetList){
const projectRoot = projectName ? path.join(target.path, projectName) : null;
const searchRoot = projectRoot && fs.existsSync(projectRoot) ? projectRoot : target.path;
const res = await findFileInDir(searchRoot, name, "check");
if(res==true){
result = true;
break;
}
}
return result;
});
ipcMain.handle("FileChoseDialog", async (_e, payload) => {
const result = await getfile(getMainWindow(), payload.title, payload.ext);
return result;
});
ipcMain.handle("FolderChoseDialog", async (_e, payload) => {
const result = await getDirectory(getMainWindow(), payload.title);
return result;
});
//============================================================================================
//image process
ipcMain.handle('RegisterCoreImage', (_e, payload) => {
const {
dirHandle: dir_handle,
type,
sourceId = "source_1",
label = "Image 1",
} = payload;
try{
//get file path
const pathData = path.parse(dir_handle);
if(pathData.dir==""){
console.log("MAIN: Failed to register core images.")
return false
}
let dirPath = null;
if (pathData.ext === ".zip") {
// if zip
dirPath = path.join(pathData.dir, pathData.base);
registerCoreImage(dirPath, type, null, { sourceId, label });
} else if(pathData.ext==""){
//case folder
dirPath = path.join(pathData.dir, pathData.name);
//register path
registerCoreImage(dirPath, type, null, { sourceId, label });
}else if(pathData.ext==".jpg"|| pathData.ext === ".jpeg"|| pathData.ext === ".tif"|| pathData.ext === ".tiff"|| pathData.ext === ".png"){
dirPath = pathData.dir;
//register path
registerCoreImage(dirPath, type, pathData.base, { sourceId, label });
}else if(pathData.ext==".lcsection"){
//lcsection from labeler
dirPath = pathData.dir;
//register path
registerCoreImage(dirPath, type, null, { sourceId, label });
}else{
return false
}
return true
}catch(err){
return false
}
});
ipcMain.handle("LoadCoreImage", async (_e, payload) => {
const { loadOptions, type } = payload;
//type: "core_images", "labeler"
const coreImages = await loadCoreImages(loadOptions, type);
return coreImages;
});
ipcMain.handle("UnregisterCoreImageSource", (_e, payload) => {
const sourceId = payload?.sourceId ?? "source_1";
const before = globalPath.dataPaths.length;
globalPath.dataPaths = globalPath.dataPaths.filter((item) => {
if (item.type !== "image_source" && item.type !== "core_images") {
return true;
}
const itemSourceId = item.sourceId ?? "source_1";
return itemSourceId !== sourceId;
});
return {
ok: true,
removed: before - globalPath.dataPaths.length,
sourceId,
};
});
async function loadCoreImages(loadOptions, type){
const isShowMemory = false;
const silentProgress = loadOptions.silentProgress === true;
if (!silentProgress) {
progressBar = progressDialog(getMainWindow(), "Load modeled section images", "Now converting...", false);
//await new Promise(r => progressBar.on('ready', r));
await new Promise(r => progressBar.once('ready', r));
}
//console.log(" Load core image called")
let releasedWorkers = 0;
let numTotalTasks = 0;
try {
if(loadOptions.targetIds.length==0){
return null
}
//initialise
let coreImages = {
sourceId: loadOptions.sourceId ?? "source_1",
tier: loadOptions.tier ?? "standard",
label: loadOptions.label ?? null,
load_target_ids: [],
operations:[],
image_resolution: {},
drilling_depth: {},
composite_depth: {},
event_free_depth: {},
age:{},
};
const hasSelectedAgeModel = LCAge?.AgeModels?.length > 0 && LCAge?.selected_id != null;
const effectiveOperations = (loadOptions.operations ?? []).filter((operation) => {
return operation !== "age" || hasSelectedAgeModel;
});
coreImages.operations = effectiveOperations;
//get registered image folder path
let targetList = getRegisteredImageSources(type, loadOptions.sourceId);
if(targetList.length < 1){
console.log("MAIN: There is no registered image folders.")