forked from chipKIT32/chipKIT32-MAX
/
Base.java
2394 lines (1966 loc) · 74.1 KB
/
Base.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) 2004-10 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.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import javax.swing.*;
import org.apache.log4j.BasicConfigurator;
//import org.apache.log4j.PropertyConfigurator;
import org.apache.log4j.Logger;
import org.apache.log4j.Level;
import processing.app.debug.Compiler;
import processing.app.debug.Target;
import processing.core.*;
/**
* 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 {
//private static Logger logger = Logger.getLogger(Base.class.getName());
static Logger logger = Logger.getLogger(Base.class.getName());
public static final int REVISION = 22;
/** This might be replaced by main() if there's a lib/version.txt file. */
static String VERSION_NAME = "0022";
/** Set true if this a proper release rather than a numbered revision. */
static public boolean RELEASE = false;
static HashMap<Integer, String> platformNames = new HashMap<Integer, String>();
static {
platformNames.put(PConstants.WINDOWS, "windows");
platformNames.put(PConstants.MACOSX, "macosx");
platformNames.put(PConstants.LINUX, "linux");
}
static HashMap<String, Integer> platformIndices = new HashMap<String, Integer>();
static {
platformIndices.put("windows", PConstants.WINDOWS);
platformIndices.put("macosx", PConstants.MACOSX);
platformIndices.put("linux", PConstants.LINUX);
}
static Platform platform;
static private boolean commandLine;
// A single instance of the preferences window
Preferences preferencesFrame;
// set to true after the first time the menu is built.
// so that the errors while building don't show up again.
boolean builtOnce;
static File buildFolder;
// these are static because they're used by Sketch
static private File examplesFolder;
static private File librariesFolder;
static private File toolsFolder;
static private File hardwareFolder;
static HashSet<File> libraries;
// maps imported packages to their library folder
static HashMap<String, File> importToLibraryTable;
// classpath for all known libraries for p5
// (both those in the p5/libs folder and those with lib subfolders
// found in the sketchbook)
static public String librariesClassPath;
static public HashMap<String, Target> targetsTable;
// Location for untitled items
static File untitledFolder;
// p5 icon for the window
// static Image icon;
// int editorCount;
// Editor[] editors;
java.util.List<Editor> editors =
Collections.synchronizedList(new ArrayList<Editor>());
// ArrayList editors = Collections.synchronizedList(new ArrayList<Editor>());
Editor activeEditor;
static public void main(String args[]) {
try {
BasicConfigurator.configure();
Logger.getRootLogger().setLevel(Level.DEBUG);
logger.debug("DEBUG: Logging enabled." + Base.class.getName());
File versionFile = getContentFile("lib/version.txt");
if (versionFile.exists()) {
String version = PApplet.loadStrings(versionFile)[0];
if (!version.equals(VERSION_NAME)) {
VERSION_NAME = version;
RELEASE = true;
}
}
} catch (Exception e) {
e.printStackTrace();
}
initPlatform();
// // Set the look and feel before opening the window
// try {
// platform.setLookAndFeel();
// } catch (Exception e) {
// System.err.println("Non-fatal error while setting the Look & Feel.");
// System.err.println("The error message follows, however Processing should run fine.");
// System.err.println(e.getMessage());
// //e.printStackTrace();
// }
// Use native popups so they don't look so crappy on osx
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();
// run static initialization that grabs all the prefs
Preferences.init(null);
// setup the theme coloring fun
Theme.init();
// Set the look and feel before opening the window
try {
platform.setLookAndFeel();
} catch (Exception e) {
String mess = e.getMessage();
if (mess.indexOf("ch.randelshofer.quaqua.QuaquaLookAndFeel") == -1) {
System.err.println("Non-fatal error while setting the Look & Feel.");
System.err.println("The error message follows, however Arduino should run fine.");
System.err.println(mess);
}
}
// Create a location for untitled sketches
untitledFolder = createTempFolder("untitled");
untitledFolder.deleteOnExit();
new Base(args);
}
static protected void setCommandLine() {
commandLine = true;
}
static protected boolean isCommandLine() {
return commandLine;
}
static protected void initPlatform() {
try {
Class<?> platformClass = Class.forName("processing.app.Platform");
if (Base.isMacOS()) {
platformClass = Class.forName("processing.app.macosx.Platform");
} else if (Base.isWindows()) {
platformClass = Class.forName("processing.app.windows.Platform");
} else if (Base.isLinux()) {
platformClass = Class.forName("processing.app.linux.Platform");
}
platform = (Platform) platformClass.newInstance();
} catch (Exception e) {
Base.showError("Problem Setting the Platform",
"An unknown error occurred while trying to load\n" +
"platform-specific code for your machine.", e);
}
}
static protected void initRequirements() {
try {
Class.forName("com.sun.jdi.VirtualMachine");
} catch (ClassNotFoundException cnfe) {
Base.showPlatforms();
Base.showError("Please install JDK 1.5 or later",
"Arduino requires a full JDK (not just a JRE)\n" +
"to run. Please install JDK 1.5 or later.\n" +
"More information can be found in the reference.", cnfe);
}
}
public Base(String[] args) {
platform.init(this);
// Get paths for the libraries and examples in the Processing folder
//String workingDirectory = System.getProperty("user.dir");
//Issue: 104 Need to support loading examples, and libraries based on platform
examplesFolder = getContentFile("examples");
librariesFolder = getContentFile("libraries");
toolsFolder = getContentFile("tools");
// Get the sketchbook path, and make sure it's set properly
String sketchbookPath = Preferences.get("sketchbook.path");
// If a value is at least set, first check to see if the folder exists.
// If it doesn't, warn the user that the sketchbook folder is being reset.
if (sketchbookPath != null) {
File skechbookFolder = new File(sketchbookPath);
if (!skechbookFolder.exists()) {
Base.showWarning("Sketchbook folder disappeared",
"The sketchbook folder no longer exists.\n" +
"Arduino will switch to the default sketchbook\n" +
"location, and create a new sketchbook folder if\n" +
"necessary. Arduino will then stop talking about\n" +
"himself in the third person.", null);
sketchbookPath = null;
}
}
// If no path is set, get the default sketchbook folder for this platform
if (sketchbookPath == null) {
File defaultFolder = getDefaultSketchbookFolder();
Preferences.set("sketchbook.path", defaultFolder.getAbsolutePath());
if (!defaultFolder.exists()) {
defaultFolder.mkdirs();
}
}
targetsTable = new HashMap<String, Target>();
loadHardware(getHardwareFolder());
loadHardware(getSketchbookHardwareFolder());
// Check if there were previously opened sketches to be restored
boolean opened = restoreSketches();
// Check if any files were passed in on the command line
for (int i = 0; i < args.length; 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 (isWindows()) {
try {
File file = new File(args[i]);
path = file.getCanonicalPath();
} 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) {
handleNew();
}
// check for updates
if (Preferences.getBoolean("update.check")) {
new UpdateCheck(this);
}
}
/**
* Post-constructor setup for the editor area. Loads the last
* sketch that was used (if any), and restores other Editor settings.
* The complement to "storePreferences", this is called when the
* application is first launched.
*/
protected boolean restoreSketches() {
// figure out window placement
Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
boolean windowPositionValid = true;
if (Preferences.get("last.screen.height") != null) {
// if screen size has changed, the window coordinates no longer
// make sense, so don't use them unless they're identical
int screenW = Preferences.getInteger("last.screen.width");
int screenH = Preferences.getInteger("last.screen.height");
if ((screen.width != screenW) || (screen.height != screenH)) {
windowPositionValid = false;
}
/*
int windowX = Preferences.getInteger("last.window.x");
int windowY = Preferences.getInteger("last.window.y");
if ((windowX < 0) || (windowY < 0) ||
(windowX > screenW) || (windowY > screenH)) {
windowPositionValid = false;
}
*/
} else {
windowPositionValid = false;
}
// Iterate through all sketches that were open last time p5 was running.
// If !windowPositionValid, then ignore the coordinates found for each.
// Save the sketch path and window placement for each open sketch
int count = Preferences.getInteger("last.sketch.count");
int opened = 0;
for (int i = 0; i < count; i++) {
String path = Preferences.get("last.sketch" + i + ".path");
int[] location;
if (windowPositionValid) {
String locationStr = Preferences.get("last.sketch" + i + ".location");
location = PApplet.parseInt(PApplet.split(locationStr, ','));
} else {
location = nextEditorLocation();
}
// If file did not exist, null will be returned for the Editor
if (handleOpen(path, location) != null) {
opened++;
}
}
return (opened > 0);
}
/**
* Store list of sketches that are currently open.
* Called when the application is quitting and documents are still open.
*/
protected void storeSketches() {
// Save the width and height of the screen
Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
Preferences.setInteger("last.screen.width", screen.width);
Preferences.setInteger("last.screen.height", screen.height);
String untitledPath = untitledFolder.getAbsolutePath();
// Save the sketch path and window placement for each open sketch
int index = 0;
for (Editor editor : editors) {
String path = editor.getSketch().getMainFilePath();
// In case of a crash, save untitled sketches if they contain changes.
// (Added this for release 0158, may not be a good idea.)
if (path.startsWith(untitledPath) &&
!editor.getSketch().isModified()) {
continue;
}
Preferences.set("last.sketch" + index + ".path", path);
int[] location = editor.getPlacement();
String locationStr = PApplet.join(PApplet.str(location), ",");
Preferences.set("last.sketch" + index + ".location", locationStr);
index++;
}
Preferences.setInteger("last.sketch.count", index);
}
// If a sketch is untitled on quit, may need to store the new name
// rather than the location from the temp folder.
protected void storeSketchPath(Editor editor, int index) {
String path = editor.getSketch().getMainFilePath();
String untitledPath = untitledFolder.getAbsolutePath();
if (path.startsWith(untitledPath)) {
path = "";
}
Preferences.set("last.sketch" + index + ".path", path);
}
/*
public void storeSketch(Editor editor) {
int index = -1;
for (int i = 0; i < editorCount; i++) {
if (editors[i] == editor) {
index = i;
break;
}
}
if (index == -1) {
System.err.println("Problem storing sketch " + editor.sketch.name);
} else {
String path = editor.sketch.getMainFilePath();
Preferences.set("last.sketch" + index + ".path", path);
}
}
*/
// .................................................................
// Because of variations in native windowing systems, no guarantees about
// changes to the focused and active Windows can be made. Developers must
// never assume that this Window is the focused or active Window until this
// Window receives a WINDOW_GAINED_FOCUS or WINDOW_ACTIVATED event.
protected void handleActivated(Editor whichEditor) {
activeEditor = whichEditor;
// set the current window to be the console that's getting output
EditorConsole.setEditor(activeEditor);
}
protected int[] nextEditorLocation() {
Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
int defaultWidth = Preferences.getInteger("editor.window.width.default");
int defaultHeight = Preferences.getInteger("editor.window.height.default");
if (activeEditor == null) {
// If no current active editor, use default placement
return new int[] {
(screen.width - defaultWidth) / 2,
(screen.height - defaultHeight) / 2,
defaultWidth, defaultHeight, 0
};
} else {
// With a currently active editor, open the new window
// using the same dimensions, but offset slightly.
synchronized (editors) {
final int OVER = 50;
// In release 0160, don't
//location = activeEditor.getPlacement();
Editor lastOpened = editors.get(editors.size() - 1);
int[] location = lastOpened.getPlacement();
// Just in case the bounds for that window are bad
location[0] += OVER;
location[1] += OVER;
if (location[0] == OVER ||
location[2] == OVER ||
location[0] + location[2] > screen.width ||
location[1] + location[3] > screen.height) {
// Warp the next window to a randomish location on screen.
return new int[] {
(int) (Math.random() * (screen.width - defaultWidth)),
(int) (Math.random() * (screen.height - defaultHeight)),
defaultWidth, defaultHeight, 0
};
}
return location;
}
}
}
// .................................................................
boolean breakTime = false;
String[] months = {
"jan", "feb", "mar", "apr", "may", "jun",
"jul", "aug", "sep", "oct", "nov", "dec"
};
/**
* Handle creating a sketch folder, return its base .pde file
* or null if the operation was canceled.
* @param shift whether shift is pressed, which will invert prompt setting
* @param noPrompt disable prompt, no matter the setting
*/
protected String createNewUntitled() throws IOException {
File newbieDir = null;
String newbieName = null;
// In 0126, untitled sketches will begin in the temp folder,
// and then moved to a new location because Save will default to Save As.
File sketchbookDir = getSketchbookFolder();
File newbieParentDir = untitledFolder;
// Use a generic name like sketch_031008a, the date plus a char
int index = 0;
//SimpleDateFormat formatter = new SimpleDateFormat("yyMMdd");
//SimpleDateFormat formatter = new SimpleDateFormat("MMMdd");
//String purty = formatter.format(new Date()).toLowerCase();
Calendar cal = Calendar.getInstance();
int day = cal.get(Calendar.DAY_OF_MONTH); // 1..31
int month = cal.get(Calendar.MONTH); // 0..11
String purty = months[month] + PApplet.nf(day, 2);
do {
if (index == 26) {
// In 0159, avoid running past z by sending people outdoors.
if (!breakTime) {
Base.showWarning("Time for a Break",
"You've reached the limit for auto naming of new sketches\n" +
"for the day. How about going for a walk instead?", null);
breakTime = true;
} else {
Base.showWarning("Sunshine",
"No really, time for some fresh air for you.", null);
}
return null;
}
newbieName = "sketch_" + purty + ((char) ('a' + index));
newbieDir = new File(newbieParentDir, newbieName);
index++;
// Make sure it's not in the temp folder *and* it's not in the sketchbook
} while (newbieDir.exists() || new File(sketchbookDir, newbieName).exists());
// Make the directory for the new sketch
newbieDir.mkdirs();
// Make an empty pde file
File newbieFile = new File(newbieDir, newbieName + ".pde");
new FileOutputStream(newbieFile); // create the file
return newbieFile.getAbsolutePath();
}
/**
* Create a new untitled document in a new sketch window.
*/
public void handleNew() {
try {
String path = createNewUntitled();
if (path != null) {
Editor editor = handleOpen(path);
editor.untitled = true;
}
} catch (IOException e) {
if (activeEditor != null) {
activeEditor.statusError(e);
}
}
}
/**
* Replace the sketch in the current window with a new untitled document.
*/
public void handleNewReplace() {
if (!activeEditor.checkModified()) {
return; // sketch was modified, and user canceled
}
// Close the running window, avoid window boogers with multiple sketches
activeEditor.internalCloseRunner();
// Actually replace things
handleNewReplaceImpl();
}
protected void handleNewReplaceImpl() {
try {
String path = createNewUntitled();
if (path != null) {
activeEditor.handleOpenInternal(path);
activeEditor.untitled = true;
}
// return true;
} catch (IOException e) {
activeEditor.statusError(e);
// return false;
}
}
/**
* Open a sketch, replacing the sketch in the current window.
* @param path Location of the primary pde file for the sketch.
*/
public void handleOpenReplace(String path) {
if (!activeEditor.checkModified()) {
return; // sketch was modified, and user canceled
}
// Close the running window, avoid window boogers with multiple sketches
activeEditor.internalCloseRunner();
boolean loaded = activeEditor.handleOpenInternal(path);
if (!loaded) {
// replace the document without checking if that's ok
handleNewReplaceImpl();
}
}
/**
* Prompt for a sketch to open, and open it in a new window.
*/
public void handleOpenPrompt() {
// get the frontmost window frame for placing file dialog
FileDialog fd = new FileDialog(activeEditor,
"Open an Arduino sketch...",
FileDialog.LOAD);
// This was annoying people, so disabled it in 0125.
//fd.setDirectory(Preferences.get("sketchbook.path"));
//fd.setDirectory(getSketchbookPath());
// Only show .pde files as eligible bachelors
fd.setFilenameFilter(new FilenameFilter() {
public boolean accept(File dir, String name) {
// TODO this doesn't seem to ever be used. AWESOME.
//System.out.println("check filter on " + dir + " " + name);
return name.toLowerCase().endsWith(".pde");
}
});
fd.setVisible(true);
String directory = fd.getDirectory();
String filename = fd.getFile();
// User canceled selection
if (filename == null) return;
File inputFile = new File(directory, filename);
handleOpen(inputFile.getAbsolutePath());
}
/**
* Open a sketch in a new window.
* @param path Path to the pde file for the sketch in question
* @return the Editor object, so that properties (like 'untitled')
* can be set by the caller
*/
public Editor handleOpen(String path) {
return handleOpen(path, nextEditorLocation());
}
protected Editor handleOpen(String path, int[] location) {
// System.err.println("entering handleOpen " + path);
File file = new File(path);
if (!file.exists()) return null;
// System.err.println(" editors: " + editors);
// Cycle through open windows to make sure that it's not already open.
for (Editor editor : editors) {
if (editor.getSketch().getMainFilePath().equals(path)) {
editor.toFront();
// System.err.println(" handleOpen: already opened");
return editor;
}
}
// If the active editor window is an untitled, and un-modified document,
// just replace it with the file that's being opened.
// if (activeEditor != null) {
// Sketch activeSketch = activeEditor.sketch;
// if (activeSketch.isUntitled() && !activeSketch.isModified()) {
// // if it's an untitled, unmodified document, it can be replaced.
// // except in cases where a second blank window is being opened.
// if (!path.startsWith(untitledFolder.getAbsolutePath())) {
// activeEditor.handleOpenUnchecked(path, 0, 0, 0, 0);
// return activeEditor;
// }
// }
// }
// System.err.println(" creating new editor");
Editor editor = new Editor(this, path, location);
// Editor editor = null;
// try {
// editor = new Editor(this, path, location);
// } catch (Exception e) {
// e.printStackTrace();
// System.err.flush();
// System.out.flush();
// System.exit(1);
// }
// System.err.println(" done creating new editor");
// EditorConsole.systemErr.println(" done creating new editor");
// Make sure that the sketch actually loaded
if (editor.getSketch() == null) {
// System.err.println("sketch was null, getting out of handleOpen");
return null; // Just walk away quietly
}
// if (editors == null) {
// editors = new Editor[5];
// }
// if (editorCount == editors.length) {
// editors = (Editor[]) PApplet.expand(editors);
// }
// editors[editorCount++] = editor;
editors.add(editor);
// if (markedForClose != null) {
// Point p = markedForClose.getLocation();
// handleClose(markedForClose, false);
// // open the new window in
// editor.setLocation(p);
// }
// now that we're ready, show the window
// (don't do earlier, cuz we might move it based on a window being closed)
editor.setVisible(true);
// System.err.println("exiting handleOpen");
return editor;
}
/**
* Close a sketch as specified by its editor window.
* @param editor Editor object of the sketch to be closed.
* @return true if succeeded in closing, false if canceled.
*/
public boolean handleClose(Editor editor) {
// Check if modified
// boolean immediate = editors.size() == 1;
if (!editor.checkModified()) {
return false;
}
// Close the running window, avoid window boogers with multiple sketches
editor.internalCloseRunner();
if (editors.size() == 1) {
// For 0158, when closing the last window /and/ it was already an
// untitled sketch, just give up and let the user quit.
// if (Preferences.getBoolean("sketchbook.closing_last_window_quits") ||
// (editor.untitled && !editor.getSketch().isModified())) {
if (Base.isMacOS()) {
Object[] options = { "OK", "Cancel" };
String prompt =
"<html> " +
"<head> <style type=\"text/css\">"+
"b { font: 13pt \"Lucida Grande\" }"+
"p { font: 11pt \"Lucida Grande\"; margin-top: 8px }"+
"</style> </head>" +
"<b>Are you sure you want to Quit?</b>" +
"<p>Closing the last open sketch will quit Arduino.";
int result = JOptionPane.showOptionDialog(editor,
prompt,
"Quit",
JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE,
null,
options,
options[0]);
if (result == JOptionPane.NO_OPTION ||
result == JOptionPane.CLOSED_OPTION) {
return false;
}
}
// This will store the sketch count as zero
editors.remove(editor);
Editor.serialMonitor.closeSerialPort();
storeSketches();
// Save out the current prefs state
Preferences.save();
// Since this wasn't an actual Quit event, call System.exit()
System.exit(0);
} else {
// More than one editor window open,
// proceed with closing the current window.
editor.setVisible(false);
editor.dispose();
// for (int i = 0; i < editorCount; i++) {
// if (editor == editors[i]) {
// for (int j = i; j < editorCount-1; j++) {[ic
// editors[j] = editors[j+1];
// }
// editorCount--;
// // Set to null so that garbage collection occurs
// editors[editorCount] = null;
// }
// }
editors.remove(editor);
}
return true;
}
/**
* Handler for File → Quit.
* @return false if canceled, true otherwise.
*/
public boolean handleQuit() {
// If quit is canceled, this will be replaced anyway
// by a later handleQuit() that is not canceled.
storeSketches();
Editor.serialMonitor.closeSerialPort();
if (handleQuitEach()) {
// make sure running sketches close before quitting
for (Editor editor : editors) {
editor.internalCloseRunner();
}
// Save out the current prefs state
Preferences.save();
if (!Base.isMacOS()) {
// If this was fired from the menu or an AppleEvent (the Finder),
// then Mac OS X will send the terminate signal itself.
System.exit(0);
}
return true;
}
return false;
}
/**
* Attempt to close each open sketch in preparation for quitting.
* @return false if canceled along the way
*/
protected boolean handleQuitEach() {
int index = 0;
for (Editor editor : editors) {
if (editor.checkModified()) {
// Update to the new/final sketch path for this fella
storeSketchPath(editor, index);
index++;
} else {
return false;
}
}
return true;
}
// .................................................................
/**
* Asynchronous version of menu rebuild to be used on save and rename
* to prevent the interface from locking up until the menus are done.
*/
protected void rebuildSketchbookMenus() {
//System.out.println("async enter");
//new Exception().printStackTrace();
SwingUtilities.invokeLater(new Runnable() {
public void run() {
//System.out.println("starting rebuild");
rebuildSketchbookMenu(Editor.sketchbookMenu);
rebuildToolbarMenu(Editor.toolbarMenu);
//System.out.println("done with rebuild");
}
});
//System.out.println("async exit");
}
protected void rebuildToolbarMenu(JMenu menu) {
JMenuItem item;
menu.removeAll();
//System.out.println("rebuilding toolbar menu");
// Add the single "Open" item
item = Editor.newJMenuItem("Open...", 'O');
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
handleOpenPrompt();
}
});
menu.add(item);
menu.addSeparator();
// Add a list of all sketches and subfolders
try {
boolean sketches = addSketches(menu, getSketchbookFolder(), true);
//boolean sketches = addSketches(menu, getSketchbookFolder());
if (sketches) menu.addSeparator();
} catch (IOException e) {
e.printStackTrace();
}
//System.out.println("rebuilding examples menu");
// Add each of the subfolders of examples directly to the menu
try {
boolean found = addSketches(menu, examplesFolder, true);
if (found) menu.addSeparator();
found = addSketches(menu, getSketchbookLibrariesFolder(), true);
if (found) menu.addSeparator();
addSketches(menu, librariesFolder, true);
} catch (IOException e) {
e.printStackTrace();
}
/*
//System.out.println("rebuilding examples menu");
// Add each of the subfolders of examples directly to the menu
try {
boolean found = addSketches(menu, getPic32CoreLibraries(), true);
if (found) menu.addSeparator();
addSketches(menu, librariesFolder, true);
} catch (IOException e) {
e.printStackTrace();
}
}
*/
}
protected void rebuildSketchbookMenu(JMenu menu) {
//System.out.println("rebuilding sketchbook menu");
//new Exception().printStackTrace();
try {
menu.removeAll();
addSketches(menu, getSketchbookFolder(), false);
//addSketches(menu, getSketchbookFolder());
} catch (IOException e) {
e.printStackTrace();
}
}
public void rebuildImportMenu(JMenu importMenu) {
logger.debug("DEBUG:start: rebuilding import menu");
importMenu.removeAll();
// reset the set of libraries
libraries = new HashSet<File>();
// reset the table mapping imports to libraries
importToLibraryTable = new HashMap<String, File>();
// Add from the "libraries" subfolder in the Processing directory
//Choose which library to add by chip platform
try {
//Find the current target. Get the platform, and then select the correct name and core path.
String platformname = this.getBoardPreferences().get("platform");
String targetname = this.getPlatformPreferences(platformname).get("name");
String libraryPath = this.getPlatformPreferences(platformname).get("library.core.path");
logger.debug("library.core.path = " + libraryPath);
logger.debug("DEBUG: add libraries.");
JMenuItem platformItem = new JMenuItem(targetname);
platformItem.setEnabled(false);
importMenu.add(platformItem);
importMenu.addSeparator();
addLibraries(importMenu, getCoreLibraries(libraryPath));
} catch (IOException e) {
e.printStackTrace();
}
// Add libraries found in the sketchbook folder
int separatorIndex = importMenu.getItemCount();
try {
File sketchbookLibraries = getSketchbookLibrariesFolder();
boolean found = addLibraries(importMenu, sketchbookLibraries);
if (found) {
JMenuItem contrib = new JMenuItem("Contributed");
contrib.setEnabled(false);
importMenu.insert(contrib, separatorIndex);
importMenu.insertSeparator(separatorIndex);
}
} catch (IOException e) {
e.printStackTrace();
}