Java Code Examples for org.netbeans.editor.Utilities#getFocusedComponent()

The following examples show how to use org.netbeans.editor.Utilities#getFocusedComponent() . 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: JspPaletteActions.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void actionPerformed(ActionEvent e) {

      ActiveEditorDrop drop = (ActiveEditorDrop) item.lookup(ActiveEditorDrop.class);
      
      JTextComponent target = Utilities.getFocusedComponent();
      if (target == null) {
          String msg = NbBundle.getMessage(JspPaletteActions.class, "MSG_ErrorNoFocusedDocument");
          DialogDisplayer.getDefault().notify(new NotifyDescriptor.Message(msg, NotifyDescriptor.ERROR_MESSAGE));
          return;
      }
      
      try {
          drop.handleTransfer(target);
      }
      finally {
          Utilities.requestFocus(target);
      }
      
      try {
          PaletteController pc = JspPaletteFactory.getPalette();
          pc.clearSelection();
      }
      catch (IOException ioe) {
          //should not occur
      } 
  }
 
Example 2
Source File: SurroundWithHint.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public void implement() throws Exception {
    EditList edits = new EditList(baseDoc);

    int start = context.selectionStart;
    int end = context.selectionEnd;

    JTextComponent component = Utilities.getFocusedComponent();

    switch (operation) {
        case COMMENT_OUT:
            edits.replace(end, 0, "*/", false, 0);
            edits.replace(start, 0, "/*", false, 1);
            edits.apply();

            // Clear selection 
            component.setCaretPosition(start);

            break;
        case ADD_IF:
            String START_INSERT = "if (true) {\n";
            String END_INSERT = "\n}";

            edits.replace(end, 0, END_INSERT, false, 0);

            int startOfRow = Utilities.getRowStart(baseDoc, start);

            edits.replace(startOfRow, 0, START_INSERT, false, 1);
            edits.setFormatAll(true);
            edits.apply();

            component.setCaretPosition(start + 4);
            component.moveCaretPosition(start + 8);

            break;
    }
}
 
Example 3
Source File: JSFConfigHyperlinkProvider.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private String[] getElementValue(javax.swing.text.Document doc, int offset){
    String tag = null;
    String value = null;

    try {
        BaseDocument bdoc = (BaseDocument) doc;
        JTextComponent target = Utilities.getFocusedComponent();

        if (target == null || target.getDocument() != bdoc)
            return null;
        ExtSyntaxSupport sup = (ExtSyntaxSupport)bdoc.getSyntaxSupport();
        TokenItem token = sup.getTokenChain(offset, offset+1);
        if (token == null || token.getTokenID().getNumericID() != JSFEditorUtilities.XML_TEXT)
            return null;
        value = token.getImage();
        if (value != null){
            String original = value;
            value = value.trim();
            valueOffset = token.getOffset()+(original.indexOf(value));
        }
        // Find element
        // 4 - tag
        while(token != null
                && !(token.getTokenID().getNumericID() == JSFEditorUtilities.XML_ELEMENT
                && !token.getImage().equals(">")))
            token = token.getPrevious();
        if (token == null)
            return null;
        tag = token.getImage().substring(1);
        if (debug) debug ("element: " + tag );   // NOI18N
        if (debug) debug ("value: " + value );  //NOI18N
        return new String[]{tag, value};

    }
    catch (BadLocationException e) {
        Exceptions.printStackTrace(e);
    }
    return null;
}
 
Example 4
Source File: StrutsConfigHyperlinkProvider.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@NbBundle.Messages({
        "lbl.goto.formbean.not.found=ActionForm Bean {0} not found."
    })
private void findForm(String name, BaseDocument doc){
    ExtSyntaxSupport sup = (ExtSyntaxSupport)doc.getSyntaxSupport();
    
    int offset = findDefinitionInSection(sup, "form-beans", "form-bean", "name", name);
    if (offset > 0){
        JTextComponent target = Utilities.getFocusedComponent();
        target.setCaretPosition(offset);
    } else {
        StatusDisplayer.getDefault().setStatusText(Bundle.lbl_goto_formbean_not_found(name));
    }
}
 
