javax.swing.text.StyledDocument Java Examples

The following examples show how to use javax.swing.text.StyledDocument. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: GuardedSectionsImpl.java    From netbeans with Apache License 2.0 7 votes vote down vote up
/** Takes the section descriptors from the GuardedReader and
* fills the table 'sections', also marks as guarded all sections
* in the given document.
* @param is Where to take the guarded section descriptions.
* @param doc Where to mark guarded.
*/
void fillSections(AbstractGuardedSectionsProvider gr, List<GuardedSection> l, NewLine newLineType) {
    this.gr = GuardsSupportAccessor.DEFAULT.isUseReadersWritersOnSet(gr) ? gr : null;
    this.newLineType = newLineType;
    // XXX this should invalidate removed GS instances
    // XXX maybe would be useful to map new list to old list to keep track of valid instances as much as possible
    // XXX synchronize
    this.sections.clear();
    
    for (GuardedSection gs: l) {
        try {
            GuardedSectionImpl gsi = GuardsAccessor.DEFAULT.getImpl(gs);
            gsi.resolvePositions();
            sections.put(gs.getName(), gsi);
            StyledDocument doc = getDocument();
            gsi.markGuarded(doc);
        } catch (BadLocationException ex) {
            Logger.getLogger(GuardedSectionsImpl.class.getName()).log(Level.SEVERE, ex.getLocalizedMessage(), ex);
        }
    }
}
 
Example #2
Source File: MWPaneSelectionManager.java    From wpcleaner with Apache License 2.0 7 votes vote down vote up
/**
 * Select previous occurrence of text. 
 */
public void selectPreviousOccurrence() {
  StyledDocument doc = textPane.getStyledDocument();
  int lastStart = Integer.MIN_VALUE;
  for (int pos = textPane.getSelectionStart(); pos > 0; pos = lastStart) {
    Element run = doc.getCharacterElement(pos - 1);
    lastStart = run.getStartOffset();
    MutableAttributeSet attr = (MutableAttributeSet) run.getAttributes();
    if ((attr != null) &&
        (attr.getAttribute(MWPaneFormatter.ATTRIBUTE_TYPE) != null) &&
        (attr.getAttribute(MWPaneFormatter.ATTRIBUTE_OCCURRENCE) != Boolean.FALSE)) {
      select(run);
      return;
    }
  }
  selectLastOccurrence();
}
 
Example #3
Source File: GuardedSectionImpl.java    From netbeans with Apache License 2.0 7 votes vote down vote up
/** 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);
        }
    }
}
 
Example #4
Source File: CasAnnotationViewer.java    From uima-uimaj with Apache License 2.0 7 votes vote down vote up
/**
 * Do bold face by spans.
 */
private void doBoldFaceBySpans() {
  if (this.boldFaceSpans == null || this.boldFaceSpans.length == 0) {
    return;
  }
  int docLength = this.cas.getDocumentText().length();
  int spanLength = this.boldFaceSpans.length - (this.boldFaceSpans.length % 2);
  int i = 0;
  while (i < spanLength) {
    int begin = this.boldFaceSpans[i];
    int end = this.boldFaceSpans[i + 1];
    if (begin >= 0 && begin <= docLength && end >= 0 && end <= docLength && begin < end) {
      MutableAttributeSet attrs = new SimpleAttributeSet();
      StyleConstants.setBold(attrs, true);
      StyledDocument doc = (StyledDocument) this.textPane.getDocument();
      doc.setCharacterAttributes(begin, end - begin, attrs, false);
    }
    i += 2;
  }
}
 
Example #5
Source File: SeaGlassTextPaneUI.java    From seaglass with Apache License 2.0 7 votes vote down vote up
/**
 * Update the font in the default style of the document.
 *
 * @param font the new font to use or null to remove the font attribute
 *             from the document's style
 */
