/** * Checks if caret position is inside attributes quotes * * @param doc edited document * @param caretOffset current caret location offset * @return true if caret inside attribute */ static boolean insideAttribute(StyledDocument doc, int caretOffset) { boolean insideQuotes = false; while (caretOffset > 0) { try { String chars = doc.getText(caretOffset - 1, 1); if (chars.equals("<") || chars.equals("\"") && insideQuotes) { return false; } else if (chars.equals("\"") && (doc.getText(caretOffset - 2, 1).equals("="))) { return true; } else if (chars.equals("\"")) { insideQuotes = true; } caretOffset--; } catch (BadLocationException ex) { Exceptions.printStackTrace(ex); } } return false; }
private void attachDetach(ToDo t) { if (t.lineStart != null) { if (LOG.isLoggable(Level.FINE)) { LOG.fine("addAnnotation: pos=" + t.lineStart.getOffset() + ", a="+ t.a + ", doc=" + System.identityHashCode(doc) + "\n"); } t.a.attachAnnotation((StyledDocument) doc, t.lineStart); } else { if (doc != null) { if (LOG.isLoggable(Level.FINE)) { LOG.fine("removeAnnotation: a=" + t.a + ", doc=" + System.identityHashCode(doc) + "\n"); } t.a.detachAnnotation((StyledDocument) doc); } } }
static int[] computeLineSpan(Document doc, int lineNumber) throws BadLocationException { lineNumber = Math.min(lineNumber, NbDocument.findLineRootElement((StyledDocument) doc).getElementCount()); int lineStartOffset = NbDocument.findLineOffset((StyledDocument) doc, Math.max(0, lineNumber - 1)); int lineEndOffset; if (doc instanceof BaseDocument) { lineEndOffset = Utilities.getRowEnd((BaseDocument) doc, lineStartOffset); } else { //XXX: performance: String lineText = doc.getText(lineStartOffset, doc.getLength() - lineStartOffset); lineText = lineText.indexOf('\n') != (-1) ? lineText.substring(0, lineText.indexOf('\n')) : lineText; lineEndOffset = lineStartOffset + lineText.length(); } int[] span = new int[] {lineStartOffset, lineEndOffset}; computeLineSpan(doc, span); return span; }
private void generate(final Document doc, final Descriptor desc, final JTextComponent jtc) throws BadLocationException { final Indent ie = Indent.get(doc); try { ie.lock(); NbDocument.runAtomicAsUser((StyledDocument) doc, new Runnable() { public void run() { try { int caretPos = jtc.getCaretPosition(); generateJavadoc(doc, desc, ie); // move caret jtc.setCaretPosition(caretPos); } catch (BadLocationException ex) { Exceptions.printStackTrace(ex); } } }); } finally { ie.unlock(); } }
@Override public void defaultAction(final JTextComponent component) { Completion.get().hideCompletion(); Completion.get().hideDocumentation(); NbDocument.runAtomic((StyledDocument) component.getDocument(), new Runnable() { @Override public void run() { Document doc = component.getDocument(); try { doc.remove(substituteOffset, component.getCaretPosition() - substituteOffset); doc.insertString(substituteOffset, getText(), null); } catch (BadLocationException e) { Logger.getLogger(FXMLCompletionItem.class.getName()).log(Level.FINE, null, e); } } }); }
public void testCallingFromAWTIsOk() throws Exception { StyledDocument doc = support.openDocument(); doc.insertString(0, "Ble", null); assertTrue("Modified", support.isModified()); class AWT implements Runnable { boolean success; public synchronized void run() { success = support.canClose(); } } AWT b = new AWT(); javax.swing.SwingUtilities.invokeAndWait(b); assertTrue("Ok, we managed to ask the question", b.success); if (ErrManager.messages.length() > 0) { fail("No messages should be reported: " + ErrManager.messages); } }
/** Marks or unmarks the section as guarded. * @param doc The styled document where this section placed in. * @param bounds The rangeof text which should be marked or unmarked. * @param mark true means mark, false unmark. */ void markGuarded(StyledDocument doc, PositionBounds bounds, boolean mark) { int begin = bounds.getBegin().getOffset(); int end = bounds.getEnd().getOffset(); if (end == doc.getLength() + 1) { end--; } GuardedRegionMarker marker = LineDocumentUtils.as(doc, GuardedRegionMarker.class); if (marker != null) { if (mark) { marker.protectRegion(begin, end - begin + 1); } else { marker.unprotectRegion(begin, end - begin + 1); } } }
private static void refreshDocument(final FileObject fo) throws IOException { RP.post(new Runnable() { @Override public void run() { try { DataObject dobj = DataObject.find(fo); EditorCookie editorCookie = dobj.getLookup().lookup(EditorCookie.class); StyledDocument document = editorCookie.openDocument(); forceReparse(document); } catch (IOException ex) { Exceptions.printStackTrace(ex); } } }); }
private static Position getPosition(final StyledDocument doc, final int offset) { class Impl implements Runnable { private Position pos; public void run() { if (offset < 0 || offset >= doc.getLength()) return ; try { pos = doc.createPosition(offset - NbDocument.findLineColumn(doc, offset)); } catch (BadLocationException ex) { //should not happen? Logger.getLogger(ComputeAnnotations.class.getName()).log(Level.FINE, null, ex); } } } Impl i = new Impl(); doc.render(i); return i.pos; }
@Override public void defaultAction(final JTextComponent component) { Completion.get().hideCompletion(); Completion.get().hideDocumentation(); NbDocument.runAtomic((StyledDocument) component.getDocument(), new Runnable() { @Override public void run() { Document doc = component.getDocument(); try { doc.remove(0, doc.getLength()); doc.insertString(0, getText(), null); } catch (BadLocationException e) { Logger.getLogger(SearchCompletionItem.class.getName()).log(Level.FINE, null, e); } } }); }
@Override protected void loadFromStreamToKit(StyledDocument doc, InputStream stream, EditorKit kit) throws IOException, BadLocationException { if (guardedEditor == null) { guardedEditor = new FormGEditor(); GuardedSectionsFactory gFactory = GuardedSectionsFactory.find("text/x-java"); if (gFactory != null) { guardedProvider = gFactory.create(guardedEditor); } } if (guardedProvider != null) { guardedEditor.doc = doc; Charset c = FileEncodingQuery.getEncoding(this.getDataObject().getPrimaryFile()); Reader reader = guardedProvider.createGuardedReader(stream, c); try { kit.read(reader, doc, 0); } finally { reader.close(); } } else { super.loadFromStreamToKit(doc, stream, kit); } }
/** Write a horizontal separator into the log window. */ public void logDivider() { if (log == null) return; clearError(); StyledDocument doc = log.getStyledDocument(); Style dividerStyle = doc.addStyle("bar", styleRegular); JPanel jpanel = new JPanel(); jpanel.setBackground(Color.LIGHT_GRAY); jpanel.setPreferredSize(new Dimension(300, 1)); // 300 is arbitrary, // since it will // auto-stretch StyleConstants.setComponent(dividerStyle, jpanel); reallyLog(".", dividerStyle); // Any character would do; "." will be // replaced by the JPanel reallyLog("\n\n", styleRegular); log.setCaretPosition(doc.getLength()); lastSize = doc.getLength(); }
@Override public void insertString(StyledDocument sd, Style style) throws BadLocationException { if(style == null) { style = authorStyle; } sd.insertString(sd.getLength(), author, style); String iconStyleName = AUTHOR_ICON_STYLE + author; Style iconStyle = sd.getStyle(iconStyleName); if(iconStyle == null) { iconStyle = sd.addStyle(iconStyleName, null); StyleConstants.setIcon(iconStyle, kenaiUser.getIcon()); } sd.insertString(sd.getLength(), " ", style); sd.insertString(sd.getLength(), " ", iconStyle); }
/** * Checks if caret is inside tag and returns tags name * * @param doc edited document * @param caretOffset current caret location offset * @return String tag name or empty if not inside tag * @throws BadLocationException */ static String getCurrentTagName(StyledDocument doc, int caretOffset) throws BadLocationException { int lastWhiteSpace = caretOffset; while (caretOffset > 0) { String chars = doc.getText(caretOffset - 1, 1); if (chars.equals(">")) { break; } else if (chars.equals(" ")) { lastWhiteSpace = caretOffset; } else if (chars.equals("<")) { return doc.getText(caretOffset, lastWhiteSpace - caretOffset); } caretOffset--; } return ""; }
public void testNationalCharactersSaved() throws Exception { DataObject d = DataObject.find(testFileObject); encodingName = "ISO-8859-2"; // NOI18N EditorCookie o = d.getLookup().lookup(EditorCookie.class); StyledDocument doc = o.openDocument(); doc.insertString(0, CZECH_STRING_UTF, null); o.saveDocument(); // try to open the file InputStream istm = testFileObject.getInputStream(); try { BufferedReader r = new BufferedReader(new InputStreamReader(istm, "ISO-8859-2")); // NOI18N String line = r.readLine(); assertEquals("Text differs", CZECH_STRING_UTF, line); // NOI18N } finally { istm.close(); } }
/** Removes any messages writtin in "red" style. */ public void clearError() { if (log == null) return; // Since this class always removes "red" messages prior to writing // anything, // that means if there are any red messages, they will always be at the // end of the JTextPane. StyledDocument doc = log.getStyledDocument(); int n = doc.getLength(); if (n > lastSize) { try { doc.remove(lastSize, n - lastSize); } catch (BadLocationException e) {} } if (batch.size() > 0) { for (String msg : batch) { reallyLog(msg, styleRegular); } batch.clear(); } }
protected final Document doRecreate(StyledDocument document, Document oldValue, Document newDom) throws IOException { assert !inIsolatingChange; logger.log(Level.FINER, "DomSupport doRecreate: {0}", ph); // ignoring oldValue, returning same newDom ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { XMLUtil.write(newDom, baos, "UTF-8"); } catch (IOException ioe) { assert false : ioe; throw ioe; } try { document.remove(0, document.getLength()); } catch (BadLocationException e) { assert false : e; } try { document.insertString(0, baos.toString("UTF-8"), null); } catch (UnsupportedEncodingException e) { assert false : e; throw e; } catch (BadLocationException e) { assert false : e; } return newDom; }
public void testLineSeparator() throws Exception { File file = File.createTempFile("lineSeparator", ".txt", getWorkDir()); file.deleteOnExit(); FileObject fileObject = FileUtil.toFileObject(file); fileObject.setAttribute(FileObject.DEFAULT_LINE_SEPARATOR_ATTR, "\r"); DataObject dataObject = DataObject.find(fileObject); EditorCookie editor = dataObject.getLookup().lookup(org.openide.cookies.EditorCookie.class); final StyledDocument doc = editor.openDocument(); SwingUtilities.invokeAndWait(new Runnable() { @Override public void run() { try { doc.insertString(doc.getLength(), ".\n", null); } catch (BadLocationException ex) { Exceptions.printStackTrace(ex); } } }); editor.saveDocument(); InputStream inputStream = fileObject.getInputStream(); assertEquals('.',inputStream.read()); assertEquals('\r',inputStream.read()); inputStream.close(); }
/** Add the line offset into the jump history */ private void addPositionToJumpList(String url, Line l, int column) { DataObject dataObject = getDataObject (url); if (dataObject != null) { EditorCookie ec = dataObject.getLookup().lookup(EditorCookie.class); if (ec != null) { try { StyledDocument doc = ec.openDocument(); JEditorPane[] eps = ec.getOpenedPanes(); if (eps != null && eps.length > 0) { JumpList.addEntry(eps[0], NbDocument.findLineOffset(doc, l.getLineNumber()) + column); } } catch (java.io.IOException ioex) { ErrorManager.getDefault().notify(ioex); } } } }
/** return the offset of the first non-whitespace character on the line, or -1 when the line does not exist */ private static int findLineOffset(StyledDocument doc, int lineNumber) { int offset; try { offset = NbDocument.findLineOffset (doc, lineNumber - 1); int offset2 = NbDocument.findLineOffset (doc, lineNumber); try { String lineStr = doc.getText(offset, offset2 - offset); for (int i = 0; i < lineStr.length(); i++) { if (!Character.isWhitespace(lineStr.charAt(i))) { offset += i; break; } } } catch (BadLocationException ex) { // ignore } } catch (IndexOutOfBoundsException ioobex) { return -1; } return offset; }
/** Set the font name. */ public void setFontName(String fontName) { if (log==null) return; this.fontName = fontName; log.setFont(new Font(fontName, Font.PLAIN, fontSize)); StyleConstants.setFontFamily(styleRegular, fontName); StyleConstants.setFontFamily(styleBold, fontName); StyleConstants.setFontFamily(styleRed, fontName); StyleConstants.setFontSize(styleRegular, fontSize); StyleConstants.setFontSize(styleBold, fontSize); StyleConstants.setFontSize(styleRed, fontSize); // Changes all existing text StyledDocument doc=log.getStyledDocument(); Style temp=doc.addStyle("temp", null); StyleConstants.setFontFamily(temp, fontName); StyleConstants.setFontSize(temp, fontSize); doc.setCharacterAttributes(0, doc.getLength(), temp, false); // Changes all existing hyperlinks Font newFont = new Font(fontName, Font.BOLD, fontSize); for(JLabel link: links) { link.setFont(newFont); } }
/** * Checks whether the given section of text overlaps with any of the * guarded sections in the editor. * * @param startPos beginning position if the section to check * @param endPos ending position of the section to check * @return <code>true</code> if the section of text overlaps, * <code>false</code> otherwise */ private synchronized boolean isInGuardedSection(final Position startPos, final Position endPos) { EditorCookie editor = sourceDataObject.getCookie(EditorCookie.class); StyledDocument doc = null; GuardedSectionManager guards = null; if (editor != null) { try { doc = editor.openDocument(); } catch (IOException ex) { Logger.getLogger("global").log(Level.SEVERE, ex.getLocalizedMessage(), ex); return false; } } if (doc != null) { guards = GuardedSectionManager.getInstance(doc); } if (guards != null) { for (Iterator it = guards.getGuardedSections().iterator(); it.hasNext();) { GuardedSection gsection = (GuardedSection) it.next(); if (gsection.contains(startPos, true) || gsection.contains(endPos, true)) { return true; } } } return false; }
public void testFileEncodingQuery () throws Exception { DES des = support(); FileEncodingQueryImpl.getDefault().reset(); StyledDocument doc = des.openDocument(); FileEncodingQueryImpl.getDefault().assertFile( des.getDataObject().getPrimaryFile() ); FileEncodingQueryImpl.getDefault().reset(); doc.insertString(doc.getLength(), " Added text.", null); des.saveDocument(); FileEncodingQueryImpl.getDefault().assertFile( des.getDataObject().getPrimaryFile() ); assertEquals(" Added text.", content); }
protected boolean writeResult(DataObject DO) { String result = ""; try { EditorCookie ec=(EditorCookie)(DO.getCookie(EditorCookie.class)); StyledDocument doc=ec.openDocument(); result=doc.getText(0, doc.getLength()); result=Common.unify(result); } catch (Exception e){ e.printStackTrace(getLog()); return false; } getRef().print(result); return true; }
/** Write a horizontal separator into the log window. */ public void logDivider() { if (log==null) return; clearError(); StyledDocument doc = log.getStyledDocument(); Style dividerStyle = doc.addStyle("bar", styleRegular); JPanel jpanel = new JPanel(); jpanel.setBackground(Color.LIGHT_GRAY); jpanel.setPreferredSize(new Dimension(300,1)); // 300 is arbitrary, since it will auto-stretch StyleConstants.setComponent(dividerStyle, jpanel); reallyLog(".", dividerStyle); // Any character would do; "." will be replaced by the JPanel reallyLog("\n\n", styleRegular); log.setCaretPosition(doc.getLength()); lastSize = doc.getLength(); }
static void register(final JTextPane pane) { final StyledDocument doc = pane.getStyledDocument(); String text = ""; try { text = doc.getText(0, doc.getLength()); } catch (BadLocationException ex) { Support.LOG.log(Level.SEVERE, null, ex); } final int[] boundaries = findBoundaries(text); if ((boundaries != null) && (boundaries.length != 0)) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { Style defStyle = StyleContext.getDefaultStyleContext() .getStyle(StyleContext.DEFAULT_STYLE); final Style hlStyle = doc.addStyle("regularBlue-url", defStyle); //NOI18N hlStyle.addAttribute(HyperlinkSupport.URL_ATTRIBUTE, new UrlAction()); StyleConstants.setForeground(hlStyle, UIUtils.getLinkColor()); StyleConstants.setUnderline(hlStyle, true); for (int i = 0; i < boundaries.length; i+=2) { doc.setCharacterAttributes(boundaries[i], boundaries[i + 1] - boundaries[i], hlStyle, true); } pane.removeMouseListener(getUrlMouseListener()); pane.addMouseListener(getUrlMouseListener()); } }); } }
synchronized void attachAnnotation(StyledDocument doc, Position lineStart) { if (attachedTo == null) { attachedTo = doc; NbDocument.addAnnotation((StyledDocument) doc, lineStart, -1, this); } else { Level toLog = Level.FINE; assert (toLog = Level.INFO) != null; AnnotationHolder.LOG.log(toLog, "Attempt to attach already attached annotation", new Exception()); } }
public static DiffElement create(Difference diff, FileObject fileObject, ModificationResult modification) { PositionRef start = diff.getStartPosition(); PositionRef end = diff.getEndPosition(); StyledDocument doc = null; PositionBounds bounds = new PositionBounds(start, end); return new DiffElement(diff, bounds, fileObject, modification); }
public static void dumpGuardedAttr(StyledDocument doc) { System.out.println("" + ((GuardedDocument) doc).toStringDetail()); // int start = 0; // int end = doc.getLength(); // Element el = null; // System.out.println("Document.guards: " + // ", s: " + start + ", e: " + end); // do { // el = doc.getCharacterElement(start); // System.out.println("s: " + el.getStartOffset() + ", e: " + el.getEndOffset() + // ", g: " + Boolean.TRUE.equals(el.getAttributes().getAttribute(NbDocument.GUARDED))); // start = el.getEndOffset() + 1; // } while (end > el.getEndOffset()); // System.out.println("-------"); }
/** * Opens a document in the editor at a given line. * This method is used in the case that the editor is not opened yet * (<code>EditorCookie.getOpenedPanes()</code> returned <code>null</code>) * and is to be opened at a specific line. * * @param editorCookie editor cookie to use for opening the document * @param doc document already loaded using the editor cookie * @param line line to open the document at (first line = <code>0</code>); * must be non-negative */ private void openDocAtLine(final EditorCookie editorCookie, final StyledDocument doc, final int line) { assert EventQueue.isDispatchThread(); assert line >= 0; assert editorCookie.getDocument() == doc; if (log.isLoggable(FINER)) { log.log(FINER, "openDocAtLine(EditorCookie, Document, line={0})", line); } int offset = getCursorOffset(doc, line); new SetCursorTask(editorCookie, offset).perform(); }
public static void verifyGuardAttr(TestCase test, StyledDocument doc, InteriorSection gs) { PositionBounds bounds = gs.getImpl().getHeaderBounds(); verifyGuardAttr(test, (GuardedDocument) doc, bounds.getBegin().getOffset(), bounds.getEnd().getOffset()); bounds = gs.getImpl().getFooterBounds(); verifyGuardAttr(test, (GuardedDocument) doc, bounds.getBegin().getOffset(), bounds.getEnd().getOffset()); }
/** Implements superclass abstract method. */ protected void setHardCodedString(HardCodedString hcString, StyledDocument document) { getStringText().setText(hcString == null ? "" : hcString.getText()); // NOI18N int pos; String hardLine; if (hcString.getStartPosition() == null) { hardLine = ""; // NOI18N } else { pos = hcString.getStartPosition().getOffset(); try { Element paragraph = document.getParagraphElement(pos); hardLine = document.getText(paragraph.getStartOffset(), paragraph.getEndOffset()-paragraph.getStartOffset()).trim(); } catch (BadLocationException ble) { hardLine = ""; // NOI18N } } getFoundInText().setText(hardLine); if(hcString instanceof FormHardCodedString) { getComponentText().setText( ((FormHardCodedString)hcString).getValidProperty().getRADComponentName()); getPropertyText().setText( ((FormHardCodedString)hcString).getNodeProperty().getName()); } else { remove(getComponentLabel()); remove(getComponentText()); remove(getPropertyLabel()); remove(getPropertyText()); } }
/** * @inheritDoc */ @Override protected void saveFromKitToStream(StyledDocument doc, EditorKit kit, OutputStream stream) throws IOException, BadLocationException { if (doc == null) { throw new NullPointerException("Document is null"); // NOI18N } if (kit == null) { throw new NullPointerException("Kit is null"); // NOI18N } Charset c = charsets.get(this.getDataObject()); if (c == null) { c = FileEncodingQuery.getEncoding(this.getDataObject().getPrimaryFile()); } FilterOutputStream fos = new FilterOutputStream(stream) { @Override public void close() throws IOException { flush(); } }; Writer w = new OutputStreamWriter (fos, c); try { kit.write(w, doc, 0, doc.getLength()); } finally { w.close(); } }
PositionEstimator(final List<? extends Tree> oldL, final List<? extends Tree> newL, final DiffContext diffContext) { this.oldL = oldL; this.newL = newL; this.diffContext = diffContext; this.seq = diffContext != null ? diffContext.tokenSequence : null; if (diffContext.doc instanceof StyledDocument) { this.guards = GuardedSectionManager.getInstance((StyledDocument) diffContext.doc); } else { this.guards = null; } initialized = false; }
/** * Get the root of the paragraph elements for the given document. * * @param doc non-null document instance. * @return root element of the paragraph elements. */ public static Element getParagraphRootElement(Document doc) { if (doc instanceof StyledDocument) { return ((StyledDocument)doc).getParagraphElement(0).getParentElement(); } else { return doc.getDefaultRootElement().getElement(0).getParentElement(); } }
protected StyledDocument createStyledDocument (EditorKit kit) { StyledDocument doc = super.createStyledDocument(kit); // have to store the field before unfusing the other thread // in normal conditions, the store would happen just on return. // CES.setDoc() no longer exists so it can't be called. // Test passes without the call so leaving it in current state for now. // try { // java.lang.reflect.Method f = CloneableEditorSupport.class.getDeclaredMethod("setDoc", StyledDocument.class, boolean.class); // f.setAccessible(true); // f.invoke(this, doc, true); // } catch (Exception e) { // exception = e; // } synchronized(kitLock) { inCreateKit = true; kitLock.notifyAll(); try { while (shouldWaitInCreate) kitLock.wait(); } catch (InterruptedException e) { exception = e; } } return doc; }
private void addTileWarning(StyledDocument doc, Colony colony, String messageId, Tile tile) { if (messageId == null || !Messages.containsKey(messageId)) return; StringTemplate t = StringTemplate.template(messageId) .addStringTemplate("%location%", tile.getColonyTileLocationLabel(colony)); try { doc.insertString(doc.getLength(), "\n\n" + Messages.message(t), doc.getStyle("regular")); } catch (Exception e) { logger.log(Level.WARNING, "Tile warning fail", e); } }
public IsOverriddenAnnotation(StyledDocument document, Position pos, AnnotationType type, String shortDescription, List<ElementDescription> declarations) { //#166351 -- null pos for some reason assert pos != null; this.document = document; this.pos = pos; this.type = type; this.shortDescription = shortDescription; this.declarations = declarations; }
@Override public GuardedSectionManager getGuardedSectionManager() { try { StyledDocument doc = null; try { doc = openDocument(); } catch (UserQuestionException uqex) { // Issue 143655 Object retVal = DialogDisplayer.getDefault().notify( new NotifyDescriptor.Confirmation(uqex.getLocalizedMessage(), NotifyDescriptor.YES_NO_OPTION)); if (NotifyDescriptor.YES_OPTION == retVal) { uqex.confirmed(); doc = openDocument(); } } if (doc == null) { // Issue 143655 - opening of big file canceled EventQueue.invokeLater(new Runnable() { @Override public void run() { close(); } }); return null; } else { return GuardedSectionManager.getInstance(doc); } } catch (IOException ex) { throw new IllegalStateException("cannot open document", ex); // NOI18N } }
public GuardedSectionManager getGuardedSectionManager() { try { StyledDocument doc = openDocument(); return GuardedSectionManager.getInstance(doc); } catch (IOException ex) { throw (IllegalStateException) new IllegalStateException("cannot open document").initCause(ex); // NOI18N } }