Example 5
Source File: PHPPaletteActions.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public void actionPerformed(ActionEvent event) {

    ActiveEditorDrop drop = (ActiveEditorDrop) item.lookup(ActiveEditorDrop.class);

    JTextComponent target = Utilities.getFocusedComponent();
    if (target == null) {
        String msg = NbBundle.getMessage(PHPPaletteActions.class, "MSG_ErrorNoFocusedDocument");
        DialogDisplayer.getDefault().notify(new NotifyDescriptor.Message(msg, NotifyDescriptor.ERROR_MESSAGE));
        return;
    }
    if (drop == null) {
        Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).log(Level.INFO, "{0} doesn''t provide {1}", new Object[]{item.getClass(), ActiveEditorDrop.class}); //NOI18N
        return;
    }
    try {
        drop.handleTransfer(target);
    } finally {
        Utilities.requestFocus(target);
    }

    try {
        PaletteController paletteController = PHPPaletteFactory.getPalette();
        paletteController.clearSelection();
    } catch (IOException ioe) {
        Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).log(Level.INFO, null, ioe);
    }

}
 
Example 6
Source File: TwigPaletteFactory.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@NbBundle.Messages("TwigPaletteInsertAction.ErrorNoFocusedDocument=No document selected. Please select a document to insert the item into.")
@Override
public void actionPerformed(ActionEvent event) {

    ActiveEditorDrop drop = item.lookup(ActiveEditorDrop.class);

    JTextComponent target = Utilities.getFocusedComponent();
    if (target == null) {
        String msg = Bundle.TwigPaletteInsertAction_ErrorNoFocusedDocument();
        DialogDisplayer.getDefault().notify(new NotifyDescriptor.Message(msg, NotifyDescriptor.ERROR_MESSAGE));
        return;
    }

    if (drop == null) {
        Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).log(Level.INFO, "{0} doesn''t provide {1}", new Object[]{item.getClass(), ActiveEditorDrop.class}); //NOI18N
        return;
    }

    try {
        drop.handleTransfer(target);
    } finally {
        Utilities.requestFocus(target);
    }

    try {
        PaletteController paletteController = TwigPaletteFactory.createPalette();
        paletteController.clearSelection();
    } catch (IOException ioe) {
        Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).log(Level.INFO, null, ioe);
    }

}
 
Example 7
Source File: CompletionActionsMainMenu.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/** Sets the state of JMenuItem*/
protected @Override void setMenu(){
    
    ActionMap am = getContextActionMap();
    Action action = null;
    if (am != null) {
        action = am.get(getActionName());
    }
    
    JMenuItem presenter = getMenuPresenter();
    Action presenterAction = presenter.getAction();
    if (presenterAction == null){
        presenter.setAction(this);
        presenter.setToolTipText(null); /* bugfix #62872 */ 
        menuInitialized = false;
    } 
    else {
        if (!this.equals(presenterAction)){
            presenter.setAction(this);
            presenter.setToolTipText(null); /* bugfix #62872 */
            menuInitialized = false;
        }
    }

    if (!menuInitialized){
        Mnemonics.setLocalizedText(presenter, getMenuItemText());
        menuInitialized = true;
    }

    presenter.setEnabled(action != null);
    JTextComponent comp = Utilities.getFocusedComponent();
    if (comp != null && comp instanceof JEditorPane){
        addAccelerators(this, presenter, comp);
    } else {
        presenter.setAccelerator(getDefaultAccelerator());
    }

}
 
Example 8
Source File: HtmlPaletteActions.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void actionPerformed(ActionEvent e) {

      ActiveEditorDrop drop = (ActiveEditorDrop) item.lookup(ActiveEditorDrop.class);
      JTextComponent target = Utilities.getFocusedComponent();
      if (target == null) {
          String msg = NbBundle.getMessage(HtmlPaletteActions.class, "MSG_ErrorNoFocusedDocument"); //NOI18N
          DialogDisplayer.getDefault().notify(new NotifyDescriptor.Message(msg, NotifyDescriptor.ERROR_MESSAGE));
          return;
      }
      
      try {
          drop.handleTransfer(target);
      }
      finally {
          Utilities.requestFocus(target);
      }
      
      try {
          FileObject fo = DataLoadersBridge.getDefault().getFileObject(target);
          if(fo != null) {
              PaletteController pc = HtmlPaletteFactory.getPalette(fo.getMIMEType());
              pc.clearSelection();
          }
      }
      catch (IOException ignored) {
      }

  }
 
