private static void setupContext(final JEditorPane editorPane, Pair<Line.Part, FileObject> context) { assert SwingUtilities.isEventDispatchThread(); if (context != null) { final Line.Part lp = context.first(); final FileObject file = context.second(); //System.err.println("WatchPanel.setupContext("+file+", "+line+", "+offset+")"); // Do the binding for text files only: if (file != null && file.getMIMEType().startsWith("text/")) { // NOI18N String origText = editorPane.getText(); DialogBinding.bindComponentToFile(file, lp.getLine().getLineNumber(), lp.getColumn(), lp.getLength(), editorPane); Document editPaneDoc = editorPane.getDocument(); //editPaneDoc.putProperty("org.netbeans.modules.editor.java.JavaCompletionProvider.skipAccessibilityCheck", "true"); editorPane.setText(origText); } } setupUI(editorPane); }
protected JTextComponent getTextComponent(URL url) { FileObject f = org.openide.filesystems.URLMapper.findFileObject(url); if (f != null) { DataObject d = null; try { d = DataObject.find(f); } catch (DataObjectNotFoundException e) { LOG.log(Level.WARNING, "Can't get DataObject for " + f, e); //NOI18N } if (d != null) { EditorCookie cookie = d.getLookup().lookup(EditorCookie.class); if (cookie != null) { JEditorPane [] allJeps = cookie.getOpenedPanes(); if (allJeps != null) { return allJeps[0]; } } } } return null; }
/**Currently, this method is supposed to be runned inside the AWT thread. * If this condition is not fullfilled, an IllegalStateException is * thrown. Do NOT modify this behaviour, or deadlock (or even Swing * or NetBeans winsys data corruption) may occur. * * Currently threading model of this method is compatible with * editor code completion threading model. Revise if this changes * in future. */ private void testPerform(PrintWriter out, PrintWriter log, JEditorPane editor, boolean unsorted, String assign, int lineIndex, int queryType) throws BadLocationException, IOException { if (!SwingUtilities.isEventDispatchThread()) throw new IllegalStateException("The testPerform method may be called only inside AWT event dispatch thread."); BaseDocument doc = Utilities.getDocument(editor); int lineOffset = Utilities.getRowStartFromLineOffset(doc, lineIndex -1); editor.grabFocus(); editor.getCaret().setDot(lineOffset); doc.insertString(lineOffset, assign, null); reparseDocument((DataObject) doc.getProperty(doc.StreamDescriptionProperty)); completionQuery(out, log, editor, unsorted, queryType); }
public void testInsertRemoveTransaction() throws Exception { loggingOn(); RandomTestContainer container = createContainer(); JEditorPane pane = container.getInstance(JEditorPane.class); final Document doc = pane.getDocument(); doc.putProperty("mimeType", "text/plain"); final RandomTestContainer.Context context = container.context(); // ViewHierarchyRandomTesting.disableHighlighting(container); DocumentTesting.setSameThreadInvoke(container.context(), true); // Do not post to EDT ((BaseDocument)doc).runAtomic(new Runnable() { @Override public void run() { try { for (int i = 0; i < 100; i++) { DocumentTesting.insert(context, 0, "a\nb\n\n"); DocumentTesting.remove(context, i * 3, 1); } } catch (Exception ex) { throw new IllegalStateException(ex); } } }); DocumentTesting.setSameThreadInvoke(container.context(), false); DocumentTesting.undo(context, 1); }
@Test public void testWrapperAction() { Map attrs = new HashMap(SIMPLE_ATTRS); attrs.put(AbstractEditorAction.WRAPPER_ACTION_KEY, true); final MyAction a = new MyAction(); // No attrs passed attrs.put("delegate", a); WrapperEditorAction wrapperAction = WrapperEditorAction.create(attrs); JTextComponent c = new JEditorPane(); assertEquals("my-name", wrapperAction.getValue(Action.NAME)); assertNull(a.getValue(Action.NAME)); ActionEvent evt = new ActionEvent(c, 0, ""); wrapperAction.actionPerformed(evt); assertEquals(Thread.currentThread(), a.actionPerformedThread); // Properties transferred assertEquals("my-name", a.getValue(Action.NAME)); }
private boolean isExcludedProperty1(FormProperty prop) { if (!Boolean.TRUE.equals(prop.getValue(EXCLUSION_DETERMINED))) { prop.setValue(EXCLUSION_DETERMINED, true); Object propOwner = prop.getPropertyContext().getOwner(); Class type = null; if (propOwner instanceof RADComponent) { type = ((RADComponent)propOwner).getBeanClass(); } else if (propOwner instanceof FormProperty) { type = ((FormProperty)propOwner).getValueType(); } String propName = prop.getName(); boolean excl = (Component.class.isAssignableFrom(type) && "name".equals(propName)) // NOI18N || (JEditorPane.class.isAssignableFrom(type) && "contentType".equals(propName)); // NOI18N prop.setValue(EXCLUDE_FROM_RESOURCING, excl); return excl; } return false; }
@Override protected void performContextAction(Node[] nodes) { if (visible(nodes)) { JEditorPane pane = activatedEditorPane(nodes); AnnotationBarManager.hideAnnotationBar(pane); } else { EditorCookie ec = activatedEditorCookie(nodes); if (ec == null) return; final File file = activatedFile(nodes); JEditorPane[] panes = ec.getOpenedPanes(); if (panes == null) { ec.open(); panes = ec.getOpenedPanes(); } if (panes == null) { return; } final JEditorPane currentPane = panes[0]; showAnnotations(currentPane, file, null, true); } }
private static int getCaretPos(FoldHierarchy h) { int caretPos = -1; JTextComponent c = h.getComponent(); if (c == null) { return -1; } Document doc = getDocument(h); Object od = doc.getProperty(Document.StreamDescriptionProperty); if (od instanceof DataObject) { DataObject d = (DataObject)od; EditorCookie cake = d.getCookie(EditorCookie.class); JEditorPane[] panes = cake.getOpenedPanes(); int idx = panes == null ? -1 : Arrays.asList(panes).indexOf(c); if (idx != -1) { caretPos = c.getCaret().getDot(); } } return caretPos; }
/** Returns editor pane. Returns null if document loading was canceled by user * through answering UserQuestionException or when CloneableEditor is closed. * * @return editor pane or null */ public JEditorPane getEditorPane() { assert SwingUtilities.isEventDispatchThread(); //User selected not to load document if (!componentCreated) { return null; } //#175528: This case should not happen as modal dialog handling UQE should //not be displayed during IDE start ie. during component deserialization. if (CloneableEditorInitializer.modalDialog) { LOG.log(Level.WARNING,"AWT is blocked by modal dialog. Return null from CloneableEditor.getEditorPane." + " Please report this to IZ."); LOG.log(Level.WARNING,"support:" + support.getClass().getName()); Exception ex = new Exception(); StringWriter sw = new StringWriter(500); PrintWriter pw = new PrintWriter(sw); ex.printStackTrace(pw); LOG.log(Level.WARNING,sw.toString()); return null; } initialize(); CloneableEditorInitializer.waitForFinishedInitialization(this); return pane; }
/** * Sets the foreground color. * * @param e the action event */ public void actionPerformed(ActionEvent e) { JEditorPane editor = getEditor(e); if (editor != null) { Color fg = this.fg; if ((e != null) && (e.getSource() == editor)) { String s = e.getActionCommand(); try { fg = Color.decode(s); } catch (NumberFormatException nfe) { } } if (fg != null) { MutableAttributeSet attr = new SimpleAttributeSet(); StyleConstants.setForeground(attr, fg); setCharacterAttributes(editor, attr, false); } else { UIManager.getLookAndFeel().provideErrorFeedback(editor); } } }
public int getTextIndex() { return EventQueueWait.exec(new Callable<Integer>() { @Override public Integer call() throws Exception { String href = getText(); int hRefIndex = 0; int current = 0; JEditorPane editor = (JEditorPane) parent.getComponent(); HTMLDocument document = (HTMLDocument) editor.getDocument(); Iterator iterator = document.getIterator(Tag.A); while (iterator.isValid()) { if (current++ >= index) { return hRefIndex; } String attribute = ((HTMLDocument) ((JEditorPane) parent.getComponent()).getDocument()) .getText(iterator.getStartOffset(), iterator.getEndOffset() - iterator.getStartOffset()); if (attribute != null && attribute.equals(href)) { hRefIndex++; } iterator.next(); } return -1; } }); }
public void testFormatterDoesNotIncludeHashOnEditor() throws ClassNotFoundException { LogRecord r = new LogRecord(Level.INFO, "EDIT"); JEditorPane ep = new javax.swing.JEditorPane(); ep.setName("SomeName"); r.setParameters(new Object[] { ep }); Formatter formatter = new LogFormatter(); String s = formatter.format(r); assertEquals("No @\n" + s, -1, s.indexOf("@")); if (s.indexOf("SomeName") == -1) { fail("SomeName should be there:\n" + s); } }
@Override public boolean canDrop(DropTargetDragEvent e) { //check if the JEditorPane contains html document JEditorPane pane = findPane(e.getDropTargetContext().getComponent()); if (pane == null) { return false; } int offset = getLineEndOffset(pane, e.getLocation()); if (!containsLanguageAtOffset(pane.getDocument(), offset)) { return false; } else { //update the caret as the user drags the object //needs to be done explicitly here as QuietEditorPane doesn't call //the original Swings DropTarget which does this pane.setCaretPosition(offset); pane.requestFocusInWindow(); //pity we need to call this all the time when dragging, but ExternalDropHandler don't handle dragEnter event return canDrop(e.getCurrentDataFlavors()); } }
/** * Sets the font size. * * @param e the action event */ public void actionPerformed(ActionEvent e) { JEditorPane editor = getEditor(e); if (editor != null) { int size = this.size; if ((e != null) && (e.getSource() == editor)) { String s = e.getActionCommand(); try { size = Integer.parseInt(s, 10); } catch (NumberFormatException nfe) { } } if (size != 0) { MutableAttributeSet attr = new SimpleAttributeSet(); StyleConstants.setFontSize(attr, size); setCharacterAttributes(editor, attr, false); } else { UIManager.getLookAndFeel().provideErrorFeedback(editor); } } }
public void testExceptionThrownWhenDocumentIsBeingReadNo () throws Exception { MyEx my = new MyEx(); toThrow = my; DD.options = null; DD.toReturn = NotifyDescriptor.NO_OPTION; support.open (); SwingUtilities.invokeAndWait(new Runnable() { public void run() { JEditorPane[] panes = support.getOpenedPanes(); assertNull(panes); } }); }
public void testInitializeAndBlockInAWT() throws Exception { assertTrue("Running in AWT", SwingUtilities.isEventDispatchThread()); class R implements PropertyChangeListener { JEditorPane p; public void run() { p = support.getOpenedPanes()[0]; } public void propertyChange(PropertyChangeEvent evt) { if (TopComponent.Registry.PROP_ACTIVATED.equals(evt.getPropertyName())) { run(); } } } R r = new R(); WindowManager.getDefault().getRegistry().addPropertyChangeListener(r); final Object LOCK = new JPanel().getTreeLock(); synchronized (LOCK) { support.open(); assertNotNull(r.p); } assertKit(r.p.getEditorKit()); }
/** * Calculates the preferred height of an editor pane with the given fixed width for the * specified string. * * @param comment * the annotation comment string * @param width * the width of the content * @return the preferred height given the comment */ public static int getContentHeight(final String comment, final int width) { if (comment == null) { throw new IllegalArgumentException("comment must not be null!"); } JEditorPane dummyEditorPane = new JEditorPane("text/html", ""); dummyEditorPane.setText(comment); dummyEditorPane.setBorder(null); dummyEditorPane.setSize(width, Short.MAX_VALUE); // height is not exact. Multiply by magic number to get a more fitting value... if (SystemInfoUtilities.getOperatingSystem() == OperatingSystem.OSX || SystemInfoUtilities.getOperatingSystem() == OperatingSystem.UNIX || SystemInfoUtilities.getOperatingSystem() == OperatingSystem.SOLARIS) { return (int) (dummyEditorPane.getPreferredSize().getHeight() * 1.05f); } else { return (int) dummyEditorPane.getPreferredSize().getHeight(); } }
public void testRenameTheDocumentWhilechangingTheTimestamp() throws Exception { Document doc = edit.openDocument(); assertFalse("Not Modified", edit.isModified()); doc.insertString(0, "Base change\n", null); assertTrue("Is Modified", edit.isModified()); edit.open(); waitEQ(); JEditorPane[] arr = getPanes(); assertNotNull("There is one opened pane", arr); obj.getFolder().rename("newName"); assertEquals("Last modified incremented by 10000", lastM + 10000, obj.getPrimaryFile().lastModified().getTime()); assertTrue("Name contains newName: " + obj.getPrimaryFile(), obj.getPrimaryFile().getPath().contains("newName/")); waitEQ(); edit.saveDocument(); if (DD.error != null) { fail("Error in dialog:\n" + DD.error); } }
/** * Sets the font family. * * @param e the event */ public void actionPerformed(ActionEvent e) { JEditorPane editor = getEditor(e); if (editor != null) { String family = this.family; if ((e != null) && (e.getSource() == editor)) { String s = e.getActionCommand(); if (s != null) { family = s; } } if (family != null) { MutableAttributeSet attr = new SimpleAttributeSet(); StyleConstants.setFontFamily(attr, family); setCharacterAttributes(editor, attr, false); } else { UIManager.getLookAndFeel().provideErrorFeedback(editor); } } }
public void testReleaseLayers() { final String mimeType = "text/plain"; TestReleaseHighlightsContainer releasableContainer = new TestReleaseHighlightsContainer(); SingletonLayerFactory releasableLayer = new SingletonLayerFactory( "releasableLayer", ZOrder.DEFAULT_RACK.forPosition(1), true, releasableContainer); MemoryMimeDataProvider.reset(null); MemoryMimeDataProvider.addInstances(mimeType, releasableLayer); JEditorPane pane = new JEditorPane(mimeType, "Hello"); HighlightingManager hm = HighlightingManager.getInstance(pane); // Ensure layers get created hm.getHighlights(HighlightsLayerFilter.IDENTITY); pane.setEditorKit(new SimpleKit(mimeType)); // Do not check against concrete release count since there are e.g. mime lookup rebuild notifications // that lead to HM.rebuildAllLayers() which increases the releaseCount too. assertTrue("Highlights container releasing not performed after pane.setEditorKit()", releasableContainer.releaseCount > 0); }
/** * Gets the document associated with an editor pane. * * @param e the editor * @return the document * @exception IllegalArgumentException for the wrong document type */ protected final StyledDocument getStyledDocument(JEditorPane e) { Document d = e.getDocument(); if (d instanceof StyledDocument) { return (StyledDocument) d; } throw new IllegalArgumentException("document must be StyledDocument"); }
static String getCurrentJavaWord() { Node[] n = TopComponent.getRegistry ().getActivatedNodes (); if (n.length == 1) { EditorCookie ec = n[0].getLookup().lookup(EditorCookie.class); if (ec != null) { JEditorPane pane = NbDocument.findRecentEditorPane(ec); return pane == null ? null : forPane(pane); } } return null; }
public FlickrSettingsPanel() { apiKey = new JTextField(); apiSharedSecret = new JTextField(); // Yuck, this seems to be the minimal amount of code to get a clickable // and styled link // (copied from the Cron link in the scheduler) JEditorPane apiKeyHelp = new JEditorPane(); apiKeyHelp.setEditorKit(new HTMLEditorKit()); apiKeyHelp.setDocument(new HTMLDocument()); apiKeyHelp.setEditable(false); apiKeyHelp.setText("<html><head><style>" + "<!--a{color:#0000cc;text-decoration: none;}//--></style></head>" + "<body>" + getString("settings.label.apikeyhelp")); apiKeyHelp.addHyperlinkListener(new HyperlinkListener() { @Override public void hyperlinkUpdate(HyperlinkEvent e) { if( e.getEventType() == HyperlinkEvent.EventType.ACTIVATED ) { getClientService().showDocument(e.getURL(), null); } } }); apiKeyHelp.setBackground(new JPanel().getBackground()); add(apiKeyHelp, "span 2"); add(new JLabel(getString("settings.label.apikey"))); add(apiKey); add(new JLabel(getString("settings.label.apisharedsecret"))); add(apiSharedSecret); }
@Override public Object _makeVisible() { JEditorPane editor = (JEditorPane) parent.getComponent(); try { Rectangle bounds = editor.modelToView(pos); if (bounds != null) { bounds.height = editor.getVisibleRect().height; editor.scrollRectToVisible(bounds); } } catch (BadLocationException e) { throw new InvalidElementStateException("Invalid position " + pos + "(" + e.getMessage() + ")", e); } return null; }
public CharTablePanel(JEditorPane ed) { try { editor = ed; jbInit(); } catch (Exception e) { e.printStackTrace(); } }
private void setContentTypeInAwt(final JEditorPane pane, final String mimeType) { try { SwingUtilities.invokeAndWait(new Runnable() { public void run() { pane.setContentType(mimeType); } }); } catch (Exception e) { e.printStackTrace(); fail("Can't set content type in AWT: " + e.getMessage()); } }
@Override public Point _getMidpoint() { JEditorPane editor = (JEditorPane) parent.getComponent(); Iterator iterator = findTag((HTMLDocument) editor.getDocument()); int startOffset = iterator.getStartOffset(); int endOffset = iterator.getEndOffset(); try { Rectangle bounds = editor.modelToView(startOffset + (endOffset - startOffset) / 2); return new Point(bounds.x + bounds.width / 2, bounds.y + bounds.height / 2); } catch (BadLocationException e) { throw new InvalidElementStateException("Unable to get text for tag " + tag + " in document with index " + index + "(" + "StartOffset: " + startOffset + " EndOffset: " + endOffset + ")", e); } }
public JComponent getToolbarRepresentation() { JComponent toolbar = null; JEditorPane jepane = getEditorPane(); if (jepane != null) { Document doc = jepane.getDocument(); if (doc instanceof NbDocument.CustomToolbar) { toolbar = ((NbDocument.CustomToolbar)doc).createToolbar(jepane); } } return toolbar; }
@BeforeMethod public void showDialog() throws Throwable { SwingUtilities.invokeAndWait(new Runnable() { @Override public void run() { frame = new JFrame(REditorPaneTest.class.getSimpleName()); frame.setName("frame-" + REditorPaneTest.class.getSimpleName()); frame.getContentPane().add(new EditorPaneDemo(), BorderLayout.CENTER); frame.setSize(800, 600); frame.setVisible(true); } }); editor = (JEditorPane) ComponentUtils.findComponent(JEditorPane.class, frame); }
/** * {@inheritDoc} */ @Override public void buildDetail(String id, JPanel panel) { if (this.id.equals(id)) return; panel.setLayout(new MigLayout("wrap 1, center")); JLabel header = Utility.localizedHeaderLabel(Messages.nameKey(id), SwingConstants.LEADING, FontLibrary.FontSize.SMALL); panel.add(header, "align center, wrap 20"); JEditorPane editorPane = new JEditorPane("text/html", Messages.getDescription(id)) { @Override public void paintComponent(Graphics g) { Graphics2D graphics2d = (Graphics2D) g; graphics2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); /* graphics2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); graphics2d.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON); */ super.paintComponent(graphics2d); } }; editorPane.putClientProperty(JEditorPane.HONOR_DISPLAY_PROPERTIES, Boolean.TRUE); editorPane.setFont(panel.getFont()); editorPane.setOpaque(false); editorPane.setEditable(false); editorPane.addHyperlinkListener(colopediaPanel); panel.add(editorPane, "width 95%"); }
@SuppressWarnings("deprecation") private static boolean doOpen(FileObject fo, final int offsetA, final int offsetB) { if (offsetA == -1) { StatusDisplayer.getDefault().setStatusText( NbBundle.getMessage(ElementOpen.class, "WARN_ElementNotFound"), StatusDisplayer.IMPORTANCE_ANNOTATION); } boolean success = UiUtils.open(fo, offsetA); if (!success) { return false; } final DataObject od; try { od = DataObject.find(fo); } catch (DataObjectNotFoundException ex) { return success; } final EditorCookie ec = od.getLookup().lookup(EditorCookie.class); if (ec != null && offsetA != -1 && offsetB != -1) { SwingUtilities.invokeLater(new Runnable() { public void run() { JEditorPane[] panes = ec.getOpenedPanes(); if (offsetB >= 0 && panes != null && panes.length > 0) { JEditorPane pane = panes[0]; FoldHierarchy fh = FoldHierarchy.get(pane); Fold f = FoldUtilities.findNearestFold(fh, offsetA); // in case a fold already exists ... if (f != null && f.getStartOffset() >= offsetA && f.getEndOffset() <= offsetB) { fh.expand(f); } } } }); } return success; }
/** * Maps {@code JEditorPane.getEditorKitForContentType(String)} through queue */ public EditorKit getEditorKitForContentType(final String string) { return (runMapping(new MapAction<EditorKit>("getEditorKitForContentType") { @Override public EditorKit map() { return ((JEditorPane) getSource()).getEditorKitForContentType(string); } })); }
private JEditorPane[] getPanes() { return Mutex.EVENT.readAccess(new Mutex.Action<JEditorPane[]>() { public JEditorPane[] run() { return edit.getOpenedPanes(); } }); }
/** * Tests that the action context for the context-aware toolbar actions * is the DataObject corresponding to the current document if there is no * Lookup.Provider ancestor. */ public void testActionContextFallbackToDataObject() throws Exception { JPanel parent = new JPanel(); JEditorPane editor = new JEditorPane(); editor.setEditorKit(new NbEditorKit()); parent.add(editor); DataObject docDataObject = createDataObject(); assertNotNull(docDataObject); editor.getDocument().putProperty(Document.StreamDescriptionProperty, docDataObject); Lookup actionContext = NbEditorToolBar.createActionContext(editor); assertNotNull(actionContext.lookup(Node.class)); assertNull(actionContext.lookup(Foo.class)); }
void setPane(JEditorPane pane) { JEditorPane origPane = getPane(); if (origPane != null) { origPane.removePropertyChangeListener(this); origPane.getDocument().removeDocumentListener(this); } assert (pane != null); this.paneRef = new WeakReference<>(pane); pane.addPropertyChangeListener(this); pane.getDocument().addDocumentListener(this); updateState(); }
void updateState() { JEditorPane pane = getPane(); if (pane != null) { boolean rectangleSelection = RectangularSelectionUtils.isRectangularSelection(pane); JToggleButton toggleButton = getToggleButton(); if (toggleButton != null) { toggleButton.setSelected(rectangleSelection); toggleButton.setContentAreaFilled(rectangleSelection); toggleButton.setBorderPainted(rectangleSelection); } } }
/** * Maps {@code JEditorPane.getEditorKit()} through queue */ public EditorKit getEditorKit() { return (runMapping(new MapAction<EditorKit>("getEditorKit") { @Override public EditorKit map() { return ((JEditorPane) getSource()).getEditorKit(); } })); }
private JEditorPane getCurrentEditor () { Node[] ns = TopComponent.getRegistry ().getActivatedNodes (); if (ns.length != 1) return null; EditorCookie editorCookie = ns [0].getLookup (). lookup (EditorCookie.class); if (editorCookie == null) return null; if (editorCookie.getOpenedPanes () == null) return null; if (editorCookie.getOpenedPanes ().length < 1) return null; return editorCookie.getOpenedPanes () [0]; }
/** * Called when the kit is being installed into * a JEditorPane. * * @param c the JEditorPane */ public void install(JEditorPane c) { c.addCaretListener(inputAttributeUpdater); c.addPropertyChangeListener(inputAttributeUpdater); Caret caret = c.getCaret(); if (caret != null) { inputAttributeUpdater.updateInputAttributes (caret.getDot(), caret.getMark(), c); } }