forked from processing/processing4
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJavaEditor.java
More file actions
2254 lines (1855 loc) · 68.8 KB
/
JavaEditor.java
File metadata and controls
2254 lines (1855 loc) · 68.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */
/*
Part of the Processing project - http://processing.org
Copyright (c) 2012-23 The Processing Foundation
Copyright (c) 2004-12 Ben Fry and Casey Reas
Copyright (c) 2001-04 Massachusetts Institute of Technology
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License version 2
as published by the Free Software Foundation.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software Foundation,
Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package processing.mode.java;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import processing.core.PApplet;
import processing.data.StringList;
import processing.app.*;
import processing.app.contrib.*;
import processing.app.syntax.JEditTextArea;
import processing.app.syntax.PdeTextArea;
import processing.app.syntax.PdeTextAreaDefaults;
import processing.app.ui.*;
import processing.app.ui.Toolkit;
import processing.mode.java.debug.Debugger;
import processing.mode.java.debug.LineBreakpoint;
import processing.mode.java.debug.LineHighlight;
import processing.mode.java.debug.LineID;
import processing.mode.java.preproc.ImportStatement;
import processing.mode.java.preproc.PdePreprocessor;
import processing.mode.java.preproc.SourceUtil;
import processing.mode.java.runner.Runner;
import processing.mode.java.tweak.ColorControlBox;
import processing.mode.java.tweak.Handle;
import processing.mode.java.tweak.SketchParser;
import processing.mode.java.tweak.TweakClient;
public class JavaEditor extends Editor {
JavaMode jmode;
// Runner associated with this editor window
private Runner runtime;
private boolean runtimeLaunchRequested;
private final Object runtimeLock = new Object[0];
// Need to sort through the rest of these additions [fry]
protected final List<LineHighlight> breakpointedLines = new ArrayList<>();
protected LineHighlight currentLine; // where the debugger is suspended
protected final String breakpointMarkerComment = " //<>//";
JMenu modeMenu;
// protected JMenuItem inspectorItem;
// static final int ERROR_TAB_INDEX = 0;
protected PreprocService preprocService;
protected Debugger debugger;
final private InspectMode inspect;
final private ShowUsage usage;
final private Rename rename;
final private ErrorChecker errorChecker;
// set true to show AST debugging window
static private final boolean SHOW_AST_VIEWER = false;
private ASTViewer astViewer;
/** P5 in decimal; if there are complaints, move to preferences.txt */
static final int REFERENCE_PORT = 8053;
// weird to link to a specific location like this, but it's versioned, so:
static final String REFERENCE_URL =
"https://github.com/processing/processing4/releases/tag/processing-1300-4.4.0";
static final String REFERENCE_URL_2 = "https://github.com/processing/processing4/releases/download/processing-1300-4.4.0/processing-4.4.0-reference.zip";
Boolean useReferenceServer;
ReferenceServer referenceServer;
protected JavaEditor(Base base, String path, EditorState state,
Mode mode) throws EditorException {
super(base, path, state, mode);
// long t1 = System.currentTimeMillis();
jmode = (JavaMode) mode;
debugger = new Debugger(this);
debugger.populateMenu(modeMenu);
// set breakpoints from marker comments
for (LineID lineID : stripBreakpointComments()) {
//System.out.println("setting: " + lineID);
debugger.setBreakpoint(lineID);
}
// setting breakpoints will flag sketch as modified, so override this here
getSketch().setModified(false);
preprocService = new PreprocService(this.jmode, this.sketch);
// long t5 = System.currentTimeMillis();
usage = new ShowUsage(this, preprocService);
inspect = new InspectMode(this, preprocService, usage);
rename = new Rename(this, preprocService, usage);
if (SHOW_AST_VIEWER) {
astViewer = new ASTViewer(this, preprocService);
}
errorChecker = new ErrorChecker(this::setProblemList, preprocService);
// long t7 = System.currentTimeMillis();
for (SketchCode code : getSketch().getCode()) {
Document document = code.getDocument();
addDocumentListener(document);
}
sketchChanged();
// long t9 = System.currentTimeMillis();
Toolkit.setMenuMnemonics(textarea.getRightClickPopup());
// ensure completion is hidden when editor loses focus
addWindowFocusListener(new WindowFocusListener() {
public void windowLostFocus(WindowEvent e) {
getJavaTextArea().hideSuggestion();
}
public void windowGainedFocus(WindowEvent e) { }
});
// long t10 = System.currentTimeMillis();
// System.out.println("java editor was " + (t10-t9) + " " + (t9-t7) + " " + (t7-t5) + " " + (t5-t1));
}
public PdePreprocessor createPreprocessor(final String sketchName) {
return PdePreprocessor.builderFor(sketchName).build();
}
protected JEditTextArea createTextArea() {
return new JavaTextArea(new PdeTextAreaDefaults(), this);
}
public EditorToolbar createToolbar() {
return new JavaToolbar(this);
}
private int previousTabCount = 1;
// TODO: this is a clumsy way to get notified when tabs get added/deleted
// Override the parent call to add hook to the rebuild() method
public EditorHeader createHeader() {
return new EditorHeader(this) {
public void rebuild() {
super.rebuild();
// after Rename and New Tab, we may have new .java tabs
if (preprocService != null) {
int currentTabCount = sketch.getCodeCount();
if (currentTabCount != previousTabCount) {
previousTabCount = currentTabCount;
sketchChanged();
}
}
}
};
}
@Override
public EditorFooter createFooter() {
EditorFooter footer = super.createFooter();
addErrorTable(footer);
return footer;
}
public Formatter createFormatter() {
return new AutoFormat();
}
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
public JMenu buildFileMenu() {
//String appTitle = JavaToolbar.getTitle(JavaToolbar.EXPORT, false);
String appTitle = Language.text("menu.file.export_application");
JMenuItem exportApplication = Toolkit.newJMenuItemShift(appTitle, 'E');
exportApplication.addActionListener(e -> {
if (sketch.isUntitled() || sketch.isReadOnly()) {
// Exporting to application will open the sketch folder, which is
// weird for untitled sketches (that live in a temp folder) and
// read-only sketches (that live in the examples folder).
// TODO Better explanation? And some localization too.
Messages.showMessage("Save First", "Please first save the sketch.");
} else {
handleExportApplication();
}
});
var exportPDEZ = new JMenuItem(Language.text("menu.file.export_pdez"));
exportPDEZ.addActionListener(e -> {
if (sketch.isUntitled() || sketch.isReadOnly()) {
Messages.showMessage("Save First", "Please first save the sketch.");
} else {
handleExportPDEZ();
}
});
return buildFileMenu(new JMenuItem[] { exportApplication, exportPDEZ });
}
public JMenu buildSketchMenu() {
JMenuItem runItem = Toolkit.newJMenuItem(Language.text("menu.sketch.run"), 'R');
runItem.addActionListener(e -> handleRun());
JMenuItem presentItem = Toolkit.newJMenuItemShift(Language.text("menu.sketch.present"), 'R');
presentItem.addActionListener(e -> handlePresent());
JMenuItem stopItem = new JMenuItem(Language.text("menu.sketch.stop"));
stopItem.addActionListener(e -> {
if (isDebuggerEnabled()) {
Messages.log("Invoked 'Stop' menu item");
debugger.stopDebug();
} else {
handleStop();
}
});
JMenuItem tweakItem = Toolkit.newJMenuItemShift(Language.text("menu.sketch.tweak"), 'T');
tweakItem.addActionListener(e -> handleTweak());
return buildSketchMenu(new JMenuItem[] {
runItem, presentItem, tweakItem, stopItem
});
}
public JMenu buildHelpMenu() {
JMenu menu = new JMenu(Language.text("menu.help"));
JMenuItem item;
// macOS already has its own about menu
if (!Platform.isMacOS()) {
item = new JMenuItem(Language.text("menu.help.about"));
item.addActionListener(e -> new About(JavaEditor.this));
menu.add(item);
}
item = new JMenuItem(Language.text("menu.help.welcome"));
item.addActionListener(e -> {
try {
new Welcome(base);
} catch (IOException ioe) {
Messages.showWarning("Unwelcome Error",
"Please report this error to\n" +
"https://github.com/processing/processing4/issues", ioe);
}
});
menu.add(item);
item = new JMenuItem(Language.text("menu.help.environment"));
item.addActionListener(e -> showReference("../environment/index.html"));
menu.add(item);
item = new JMenuItem(Language.text("menu.help.reference"));
item.addActionListener(e -> showReference("index.html"));
menu.add(item);
item = Toolkit.newJMenuItemShift(Language.text("menu.help.find_in_reference"), 'F');
item.addActionListener(e -> {
if (textarea.isSelectionActive()) {
handleFindReference();
} else {
statusNotice(Language.text("editor.status.find_reference.select_word_first"));
}
});
menu.add(item);
// Not gonna use "update" since it's more about re-downloading:
// it doesn't make sense to "update" the reference because it's
// specific to a version of the software anyway. [fry 221125]
// item = new JMenuItem(isReferenceDownloaded() ?
// "menu.help.reference.update" : "menu.help.reference.download");
item = new JMenuItem(Language.text("menu.help.reference.download"));
item.addActionListener(e -> new Thread(this::downloadReference).start());
menu.add(item);
menu.addSeparator();
// Report a bug link opener
item = new JMenuItem(Language.text("menu.help.report"));
item.addActionListener(e -> Platform.openURL(Language.text("menu.help.report.url")));
menu.add(item);
// Ask on the Forum link opener
item = new JMenuItem(Language.text("menu.help.ask"));
item.addActionListener(e -> Platform.openURL(Language.text("menu.help.getting_started.url")));
menu.add(item);
menu.addSeparator();
final JMenu libRefSubmenu = new JMenu(Language.text("menu.help.libraries_reference"));
// Adding this in case references are included in a core library,
// or other core libraries are included in the future
boolean isCoreLibMenuItemAdded =
addLibReferencesToSubMenu(mode.coreLibraries, libRefSubmenu);
if (isCoreLibMenuItemAdded && !mode.contribLibraries.isEmpty()) {
libRefSubmenu.addSeparator();
}
boolean isContribLibMenuItemAdded =
addLibReferencesToSubMenu(mode.contribLibraries, libRefSubmenu);
if (!isContribLibMenuItemAdded && !isCoreLibMenuItemAdded) {
JMenuItem emptyMenuItem = new JMenuItem(Language.text("menu.help.empty"));
emptyMenuItem.setEnabled(false);
emptyMenuItem.setFocusable(false);
emptyMenuItem.setFocusPainted(false);
libRefSubmenu.add(emptyMenuItem);
} else if (!isContribLibMenuItemAdded && !mode.coreLibraries.isEmpty()) {
//re-populate the menu to get rid of terminal separator
libRefSubmenu.removeAll();
addLibReferencesToSubMenu(mode.coreLibraries, libRefSubmenu);
}
menu.add(libRefSubmenu);
final JMenu toolRefSubmenu = new JMenu(Language.text("menu.help.tools_reference"));
boolean coreToolMenuItemAdded;
boolean contribToolMenuItemAdded;
List<ToolContribution> contribTools = base.getContribTools();
// Adding this in case a reference folder is added for MovieMaker,
// or in case other core tools are introduced later.
coreToolMenuItemAdded = addToolReferencesToSubMenu(base.getCoreTools(), toolRefSubmenu);
if (coreToolMenuItemAdded && !contribTools.isEmpty())
toolRefSubmenu.addSeparator();
contribToolMenuItemAdded = addToolReferencesToSubMenu(contribTools, toolRefSubmenu);
if (!contribToolMenuItemAdded && !coreToolMenuItemAdded) {
toolRefSubmenu.removeAll(); // in case a separator was added
final JMenuItem emptyMenuItem = new JMenuItem(Language.text("menu.help.empty"));
emptyMenuItem.setEnabled(false);
emptyMenuItem.setBorderPainted(false);
emptyMenuItem.setFocusable(false);
emptyMenuItem.setFocusPainted(false);
toolRefSubmenu.add(emptyMenuItem);
}
else if (!contribToolMenuItemAdded && !contribTools.isEmpty()) {
// re-populate the menu to get rid of terminal separator
toolRefSubmenu.removeAll();
addToolReferencesToSubMenu(base.getCoreTools(), toolRefSubmenu);
}
menu.add(toolRefSubmenu);
menu.addSeparator();
/*
item = new JMenuItem(Language.text("menu.help.online"));
item.setEnabled(false);
menu.add(item);
*/
item = new JMenuItem(Language.text("menu.help.getting_started"));
item.addActionListener(e -> Platform.openURL(Language.text("menu.help.getting_started.url")));
menu.add(item);
item = new JMenuItem(Language.text("menu.help.troubleshooting"));
item.addActionListener(e -> Platform.openURL(Language.text("menu.help.troubleshooting.url")));
menu.add(item);
item = new JMenuItem(Language.text("menu.help.faq"));
item.addActionListener(e -> Platform.openURL(Language.text("menu.help.faq.url")));
menu.add(item);
item = new JMenuItem(Language.text("menu.help.foundation"));
item.addActionListener(e -> Platform.openURL(Language.text("menu.help.foundation.url")));
menu.add(item);
item = new JMenuItem(Language.text("menu.help.visit"));
item.addActionListener(e -> Platform.openURL(Language.text("menu.help.visit.url")));
menu.add(item);
return menu;
}
//. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
/**
* Populates the JMenu with JMenuItems, one for each Library that has a
* reference accompanying it. The JMenuItems open the index.htm/index.html
* file of the reference in the user's default browser, or the readme.txt in
* the user's default text editor.
*
* @param libsList
* A list of the Libraries to be added
* @param subMenu
* The JMenu to which the JMenuItems corresponding to the Libraries
* are to be added
* @return true if and only if any JMenuItems were added; false otherwise
*/
private boolean addLibReferencesToSubMenu(List<Library> libsList, JMenu subMenu) {
boolean isItemAdded = false;
for (Library libContrib : libsList) {
if (libContrib.hasReference()) {
JMenuItem libRefItem = new JMenuItem(libContrib.getName());
libRefItem.addActionListener(arg0 -> showReferenceFile(libContrib.getReferenceIndexFile()));
subMenu.add(libRefItem);
isItemAdded = true;
}
}
return isItemAdded;
}
/**
* Populates the JMenu with JMenuItems, one for each Tool that has a reference
* accompanying it. The JMenuItems open the index.htm/index.html file of the
* reference in the user's default browser, or the readme.txt in the user's
* default text editor.
*
* @param toolsList
* A list of Tools to be added
* @param subMenu
* The JMenu to which the JMenuItems corresponding to the Tools are
* to be added
* @return true if and only if any JMenuItems were added; false otherwise
*/
private boolean addToolReferencesToSubMenu(List<ToolContribution> toolsList, JMenu subMenu) {
boolean isItemAdded = false;
for (ToolContribution toolContrib : toolsList) {
final File toolRef = new File(toolContrib.getFolder(), "reference/index.html");
if (toolRef.exists()) {
JMenuItem libRefItem = new JMenuItem(toolContrib.getName());
libRefItem.addActionListener(arg0 -> showReferenceFile(toolRef));
subMenu.add(libRefItem);
isItemAdded = true;
}
}
return isItemAdded;
}
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
public String getCommentPrefix() {
return "//";
}
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
/**
* Handler for Sketch → Export Application
*/
public void handleExportApplication() {
if (handleExportCheckModified()) {
statusNotice(Language.text("export.notice.exporting"));
ExportPrompt ep = new ExportPrompt(this, () -> {
try {
if (jmode.handleExportApplication(getSketch())) {
Platform.openFolder(sketch.getFolder());
statusNotice(Language.text("export.notice.exporting.done"));
}
} catch (Exception e) {
statusNotice(Language.text("export.notice.exporting.error"));
e.printStackTrace();
}
});
ep.trigger();
}
}
/**
* Handler for File → Export PDEZ
*/
public void handleExportPDEZ() {
if (handleExportCheckModified()) {
var sketch = getSketch();
var folder = sketch.getFolder().toPath();
var target = new File(folder + ".pdez").toPath();
if (Files.exists(target)) {
try {
Platform.deleteFile(target.toFile());
} catch (IOException e) {
Messages.showError("Export Error", "Could not delete existing file: " + target, e);
}
}
try (var zs = new ZipOutputStream(Files.newOutputStream(target))) {
Files.walk(folder)
.filter(path -> !Files.isDirectory(path))
.forEach(path -> {
var zipEntry = new ZipEntry(folder.getParent().relativize(path).toString());
try {
zs.putNextEntry(zipEntry);
Files.copy(path, zs);
zs.closeEntry();
} catch (IOException e) {
throw new RuntimeException(e);
}
});
} catch (IOException e) {
throw new RuntimeException(e);
}
if (Desktop.isDesktopSupported()) {
var desktop = Desktop.getDesktop();
if (desktop.isSupported(Desktop.Action.BROWSE_FILE_DIR)) {
desktop.browseFileDirectory(target.toFile());
} else {
try {
desktop.open(target.getParent().toFile());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}
}
/**
* Checks to see if the sketch has been modified, and if so,
* asks the user to save the sketch or cancel the export.
* This prevents issues where an incomplete version of the sketch
* would be exported, and is a fix for
* <A HREF="https://download.processing.org/bugzilla/157.html">Bug 157</A>
*/
protected boolean handleExportCheckModified() {
if (sketch.isReadOnly()) {
// if the files are read-only, need to first do a "save as".
Messages.showMessage(Language.text("export.messages.is_read_only"),
Language.text("export.messages.is_read_only.description"));
return false;
}
// don't allow if untitled
if (sketch.isUntitled()) {
Messages.showMessage(Language.text("export.messages.cannot_export"),
Language.text("export.messages.cannot_export.description"));
return false;
}
if (sketch.isModified()) {
Object[] options = { Language.text("prompt.ok"), Language.text("prompt.cancel") };
int result = JOptionPane.showOptionDialog(this,
Language.text("export.unsaved_changes"),
Language.text("menu.file.save"),
JOptionPane.OK_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE,
null,
options,
options[0]);
if (result == JOptionPane.OK_OPTION) {
handleSave(true);
} else {
// why it's not CANCEL_OPTION is beyond me (at least on the mac)
// but f-- it... let's get this shite done...
//} else if (result == JOptionPane.CANCEL_OPTION) {
statusNotice(Language.text("export.notice.cancel.unsaved_changes"));
//toolbar.clear();
return false;
}
}
return true;
}
public void handleRun() {
if (isDebuggerEnabled()) {
// Hitting Run while a sketch is running should restart the sketch
// https://github.com/processing/processing/issues/3623
if (debugger.isStarted()) {
debugger.stopDebug();
}
// Don't start the sketch paused, continue until a breakpoint or error
// https://github.com/processing/processing/issues/3096
debugger.continueDebug();
} else {
handleLaunch(false, false);
}
}
public void handlePresent() {
handleLaunch(true, false);
}
public void handleTweak() {
autoSave();
if (sketch.isModified()) {
Messages.showMessage(Language.text("menu.file.save"),
Language.text("tweak_mode.save_before_tweak"));
return;
}
handleLaunch(false, true);
}
protected void handleLaunch(boolean present, boolean tweak) {
prepareRun();
toolbar.activateRun();
synchronized (runtimeLock) {
runtimeLaunchRequested = true;
}
new Thread(() -> {
try {
synchronized (runtimeLock) {
if (runtimeLaunchRequested) {
runtimeLaunchRequested = false;
RunnerListener listener = new RunnerListenerEdtAdapter(JavaEditor.this);
if (!tweak) {
runtime = jmode.handleLaunch(sketch, listener, present);
} else {
runtime = jmode.handleTweak(sketch, listener, JavaEditor.this);
}
}
}
} catch (Exception e) {
EventQueue.invokeLater(() -> statusError(e));
}
}).start();
}
/**
* Event handler called when hitting the stop button. Stops a running debug
* session or performs standard stop action if not currently debugging.
*/
public void handleStop() {
if (debugger.isStarted()) {
debugger.stopDebug();
} else {
toolbar.activateStop();
try {
synchronized (runtimeLock) {
if (runtimeLaunchRequested) {
// Cancel the launch before the runtime was created
runtimeLaunchRequested = false;
}
if (runtime != null) {
// Cancel the launch after the runtime was created
runtime.close(); // kills the window
runtime = null;
}
}
} catch (Exception e) {
statusError(e);
}
toolbar.deactivateStop();
toolbar.deactivateRun();
// focus the PDE again after quitting presentation mode [toxi 030903]
toFront();
}
}
public void onRunnerExiting(Runner runner) {
synchronized (runtimeLock) {
if (this.runtime == runner) {
deactivateRun();
}
}
}
// /** Toggle a breakpoint on the current line. */
// public void toggleBreakpoint() {
// toggleBreakpoint(getCurrentLineID().lineIdx());
// }
@Override
public void toggleBreakpoint(int lineIndex) {
debugger.toggleBreakpoint(lineIndex);
}
public boolean handleSaveAs() {
//System.out.println("handleSaveAs");
String oldName = getSketch().getCode(0).getFileName();
//System.out.println("old name: " + oldName);
boolean saved = super.handleSaveAs();
if (saved) {
// re-set breakpoints in first tab (name has changed)
List<LineBreakpoint> bps = debugger.getBreakpoints(oldName);
debugger.clearBreakpoints(oldName);
String newName = getSketch().getCode(0).getFileName();
//System.out.println("new name: " + newName);
for (LineBreakpoint bp : bps) {
LineID line = new LineID(newName, bp.lineID().lineIdx());
//System.out.println("setting: " + line);
debugger.setBreakpoint(line);
}
// add breakpoint marker comments to source file
for (SketchCode code : getSketch().getCode()) {
addBreakpointComments(code.getFileName());
}
// set new name of variable inspector
//inspector.setTitle(getSketch().getName());
}
return saved;
}
/**
* Add import statements to the current tab for all packages inside
* the specified jar file.
*/
public void handleImportLibrary(String libraryName) {
// make sure the user didn't hide the sketch folder
sketch.ensureExistence();
// import statements into the main sketch file (code[0])
// if the current code is a .java file, insert into current
//if (current.flavor == PDE) {
if (mode.isDefaultExtension(sketch.getCurrentCode())) {
sketch.setCurrentCode(0);
}
Library lib = mode.findLibraryByName(libraryName);
if (lib == null) {
statusError("Unable to locate library: "+libraryName);
return;
}
// could also scan the text in the file to see if each import
// statement is already in there, but if the user has the import
// commented out, then this will be a problem.
StringList list = lib.getImports(); // ask the library for its imports
if (list == null) {
// Default to old behavior and load each package in the primary jar
list = Util.packageListFromClassPath(lib.getJarPath());
}
StringBuilder sb = new StringBuilder();
// for (int i = 0; i < list.length; i++) {
for (String item : list) {
sb.append("import ");
// sb.append(list[i]);
sb.append(item);
sb.append(".*;\n");
}
sb.append('\n');
sb.append(getText());
setText(sb.toString());
setSelection(0, 0); // scroll to start
sketch.setModified(true);
}
@Override
public void librariesChanged() {
preprocService.notifyLibrariesChanged();
}
@Override
public void codeFolderChanged() {
preprocService.notifyCodeFolderChanged();
}
@Override
public void sketchChanged() {
errorChecker.notifySketchChanged();
preprocService.notifySketchChanged();
}
public void addDocumentListener(Document doc) {
if (doc != null) {
doc.addDocumentListener(new DocumentListener() {
@Override
public void insertUpdate(DocumentEvent e) {
sketchChanged();
}
@Override
public void removeUpdate(DocumentEvent e) {
sketchChanged();
}
@Override
public void changedUpdate(DocumentEvent e) {
sketchChanged();
}
});
}
}
public void showReference(String name) {
if (useReferenceServer == null) {
// Because of this, it should be possible to create your own dist
// that includes the reference by simply adding it to modes/java.
File referenceZip = new File(mode.getFolder(), "reference.zip");
if (!referenceZip.exists()) {
// For Java Mode (the default), check for a reference.zip in the root
// of the sketchbook folder. If other Modes subclass JavaEditor and
// don't override this function, it may cause a little trouble.
referenceZip = getOfflineReferenceFile();
}
if (referenceZip.exists()) {
try {
referenceServer = new ReferenceServer(referenceZip, REFERENCE_PORT);
useReferenceServer = true;
} catch (IOException e) {
Messages.showWarning("Reference Server Problem", "Error while starting the documentation server.");
}
} else {
useReferenceServer = false;
}
}
if (useReferenceServer) {
String url = referenceServer.getPrefix() + "reference/" + name;
Platform.openURL(url);
} else {
File file = new File(mode.getReferenceFolder(), name);
if (file.exists()) {
showReferenceFile(file);
} else {
// Offline reference (temporarily) removed in 4.0 beta 9
// https://github.com/processing/processing4/issues/524
Platform.openURL("https://processing.org/reference/" + name);
}
}
}
private File getOfflineReferenceFile() {
return new File(Base.getSketchbookFolder(), "reference.zip");
}
/*
private boolean isReferenceDownloaded() {
return getOfflineReferenceFile().exists();
}
*/
private String getReferenceDownloadUrl() {
String versionName = Base.getVersionName();
int revisionInt = Base.getRevision();
String revision = String.valueOf(revisionInt);
if ("unspecified".equals(versionName) || revisionInt == Integer.MAX_VALUE) {
return "https://github.com/processing/processing4/releases/download/processing-1300-4.4.0/processing-4.4.0-reference.zip";
}
String url = String.format(
"https://github.com/processing/processing4/releases/download/processing-%s-%s/processing-%s-reference.zip",
revision, versionName, versionName);
System.out.println("Generated URL: " + url);
return url;
}
private void downloadReference() {
try {
URL source = new URL(getReferenceDownloadUrl());
HttpURLConnection conn = (HttpURLConnection) source.openConnection();
HttpURLConnection.setFollowRedirects(true);
conn.setConnectTimeout(15 * 1000);
conn.setReadTimeout(60 * 1000);
conn.setRequestMethod("GET");
conn.connect();
int length = conn.getContentLength();
// float size = (length >> 10) / 1024f;
//float size = (length / 1000) / 1000f;
// String msg =
// "Downloading reference (" + PApplet.nf(size, 0, 1) + " MB)… ";
String mb = PApplet.nf((length >> 10) / 1024f, 0, 1);
if (mb.endsWith(".0")) {
mb = mb.substring(0, mb.length() - 2); // don't show .0
}
ProgressMonitorInputStream input =
new ProgressMonitorInputStream(this,
"Downloading reference (" + mb + " MB)… ", conn.getInputStream());
input.getProgressMonitor().setMaximum(length);
// ProgressMonitor monitor = input.getProgressMonitor();
// monitor.setMaximum(length);
PApplet.saveStream(getOfflineReferenceFile(), input);
// reset the internal handling for the reference server
useReferenceServer = null;
} catch (InterruptedIOException iioe) {
// download canceled
} catch (IOException e) {
Messages.showWarning("Error downloading reference",
"Could not download the reference. Try again later.", e);
}
}
public void statusError(String what) {
super.statusError(what);
// new Exception("deactivating RUN").printStackTrace();
// toolbar.deactivate(JavaToolbar.RUN);
toolbar.deactivateRun();
}
public void internalCloseRunner() {
// Added temporarily to dump error log. TODO: Remove this later [mk29]
//if (JavaMode.errorLogsEnabled) {
// writeErrorsToFile();
//}
handleStop();
}
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
// Additions from PDE X, Debug Mode, Twerk Mode...
/**
* Used instead of the windowClosing event handler, since it's not called on
* mode switch. Called when closing the editor window. Stops running debug
* sessions and kills the variable inspector window.
*/
@Override
public void dispose() {
//System.out.println("window dispose");
// quit running debug session
if (debugger.isEnabled()) {
debugger.stopDebug();
}
debugger.dispose();
preprocService.dispose();
inspect.dispose();
usage.dispose();
rename.dispose();
errorChecker.dispose();
if (astViewer != null) {
astViewer.dispose();