Example 9
Source File: InvokeOperationAction.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@Override
    protected void performAction(Node[] activatedNodes) {
        if(activatedNodes[0] != null) {
            FileObject currentFO = getCurrentFileObject(activatedNodes[0]);
            if(currentFO != null) {
                // !PW I wrote this code before I knew about NodeOperation.  Anyway, this
                // behaves a bit nicer in that the root node is hidden and the tree opens
                // up expanded.  Both improve usability for this use case I think.
                InvokeOperationCookie invokeOp = WebServiceActionProvider.getInvokeOperationAction(currentFO);
                InvokeOperationCookie.ClientSelectionPanel serviceExplorer = invokeOp.getDialogDescriptorPanel();
                final DialogDescriptor descriptor = new DialogDescriptor(serviceExplorer,
                        NbBundle.getMessage(InvokeOperationAction.class, "TTL_SelectOperation"));

                // !PW FIXME put help context here when known to get a displayed help button on the panel.
//                descriptor.setHelpCtx(new HelpCtx("HelpCtx_J2eePlatformInstallRootQuery"));
//                Dialog dlg = DialogDisplayer.getDefault().createDialog(descriptor);
//                dlg.getAccessibleContext().setAccessibleDescription(dlg.getTitle());
//                dlg.setVisible(true);
                serviceExplorer.addPropertyChangeListener(
                        InvokeOperationCookie.ClientSelectionPanel.PROPERTY_SELECTION_VALID,
                        new PropertyChangeListener() {
                            @Override
                            public void propertyChange(PropertyChangeEvent evt) {
                                descriptor.setValid(((Boolean)evt.getNewValue()));
                            }

                        });
                descriptor.setValid(false);
                DialogDisplayer.getDefault().notify(descriptor);
                if (descriptor.getValue().equals(NotifyDescriptor.OK_OPTION)) {
                    // !PW FIXME refactor this as a method implemented in a cookie
                    // on the method node.
                    InvokeOperationCookie invokeCookie = WebServiceActionProvider.getInvokeOperationAction(currentFO);
                    //JTextComponent textComp = activatedNodes[0].getLookup().lookup(JTextComponent.class);

                    if (invokeCookie!=null) {
                        JTextComponent target = Utilities.getFocusedComponent();
                        if (target != null) {
                            invokeCookie.invokeOperation(serviceExplorer.getSelectedClient(), target);
                        }
                        // logging usage of action
                        Object[] params = new Object[2];
                        String cookieClassName = invokeCookie.getClass().getName();
                        if (cookieClassName.contains("jaxrpc")) { // NOI18N
                            params[0] = LogUtils.WS_STACK_JAXRPC;
                        } else {
                            params[0] = LogUtils.WS_STACK_JAXWS;
                        }
                        params[1] = "CALL WS OPERATION"; // NOI18N
                        LogUtils.logWsAction(params);
                    }
                }
            }
        }
    }
 
Example 10
Source File: StrutsConfigHyperlinkProvider.java    From netbeans with Apache License 2.0 4 votes vote down vote up
/** This method finds the value for an attribute of element of on the offset.
 * @return Returns null, when the offset is not a value of an attribute. If the there is value
 * of an attribute, then returns String array [element, attribute, value].
 */