private void updateFont(Font font) {
    StyledDocument doc = (StyledDocument)getComponent().getDocument();
    Style style = doc.getStyle(StyleContext.DEFAULT_STYLE);

    if (style == null) {
        return;
    }

    if (font == null) {
        style.removeAttribute(StyleConstants.FontFamily);
        style.removeAttribute(StyleConstants.FontSize);
        style.removeAttribute(StyleConstants.Bold);
        style.removeAttribute(StyleConstants.Italic);
    } else {
        StyleConstants.setFontFamily(style, font.getName());
        StyleConstants.setFontSize(style, font.getSize());
        StyleConstants.setBold(style, font.isBold());
        StyleConstants.setItalic(style, font.isItalic());
    }
}
 
Example #6
Source File: GuardedSectionImpl.java    From netbeans with Apache License 2.0 7 votes vote down vote up
/** Deletes the text in the section.
 * @exception BadLocationException
 */
final void deleteText() throws BadLocationException {
    if (valid) {
        final StyledDocument doc = guards.getDocument();
        final BadLocationException[] blex = new BadLocationException[1];
        Runnable r = new Runnable() {
            public void run() {
                try {
                    int start = getStartPosition().getOffset();
                    if (start > 0 && "\n".equals(doc.getText(start - 1, 1))) { // NOI18N
                        start--;
                    }
                    doc.remove(start, getEndPosition().getOffset() - start + 1);
                } catch (BadLocationException ex) {
                    blex[0] = ex;
                }
            }
        };
        
        GuardedSectionsImpl.doRunAtomic(doc, r);
        
        if (blex[0] != null) {
            throw blex[0];
        }
    }
}
 
