-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patheditor.pde
executable file
·1844 lines (1512 loc) · 62.9 KB
/
editor.pde
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
import java.util.Base64;
import de.humatic.dsj.DSCapture;
import processing.video.Capture;
//import java.awt.image.BufferedImage;
import java.util.concurrent.atomic.AtomicInteger;
class CameraException extends RuntimeException {};
abstract class EditorCapture {
public int width, height;
protected TWEngine engine;
public AtomicBoolean ready = new AtomicBoolean(false);
public AtomicBoolean error = new AtomicBoolean(false);
public AtomicInteger errorCode = new AtomicInteger(0);
public int selectedCamera = 0;
public abstract void setup();
public abstract void turnOffCamera();
public abstract void switchNextCamera();
public abstract PImage updateImage();
}
class PCapture extends EditorCapture {
private String[] cameraDevices = null;
private Capture capture = null;
private PImage currCapture = null;
public PCapture(TWEngine e) {
ready.set(false);
error.set(false);
engine = e;
currCapture = engine.display.errorImg;
}
public void setup() {
ready.set(false);
error.set(false);
try {
cameraDevices = Capture.list();
if (cameraDevices.length <= 0) {
error.set(true);
errorCode.set(Editor.ERR_NO_CAMERA_DEVICES);
return;
}
if (cameraDevices == null) {
//engine.console.log("Unable to get cameras, but I'll try to start default camera anyway...");
//boolean failed = false;
//try {
// capture = new Capture(engine.app);
// if (capture == null) {
// failed = true;
// }
//}
//catch (Exception e) {
// failed = true;
//}
//if (failed) {
// engine.console.warn("I tried. Unable to start default camera.");
// error.set(true);
// errorCode.set(Editor.ERR_UNKNOWN);
// return;
//}
//// At this point it has been successful so spoof
//// camera device
//cameraDevices = new String[1];
//cameraDevices[0] = "Unknown device";
// TODO: at least try the default camera
error.set(true);
errorCode.set(Editor.ERR_UNKNOWN);
return;
}
}
catch (Exception e) {
error.set(true);
errorCode.set(Editor.ERR_UNKNOWN);
return;
}
selectedCamera = (int)engine.sharedResources.get("lastusedcamera", 0);
activateCamera();
ready.set(true);
}
// Activate currently selected camera, switching to next camera if it doesn't work
private void activateCamera() {
boolean success = false;
int originalSelection = selectedCamera;
while (!success) {
try {
// Activate the next camera in the list.
// Some cameras may not work. Skip them if they don't work. If none of them work, throw an error.
capture = new Capture(engine.app, cameraDevices[selectedCamera]);
success = true;
}
catch (DSJException e) {
success = false; // Keep trying
// Increase index by 1, reset to 0 if we're at end of list.
selectedCamera = ((selectedCamera+1)%(cameraDevices.length));
// If we're back where we started, then there's been a problem :(
if (originalSelection == selectedCamera) {
error.set(true);
errorCode.set(Editor.ERR_FAILED_TO_SWITCH);
return;
}
}
}
capture.start();
capture.read();
width = capture.width;
height = capture.height;
}
public PImage updateImage() {
if (capture == null) {
engine.console.bugWarnOnce("No capture available.");
return engine.display.errorImg;
}
if (capture.available()) {
capture.read();
currCapture = capture;
}
return currCapture;
}
public void switchNextCamera() {
// Only run if a camera isn't currently being setup.
if (ready.compareAndSet(true, false)) {
if (cameraDevices == null) return;
if (cameraDevices.length == 0) return;
// Turn off last used camera.
turnOffCamera();
// Increase index by 1, reset to 0 if we're at end of list.
selectedCamera = ((selectedCamera+1)%(cameraDevices.length));
activateCamera();
ready.set(true);
}
}
public void turnOffCamera() {
if (capture != null) capture.stop();
}
}
class DCapture extends EditorCapture implements java.beans.PropertyChangeListener {
private DSCapture capture;
public final int DEVICE_NONE = -1;
public final int DEVICE_CAMERA = 0;
public final int DEVICE_MICROPHONE = 1;
public ArrayList<DSFilterInfo> cameraDevices;
public DCapture(TWEngine e) {
ready.set(false);
error.set(false);
engine = e;
}
// Lmao don't care I'm using Java 8 in 2023 dangit
@SuppressWarnings("deprecation")
public void setup() {
ready.set(false);
error.set(false);
try {
DSFilterInfo[][] dsi = DSCapture.queryDevices();
cameraDevices = new ArrayList<DSFilterInfo>();
for (int y = 0; y < dsi.length; y++) {
for (int x = 0; x < dsi[y].length; x++) {
println("("+x+", "+y+") "+dsi[y][x].getName(), dsi[y][x].getType());
if (dsi[y][x].getType() == DEVICE_CAMERA)
cameraDevices.add(dsi[y][x]);
}
}
if (cameraDevices.size() <= 0) {
error.set(true);
errorCode.set(Editor.ERR_NO_CAMERA_DEVICES);
return;
}
}
catch (UnsatisfiedLinkError e) {
error.set(true);
errorCode.set(Editor.ERR_UNSUPPORTED_SYSTEM);
return;
}
catch (NoClassDefFoundError e) {
error.set(true);
errorCode.set(Editor.ERR_UNSUPPORTED_SYSTEM);
return;
}
catch (Exception e) {
error.set(true);
errorCode.set(Editor.ERR_UNKNOWN);
return;
}
selectedCamera = (int)engine.sharedResources.get("lastusedcamera", 0);
activateCamera();
ready.set(true);
}
public void turnOffCamera() {
if (capture != null) capture.dispose();
}
// Activate currently selected camera, switching to next camera if it doesn't work
private void activateCamera() {
boolean success = false;
int originalSelection = selectedCamera;
while (!success) {
try {
// Activate the next camera in the list.
// Some cameras may not work. Skip them if they don't work. If none of them work, throw an error.
capture = new DSCapture(DSFiltergraph.DD7, cameraDevices.get(selectedCamera), false, DSFilterInfo.doNotRender(), this);
success = true;
}
catch (DSJException e) {
success = false; // Keep trying
// Increase index by 1, reset to 0 if we're at end of list.
selectedCamera = ((selectedCamera+1)%(cameraDevices.size()));
// If we're back where we started, then there's been a problem :(
if (originalSelection == selectedCamera) {
error.set(true);
errorCode.set(Editor.ERR_FAILED_TO_SWITCH);
return;
}
}
}
width = getDCaptureWidth(capture);
height = getDCaptureHeight(capture);
}
public void switchNextCamera() {
// Only run if a camera isn't currently being setup.
if (ready.compareAndSet(true, false)) {
if (cameraDevices == null) return;
if (cameraDevices.size() == 0) return;
// Turn off last used camera.
turnOffCamera();
// Increase index by 1, reset to 0 if we're at end of list.
selectedCamera = ((selectedCamera+1)%(cameraDevices.size()));
activateCamera();
ready.set(true);
}
}
public PImage updateImage() {
return getDCaptureImage(capture);
}
public void propertyChange(java.beans.PropertyChangeEvent e) {
switch (DSJUtils.getEventType(e)) {
}
}
}
public class Editor extends Screen {
private boolean showGUI = false;
private float upperbarExpand = 0;
private SpriteSystemPlaceholder gui;
private SpriteSystemPlaceholder placeables;
private HashSet<Placeable> placeableset;
private ArrayList<String> imagesInEntry; // This is so that we can know what to remove when we exit this screen.
private Placeable editingPlaceable = null;
private EditorCapture camera;
private String entryName;
private String entryPath;
private String entryDir;
private color selectedColor = color(255, 255, 255);
private float selectedFontSize = 20;
private TextPlaceable entryNameText;
private boolean cameraMode = false;
private boolean autoScaleDown = false;
private boolean changesMade = false;
private int upperBarDrop = INITIALISE_DROP_ANIMATION;
private PGraphics canvas;
private float canvasScale;
private JSONArray loadedJsonArray;
protected boolean readOnly = false;
// X goes unused for now but could be useful later.
private float extentX = 0.;
private float extentY = 0.;
private float scrollLimitY = 0.;
private float prevMouseY = 0.;
private float scrollVelocity = 0.;
public static final int INITIALISE_DROP_ANIMATION = 0;
public static final int CAMERA_ON_ANIMATION = 1;
public static final int CAMERA_OFF_ANIMATION = 2;
final String RENAMEABLE_NAME = "title"; // The name of the sprite object which is used to rename entries
final float EXPAND_HITBOX = 10; // For the (unused) ERS system to slightly increase the erase area to prevent glitches
final String DEFAULT_FONT = "Typewriter"; // Default font for entries
final float STANDARD_FONT_SIZE = 64; // You get the idea
float DEFAULT_FONT_SIZE = 30;
final color DEFAULT_FONT_COLOR = color(255, 255, 255);
final float MIN_FONT_SIZE = 8.;
final float UPPER_BAR_DROP_WEIGHT = 150;
final int SCALE_DOWN_SIZE = 512;
final float SCROLL_LIMIT = 600.;
final color BACKGROUND_COLOR = 0xFF0f0f0e;
// Camera errors
public final static int ERR_UNKNOWN = 0;
public final static int ERR_NO_CAMERA_DEVICES = 1;
public final static int ERR_FAILED_TO_SWITCH = 2;
public final static int ERR_UNSUPPORTED_SYSTEM = 3;
private void textOptions() {
String[] labels = new String[2];
Runnable[] actions = new Runnable[2];
labels[0] = "Copy";
actions[0] = new Runnable() {public void run() {
if (editingPlaceable != null) {
if (editingPlaceable instanceof TextPlaceable) {
TextPlaceable t = (TextPlaceable)editingPlaceable;
boolean success = clipboard.copyString(t.text);
if (success)
console.log("Copied!");
}
}
}};
labels[1] = "Delete";
actions[1] = new Runnable() {public void run() {
if (editingPlaceable != null) {
placeableset.remove(editingPlaceable);
changesMade = true;
}
}};
ui.createOptionsMenu(labels, actions);
}
private void imageOptions() {
String[] labels = new String[3];
Runnable[] actions = new Runnable[3];
labels[0] = "Copy";
actions[0] = new Runnable() {public void run() {
console.log("Copying images to clipboard not supported yet, sorry!");
}};
labels[1] = "Save";
actions[1] = new Runnable() {public void run() {
if (editingPlaceable != null && editingPlaceable instanceof ImagePlaceable) {
ImagePlaceable im = (ImagePlaceable)editingPlaceable;
file.selectOutput("Save image...", im.getImage());
}
}};
labels[2] = "Delete";
actions[2] = new Runnable() {public void run() {
if (editingPlaceable != null) {
placeableset.remove(editingPlaceable);
changesMade = true;
}
}};
ui.createOptionsMenu(labels, actions);
}
public class Placeable {
public SpriteSystemPlaceholder.Sprite sprite;
public Placeable() {
// Essentially get the number of placeables that already exist so we have a unique id for the placeable..
int id = placeables.spriteNames.size();
// I wonder if it will crash if there's over 999 objects on a page lol.
// A bug to look out for later.
String name = engine.appendZeros(id, 3);
placeables.placeable(name);
sprite = placeables.getSprite(name);
if (!placeableset.contains(this)) {
placeableset.add(this);
}
}
protected boolean placeableSelected() {
if (input.mouseY() < myUpperBarWeight) return false;
return (sprite.mouseWithinHitbox() && placeables.selectedSprite == sprite && input.primaryDown && !input.mouseMoved);
}
protected boolean placeableSelectedSecondary() {
return (sprite.mouseWithinHitbox() && placeables.selectedSprite == sprite && input.secondaryDown && !input.mouseMoved);
}
// Just a placeholder display for the base class.
// You shouldn't use super.display() for inherited classes.
public void display() {
canvas.fill(255, 0, 0);
canvas.rect(sprite.xpos, sprite.ypos, sprite.wi, sprite.hi);
}
public void update() {
sprite.offmove(0, input.scrollOffset);
display();
placeables.placeable(sprite);
}
}
public class TextPlaceable extends Placeable {
public String text = "Sample text";
public float fontSize = DEFAULT_FONT_SIZE;
public PFont fontStyle;
public color textColor = DEFAULT_FONT_COLOR;
public float lineSpacing = 8;
int newlines = 0;
public TextPlaceable() {
super();
sprite.allowResizing = false;
fontStyle = display.getFont(DEFAULT_FONT);
selectedFontSize = this.fontSize;
}
private boolean editing() {
if (editingPlaceable == this)
changesMade = true;
return editingPlaceable == this;
}
private int countNewlines(String t) {
int count = 0;
for (int i = 0; i < t.length(); i++) {
if (t.charAt(i) == '\n') {
count++;
}
}
newlines = count;
return count;
}
int testy = 0;
public void display() {
canvas.pushMatrix();
canvas.scale(canvasScale);
canvas.fill(textColor);
canvas.textAlign(LEFT, TOP);
canvas.textFont(fontStyle, fontSize);
canvas.textLeading(fontSize+lineSpacing);
String displayText = "";
if (editing()) {
displayText = input.keyboardMessageDisplay();
}
else {
displayText = text;
}
canvas.text(displayText, sprite.xpos, sprite.ypos-canvas.textDescent()+EXPAND_HITBOX/2+10);
canvas.popMatrix();
}
public void updateDimensions() {
placeables.hackSpriteDimensions(sprite, int(app.textWidth(text)), int((app.textAscent()+app.textDescent()+lineSpacing)*(countNewlines(text)+1) + EXPAND_HITBOX));
}
public void update() {
//fontSize = (float)sprite.getWidth()/40.;
app.textFont(fontStyle, fontSize);
app.textLeading(fontSize+lineSpacing);
// The famous hitbox hack where we set the hitbox to the text size.
// For width we simply check the textWidth with the handy function.
// For text height we account for the ascent/descent thing, expand hitbox to make it slightly larger
// and times it by the number of newlines.
if (sprite.isSelected()) {
updateDimensions();
}
if (editing()) {
input.addNewlineWhenEnterPressed = true;
// Oh my god if this bug fix doesn't work I'm gonna lose it
// DO NOT allow the command prompt to appear by pressing '/' and make the current text we're writing disappear
// while writing text
engine.allowShowCommandPrompt = false;
text = input.keyboardMessage;
}
if (placeableSelected() || placeableSelectedSecondary()) {
engine.allowShowCommandPrompt = false;
editingPlaceable = this;
input.keyboardMessage = text;
input.cursorX = input.keyboardMessage.length();
selectedFontSize = this.fontSize;
}
// Mini menu for text
if (placeableSelectedSecondary()) {
textOptions();
}
super.update();
}
}
public class ImagePlaceable extends Placeable {
// You'd think we'd assign a PImage object to each ImagePlaceable.
// However, because of the Sprite implementation, that's not how things
// are done unfortunately.
// Instead, we must add the image to the engine's image hashmap and then
// give it a name that the sprite will use to find the correct image.
// Stupid workaround but it's the least complicated way of doing things lol.
// We must also remember to remove the image from the engine when we leave
// this screen otherwise we'll technically create a memory leak.
public String imageName;
public ImagePlaceable() {
super();
sprite.allowResizing = true;
}
public ImagePlaceable(PImage img) {
super();
sprite.allowResizing = true;
// Ok yes I see the flaws in this, I'll figure out a more robust system later maybe.
int uniqueIdentifier = int(random(0, 2147483646));
String name = "cache-"+str(uniqueIdentifier);
this.imageName = name;
// I feel so bad using systemImages because it was only ever intended
// for images loaded by the engine only >.<
display.systemImages.put(name, img);
imagesInEntry.add(name);
}
public void setImage(PImage img, String imgName) {
this.imageName = imgName;
display.systemImages.put(imgName, img);
//app.image(img,0,0);
imagesInEntry.add(imgName);
}
public PImage getImage() {
return display.systemImages.get(this.imageName);
}
public void display() {
}
public void update() {
sprite.offmove(0, input.scrollOffset);
if (placeableSelectedSecondary()) {
editingPlaceable = this;
imageOptions();
}
if (placeableSelected()) {
editingPlaceable = this;
}
canvas.pushMatrix();
canvas.scale(canvasScale);
placeables.sprite(sprite.getName(), imageName);
canvas.popMatrix();
}
}
//**************************************************************************************
//**********************************EDITOR SCREEN CODE**********************************
//**************************************************************************************
// Pls don't use this constructor in your code if you are sane.
public Editor(TWEngine engine, String entryPath, PGraphics c, boolean doMultithreaded) {
super(engine);
this.entryPath = entryPath;
if (c == null) {
gui = new SpriteSystemPlaceholder(engine, engine.APPPATH+engine.PATH_SPRITES_ATTRIB()+"gui/editor/");
gui.repositionSpritesToScale();
gui.interactable = false;
// Bug fix: run once so that text element in GUI being at pos 0,0 isn't shown.
runGUI();
if (isWindows()) {
camera = new DCapture(engine);
}
else if (isAndroid()) {
camera = new PCapture(engine);
}
// In android we use our own camera.
}
if (isAndroid()) {
DEFAULT_FONT_SIZE = 50;
}
placeables = new SpriteSystemPlaceholder(engine);
placeables.allowSelectOffContentPane = false;
imagesInEntry = new ArrayList<String>();
placeableset = new HashSet<Placeable>();
// Get the path without the file name
int lindex = entryPath.lastIndexOf('/');
if (lindex == -1) {
lindex = entryPath.lastIndexOf('\\');
if (lindex == -1) console.bugWarn("Could not find entry's dir, possible bug?");
}
if (lindex != -1) {
this.entryDir = entryPath.substring(0, lindex+1);
this.entryName = entryPath.substring(lindex+1, entryPath.lastIndexOf('.'));
}
autoScaleDown = settings.getBoolean("autoScaleDown");
input.scrollOffset = 0.;
if (c != null) {
canvas = c;
canvasScale = canvas.width/(WIDTH);
}
else {
canvas = g;
canvasScale = canvas.width/(WIDTH*display.getScale());
}
myLowerBarColor = 0xFF4c4945;
myUpperBarColor = myLowerBarColor;
myBackgroundColor = BACKGROUND_COLOR;
//myBackgroundColor = color(255,0,0);
if (doMultithreaded)
readEntryJSONInSeperateThread();
else {
readEntryJSON();
loading = false;
}
}
public Editor(TWEngine e, String entryPath) {
this(e, entryPath, null, true);
}
//*****************************************************************
//***********************PLACEABLE TYPES***************************
//*****************************************************************
public final int TYPE_UNKNOWN = 0;
public final int TYPE_TEXT = 1;
public final int TYPE_IMAGE = 2;
//*****************************************************************
//**************************SAVE PAGE******************************
//*****************************************************************
public void saveEntryJSON() {
// Only save if any changes were made.
if (changesMade) {
sound.playSound("chime");
numImages = 0;
//JSONObject json = new JSONObject();
JSONArray array = new JSONArray();
for (Placeable p : placeableset) {
if (p instanceof TextPlaceable)
saveTextPlaceable(p, array);
else if (p instanceof ImagePlaceable)
saveImagePlaceable(p, array);
else {
console.bugWarn("Missing code! Couldn't save unknown placeable.");
console.log("Once: "+p.toString());
}
}
engine.app.saveJSONArray(array, entryPath);
}
}
private void saveTextPlaceable(Placeable p, JSONArray array) {
TextPlaceable t = (TextPlaceable)p;
JSONObject obj = new JSONObject();
t.sprite.offmove(0,0);
obj.setString("ID", t.sprite.name);
obj.setInt("type", TYPE_TEXT);
obj.setInt("x", int(t.sprite.getX()));
obj.setInt("y", int(t.sprite.getY()));
obj.setFloat("size", t.fontSize);
obj.setString("text", t.text);
obj.setInt("color", t.textColor);
array.append(obj);
}
public int numImages = 0;
// TODO: we need to put it into a new thread, huh?
private void saveImagePlaceable(Placeable p, JSONArray array) {
// First, we need the png image data.
ImagePlaceable imgPlaceable = (ImagePlaceable)p;
PImage image = display.systemImages.get(imgPlaceable.sprite.imgName);
if (image == null) {
console.bugWarn("Trying to save image placeable, and image doesn't exist in memory?? Possible bug??");
return;
}
// No multithreading please!
// And no shrinking please!
engine.setCachingShrink(0,0);
String cachePath = engine.saveCacheImage(entryPath+"_"+str(numImages++), image);
byte[] cacheBytes = loadBytes(cachePath);
// TODO: I don't like this line of code at all...
//File f = new File(cachePath);
//f.delete();
// NullPointerException
String encodedPng = new String(Base64.getEncoder().encode(cacheBytes));
imgPlaceable.sprite.offmove(0,0);
JSONObject obj = new JSONObject();
obj.setString("ID", imgPlaceable.sprite.name);
obj.setInt("type", TYPE_IMAGE);
obj.setInt("x", int(imgPlaceable.sprite.getX()));
obj.setInt("y", int(imgPlaceable.sprite.getY()));
obj.setInt("wi", int(imgPlaceable.sprite.wi));
obj.setInt("hi", int(imgPlaceable.sprite.hi));
obj.setString("imgName", imgPlaceable.sprite.imgName);
obj.setString("png", encodedPng);
array.append(obj);
}
// Util json ancient functions moved from Engine
public int getJSONArrayInt(int index, String property, int defaultValue) {
if (loadedJsonArray == null) {
console.bugWarn("Cannot get property, entry not opened.");
return defaultValue;
}
if (index > loadedJsonArray.size()) {
console.bugWarn("No more elements.");
return defaultValue;
}
int result = 0;
try {
result = loadedJsonArray.getJSONObject(index).getInt(property);
}
catch (Exception e) {
return defaultValue;
}
return result;
}
public String getJSONArrayString(int index, String property, String defaultValue) {
if (loadedJsonArray == null) {
console.bugWarn("Cannot get property, entry not opened.");
return defaultValue;
}
if (index > loadedJsonArray.size()) {
console.bugWarn("No more elements.");
return defaultValue;
}
String result = "";
try {
result = loadedJsonArray.getJSONObject(index).getString(property);
}
catch (Exception e) {
return defaultValue;
}
return result;
}
public float getJSONArrayFloat(int index, String property, float defaultValue) {
if (loadedJsonArray == null) {
console.warn("Cannot get property, entry not opened.");
return defaultValue;
}
if (index > loadedJsonArray.size()) {
console.warn("No more elements.");
return defaultValue;
}
float result = 0;
try {
result = loadedJsonArray.getJSONObject(index).getFloat(property);
}
catch (Exception e) {
return defaultValue;
}
return result;
}
//*****************************************************************
//**************************SAVE PAGE******************************
//*****************************************************************
public void readEntryJSON() {
// check if file exists
if (!file.exists(entryPath) || file.fileSize(entryPath) <= 2) {
// If it doesn't exist or is blank, create a new placeable for the name of the entry
entryNameText = new TextPlaceable();
entryNameText.sprite.move(20., UPPER_BAR_DROP_WEIGHT + 80);
entryNameText.fontSize = 60.;
entryNameText.textColor = color(255);
entryNameText.text = entryName;
entryNameText.sprite.name = RENAMEABLE_NAME;
entryNameText.updateDimensions();
// Create date
TextPlaceable date = new TextPlaceable();
String d = engine.appendZeros(day(), 2)+"/"+engine.appendZeros(month(), 2)+"/"+year()+"\n"+engine.appendZeros(hour(), 2)+":"+engine.appendZeros(minute(), 2)+":"+engine.appendZeros(second(), 2);
date.sprite.move(WIDTH-app.textWidth(d)*2., 250);
date.text = d;
date.updateDimensions();
// New entry, new default template, ofc we want to save changes!
changesMade = true;
loading = false;
return;
}
// Open json array
// (This function used to be in the engine code and was ancient)
try {
loadedJsonArray = app.loadJSONArray(entryPath);
}
catch (RuntimeException e) {
console.warn("Failed to open JSON file, there was an error: "+e.getMessage());
return;
}
// If the file doesn't exist
if (loadedJsonArray == null) {
console.warn("What. The file doesn't exist.");
return;
}
for (int i = 0; i < loadedJsonArray.size(); i++) {
int type = getJSONArrayInt(i, "type", 0);
switch (type) {
case TYPE_UNKNOWN:
console.warn("Corrupted element, skipping.");
break;
case TYPE_TEXT:
TextPlaceable t = readTextPlaceable(i);
// Title text element should always be 000
if (t.sprite.name.equals(RENAMEABLE_NAME)) entryNameText = t;
break;
case TYPE_IMAGE:
readImagePlaceable(i);
break;
default:
console.warn("Corrupted element, skipping.");
break;
}
}
loading = false;
}
private TextPlaceable readTextPlaceable(int i) {
TextPlaceable t = new TextPlaceable();
t.sprite.setX((float)getJSONArrayInt(i, "x", (int)WIDTH/2));
t.sprite.setY((float)getJSONArrayInt(i, "y", (int)HEIGHT/2));
t.sprite.name = getJSONArrayString(i, "ID", "");
t.text = getJSONArrayString(i, "text", "");
t.fontSize = getJSONArrayFloat(i, "size", 12.);
t.textColor = getJSONArrayInt(i, "color", color(255, 255, 255));
t.updateDimensions();
placeableset.add(t);
return t;
}
private ImagePlaceable readImagePlaceable(final int i) {
ImagePlaceable im = new ImagePlaceable();
im.sprite.setX((float)getJSONArrayInt(i, "x", (int)WIDTH/2));
im.sprite.setY((float)getJSONArrayInt(i, "y", (int)HEIGHT/2));
im.sprite.wi = getJSONArrayInt(i, "wi", 512);
im.sprite.hi = getJSONArrayInt(i, "hi", 512);
String imageName = getJSONArrayString(i, "imgName", "");
// If there's cache, don't bother decoding the base64 string.
// Otherwise, read the base64 string, generate cache, read from that cache.
Runnable loadFromEntry = new Runnable() {
public void run() {
// Decode the string of base64
String encoded = getJSONArrayString(i, "png", "");
// Png image data in json is missing
if (encoded.length() == 0) {
console.warn("while loading entry: png image data in json is missing.");
}
// Everything is found as expected.
else {
byte[] decodedBytes = Base64.getDecoder().decode(encoded.getBytes());
PImage img = engine.saveCacheImageBytes(entryPath+"_"+str(i), decodedBytes, "png");
// An error occured, data may have been tampered with/corrupted.
if (img == null)
console.warn("while loading entry: png image data is corrupted or cachepath is invalid.");
else
engine.setOriginalImage(img);
}
}
};
PImage img = engine.tryLoadImageCache(this.entryPath+"_"+str(i), loadFromEntry);
im.setImage(img, imageName);
placeableset.add(im);
return im;
}
public boolean loading = false;
public void readEntryJSONInSeperateThread() {
loading = true;
Thread t = new Thread(new Runnable() {
public void run() {
readEntryJSON();
}
});
t.start();
}
public boolean isLoaded() {
return !loading;
}
protected boolean customCommands(String command) {
if (command.equals("/editgui")) {
gui.interactable = !gui.interactable;
if (gui.interactable) console.log("GUI now interactable.");
else console.log("GUI is no longer interactable.");
return true;
}
else return false;
}
//*****************************************************************
//*********************GUI BUTTONS AND ACTIONS*********************