/
Sketch.java
1917 lines (1619 loc) · 62.7 KB
/
Sketch.java
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
/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */
/*
Part of the Processing project - http://processing.org
Copyright (c) 2012-22 The Processing Foundation
Copyright (c) 2004-11 Ben Fry and Casey Reas
Copyright (c) 2001-04 Massachusetts Institute of Technology
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software Foundation,
Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package processing.app;
import processing.app.ui.Editor;
import processing.app.ui.Recent;
import processing.app.ui.Toolkit;
import processing.core.*;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.EventQueue;
import java.awt.FileDialog;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
/**
* Stores information about files in the current sketch.
*/
public class Sketch {
private final Editor editor;
private final Mode mode;
/** main pde file for this sketch. */
private File mainFile;
/**
* Name of the sketch, which is the name of the folder since 4.0 beta 6.
* Prior, it was the "pretty" name of the first tab (they were synonymous).
*/
private String name;
/** true if any of the files have been modified. */
private boolean modified;
/** folder that contains this sketch */
private File folder;
/** data folder location for this sketch (may not exist yet) */
private File dataFolder;
/** code folder location for this sketch (may not exist yet) */
private File codeFolder;
private SketchCode current;
private int currentIndex;
/**
* Number of SketchCode objects (tabs) in the current sketch. Note
* that this will be the same as code.length, because the getCode()
* method returns just the code[] array, rather than a copy of it,
* or an array that's been resized to just the relevant files.
* (<a href="https://download.processing.org/bugzilla/940.html">Bugzilla 940</a>)
*/
private int codeCount;
private SketchCode[] code;
/** Moved out of Editor and into here for cleaner access. */
private boolean untitled;
/** true if we've posted a "sketch disappeared" warning */
private boolean disappearedWarning;
/**
* Used by the command-line version to create a sketch object.
* @param path location of the main .pde file
* @param mode what flavor of sketch we're dealing with.
*/
public Sketch(String path, Mode mode) {
this.editor = null;
this.mode = mode;
load(path);
}
/**
* path is location of the main .pde file, because this is also
* simplest to use when opening the file from the finder/explorer.
*/
public Sketch(String path, Editor editor) throws IOException {
this.editor = editor;
this.mode = editor.getMode();
load(path);
}
protected void load(String path) {
mainFile = new File(path);
folder = mainFile.getParentFile();
/*
// get the name of the sketch by chopping .pde or .java
// off of the main file name
String mainFilename = primaryFile.getName();
int suffixLength = mode.getDefaultExtension().length() + 1;
name = mainFilename.substring(0, mainFilename.length() - suffixLength);
*/
// starting in 4.0 beta 6, use the folder name instead of the main tab
name = folder.getName();
disappearedWarning = false;
load();
}
/**
* Build the list of files.
* <P>
* Generally this is only done once, rather than
* each time a change is made, because otherwise it gets to be
* a nightmare to keep track of what files went where, because
* not all the data will be saved to disk.
* <P>
* This also gets called when the main sketch file is renamed,
* because the sketch has to be reloaded from a different folder.
* <P>
* Another exception is when an external editor is in use,
* in which case the load happens each time "run" is hit.
*/
protected void load() {
codeFolder = new File(folder, "code");
dataFolder = new File(folder, "data");
List<String> filenames = new ArrayList<>();
List<String> extensions = new ArrayList<>();
getSketchCodeFiles(filenames, extensions);
codeCount = filenames.size();
code = new SketchCode[codeCount];
for (int i = 0; i < codeCount; i++) {
String filename = filenames.get(i);
String extension = extensions.get(i);
code[i] = new SketchCode(new File(folder, filename), extension);
}
// move the main class to the first tab
// start at 1, if it's at zero, don't bother
for (int i = 1; i < codeCount; i++) {
//if (code[i].file.getName().equals(mainFilename)) {
if (code[i].getFile().equals(mainFile)) {
SketchCode temp = code[0];
code[0] = code[i];
code[i] = temp;
break;
}
}
// sort the entries at the top
sortCode();
// set the main file to be the current tab
if (editor != null) {
setCurrentCode(0);
}
}
public void getSketchCodeFiles(List<String> outFilenames,
List<String> outExtensions) {
// get list of files in the sketch folder
String[] list = folder.list();
if (list != null) {
for (String filename : list) {
// Ignoring the dot prefix files is especially important to avoid files
// with the ._ prefix on Mac OS X. (You'll see this with Mac files on
// non-HFS drives, i.e. a thumb drive formatted FAT32.)
if (filename.startsWith(".")) continue;
// Don't let some wacko name a directory blah.pde or bling.java.
if (new File(folder, filename).isDirectory()) continue;
// figure out the name without any extension
String base = filename;
// now strip off the .pde and .java extensions
for (String extension : mode.getExtensions()) {
if (base.toLowerCase().endsWith("." + extension)) {
base = base.substring(0, base.length() - (extension.length() + 1));
// Don't allow people to use files with invalid names, since on load,
// it would be otherwise possible to sneak in nasty filenames. [0116]
if (isSanitaryName(base)) {
if (outFilenames != null) outFilenames.add(filename);
if (outExtensions != null) outExtensions.add(extension);
}
}
}
}
}
}
/**
* Reload the current sketch. Used to update the text area when
* an external editor is in use.
*/
public void reload() {
// set current to null so that the tab gets updated
// https://download.processing.org/bugzilla/515.html
current = null;
// nuke previous files and settings
load();
}
/**
* Load a tab that the user added to the sketch or modified with an external
* editor.
*/
public void loadNewTab(String filename, String ext, boolean newAddition) {
if (newAddition) {
insertCode(new SketchCode(new File(folder, filename), ext));
} else {
replaceCode(new SketchCode(new File(folder, filename), ext));
}
sortCode();
}
protected void replaceCode(SketchCode newCode) {
for (int i = 0; i < codeCount; i++) {
if (code[i].getFileName().equals(newCode.getFileName())) {
code[i] = newCode;
break;
}
}
}
protected void insertCode(SketchCode newCode) {
// make sure the user didn't hide the sketch folder
ensureExistence();
// add file to the code/codeCount list, resort the list
//if (codeCount == code.length) {
code = (SketchCode[]) PApplet.append(code, newCode);
codeCount++;
//}
//code[codeCount++] = newCode;
}
protected void sortCode() {
// cheap-ass sort of the rest of the files
// it's a dumb, slow sort, but there shouldn't be more than ~5 files
for (int i = 1; i < codeCount; i++) {
int who = i;
for (int j = i + 1; j < codeCount; j++) {
if (code[j].getFileName().compareTo(code[who].getFileName()) < 0) {
who = j; // this guy is earlier in the alphabet
}
}
if (who != i) { // swap with someone if changes made
SketchCode temp = code[who];
code[who] = code[i];
code[i] = temp;
// We also need to update the current tab
if (currentIndex == i) {
currentIndex = who;
} else if (currentIndex == who) {
currentIndex = i;
}
}
}
}
boolean renamingCode;
/**
* Handler for the New Code menu option.
*/
public void handleNewCode() {
// make sure the user didn't hide the sketch folder
ensureExistence();
// if read-only, give an error
if (isReadOnly()) {
// if the files are read-only, need to first do a "save as".
Messages.showMessage(Language.text("new.messages.is_read_only"),
Language.text("new.messages.is_read_only.description"));
return;
}
renamingCode = false;
// editor.status.edit("Name for new file:", "");
promptForTabName(Language.text("editor.tab.rename.description")+":", "");
}
/**
* Handler for the "Rename Code" menu option.
*/
public void handleRenameCode() {
// make sure the user didn't hide the sketch folder
ensureExistence();
if (currentIndex == 0 && isUntitled()) {
Messages.showMessage(Language.text("rename.messages.is_untitled"),
Language.text("rename.messages.is_untitled.description"));
return;
}
if (isModified()) {
Messages.showMessage(Language.text("menu.file.save"),
Language.text("rename.messages.is_modified"));
return;
}
// if read-only, give an error
if (isReadOnly()) {
// if the files are read-only, need to first do a "save as".
Messages.showMessage(Language.text("rename.messages.is_read_only"),
Language.text("rename.messages.is_read_only.description"));
return;
}
// ask for new name of file (internal to window)
// TODO maybe just pop up a text area?
renamingCode = true;
String prompt = (currentIndex == 0 && Preferences.getBoolean("editor.sync_folder_and_filename")) ?
Language.text("editor.sketch.rename.description") :
Language.text("editor.tab.rename.description");
String oldName = (current.isExtension(mode.getDefaultExtension())) ?
current.getPrettyName() : current.getFileName();
promptForTabName(prompt + ":", oldName);
}
/**
* Displays a dialog for renaming or creating a new tab
*/
protected void promptForTabName(String prompt, String oldName) {
final JTextField field = new JTextField(oldName);
field.addKeyListener(new KeyAdapter() {
// Forget ESC, the JDialog should handle it.
// Use keyTyped to catch when the feller is actually added to the text
// field. With keyTyped, as opposed to keyPressed, the keyCode will be
// zero, even if it's enter or backspace or whatever, so the key char
// should be used instead. Grr.
public void keyTyped(KeyEvent event) {
//System.out.println("got event " + event);
char ch = event.getKeyChar();
//noinspection StatementWithEmptyBody
if ((ch == '_') || (ch == '.') || // allow.pde and .java
(('A' <= ch) && (ch <= 'Z')) || (('a' <= ch) && (ch <= 'z'))) {
// These events are allowed straight through.
} else if (ch == ' ') {
String t = field.getText();
int start = field.getSelectionStart();
int end = field.getSelectionEnd();
field.setText(t.substring(0, start) + "_" + t.substring(end));
field.setCaretPosition(start + 1);
event.consume();
} else if ((ch >= '0') && (ch <= '9')) {
// getCaretPosition == 0 means that it's the first char
// and the field is empty.
// getSelectionStart means that it *will be* the first
// char, because the selection is about to be replaced
// with whatever is typed.
if (field.getCaretPosition() == 0 ||
field.getSelectionStart() == 0) {
// number not allowed as first digit
event.consume();
}
} else if (ch == KeyEvent.VK_ENTER) {
// Slightly ugly hack that ensures OK button of the dialog consumes
// the Enter key event. Since the text field is the default component
// in the dialog, OK doesn't consume Enter key event, by default.
Container parent = field.getParent();
while (!(parent instanceof JOptionPane pane)) {
parent = parent.getParent();
}
final JPanel pnlBottom = (JPanel)
pane.getComponent(pane.getComponentCount() - 1);
for (int i = 0; i < pnlBottom.getComponents().length; i++) {
Component component = pnlBottom.getComponents()[i];
if (component instanceof final JButton okButton) {
if (okButton.getText().equalsIgnoreCase("OK")) {
ActionListener[] actionListeners =
okButton.getActionListeners();
if (actionListeners.length > 0) {
actionListeners[0].actionPerformed(null);
event.consume();
}
}
}
}
} else {
event.consume();
}
}
});
int userReply = JOptionPane.showOptionDialog(editor, new Object[] {
prompt, field },
Language.text("editor.tab.new"),
JOptionPane.OK_CANCEL_OPTION,
JOptionPane.PLAIN_MESSAGE,
null, new Object[] {
Language.getPrompt("ok"),
Language.getPrompt("cancel") },
field);
if (userReply == JOptionPane.OK_OPTION) {
nameCode(field.getText());
}
}
/**
* This is called upon return from entering a new file name.
* (that is, from either newCode or renameCode after the prompt)
*/
protected void nameCode(String newName) {
newName = newName.trim();
if (newName.length() == 0) {
return;
}
// Make sure the sketch folder is still available and exists.
ensureExistence();
// Add the extension here, this simplifies some logic below.
if (newName.indexOf('.') == -1) {
newName += "." + (renamingCode ? mode.getDefaultExtension() : mode.getModuleExtension());
}
// If renaming to the same thing as before, just ignore.
// Also ignoring case here, because I don't want to write/maintain/debug
// a bunch of platform-specific quirks: macOS is case-insensitive but
// preserving, Windows is insensitive, *nix is sensitive and preserving,
// and someday we're all gonna die, and I'm comfortable that writing the
// necessary code is not essential to the story of my life on Earth.
if (renamingCode) {
if (newName.equalsIgnoreCase(current.getFileName())) {
// exit quietly for the 'rename' case.
// if it's a 'new' then an error will occur down below
return;
}
}
if (newName.startsWith(".")) {
Messages.showWarning(Language.text("name.messages.problem_renaming"),
Language.text("name.messages.starts_with_dot.description"));
return;
}
int dot = newName.lastIndexOf('.');
String newExtension = newName.substring(dot+1).toLowerCase();
if (!mode.validExtension(newExtension)) {
Messages.showWarning(Language.text("name.messages.problem_renaming"),
Language.interpolate("name.messages.invalid_extension.description",
newExtension));
return;
}
// Don't let the user create the main tab as a .java file instead of .pde
if (!mode.isDefaultExtension(newExtension)) {
if (renamingCode) { // If creating a new tab, don't show this error
if (current == code[0]) { // If this is the main tab, disallow
Messages.showWarning(Language.text("name.messages.problem_renaming"),
Language.interpolate("name.messages.main_java_extension.description",
newExtension));
return;
}
}
}
// Dots are allowed for the .pde and .java, but not in the name.
// Make sure the user didn't name the file poo.time.pde or anything
// else with a dot inside it (nothing against poo time).
String shortName = newName.substring(0, dot);
String sanitaryName = Sketch.sanitizeName(shortName);
if (!shortName.equals(sanitaryName)) {
newName = sanitaryName + "." + newExtension;
}
// If changing the extension of a file from .pde to .java, then it's ok.
// https://github.com/processing/processing/issues/814
// (That regression was introduced years earlier by the bug report below.)
if (!(renamingCode && sanitaryName.equals(current.getPrettyName()))) {
// Make sure no .pde *and* no .java files with the same name already exist
// (other than the one we are currently attempting to rename)
// http://processing.org/bugs/bugzilla/543.html
for (SketchCode c : code) {
if (c != current && sanitaryName.equalsIgnoreCase(c.getPrettyName())) {
Messages.showMessage(Language.text("name.messages.new_sketch_exists"),
Language.interpolate("name.messages.new_sketch_exists.description",
c.getFileName(), folder.getAbsolutePath()));
return;
}
}
}
File newFile = new File(folder, newName);
if (renamingCode) {
if (currentIndex == 0 &&
Preferences.getBoolean("editor.sync_folder_and_filename")) {
if (!renameSketch(newName, newExtension)) return;
} else { // else if something besides code[0], or ok to decouple name
if (!current.renameTo(newFile, newExtension)) {
Messages.showWarning(Language.text("name.messages.error"),
Language.interpolate("name.messages.no_rename_file.description",
current.getFileName(), newFile.getName()));
return;
}
if (currentIndex == 0) {
// If the main tab was renamed, check sketch.properties
mainFile = newFile; //code[0].getFile();
updateNameProperties();
}
}
} else { // not renaming, creating a new file
try {
if (!newFile.createNewFile()) {
// Already checking for IOException, so make our own.
throw new IOException("createNewFile() returned false");
}
} catch (IOException e) {
Messages.showWarning(Language.text("name.messages.error"),
Language.interpolate("name.messages.no_create_file.description",
newFile, folder.getAbsolutePath()), e);
return;
}
SketchCode newCode = new SketchCode(newFile, newExtension);
insertCode(newCode);
}
// sort the entries
sortCode();
// set the new guy as current
setCurrentCode(newName);
// update the tabs
editor.rebuildHeader();
}
/**
* Pre-4.0b6 style rename where the sketch name must be identical
* to the name of the first (main) tab with the extension removed.
*/
protected boolean renameSketch(String newName, String newExtension) {
// get the new folder name/location
String folderName = newName.substring(0, newName.indexOf('.'));
File newFolder = new File(folder.getParentFile(), folderName);
if (newFolder.exists()) {
Messages.showWarning(Language.text("name.messages.new_folder_exists"),
Language.interpolate("name.messages.new_folder_exists.description", newName));
return false;
}
// renaming the containing sketch folder
boolean success = folder.renameTo(newFolder);
if (!success) {
Messages.showWarning(Language.text("name.messages.error"),
Language.text("name.messages.no_rename_folder.description"));
return false;
}
// let this guy know where he's living (at least for a split second)
current.setFolder(newFolder);
// folder will be set to newFolder by updateInternal()
// unfortunately this can't be a "save as" because that
// only copies the sketch files and the data folder
// however this *will* first save the sketch, then rename
// This isn't changing folders, just changes the name
File newFile = new File(newFolder, newName);
if (!current.renameTo(newFile, newExtension)) {
Messages.showWarning(Language.text("name.messages.error"),
Language.interpolate("name.messages.no_rename_file.description",
current.getFileName(), newFile.getName()));
return false;
}
// Tell each code file the good news about their new home.
// current.renameTo() above already took care of the main tab.
for (int i = 1; i < codeCount; i++) {
code[i].setFolder(newFolder);
}
// Save the path in case we need to remove it from the Recent menu
String oldPath = getMainPath();
// Update internal state to reflect the new location
updateInternal(newFolder);
if (renamingCode) {
// Update the Recent menu if a Rename event (but not Save As)
// https://github.com/processing/processing/issues/5902
Recent.rename(editor, oldPath);
}
return true;
}
/**
* Remove a piece of code from the sketch and from the disk.
*/
public void handleDeleteCode() {
// make sure the user didn't hide the sketch folder
ensureExistence();
// if read-only, give an error
if (isReadOnly()) {
// if the files are read-only, need to first do a "save as".
Messages.showMessage(Language.text("delete.messages.is_read_only"),
Language.text("delete.messages.is_read_only.description"));
return;
}
// don't allow if untitled
if (currentIndex == 0 && isUntitled()) {
Messages.showMessage(Language.text("delete.messages.cannot_delete"),
Language.text("delete.messages.cannot_delete.description"));
return;
}
// confirm deletion with user, yes/no
Object[] options = { Language.text("prompt.ok"), Language.text("prompt.cancel") };
String prompt = (currentIndex == 0) ?
Language.interpolate("warn.delete.sketch_folder", getName()) :
Language.interpolate("warn.delete.sketch_file", current.getPrettyName());
int result = JOptionPane.showOptionDialog(editor,
prompt,
Language.text("warn.delete"),
JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE,
null,
options,
options[0]);
if (result == JOptionPane.YES_OPTION) {
if (currentIndex == 0) { // delete the entire sketch
// need to unset all the modified flags, otherwise tries
// to do a save on the handleNew()
// Attempt to move to the trash (falls back to removeDir)
try {
Platform.deleteFile(folder);
} catch (IOException e) {
e.printStackTrace();
}
// make a new sketch and rebuild the sketch menu
editor.getBase().rebuildSketchbook();
editor.getBase().handleClose(editor, false);
} else { // delete a single tab
if (!current.deleteFile()) {
Messages.showMessage(Language.text("delete.messages.cannot_delete.file"),
Language.text("delete.messages.cannot_delete.file.description")+" \"" +
current.getFileName() + "\".");
return;
}
// remove code from the list
removeCode(current);
// update the tabs
editor.rebuildHeader();
// just set current tab to the main tab
setCurrentCode(0);
}
}
}
/**
* Remove a SketchCode from the list of files without deleting its file.
* @see #handleDeleteCode()
*/
public void removeCode(SketchCode which) {
// remove it from the internal list of files
// resort internal list of files
for (int i = 0; i < codeCount; i++) {
if (code[i] == which) {
for (int j = i; j < codeCount-1; j++) {
code[j] = code[j+1];
}
codeCount--;
code = (SketchCode[]) PApplet.shorten(code);
return;
}
}
if (Base.DEBUG) {
// This can happen with the change detector, but need not be reported.
System.err.println("removeCode: could not find " + which.getFileName());
}
}
/**
* Move to the previous tab.
*/
public void handlePrevCode() {
int prev = currentIndex - 1;
if (prev < 0) prev = codeCount-1;
setCurrentCode(prev);
}
/**
* Move to the next tab.
*/
public void handleNextCode() {
setCurrentCode((currentIndex + 1) % codeCount);
}
/**
* Sets the modified value for the code in the front-most tab.
*/
public void setModified(boolean state) {
if (current.isModified() != state) {
current.setModified(state);
calcModified();
}
}
protected void calcModified() {
modified = false;
for (int i = 0; i < codeCount; i++) {
if (code[i].isModified()) {
modified = true;
break;
}
}
editor.repaintHeader();
if (Platform.isMacOS()) {
// http://developer.apple.com/qa/qa2001/qa1146.html
Object modifiedParam = modified ? Boolean.TRUE : Boolean.FALSE;
// https://developer.apple.com/library/mac/technotes/tn2007/tn2196.html#WINDOW_DOCUMENTMODIFIED
editor.getRootPane().putClientProperty("Window.documentModified", modifiedParam);
}
}
public boolean isModified() {
return modified;
}
/**
* Ensure that all SketchCodes are up-to-date, so that sc.save() works.
*/
public void updateSketchCodes() {
current.setProgram(editor.getText());
}
/**
* Save all code in the current sketch. This just forces the files to save
* in place, so if it's an untitled (un-saved) sketch, saveAs() should be
* called instead. (This is handled inside Editor.handleSave()).
*/
public boolean save() throws IOException {
// make sure the user didn't hide the sketch folder
ensureExistence();
// first get the contents of the editor text area
updateSketchCodes();
// don't do anything if not actually modified
//if (!modified) return false;
if (isReadOnly()) {
// if the files are read-only, need to first do a "save as".
Messages.showMessage(Language.text("save_file.messages.is_read_only"),
Language.text("save_file.messages.is_read_only.description"));
// if the user cancels, give up on the save()
if (!saveAs()) return false;
}
for (SketchCode sc : code) {
if (sc.isModified()) {
sc.save();
}
}
calcModified();
return true;
}
/**
* Handles 'Save As' for a sketch.
* <P>
* This basically just duplicates the current sketch folder to
* a new location, and then calls 'Save'. (needs to take the current
* state of the open files and save them to the new folder,
* but not save over the old versions for the old sketch...)
* <P>
* Also removes the previously-generated .class and .jar files,
* because they can cause trouble.
*/
public boolean saveAs() throws IOException {
String newParentDir = null;
String newSketchName = null;
final String PROMPT = Language.text("save");
// https://github.com/processing/processing4/issues/77
boolean useNative = Preferences.getBoolean("chooser.files.native");
if (useNative) {
// get new name for folder
FileDialog fd = new FileDialog(editor, PROMPT, FileDialog.SAVE);
if (isReadOnly() || isUntitled()) {
// default to the sketchbook folder
fd.setDirectory(Preferences.getSketchbookPath());
} else {
// default to the parent folder of where this was
fd.setDirectory(folder.getParent());
}
String oldFolderName = folder.getName();
fd.setFile(oldFolderName);
fd.setVisible(true);
newParentDir = fd.getDirectory();
newSketchName = fd.getFile();
} else {
JFileChooser fc = new JFileChooser();
fc.setDialogTitle(PROMPT);
if (isReadOnly() || isUntitled()) {
// default to the sketchbook folder
fc.setCurrentDirectory(new File(Preferences.getSketchbookPath()));
} else {
// default to the parent folder of where this was
fc.setCurrentDirectory(folder.getParentFile());
}
// can't do this, will try to save into itself by default
//fc.setSelectedFile(folder);
int result = fc.showSaveDialog(editor);
if (result == JFileChooser.APPROVE_OPTION) {
File selection = fc.getSelectedFile();
newParentDir = selection.getParent();
newSketchName = selection.getName();
}
}
// user canceled selection
if (newSketchName == null) return false;
boolean sync = Preferences.getBoolean("editor.sync_folder_and_filename");
String newMainFileName = null; // only set with !sync
File newFolder;
if (sync) {
// before 4.0 beta 6
//String sanitaryName = Sketch.checkName(newSketchName);
String newMainName = sanitizeName(newSketchName);
newFolder = new File(newParentDir, newMainName);
if (!newMainName.equals(newSketchName) && newFolder.exists()) {
Messages.showMessage(Language.text("save_file.messages.sketch_exists"),
Language.interpolate("save_file.messages.sketch_exists.description",
newMainName));
return false;
}
newSketchName = newMainName;
newMainFileName = newMainName + "." + mode.getDefaultExtension();
} else {
newFolder = new File(newParentDir, newSketchName); // sketch folder name can be different
}
// make sure there doesn't exist a tab with that name already
// but ignore this situation for the first tab, since it's probably being
// re-saved (with the same name) to another location/folder.
for (int i = 1; i < codeCount; i++) {
if (newSketchName.equalsIgnoreCase(code[i].getPrettyName())) {
Messages.showMessage(Language.text("save_file.messages.tab_exists"),
Language.interpolate("save_file.messages.tab_exists.description",
newSketchName));
return false;
}
}
// check if the paths are identical
if (newFolder.equals(folder)) {
// just use "save" here instead, because the user will have received a
// message (from the operating system) about "do you want to replace?"
return save();
}
// check to see if the user is trying to save this sketch inside itself
try {
// Includes the separator so that a/b/c is different from a/b/c2.
// (a/b/c matches a/b/c2, but a/b/c/ does not match a/b/c2/)
String newPath = newFolder.getCanonicalPath() + File.separator;
String oldPath = folder.getCanonicalPath() + File.separator;
if (newPath.indexOf(oldPath) == 0) {
Messages.showWarning(Language.text("save_file.messages.recursive_save"),
Language.text("save_file.messages.recursive_save.description"));
return false;
}
} catch (IOException ignored) { }
// if the new folder already exists, then first remove its contents before
// copying everything over (user will have already been warned).
if (newFolder.exists()) {
//Util.removeDir(newFolder);
try {
Platform.deleteFile(newFolder);
} catch (IOException e) {
e.printStackTrace();
}
}
// in fact, you can't do this on Windows because the file dialog
// will instead put you inside the folder, but it happens on OS X a lot.
// now make a fresh copy of the folder
if (!newFolder.mkdirs()) {
// mkdirs() returns true when the folders are created, which should
// be the case here because we removed any existing 'newFolder' above.
// If this fails, then it probably means the removeDir() failed,
// or at least left things behind, which could mean badness later.
System.err.println("Error creating path " + newFolder);
}
// grab the contents of the current tab before saving
// first get the contents of the editor text area
updateSketchCodes();
File[] copyItems = folder.listFiles(file -> {
String name = file.getName();
// just in case the OS likes to return these as if they're legit
if (name.equals(".") || name.equals("..")) {
return false;
}
// list of files/folders to be ignored during "save as"
String[] ignorable = mode.getIgnorable();
if (ignorable != null) {
for (String ignore : ignorable) {
if (name.equals(ignore)) {
return false;
}
}
}
// ignore the extensions for code, since that'll be copied below
for (String ext : mode.getExtensions()) {
if (name.endsWith(ext)) {
return false;
}
}
// don't do screen captures, since there might be thousands. kind of
// a hack, but seems harmless. hm, where have i heard that before...
//noinspection RedundantIfStatement
if (name.startsWith("screen-")) {
return false;
}
return true;
});
startSaveAsThread(newFolder, copyItems);