Example #7
Source File: EditorContextImpl.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/** 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;
}
 
Example #8
Source File: DocumentOpenClose.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private StyledDocument retainExistingDocLA() { // Lock acquired mandatory
    switch (documentStatus) {
        case CLOSED:
            break;
        case RELOADING:
        case LOADING:
            cancelCloseLA(); // Cancel possible closing
            break;

        case OPENED:
            StyledDocument openDoc = getRefDocument();
            if (openDoc != null) { // Still opened
                // Check if a close attempt is not active and possibly cancel it
                cancelCloseLA();
                if (activeClose == null) {
                    return openDoc;
                }
            }
            break;

        default:
            throw invalidStatus();

    }
    return null;
}
 
Example #9
Source File: XMLDataObjectMimeTypeTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void testForUnknownMime() throws Exception {
    
    
    X l = X.getLoader(X.class);
    l.getExtensions().addExtension(getName());
    AddLoaderManuallyHid.addRemoveLoader(l, true);
    
    try {
        setUp("content/unknown");
        EditorCookie cook = obj.getCookie(EditorCookie.class);
        StyledDocument doc = cook.openDocument();
        assertEquals("text/xml", doc.getProperty("mimeType"));
    } finally {
        AddLoaderManuallyHid.addRemoveLoader(l, false);
    }
}
 
Example #10
Source File: DocumentCannotBeClosedWhenAWTBlockedTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
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);
    }
}
 
Example #11
Source File: JavaI18nFinderTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws Exception {
    FileSystem fs = FileUtil.createMemoryFileSystem();
    FileObject fo = fs.getRoot().createData("JFrame.java");
    
    source = convertStreamToString(getClass().getResourceAsStream("resources/JFrame.txt"));
    
    writeFile(source, fo);
    DataObject sourceDataObject = DataObject.find(fo);
    
    EditorCookie editorCookie = sourceDataObject.getCookie(EditorCookie.class);        
    if (editorCookie == null) {
        throw new IllegalArgumentException("I18N: Illegal data object type"+ sourceDataObject); // NOI18N
    }        
    StyledDocument document = editorCookie.getDocument();
    while(document == null) {
        document = editorCookie.openDocument();
    }        
                    
    instance = new JavaI18nFinder(document);
}
 
Example #12
Source File: WordCompletionItem.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void defaultAction(final JTextComponent component) {
    Completion.get().hideCompletion();
    Completion.get().hideDocumentation();
    NbDocument.runAtomic((StyledDocument) component.getDocument(), new Runnable() {
        public void run() {
            Document doc = component.getDocument();
            
            try {
                doc.remove(substituteOffset, component.getCaretPosition() - substituteOffset);
                doc.insertString(substituteOffset, getText(), null);
            } catch (BadLocationException e) {
                ErrorManager.getDefault().notify(e);
            }
        }
    });
}
 
Example #13
Source File: SearchCompletionItem.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@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);
            }
        }
    });
}
 
Example #14
Source File: NbToolTip.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private boolean isDocumentValid() {
    DataObject dob = NbEditorUtilities.getDataObject(doc);
    if (dob != null) {
        EditorCookie ec = dob.getCookie(EditorCookie.class);
        if (ec != null) {
            StyledDocument openedDoc;
            try {
                openedDoc = ec.openDocument();
            } catch (IOException e) {
                openedDoc = null; // should return in next if stmt
            }
            
            return (openedDoc == doc);
        }
    }
    return false;
}
 
Example #15
Source File: CssActionsImplementationProvider.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private static boolean isRefactorableEditorElement(final Node node) {
    final AtomicBoolean result = new AtomicBoolean(false);
    Mutex.EVENT.readAccess(new Runnable() {

        @Override
        public void run() {
            EditorCookie ec = getEditorCookie(node);
            if (isFromEditor(ec)) {
                //check if there's css code at the offset
                final StyledDocument document = ec.getDocument();
                JEditorPane pane = ec.getOpenedPanes()[0];
                final int caret = pane.getCaretPosition();
                document.render(new Runnable() {

                    @Override
                    public void run() {
                        result.set(null != LexerUtils.getTokenSequence(document, caret, CssTokenId.language(), true));
                    }
                });
            }
        }
        
    });

    return result.get();
}
 
Example #16
Source File: DocumentImportStructureProvider.java    From uima-uimaj with Apache License 2.0 6 votes vote down vote up
private String convert(InputStream rtfDocumentInputStream) throws IOException {
  RTFEditorKit aRtfEditorkit = new RTFEditorKit();

  StyledDocument styledDoc = new DefaultStyledDocument();

  String textDocument;

  try {
    aRtfEditorkit.read(rtfDocumentInputStream, styledDoc, 0);

    textDocument = styledDoc.getText(0, styledDoc.getLength());
  } catch (BadLocationException e) {
    throw new IOException("Error during parsing");
  }

  return textDocument;
}
 
Example #17
Source File: BaseTypeTableCellRenderer.java    From binnavi with Apache License 2.0 6 votes vote down vote up
private static void generateDocument(
    final TypeInstance instance, final boolean renderData, final StyledDocument document) {
  switch (instance.getBaseType().getCategory()) {
    case ARRAY:
      renderArray(instance, document, renderData);
      break;
    case ATOMIC:
      renderAtomic(instance, document, renderData);
      break;
    case POINTER:
      renderPointer(instance, document);
      break;
    case STRUCT:
      renderStruct(instance, document, renderData);
      break;
    default:
      break;
  }
}
 
Example #18
Source File: PositionBounds.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void resolvePositions() throws BadLocationException {
    StyledDocument doc = guards.getDocument();

    if (begin instanceof UnresolvedPosition) {
        begin = doc.createPosition(begin.getOffset());
    } else if (begin instanceof BiasedPosition) {
        ((BiasedPosition) begin).resolve(doc);
    }

    if (end instanceof UnresolvedPosition) {
        end = doc.createPosition(end.getOffset());
    } else if (end instanceof BiasedPosition) {
        ((BiasedPosition) end).resolve(doc);
    }
    assertPositionBounds();
}
 
Example #19
Source File: ResultsTextPane.java    From mzmine2 with GNU General Public License v2.0 6 votes vote down vote up
public ResultsTextPane(StyledDocument doc) {
  super(doc);
  createStyles();
  setEditorKit(JTextPane.createEditorKitForContentType("text/html"));
  setEditable(false);
  addHyperlinkListener(new HyperlinkListener() {
    @Override
    public void hyperlinkUpdate(HyperlinkEvent e) {
      if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
        if (Desktop.isDesktopSupported()) {
          try {
            Desktop.getDesktop().browse(e.getURL().toURI());
          } catch (IOException | URISyntaxException e1) {
            e1.printStackTrace();
          }
        }
      }
    }
  });
}
 
Example #20
Source File: MergePane.java    From netbeans with Apache License 2.0 6 votes vote down vote up
void addHighlight (StyledDocument doc, int line1, int line2, final java.awt.Color color) {
    if (line1 > 0) {
        --line1;
    }
    SimpleAttributeSet attrs = new SimpleAttributeSet();
    StyleConstants.setBackground(attrs, color);
    attrs.addAttribute(HighlightsContainer.ATTR_EXTENDS_EOL, Boolean.TRUE);
    int startOffset = getRowStartFromLineOffset(doc, line1);
    int endOffset = getRowStartFromLineOffset(doc, line2);
    synchronized (highlights) {
        ListIterator<HighLight> it = highlights.listIterator();
        HighLight toAdd = new HighLight(startOffset, endOffset, attrs);
        while (it.hasNext()) {
            HighLight highlight = it.next();
            if (highlight.contains(startOffset)) {
                it.remove();
                break;
            } else if (highlight.precedes(startOffset)) {
                it.previous();
                break;
            }
        }
        it.add(toAdd);
    }
    fireHilitingChanged();
}
 
Example #21
Source File: FormEditorSupport.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
protected void loadFromStreamToKit(StyledDocument doc, InputStream stream, EditorKit kit) throws IOException, BadLocationException {
    if (guardedEditor == null) {
        guardedEditor = new FormGEditor();
        GuardedSectionsFactory gFactory = GuardedSectionsFactory.find(((DataEditorSupport.Env) env).getMimeType());
        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);
    }
}
 
Example #22
Source File: Model.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public void propertyChange(PropertyChangeEvent pce) {
    if (EditorCookie.Observable.PROP_DOCUMENT.equals(pce.getPropertyName())) {
        Object newValue = pce.getNewValue();
        if (newValue == null) {
            try {
                //Document closed.
                //Re-create the document and update the lookup.
                if(dataObject.isValid()) {
                    StyledDocument newDocument = editorCookie.openDocument();
                    documentLookup.updateLookup(Lookups.fixed(newDocument));

                    LOGGER.log(Level.FINE, "Model: {0}: new document instance set to {0} upon "
                            + "EditorCookie.Observable.PROP_DOCUMENT property change.",
                            new Object[]{this, System.identityHashCode(newDocument)}); //NOI18N
                } else {
                    documentLookup.updateLookup(Lookups.fixed()); //remove the document from lookup
                    LOGGER.log(Level.FINE, "Model: {0}: DataObject become invalid.",
                            new Object[]{this}); //NOI18N
                }
            } catch (IOException ex) {
                Exceptions.printStackTrace(ex);
            }
        }

    }
}
 
Example #23
Source File: Utilities.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public static String getAsString(File file) {
    String result;
    try {
        FileObject testFile = FileUtil.toFileObject(file);
        DataObject DO = DataObject.find(testFile);
        
        EditorCookie ec=(EditorCookie)(DO.getCookie(EditorCookie.class));
        StyledDocument doc=ec.openDocument();
        result=doc.getText(0, doc.getLength());
    } catch (Exception e){
        throw new AssertionFailedErrorException(e);
    }
    return result;
}
 
Example #24
Source File: TextEditorGUI.java    From trygve with GNU General Public License v2.0 5 votes vote down vote up
public void removeAllBreakpoints() {
	final StyledDocument doc = (StyledDocument)editPane.getDocument();
	final SimpleAttributeSet sas = new SimpleAttributeSet();
	StyleConstants.setBackground(sas, new java.awt.Color(233, 228, 242));
	
	// https://stackoverflow.com/questions/28927274/get-attributes-of-selected-text-in-jtextpane
	for(int i = 0; i < doc.getLength(); i++) {
	    final AttributeSet set = doc.getCharacterElement(i).getAttributes();
	    final Color backgroundColor = StyleConstants.getBackground(set);
	    if (backgroundColor.equals(Color.cyan)) {
	    	// The breakpoint color. Remove breakpoint annotation from this text
	    	doc.setCharacterAttributes(i, 1, sas, false);
	    }
	}
}
 
Example #25
Source File: MMDEditorSupport.java    From netbeans-mmd-plugin with Apache License 2.0 5 votes vote down vote up
public String getDocumentText() {
  if (this.getDataObject().isValid()) {
    try {
      final StyledDocument doc = this.openDocument();
      return doc.getText(0, doc.getLength());
    } catch (Exception ex) {
      LOGGER.error("Can't get document text", ex); //NOI18N
      return null;
    }
  } else {
    LOGGER.warn("DataObject " + this.getDataObject() + " is not valid");
    return null;
  }
}
 
Example #26
Source File: MagicTextPane.java    From MtgDesktopCompanion with GNU General Public License v3.0 5 votes vote down vote up
public void updateTextWithIcons() {

		textPane.setText(textPane.getText().replaceAll("(?m)^[ \t]*\r?\n", ""));
		Pattern p = Pattern.compile(CardsPatterns.MANA_PATTERN.getPattern());
		Matcher m = p.matcher(textPane.getText());

		String text = textPane.getText();
		StyleContext context = new StyleContext();
		StyledDocument document = new DefaultStyledDocument(context);

		Style labelStyle = context.getStyle(StyleContext.DEFAULT_STYLE);

		Style italic = context.addStyle("italicStyle", labelStyle);
		StyleConstants.setItalic(italic, true);

		int cumule = 0;
		try {
			document.insertString(0, text, null);
			while (m.find()) {
				Image ic = manaPanel.getManaSymbol(m.group());

				int width = 15;
				if (m.group().equals("{100}"))
					width = 30;

				JLabel label = new JLabel(new ImageIcon(ic.getScaledInstance(width, 15, Image.SCALE_DEFAULT)));
				label.setAlignmentY(SwingConstants.TOP);

				StyleConstants.setComponent(labelStyle, label);

				document.remove(m.start() + cumule, (m.end() - m.start()));
				document.insertString(m.start() + cumule, m.group(), labelStyle);
			}

			textPane.setDocument(document);
		} catch (BadLocationException e) {
			textPane.setText(text);
		}
	}
 
Example #27
Source File: JTextPaneOperator.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Maps {@code JTextPane.setStyledDocument(StyledDocument)} through queue
 */
