forked from processing/processing
/
ErrorCheckerService.java
1712 lines (1470 loc) · 53.1 KB
/
ErrorCheckerService.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) 2012-15 The Processing Foundation
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.
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package processing.mode.java.pdex;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.Element;
import javax.swing.text.PlainDocument;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.compiler.IProblem;
import org.eclipse.jdt.core.dom.AST;
import org.eclipse.jdt.core.dom.ASTNode;
import org.eclipse.jdt.core.dom.ASTParser;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.internal.compiler.impl.CompilerOptions;
import processing.app.Library;
import processing.app.Messages;
import processing.app.Preferences;
import processing.app.Sketch;
import processing.app.SketchCode;
import processing.app.Util;
import processing.app.syntax.SyntaxDocument;
import processing.app.ui.Editor;
import processing.app.ui.EditorStatus;
import processing.app.ui.ErrorTable;
import processing.core.PApplet;
import processing.mode.java.JavaMode;
import processing.mode.java.JavaEditor;
import processing.mode.java.preproc.PdePreprocessor;
/**
* The main error checking service
*/
@SuppressWarnings("unchecked")
public class ErrorCheckerService implements Runnable {
protected JavaEditor editor;
/** Error check happens every sleepTime milliseconds */
public static final int sleepTime = 1000;
/** The amazing eclipse ast parser */
protected ASTParser parser;
/**
* Used to indirectly stop the Error Checker Thread
*/
protected AtomicBoolean stopThread;
/**
* If true, Error Checking is paused. Calls to checkCode() become useless.
*/
protected AtomicBoolean pauseThread;
//protected ErrorWindow errorWindow;
/**
* IProblem[] returned by parser stored in here
*/
protected IProblem[] problems;
/**
* Class name of current sketch
*/
protected String className;
/**
* Source code of current sketch
*/
protected String sourceCode;
/**
* URLs of extra imports jar files stored here.
*/
protected URL[] classPath;
/**
* Stores all Problems in the sketch
*/
public List<Problem> problemsList;
/**
* How many lines are present till the initial class declaration? In static
* mode, this would include imports, class declaration and setup
* declaration. In nomral mode, this would include imports, class
* declaration only. It's fate is decided inside preprocessCode()
*/
public int mainClassOffset;
/**
* Fixed p5 offsets for all sketches
*/
public int defaultImportsOffset;
/**
* Is the sketch running in static mode or active mode?
*/
public PdePreprocessor.Mode mode = PdePreprocessor.Mode.ACTIVE;
/**
* Compilation Unit for current sketch
*/
protected CompilationUnit cu;
/**
* The Compilation Unit generated during compile check
*/
protected CompilationUnit compileCheckCU;
/**
* This Compilation Unit points to the last error free CU
*/
protected CompilationUnit lastCorrectCU;
/**
* If true, compilation checker will be reloaded with updated classpath
* items.
*/
protected boolean loadCompClass = true;
/**
* Compiler Checker class. Note that methods for compilation checking are
* called from the compilationChecker object, not from this
*/
protected Class<?> checkerClass;
/**
* Compilation Checker object.
*/
protected CompilationChecker compilationChecker;
/**
* List of jar files to be present in compilation checker's classpath
*/
protected List<URL> classpathJars;
/**
* Timestamp - for measuring total overhead
*/
protected long lastTimeStamp = System.currentTimeMillis();
/**
* Used for displaying the rotating slash on the Problem Window title bar
*/
protected String[] slashAnimation = { "|", "/", "--", "\\", "|", "/", "--",
"\\" };
protected int slashAnimationIndex = 0;
/**
* Used to detect if the current tab index has changed and thus repaint the
* textarea.
*/
public int currentTab = 0, lastTab = 0;
/**
* Stores the current import statements in the program. Used to compare for
* changed import statements and update classpath if needed.
*/
protected ArrayList<ImportStatement> programImports;
/**
* List of imports when sketch was last checked. Used for checking for
* changed imports
*/
protected ArrayList<ImportStatement> previousImports = new ArrayList<ImportStatement>();
/**
* Teh Preprocessor
*/
protected XQPreprocessor xqpreproc;
/**
* Regexp for import statements. (Used from Processing source)
*/
final public String importRegexp = "(?:^|;)\\s*(import\\s+)((?:static\\s+)?\\S+)(\\s*;)";
// /**
// * Regexp for function declarations. (Used from Processing source)
// */
// final Pattern FUNCTION_DECL = Pattern
// .compile("(^|;)\\s*((public|private|protected|final|static)\\s+)*"
// + "(void|int|float|double|String|char|byte|boolean)"
// + "(\\s*\\[\\s*\\])?\\s+[a-zA-Z0-9]+\\s*\\(", Pattern.MULTILINE);
// /**
// * Matches setup or draw function declaration. We search for all those
// * modifiers and return types in order to have proper error message
// * when people use incompatible modifiers or non-void return type
// */
// private static final Pattern SETUP_OR_DRAW_FUNCTION_DECL =
// Pattern.compile("(^|;)\\s*((public|private|protected|final|static)\\s+)*" +
// "(void|int|float|double|String|char|byte|boolean)" +
// "(\\s*\\[\\s*\\])?\\s+(setup|draw)\\s*\\(",
// Pattern.MULTILINE);
protected ErrorMessageSimplifier errorMsgSimplifier;
public ErrorCheckerService(JavaEditor debugEditor) {
this.editor = debugEditor;
stopThread = new AtomicBoolean(false);
pauseThread = new AtomicBoolean(false);
problemsList = new ArrayList<Problem>();
classpathJars = new ArrayList<URL>();
initParser();
//initializeErrorWindow();
xqpreproc = new XQPreprocessor();
PdePreprocessor pdePrepoc = new PdePreprocessor(null);
defaultImportsOffset = pdePrepoc.getCoreImports().length +
pdePrepoc.getDefaultImports().length + 1;
astGenerator = new ASTGenerator(this);
syntaxErrors = new AtomicBoolean(true);
containsErrors = new AtomicBoolean(true);
errorMsgSimplifier = new ErrorMessageSimplifier();
tempErrorLog = new TreeMap<String, IProblem>();
sketchChangedListener = new SketchChangedListener();
// for (final SketchCode sc : editor.getSketch().getCode()) {
// sc.getDocument().addDocumentListener(sketchChangedListener);
// }
}
/**
* Initializes ASTParser
*/
protected void initParser() {
try {
parser = ASTParser.newParser(AST.JLS8);
} catch (Exception e) {
System.err.println("Experimental Mode initialization failed. "
+ "Are you running the right version of Processing? ");
pauseThread();
} catch (Error e) {
System.err.println("Experimental Mode initialization failed. ");
e.printStackTrace();
pauseThread();
}
}
/**
* Error checking doesn't happen before this interval has ellapsed since the
* last runManualErrorCheck() call.
*/
private final static long errorCheckInterval = 500;
/**
* Bypass sleep time
*/
private volatile boolean noSleep = false;
/**
* The way the error checking happens is: DocumentListeners are added
* to each SketchCode object. Whenever the document is edited, runManualErrorCheck()
* is called. Internally, an atomic integer counter is incremented.
* The ECS thread checks the value of this counter evey sleepTime seconds.
* If the counter is non zero, error checking is done(in the ECS thread)
* and the counter is reset.
*/
public void run() {
stopThread.set(false);
checkCode();
lastErrorCheckCall = System.currentTimeMillis();
if (!hasSyntaxErrors()) {
// editor.showProblemListView(Language.text("editor.footer.console"));
editor.showConsole();
}
// Make sure astGen has at least one CU to start with
// This is when the loaded sketch already has syntax errors.
// Completion wouldn't be complete, but it'd be still something
// better than nothing
synchronized (astGenerator) {
astGenerator.buildAST(cu);
}
handleErrorCheckingToggle();
while (!stopThread.get()) {
try {
// Take a nap.
if(!noSleep) {
Thread.sleep(sleepTime);
}
else {
noSleep = false;
Messages.log("Didn't sleep!");
}
} catch (Exception e) {
Messages.log("Oops! [ErrorCheckerThreaded]: " + e);
// e.printStackTrace();
}
updatePaintedThingys();
updateEditorStatus();
updateSketchCodeListeners();
if (pauseThread.get())
continue;
if(textModified.get() == 0)
continue;
// Check if a certain interval has passed after the call. Only then
// begin error check. Helps prevent unnecessary flickering. See #2677
if (System.currentTimeMillis() - lastErrorCheckCall > errorCheckInterval) {
Messages.log("Interval passed, starting error check");
checkCode();
checkForMissingImports();
}
}
synchronized (astGenerator) {
astGenerator.disposeAllWindows();
}
compilationChecker = null;
checkerClass = null;
classLoader = null;
System.gc();
Messages.loge("Thread stopped: " + editor.getSketch().getName());
System.gc();
}
protected void updateSketchCodeListeners() {
for (SketchCode sc : editor.getSketch().getCode()) {
SyntaxDocument doc = (SyntaxDocument) sc.getDocument();
if (!hasSketchChangedListener(doc)) {
doc.addDocumentListener(sketchChangedListener);
}
}
}
boolean hasSketchChangedListener(SyntaxDocument doc) {
if (doc != null && doc.getDocumentListeners() != null) {
for (DocumentListener dl : doc.getDocumentListeners()) {
if (dl.equals(sketchChangedListener)) {
return true;
}
}
}
return false;
}
protected void checkForMissingImports() {
if (Preferences.getBoolean(JavaMode.SUGGEST_IMPORTS_PREF)) {
for (Problem p : problemsList) {
if(p.getIProblem().getID() == IProblem.UndefinedType) {
String args[] = p.getIProblem().getArguments();
if (args.length > 0) {
String missingClass = args[0];
Messages.log("Will suggest for type:" + missingClass);
//astGenerator.suggestImports(missingClass);
}
}
}
}
}
protected ASTGenerator astGenerator;
public ASTGenerator getASTGenerator() {
return astGenerator;
}
/**
* This thing acts as an event queue counter of sort.
* Since error checking happens on demand, anytime this counter
* goes above 0, error check is triggered, and counter reset.
* It's thread safe to avoid any mess.
*/
protected AtomicInteger textModified = new AtomicInteger();
/**
* Time stamp of last runManualErrorCheck() call.
*/
private volatile long lastErrorCheckCall = 0;
/**
* Triggers error check
*/
public void runManualErrorCheck() {
// log("Error Check.");
textModified.incrementAndGet();
lastErrorCheckCall = System.currentTimeMillis();
}
// TODO: Experimental, lookout for threading related issues
public void quickErrorCheck() {
noSleep = true;
}
protected SketchChangedListener sketchChangedListener;
protected class SketchChangedListener implements DocumentListener{
private SketchChangedListener(){
}
@Override
public void insertUpdate(DocumentEvent e) {
if (JavaMode.errorCheckEnabled) {
runManualErrorCheck();
//log("doc insert update, man error check..");
}
}
@Override
public void removeUpdate(DocumentEvent e) {
if (JavaMode.errorCheckEnabled){
runManualErrorCheck();
//log("doc remove update, man error check..");
}
}
@Override
public void changedUpdate(DocumentEvent e) {
if (JavaMode.errorCheckEnabled){
runManualErrorCheck();
//log("doc changed update, man error check..");
}
}
}
/**
* state = 1 > syntax check done<br>
* state = 2 > compilation check done
*/
public int compilationUnitState = 0;
protected boolean checkCode() {
// log("checkCode() " + textModified.get());
lastTimeStamp = System.currentTimeMillis();
try {
sourceCode = preprocessCode(editor.getSketch().getMainProgram());
compilationUnitState = 0;
syntaxCheck();
// log(editor.getSketch().getName() + "1 MCO " + mainClassOffset);
// No syntax errors, proceed for compilation check, Stage 2.
//if(hasSyntaxErrors()) astGenerator.buildAST(null);
if (!hasSyntaxErrors()) {
}
if (problems.length == 0 && !editor.hasJavaTabs()) {
//mainClassOffset++; // just a hack.
sourceCode = xqpreproc.doYourThing(sourceCode, programImports);
prepareCompilerClasspath();
// mainClassOffset = xqpreproc.mainClassOffset; // tiny, but
// // significant
// if (staticMode) {
// mainClassOffset++; // Extra line for setup() decl.
// }
// log(sourceCode);
// log("--------------------------");
compileCheck();
// log(editor.getSketch().getName() + "2 MCO " + mainClassOffset);
}
synchronized (astGenerator) {
astGenerator.buildAST(cu);
}
if (!JavaMode.errorCheckEnabled) {
problemsList.clear();
Messages.log("Error Check disabled, so not updating UI.");
}
calcPdeOffsetsForProbList();
updateErrorTable();
editor.updateErrorBar(problemsList);
updateEditorStatus();
editor.getTextArea().repaint();
updatePaintedThingys();
editor.updateErrorToggle();
int x = textModified.get();
//log("TM " + x);
if (x >= 2) {
textModified.set(2);
x = 2;
}
if (x > 0)
textModified.set(x - 1);
else
textModified.set(0);
return true;
} catch (Exception e) {
Messages.log("Oops! [ErrorCheckerService.checkCode]: " + e);
e.printStackTrace();
}
return false;
}
protected AtomicBoolean syntaxErrors, containsErrors;
public boolean hasSyntaxErrors(){
return syntaxErrors.get();
}
public boolean hasErrors(){
return containsErrors.get();
}
public TreeMap<String, IProblem> tempErrorLog;
protected void syntaxCheck() {
syntaxErrors.set(true);
containsErrors.set(true);
parser.setSource(sourceCode.toCharArray());
parser.setKind(ASTParser.K_COMPILATION_UNIT);
Map<String, String> options = JavaCore.getOptions();
JavaCore.setComplianceOptions(JavaCore.VERSION_1_8, options);
options.put(JavaCore.COMPILER_SOURCE, JavaCore.VERSION_1_8);
options.put(JavaCore.COMPILER_DOC_COMMENT_SUPPORT, JavaCore.ENABLED);
parser.setCompilerOptions(options);
if (cu == null)
cu = (CompilationUnit) parser.createAST(null);
else {
synchronized (cu) {
cu = (CompilationUnit) parser.createAST(null);
}
}
compilationUnitState = 1;
synchronized (problemsList) {
// Store errors returned by the ast parser
problems = cu.getProblems();
// log("Problem Count: " + problems.length);
// Populate the probList
problemsList = new ArrayList<Problem>();
for (int i = 0; i < problems.length; i++) {
int a[] = calculateTabIndexAndLineNumber(problems[i].getSourceLineNumber());
Problem p = new Problem(problems[i], a[0], a[1]);
problemsList.add(p);
// log(problems[i].getMessage());
// for (String j : problems[i].getArguments()) {
// log("arg " + j);
// }
// log(p.toString());
}
if (problems.length == 0) {
syntaxErrors.set(false);
containsErrors.set(false);
parser.setSource(sourceCode.toCharArray());
parser.setKind(ASTParser.K_COMPILATION_UNIT);
parser.setCompilerOptions(options);
lastCorrectCU = (CompilationUnit) parser.createAST(null);
} else {
syntaxErrors.set(true);
containsErrors.set(true);
}
}
}
protected URLClassLoader classLoader;
protected void compileCheck() {
// CU needs to be updated coz before compileCheck xqpreprocessor is run on
// the source code which makes some further changes
//TODO Check if this breaks things
parser.setSource(sourceCode.toCharArray());
parser.setKind(ASTParser.K_COMPILATION_UNIT);
Map<String, String> options = JavaCore.getOptions();
JavaCore.setComplianceOptions(JavaCore.VERSION_1_8, options);
options.put(JavaCore.COMPILER_SOURCE, JavaCore.VERSION_1_8);
options.put(JavaCore.COMPILER_DOC_COMMENT_SUPPORT, JavaCore.ENABLED);
parser.setCompilerOptions(options);
if (compileCheckCU == null) {
compileCheckCU = (CompilationUnit) parser.createAST(null);
} else {
synchronized (compileCheckCU) {
compileCheckCU = (CompilationUnit) parser.createAST(null);
}
}
if (!hasSyntaxErrors()) {
lastCorrectCU = compileCheckCU;
}
cu = compileCheckCU;
compilationUnitState = 2;
// Currently (Sept, 2012) I'm using Java's reflection api to load the
// CompilationChecker class(from CompilationChecker.jar) that houses the
// Eclispe JDT compiler, and call its getErrorsAsObj method to obtain
// errors. This way, I'm able to add the paths of contributed libraries
// to the classpath of CompilationChecker, dynamically. The eclipse compiler
// needs all referenced libraries in the classpath. Totally a hack. If you find
// a better method, do let me know.
try {
// NOTE TO SELF: If classpath contains null Strings
// URLClassLoader shoots NPE bullets.
// If imports have changed, reload classes with new classpath.
if (loadCompClass) {
classPath = new URL[classpathJars.size()];
classpathJars.toArray(classPath);
compilationChecker = null;
classLoader = null;
System.gc();
// log("CP Len -- " + classpath.length);
classLoader = new URLClassLoader(classPath);
compilationChecker = new CompilationChecker();
loadCompClass = false;
}
if (compilerSettings == null) {
prepareCompilerSetting();
}
synchronized (problemsList) {
problems = compilationChecker.getErrors(className, sourceCode,
compilerSettings, classLoader);
if (problems == null) {
return;
}
for (IProblem problem : problems) {
// added a -1 to line number because in compile check code
// an extra package statement is added, so all line numbers
// are increased by 1
int[] a = calculateTabIndexAndLineNumber(problem.getSourceLineNumber() - 1);
Problem p = new Problem(problem, a[0], a[1]);
if (problem.isError()) {
p.setType(Problem.ERROR);
containsErrors.set(true); // set flag
}
if (problem.isWarning()) {
p.setType(Problem.WARNING);
}
// If warnings are disabled, skip 'em
if (p.isWarning() && !JavaMode.warningsEnabled) {
continue;
}
problemsList.add(p);
}
}
} catch (Exception e) {
System.err.println("compileCheck() problem." + e);
e.printStackTrace();
pauseThread();
} catch (NoClassDefFoundError e) {
e.printStackTrace();
pauseThread();
} catch(OutOfMemoryError e) {
System.err.println("Out of memory while checking for errors.");
System.err.println("Close some sketches and then re-open this sketch.");
pauseThread();
}
}
/**
* Calculates PDE Offsets from Java Offsets for Problems
*/
private void calcPdeOffsetsForProbList() {
try {
PlainDocument javaSource = new PlainDocument();
javaSource.insertString(0, sourceCode, null);
// Code in pde tabs stored as PlainDocument
List<Document> pdeTabs = new ArrayList<>();
for (SketchCode sc : editor.getSketch().getCode()) {
PlainDocument tab = new PlainDocument();
if (editor.getSketch().getCurrentCode().equals(sc)) {
tab.insertString(0, sc.getDocumentText(), null);
} else {
tab.insertString(0, sc.getProgram(), null);
}
pdeTabs.add(tab);
}
int pkgNameOffset = ("package " + className + ";\n").length();
// package name is added only during compile check
if (compilationUnitState != 2) {
pkgNameOffset = 0;
}
for (Problem p : problemsList) {
int prbStart = p.getIProblem().getSourceStart() - pkgNameOffset;
int prbEnd = p.getIProblem().getSourceEnd() - pkgNameOffset;
int javaLineNumber = p.getSourceLineNumber() - 1;
// not sure if this is necessary [fry 150808]
if (compilationUnitState == 2) {
javaLineNumber--;
}
// errors on the first line were setting this to -1 [fry 150808]
if (javaLineNumber < 0) {
javaLineNumber = 0;
}
Element lineElement =
javaSource.getDefaultRootElement().getElement(javaLineNumber);
if (lineElement == null) {
Messages.log("calcPDEOffsetsForProbList(): " +
"Couldn't fetch Java line number " +
javaLineNumber + "\nProblem: " + p);
p.setPDEOffsets(-1, -1);
continue;
}
int lineStart = lineElement.getStartOffset();
int lineLength = lineElement.getEndOffset() - lineStart;
String javaLine = javaSource.getText(lineStart, lineLength);
Document doc = pdeTabs.get(p.getTabIndex());
Element pdeLineElement =
doc.getDefaultRootElement().getElement(p.getLineNumber());
if (pdeLineElement == null) {
Messages.log("calcPDEOffsetsForProbList(): " +
"Couldn't fetch pde line number " +
javaLineNumber + "\nProblem: " + p);
p.setPDEOffsets(-1,-1);
continue;
}
int pdeLineStart = pdeLineElement.getStartOffset();
int pdeLineLength = pdeLineElement.getEndOffset() - pdeLineStart;
String pdeLine =
pdeTabs.get(p.getTabIndex()).getText(pdeLineStart, pdeLineLength);
OffsetMatcher ofm = new OffsetMatcher(pdeLine, javaLine);
int pdeOffset =
ofm.getPdeOffForJavaOff(prbStart - lineStart, prbEnd - prbStart + 1);
p.setPDEOffsets(pdeOffset, pdeOffset + prbEnd - prbStart);
}
} catch (BadLocationException ble) {
ble.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
public CompilationUnit getLastCorrectCU() {
return lastCorrectCU;
}
public CompilationUnit getLatestCU() {
return compileCheckCU;
}
private int loadClassCounter = 0;
public URLClassLoader getSketchClassLoader() {
loadClassCounter++;
if (loadClassCounter > 100) {
loadClassCounter = 0;
classLoader = null;
System.gc();
classLoader = new URLClassLoader(classPath);
}
return classLoader;
}
/**
* Processes import statements to obtain class paths of contributed
* libraries. This would be needed for compilation check. Also, adds
* stuff(jar files, class files, candy) from the code folder. And it looks
* messed up.
*/
protected void prepareCompilerClasspath() {
if (!loadCompClass) {
return;
}
synchronized (classpathJars) {
// log("1..");
classpathJars = new ArrayList<URL>();
String entry = "";
// boolean codeFolderChecked = false;
for (ImportStatement impstat : programImports) {
String item = impstat.getImportName();
int dot = item.lastIndexOf('.');
entry = (dot == -1) ? item : item.substring(0, dot);
entry = entry.substring(6).trim();
// log("Entry--" + entry);
if (ignorableImport(entry)) {
// log("Ignoring: " + entry);
continue;
}
Library library = null;
// Try to get the library classpath and add it to the list
try {
library = editor.getMode().getLibrary(entry);
String[] libraryPath =
PApplet.split(library.getClassPath().substring(1).trim(),
File.pathSeparatorChar);
for (String pathItem : libraryPath) {
classpathJars.add(new File(pathItem).toURI().toURL());
}
} catch (Exception e) {
Messages.log("Encountered " + e + " while adding library to classpath");
}
}
// Look around in the code folder for jar files and them too
if (editor.getSketch().hasCodeFolder()) {
File codeFolder = editor.getSketch().getCodeFolder();
// get a list of .jar files in the "code" folder
// (class files in subfolders should also be picked up)
String codeFolderClassPath = Util.contentsToClassPath(codeFolder);
// codeFolderChecked = true;
// huh? doesn't this mean .length() == 0? [fry]
if (!codeFolderClassPath.equalsIgnoreCase("")) {
Messages.log("Sketch has a code folder. Adding its jars");
String codeFolderPath[] =
PApplet.split(codeFolderClassPath.substring(1).trim(),
File.pathSeparatorChar);
try {
for (String pathItem : codeFolderPath) {
classpathJars.add(new File(pathItem).toURI().toURL());
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
}
// Also add jars specified in mode's search path
String modeJars[] = ((JavaMode) getEditor().getMode()).getSearchPath().split(File.pathSeparatorChar + "");
for (String mj : modeJars) {
try {
classpathJars.add(new File(mj).toURI().toURL());
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
}
new Thread(new Runnable() {
public void run() {
synchronized (astGenerator) {
astGenerator.loadJars(); // update jar file for completion lookup
}
}
}).start();
}
/**
* Ignore processing packages, java.*.*. etc.
*/
protected boolean ignorableImport(String packageName) {
return (packageName.startsWith("java.") ||
packageName.startsWith("javax."));
}
protected boolean ignorableSuggestionImport(String impName) {
String impNameLc = impName.toLowerCase();
for (ImportStatement impS : programImports) {
if (impNameLc.startsWith(impS.getPackageName().toLowerCase())) {
return false;
}
}
/*for (ImportStatement impS : codeFolderImports) {
if (impNameLc.startsWith(impS.getPackageName().toLowerCase())) {
return false;
}
}*/
final String include = "include";
final String exclude = "exclude";
if (impName.startsWith("processing")) {
if (JavaMode.suggestionsMap.get(include).contains(impName)) {
return false;
} else if (JavaMode.suggestionsMap.get(exclude).contains(impName)) {
return true;
}
} else if (impName.startsWith("java")) {
if (JavaMode.suggestionsMap.get(include).contains(impName)) {
return false;
}
}
return true;
}
/** Options for the JDT Compiler */
protected Map<String, String> compilerSettings;
/** Set compiler options for JDT Compiler */
protected void prepareCompilerSetting() {
compilerSettings = new HashMap<String, String>();
compilerSettings.put(CompilerOptions.OPTION_LineNumberAttribute,
CompilerOptions.GENERATE);
compilerSettings.put(CompilerOptions.OPTION_SourceFileAttribute,
CompilerOptions.GENERATE);
compilerSettings.put(CompilerOptions.OPTION_Source,
CompilerOptions.VERSION_1_8);
compilerSettings.put(CompilerOptions.OPTION_ReportUnusedImport,
CompilerOptions.IGNORE);
compilerSettings.put(CompilerOptions.OPTION_ReportMissingSerialVersion,
CompilerOptions.IGNORE);
compilerSettings.put(CompilerOptions.OPTION_ReportRawTypeReference,
CompilerOptions.IGNORE);
compilerSettings.put(CompilerOptions.OPTION_ReportUncheckedTypeOperation,
CompilerOptions.IGNORE);
}
/**
* Updates the error table in the Error Window.
*/
public void updateErrorTable() {
try {
ErrorTable table = editor.getErrorTable();
table.clearRows();
// String[][] errorData = new String[problemsList.size()][3];
// int index = 0;
// for (int i = 0; i < problemsList.size(); i++) {
Sketch sketch = editor.getSketch();
for (Problem p : problemsList) {
String message = p.getMessage();
if (Preferences.getBoolean(JavaMode.SUGGEST_IMPORTS_PREF)) {
if (p.getIProblem().getID() == IProblem.UndefinedType) {
String[] args = p.getIProblem().getArguments();
if (args.length > 0) {
String missingClass = args[0];
String[] si;
synchronized (astGenerator) {
si = astGenerator.getSuggestImports(missingClass);
}
if (si != null && si.length > 0) {
p.setImportSuggestions(si);
// errorData[index][0] = "<html>" + p.getMessage() +
// " (<font color=#0000ff><u>Import Suggestions available</u></font>)</html>";
message += " (double-click for suggestions)";
}
}
}