private ProperTextRange offsetToYPosition(int start, int end) { if (myEditorScrollbarTop == -1 || myEditorTargetHeight == -1) { recalcEditorDimensions(); } Document document = myEditor.getDocument(); int startLineNumber = offsetToLine(start, document); int startY; int lineCount; if (myEditorSourceHeight < myEditorTargetHeight) { lineCount = 0; startY = myEditorScrollbarTop + startLineNumber * myEditor.getLineHeight(); } else { lineCount = myEditorSourceHeight / myEditor.getLineHeight(); startY = myEditorScrollbarTop + (int) ((float) startLineNumber / lineCount * myEditorTargetHeight); } int endY; if (document.getLineNumber(start) == document.getLineNumber(end)) { endY = startY; // both offsets are on the same line, no need to recalc Y position } else { int endLineNumber = offsetToLine(end, document); if (myEditorSourceHeight < myEditorTargetHeight) { endY = myEditorScrollbarTop + endLineNumber * myEditor.getLineHeight(); } else { endY = myEditorScrollbarTop + (int) ((float) endLineNumber / lineCount * myEditorTargetHeight); } if (endY < startY) endY = startY; } return new ProperTextRange(startY, endY); }
/** * Creates an Element(or Node in XML in Document d) for single component * * @param x the component for which Element will be created * @param d Where the element will be added * @return the Element(for XML) created from component x */ private Element createCmpEle(component x, Document d) { Element cmp_el = d.createElement("comp"); cmp_el.setAttribute("id", String.valueOf(x.getId())); Element type_el = d.createElement("comp_type_id"); Text type_txt = d.createTextNode(String.valueOf(x.getType().getId())); type_el.appendChild(type_txt); cmp_el.appendChild(type_el); Element pkg_el = d.createElement("pkg_name"); Text pkg_txt = d.createTextNode(x.getType().getType_pkg_name()); pkg_el.appendChild(pkg_txt); cmp_el.appendChild(pkg_el); Element pos_el = d.createElement("position"); Element x_el = d.createElement("x"); Text x_txt = d.createTextNode(String.valueOf(x.getPosition().x)); x_el.appendChild(x_txt); pos_el.appendChild(x_el); Element y_el = d.createElement("y"); Text y_txt = d.createTextNode(String.valueOf(x.getPosition().y)); y_el.appendChild(y_txt); pos_el.appendChild(y_el); cmp_el.appendChild(pos_el); return cmp_el; }
public Element getFileRoot(String filename) { // find file & load file Element root = null; boolean verify = false; try { SAXBuilder builder = new SAXBuilder("org.apache.xerces.parsers.SAXParser", verify); builder.setFeature("http://apache.org/xml/features/xinclude", true); builder.setFeature("http://apache.org/xml/features/xinclude/fixup-base-uris", false); builder.setFeature("http://apache.org/xml/features/allow-java-encodings", true); builder.setFeature("http://apache.org/xml/features/validation/schema", verify); builder.setFeature("http://apache.org/xml/features/validation/schema-full-checking", verify); builder.setFeature("http://xml.org/sax/features/namespaces", true); Document doc = builder.build(new BufferedInputStream(new FileInputStream(new File(filename)))); root = doc.getRootElement(); } catch (Exception e) { System.out.println("While reading file: " + e); } return root; }
/** * Replaces the currently selected content with new content represented by the given StyledText. * If there is no selection this amounts to an insert of the given text. If there is no * replacement text this amounts to a removal of the current selection. The replacement text will * have the attributes currently defined for input at the point of insertion. If the document is * not editable, beep and return * * @param content the content to replace the selection with * @see StyledText#insert */ public static void replaceSelection(Word word, StyledText content) { Document doc = word.workspace.getDocument(); String text; Caret caret = word.workspace.getCaret(); int insertPos = 0; int i; int contentSize; if (doc != null) { try { int p0 = Math.min(caret.getDot(), caret.getMark()); int p1 = Math.max(caret.getDot(), caret.getMark()); // if there is any selection if (p0 != p1) { doc.remove(p0, p1 - p0); } // insert the content if (content != null) { content.insert(doc, p0); } } catch (BadLocationException ble) { javax.swing.UIManager.getLookAndFeel().provideErrorFeedback(word.workspace); return; } } }
private void initGuardedBlocks(Place shreds) { int origOffset = -1; int curOffset = 0; for (PsiLanguageInjectionHost.Shred shred : shreds) { Segment hostRangeMarker = shred.getHostRangeMarker(); int start = shred.getRange().getStartOffset() + shred.getPrefix().length(); int end = shred.getRange().getEndOffset() - shred.getSuffix().length(); if (curOffset < start) { RangeMarker guard = myNewDocument.createGuardedBlock(curOffset, start); if (curOffset == 0 && shred == shreds.get(0)) guard.setGreedyToLeft(true); String padding = origOffset < 0 ? "" : myOrigDocument.getText().substring(origOffset, hostRangeMarker.getStartOffset()); guard.putUserData(REPLACEMENT_KEY, fixQuotes(padding)); } curOffset = end; origOffset = hostRangeMarker.getEndOffset(); } if (curOffset < myNewDocument.getTextLength()) { RangeMarker guard = myNewDocument.createGuardedBlock(curOffset, myNewDocument.getTextLength()); guard.setGreedyToRight(true); guard.putUserData(REPLACEMENT_KEY, ""); } }
public void initMarkers(Place shreds) { SmartPointerManager smartPointerManager = SmartPointerManager.getInstance(myProject); int curOffset = -1; for (PsiLanguageInjectionHost.Shred shred : shreds) { final RangeMarker rangeMarker = myNewDocument.createRangeMarker( shred.getRange().getStartOffset() + shred.getPrefix().length(), shred.getRange().getEndOffset() - shred.getSuffix().length()); final TextRange rangeInsideHost = shred.getRangeInsideHost(); PsiLanguageInjectionHost host = shred.getHost(); RangeMarker origMarker = myOrigDocument.createRangeMarker( rangeInsideHost.shiftRight(host.getTextRange().getStartOffset())); SmartPsiElementPointer<PsiLanguageInjectionHost> elementPointer = smartPointerManager.createSmartPsiElementPointer(host); Trinity<RangeMarker, RangeMarker, SmartPsiElementPointer> markers = Trinity.<RangeMarker, RangeMarker, SmartPsiElementPointer>create( origMarker, rangeMarker, elementPointer); myMarkers.add(markers); origMarker.setGreedyToRight(true); rangeMarker.setGreedyToRight(true); if (origMarker.getStartOffset() > curOffset) { origMarker.setGreedyToLeft(true); rangeMarker.setGreedyToLeft(true); } curOffset = origMarker.getEndOffset(); } initGuardedBlocks(shreds); }
private boolean replaceWithImage(int startOff, int endOff, Pattern ptn) throws BadLocationException { Document doc = getDocument(); String imgStr = doc.getText(startOff, endOff - startOff); JComponent comp = null; if (ptn == patPatternStr || ptn == patPngStr) { if (pref.getPrefMoreImageThumbs()) { comp = EditorPatternButton.createFromString(this, imgStr, null); } else { comp = EditorPatternLabel.labelFromString(this, imgStr); } } else if (ptn == patRegionStr) { if (pref.getPrefMoreImageThumbs()) { comp = EditorRegionButton.createFromString(this, imgStr); } else { comp = EditorRegionLabel.labelFromString(this, imgStr); } } else if (ptn == patCaptureBtn) { comp = EditorPatternLabel.labelFromString(this, ""); } if (comp != null) { this.select(startOff, endOff); this.insertComponent(comp); return true; } return false; }
/** * Determines the preferred span for this view along an axis. * * @param axis may be either View.X_AXIS or View.Y_AXIS * @return the span the view would like to be rendered into >= 0. Typically the view is told to * render into the span that is returned, although there is no guarantee. The parent may * choose to resize or break the view. */ public float getPreferredSpan(int axis) { switch (axis) { case View.X_AXIS: Segment buff = SegmentCache.getSharedSegment(); Document doc = getDocument(); int width; try { FontMetrics fm = getFontMetrics(); doc.getText(0, doc.getLength(), buff); width = Utilities.getTabbedTextWidth(buff, fm, 0, this, 0); if (buff.count > 0) { Component c = getContainer(); firstLineOffset = sun.swing.SwingUtilities2.getLeftSideBearing( (c instanceof JComponent) ? (JComponent) c : null, fm, buff.array[buff.offset]); firstLineOffset = Math.max(0, -firstLineOffset); } else { firstLineOffset = 0; } } catch (BadLocationException bl) { width = 0; } SegmentCache.releaseSharedSegment(buff); return width + firstLineOffset; default: return super.getPreferredSpan(axis); } }
public void execute() { if (!isEditable() || !isEnabled()) { return; } try { int position = lastClickPoint != null ? viewToModel(lastClickPoint) : getCaretPosition(); lastClickPoint = null; Document document = getDocument(); String selectedText = getSelectedText(); if (selectedText != null && !CommonUtil.isEmpty(selectedText)) { final int selectionEnd = getSelectionEnd(); document.insertString(selectionEnd, selectedText, null); select(selectionEnd, selectionEnd + selectedText.length()); } else { final int docLen = document.getLength(); int fromIndex = Math.max(0, getText(0, position).lastIndexOf('\n')); int toIndex = getText(fromIndex + 1, docLen - fromIndex).indexOf('\n'); toIndex = toIndex < 0 ? docLen : fromIndex + toIndex; String textToDuplicate = getText(fromIndex, toIndex - fromIndex + 1); if (!textToDuplicate.startsWith("\n")) { textToDuplicate = "\n" + textToDuplicate; } if (textToDuplicate.endsWith("\n")) { textToDuplicate = textToDuplicate.substring(0, textToDuplicate.length() - 1); } document.insertString(Math.min(docLen, toIndex + 1), textToDuplicate, null); setCaretPosition(position + textToDuplicate.length()); } } catch (BadLocationException e1) { e1.printStackTrace(); } }
@Override public void actionPerformed(ActionEvent e) { Frame frame = getFrame(); JFileChooser chooser = new JFileChooser(); int ret = chooser.showOpenDialog(frame); if (ret != JFileChooser.APPROVE_OPTION) { return; } File f = chooser.getSelectedFile(); if (f.isFile() && f.canRead()) { Document oldDoc = getEditor().getDocument(); if (oldDoc != null) { oldDoc.removeUndoableEditListener(undoHandler); } if (elementTreePanel != null) { elementTreePanel.setEditor(null); } getEditor().setDocument(new PlainDocument()); frame.setTitle(f.getName()); Thread loader = new FileLoader(f, editor.getDocument()); loader.start(); } else { JOptionPane.showMessageDialog( getFrame(), "Could not open file: " + f, "Error opening file", JOptionPane.ERROR_MESSAGE); } }
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)); }
/** * Updates the AttributedCharacterIterator by invoking <code>formatToCharacterIterator</code> on * the <code>Format</code>. If this is successful, <code>updateMask(AttributedCharacterIterator) * </code> is then invoked to update the internal bitmask. */ void updateMask() { if (getFormat() != null) { Document doc = getFormattedTextField().getDocument(); validMask = false; if (doc != null) { try { string = doc.getText(0, doc.getLength()); } catch (BadLocationException ble) { string = null; } if (string != null) { try { Object value = stringToValue(string); AttributedCharacterIterator iterator = getFormat().formatToCharacterIterator(value); updateMask(iterator); } catch (ParseException pe) { } catch (IllegalArgumentException iae) { } catch (NullPointerException npe) { } } } } }
private void altCommitToOriginal(@NotNull DocumentEvent e) { final PsiFile origPsiFile = PsiDocumentManager.getInstance(myProject).getPsiFile(myOrigDocument); String newText = myNewDocument.getText(); // prepare guarded blocks LinkedHashMap<String, String> replacementMap = new LinkedHashMap<String, String>(); int count = 0; for (RangeMarker o : ContainerUtil.reverse(((DocumentEx) myNewDocument).getGuardedBlocks())) { String replacement = o.getUserData(REPLACEMENT_KEY); String tempText = "REPLACE" + (count++) + Long.toHexString(StringHash.calc(replacement)); newText = newText.substring(0, o.getStartOffset()) + tempText + newText.substring(o.getEndOffset()); replacementMap.put(tempText, replacement); } // run preformat processors final int hostStartOffset = myAltFullRange.getStartOffset(); myEditor.getCaretModel().moveToOffset(hostStartOffset); for (CopyPastePreProcessor preProcessor : Extensions.getExtensions(CopyPastePreProcessor.EP_NAME)) { newText = preProcessor.preprocessOnPaste(myProject, origPsiFile, myEditor, newText, null); } myOrigDocument.replaceString(hostStartOffset, myAltFullRange.getEndOffset(), newText); // replace temp strings for guarded blocks for (String tempText : replacementMap.keySet()) { int idx = CharArrayUtil.indexOf( myOrigDocument.getCharsSequence(), tempText, hostStartOffset, myAltFullRange.getEndOffset()); myOrigDocument.replaceString(idx, idx + tempText.length(), replacementMap.get(tempText)); } // JAVA: fix occasional char literal concatenation fixDocumentQuotes(myOrigDocument, hostStartOffset - 1); fixDocumentQuotes(myOrigDocument, myAltFullRange.getEndOffset()); // reformat PsiDocumentManager.getInstance(myProject).commitDocument(myOrigDocument); Runnable task = () -> { try { CodeStyleManager.getInstance(myProject) .reformatRange(origPsiFile, hostStartOffset, myAltFullRange.getEndOffset(), true); } catch (IncorrectOperationException e1) { // LOG.error(e); } }; DocumentUtil.executeInBulk(myOrigDocument, true, task); PsiElement newInjected = InjectedLanguageManager.getInstance(myProject) .findInjectedElementAt(origPsiFile, hostStartOffset); DocumentWindow documentWindow = newInjected == null ? null : InjectedLanguageUtil.getDocumentWindow(newInjected); if (documentWindow != null) { myEditor.getCaretModel().moveToOffset(documentWindow.injectedToHost(e.getOffset())); myEditor.getScrollingModel().scrollToCaret(ScrollType.MAKE_VISIBLE); } }
private void updateDocumentFromPropertyValue( final String value, final Document document, final PropertiesFile propertiesFile) { @NonNls String text = value; if (myBackSlashPressed.contains(propertiesFile)) { text += "\\"; } document.replaceString(0, document.getTextLength(), text); }
private void addText(String str, String styleName, JTextPane pane) { Document doc = pane.getDocument(); int len = doc.getLength(); try { doc.insertString(len, str, pane.getStyle(styleName)); } catch (javax.swing.text.BadLocationException e) { } }
private void insertString(int pos, String str) { Document doc = getDocument(); try { doc.insertString(pos, str, null); } catch (Exception e) { Debug.error(me + "insertString: Problem while trying to insert at pos\n%s", e.getMessage()); } }
// </editor-fold> // <editor-fold defaultstate="collapsed" desc="fill pane content"> @Override public void read(Reader in, Object desc) throws IOException { super.read(in, desc); Document doc = getDocument(); Element root = doc.getDefaultRootElement(); parse(root); setCaretPosition(0); }
private void paintCaret(Graphics2D g_) { EditorImpl.CaretRectangle[] locations = myEditor.getCaretLocations(true); if (locations == null) return; Graphics2D g = IdeBackgroundUtil.getOriginalGraphics(g_); int lineHeight = myView.getLineHeight(); EditorSettings settings = myEditor.getSettings(); Color caretColor = myEditor.getColorsScheme().getColor(EditorColors.CARET_COLOR); if (caretColor == null) caretColor = new JBColor(CARET_DARK, CARET_LIGHT); g.setColor(caretColor); for (EditorImpl.CaretRectangle location : locations) { int x = location.myPoint.x; int y = location.myPoint.y; Caret caret = location.myCaret; boolean isRtl = location.myIsRtl; if (myEditor.isInsertMode() != settings.isBlockCursor()) { int lineWidth = JBUI.scale(settings.getLineCursorWidth()); g.fillRect(x, y, lineWidth, lineHeight); if (myDocument.getTextLength() > 0 && caret != null && !myView.getLineLayout(caret.getLogicalPosition().line).isLtr()) { g.fillPolygon( new int[] { isRtl ? x + lineWidth : x, isRtl ? x + lineWidth - CARET_DIRECTION_MARK_SIZE : x + CARET_DIRECTION_MARK_SIZE, isRtl ? x + lineWidth : x }, new int[] {y, y, y + CARET_DIRECTION_MARK_SIZE}, 3); } } else { int width = location.myWidth; int startX = Math.max(0, isRtl ? x - width : x); g.fillRect(startX, y, width, lineHeight - 1); if (myDocument.getTextLength() > 0 && caret != null) { int targetVisualColumn = caret.getVisualPosition().column; for (VisualLineFragmentsIterator.Fragment fragment : VisualLineFragmentsIterator.create(myView, caret.getVisualLineStart(), false)) { int startVisualColumn = fragment.getStartVisualColumn(); int endVisualColumn = fragment.getEndVisualColumn(); if (startVisualColumn < targetVisualColumn && endVisualColumn > targetVisualColumn || startVisualColumn == targetVisualColumn && !isRtl || endVisualColumn == targetVisualColumn && isRtl) { g.setColor(ColorUtil.isDark(caretColor) ? CARET_LIGHT : CARET_DARK); fragment.draw( g, startX, y + myView.getAscent(), targetVisualColumn - startVisualColumn - (isRtl ? 1 : 0), targetVisualColumn - startVisualColumn + (isRtl ? 0 : 1)); break; } } } } } }
private void addListenerToAllHyperlinkItems(EventListener listener) { final Document doc = myEngine.getDocument(); if (doc != null) { final NodeList nodeList = doc.getElementsByTagName("a"); for (int i = 0; i < nodeList.getLength(); i++) { ((EventTarget) nodeList.item(i)).addEventListener(EVENT_TYPE_CLICK, listener, false); } } }
void removeText() { if ((p0 != null) && (p1 != null) && (p0.getOffset() != p1.getOffset())) { try { Document doc = c.getDocument(); doc.remove(p0.getOffset(), p1.getOffset() - p0.getOffset()); } catch (BadLocationException e) { } } }
TextTransferable(JTextComponent c, int start, int end) { this.c = c; Document doc = c.getDocument(); try { p0 = doc.createPosition(start); p1 = doc.createPosition(end); plainData = c.getSelectedText(); } catch (BadLocationException ble) { } }
public void insertUpdate(DocumentEvent e) { Document doc = e.getDocument(); try { prop.set(doc.getText(0, doc.getLength())); } catch (BadLocationException b) { // Once again, no idea what this is supposed to be. // I don't think I like this interface much :-(. System.out.println(b); } }
// TODO not used public void appendString(String str) { Document doc = getDocument(); try { int start = doc.getLength(); doc.insertString(doc.getLength(), str, null); int end = doc.getLength(); // end = parseLine(start, end, patHistoryBtnStr); } catch (Exception e) { Debug.error(me + "appendString: Problem while trying to append\n%s", e.getMessage()); } }
public void actionPerformed(ActionEvent e) { Document oldDoc = getEditor().getDocument(); if (oldDoc != null) { oldDoc.removeUndoableEditListener(undoHandler); } getEditor().setDocument(new PlainDocument()); getEditor().getDocument().addUndoableEditListener(undoHandler); resetUndoManager(); getFrame().setTitle(resources.getString("Title")); revalidate(); }
private void updateBoard(DocumentEvent e) throws BadLocationException { Document doc = e.getDocument(); int index = (int) doc.getProperty("index"); String valueString = doc.getText(0, doc.getLength()); if (doc.getLength() == 0) valueString = "0"; int value = Integer.parseInt(valueString); gameBoard.changeCellAt(index, value); // gameBoard.out(); if (gameBoard.checkGameOver()) { JOptionPane.showMessageDialog(frame, "NUMBRIX COMPLETED!!!"); } }
private void setStructureViewSelectionFromPropertiesFile(@NotNull Editor propertiesFileEditor) { int line = propertiesFileEditor.getCaretModel().getLogicalPosition().line; Document document = propertiesFileEditor.getDocument(); if (line >= document.getLineCount()) { return; } final String propertyName = getPropertyName(document, line); if (propertyName == null) { return; } setStructureViewSelection(propertyName); }
@Override @SuppressWarnings("SleepWhileHoldingLock") public void run() { try { // initialize the statusbar status.removeAll(); JProgressBar progress = new JProgressBar(); progress.setMinimum(0); progress.setMaximum(doc.getLength()); status.add(progress); status.revalidate(); // start writing Writer out = new FileWriter(f); Segment text = new Segment(); text.setPartialReturn(true); int charsLeft = doc.getLength(); int offset = 0; while (charsLeft > 0) { doc.getText(offset, Math.min(4096, charsLeft), text); out.write(text.array, text.offset, text.count); charsLeft -= text.count; offset += text.count; progress.setValue(offset); try { Thread.sleep(10); } catch (InterruptedException e) { Logger.getLogger(FileSaver.class.getName()).log(Level.SEVERE, null, e); } } out.flush(); out.close(); } catch (IOException e) { final String msg = e.getMessage(); SwingUtilities.invokeLater( new Runnable() { public void run() { JOptionPane.showMessageDialog( getFrame(), "Could not save file: " + msg, "Error saving file", JOptionPane.ERROR_MESSAGE); } }); } catch (BadLocationException e) { System.err.println(e.getMessage()); } // we are done... get rid of progressbar status.removeAll(); status.revalidate(); }
/** * This function inserts or replaces the user's input in a string buffer, to create the text * which would be on screen if we allowed it. We declare to throw bad location due to * doc.getText, but since the paramters are coming from the farmework, that should never * happen.... in theory. If insert is true we insert, if false we replace. Length parameter only * used when replacing. */ private StringBuffer getTextPrototype( boolean insert, FilterBypass fb, int offs, String str, int length) throws BadLocationException { Document doc = fb.getDocument(); String text = doc.getText(0, doc.getLength()); StringBuffer sb = new StringBuffer(text); if (insert) { sb.insert(offs, str); } else { sb.replace(offs, offs + length, str); } return sb; } // end of getTextPrototype
/** Resets the value of the JFormattedTextField to be <code>value</code>. */ void resetValue(Object value) throws BadLocationException, ParseException { Document doc = getFormattedTextField().getDocument(); String string = valueToString(value); try { ignoreDocumentMutate = true; doc.remove(0, doc.getLength()); doc.insertString(0, string, null); } finally { ignoreDocumentMutate = false; } updateValue(value); }
@Nullable private static String getPropertyName(@NotNull Document document, int line) { int startOffset = document.getLineStartOffset(line); int endOffset = StringUtil.indexOf( document.getCharsSequence(), '=', startOffset, document.getLineEndOffset(line)); if (endOffset <= startOffset) { return null; } String propertyName = document.getCharsSequence().subSequence(startOffset, endOffset).toString().trim(); return propertyName.isEmpty() ? null : propertyName; }