-
-
Notifications
You must be signed in to change notification settings - Fork 7k
/
Copy pathEditor.java
2756 lines (2323 loc) · 85.2 KB
/
Editor.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-09 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.packages.BoardPort;
import cc.arduino.packages.MonitorFactory;
import cc.arduino.packages.Uploader;
import cc.arduino.packages.uploaders.SerialUploader;
import cc.arduino.view.GoToLineNumber;
import cc.arduino.view.StubMenuListener;
import cc.arduino.view.findreplace.FindReplace;
import cc.arduino.CompilerProgressListener;
import com.jcraft.jsch.JSchException;
import jssc.SerialPortException;
import processing.app.debug.RunnerException;
import processing.app.debug.TargetBoard;
import processing.app.debug.TargetPackage;
import processing.app.debug.TargetPlatform;
import processing.app.forms.PasswordAuthorizationDialog;
import processing.app.helpers.DocumentTextChangeListener;
import processing.app.helpers.Keys;
import processing.app.helpers.OSUtils;
import processing.app.helpers.PreferencesMapException;
import processing.app.helpers.StringReplacer;
import processing.app.legacy.PApplet;
import processing.app.syntax.PdeKeywords;
import processing.app.syntax.SketchTextArea;
import processing.app.tools.MenuScroller;
import processing.app.tools.Tool;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.BadLocationException;
import java.awt.*;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.event.*;
import java.awt.print.PageFormat;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;
import java.io.File;
import java.io.FileFilter;
import java.io.FilenameFilter;
import java.io.IOException;
import java.net.ConnectException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.*;
import java.util.List;
import java.util.function.Predicate;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.ArrayList;
import static processing.app.I18n.tr;
import static processing.app.Theme.scale;
/**
* Main editor panel for the Processing Development Environment.
*/
@SuppressWarnings("serial")
public class Editor extends JFrame implements RunnerListener {
public static final int MAX_TIME_AWAITING_FOR_RESUMING_SERIAL_MONITOR = 10000;
final Platform platform;
private JMenu recentSketchesMenu;
private JMenu programmersMenu;
private final Box upper;
private ArrayList<EditorTab> tabs = new ArrayList<>();
private int currentTabIndex = -1;
private static class ShouldSaveIfModified
implements Predicate<SketchController> {
@Override
public boolean test(SketchController controller) {
return PreferencesData.getBoolean("editor.save_on_verify")
&& controller.getSketch().isModified()
&& !controller.isReadOnly(
BaseNoGui.librariesIndexer
.getInstalledLibraries(),
BaseNoGui.getExamplesPath());
}
}
private static class ShouldSaveReadOnly implements Predicate<SketchController> {
@Override
public boolean test(SketchController sketch) {
return sketch.isReadOnly(BaseNoGui.librariesIndexer.getInstalledLibraries(), BaseNoGui.getExamplesPath());
}
}
private final static List<String> BOARD_PROTOCOLS_ORDER = Arrays.asList("serial", "network");
private final static List<String> BOARD_PROTOCOLS_ORDER_TRANSLATIONS = Arrays.asList(tr("Serial ports"), tr("Network ports"));
final Base base;
// otherwise, if the window is resized with the message label
// set to blank, it's preferredSize() will be fukered
private static final String EMPTY =
" " +
" " +
" ";
/** Command on Mac OS X, Ctrl on Windows and Linux */
private static final int SHORTCUT_KEY_MASK =
Toolkit.getDefaultToolkit().getMenuShortcutKeyMask();
/** Command-W on Mac OS X, Ctrl-W on Windows and Linux */
static final KeyStroke WINDOW_CLOSE_KEYSTROKE =
KeyStroke.getKeyStroke('W', SHORTCUT_KEY_MASK);
/** Command-Option on Mac OS X, Ctrl-Alt on Windows and Linux */
static final int SHORTCUT_ALT_KEY_MASK = ActionEvent.ALT_MASK |
Toolkit.getDefaultToolkit().getMenuShortcutKeyMask();
/**
* true if this file has not yet been given a name by the user
*/
boolean untitled;
private PageFormat pageFormat;
// file, sketch, and tools menus for re-inserting items
private JMenu fileMenu;
private JMenu toolsMenu;
private int numTools = 0;
public boolean avoidMultipleOperations = false;
private final EditorToolbar toolbar;
// these menus are shared so that they needn't be rebuilt for all windows
// each time a sketch is created, renamed, or moved.
static JMenu toolbarMenu;
static JMenu sketchbookMenu;
static JMenu examplesMenu;
static JMenu importMenu;
private static JMenu portMenu;
static volatile AbstractMonitor serialMonitor;
static AbstractMonitor serialPlotter;
final EditorHeader header;
EditorStatus status;
EditorConsole console;
private JSplitPane splitPane;
// currently opened program
SketchController sketchController;
Sketch sketch;
EditorLineStatus lineStatus;
//JEditorPane editorPane;
/** Contains all EditorTabs, of which only one will be visible */
private JPanel codePanel;
//Runner runtime;
private JMenuItem saveMenuItem;
private JMenuItem saveAsMenuItem;
//boolean presenting;
private boolean uploading;
// undo fellers
private JMenuItem undoItem;
private JMenuItem redoItem;
private FindReplace find;
Runnable runHandler;
Runnable presentHandler;
private Runnable runAndSaveHandler;
private Runnable presentAndSaveHandler;
Runnable exportHandler;
private Runnable exportAppHandler;
private Runnable timeoutUploadHandler;
public Editor(Base ibase, File file, int[] storedLocation, int[] defaultLocation, Platform platform) throws Exception {
super("Arduino");
this.base = ibase;
this.platform = platform;
Base.setIcon(this);
// Install default actions for Run, Present, etc.
resetHandlers();
// add listener to handle window close box hit event
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
base.handleClose(Editor.this);
}
});
// don't close the window when clicked, the app will take care
// of that via the handleQuitInternal() methods
// http://dev.processing.org/bugs/show_bug.cgi?id=440
setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
// When bringing a window to front, let the Base know
addWindowListener(new WindowAdapter() {
public void windowActivated(WindowEvent e) {
base.handleActivated(Editor.this);
}
// added for 1.0.5
// http://dev.processing.org/bugs/show_bug.cgi?id=1260
public void windowDeactivated(WindowEvent e) {
fileMenu.remove(sketchbookMenu);
fileMenu.remove(examplesMenu);
List<Component> toolsMenuItemsToRemove = new LinkedList<>();
for (Component menuItem : toolsMenu.getMenuComponents()) {
if (menuItem instanceof JComponent) {
Object removeOnWindowDeactivation = ((JComponent) menuItem).getClientProperty("removeOnWindowDeactivation");
if (removeOnWindowDeactivation != null && Boolean.valueOf(removeOnWindowDeactivation.toString())) {
toolsMenuItemsToRemove.add(menuItem);
}
}
}
for (Component menuItem : toolsMenuItemsToRemove) {
toolsMenu.remove(menuItem);
}
toolsMenu.remove(portMenu);
}
});
//PdeKeywords keywords = new PdeKeywords();
//sketchbook = new Sketchbook(this);
buildMenuBar();
// For rev 0120, placing things inside a JPanel
Container contentPain = getContentPane();
contentPain.setLayout(new BorderLayout());
JPanel pane = new JPanel();
pane.setLayout(new BorderLayout());
contentPain.add(pane, BorderLayout.CENTER);
Box box = Box.createVerticalBox();
upper = Box.createVerticalBox();
if (toolbarMenu == null) {
toolbarMenu = new JMenu();
base.rebuildToolbarMenu(toolbarMenu);
}
toolbar = new EditorToolbar(this, toolbarMenu);
upper.add(toolbar);
header = new EditorHeader(this);
upper.add(header);
// assemble console panel, consisting of status area and the console itself
JPanel consolePanel = new JPanel();
consolePanel.setLayout(new BorderLayout());
status = new EditorStatus(this);
consolePanel.add(status, BorderLayout.NORTH);
console = new EditorConsole();
console.setName("console");
// windows puts an ugly border on this guy
console.setBorder(null);
consolePanel.add(console, BorderLayout.CENTER);
lineStatus = new EditorLineStatus();
consolePanel.add(lineStatus, BorderLayout.SOUTH);
codePanel = new JPanel(new BorderLayout());
upper.add(codePanel);
splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, upper, consolePanel);
// repaint child panes while resizing
splitPane.setContinuousLayout(true);
// if window increases in size, give all of increase to
// the textarea in the uppper pane
splitPane.setResizeWeight(1D);
// to fix ugliness.. normally macosx java 1.3 puts an
// ugly white border around this object, so turn it off.
splitPane.setBorder(null);
// By default, the split pane binds Ctrl-Tab and Ctrl-Shift-Tab for changing
// focus. Since we do not use that, but want to use these shortcuts for
// switching tabs, remove the bindings from the split pane. This allows the
// events to bubble up and be handled by the EditorHeader.
Keys.killBinding(splitPane, Keys.ctrl(KeyEvent.VK_TAB));
Keys.killBinding(splitPane, Keys.ctrlShift(KeyEvent.VK_TAB));
splitPane.setDividerSize(scale(splitPane.getDividerSize()));
// the following changed from 600, 400 for netbooks
// http://code.google.com/p/arduino/issues/detail?id=52
splitPane.setMinimumSize(scale(new Dimension(600, 100)));
box.add(splitPane);
// hopefully these are no longer needed w/ swing
// (har har har.. that was wishful thinking)
// listener = new EditorListener(this, textarea);
pane.add(box);
pane.setTransferHandler(new FileDropHandler());
// Set the minimum size for the editor window
setMinimumSize(scale(new Dimension(
PreferencesData.getInteger("editor.window.width.min"),
PreferencesData.getInteger("editor.window.height.min"))));
// Bring back the general options for the editor
applyPreferences();
// Finish preparing Editor (formerly found in Base)
pack();
// Set the window bounds and the divider location before setting it visible
setPlacement(storedLocation, defaultLocation);
// Open the document that was passed in
boolean loaded = handleOpenInternal(file);
if (!loaded) sketchController = null;
}
/**
* Handles files dragged & dropped from the desktop and into the editor
* window. Dragging files into the editor window is the same as using
* "Sketch → Add File" for each file.
*/
private class FileDropHandler extends TransferHandler {
public boolean canImport(JComponent dest, DataFlavor[] flavors) {
return true;
}
@SuppressWarnings("unchecked")
public boolean importData(JComponent src, Transferable transferable) {
int successful = 0;
try {
DataFlavor uriListFlavor =
new DataFlavor("text/uri-list;class=java.lang.String");
if (transferable.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
List<File> list = (List<File>)
transferable.getTransferData(DataFlavor.javaFileListFlavor);
for (File file : list) {
if (sketchController.addFile(file)) {
successful++;
}
}
} else if (transferable.isDataFlavorSupported(uriListFlavor)) {
// Some platforms (Mac OS X and Linux, when this began) preferred
// this method of moving files.
String data = (String)transferable.getTransferData(uriListFlavor);
String[] pieces = PApplet.splitTokens(data, "\r\n");
for (String piece : pieces) {
if (piece.startsWith("#")) continue;
String path = null;
if (piece.startsWith("file:///")) {
path = piece.substring(7);
} else if (piece.startsWith("file:/")) {
path = piece.substring(5);
}
if (sketchController.addFile(new File(path))) {
successful++;
}
}
}
} catch (Exception e) {
e.printStackTrace();
return false;
}
if (successful == 0) {
statusError(tr("No files were added to the sketch."));
} else if (successful == 1) {
statusNotice(tr("One file added to the sketch."));
} else {
statusNotice(I18n.format(tr("{0} files added to the sketch."), successful));
}
return true;
}
}
private void setPlacement(int[] storedLocation, int[] defaultLocation) {
if (storedLocation.length > 5 && storedLocation[5] != 0) {
setExtendedState(storedLocation[5]);
setPlacement(defaultLocation);
} else {
setPlacement(storedLocation);
}
}
private void setPlacement(int[] location) {
setBounds(location[0], location[1], location[2], location[3]);
if (location[4] != 0) {
splitPane.setDividerLocation(location[4]);
}
}
protected int[] getPlacement() {
int[] location = new int[6];
// Get the dimensions of the Frame
Rectangle bounds = getBounds();
location[0] = bounds.x;
location[1] = bounds.y;
location[2] = bounds.width;
location[3] = bounds.height;
// Get the current placement of the divider
location[4] = splitPane.getDividerLocation();
location[5] = getExtendedState() & MAXIMIZED_BOTH;
return location;
}
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
/**
* Read and apply new values from the preferences, either because
* the app is just starting up, or the user just finished messing
* with things in the Preferences window.
*/
public void applyPreferences() {
boolean external = PreferencesData.getBoolean("editor.external");
saveMenuItem.setEnabled(!external);
saveAsMenuItem.setEnabled(!external);
for (EditorTab tab: tabs)
tab.applyPreferences();
}
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
private void buildMenuBar() {
JMenuBar menubar = new JMenuBar();
final JMenu fileMenu = buildFileMenu();
fileMenu.addMenuListener(new StubMenuListener() {
@Override
public void menuSelected(MenuEvent e) {
List<Component> components = Arrays.asList(fileMenu.getComponents());
if (!components.contains(sketchbookMenu)) {
fileMenu.insert(sketchbookMenu, 3);
}
if (!components.contains(sketchbookMenu)) {
fileMenu.insert(examplesMenu, 4);
}
fileMenu.revalidate();
validate();
}
});
menubar.add(fileMenu);
menubar.add(buildEditMenu());
final JMenu sketchMenu = new JMenu(tr("Sketch"));
sketchMenu.setMnemonic(KeyEvent.VK_S);
sketchMenu.addMenuListener(new StubMenuListener() {
@Override
public void menuSelected(MenuEvent e) {
buildSketchMenu(sketchMenu);
sketchMenu.revalidate();
validate();
}
});
buildSketchMenu(sketchMenu);
menubar.add(sketchMenu);
final JMenu toolsMenu = buildToolsMenu();
toolsMenu.addMenuListener(new StubMenuListener() {
@Override
public void menuSelected(MenuEvent e) {
List<Component> components = Arrays.asList(toolsMenu.getComponents());
int offset = 0;
for (JMenu menu : base.getBoardsCustomMenus()) {
if (!components.contains(menu)) {
toolsMenu.insert(menu, numTools + offset);
offset++;
}
}
if (!components.contains(portMenu)) {
toolsMenu.insert(portMenu, numTools + offset);
}
programmersMenu.removeAll();
base.getProgrammerMenus().forEach(programmersMenu::add);
toolsMenu.revalidate();
validate();
}
});
menubar.add(toolsMenu);
menubar.add(buildHelpMenu());
setJMenuBar(menubar);
}
private JMenu buildFileMenu() {
JMenuItem item;
fileMenu = new JMenu(tr("File"));
fileMenu.setMnemonic(KeyEvent.VK_F);
item = newJMenuItem(tr("New"), 'N');
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
base.handleNew();
} catch (Exception e1) {
e1.printStackTrace();
}
}
});
fileMenu.add(item);
item = Editor.newJMenuItem(tr("Open..."), 'O');
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
base.handleOpenPrompt();
} catch (Exception e1) {
e1.printStackTrace();
}
}
});
fileMenu.add(item);
base.rebuildRecentSketchesMenuItems();
recentSketchesMenu = new JMenu(tr("Open Recent"));
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
rebuildRecentSketchesMenu();
}
});
fileMenu.add(recentSketchesMenu);
if (sketchbookMenu == null) {
sketchbookMenu = new JMenu(tr("Sketchbook"));
MenuScroller.setScrollerFor(sketchbookMenu);
base.rebuildSketchbookMenu(sketchbookMenu);
}
fileMenu.add(sketchbookMenu);
if (examplesMenu == null) {
examplesMenu = new JMenu(tr("Examples"));
MenuScroller.setScrollerFor(examplesMenu);
base.rebuildExamplesMenu(examplesMenu);
}
fileMenu.add(examplesMenu);
item = Editor.newJMenuItem(tr("Close"), 'W');
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
base.handleClose(Editor.this);
}
});
fileMenu.add(item);
saveMenuItem = newJMenuItem(tr("Save"), 'S');
saveMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
handleSave(false);
}
});
fileMenu.add(saveMenuItem);
saveAsMenuItem = newJMenuItemShift(tr("Save As..."), 'S');
saveAsMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
handleSaveAs();
}
});
fileMenu.add(saveAsMenuItem);
fileMenu.addSeparator();
item = newJMenuItemShift(tr("Page Setup"), 'P');
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
handlePageSetup();
}
});
fileMenu.add(item);
item = newJMenuItem(tr("Print"), 'P');
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
handlePrint();
}
});
fileMenu.add(item);
// macosx already has its own preferences and quit menu
if (!OSUtils.hasMacOSStyleMenus()) {
fileMenu.addSeparator();
item = newJMenuItem(tr("Preferences"), ',');
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
base.handlePrefs();
}
});
fileMenu.add(item);
fileMenu.addSeparator();
item = newJMenuItem(tr("Quit"), 'Q');
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
base.handleQuit();
}
});
fileMenu.add(item);
}
return fileMenu;
}
public void rebuildRecentSketchesMenu() {
recentSketchesMenu.removeAll();
for (JMenuItem recentSketchMenuItem : base.getRecentSketchesMenuItems()) {
recentSketchesMenu.add(recentSketchMenuItem);
}
}
private void buildSketchMenu(JMenu sketchMenu) {
sketchMenu.removeAll();
JMenuItem item = newJMenuItem(tr("Verify/Compile"), 'R');
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
handleRun(false, Editor.this.presentHandler, Editor.this.runHandler);
}
});
sketchMenu.add(item);
item = newJMenuItem(tr("Upload"), 'U');
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
handleExport(false);
}
});
sketchMenu.add(item);
item = newJMenuItemShift(tr("Upload Using Programmer"), 'U');
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
handleExport(true);
}
});
sketchMenu.add(item);
item = newJMenuItemAlt(tr("Export compiled Binary"), 'S');
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (new ShouldSaveReadOnly().test(sketchController) && !handleSave(true)) {
System.out.println(tr("Export canceled, changes must first be saved."));
return;
}
handleRun(false, new ShouldSaveReadOnly(), Editor.this.presentAndSaveHandler, Editor.this.runAndSaveHandler);
}
});
sketchMenu.add(item);
// item = new JMenuItem("Stop");
// item.addActionListener(new ActionListener() {
// public void actionPerformed(ActionEvent e) {
// handleStop();
// }
// });
// sketchMenu.add(item);
sketchMenu.addSeparator();
item = newJMenuItem(tr("Show Sketch Folder"), 'K');
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Base.openFolder(sketch.getFolder());
}
});
sketchMenu.add(item);
item.setEnabled(Base.openFolderAvailable());
if (importMenu == null) {
importMenu = new JMenu(tr("Include Library"));
MenuScroller.setScrollerFor(importMenu);
base.rebuildImportMenu(importMenu);
}
sketchMenu.add(importMenu);
item = new JMenuItem(tr("Add File..."));
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
sketchController.handleAddFile();
}
});
sketchMenu.add(item);
}
private JMenu buildToolsMenu() {
toolsMenu = new JMenu(tr("Tools"));
toolsMenu.setMnemonic(KeyEvent.VK_T);
addInternalTools(toolsMenu);
JMenuItem item = newJMenuItemShift(tr("Manage Libraries..."), 'I');
item.addActionListener(e -> base.openLibraryManager("", ""));
toolsMenu.add(item);
item = newJMenuItemShift(tr("Serial Monitor"), 'M');
item.addActionListener(e -> handleSerial());
toolsMenu.add(item);
item = newJMenuItemShift(tr("Serial Plotter"), 'L');
item.addActionListener(e -> handlePlotter());
toolsMenu.add(item);
addTools(toolsMenu, BaseNoGui.getToolsFolder());
File sketchbookTools = new File(BaseNoGui.getSketchbookFolder(), "tools");
addTools(toolsMenu, sketchbookTools);
toolsMenu.addSeparator();
numTools = toolsMenu.getItemCount();
// XXX: DAM: these should probably be implemented using the Tools plugin
// API, if possible (i.e. if it supports custom actions, etc.)
base.getBoardsCustomMenus().stream().forEach(toolsMenu::add);
if (portMenu == null)
portMenu = new JMenu(tr("Port"));
populatePortMenu();
toolsMenu.add(portMenu);
MenuScroller.setScrollerFor(portMenu);
item = new JMenuItem(tr("Get Board Info"));
item.addActionListener(e -> handleBoardInfo());
toolsMenu.add(item);
toolsMenu.addSeparator();
base.rebuildProgrammerMenu();
programmersMenu = new JMenu(tr("Programmer"));
MenuScroller.setScrollerFor(programmersMenu);
base.getProgrammerMenus().stream().forEach(programmersMenu::add);
toolsMenu.add(programmersMenu);
item = new JMenuItem(tr("Burn Bootloader"));
item.addActionListener(e -> handleBurnBootloader());
toolsMenu.add(item);
toolsMenu.addMenuListener(new StubMenuListener() {
public void menuSelected(MenuEvent e) {
//System.out.println("Tools menu selected.");
populatePortMenu();
for (Component c : toolsMenu.getMenuComponents()) {
if ((c instanceof JMenu) && c.isVisible()) {
JMenu menu = (JMenu)c;
String name = menu.getText();
if (name == null) continue;
String basename = name;
int index = name.indexOf(':');
if (index > 0) basename = name.substring(0, index);
String sel = null;
int count = menu.getItemCount();
for (int i=0; i < count; i++) {
JMenuItem item = menu.getItem(i);
if (item != null && item.isSelected()) {
sel = item.getText();
if (sel != null) break;
}
}
if (sel == null) {
if (!name.equals(basename)) menu.setText(basename);
} else {
if (sel.length() > 50) sel = sel.substring(0, 50) + "...";
String newname = basename + ": \"" + sel + "\"";
if (!name.equals(newname)) menu.setText(newname);
}
}
}
}
});
return toolsMenu;
}
private void addTools(JMenu menu, File sourceFolder) {
if (sourceFolder == null)
return;
Map<String, JMenuItem> toolItems = new HashMap<>();
File[] folders = sourceFolder.listFiles(new FileFilter() {
public boolean accept(File folder) {
if (folder.isDirectory()) {
//System.out.println("checking " + folder);
File subfolder = new File(folder, "tool");
return subfolder.exists();
}
return false;
}
});
if (folders == null || folders.length == 0) {
return;
}
for (File folder : folders) {
File toolDirectory = new File(folder, "tool");
try {
// add dir to classpath for .classes
//urlList.add(toolDirectory.toURL());
// add .jar files to classpath
File[] archives = toolDirectory.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
return (name.toLowerCase().endsWith(".jar") ||
name.toLowerCase().endsWith(".zip"));
}
});
URL[] urlList = new URL[archives.length];
for (int j = 0; j < urlList.length; j++) {
urlList[j] = archives[j].toURI().toURL();
}
URLClassLoader loader = new URLClassLoader(urlList);
String className = null;
for (File archive : archives) {
className = findClassInZipFile(folder.getName(), archive);
if (className != null) break;
}
/*
// Alternatively, could use manifest files with special attributes:
// http://java.sun.com/j2se/1.3/docs/guide/jar/jar.html
// Example code for loading from a manifest file:
// http://forums.sun.com/thread.jspa?messageID=3791501
File infoFile = new File(toolDirectory, "tool.txt");
if (!infoFile.exists()) continue;
String[] info = PApplet.loadStrings(infoFile);
//Main-Class: org.poo.shoe.AwesomerTool
//String className = folders[i].getName();
String className = null;
for (int k = 0; k < info.length; k++) {
if (info[k].startsWith(";")) continue;
String[] pieces = PApplet.splitTokens(info[k], ": ");
if (pieces.length == 2) {
if (pieces[0].equals("Main-Class")) {
className = pieces[1];
}
}
}
*/
// If no class name found, just move on.
if (className == null) continue;
Class<?> toolClass = Class.forName(className, true, loader);
final Tool tool = (Tool) toolClass.newInstance();
tool.init(Editor.this);
String title = tool.getMenuTitle();
JMenuItem item = new JMenuItem(title);
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
SwingUtilities.invokeLater(tool);
//new Thread(tool).start();
}
});
//menu.add(item);
toolItems.put(title, item);
} catch (Exception e) {
e.printStackTrace();
}
}
ArrayList<String> toolList = new ArrayList<>(toolItems.keySet());
if (toolList.size() == 0) return;
menu.addSeparator();
Collections.sort(toolList);
for (String title : toolList) {
menu.add(toolItems.get(title));
}
}
private String findClassInZipFile(String base, File file) {
// Class file to search for
String classFileName = "/" + base + ".class";
ZipFile zipFile = null;
try {
zipFile = new ZipFile(file);
Enumeration<?> entries = zipFile.entries();
while (entries.hasMoreElements()) {
ZipEntry entry = (ZipEntry) entries.nextElement();
if (!entry.isDirectory()) {
String name = entry.getName();
//System.out.println("entry: " + name);
if (name.endsWith(classFileName)) {
//int slash = name.lastIndexOf('/');
//String packageName = (slash == -1) ? "" : name.substring(0, slash);
// Remove .class and convert slashes to periods.
return name.substring(0, name.length() - 6).replace('/', '.');
}
}
}
} catch (IOException e) {
//System.err.println("Ignoring " + filename + " (" + e.getMessage() + ")");
e.printStackTrace();
} finally {
if (zipFile != null) {
try {
zipFile.close();
} catch (IOException e) {
// noop
}
}
}
return null;
}
public void updateKeywords(PdeKeywords keywords) {
for (EditorTab tab : tabs)
tab.updateKeywords(keywords);
}
JMenuItem createToolMenuItem(String className) {
try {
Class<?> toolClass = Class.forName(className);
final Tool tool = (Tool) toolClass.newInstance();
JMenuItem item = new JMenuItem(tool.getMenuTitle());
tool.init(Editor.this);
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
SwingUtilities.invokeLater(tool);
}
});
return item;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
private void addInternalTools(JMenu menu) {
JMenuItem item;
item = createToolMenuItem("cc.arduino.packages.formatter.AStyle");
if (item == null) {
throw new NullPointerException("Tool cc.arduino.packages.formatter.AStyle unavailable");
}
item.setName("menuToolsAutoFormat");
int modifiers = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask();
item.setAccelerator(KeyStroke.getKeyStroke('T', modifiers));
menu.add(item);