Java Code Examples for org.openide.text.NbDocument#findRecentEditorPane()

The following examples show how to use org.openide.text.NbDocument#findRecentEditorPane() . 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: BasicSearchForm.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/**
 * Set currently selected text (in editor) as "Text to find" value.
 */
public void useCurrentlySelectedText() {
    Node[] arr = TopComponent.getRegistry().getActivatedNodes();
    if (arr.length > 0) {
        EditorCookie ec = arr[0].getLookup().lookup(EditorCookie.class);
        if (ec != null) {
            JEditorPane recentPane = NbDocument.findRecentEditorPane(ec);
            if (recentPane != null) {
                String initSearchText = recentPane.getSelectedText();
                if (initSearchText != null) {
                    cboxTextToFind.setSearchPattern(SearchPattern.create(
                            initSearchText, false, false, false));
                    searchCriteria.setTextPattern(initSearchText);
                    return;
                }
            }
        }
    }
    searchCriteria.setTextPattern(
            cboxTextToFind.getSearchPattern().getSearchExpression());
}
 
Example 2
Source File: CallHierarchyTasks.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public static void resolveRoot(final Lookup lookup, final boolean searchFromBase, final boolean isCallerGraph, final Task<Call> rootCallback) {
        JavaSource js = null;
        RootResolver resolver = null;
        EditorCookie ec = lookup.lookup(EditorCookie.class);
        if (ec != null/*RefactoringActionsProvider.isFromEditor(ec)*/) {
            JEditorPane openedPane = NbDocument.findRecentEditorPane(ec);
            Document doc = ec.getDocument();
            js = JavaSource.forDocument(doc);
            resolver = new RootResolver(openedPane.getCaretPosition(), isCallerGraph, searchFromBase);
        }
//        else {
            // XXX resolve Node.class
//        }
        postResolveRoot(js, resolver, rootCallback);
    }
 
Example 3
Source File: JavaRefactoringActionDelegate.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * Determine if the action should be enabled.  By default, this method
 * checks for the presence of an open editor;  if <code>requiresSelection</code>
 * was passed to the constructor, it also depends on a text selection in that
 * editor being present.
 * @param context A Lookup containing either an EditorCookie or one or more
 *                Nodes whose lookup contains an EditorCookie
 * @return true if the action should be enabled, false otherwise
 */
protected boolean isEnabled(Lookup context) {
    EditorCookie ck = JavaRefactoringGlobalAction.getEditorCookie(context);
    boolean result = false;
    if(ck != null) {
        JEditorPane pane = NbDocument.findRecentEditorPane(ck);
        result = pane != null;
        if (requiresSelection) {
            result = result && (pane.getSelectionStart() != pane.getSelectionEnd());
        }
    }
    return result;
}
 
Example 4
Source File: RefactoringUtils.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public static boolean isFromEditor(EditorCookie ec) {
    if (ec != null && NbDocument.findRecentEditorPane(ec) != null) {
        TopComponent activetc = TopComponent.getRegistry().getActivated();
        if (activetc instanceof CloneableEditorSupport.Pane) {
            return true;
        }
    }
    return false;
}
 
Example 5
Source File: GetJavaWord.java    From netbeans with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example 6
Source File: GotoOppositeAction.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private FileObject getApplicableFileObject(int[] caretPosHolder) {
    if (!EventQueue.isDispatchThread()) {
        // Unsafe to ask for an editor pane from a random thread.
        // E.g. org.netbeans.lib.uihandler.LogRecords.write asking for getName().
        Collection<? extends FileObject> dobs = Utilities.actionsGlobalContext().lookupAll(FileObject.class);
        return dobs.size() == 1 ? dobs.iterator().next() : null;
    }

    // TODO: Use the new editor library to compute this:
    // JTextComponent pane = EditorRegistry.lastFocusedComponent();

    TopComponent comp = TopComponent.getRegistry().getActivated();
    if(comp == null) {
        return null;
    }
    Node[] nodes = comp.getActivatedNodes();
    if (nodes != null && nodes.length == 1) {
        if (comp instanceof CloneableEditorSupport.Pane) { //OK. We have an editor
            EditorCookie ec = nodes[0].getLookup().lookup(EditorCookie.class);
            if (ec != null) {
                JEditorPane editorPane = NbDocument.findRecentEditorPane(ec);
                if (editorPane != null) {
                    if (editorPane.getCaret() != null) {
                            caretPosHolder[0] = editorPane.getCaret().getDot();
                    }
                    Document document = editorPane.getDocument();
                    return Source.create(document).getFileObject();
                }
            }
        } else {
            return UICommonUtils.getFileObjectFromNode(nodes[0]);
        }
    }
    
    return null;
}
 
