@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()); }
private void updateTemplateFromEditor(PrintfTemplate template) { ArrayList params = new ArrayList(); String format = null; int text_length = editorPane.getDocument().getLength(); try { format = editorPane.getDocument().getText(0, text_length); } catch (BadLocationException ex1) { } Element section_el = editorPane.getDocument().getDefaultRootElement(); // Get number of paragraphs. int num_para = section_el.getElementCount(); for (int p_count = 0; p_count < num_para; p_count++) { Element para_el = section_el.getElement(p_count); // Enumerate the content elements int num_cont = para_el.getElementCount(); for (int c_count = 0; c_count < num_cont; c_count++) { Element content_el = para_el.getElement(c_count); AttributeSet attr = content_el.getAttributes(); // Get the name of the style applied to this content element; may be null String sn = (String) attr.getAttribute(StyleConstants.NameAttribute); // Check if style name match if (sn != null && sn.startsWith("Parameter")) { // we extract the label. JLabel l = (JLabel) StyleConstants.getComponent(attr); if (l != null) { params.add(l.getName()); } } } } template.setFormat(format); template.setTokens(params); }
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)); }
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; }
public void parseChildren(Element e) { try { NodeList nl = e.getChildNodes(); for (int i = 0; i < nl.getLength(); i++) { // parse Elements only if ((nl.item(i).getNodeType() == Node.ELEMENT_NODE)) { Element elm = (Element) nl.item(i); String tag = elm.getTagName(); if (tag.equals("canvas")) { parseChildren(elm); } else if (tag.equals("label")) { parseLabel(elm); } else if (tag.equals("textfield")) { parseTextField(elm); } else if (tag.equals("button")) { parseButton(elm); } else if (tag.equals("textarea")) { parseTextArea(elm); } else if (tag.equals("progressbar")) { parseProgressBar(elm); } } } } catch (Exception ex) { ex.printStackTrace(); } }
/* * 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; }
@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); } }
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; }
public synchronized V put(K key, V value) { Element<V> element = new Element<V>(); element.date = System.currentTimeMillis(); element.value = value; map.put(key, element); return value; }
/* * 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 ""; }
public Element handleShortAddressVal(Element type, long cv, String name, String comment) { Element r = new Element("int"); r.setAttribute("origin", "" + (4278190080L + cv)); r.addContent(new Element("name").addContent(name)); if (comment != null && !comment.equals("")) r.addContent(new Element("description").addContent(comment)); return r; }
/** Invoked when an action occurs. */ public static BoxItem createNewElement(String className, int posX, int posY) { BoxItem ret = null; Element elem = null; try { if (debug) System.out.println("Creating new element '" + className + "'"); elem = Element.newInstance(className); if (elem == null) { if (debug) System.out.println("Element '" + className + "' not found"); return null; } ret = elem.getDesignerBox(); ret.setBounds( (posX / DesignEventHandler.ELEM_STEP) * DesignEventHandler.ELEM_STEP, (posY / DesignEventHandler.ELEM_STEP) * DesignEventHandler.ELEM_STEP, ConfigurableSystemSettings.getDesignerElementWidth(), ConfigurableSystemSettings.getDesignerElementHeight()); Main.app.designFrame.addElement(ret); Item.highlighted.clear(); Item.highlighted.add(ret); Main.app.processor.add(elem); // elem.setActive(false); Main.app.designFrame.panel.repaint(); if (elem instanceof Display) { Chart chart = ((Display) elem).newChart(); ((Display) elem).setChart(chart); chart.setAtTopLayer(); // System.out.println("c1 " + chart.getBounds()); Main.app.runtimeFrame.addChart(chart); // Main.app.runtimeFrame.show(); Main.app.runtimeFrame.setVisible(); // Main.app.runtimeFrame.repaint(); // Change runtime to edit mode if not now if (!Main.app.runtimeFrame.framedCharts) { Main.app.runtimeFrame.framedCharts = true; try { Main.app.runtimeFrame.reload(); } catch (Exception ex) { ex.printStackTrace(); } } } elem.reinit(); } catch (Exception e) { if (elem != null) elem.disactivate(e); System.out.println("New element error: " + e); // e.printStackTrace(); } catch (Throwable e) { System.out.println("Critical error occurred while creating new element: " + e); e.printStackTrace(); } return ret; }
public synchronized V get(K key) { V value = null; Element<V> element = map.get(key); if (element != null) { element.date = System.currentTimeMillis(); value = element.value; } return value; }
public void appendToEnd(String text) { Element root = document.getDefaultRootElement(); try { document.insertAfterEnd(root.getElement(root.getElementCount() - 1), text); } catch (BadLocationException e) { logger.error("Insert in the HTMLDocument failed.", e); } catch (IOException e) { logger.error("Insert in the HTMLDocument failed.", e); } }
@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 void insertAfterStart(String text) { Element root = this.document.getDefaultRootElement(); try { this.document.insertBeforeStart(root.getElement(0), text); } catch (BadLocationException e) { logger.error("Insert in the HTMLDocument failed.", e); } catch (IOException e) { logger.error("Insert in the HTMLDocument failed.", 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(); } }
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); }
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; }
// // 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; }
public void caretUpdate(CaretEvent e) { // when the cursor moves on _textView // this method will be called. Then, we // must determine what the line number is // and update the line number view Element root = textView.getDocument().getDefaultRootElement(); int line = root.getElementIndex(e.getDot()); root = root.getElement(line); int col = root.getElementIndex(e.getDot()); lineNumberView.setText(line + ":" + col); // if text is selected then enable copy and cut boolean isSelection = e.getDot() != e.getMark(); copyAction.setEnabled(isSelection); cutAction.setEnabled(isSelection); }
public void parseAttributes(Element elm, JComponent comp) { String enabled = elm.getAttribute("enabled"); if (enabled != null) { comp.setEnabled(!enabled.equals("false")); } String id = elm.getAttribute("id"); if (id.length() > 0) { components.put(id, comp); comp.setName(id); } String tooltip = elm.getAttribute("tooltip"); if (tooltip.length() > 0) { comp.setToolTipText(tooltip); } }
private String addWhiteSpace(Document doc, int offset) throws BadLocationException { StringBuilder whiteSpace = new StringBuilder("\n"); Element rootElement = doc.getDefaultRootElement(); int line = rootElement.getElementIndex(offset); int i = rootElement.getElement(line).getStartOffset(); while (true) { String temp = doc.getText(i, 1); if (temp.equals(" ") || temp.equals("\t")) { whiteSpace.append(temp); i++; } else break; } return whiteSpace.toString(); }
void editorPane_keyPressed(KeyEvent e) { StyledDocument doc = editorPane.getStyledDocument(); int pos = editorPane.getCaretPosition(); int code = e.getKeyCode(); Element el; switch (code) { case KeyEvent.VK_BACK_SPACE: case KeyEvent.VK_DELETE: case KeyEvent.VK_LEFT: case KeyEvent.VK_KP_LEFT: if (pos == 0) return; // we want to get the element to the left of position. el = doc.getCharacterElement(pos - 1); break; case KeyEvent.VK_RIGHT: case KeyEvent.VK_KP_RIGHT: // we want to get the element to the right of position. el = doc.getCharacterElement(pos + 1); break; default: return; // bail we don't handle it. } AttributeSet attr = el.getAttributes(); String el_name = (String) attr.getAttribute(StyleConstants.NameAttribute); int el_range = el.getEndOffset() - el.getStartOffset() - 1; if (el_name.startsWith("Parameter") && StyleConstants.getComponent(attr) != null) { try { switch (code) { case KeyEvent.VK_BACK_SPACE: case KeyEvent.VK_DELETE: doc.remove(el.getStartOffset(), el_range); break; case KeyEvent.VK_LEFT: case KeyEvent.VK_KP_LEFT: editorPane.setCaretPosition(pos - el_range); break; case KeyEvent.VK_RIGHT: case KeyEvent.VK_KP_RIGHT: editorPane.setCaretPosition(pos + (el_range)); break; } } catch (BadLocationException ex) { } } }
public void parseButton(Element elm) { JButton btn = new JButton(); String title = elm.getAttribute("title"); if (title != null) { btn.setText(title); } SpazPosition lp = parseSpazPosition(elm); if (lp == null) { return; } this.add(btn, lp); parseBorder(btn, elm); parseAttributes(elm, btn); String action = elm.getAttribute("action"); if (action.length() > 0) { actions.put(btn, action); btn.addActionListener(this); } }
/** Calculate the width needed to display the maximum line number */ private void setPreferredWidth() { Element root = component.getDocument().getDefaultRootElement(); int lines = root.getElementCount(); int digits = Math.max(String.valueOf(lines).length(), minimumDisplayDigits); // Update sizes when number of digits in the line number changes if (lastDigits != digits) { lastDigits = digits; FontMetrics fontMetrics = getFontMetrics(getFont()); int width = fontMetrics.charWidth('0') * digits; Insets insets = getInsets(); int preferredWidth = insets.left + insets.right + width; Dimension d = getPreferredSize(); d.setSize(preferredWidth, HEIGHT); setPreferredSize(d); setSize(d); } }
public void parseBorder(JComponent c, Element elm) { if (elm.getTagName().equals("border")) { String type = elm.getAttribute("type"); if (type.equals("empty")) { c.setBorder(new EmptyBorder(2, 2, 2, 2)); } else if (type.equals("titled")) { String title = elm.getAttribute("title"); c.setBorder(new TitledBorder(title)); } else if (type.equals("beveled")) { int btype = Integer.parseInt(elm.getAttribute("bevel")); c.setBorder(new BevelBorder(btype)); } } else { NodeList nl = elm.getElementsByTagName("border"); for (int n = 0; n < nl.getLength(); n++) { parseBorder(c, (Element) nl.item(n)); } } }
public Element getLineAtCaret(int caretPosition) { Element root = getDocument().getDefaultRootElement(); if (caretPosition == -1) { return root.getElement(root.getElementIndex(getCaretPosition())); } else { return root.getElement(root.getElementIndex(root.getElementIndex(caretPosition))); } }