-
-
Notifications
You must be signed in to change notification settings - Fork 7k
/
Base.java
2448 lines (2076 loc) · 82.2 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 cc.arduino.Compiler;
import cc.arduino.Constants;
import cc.arduino.UpdatableBoardsLibsFakeURLsHandler;
import cc.arduino.UploaderUtils;
import cc.arduino.contributions.*;
import cc.arduino.contributions.libraries.ContributedLibrary;
import cc.arduino.contributions.libraries.LibrariesIndexer;
import cc.arduino.contributions.libraries.LibraryInstaller;
import cc.arduino.contributions.libraries.LibraryOfSameTypeComparator;
import cc.arduino.contributions.libraries.ui.LibraryManagerUI;
import cc.arduino.contributions.packages.ContributedPlatform;
import cc.arduino.contributions.packages.ContributionInstaller;
import cc.arduino.contributions.packages.ContributionsIndexer;
import cc.arduino.contributions.packages.ui.ContributionManagerUI;
import cc.arduino.files.DeleteFilesOnShutdown;
import cc.arduino.packages.DiscoveryManager;
import cc.arduino.packages.Uploader;
import cc.arduino.view.Event;
import cc.arduino.view.JMenuUtils;
import cc.arduino.view.SplashScreenHelper;
import com.github.zafarkhaja.semver.Version;
import org.apache.commons.compress.utils.IOUtils;
import org.apache.commons.lang3.StringUtils;
import processing.app.debug.TargetBoard;
import processing.app.debug.TargetPackage;
import processing.app.debug.TargetPlatform;
import processing.app.helpers.*;
import processing.app.helpers.filefilters.OnlyDirs;
import processing.app.helpers.filefilters.OnlyFilesWithExtension;
import processing.app.javax.swing.filechooser.FileNameExtensionFilter;
import processing.app.legacy.PApplet;
import processing.app.macosx.ThinkDifferent;
import processing.app.packages.LibraryList;
import processing.app.packages.UserLibrary;
import processing.app.packages.UserLibraryFolder.Location;
import processing.app.syntax.PdeKeywords;
import processing.app.syntax.SketchTextAreaDefaultInputMap;
import processing.app.tools.MenuScroller;
import processing.app.tools.ZipDeflater;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.List;
import java.util.Timer;
import java.util.*;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static processing.app.I18n.format;
import static processing.app.I18n.tr;
/**
* 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 final int RECENT_SKETCHES_MAX_SIZE = 10;
private static boolean commandLine;
public static volatile Base INSTANCE;
public static Map<String, Object> FIND_DIALOG_STATE = new HashMap<>();
private final ContributionInstaller contributionInstaller;
private final LibraryInstaller libraryInstaller;
private ContributionsSelfCheck contributionsSelfCheck;
// set to true after the first time the menu is built.
// so that the errors while building don't show up again.
boolean builtOnce;
// 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;
// Location for untitled items
static File untitledFolder;
// p5 icon for the window
// static Image icon;
// int editorCount;
List<Editor> editors = Collections.synchronizedList(new ArrayList<Editor>());
Editor activeEditor;
// these menus are shared so that the board and serial port selections
// are the same for all windows (since the board and serial port that are
// actually used are determined by the preferences, which are shared)
private List<JMenu> boardsCustomMenus;
private List<JMenuItem> programmerMenus;
private PdeKeywords pdeKeywords;
private final List<JMenuItem> recentSketchesMenuItems = new LinkedList<>();
static public void main(String args[]) throws Exception {
if (!OSUtils.isWindows()) {
// Those properties helps enabling anti-aliasing on Linux
// (but not on Windows where they made things worse actually
// and the font rendering becomes ugly).
// Those properties must be set before initializing any
// graphic object, otherwise they don't have any effect.
System.setProperty("awt.useSystemAAFontSettings", "on");
System.setProperty("swing.aatext", "true");
}
System.setProperty("java.net.useSystemProxies", "true");
if (OSUtils.isMacOS()) {
System.setProperty("apple.laf.useScreenMenuBar",
String.valueOf(!System.getProperty("os.version").startsWith("10.13")
|| isMacOsAboutMenuItemPresent()));
ThinkDifferent.init();
}
try {
INSTANCE = new Base(args);
} catch (Throwable e) {
e.printStackTrace(System.err);
System.exit(255);
}
}
@SuppressWarnings("deprecation")
public static boolean isMacOsAboutMenuItemPresent() {
return com.apple.eawt.Application.getApplication().isAboutMenuItemPresent();
}
static public void initLogger() {
Handler consoleHandler = new ConsoleLogger();
consoleHandler.setLevel(Level.ALL);
consoleHandler.setFormatter(new LogFormatter("%1$tl:%1$tM:%1$tS [%4$7s] %2$s: %5$s%n"));
Logger globalLogger = Logger.getLogger(Logger.GLOBAL_LOGGER_NAME);
globalLogger.setLevel(consoleHandler.getLevel());
// Remove default
Handler[] handlers = globalLogger.getHandlers();
for(Handler handler : handlers) {
globalLogger.removeHandler(handler);
}
Logger root = Logger.getLogger("");
handlers = root.getHandlers();
for(Handler handler : handlers) {
root.removeHandler(handler);
}
globalLogger.addHandler(consoleHandler);
Logger.getLogger("cc.arduino.packages.autocomplete").setParent(globalLogger);
Logger.getLogger("br.com.criativasoft.cpluslibparser").setParent(globalLogger);
Logger.getLogger(Base.class.getPackage().getName()).setParent(globalLogger);
}
static protected boolean isCommandLine() {
return commandLine;
}
// Returns a File object for the given pathname. If the pathname
// is not absolute, it is interpreted relative to the current
// directory when starting the IDE (which is not the same as the
// current working directory!).
static public File absoluteFile(String path) {
return BaseNoGui.absoluteFile(path);
}
public Base(String[] args) throws Exception {
Thread deleteFilesOnShutdownThread = new Thread(DeleteFilesOnShutdown.INSTANCE);
deleteFilesOnShutdownThread.setName("DeleteFilesOnShutdown");
Runtime.getRuntime().addShutdownHook(deleteFilesOnShutdownThread);
BaseNoGui.initLogger();
initLogger();
BaseNoGui.initPlatform();
BaseNoGui.getPlatform().init();
BaseNoGui.initPortableFolder();
// Look for a possible "--preferences-file" parameter and load preferences
BaseNoGui.initParameters(args);
CommandlineParser parser = new CommandlineParser(args);
parser.parseArgumentsPhase1();
commandLine = !parser.isGuiMode();
BaseNoGui.checkInstallationFolder();
// If no path is set, get the default sketchbook folder for this platform
if (BaseNoGui.getSketchbookPath() == null) {
File defaultFolder = getDefaultSketchbookFolderOrPromptForIt();
if (BaseNoGui.getPortableFolder() != null)
PreferencesData.set("sketchbook.path", BaseNoGui.getPortableSketchbookFolder());
else
PreferencesData.set("sketchbook.path", defaultFolder.getAbsolutePath());
if (!defaultFolder.exists()) {
defaultFolder.mkdirs();
}
}
SplashScreenHelper splash;
if (parser.isGuiMode()) {
// Setup all notification widgets
splash = new SplashScreenHelper(SplashScreen.getSplashScreen());
BaseNoGui.notifier = new GUIUserNotifier(this);
// Setup the theme coloring fun
Theme.init();
System.setProperty("swing.aatext", PreferencesData.get("editor.antialias", "true"));
// Set the look and feel before opening the window
try {
BaseNoGui.getPlatform().setLookAndFeel();
} catch (Exception e) {
// ignore
}
// Use native popups so they don't look so crappy on osx
JPopupMenu.setDefaultLightWeightPopupEnabled(false);
} else {
splash = new SplashScreenHelper(null);
}
splash.splashText(tr("Loading configuration..."));
BaseNoGui.initVersion();
// Don't put anything above this line that might make GUI,
// because the platform has to be inited properly first.
// Create a location for untitled sketches
untitledFolder = FileUtils.createTempFolder("untitled" + new Random().nextInt(Integer.MAX_VALUE), ".tmp");
DeleteFilesOnShutdown.add(untitledFolder);
splash.splashText(tr("Initializing packages..."));
BaseNoGui.initPackages();
parser.getUploadPort().ifPresent(BaseNoGui::selectSerialPort);
splash.splashText(tr("Preparing boards..."));
if (!isCommandLine()) {
rebuildBoardsMenu();
rebuildProgrammerMenu();
} else {
TargetBoard lastSelectedBoard = BaseNoGui.getTargetBoard();
if (lastSelectedBoard != null)
BaseNoGui.selectBoard(lastSelectedBoard);
}
// Setup board-dependent variables.
onBoardOrPortChange();
pdeKeywords = new PdeKeywords();
pdeKeywords.reload();
final GPGDetachedSignatureVerifier gpgDetachedSignatureVerifier = new GPGDetachedSignatureVerifier();
contributionInstaller = new ContributionInstaller(BaseNoGui.getPlatform(), gpgDetachedSignatureVerifier);
libraryInstaller = new LibraryInstaller(BaseNoGui.getPlatform(), gpgDetachedSignatureVerifier);
parser.parseArgumentsPhase2();
// Save the preferences. For GUI mode, this happens in the quit
// handler, but for other modes we should also make sure to save
// them.
if (parser.isForceSavePrefs()) {
PreferencesData.save();
}
if (parser.isInstallBoard()) {
ContributionsIndexer indexer = new ContributionsIndexer(
BaseNoGui.getSettingsFolder(), BaseNoGui.getHardwareFolder(),
BaseNoGui.getPlatform(), gpgDetachedSignatureVerifier);
ProgressListener progressListener = new ConsoleProgressListener();
contributionInstaller.updateIndex(progressListener);
indexer.parseIndex();
indexer.syncWithFilesystem();
String[] boardToInstallParts = parser.getBoardToInstall().split(":");
ContributedPlatform selected = null;
if (boardToInstallParts.length == 3) {
Optional<Version> version = VersionHelper.valueOf(boardToInstallParts[2]);
if (!version.isPresent()) {
System.out.println(format(tr("Invalid version {0}"), boardToInstallParts[2]));
System.exit(1);
}
selected = indexer.getIndex().findPlatform(boardToInstallParts[0], boardToInstallParts[1], version.get().toString());
} else if (boardToInstallParts.length == 2) {
List<ContributedPlatform> platformsByName = indexer.getIndex().findPlatforms(boardToInstallParts[0], boardToInstallParts[1]);
Collections.sort(platformsByName, new DownloadableContributionVersionComparator());
if (!platformsByName.isEmpty()) {
selected = platformsByName.get(platformsByName.size() - 1);
}
}
if (selected == null) {
System.out.println(tr("Selected board is not available"));
System.exit(1);
}
ContributedPlatform installed = indexer.getInstalled(boardToInstallParts[0], boardToInstallParts[1]);
if (!selected.isBuiltIn()) {
contributionInstaller.install(selected, progressListener);
}
if (installed != null && !installed.isBuiltIn()) {
contributionInstaller.remove(installed);
}
System.exit(0);
} else if (parser.isInstallLibrary()) {
BaseNoGui.onBoardOrPortChange();
ProgressListener progressListener = new ConsoleProgressListener();
libraryInstaller.updateIndex(progressListener);
LibrariesIndexer indexer = new LibrariesIndexer(BaseNoGui.getSettingsFolder());
indexer.parseIndex();
indexer.setLibrariesFolders(BaseNoGui.getLibrariesFolders());
indexer.rescanLibraries();
for (String library : parser.getLibraryToInstall().split(",")) {
String[] libraryToInstallParts = library.split(":");
ContributedLibrary selected = null;
if (libraryToInstallParts.length == 2) {
Optional<Version> version = VersionHelper.valueOf(libraryToInstallParts[1]);
if (!version.isPresent()) {
System.out.println(format(tr("Invalid version {0}"), libraryToInstallParts[1]));
System.exit(1);
}
selected = indexer.getIndex().find(libraryToInstallParts[0], version.get().toString());
} else if (libraryToInstallParts.length == 1) {
List<ContributedLibrary> librariesByName = indexer.getIndex().find(libraryToInstallParts[0]);
Collections.sort(librariesByName, new DownloadableContributionVersionComparator());
if (!librariesByName.isEmpty()) {
selected = librariesByName.get(librariesByName.size() - 1);
}
}
if (selected == null) {
System.out.println(tr("Selected library is not available"));
System.exit(1);
}
Optional<ContributedLibrary> mayInstalled = indexer.getIndex().getInstalled(libraryToInstallParts[0]);
if (mayInstalled.isPresent() && selected.isIDEBuiltIn()) {
System.out.println(tr(I18n
.format("Library {0} is available as built-in in the IDE.\nRemoving the other version {1} installed in the sketchbook...",
library, mayInstalled.get().getParsedVersion())));
libraryInstaller.remove(mayInstalled.get(), progressListener);
} else {
libraryInstaller.install(selected, progressListener);
}
}
System.exit(0);
} else if (parser.isVerifyOrUploadMode()) {
// Set verbosity for command line build
PreferencesData.setBoolean("build.verbose", parser.isDoVerboseBuild());
PreferencesData.setBoolean("upload.verbose", parser.isDoVerboseUpload());
// Set preserve-temp flag
PreferencesData.setBoolean("runtime.preserve.temp.files", parser.isPreserveTempFiles());
// Make sure these verbosity preferences are only for the current session
PreferencesData.setDoSave(false);
Sketch sketch = null;
String outputFile = null;
try {
// Build
splash.splashText(tr("Verifying..."));
File sketchFile = BaseNoGui.absoluteFile(parser.getFilenames().get(0));
sketch = new Sketch(sketchFile);
outputFile = new Compiler(sketch).build(progress -> {}, false);
} catch (Exception e) {
// Error during build
e.printStackTrace();
System.exit(1);
}
if (parser.isUploadMode()) {
// Upload
splash.splashText(tr("Uploading..."));
try {
List<String> warnings = new ArrayList<>();
UploaderUtils uploader = new UploaderUtils();
boolean res = uploader.upload(sketch, null, outputFile,
parser.isDoUseProgrammer(),
parser.isNoUploadPort(), warnings);
for (String warning : warnings) {
System.out.println(tr("Warning") + ": " + warning);
}
if (!res) {
throw new Exception();
}
} catch (Exception e) {
// Error during upload
System.out.flush();
System.err.flush();
System.err
.println(tr("An error occurred while uploading the sketch"));
System.exit(1);
}
}
// No errors exit gracefully
System.exit(0);
} else if (parser.isGuiMode()) {
splash.splashText(tr("Starting..."));
for (String path : parser.getFilenames()) {
// Correctly resolve relative paths
File file = absoluteFile(path);
// 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 (OSUtils.isWindows()) {
try {
file = file.getCanonicalFile();
} catch (IOException e) {
e.printStackTrace();
}
}
if (!parser.isForceSavePrefs())
PreferencesData.setDoSave(true);
if (handleOpen(file, retrieveSketchLocation(".default"), false) == null) {
String mess = format(tr("Failed to open sketch: \"{0}\""), path);
// Open failure is fatal in upload/verify mode
if (parser.isVerifyOrUploadMode())
showError(null, mess, 2);
else
showWarning(null, mess, null);
}
}
installKeyboardInputMap();
// Check if there were previously opened sketches to be restored
restoreSketches();
// Create a new empty window (will be replaced with any files to be opened)
if (editors.isEmpty()) {
handleNew();
}
new Thread(new BuiltInCoreIsNewerCheck(this)).start();
// Check for boards which need an additional core
new Thread(new NewBoardListener(this)).start();
// Check for updates
if (PreferencesData.getBoolean("update.check")) {
new UpdateCheck(this);
contributionsSelfCheck = new ContributionsSelfCheck(this, new UpdatableBoardsLibsFakeURLsHandler(this), contributionInstaller, libraryInstaller);
new Timer(false).schedule(contributionsSelfCheck, Constants.BOARDS_LIBS_UPDATABLE_CHECK_START_PERIOD);
}
} else if (parser.isNoOpMode()) {
// Do nothing (intended for only changing preferences)
System.exit(0);
} else if (parser.isGetPrefMode()) {
BaseNoGui.dumpPrefs(parser);
} else if (parser.isVersionMode()) {
System.out.println("Arduino: " + BaseNoGui.VERSION_NAME_LONG);
System.exit(0);
}
}
private void installKeyboardInputMap() {
UIManager.put("RSyntaxTextAreaUI.inputMap", new SketchTextAreaDefaultInputMap());
}
/**
* 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.
*
* @throws Exception
*/
protected boolean restoreSketches() throws Exception {
// 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 = PreferencesData.getInteger("last.sketch.count");
int opened = 0;
for (int i = count - 1; i >= 0; i--) {
String path = PreferencesData.get("last.sketch" + i + ".path");
if (path == null) {
continue;
}
if (BaseNoGui.getPortableFolder() != null && !new File(path).isAbsolute()) {
File absolute = new File(BaseNoGui.getPortableFolder(), path);
try {
path = absolute.getCanonicalPath();
} catch (IOException e) {
// path unchanged.
}
}
int[] location = retrieveSketchLocation("" + i);
// If file did not exist, null will be returned for the Editor
if (handleOpen(new File(path), location, nextEditorLocation(), false, false) != null) {
opened++;
}
}
return (opened > 0);
}
/**
* Store screen dimensions on last close
*/
protected void storeScreenDimensions() {
// Save the width and height of the screen
Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
PreferencesData.setInteger("last.screen.width", screen.width);
PreferencesData.setInteger("last.screen.height", screen.height);
}
/**
* Store list of sketches that are currently open.
* Called when the application is quitting and documents are still open.
*/
protected void storeSketches() {
// If there is only one sketch opened save his position as default
if (editors.size() == 1) {
storeSketchLocation(editors.get(0), ".default");
}
// Save the sketch path and window placement for each open sketch
String untitledPath = untitledFolder.getAbsolutePath();
List<Editor> reversedEditors = new LinkedList<>(editors);
Collections.reverse(reversedEditors);
int index = 0;
for (Editor editor : reversedEditors) {
Sketch sketch = editor.getSketch();
String path = sketch.getMainFilePath();
// Skip untitled sketches if they do not contains changes.
if (path.startsWith(untitledPath) && !sketch.isModified()) {
continue;
}
storeSketchLocation(editor, "" + index);
index++;
}
PreferencesData.setInteger("last.sketch.count", index);
}
private void storeSketchLocation(Editor editor, String index) {
String path = editor.getSketch().getMainFilePath();
String loc = StringUtils.join(editor.getPlacement(), ',');
PreferencesData.set("last.sketch" + index + ".path", path);
PreferencesData.set("last.sketch" + index + ".location", loc);
}
private int[] retrieveSketchLocation(String index) {
if (PreferencesData.get("last.screen.height") == null)
return defaultEditorLocation();
// if screen size has changed, the window coordinates no longer
// make sense, so don't use them unless they're identical
Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
int screenW = PreferencesData.getInteger("last.screen.width");
int screenH = PreferencesData.getInteger("last.screen.height");
if ((screen.width != screenW) || (screen.height != screenH))
return defaultEditorLocation();
String locationStr = PreferencesData
.get("last.sketch" + index + ".location");
if (locationStr == null)
return defaultEditorLocation();
int location[] = PApplet.parseInt(PApplet.split(locationStr, ','));
if (location[0] > screen.width || location[1] > screen.height)
return defaultEditorLocation();
return location;
}
protected void storeRecentSketches(SketchController sketch) {
if (sketch.isUntitled()) {
return;
}
Set<String> sketches = new LinkedHashSet<>();
sketches.add(sketch.getSketch().getMainFilePath());
sketches.addAll(PreferencesData.getCollection("recent.sketches"));
PreferencesData.setCollection("recent.sketches", sketches);
}
protected void removeRecentSketchPath(String path) {
Collection<String> sketches = new LinkedList<>(PreferencesData.getCollection("recent.sketches"));
sketches.remove(path);
PreferencesData.setCollection("recent.sketches", sketches);
}
// 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;
activeEditor.rebuildRecentSketchesMenu();
if (PreferencesData.getBoolean("editor.external")) {
try {
// If the list of files on disk changed, recreate the tabs for them
if (activeEditor.getSketch().reload())
activeEditor.createTabs();
else // Let the current tab know it was activated, so it can reload
activeEditor.getCurrentTab().activated();
} catch (IOException e) {
System.err.println(e);
}
}
}
protected int[] defaultEditorLocation() {
int defaultWidth = PreferencesData.getInteger("editor.window.width.default");
int defaultHeight = PreferencesData.getInteger("editor.window.height.default");
Rectangle screen = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getDefaultConfiguration().getBounds();
return new int[]{
(screen.width - defaultWidth) / 2,
(screen.height - defaultHeight) / 2,
defaultWidth, defaultHeight, 0
};
}
protected int[] nextEditorLocation() {
if (activeEditor == null) {
// If no current active editor, use default placement
return defaultEditorLocation();
}
Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
// With a currently active editor, open the new window
// using the same dimensions, but offset slightly.
synchronized (editors) {
int[] location = activeEditor.getPlacement();
// Just in case the bounds for that window are bad
final int OVER = 50;
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.
int[] l = defaultEditorLocation();
l[0] *= Math.random() * 2;
l[1] *= Math.random() * 2;
return l;
}
return location;
}
}
// .................................................................
boolean breakTime = false;
String[] months = {
"jan", "feb", "mar", "apr", "may", "jun",
"jul", "aug", "sep", "oct", "nov", "dec"
};
protected File 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 = BaseNoGui.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*26) {
// In 0166, avoid running past zz by sending people outdoors.
if (!breakTime) {
showWarning(tr("Time for a Break"),
tr("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 {
showWarning(tr("Sunshine"),
tr("No really, time for some fresh air for you."), null);
}
return null;
}
int multiples = index / 26;
if(multiples > 0){
newbieName = ((char) ('a' + (multiples-1))) + "" + ((char) ('a' + (index % 26))) + "";
}else{
newbieName = ((char) ('a' + index)) + "";
}
newbieName = "sketch_" + purty + newbieName;
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 + ".ino");
if (!newbieFile.createNewFile()) {
throw new IOException();
}
// Initialize the pde file with the BareMinimum sketch.
// Apply user-defined tab settings.
String sketch = FileUtils.readFileToString(
new File(getContentFile("examples"), "01.Basics" + File.separator
+ "BareMinimum" + File.separator + "BareMinimum.ino"));
String currentTab = " ";
String newTab = (PreferencesData.getBoolean("editor.tabs.expand")
? StringUtils.repeat(" ",
PreferencesData.getInteger("editor.tabs.size"))
: "\t");
sketch = sketch.replaceAll(
"(?<=(^|\n)(" + currentTab + "){0,50})" + currentTab, newTab);
FileUtils.writeStringToFile(newbieFile, sketch);
return newbieFile;
}
/**
* Create a new untitled document in a new sketch window.
*
* @throws Exception
*/
public void handleNew() throws Exception {
try {
File file = createNewUntitled();
if (file != null) {
handleOpen(file, true);
}
} catch (IOException e) {
if (activeEditor != null) {
activeEditor.statusError(e);
}
}
}
/**
* Prompt for a sketch to open, and open it in a new window.
*
* @throws Exception
*/
public void handleOpenPrompt() throws Exception {
// get the frontmost window frame for placing file dialog
FileDialog fd = new FileDialog(activeEditor, tr("Open an Arduino sketch..."), FileDialog.LOAD);
File lastFolder = new File(PreferencesData.get("last.folder", BaseNoGui.getSketchbookFolder().getAbsolutePath()));
if (lastFolder.exists() && lastFolder.isFile()) {
lastFolder = lastFolder.getParentFile();
}
fd.setDirectory(lastFolder.getAbsolutePath());
// Only show .pde files as eligible bachelors
fd.setFilenameFilter(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.toLowerCase().endsWith(".ino")
|| 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);
PreferencesData.set("last.folder", inputFile.getAbsolutePath());
handleOpen(inputFile);
}
/**
* Open a sketch in a new window.
*
* @param file File to open
* @return the Editor object, so that properties (like 'untitled')
* can be set by the caller
* @throws Exception
*/
public Editor handleOpen(File file) throws Exception {
return handleOpen(file, false);
}
public Editor handleOpen(File file, boolean untitled) throws Exception {
return handleOpen(file, nextEditorLocation(), untitled);
}
protected Editor handleOpen(File file, int[] location, boolean untitled) throws Exception {
return handleOpen(file, location, location, true, untitled);
}
protected Editor handleOpen(File file, int[] storedLocation, int[] defaultLocation, boolean storeOpenedSketches, boolean untitled) throws Exception {
if (!file.exists()) return null;
// Cycle through open windows to make sure that it's not already open.
for (Editor editor : editors) {
if (editor.getSketch().getPrimaryFile().getFile().equals(file)) {
editor.toFront();
return editor;
}
}
Editor editor = new Editor(this, file, storedLocation, defaultLocation, BaseNoGui.getPlatform());
// Make sure that the sketch actually loaded
if (editor.getSketchController() == null) {
return null; // Just walk away quietly
}
editor.untitled = untitled;
editors.add(editor);
if (storeOpenedSketches) {
// Store information on who's open and running
// (in case there's a crash or something that can't be recovered)
storeSketches();
storeRecentSketches(editor.getSketchController());
rebuildRecentSketchesMenuItems();
PreferencesData.save();
}
// now that we're ready, show the window
// (don't do earlier, cuz we might move it based on a window being closed)
SwingUtilities.invokeLater(() -> editor.setVisible(true));
return editor;
}
protected void rebuildRecentSketchesMenuItems() {
Set<File> recentSketches = new LinkedHashSet<File>() {
@Override
public boolean add(File file) {
if (size() >= RECENT_SKETCHES_MAX_SIZE) {
return false;
}
return super.add(file);
}
};
for (String path : PreferencesData.getCollection("recent.sketches")) {
File file = new File(path);
if (file.exists()) {
recentSketches.add(file);
}
}
recentSketchesMenuItems.clear();
for (final File recentSketch : recentSketches) {
JMenuItem recentSketchMenuItem = new JMenuItem(recentSketch.getParentFile().getName());
recentSketchMenuItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent actionEvent) {
try {
handleOpen(recentSketch);
} catch (Exception e) {
e.printStackTrace();
}
}
});
recentSketchesMenuItems.add(recentSketchMenuItem);
}
}
/**
* 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) {
if (editors.size() == 1) {
if (!handleQuit()) {
return false;
}
// Everything called after handleQuit will only affect OSX
editor.setVisible(false);
editors.remove(editor);
} else {
// More than one editor window open,
// proceed with closing the current window.
// Check if modified
if (!editor.checkModified()) {
return false;
}
editor.setVisible(false);
editor.dispose();
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.
storeScreenDimensions();
storeSketches();
try {
Editor.serialMonitor.close();
} catch (Exception e) {
// ignore
}
// kill uploader (if still alive)
UploaderUtils uploaderInstance = new UploaderUtils();
Uploader uploader = uploaderInstance.getUploaderByPreferences(false);
if (uploader != null && Uploader.programmerPid != null && Uploader.programmerPid.isAlive()) {
// kill the stuck programmer
Uploader.programmerPid.destroyForcibly();
}
if (handleQuitEach()) {