Example 7
Source File: GoToSymbolAction.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public SymbolDescriptor getSelectedSymbol() {
    SymbolDescriptor result = null;
    try {
        final JButton okButton = new JButton (NbBundle.getMessage(GoToSymbolAction.class, "CTL_OK"));
        final ContentProviderImpl cp = new ContentProviderImpl(okButton);
        final GoToPanelImpl panel = new GoToPanelImpl(cp);
        final Dialog dialog = DialogFactory.createDialog(title, panel, cp, okButton);
        cp.setDialog(dialog);
        
        Node[] arr = TopComponent.getRegistry ().getActivatedNodes();
        String initSearchText;
        if (arr.length > 0) {
            EditorCookie ec = arr[0].getCookie (EditorCookie.class);
            if (ec != null) {
                JEditorPane recentPane = NbDocument.findRecentEditorPane(ec);
                if (recentPane != null) {
                    initSearchText = org.netbeans.editor.Utilities.getSelectionOrIdentifier(recentPane);
                    if (initSearchText != null && org.openide.util.Utilities.isJavaIdentifier(initSearchText)) {
                        panel.setInitialText(initSearchText);
                    }
                }
            }
        }            
        
        dialog.setVisible(true);
        result = panel.getSelectedSymbol();

    } catch (IOException ex) {
        ErrorManager.getDefault().notify(ex);
    }
    return result;
}
 
Example 8
Source File: FileSearchAction.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private FileDescriptor[] getSelectedFiles() {
    FileDescriptor[] result = null;
    panel = new FileSearchPanel(this, findCurrentProject());
    dialog = createDialog(panel);

    Node[] arr = TopComponent.getRegistry ().getActivatedNodes();
    if (arr.length > 0) {
        EditorCookie ec = arr[0].getCookie (EditorCookie.class);
        if (ec != null) {
            JEditorPane recentPane = NbDocument.findRecentEditorPane(ec);
            if (recentPane != null) {
                String initSearchText = null;
                if (org.netbeans.editor.Utilities.isSelectionShowing(recentPane.getCaret())) {
                    initSearchText = recentPane.getSelectedText();
                }
                if (initSearchText != null) {
                    if (initSearchText.length() > 256) {
                        initSearchText = initSearchText.substring(0, 256);
                    }
                    panel.setInitialText(initSearchText);
                } else {
                    FileObject fo = arr[0].getLookup().lookup(FileObject.class);
                    if (fo != null) {
                        panel.setInitialText(fo.getNameExt());
                    }
                }
            }
        }
    }

    dialog.setVisible(true);
    result = panel.getSelectedFiles();
    return result;
}
 
Example 9
Source File: GoToTypeAction.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public Iterable<? extends TypeDescriptor> getSelectedTypes(final boolean visible, String initSearchText) {
    Iterable<? extends TypeDescriptor> result = Collections.emptyList();
    try {
        panel = new GoToPanel(this, multiSelection);
        dialog = createDialog(panel);

        if (initSearchText != null) {
            panel.setInitialText(initSearchText);
        } else {
            Node[] arr = TopComponent.getRegistry ().getActivatedNodes();
            if (arr.length > 0) {
                EditorCookie ec = arr[0].getCookie (EditorCookie.class);
                if (ec != null) {
                    JEditorPane recentPane = NbDocument.findRecentEditorPane(ec);
                    if (recentPane != null) {
                        initSearchText = org.netbeans.editor.Utilities.getSelectionOrIdentifier(recentPane);
                        if (initSearchText != null && org.openide.util.Utilities.isJavaIdentifier(initSearchText)) {
                            panel.setInitialText(initSearchText);
                        } else {
                            panel.setInitialText(arr[0].getName());
                        }
                    }
                }
            }
        }

        dialog.setVisible(visible);
        result = panel.getSelectedTypes();

    } catch (IOException ex) {
        ErrorManager.getDefault().notify(ex);
    }
    return result;
}
 
