@Override protected Transferable createTransferable(JComponent c) { JTextPane aTextPane = (JTextPane) c; HTMLEditorKit kit = ((HTMLEditorKit) aTextPane.getEditorKit()); StyledDocument sdoc = aTextPane.getStyledDocument(); int sel_start = aTextPane.getSelectionStart(); int sel_end = aTextPane.getSelectionEnd(); int i = sel_start; StringBuilder output = new StringBuilder(); while (i < sel_end) { Element e = sdoc.getCharacterElement(i); Object nameAttr = e.getAttributes().getAttribute(StyleConstants.NameAttribute); int start = e.getStartOffset(), end = e.getEndOffset(); if (nameAttr == HTML.Tag.BR) { output.append("\n"); } else if (nameAttr == HTML.Tag.CONTENT) { if (start < sel_start) { start = sel_start; } if (end > sel_end) { end = sel_end; } try { String str = sdoc.getText(start, end - start); output.append(str); } catch (BadLocationException ble) { Debug.error(me + "Copy-paste problem!\n%s", ble.getMessage()); } } i = end; } return new StringSelection(output.toString()); }
public int computeDocumentOffset(int line, int column) throws BadLocationException { if (line < 0 || column < 0) throw new BadLocationException("Negative line/col", -1); Element lineElement = editor.getDocument().getDefaultRootElement().getElement(line - 1); int beginLineOffset = lineElement.getStartOffset(); int endLineOffset = lineElement.getEndOffset(); String text = editor.getDocument().getText(beginLineOffset, endLineOffset - beginLineOffset); int parserChar = 1; int documentChar = 0; while (parserChar < column) { if (documentChar < text.length() && text.charAt(documentChar) == '\t') { parserChar += 8; documentChar += 1; } else { parserChar += 1; documentChar += 1; } } return beginLineOffset + documentChar; }
@Override public void mouseClicked(MouseEvent me) { Element el = doc.getCharacterElement(viewToModel(me.getPoint())); if (el == null) return; AttributeSet as = el.getAttributes(); if (as.isDefined("ip")) { String ip = (String) as.getAttribute("ip"); ScriptException se = (ScriptException) as.getAttribute("exception"); Node node = net.getAtIP(ip); if (node == null) { Utility.displayError("Error", "Computer does not exist"); return; } String errorString = "--ERROR--\n" + "Error at line number " + se.getLineNumber() + " and column number " + se.getColumnNumber() + "\n" + se.getMessage(); new ScriptDialog( parentFrame, str -> { if (str != null) { node.setScript(str); } }, node.getScript(), errorString) .setVisible(true); } }
private void analyseDocument(Document document, int lineNum, PythonIndentation indentationLogic) throws BadLocationException { Element map = document.getDefaultRootElement(); int endPos = map.getElement(lineNum).getEndOffset(); indentationLogic.reset(); indentationLogic.addText(document.getText(0, endPos)); }
/** * Repaint the region of change covered by the given document event. Damages the line that begins * the range to cover the case when the insert/remove is only on one line. If lines are added or * removed, damages the whole view. The longest line is checked to see if it has changed. */ protected void updateDamage(DocumentEvent changes, Shape a, ViewFactory f) { Component host = getContainer(); updateMetrics(); Element elem = getElement(); DocumentEvent.ElementChange ec = changes.getChange(elem); Element[] added = (ec != null) ? ec.getChildrenAdded() : null; Element[] removed = (ec != null) ? ec.getChildrenRemoved() : null; if (((added != null) && (added.length > 0)) || ((removed != null) && (removed.length > 0))) { // lines were added or removed... if (added != null) { int addedAt = ec.getIndex(); // FIXME: Is this correct????? for (int i = 0; i < added.length; i++) possiblyUpdateLongLine(added[i], addedAt + i); } if (removed != null) { for (int i = 0; i < removed.length; i++) { if (removed[i] == longLine) { longLineWidth = -1; // Must do this!! calculateLongestLine(); break; } } } preferenceChanged(null, true, true); host.repaint(); } // This occurs when syntax highlighting only changes on lines // (i.e. beginning a multiline comment). else if (changes.getType() == DocumentEvent.EventType.CHANGE) { // System.err.println("Updating the damage due to a CHANGE event..."); int startLine = changes.getOffset(); int endLine = changes.getLength(); damageLineRange(startLine, endLine, a, host); } else { Element map = getElement(); int line = map.getElementIndex(changes.getOffset()); damageLineRange(line, line, a, host); if (changes.getType() == DocumentEvent.EventType.INSERT) { // check to see if the line is longer than current // longest line. Element e = map.getElement(line); if (e == longLine) { // We must recalculate longest line's width here // because it has gotten longer. longLineWidth = getLineWidth(line); preferenceChanged(null, true, false); } else { // If long line gets updated, update the status bars too. if (possiblyUpdateLongLine(e, line)) preferenceChanged(null, true, false); } } else if (changes.getType() == DocumentEvent.EventType.REMOVE) { if (map.getElement(line) == longLine) { // removed from longest line... recalc longLineWidth = -1; // Must do this! calculateLongestLine(); preferenceChanged(null, true, false); } } } }
/* * We need to know if the caret is currently positioned on the line we * are about to paint so the line number can be highlighted. */ private boolean isCurrentLine(int rowStartOffset) { int caretPosition = component.getCaretPosition(); Element root = component.getDocument().getDefaultRootElement(); if (root.getElementIndex(rowStartOffset) == root.getElementIndex(caretPosition)) return true; else return false; }
private static int getNSVisualPosition(EditorPane txt, int pos, int direction) { Element root = txt.getDocument().getDefaultRootElement(); int numLines = root.getElementIndex(txt.getDocument().getLength() - 1) + 1; int line = root.getElementIndex(pos) + 1; int tarLine = direction == SwingConstants.NORTH ? line - 1 : line + 1; try { if (tarLine <= 0) { return 0; } if (tarLine > numLines) { return txt.getDocument().getLength(); } Rectangle curRect = txt.modelToView(pos); Rectangle tarEndRect; if (tarLine < numLines) { tarEndRect = txt.modelToView(txt.getLineStartOffset(tarLine) - 1); } else { tarEndRect = txt.modelToView(txt.getDocument().getLength() - 1); } Debug.log(9, "curRect: " + curRect + ", tarEnd: " + tarEndRect); if (curRect.x > tarEndRect.x) { pos = txt.viewToModel(new Point(tarEndRect.x, tarEndRect.y)); } else { pos = txt.viewToModel(new Point(curRect.x, tarEndRect.y)); } } catch (BadLocationException e) { Debug.error(me + "Problem getting next visual position\n%s", e.getMessage()); } return pos; }
/** * Adds the matching block end. * * @param offset the offset * @return the string after adding the matching block end * @throws BadLocationException if the offset is invalid */ protected String addMatchingBlockEnd(int offset) throws BadLocationException { StringBuffer result; StringBuffer whiteSpace = new StringBuffer(); int line = m_RootElement.getElementIndex(offset); int i = m_RootElement.getElement(line).getStartOffset(); while (true) { String temp = m_Self.getText(i, 1); if (temp.equals(" ") || temp.equals("\t")) { whiteSpace.append(temp); i++; } else { break; } } // assemble string result = new StringBuffer(); result.append(m_BlockStart); result.append("\n"); result.append(whiteSpace.toString()); if (m_UseBlanks) result.append(m_Indentation); else result.append("\t"); result.append("\n"); result.append(whiteSpace.toString()); result.append(m_BlockEnd); return result.toString(); }
// Method to draw on the view @Override public void paint(Graphics g) { Graphics2D g2D = (Graphics2D) g; // Get a 2D device context for (Element element : theApp.getModel()) { // For each element in the model element.draw(g2D); // ...draw the element } }
protected int getViewIndexAtPosition(int pos) { Element elem = getElement(); if (elem.isLeaf()) { return 0; } return super.getViewIndexAtPosition(pos); }
private void processPanel(Session session, Element element, HashMap additionalInformation) { panelElementPresent = true; String panelName = element.getAttribute("name"); if (panelName == null) { panelName = "Panel" + panelCounter++; } List<Track> panelTracks = new ArrayList(); NodeList elements = element.getChildNodes(); for (int i = 0; i < elements.getLength(); i++) { Node childNode = elements.item(i); if (childNode.getNodeName().equalsIgnoreCase(SessionElement.DATA_TRACK.getText()) || // Is this a track? childNode.getNodeName().equalsIgnoreCase(SessionElement.TRACK.getText())) { List<Track> tracks = processTrack(session, (Element) childNode, additionalInformation); if (tracks != null) { panelTracks.addAll(tracks); } } else { process(session, childNode, additionalInformation); } } TrackPanel panel = IGV.getInstance().getTrackPanel(panelName); panel.addTracks(panelTracks); }
/** * Returns the line. * * @param content the content * @param offset the offset to start at * @return the line */ protected String getLine(String content, int offset) { int line = m_RootElement.getElementIndex(offset); Element lineElement = m_RootElement.getElement(line); int start = lineElement.getStartOffset(); int end = lineElement.getEndOffset(); return content.substring(start, end - 1); }
/** * Paints the word-wrapped text. * * @param g The graphics context in which to paint. * @param a The shape (usually a rectangle) in which to paint. */ public void paint(Graphics g, Shape a) { Rectangle alloc = (a instanceof Rectangle) ? (Rectangle) a : a.getBounds(); tabBase = alloc.x; Graphics2D g2d = (Graphics2D) g; host = (RSyntaxTextArea) getContainer(); int ascent = host.getMaxAscent(); int fontHeight = host.getLineHeight(); FoldManager fm = host.getFoldManager(); TokenPainter painter = host.getTokenPainter(); Element root = getElement(); // Whether token styles should always be painted, even in selections int selStart = host.getSelectionStart(); int selEnd = host.getSelectionEnd(); boolean useSelectedTextColor = host.getUseSelectedTextColor(); int n = getViewCount(); // Number of lines. int x = alloc.x + getLeftInset(); tempRect.y = alloc.y + getTopInset(); Rectangle clip = g.getClipBounds(); for (int i = 0; i < n; i++) { tempRect.x = x + getOffset(X_AXIS, i); // tempRect.y = y + getOffset(Y_AXIS, i); tempRect.width = getSpan(X_AXIS, i); tempRect.height = getSpan(Y_AXIS, i); // System.err.println("For line " + i + ": tempRect==" + tempRect); if (tempRect.intersects(clip)) { Element lineElement = root.getElement(i); int startOffset = lineElement.getStartOffset(); int endOffset = lineElement.getEndOffset() - 1; // Why always "-1"? View view = getView(i); if (!useSelectedTextColor || selStart == selEnd || (startOffset >= selEnd || endOffset < selStart)) { drawView(painter, g2d, alloc, view, fontHeight, tempRect.y + ascent); } else { // System.out.println("Drawing line with selection: " + i); drawViewWithSelection( painter, g2d, alloc, view, fontHeight, tempRect.y + ascent, selStart, selEnd); } } tempRect.y += tempRect.height; Fold possibleFold = fm.getFoldForLine(i); if (possibleFold != null && possibleFold.isCollapsed()) { i += possibleFold.getCollapsedLineCount(); // Visible indicator of collapsed lines Color c = RSyntaxUtilities.getFoldedLineBottomColor(host); if (c != null) { g.setColor(c); g.drawLine(x, tempRect.y - 1, alloc.width, tempRect.y - 1); } } } }
private FixedCoords getFixedCoords(Element shape, int width, int height, String suffix) { if (suffix == null) suffix = ""; // parse the coordinates and check if they are fixed or reverse fixed String val = shape.getAttribute(ATR_X + suffix); int x, y, fixedX = 0, fixedY = 0; if (val.endsWith(VAL_RF)) { x = width; fixedX = x - Integer.parseInt(val.substring(0, val.length() - 2)); } else if (val.endsWith(VAL_F)) { x = Integer.parseInt(val.substring(0, val.length() - 1)); fixedX = -1; } else { x = Integer.parseInt(val); } val = shape.getAttribute(ATR_Y + suffix); if (val.endsWith(VAL_RF)) { y = height; fixedY = y - Integer.parseInt(val.substring(0, val.length() - 2)); } else if (val.endsWith(VAL_F)) { y = Integer.parseInt(val.substring(0, val.length() - 1)); fixedY = -1; } else { y = Integer.parseInt(val); } return new FixedCoords(x, fixedX, y, fixedY); }
private Dim getDim(Element shape) { return new Dim( Integer.parseInt(shape.getAttribute(ATR_X)), Integer.parseInt(shape.getAttribute(ATR_Y)), Integer.parseInt(shape.getAttribute(ATR_WIDTH)), Integer.parseInt(shape.getAttribute(ATR_HEIGHT))); }
/* * Get the line number to be drawn. The empty string will be returned * when a line of text has wrapped. */ protected String getTextLineNumber(int rowStartOffset) { Element root = component.getDocument().getDefaultRootElement(); int index = root.getElementIndex(rowStartOffset); Element line = root.getElement(index); if (line.getStartOffset() == rowStartOffset) return String.valueOf(index + 1); else return ""; }
/** * Loads all of the children to initialize the view. This is called by the <code>setParent</code> * method. Subclasses can re-implement this to initialize their child views in a different manner. * The default implementation creates a child view for each child element. * * @param f the view factory */ protected void loadChildren(ViewFactory f) { Element e = getElement(); int n = e.getElementCount(); if (n > 0) { View[] added = new View[n]; for (int i = 0; i < n; i++) added[i] = new WrappedLine(e.getElement(i)); replace(0, 0, added); } }
protected void loadChildren(ViewFactory f) { Element elem = getElement(); if (elem.isLeaf()) { View v = new LabelView(elem); append(v); } else { super.loadChildren(f); } }
private Lineprops getLineProps(Element shape) { return new Lineprops( shape.hasAttribute(ATR_STROKE) ? Float.parseFloat(shape.getAttribute(ATR_STROKE)) : IMPLIED_STROKE, shape.hasAttribute(ATR_LINETYPE) ? Float.parseFloat(shape.getAttribute(ATR_LINETYPE)) : IMPLIED_LINE); }
/** * Provides a mapping from the document model coordinate space to the coordinate space of the * view mapped to it. * * @param pos the position to convert * @param a the allocated region to render into * @return the bounding box of the given position is returned * @exception BadLocationException if the given position does not represent a valid location in * the associated document. */ @Override public Shape modelToView(int pos, Shape a, Position.Bias b) throws BadLocationException { // System.err.println("--- begin modelToView ---"); Rectangle alloc = a.getBounds(); RSyntaxTextArea textArea = (RSyntaxTextArea) getContainer(); alloc.height = textArea.getLineHeight(); // metrics.getHeight(); alloc.width = 1; int p0 = getStartOffset(); int p1 = getEndOffset(); int testP = (b == Position.Bias.Forward) ? pos : Math.max(p0, pos - 1); // Get the token list for this line so we don't have to keep // recomputing it if this logical line spans multiple physical // lines. RSyntaxDocument doc = (RSyntaxDocument) getDocument(); Element map = doc.getDefaultRootElement(); int line = map.getElementIndex(p0); Token tokenList = doc.getTokenListForLine(line); float x0 = alloc.x; // 0; while (p0 < p1) { TokenSubList subList = TokenUtils.getSubTokenList( tokenList, p0, WrappedSyntaxView.this, textArea, x0, lineCountTempToken); x0 = subList != null ? subList.x : x0; tokenList = subList != null ? subList.tokenList : null; int p = calculateBreakPosition(p0, tokenList, x0); if ((pos >= p0) && (testP < p)) { // pos < p)) { // it's in this line alloc = RSyntaxUtilities.getLineWidthUpTo( textArea, s, p0, pos, WrappedSyntaxView.this, alloc, alloc.x); // System.err.println("--- end modelToView ---"); return alloc; } // if (p == p1 && pos == p1) { if (p == p1 - 1 && pos == p1 - 1) { // Wants end. if (pos > p0) { alloc = RSyntaxUtilities.getLineWidthUpTo( textArea, s, p0, pos, WrappedSyntaxView.this, alloc, alloc.x); } // System.err.println("--- end modelToView ---"); return alloc; } p0 = (p == p0) ? p1 : p; // System.err.println("... ... Incrementing y"); alloc.y += alloc.height; } throw new BadLocationException(null, pos); }
@Override public void mouseMoved(MouseEvent me) { Element el = doc.getCharacterElement(viewToModel(me.getPoint())); if (el == null) return; AttributeSet as = el.getAttributes(); if (as.isDefined("ip")) { setCursor(handCursor); } else { setCursor(defaultCursor); } }
public Element getClone() { try { Element element = (Element) this.clone(); element.start = this.start.getLocation(); element.end = this.end.getLocation(); element.parentSubnet = this.parentSubnet; return element; } catch (CloneNotSupportedException ex) { throw new RuntimeException(); } }
public Element getLineAtPoint(MouseEvent me) { Point p = me.getLocationOnScreen(); Point pp = getLocationOnScreen(); p.translate(-pp.x, -pp.y); int pos = viewToModel(p); Element root = getDocument().getDefaultRootElement(); int e = root.getElementIndex(pos); if (e == -1) { return null; } return root.getElement(e); }
public int getLineStartOffset(int line) throws BadLocationException { // line starting from 0 Element map = getDocument().getDefaultRootElement(); if (line < 0) { throw new BadLocationException("Negative line", -1); } else if (line >= map.getElementCount()) { throw new BadLocationException("No such line", getDocument().getLength() + 1); } else { Element lineElem = map.getElement(line); return lineElem.getStartOffset(); } }
private Node generateFieldNode(Document doc, ClassField field) { Element fieldEl = doc.createElement(EL_FIELD); fieldEl.setAttribute(ATR_NAME, field.getName()); fieldEl.setAttribute(ATR_TYPE, field.getType()); if (field.isInput()) fieldEl.setAttribute(ATR_NATURE, "input"); else if (field.isGoal()) fieldEl.setAttribute(ATR_NATURE, "goal"); if (field.getValue() != null) fieldEl.setAttribute(ATR_VALUE, field.getValue()); return fieldEl; }
private void handleDecreaseIndent(int line, Element elem, StyledDocument doc) throws BadLocationException { int start = elem.getStartOffset(); int end = elem.getEndOffset() - 1; doc.getText(start, end - start, segLine); int i = segLine.offset; end = i + segLine.count; if (end > i) { String leadingWS = PythonIndentation.getLeadingWhitespace(doc, start, end - start); int toRemove = indentationLogic.checkDedent(leadingWS, line + 1); doc.remove(start, toRemove); } }
public File reparseBefore() { Element e = this.getDocument().getDefaultRootElement(); if (e.getEndOffset() - e.getStartOffset() == 1) { return null; } File temp = FileManager.createTempFile("reparse"); try { writeFile(temp.getAbsolutePath()); return temp; } catch (IOException ex) { } return null; }
@Override public VPackage parse() { logger.debug("Starting parsing package: " + xmlFile.getAbsolutePath()); long startParsing = System.currentTimeMillis(); try { Document document = getDocument(); Element root = document.getDocumentElement(); _package = new VPackage(xmlFile); Node name = root.getElementsByTagName(EL_NAME).item(0); _package.setName(name.getTextContent()); Node descr = root.getElementsByTagName(EL_DESCRIPTION).item(0); _package.setDescription(descr.getTextContent()); NodeList list = root.getElementsByTagName(EL_CLASS); boolean initPainters = false; for (int i = 0; i < list.getLength(); i++) { PackageClass pc = parseClass((Element) list.item(i)); if (pc.getPainterName() != null) { initPainters = true; } } if (initPainters) { _package.initPainters(); } logger.info( "Parsing the package '{}' finished in {}ms.\n", _package.getName(), (System.currentTimeMillis() - startParsing)); } catch (Exception e) { collector.collectDiagnostic(e.getMessage(), true); if (RuntimeProperties.isLogDebugEnabled()) { e.printStackTrace(); } } try { checkProblems("Error parsing package file " + xmlFile.getName()); } catch (Exception e) { return null; } return _package; }
// // Implement CaretListener interface // @Override public void caretUpdate(CaretEvent e) { // Get the line the caret is positioned on int caretPosition = component.getCaretPosition(); Element root = component.getDocument().getDefaultRootElement(); int currentLine = root.getElementIndex(caretPosition); // Need to repaint so the correct line number can be highlighted if (lastLine != currentLine) { repaint(); lastLine = currentLine; } }
// <editor-fold defaultstate="collapsed" desc="replace text patterns with image buttons"> public boolean reparse() { File temp = null; Element e = this.getDocument().getDefaultRootElement(); if (e.getEndOffset() - e.getStartOffset() == 1) { return true; } if ((temp = reparseBefore()) != null) { if (reparseAfter(temp)) { updateDocumentListeners(); return true; } } return false; }