-
-
Notifications
You must be signed in to change notification settings - Fork 1.5k
Expand file tree
/
Copy pathBase.java
More file actions
2051 lines (1693 loc) · 67.1 KB
/
Base.java
File metadata and controls
2051 lines (1693 loc) · 67.1 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
/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */
/*
Part of the Processing project - http://processing.org
Copyright (c) 2012-19 The Processing Foundation
Copyright (c) 2004-12 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
version 2, as published by the Free Software Foundation.
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 java.awt.EventQueue;
import java.awt.FileDialog;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.Map.Entry;
import javax.swing.JFileChooser;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPopupMenu;
import javax.swing.tree.DefaultMutableTreeNode;
import processing.app.contrib.*;
import processing.app.tools.Tool;
import processing.app.ui.*;
import processing.core.*;
import processing.data.StringList;
/**
* The base class for the main processing application.
* Primary role of this class is for platform identification and
* general interaction with the system (launching URLs, loading
* files and images, etc) that comes from that.
*/
public class Base {
// Added accessors for 0218 because the UpdateCheck class was not properly
// updating the values, due to javac inlining the static final values.
static private final int REVISION = 271;
/** This might be replaced by main() if there's a lib/version.txt file. */
static private String VERSION_NAME = "0271"; //$NON-NLS-1$
/** Set true if this a proper release rather than a numbered revision. */
/**
* True if heavy debugging error/log messages are enabled. Set to true
* if an empty file named 'debug' is found in the settings folder.
* See implementation in createAndShowGUI().
*/
static public boolean DEBUG;
static private boolean commandLine;
// A single instance of the preferences window
PreferencesFrame preferencesFrame;
// A single instance of the library manager window
// ContributionManagerDialog contributionManagerFrame;
// Location for untitled items
static File untitledFolder;
/** List of currently active editors. */
protected List<Editor> editors =
Collections.synchronizedList(new ArrayList<Editor>());
protected Editor activeEditor;
/** A lone file menu to be used when all sketch windows are closed. */
static public JMenu defaultFileMenu;
/**
* Starts with the last mode used with the environment,
* or the default mode if not used.
*/
private Mode nextMode;
/** The built-in modes. coreModes[0] will be considered the 'default'. */
private Mode[] coreModes;
protected List<ModeContribution> modeContribs;
protected List<ExamplesContribution> exampleContribs;
private JMenu sketchbookMenu;
// private Recent recent;
// Used by handleOpen(), this saves the chooser to remember the directory.
// Doesn't appear to be necessary with the AWT native file dialog.
// https://github.com/processing/processing/pull/2366
private JFileChooser openChooser;
static protected File sketchbookFolder;
// protected File toolsFolder;
static public void main(final String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
createAndShowGUI(args);
} catch (Throwable t) {
// Windows Defender has been insisting on destroying each new
// release by removing core.jar and other files. Yay!
// https://github.com/processing/processing/issues/5537
if (Platform.isWindows()) {
String mess = t.getMessage();
String missing = null;
if (mess.contains("Could not initialize class com.sun.jna.Native")) {
missing = "jnidispatch.dll";
} else if (mess.contains("NoClassDefFoundError: processing/core/PApplet")) {
missing = "core.jar";
}
if (missing != null) {
Messages.showError("Necessary files are missing",
"A file required by Processing (" + missing + ") is missing.\n\n" +
"Make sure that you're not trying to run Processing from inside\n" +
"the .zip file you downloaded, and check that Windows Defender\n" +
"hasn't removed files from the Processing folder.\n\n" +
"(It sometimes flags parts of Processing as a trojan or virus.\n" +
"It is neither, but Microsoft has ignored our pleas for help.)", t);
}
}
Messages.showTrace("Unknown Problem",
"A serious error happened during startup. Please report:\n" +
"http://github.com/processing/processing/issues/new", t, true);
}
}
});
}
static private void createAndShowGUI(String[] args) {
try {
File versionFile = Platform.getContentFile("lib/version.txt");
if (versionFile.exists()) {
String version = PApplet.loadStrings(versionFile)[0];
if (!version.equals(VERSION_NAME)) {
VERSION_NAME = version;
}
}
} catch (Exception e) {
e.printStackTrace();
}
Platform.init();
// call after Platform.init() because we need the settings folder
Console.startup();
// Set the debug flag based on a file being present in the settings folder
File debugFile = getSettingsFile("debug.txt");
/*
if (debugFile.isDirectory()) {
// if it's a directory, it's a leftover from older releases, clear it
Util.removeDir(debugFile);
} else*/
if (debugFile.exists()) {
DEBUG = true;
}
// Use native popups so they don't look so crappy on OS X
JPopupMenu.setDefaultLightWeightPopupEnabled(false);
// Don't put anything above this line that might make GUI,
// because the platform has to be inited properly first.
// Make sure a full JDK is installed
//initRequirements();
// Load the languages
Language.init();
// run static initialization that grabs all the prefs
Preferences.init();
if (!SingleInstance.alreadyRunning(args)) {
// Set the look and feel before opening the window
try {
Platform.setLookAndFeel();
} catch (Exception e) {
Messages.loge("Could not set the Look & Feel", e); //$NON-NLS-1$
}
boolean sketchbookPrompt = false;
if (Preferences.getBoolean("welcome.show")) {
// only ask once about split sketchbooks
if (!Preferences.getBoolean("welcome.seen")) {
// Check if there's a 2.0 sketchbook present
String oldPath = Preferences.getOldSketchbookPath();
if (oldPath != null) {
String newPath = Preferences.getSketchbookPath();
// If newPath is null, this is the first run of any 3.x version
if (newPath == null) {
sketchbookPrompt = true;
} else if (oldPath.equals(newPath)) {
// If both exist and are identical, then the user has used
// pre-releases of 3.x and needs to be warned about the
// larger changes in this release.
sketchbookPrompt = true;
}
}
}
}
// Get the sketchbook path, and make sure it's set properly
locateSketchbookFolder();
// Create a location for untitled sketches
try {
untitledFolder = Util.createTempFolder("untitled", "sketches", null);
untitledFolder.deleteOnExit();
} catch (IOException e) {
Messages.showError("Trouble without a name",
"Could not create a place to store untitled sketches.\n" +
"That's gonna prevent us from continuing.", e);
}
Messages.log("About to create Base..."); //$NON-NLS-1$
try {
final Base base = new Base(args);
Messages.log("Base() constructor succeeded");
// Prevent more than one copy of the PDE from running.
SingleInstance.startServer(base);
// Needs to be shown after the first editor window opens, so that it
// shows up on top, and doesn't prevent an editor window from opening.
if (Preferences.getBoolean("welcome.show")) {
try {
new Welcome(base, sketchbookPrompt);
} catch (IOException e) {
Messages.showTrace("Unwelcoming",
"Please report this error to\n" +
"https://github.com/processing/processing/issues", e, false);
}
}
checkDriverBug();
} catch (Throwable t) {
// Catch-all to pick up badness during startup.
if (t.getCause() != null) {
// Usually this is the more important piece of information. We'll
// show this one so that it's not truncated in the error window.
t = t.getCause();
}
Messages.showTrace("We're off on the wrong foot",
"An error occurred during startup.", t, true);
}
Messages.log("Done creating Base..."); //$NON-NLS-1$
}
}
// Remove this code in a couple months [fry 170211]
// https://github.com/processing/processing/issues/4853
// Or maybe not, if NVIDIA keeps doing this [fry 170423]
// https://github.com/processing/processing/issues/4997
static private void checkDriverBug() {
if (System.getProperty("os.name").contains("Windows 10")) {
new Thread(new Runnable() {
public void run() {
try {
Process p = Runtime.getRuntime().exec("powershell Get-WmiObject Win32_PnPSignedDriver| select devicename, driverversion | where {$_.devicename -like \\\"*nvidia*\\\"}");
BufferedReader reader = PApplet.createReader(p.getInputStream());
String line = null;
while ((line = reader.readLine()) != null) {
if (line.contains("3.7849")) {
EventQueue.invokeLater(new Runnable() {
public void run() {
Messages.showWarning("NVIDIA screwed up",
"Due to an NVIDIA bug, you need to update your graphics drivers,\n" +
"otherwise you won't be able to run any sketches. Update here:\n" +
"http://nvidia.custhelp.com/app/answers/detail/a_id/4378\n" +
"or read background about the issue at this link:\n" +
"https://github.com/processing/processing/issues/4853");
}
});
} else if (line.contains("3.8165")) {
EventQueue.invokeLater(new Runnable() {
public void run() {
Messages.showWarning("NVIDIA screwed up again",
"Due to an NVIDIA bug, you need to update your graphics drivers,\n" +
"otherwise you won't be able to run any sketches. Update here:\n" +
"http://nvidia.custhelp.com/app/answers/detail/a_id/4453/\n" +
"or read background about the issue at this link:\n" +
"https://github.com/processing/processing/issues/4997");
}
});
}
}
} catch (Exception e) {
Messages.loge("Problem checking NVIDIA driver", e);
}
}
}).start();
}
}
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
/**
* @return the current revision number, safe to be used for update checks
*/
static public int getRevision() {
return REVISION;
}
/**
* @return something like 2.2.1 or 3.0b4 (or 0213 if it's not a release)
*/
static public String getVersionName() {
return VERSION_NAME;
}
public static void setCommandLine() {
commandLine = true;
}
static public boolean isCommandLine() {
return commandLine;
}
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
public Base(String[] args) throws Exception {
ContributionManager.init(this);
buildCoreModes();
rebuildContribModes();
rebuildContribExamples();
// Needs to happen after the sketchbook folder has been located.
// Also relies on the modes to be loaded so it knows what can be
// marked as an example.
// recent = new Recent(this);
Recent.init(this);
String lastModeIdentifier = Preferences.get("mode.last"); //$NON-NLS-1$
if (lastModeIdentifier == null) {
nextMode = getDefaultMode();
Messages.log("Nothing set for last.sketch.mode, using default."); //$NON-NLS-1$
} else {
for (Mode m : getModeList()) {
if (m.getIdentifier().equals(lastModeIdentifier)) {
Messages.logf("Setting next mode to %s.", lastModeIdentifier); //$NON-NLS-1$
nextMode = m;
}
}
if (nextMode == null) {
nextMode = getDefaultMode();
Messages.logf("Could not find mode %s, using default.", lastModeIdentifier); //$NON-NLS-1$
}
}
//contributionManagerFrame = new ContributionManagerDialog();
// Make sure ThinkDifferent has library examples too
nextMode.rebuildLibraryList();
// Put this after loading the examples, so that building the default file
// menu works on Mac OS X (since it needs examplesFolder to be set).
Platform.initBase(this);
// toolsFolder = getContentFile("tools");
// // Check if there were previously opened sketches to be restored
// boolean opened = restoreSketches();
boolean opened = false;
// Check if any files were passed in on the command line
for (int i = 0; i < args.length; i++) {
Messages.logf("Parsing command line... args[%d] = '%s'", i, args[i]);
String path = args[i];
// Fix a problem with systems that use a non-ASCII languages. Paths are
// being passed in with 8.3 syntax, which makes the sketch loader code
// unhappy, since the sketch folder naming doesn't match up correctly.
// http://dev.processing.org/bugs/show_bug.cgi?id=1089
if (Platform.isWindows()) {
try {
File file = new File(args[i]);
path = file.getCanonicalPath();
Messages.logf("Changing %s to canonical %s", i, args[i], path);
} catch (IOException e) {
e.printStackTrace();
}
}
if (handleOpen(path) != null) {
opened = true;
}
}
// Create a new empty window (will be replaced with any files to be opened)
if (!opened) {
Messages.log("Calling handleNew() to open a new window");
handleNew();
} else {
Messages.log("No handleNew(), something passed on the command line");
}
// check for updates
new UpdateCheck(this);
ContributionListing cl = ContributionListing.getInstance();
cl.downloadAvailableList(this, new ContribProgressMonitor() { });
}
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
void buildCoreModes() {
Mode javaMode =
ModeContribution.load(this, Platform.getContentFile("modes/java"),
getDefaultModeIdentifier()).getMode();
// PDE X calls getModeList() while it's loading, so coreModes must be set
coreModes = new Mode[] { javaMode };
/*
Mode pdexMode =
ModeContribution.load(this, getContentFile("modes/ExperimentalMode"), //$NON-NLS-1$
"processing.mode.experimental.ExperimentalMode").getMode(); //$NON-NLS-1$
// Safe to remove the old Java mode here?
//coreModes = new Mode[] { pdexMode };
coreModes = new Mode[] { pdexMode, javaMode };
*/
}
/**
* Instantiates and adds new contributed modes to the contribModes list.
* Checks for duplicates so the same mode isn't instantiates twice. Does not
* remove modes because modes can't be removed once they are instantiated.
*/
void rebuildContribModes() {
if (modeContribs == null) {
modeContribs = new ArrayList<>();
}
File modesFolder = getSketchbookModesFolder();
List<ModeContribution> contribModes = getModeContribs();
Map<File, ModeContribution> known = new HashMap<>();
for (ModeContribution contrib : contribModes) {
known.put(contrib.getFolder(), contrib);
}
File[] potential = ContributionType.MODE.listCandidates(modesFolder);
// If modesFolder does not exist or is inaccessible (folks might like to
// mess with folders then report it as a bug) 'potential' will be null.
if (potential != null) {
for (File folder : potential) {
if (!known.containsKey(folder)) {
try {
contribModes.add(new ModeContribution(this, folder, null));
} catch (NoSuchMethodError nsme) {
System.err.println(folder.getName() + " is not compatible with this version of Processing");
if (DEBUG) nsme.printStackTrace();
} catch (NoClassDefFoundError ncdfe) {
System.err.println(folder.getName() + " is not compatible with this version of Processing");
if (DEBUG) ncdfe.printStackTrace();
} catch (InvocationTargetException ite) {
System.err.println(folder.getName() + " could not be loaded and may not compatible with this version of Processing");
if (DEBUG) ite.printStackTrace();
} catch (IgnorableException ig) {
Messages.log(ig.getMessage());
if (DEBUG) ig.printStackTrace();
} catch (Throwable e) {
System.err.println("Could not load Mode from " + folder);
e.printStackTrace();
}
} else {
known.remove(folder); // remove this item as already been seen
}
}
}
// This allows you to build and test your Mode code from Eclipse.
// -Dusemode=com.foo.FrobMode:/path/to/FrobMode
final String useMode = System.getProperty("usemode");
if (useMode != null) {
final String[] modeInfo = useMode.split(":", 2);
final String modeClass = modeInfo[0];
final String modeResourcePath = modeInfo[1];
System.out.println("Attempting to load " + modeClass + " with resources at " + modeResourcePath);
ModeContribution mc = ModeContribution.load(this, new File(modeResourcePath), modeClass);
contribModes.add(mc);
File key = getFileForContrib(mc, known);
if (key != null) {
known.remove(key);
}
}
if (known.size() != 0) {
for (ModeContribution mc : known.values()) {
System.out.println("Extraneous Mode entry: " + mc.getName());
}
}
}
static private File getFileForContrib(ModeContribution contrib,
Map<File, ModeContribution> known) {
for (Entry<File, ModeContribution> entry : known.entrySet()) {
if (entry.getValue() == contrib) {
return entry.getKey();
}
}
return null;
}
/**
* Instantiates and adds new contributed modes to the contribModes list.
* Checks for duplicates so the same mode isn't instantiates twice. Does not
* remove modes because modes can't be removed once they are instantiated.
*/
void rebuildContribExamples() {
if (exampleContribs == null) {
exampleContribs = new ArrayList<>();
}
ExamplesContribution.loadMissing(this);
}
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
/**
* Tools require an 'Editor' object when they're instantiated, but the
* activeEditor will be null when the first Editor that opens is creating
* its Tools menu. This will temporarily set the activeEditor to the one
* that's opening so that we don't go all NPE on startup. If there's already
* an active editor, then this does nothing.
*/
public void checkFirstEditor(Editor editor) {
if (activeEditor == null) {
activeEditor = editor;
}
}
/** Returns the front most, active editor window. */
public Editor getActiveEditor() {
return activeEditor;
}
/** Get the list of currently active editor windows. */
public List<Editor> getEditors() {
return editors;
}
/**
* Called when a window is activated. Because of variations in native
* windowing systems, no guarantees about changes to the focused and active
* Windows can be made. Never assume that this Window is the focused or
* active Window until this Window actually receives a WINDOW_GAINED_FOCUS
* or WINDOW_ACTIVATED event.
*/
public void handleActivated(Editor whichEditor) {
activeEditor = whichEditor;
// set the current window to be the console that's getting output
EditorConsole.setEditor(activeEditor);
// make this the next mode to be loaded
nextMode = whichEditor.getMode();
Preferences.set("mode.last", nextMode.getIdentifier()); //$NON-NLS-1$
}
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
public void refreshContribs(ContributionType ct) {
if (ct == ContributionType.LIBRARY) {
for (Mode m : getModeList()) {
m.rebuildImportMenu();
}
} else if (ct == ContributionType.MODE) {
rebuildContribModes();
for (Editor editor : editors) {
editor.rebuildModePopup();
}
} else if (ct == ContributionType.TOOL) {
rebuildToolList();
for (Editor editor : editors) {
populateToolsMenu(editor.getToolMenu());
}
} else if (ct == ContributionType.EXAMPLES) {
rebuildContribExamples();
for (Mode m : getModeList()) {
m.rebuildExamplesFrame();
}
}
}
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
private int updatesAvailable = 0;
public void setUpdatesAvailable(int n) {
updatesAvailable = n;
synchronized (editors) {
for (Editor e : editors) {
e.setUpdatesAvailable(n);
}
}
}
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
List<Tool> internalTools;
List<ToolContribution> coreTools;
List<ToolContribution> contribTools;
public List<ToolContribution> getCoreTools() {
return coreTools;
}
public List<ToolContribution> getToolContribs() {
return contribTools;
}
public void removeToolContrib(ToolContribution tc) {
contribTools.remove(tc);
}
public void rebuildToolList() {
// Only do this once because the list of internal tools will never change
if (internalTools == null) {
internalTools = new ArrayList<>();
initInternalTool("processing.app.tools.CreateFont");
initInternalTool("processing.app.tools.ColorSelector");
initInternalTool("processing.app.tools.Archiver");
if (Platform.isMacOS()) {
initInternalTool("processing.app.tools.InstallCommander");
}
}
// No need to reload these either
if (coreTools == null) {
coreTools = ToolContribution.loadAll(Base.getToolsFolder());
for (Tool tool : coreTools) {
tool.init(this);
}
}
// Rebuilt when new tools installed, etc
contribTools = ToolContribution.loadAll(Base.getSketchbookToolsFolder());
for (Tool tool : contribTools) {
try {
tool.init(this);
// With the exceptions, we can't call statusError because the window
// isn't completely set up yet. Also not gonna pop up a warning because
// people may still be running different versions of Processing.
} catch (VerifyError ve) {
System.err.println("\"" + tool.getMenuTitle() + "\" is not " +
"compatible with this version of Processing");
} catch (NoSuchMethodError nsme) {
System.err.println("\"" + tool.getMenuTitle() + "\" is not " +
"compatible with this version of Processing");
System.err.println("The " + nsme.getMessage() + " method no longer exists.");
Messages.loge("Incompatible Tool found during tool.init()", nsme);
} catch (NoClassDefFoundError ncdfe) {
System.err.println("\"" + tool.getMenuTitle() + "\" is not " +
"compatible with this version of Processing");
System.err.println("The " + ncdfe.getMessage() + " class is no longer available.");
Messages.loge("Incompatible Tool found during tool.init()", ncdfe);
} catch (AbstractMethodError ame) {
System.err.println("\"" + tool.getMenuTitle() + "\" is not " +
"compatible with this version of Processing");
// ame.printStackTrace();
} catch (Error err) {
System.err.println("An error occurred inside \"" + tool.getMenuTitle() + "\"");
err.printStackTrace();
} catch (Exception ex) {
System.err.println("An exception occurred inside \"" + tool.getMenuTitle() + "\"");
ex.printStackTrace();
}
}
}
protected void initInternalTool(String className) {
try {
Class<?> toolClass = Class.forName(className);
final Tool tool = (Tool)
toolClass.getDeclaredConstructor().newInstance();
tool.init(this);
internalTools.add(tool);
} catch (Exception e) {
e.printStackTrace();
}
}
/*
Iterator<Editor> editorIter = base.getEditors().iterator();
while (editorIter.hasNext()) {
Editor editor = editorIter.next();
List<ToolContribution> contribTools = editor.getToolContribs();
for (ToolContribution toolContrib : contribTools) {
if (toolContrib.getName().equals(this.name)) {
try {
((URLClassLoader) toolContrib.loader).close();
editor.removeToolContrib(toolContrib);
break;
} catch (IOException e) {
e.printStackTrace();
}
}
}
*/
public void clearToolMenus() {
for (Editor ed : editors) {
ed.clearToolMenu();
}
}
public void populateToolsMenu(JMenu toolsMenu) {
// If this is the first run, need to build out the lists
if (internalTools == null) {
rebuildToolList();
}
// coreTools = ToolContribution.loadAll(Base.getToolsFolder());
// contribTools = ToolContribution.loadAll(Base.getSketchbookToolsFolder());
// Collections.sort(coreTools);
// Collections.sort(contribTools);
// Collections.sort(coreTools, new Comparator<ToolContribution>() {
// @Override
// public int compare(ToolContribution o1, ToolContribution o2) {
// return o1.getMenuTitle().compareTo(o2.getMenuTitle());
// }
// });
toolsMenu.removeAll();
for (Tool tool : internalTools) {
toolsMenu.add(createToolItem(tool));
}
toolsMenu.addSeparator();
if (coreTools.size() > 0) {
for (Tool tool : coreTools) {
toolsMenu.add(createToolItem(tool));
}
toolsMenu.addSeparator();
}
if (contribTools.size() > 0) {
for (Tool tool : contribTools) {
toolsMenu.add(createToolItem(tool));
}
toolsMenu.addSeparator();
}
JMenuItem item = new JMenuItem(Language.text("menu.tools.add_tool"));
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ContributionManager.openTools();
}
});
toolsMenu.add(item);
}
/*
static public void addTools(JMenu menu, List<Tool> tools) {
Map<String, JMenuItem> toolItems = new HashMap<String, JMenuItem>();
for (final Tool tool : tools) {
// If init() fails, the item won't be added to the menu
addToolItem(tool, toolItems);
}
List<String> toolList = new ArrayList<String>(toolItems.keySet());
if (toolList.size() > 0) {
if (menu.getItemCount() != 0) {
menu.addSeparator();
}
Collections.sort(toolList);
for (String title : toolList) {
menu.add(toolItems.get(title));
}
}
}
*/
JMenuItem createToolItem(final Tool tool) { //, Map<String, JMenuItem> toolItems) {
String title = tool.getMenuTitle();
final JMenuItem item = new JMenuItem(title);
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
tool.run();
} catch (NoSuchMethodError nsme) {
activeEditor.statusError("\"" + tool.getMenuTitle() + "\" is not" +
"compatible with this version of Processing");
//nsme.printStackTrace();
Messages.loge("Incompatible tool found during tool.run()", nsme);
item.setEnabled(false);
} catch (Exception ex) {
activeEditor.statusError("An error occurred inside \"" + tool.getMenuTitle() + "\"");
ex.printStackTrace();
item.setEnabled(false);
}
}
});
//toolItems.put(title, item);
return item;
}
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
public List<ModeContribution> getModeContribs() {
return modeContribs;
}
public List<Mode> getModeList() {
List<Mode> allModes = new ArrayList<>();
allModes.addAll(Arrays.asList(coreModes));
if (modeContribs != null) {
for (ModeContribution contrib : modeContribs) {
allModes.add(contrib.getMode());
}
}
return allModes;
}
public List<ExamplesContribution> getExampleContribs() {
return exampleContribs;
}
private List<Contribution> getInstalledContribs() {
List<Contribution> contributions = new ArrayList<>();
List<ModeContribution> modeContribs = getModeContribs();
contributions.addAll(modeContribs);
for (ModeContribution modeContrib : modeContribs) {
Mode mode = modeContrib.getMode();
contributions.addAll(new ArrayList<>(mode.contribLibraries));
}
// TODO this duplicates code in Editor, but it's not editor-specific
// List<ToolContribution> toolContribs =
// ToolContribution.loadAll(Base.getSketchbookToolsFolder());
// contributions.addAll(toolContribs);
contributions.addAll(ToolContribution.loadAll(getSketchbookToolsFolder()));
contributions.addAll(getExampleContribs());
return contributions;
}
public byte[] getInstalledContribsInfo() {
List<Contribution> contribs = getInstalledContribs();
StringList entries = new StringList();
for (Contribution c : contribs) {
String entry = c.getTypeName() + "=" +
PApplet.urlEncode(String.format("name=%s\nurl=%s\nrevision=%d\nversion=%s",
c.getName(), c.getUrl(),
c.getVersion(), c.getBenignVersion()));
entries.append(entry);
}
String joined =
"id=" + UpdateCheck.getUpdateID() + "&" + entries.join("&");
// StringBuilder sb = new StringBuilder();
// try {
// // Truly ridiculous attempt to shove everything into a GET request.
// // More likely to be seen as part of a grand plot.
// ByteArrayOutputStream baos = new ByteArrayOutputStream();
// GZIPOutputStream output = new GZIPOutputStream(baos);
// PApplet.saveStream(output, new ByteArrayInputStream(joined.getBytes()));
// output.close();
// byte[] b = baos.toByteArray();
// for (int i = 0; i < b.length; i++) {
// sb.append(PApplet.hex(b[i], 2));
// }
// } catch (IOException e) {
// e.printStackTrace();
// }
// return sb.toString();
return joined.getBytes();
}
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
/**
* Create or modify a sketch.proprties file to specify the given Mode.
*/
private void saveModeSettings(final File sketchProps, final Mode mode) {
try {
final Settings settings = new Settings(sketchProps);
settings.set("mode", mode.getTitle());
settings.set("mode.id", mode.getIdentifier());
settings.save();
} catch (IOException e) {
System.err.println("While creating " + sketchProps + ": " + e.getMessage());
}
}
String getDefaultModeIdentifier() {
return "processing.mode.java.JavaMode";
}
public Mode getDefaultMode() {
return coreModes[0];
}
/** Used by ThinkDifferent so that it can have a Sketchbook menu. */
public Mode getNextMode() {
return nextMode;
}
/**
* The call has already checked to make sure this sketch is not modified,
* now change the mode.
* @return true if mode is changed.
*/
public boolean changeMode(Mode mode) {
Mode oldMode = activeEditor.getMode();
if (oldMode != mode) {
Sketch sketch = activeEditor.getSketch();
nextMode = mode;
if (sketch.isUntitled()) {
// The current sketch is empty, just close and start fresh.
// (Otherwise the editor would lose its 'untitled' status.)
handleClose(activeEditor, true);