Example 10
Source File: HtmlSpecificRefactoringsProvider.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public boolean canExtractInlineStyle(Lookup lookup) {
    //the editor cookie is in the lookup only if the file is opened in the editor and is active
    EditorCookie ec = lookup.lookup(EditorCookie.class);
    if(ec == null) {
        return false;
    }

    //non-blocking call, return null if no document pane initialized yet
    JEditorPane pane = NbDocument.findRecentEditorPane(ec);
    if(pane == null) {
        return false;
    }
    return canExtractInlineStyle(ec.getDocument(), new OffsetRange(pane.getSelectionStart(), pane.getSelectionEnd()));
}
 
Example 11
Source File: EncapsulateFieldUI.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@Override
public RefactoringUI create(CompilationInfo info, TreePathHandle[] handles, FileObject[] files, NonRecursiveFolder[] packages) {
    EditorCookie ec = lookup.lookup(EditorCookie.class);
    if (ec == null) {
        return create(info, -1, handles);
    }
    JEditorPane textC = NbDocument.findRecentEditorPane(ec);
    if (textC == null) {
        return create(info, -1, handles);
    }
    int startOffset = textC.getSelectionStart();
    int endOffset = textC.getSelectionEnd();

    if (startOffset == endOffset) {
        //cursor position
        return create(info, startOffset, handles[0]);
    }

    //editor selection
    TreePath path = info.getTreeUtilities().pathFor(startOffset);
    if (path == null) {
        return null;
    }
    TreePath enclosingClass = JavaRefactoringUtils.findEnclosingClass(info, path, true, true, true, true, true);
    if (enclosingClass == null) {
        return null;
    }
    Element el = info.getTrees().getElement(enclosingClass);
    if (el == null) {
        return null;
    }
    if (!(el.getKind().isClass() || el.getKind().isInterface())) {
        el = info.getElementUtilities().enclosingTypeElement(el);
    }
    Collection<TreePathHandle> h = new ArrayList<TreePathHandle>();
    for (Element e : ElementFilter.fieldsIn(el.getEnclosedElements())) {
        //            SourcePositions sourcePositions = info.getTrees().getSourcePositions();
        Tree leaf = info.getTrees().getPath(e).getLeaf();
        int[] namespan = info.getTreeUtilities().findNameSpan((VariableTree) leaf);
        if (namespan != null) {
            long start = namespan[0]; //sourcePositions.getStartPosition(info.getCompilationUnit(), leaf);
            long end = namespan[1]; //sourcePositions.getEndPosition(info.getCompilationUnit(), leaf);
            if ((start <= endOffset && start >= startOffset)
                    || (end <= endOffset && end >= startOffset)) {
                h.add(TreePathHandle.create(e, info));
            }
        }
    }
    if (h.isEmpty()) {
        return create(info, startOffset, handles[0]);
    }
    return create(info, -1, h.toArray(new TreePathHandle[h.size()]));
}
 
Example 12
Source File: CssCaretAwareSourceTask.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private void runInEDT(Snapshot snapshot, Model model, final FileObject file, String mimeType, int caretOffset) {
    LOG.log(Level.FINER, "runInEDT(), file: {0}, caret: {1}", new Object[]{file, caretOffset});

    if (cancelled) {
        LOG.log(Level.FINER, "cancelled");
        return;
    }

    if (caretOffset == -1) {
        try {
            //dirty workaround
            DataObject dobj = DataObject.find(file);
            EditorCookie ec = dobj.getLookup().lookup(EditorCookie.class);
            if (ec != null) {
                JEditorPane pane = NbDocument.findRecentEditorPane(ec);
                if (pane != null) {
                    caretOffset = pane.getCaretPosition();
                }
            }

        } catch (DataObjectNotFoundException ex) {
            //possibly deleted file, give up
            return;

        }
        
        LOG.log(Level.INFO, "workarounded caret offset: {0}", caretOffset);
    }


    //find rule corresponding to the offset
    Rule rule = findRuleAtOffset(snapshot, model, caretOffset);
    //>>hack, remove once the css.lib css grammar gets finalized
    if(rule != null && rule.getSelectorsGroup() == null) {
        rule = null;
    }
    //<<hack
    
    
    if(rule != null) {
        //check whether the rule is virtual
        if(snapshot.getOriginalOffset(rule.getSelectorsGroup().getStartOffset()) == -1) {
            //virtual selector created for html source element with class or id attribute
            LOG.log(Level.FINER, "the found rule is virtual, exiting w/o change of the RuleEditor", caretOffset);
            return ;
        }
    }
    
    if (!mimeType.equals("text/css")) {
        //if not a css file, 
        //update the rule editor only if there's a rule in an embedded css code
        if (rule == null) {
            LOG.log(Level.FINER, "not a css file and rule not found at {0} offset, exiting w/o change of the RuleEditor", caretOffset);
            return;
        }
    }

    final CssStylesTC cssStylesTC = (CssStylesTC) WindowManager.getDefault().findTopComponent(CssStylesTC.ID);
    if (cssStylesTC == null) {
        return;
    }
    
    //update the RuleEditor TC name
    RuleEditorController controller = cssStylesTC.getRuleEditorController();
    LOG.log(Level.FINER, "SourceTask: calling controller.setModel({0})", model);
    controller.setModel(model);
    
    if (rule == null) {
        controller.setNoRuleState();
    } else {
        controller.setRule(rule);
    }
}
 