public void setStyledDocument(final StyledDocument styledDocument) {
    runMapping(new MapVoidAction("setStyledDocument") {
        @Override
        public void map() {
            ((JTextPane) getSource()).setStyledDocument(styledDocument);
        }
    });
}
 
Example #28
Source File: ImageView.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
public Color getForeground() {
    View parent;
    if (fg == null && (parent = getParent()) != null) {
        Document doc = getDocument();
        AttributeSet attr = parent.getAttributes();

        if (attr != null && (doc instanceof StyledDocument)) {
            fg = ((StyledDocument)doc).getForeground(attr);
        }
    }
    return fg;
}
 
Example #29
Source File: EditorContextImpl.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static CompilationController retrieveController(ResultIterator resIt, StyledDocument doc) throws ParseException {
    Result res = resIt.getParserResult();
    CompilationController ci = res != null ? CompilationController.get(res) : null;
    if (ci == null) {
        ErrorManager.getDefault().log(ErrorManager.WARNING,
                "Unable to get compilation controller " + doc);
    }
    return ci;
}
 
Example #30
Source File: FormatMessageDialogWorker.java    From otroslogviewer with Apache License 2.0 5 votes vote down vote up
@Override
protected void done() {
  LOGGER.trace("Message details format and colors calculated, updating GUI");
  StyledDocument styledDocument = otrosJTextWithRulerScrollPane.getjTextComponent().getStyledDocument();
  try {
    styledDocument.remove(0, styledDocument.getLength());
  } catch (BadLocationException e) {
    LOGGER.error("Can't clear log events text  area", e);
  }
  if (!isCancelled()) {
    updateChanges(chunks);
  }
  LOGGER.trace("GUI updated");
}