private String[] getElementAttrValue(javax.swing.text.Document doc, int offset){
    String attribute = null;
    String tag = null;
    String value = null;
    
    try {
        BaseDocument bdoc = (BaseDocument) doc;
        JTextComponent target = Utilities.getFocusedComponent();
        
        if (target == null || target.getDocument() != bdoc)
            return null;
        
        ExtSyntaxSupport sup = (ExtSyntaxSupport)bdoc.getSyntaxSupport();
        //TokenID tokenID = sup.getTokenID(offset);
        TokenItem token = sup.getTokenChain(offset, offset+1);
        //if (debug) debug ("token: "  +token.getTokenID().getNumericID() + ":" + token.getTokenID().getName());
        // when it's not a value -> do nothing.
        if (token == null || token.getTokenID().getNumericID() != StrutsEditorUtilities.XML_ATTRIBUTE_VALUE)
            return null;
        value = token.getImage();
        if (value != null){
            // value = value.substring(0, offset - token.getOffset());
            //if (debug) debug ("value to cursor: " + value);
            value = value.trim();
            valueOffset = token.getOffset();
            if (value.charAt(0) == '"') {
                value = value.substring(1);
                valueOffset ++;
            }
            
            if (value.length() > 0  && value.charAt(value.length()-1) == '"') value = value.substring(0, value.length()-1);
            value = value.trim();
            //if (debug) debug ("value: " + value);
        }
        
        //if (debug) debug ("Token: " + token);
        // Find attribute and tag
        // 5 - attribute
        // 4 - tag
        while(token != null && token.getTokenID().getNumericID() != StrutsEditorUtilities.XML_ATTRIBUTE
                && token.getTokenID().getNumericID() != StrutsEditorUtilities.XML_ELEMENT)
            token = token.getPrevious();
        if (token != null && token.getTokenID().getNumericID() == StrutsEditorUtilities.XML_ATTRIBUTE){
            attribute = token.getImage();
            while(token != null && token.getTokenID().getNumericID() != StrutsEditorUtilities.XML_ELEMENT)
                token = token.getPrevious();
            if (token != null && token.getTokenID().getNumericID() == StrutsEditorUtilities.XML_ELEMENT)
                tag = token.getImage();
        }
        if (attribute == null || tag == null)
            return null;
        tag = tag.substring(1);
        if (debug) debug("element: " + tag );   // NOI18N
        if (debug) debug("attribute: " + attribute ); //NOI18N
        if (debug) debug("value: " + value );  //NOI18N
        return new String[]{tag, attribute, value};
    } catch (BadLocationException e) {
    }
    return null;
}
 
Example 11
Source File: StrutsConfigHyperlinkProvider.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private void findResourcePath(String path, BaseDocument doc){
    path = path.trim();
    if (debug) debug("path: " + path);
    if (path.indexOf('?') > 0){
        // remove query from the path
        path = path.substring(0, path.indexOf('?'));
    }
    WebModule wm = WebModule.getWebModule(NbEditorUtilities.getFileObject(doc));
    if (wm != null){
        FileObject docBase= wm.getDocumentBase();
        FileObject fo = docBase.getFileObject(path);
        if (fo == null){
            // maybe an action
            String servletMapping = StrutsConfigUtilities.getActionServletMapping(wm.getDeploymentDescriptor());
            if (servletMapping != null){
                String actionPath = null;
                if (servletMapping != null && servletMapping.lastIndexOf('.')>0){
                    // the mapping is in *.xx way
                    String extension = servletMapping.substring(servletMapping.lastIndexOf('.'));
                    if (path.endsWith(extension))
                        actionPath = path.substring(0, path.length()-extension.length());
                    else
                        actionPath = path;
                } else{
                    // the mapping is /xx/* way
                    servletMapping = servletMapping.trim();
                    String prefix = servletMapping.substring(0, servletMapping.length()-2);
                    if (path.startsWith(prefix))
                        actionPath = path.substring(prefix.length(), path.length());
                    else
                        actionPath = path;
                }
                if (debug) debug(" actionPath: " + actionPath);
                if(actionPath != null){
                    ExtSyntaxSupport sup = (ExtSyntaxSupport)doc.getSyntaxSupport();
                    int offset = findDefinitionInSection(sup, "action-mappings","action","path", actionPath);
                    if (offset > 0){
                        JTextComponent target = Utilities.getFocusedComponent();
                        target.setCaretPosition(offset);
                    }
                }
            }
        } else
            openInEditor(fo);
    }
}
 
Example 12
Source File: NbCodeFoldingAction.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private static JTextComponent getComponent(){
    return Utilities.getFocusedComponent();
}
 
Example 13
Source File: MainMenuAction.java    From netbeans with Apache License 2.0 4 votes vote down vote up
/** Returns focused editor component */
private static JTextComponent getComponent(){
    return Utilities.getFocusedComponent();
}