Example 13
Source File: ToggleBookmarkAction.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public static JTextComponent findComponent(Lookup lookup) {
    EditorCookie ec = lookup.lookup(EditorCookie.class);
    return ec == null ? null : NbDocument.findRecentEditorPane(ec);
}
 
Example 14
Source File: ShowHistoryAction.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@Override
protected void performAction(final Node[] activatedNodes) {                        
    VCSContext ctx = VCSContext.forNodes(activatedNodes);
    final Set<VCSFileProxy> rootSet = ctx.getRootFiles();                    

    final VCSFileProxy[] files = rootSet.toArray(new VCSFileProxy[rootSet.size()]);                
    if(!files[0].isFile()) {
        return;
    }

    VCSFileProxy file = files[0];
    FileObject fo = file.toFileObject();
    if(fo != null) {
        DataObject dataObject = null;
        try {
            dataObject = DataObject.find(fo);
        } catch (DataObjectNotFoundException ex) {
            History.LOG.log(Level.WARNING, null, ex);
        }
        if(dataObject != null) {
            
            if(!hasHistoryElement(dataObject)) {
                // there is no history element defined for this data object, so 
                // lets open in a separate TopComponent
                openLocalHistoryTC(files);
                return;
            }
            
            // activate the History tab if there is a opened TopComponent 
            // with a History MultiView element
            Set<TopComponent> tcs = TopComponent.getRegistry().getOpened();
            for (final TopComponent tc : tcs) {
                Lookup l = tc.getLookup();
                final DataObject tcDataObject = l.lookup(DataObject.class);
                if (tcDataObject != null && dataObject.equals(tcDataObject)) { 
                    final MultiViewHandler handler = MultiViews.findMultiViewHandler(tc);
                    if(handler != null) {
                        if(activateHistoryTab(handler, tc)) {
                            // done, history tab found and activated.
                            return;
                        }
                    } 
                }
            }
            
            final EditorCookie editorCookie = dataObject.getLookup().lookup(EditorCookie.class);
            if(editorCookie != null) {
                Runnable r = new Runnable() {
                    @Override
                    public void run() {
                        JEditorPane pane = NbDocument.findRecentEditorPane(editorCookie);
                        if(pane != null) {
                            // editor is oen, though we havent found a multiview => open the LH top component
                            openLocalHistoryTC(files);
                        }
                    }
                };
                if(SwingUtilities.isEventDispatchThread()) {
                    r.run();
                } else {
                    SwingUtilities.invokeLater(r);
                }
            }
           
            EditCookie editCookie = dataObject.getLookup().lookup(EditCookie.class);
            if(editCookie != null) {
            // no editor found, lets open it...
                // editcookie might return imediately, so listen for the TC 
                // to be opened and activate then
                TopComponent.getRegistry().addPropertyChangeListener(new TCOpenedListener(dataObject, files));
                editCookie.edit();
                return;
            }
        }
    }
    openLocalHistoryTC(files);
}
 
Example 15
Source File: InsertI18nStringAction.java    From netbeans with Apache License 2.0 2 votes vote down vote up
/**
 * Checks whether at least one opened editor pane exists.
 * @param ec the {@code EditorCookie} associated to the editor pane.
 * @return (@code true} if the editor pane associated with the specified 
 * {@code EditorCookie} exists, otherwise (@code false}.
 * @see Bug 188430
 */
private boolean hasOpenedPane(EditorCookie ec) {
    JEditorPane pane = NbDocument.findRecentEditorPane(ec);
    return pane != null;
}