use of javax.swing.text.BadLocationException in project SKMCLauncher by SKCraft.
the class LimitLinesDocumentListener method removeFromStart.
private void removeFromStart(Document document, Element root) {
Element line = root.getElement(0);
int end = line.getEndOffset();
try {
document.remove(0, end);
} catch (BadLocationException ble) {
System.out.println(ble);
}
}
use of javax.swing.text.BadLocationException in project processing by processing.
the class CompositionTextManager method processCompositionText.
/**
* Called when a user processing input characters and
* select candidates from input method.
*
* @param text Text from InputMethodEvent.
* @param committed_count Numbers of committed characters in text.
*/
public void processCompositionText(AttributedCharacterIterator text, int committed_count) {
int layoutCaretPosition = initialCaretPosition + committed_count;
CompositionTextPainter compositionPainter = textArea.getPainter().getCompositionTextpainter();
compositionPainter.setComposedTextLayout(getTextLayout(text, committed_count), layoutCaretPosition);
int textLength = text.getEndIndex() - text.getBeginIndex() - committed_count;
StringBuilder unCommitedStringBuf = new StringBuilder(textLength);
char c;
for (c = text.setIndex(committed_count); c != CharacterIterator.DONE && textLength > 0; c = text.next(), --textLength) {
unCommitedStringBuf.append(c);
}
String unCommittedString = unCommitedStringBuf.toString();
try {
if (canRemovePreviousInput(committed_count)) {
textArea.getDocument().remove(layoutCaretPosition, prevComposeString.length());
}
textArea.getDocument().insertString(layoutCaretPosition, unCommittedString, null);
if (committed_count > 0) {
initialCaretPosition = initialCaretPosition + committed_count;
}
prevComposeString = unCommittedString;
prevCommittedCount = committed_count;
} catch (BadLocationException e) {
e.printStackTrace();
}
}
use of javax.swing.text.BadLocationException in project processing by processing.
the class PdeTextAreaPainter method paintErrorLine.
/**
* Paints the underline for an error/warning line
*/
protected void paintErrorLine(Graphics gfx, int line, int x) {
List<Problem> problems = getEditor().findProblems(line);
for (Problem problem : problems) {
int startOffset = problem.getStartOffset();
int stopOffset = problem.getStopOffset();
int lineOffset = textArea.getLineStartOffset(line);
int wiggleStart = Math.max(startOffset, lineOffset);
int wiggleStop = Math.min(stopOffset, textArea.getLineStopOffset(line));
int y = textArea.lineToY(line) + fm.getLeading() + fm.getMaxDescent();
try {
String badCode = null;
String goodCode = null;
try {
SyntaxDocument doc = textArea.getDocument();
badCode = doc.getText(wiggleStart, wiggleStop - wiggleStart);
goodCode = doc.getText(lineOffset, wiggleStart - lineOffset);
//log("paintErrorLine() LineText GC: " + goodCode);
//log("paintErrorLine() LineText BC: " + badCode);
} catch (BadLocationException bl) {
// log((ta.getLineStopOffset(line) - start - 1));
return;
}
int trimmedLength = badCode.trim().length();
int rightTrimmedLength = trimRight(badCode).length();
int leftTrimLength = rightTrimmedLength - trimmedLength;
// Fix offsets when bad code is just whitespace
if (trimmedLength == 0) {
leftTrimLength = 0;
rightTrimmedLength = badCode.length();
}
int x1 = textArea.offsetToX(line, goodCode.length() + leftTrimLength);
int x2 = textArea.offsetToX(line, goodCode.length() + rightTrimmedLength);
if (x1 == x2)
x2 += fm.stringWidth(" ");
int y1 = y + fm.getHeight() - 2;
if (line != problem.getLineNumber()) {
// on the following lines, wiggle extends to the left border
x1 = Editor.LEFT_GUTTER;
}
gfx.setColor(errorUnderlineColor);
if (problem.isWarning()) {
gfx.setColor(warningUnderlineColor);
}
paintSquiggle(gfx, y1, x1, x2);
} catch (Exception e) {
e.printStackTrace();
}
}
}
use of javax.swing.text.BadLocationException in project processing by processing.
the class PreprocessingService method preprocessSketch.
/// --------------------------------------------------------------------------
private PreprocessedSketch preprocessSketch(PreprocessedSketch prevResult) {
boolean firstCheck = prevResult == null;
PreprocessedSketch.Builder result = new PreprocessedSketch.Builder();
List<ImportStatement> codeFolderImports = result.codeFolderImports;
List<ImportStatement> programImports = result.programImports;
JavaMode javaMode = (JavaMode) editor.getMode();
Sketch sketch = result.sketch = editor.getSketch();
String className = sketch.getName();
StringBuilder workBuffer = new StringBuilder();
// Combine code into one buffer
IntList tabStartsList = new IntList();
for (SketchCode sc : sketch.getCode()) {
if (sc.isExtension("pde")) {
tabStartsList.append(workBuffer.length());
try {
workBuffer.append(sc.getDocumentText());
} catch (BadLocationException e) {
e.printStackTrace();
}
workBuffer.append('\n');
}
}
result.tabStartOffsets = tabStartsList.array();
String pdeStage = result.pdeCode = workBuffer.toString();
boolean reloadCodeFolder = firstCheck || codeFolderChanged.getAndSet(false);
boolean reloadLibraries = firstCheck || librariesChanged.getAndSet(false);
// Core and default imports
if (coreAndDefaultImports == null) {
PdePreprocessor p = editor.createPreprocessor(null);
coreAndDefaultImports = buildCoreAndDefaultImports(p);
}
result.coreAndDefaultImports.addAll(coreAndDefaultImports);
// Prepare code folder imports
if (reloadCodeFolder) {
codeFolderImports.addAll(buildCodeFolderImports(sketch));
} else {
codeFolderImports.addAll(prevResult.codeFolderImports);
}
// TODO: convert unicode escapes to chars
SourceUtils.scrubCommentsAndStrings(workBuffer);
Mode sketchMode = PdePreprocessor.parseMode(workBuffer);
// Prepare transforms to convert pde code into parsable code
TextTransform toParsable = new TextTransform(pdeStage);
toParsable.addAll(SourceUtils.insertImports(coreAndDefaultImports));
toParsable.addAll(SourceUtils.insertImports(codeFolderImports));
toParsable.addAll(SourceUtils.parseProgramImports(workBuffer, programImports));
toParsable.addAll(SourceUtils.replaceTypeConstructors(workBuffer));
toParsable.addAll(SourceUtils.replaceHexLiterals(workBuffer));
toParsable.addAll(SourceUtils.wrapSketch(sketchMode, className, workBuffer.length()));
{
// Refresh sketch classloader and classpath if imports changed
if (javaRuntimeClassPath == null) {
javaRuntimeClassPath = buildJavaRuntimeClassPath();
sketchModeClassPath = buildModeClassPath(javaMode, false);
searchModeClassPath = buildModeClassPath(javaMode, true);
}
if (reloadLibraries) {
coreLibraryClassPath = buildCoreLibraryClassPath(javaMode);
}
boolean rebuildLibraryClassPath = reloadLibraries || checkIfImportsChanged(programImports, prevResult.programImports);
if (rebuildLibraryClassPath) {
sketchLibraryClassPath = buildSketchLibraryClassPath(javaMode, programImports);
searchLibraryClassPath = buildSearchLibraryClassPath(javaMode);
}
boolean rebuildClassPath = reloadCodeFolder || rebuildLibraryClassPath || prevResult.classLoader == null || prevResult.classPath == null || prevResult.classPathArray == null || prevResult.searchClassPathArray == null;
if (reloadCodeFolder) {
codeFolderClassPath = buildCodeFolderClassPath(sketch);
}
if (rebuildClassPath) {
{
// Sketch class path
List<String> sketchClassPath = new ArrayList<>();
sketchClassPath.addAll(javaRuntimeClassPath);
sketchClassPath.addAll(sketchModeClassPath);
sketchClassPath.addAll(sketchLibraryClassPath);
sketchClassPath.addAll(coreLibraryClassPath);
sketchClassPath.addAll(codeFolderClassPath);
String[] classPathArray = sketchClassPath.stream().toArray(String[]::new);
URL[] urlArray = Arrays.stream(classPathArray).map(path -> {
try {
return Paths.get(path).toUri().toURL();
} catch (MalformedURLException e) {
Messages.loge("malformed URL when preparing sketch classloader", e);
return null;
}
}).filter(url -> url != null).toArray(URL[]::new);
result.classLoader = new URLClassLoader(urlArray, null);
result.classPath = classPathFactory.createFromPaths(classPathArray);
result.classPathArray = classPathArray;
}
{
// Search class path
List<String> searchClassPath = new ArrayList<>();
searchClassPath.addAll(javaRuntimeClassPath);
searchClassPath.addAll(searchModeClassPath);
searchClassPath.addAll(searchLibraryClassPath);
searchClassPath.addAll(coreLibraryClassPath);
searchClassPath.addAll(codeFolderClassPath);
result.searchClassPathArray = searchClassPath.stream().toArray(String[]::new);
}
} else {
result.classLoader = prevResult.classLoader;
result.classPath = prevResult.classPath;
result.searchClassPathArray = prevResult.searchClassPathArray;
result.classPathArray = prevResult.classPathArray;
}
}
{
// Check for missing braces
List<JavaProblem> missingBraceProblems = SourceUtils.checkForMissingBraces(workBuffer, result.tabStartOffsets);
if (!missingBraceProblems.isEmpty()) {
result.missingBraceProblems.addAll(missingBraceProblems);
result.hasSyntaxErrors = true;
}
}
// Transform code to parsable state
String parsableStage = toParsable.apply();
OffsetMapper parsableMapper = toParsable.getMapper();
// Create intermediate AST for advanced preprocessing
CompilationUnit parsableCU = makeAST(parser, parsableStage.toCharArray(), COMPILER_OPTIONS);
// Prepare advanced transforms which operate on AST
TextTransform toCompilable = new TextTransform(parsableStage);
toCompilable.addAll(SourceUtils.preprocessAST(parsableCU));
// Transform code to compilable state
String compilableStage = toCompilable.apply();
OffsetMapper compilableMapper = toCompilable.getMapper();
char[] compilableStageChars = compilableStage.toCharArray();
// Create compilable AST to get syntax problems
CompilationUnit compilableCU = makeAST(parser, compilableStageChars, COMPILER_OPTIONS);
// Get syntax problems from compilable AST
result.hasSyntaxErrors |= Arrays.stream(compilableCU.getProblems()).anyMatch(IProblem::isError);
// Generate bindings after getting problems - avoids
// 'missing type' errors when there are syntax problems
CompilationUnit bindingsCU = makeASTWithBindings(parser, compilableStageChars, COMPILER_OPTIONS, className, result.classPathArray);
// Get compilation problems
List<IProblem> bindingsProblems = Arrays.asList(bindingsCU.getProblems());
result.hasCompilationErrors = bindingsProblems.stream().anyMatch(IProblem::isError);
// Update builder
result.offsetMapper = parsableMapper.thenMapping(compilableMapper);
result.javaCode = compilableStage;
result.compilationUnit = bindingsCU;
// Build it
return result.build();
}
use of javax.swing.text.BadLocationException in project jadx by skylot.
the class LineNumbers method getOffsetY.
private int getOffsetY(int rowStartOffset, FontMetrics fontMetrics) throws BadLocationException {
Rectangle r = codeArea.modelToView(rowStartOffset);
if (r == null) {
throw new BadLocationException("Can't get Y offset", rowStartOffset);
}
int lineHeight = fontMetrics.getHeight();
int y = r.y + r.height;
int descent = 0;
if (r.height == lineHeight) {
descent = fontMetrics.getDescent();
} else {
if (fonts == null) {
fonts = new HashMap<String, FontMetrics>();
}
Element root = codeArea.getDocument().getDefaultRootElement();
int index = root.getElementIndex(rowStartOffset);
Element line = root.getElement(index);
for (int i = 0; i < line.getElementCount(); i++) {
Element child = line.getElement(i);
AttributeSet as = child.getAttributes();
String fontFamily = (String) as.getAttribute(StyleConstants.FontFamily);
Integer fontSize = (Integer) as.getAttribute(StyleConstants.FontSize);
String key = fontFamily + fontSize;
FontMetrics fm = fonts.get(key);
if (fm == null) {
Font font = new Font(fontFamily, Font.PLAIN, fontSize);
fm = codeArea.getFontMetrics(font);
fonts.put(key, fm);
}
descent = Math.max(descent, fm.getDescent());
}
}
return y - descent;
}
Aggregations