Java Code Examples for javax.swing.text.JTextComponent#getDocument()

The following examples show how to use javax.swing.text.JTextComponent#getDocument() . 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: ActionUtils.java    From jpexs-decompiler with GNU General Public License v3.0 6 votes vote down vote up
/**
 * If the selection is multi lined, then the full lines are selected,
 * otherwise, nothing is done.
 * @param target
 * @return true if the selection is multi-line, or a whole line
 */
public static boolean selectLines(JTextComponent target) {
	if (target.getSelectionStart() == target.getSelectionEnd()) {
		return false;
	}
	PlainDocument pDoc = (PlainDocument) target.getDocument();
	Element es = pDoc.getParagraphElement(target.getSelectionStart());
	// if more than one line is selected, we need to subtract one from the end
	// so that we do not select the line with the caret and no selection in it
	Element ee = pDoc.getParagraphElement(target.getSelectionEnd() - 1);
	if (es.equals(ee) && ee.getEndOffset() != target.getSelectionEnd()) {
		return false;
	}
	int start = es.getStartOffset();
	int end = ee.getEndOffset();
	target.select(start, end - 1);
	return true;
}
 
Example 2
Source File: WordMatch.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private Document getNextDocument() {
    // Initially documentIndex == -1
    if (documentIndex == documents.size() - 1) { // Check adding
        if (documentSet.isEmpty()) { // documents list not inited yet -> add 'doc'
            documentSet.put(doc, Boolean.TRUE);
        }
        for (JTextComponent tc : EditorRegistry.componentList()) {
            Document d = tc.getDocument();
            if (!documentSet.containsKey(d)) {
                documentSet.put(d, Boolean.TRUE);
                documents.add(new WeakReference<Document>(d));
            }
        }
    }
    Document retDoc = null;
    while (documentIndex < documents.size() - 1) {
        documentIndex++;
        retDoc = documents.get(documentIndex).get();
        if (retDoc != null) {
            break;
        }
    }
    return retDoc;
}
 
Example 3
Source File: CompletionSupport.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void processKeyEvent (KeyEvent evt) {
    if (evt.getID() == KeyEvent.KEY_TYPED) {
        char c = evt.getKeyChar();
        JTextComponent component = (JTextComponent)evt.getSource();
        if (confirmChars == null) {
            confirmChars = getConfirmChars(component);
        }
        if (confirmChars.indexOf(c) != -1) {
            if (c != '.') {
                Completion.get().hideDocumentation();
                Completion.get().hideCompletion();
            }
            NbEditorDocument doc = (NbEditorDocument) component.getDocument ();
            try {
                defaultAction(component);
                doc.insertString(processKeyEventOffset, Character.toString(c), null);
            } catch (BadLocationException e) {
            }
            if (c == '.')
                Completion.get().showCompletion();
            evt.consume();
        } // if
    } // if
}
 
Example 4
Source File: TextActions.java    From rapidminer-studio with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public void actionPerformed(ActionEvent e) {
	JTextComponent target = getTextComponent(e);
	boolean beep = true;
	if ((target != null) && (target.isEditable())) {
		try {
			Document doc = target.getDocument();
			int ss = 0;
			int se = doc.getLength();

			if (ss != se) {
				doc.remove(ss, se - ss);
				beep = false;
			}
		} catch (BadLocationException bl) {
		}
	}
	if (beep) {
		UIManager.getLookAndFeel().provideErrorFeedback(target);
	}
}
 
Example 5
Source File: ToggleBlockCommentAction.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
public void actionPerformed(ActionEvent evt, JTextComponent target) {
    final AtomicBoolean processedHere = new AtomicBoolean(false);
    if (target != null) {
        if (!target.isEditable() || !target.isEnabled() || !(target.getDocument() instanceof BaseDocument)) {
            target.getToolkit().beep();
            return;
        }
        final Positions positions = Positions.create(target);
        final BaseDocument doc = (BaseDocument) target.getDocument();
        doc.runAtomic(new Runnable() {

            @Override
            public void run() {
                performCustomAction(doc, positions, processedHere);
            }
        });
        if (!processedHere.get()) {
            performDefaultAction(evt, target);
        }
    }
}
 
Example 6
Source File: JspCompletionItem.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
public void defaultAction(JTextComponent component) {
    super.defaultAction(component);
    final BaseDocument doc = (BaseDocument) component.getDocument();

    doc.runAtomic(new Runnable() {

        @Override
        public void run() {
            try {
                doc.insertString(Util.findPositionForJspDirective(doc),
                        "<%@ taglib prefix=\"" //NOI18N
                        + tagLibPrefix + "\" uri=\"" //NOI18N
                        + tagLibURI + "\" %>\n", null);     //NOI18N

            } catch (BadLocationException ex) {
                Exceptions.printStackTrace(ex);
            }
        }
    });
}
 
Example 7
Source File: CamelCaseOperations.java    From netbeans with Apache License 2.0 6 votes vote down vote up
static int nextCamelCasePosition(JTextComponent textComponent) {
    int offset = textComponent.getCaretPosition();
    Document doc = textComponent.getDocument();

    // Are we at the end of the document?
    if (offset == doc.getLength()) {
        return -1;
    }

    KeystrokeHandler bc = UiUtils.getBracketCompletion(doc, offset);
    if (bc != null) {
        int nextOffset = bc.getNextWordOffset(doc, offset, false);
        if (nextOffset != -1) {
            return nextOffset;
        }
    }
    
    try {
        return Utilities.getNextWord(textComponent, offset);
    } catch (BadLocationException ble) {
        // something went wrong :(
        ErrorManager.getDefault().notify(ble);
    }
    return -1;
}
 
Example 8
Source File: ActionUtils.java    From visualvm with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Return the lines that span the selection (split as an array of Strings)
 * if there is no selection then current line is returned.
 * 
 * Note that the strings returned will not contain the terminating line feeds
 * 
 * The text component will then have the full lines set as selection
 * @param target
 * @return String[] of lines spanning selection / or Dot
 */
public static String[] getSelectedLines(JTextComponent target) {
    String[] lines = null;
    try {
        PlainDocument pDoc = (PlainDocument) target.getDocument();
        int start = pDoc.getParagraphElement(target.getSelectionStart()).getStartOffset();
        int end;
        if (target.getSelectionStart() == target.getSelectionEnd()) {
            end = pDoc.getParagraphElement(target.getSelectionEnd()).getEndOffset();
        } else {
            // if more than one line is selected, we need to subtract one from the end
            // so that we do not select the line with the caret and no selection in it
            end = pDoc.getParagraphElement(target.getSelectionEnd() - 1).getEndOffset();
        }
        target.select(start, end);
        lines = pDoc.getText(start, end - start).split("\n");
        target.select(start, end);
    } catch (BadLocationException ex) {
        Logger.getLogger(ActionUtils.class.getName()).log(Level.SEVERE, null, ex);
        lines = EMPTY_STRING_ARRAY;
    }
    return lines;
}
 
Example 9
Source File: MainPanel.java    From java-swing-tips with MIT License 6 votes vote down vote up
private static void setHighlight(JTextComponent jtc, String pattern) {
  Highlighter highlighter = jtc.getHighlighter();
  highlighter.removeAllHighlights();
  try {
    Document doc = jtc.getDocument();
    String text = doc.getText(0, doc.getLength());
    Matcher matcher = Pattern.compile(pattern).matcher(text);
    int pos = 0;
    while (matcher.find(pos) && !matcher.group().isEmpty()) {
      pos = matcher.end();
      highlighter.addHighlight(matcher.start(), pos, HIGHLIGHT);
    }
    // while ((pos = text.indexOf(pattern, pos)) >= 0) {
    //   highlighter.addHighlight(pos, pos + pattern.length(), HIGHLIGHT);
    //   pos += pattern.length();
    // }
  } catch (BadLocationException | PatternSyntaxException ex) {
    UIManager.getLookAndFeel().provideErrorFeedback(jtc);
  }
}
 
Example 10
Source File: ElementTreePanel.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Resets the JTextComponent to <code>editor</code>. This will update
 * the tree accordingly.
 */
public void setEditor(JTextComponent editor) {
    if (this.editor == editor) {
        return;
    }

    if (this.editor != null) {
        Document oldDoc = this.editor.getDocument();

        oldDoc.removeDocumentListener(this);
        this.editor.removePropertyChangeListener(this);
        this.editor.removeCaretListener(this);
    }
    this.editor = editor;
    if (editor == null) {
        treeModel = null;
        tree.setModel(null);
    } else {
        Document newDoc = editor.getDocument();

        newDoc.addDocumentListener(this);
        editor.addPropertyChangeListener(this);
        editor.addCaretListener(this);
        treeModel = new ElementTreeModel(newDoc);
        tree.setModel(treeModel);
    }
}
 
Example 11
Source File: Install.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public synchronized void propertyChange(PropertyChangeEvent evt) {
    JTextComponent jtc = EditorRegistry.focusedComponent();
    if (jtc == null) return;
    
    Document active = jtc.getDocument();
    Object sourceProperty = active.getProperty(Document.StreamDescriptionProperty);
    if (!(sourceProperty instanceof DataObject)) return;

    FileObject activeFile = ((DataObject)sourceProperty).getPrimaryFile();
    TimesCollectorPeer.getDefault().select(activeFile);
}
 
Example 12
Source File: Utilities.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/** Get the identifier around the given position or null if there's no identifier
 * around the given position. The identifier is not verified against SyntaxSupport.isIdentifier().
 * @param c JTextComponent to work on
 * @param offset position in document - usually the caret.getDot()
 * @return the block (starting and ending position) enclosing the identifier
 * or null if no identifier was found
 */
public static int[] getIdentifierBlock(JTextComponent c, int offset)
throws BadLocationException {
    CharSequence id = null;
    int[] ret = null;
    Document doc = c.getDocument();
    int idStart = javax.swing.text.Utilities.getWordStart(c, offset);
    if (idStart >= 0) {
        int idEnd = javax.swing.text.Utilities.getWordEnd(c, idStart);
        if (idEnd >= 0) {
            id = DocumentUtilities.getText(doc, idStart, idEnd - idStart);
            ret = new int[] { idStart, idEnd };
            CharSequence trim = CharSequenceUtilities.trim(id);
            if (trim.length() == 0 || (trim.length() == 1 && !Character.isJavaIdentifierPart(trim.charAt(0)))) {
                int prevWordStart = javax.swing.text.Utilities.getPreviousWord(c, offset);
                if (offset == javax.swing.text.Utilities.getWordEnd(c,prevWordStart )){
                    ret = new int[] { prevWordStart, offset };
                } else {
                    return null;
                }
            } else if ((id != null) && (id.length() != 0)  && (CharSequenceUtilities.indexOf(id, '.') != -1)){ //NOI18N
                int index = offset - idStart;
                int begin = CharSequenceUtilities.lastIndexOf(id.subSequence(0, index), '.');
                begin = (begin == -1) ? 0 : begin + 1; //first index after the dot, if exists
                int end = CharSequenceUtilities.indexOf(id, '.', index);
                end = (end == -1) ? id.length() : end;
                ret = new int[] { idStart+begin, idStart+end };
            }
        }
    }
    return ret;
}
 
Example 13
Source File: ActionUtils.java    From visualvm with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Gets the Line Number at the give position of the editor component.
 * The first line number is ZERO
 * @param editor
 * @param pos
 * @return line number
 * @throws javax.swing.text.BadLocationException
 */
public static int getLineNumber(JTextComponent editor, int pos)
        throws BadLocationException {
    if (getSyntaxDocument(editor) != null) {
        SyntaxDocument sdoc = getSyntaxDocument(editor);
        return sdoc.getLineNumberAt(pos);
    } else {
        Document doc = editor.getDocument();
        return doc.getDefaultRootElement().getElementIndex(pos);
    }
}
 
Example 14
Source File: CaretBasedBlockHighlighting.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/** Creates a new instance of CaretSelectionLayer */
protected CaretBasedBlockHighlighting(JTextComponent component, String coloringName, boolean extendsEOL, boolean extendsEmptyLine) {
    // Determine the mime type
    String mimeType = BlockHighlighting.getMimeType(component);
    this.mimePath = mimeType == null ? MimePath.EMPTY : MimePath.parse(mimeType);

    this.coloringName = coloringName;
    this.extendsEOL = extendsEOL;
    this.extendsEmptyLine = extendsEmptyLine;
    
    // Hook up the component
    this.component = component;
    
    selectionsBag = new PositionsBag(component.getDocument(), false);
}
 
Example 15
Source File: HtmlCompletionProvider.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
protected boolean canFilter(JTextComponent component) {
    try {
        if (component.getCaret() == null || component.getCaretPosition() < anchor) {
            return false;
        }
        
        Document doc = component.getDocument();
        int offset = component.getCaretPosition();

        String prefix = doc.getText(anchor, offset - anchor);

        //check the items
        for (CompletionItem item : items) {
            if (item instanceof HtmlCompletionItem) {
                String itemText = ((HtmlCompletionItem) item).getItemText();
                if(itemText != null) { //http://netbeans.org/bugzilla/show_bug.cgi?id=222234
                    if (startsWithIgnoreCase(itemText, prefix)) {
                        return true; //at least one item will remain
                    }
                } else {
                    LOG.log(Level.WARNING, "CompletionItem {0} returned null from getItemText()!", item);
                }
            }
        }


    } catch (BadLocationException ex) {
        Exceptions.printStackTrace(ex);
    }

    return false;

}
 
Example 16
Source File: BaseCaret.java    From netbeans with Apache License 2.0 4 votes vote down vote up
/**
 * Extend rectangular selection either by char in a specified selection
 * or by word (if ctrl is pressed).
 *
 * @param toRight true for right or false for left.
 * @param ctrl 
 */
public void extendRectangularSelection(boolean toRight, boolean ctrl) {
    JTextComponent c = component;
    Document doc = c.getDocument();
    int dotOffset = getDot();
    Element lineRoot = doc.getDefaultRootElement();
    int lineIndex = lineRoot.getElementIndex(dotOffset);
    Element lineElement = lineRoot.getElement(lineIndex);
    float charWidth;
    LockedViewHierarchy lvh = ViewHierarchy.get(c).lock();
    try {
        charWidth = lvh.getDefaultCharWidth();
    } finally {
        lvh.unlock();
    }
    int newDotOffset = -1;
    try {
        int newlineOffset = lineElement.getEndOffset() - 1;
        Rectangle newlineRect = c.modelToView(newlineOffset);
        if (!ctrl) {
            if (toRight) {
                if (rsDotRect.x < newlineRect.x) {
                    newDotOffset = dotOffset + 1;
                } else {
                    rsDotRect.x += charWidth;
                }
            } else { // toLeft
                if (rsDotRect.x > newlineRect.x) {
                    rsDotRect.x -= charWidth;
                    if (rsDotRect.x < newlineRect.x) { // Fix on rsDotRect
                        newDotOffset = newlineOffset;
                    }
                } else {
                    newDotOffset = Math.max(dotOffset - 1, lineElement.getStartOffset());
                }
            }

        } else { // With Ctrl
            int numVirtualChars = 8; // Number of virtual characters per one Ctrl+Shift+Arrow press
            if (toRight) {
                if (rsDotRect.x < newlineRect.x) {
                    newDotOffset = Math.min(Utilities.getNextWord(c, dotOffset), lineElement.getEndOffset() - 1);
                } else { // Extend virtually
                    rsDotRect.x += numVirtualChars * charWidth;
                }
            } else { // toLeft
                if (rsDotRect.x > newlineRect.x) { // Virtually extended
                    rsDotRect.x -= numVirtualChars * charWidth;
                    if (rsDotRect.x < newlineRect.x) {
                        newDotOffset = newlineOffset;
                    }
                } else {
                    newDotOffset = Math.max(Utilities.getPreviousWord(c, dotOffset), lineElement.getStartOffset());
                }
            }
        }

        if (newDotOffset != -1) {
            rsDotRect = c.modelToView(newDotOffset);
            moveDot(newDotOffset); // updates rs and fires state change
        } else {
            updateRectangularSelectionPaintRect();
            fireStateChanged();
        }
    } catch (BadLocationException ex) {
        // Leave selection as is
    }
}
 
Example 17
Source File: ElementTreePanel.java    From jdk8u-dev-jdk with GNU General Public License v2.0 4 votes vote down vote up
@SuppressWarnings("LeakingThisInConstructor")
public ElementTreePanel(JTextComponent editor) {
    this.editor = editor;

    Document document = editor.getDocument();

    // Create the tree.
    treeModel = new ElementTreeModel(document);
    tree = new JTree(treeModel) {

        @Override
        public String convertValueToText(Object value, boolean selected,
                boolean expanded, boolean leaf,
                int row, boolean hasFocus) {
            // Should only happen for the root
            if (!(value instanceof Element)) {
                return value.toString();
            }

            Element e = (Element) value;
            AttributeSet as = e.getAttributes().copyAttributes();
            String asString;

            if (as != null) {
                StringBuilder retBuffer = new StringBuilder("[");
                Enumeration names = as.getAttributeNames();

                while (names.hasMoreElements()) {
                    Object nextName = names.nextElement();

                    if (nextName != StyleConstants.ResolveAttribute) {
                        retBuffer.append(" ");
                        retBuffer.append(nextName);
                        retBuffer.append("=");
                        retBuffer.append(as.getAttribute(nextName));
                    }
                }
                retBuffer.append(" ]");
                asString = retBuffer.toString();
            } else {
                asString = "[ ]";
            }

            if (e.isLeaf()) {
                return e.getName() + " [" + e.getStartOffset() + ", " + e.
                        getEndOffset() + "] Attributes: " + asString;
            }
            return e.getName() + " [" + e.getStartOffset() + ", " + e.
                    getEndOffset() + "] Attributes: " + asString;
        }
    };
    tree.addTreeSelectionListener(this);
    tree.setDragEnabled(true);
    // Don't show the root, it is fake.
    tree.setRootVisible(false);
    // Since the display value of every node after the insertion point
    // changes every time the text changes and we don't generate a change
    // event for all those nodes the display value can become off.
    // This can be seen as '...' instead of the complete string value.
    // This is a temporary workaround, increase the needed size by 15,
    // hoping that will be enough.
    tree.setCellRenderer(new DefaultTreeCellRenderer() {

        @Override
        public Dimension getPreferredSize() {
            Dimension retValue = super.getPreferredSize();
            if (retValue != null) {
                retValue.width += 15;
            }
            return retValue;
        }
    });
    // become a listener on the document to update the tree.
    document.addDocumentListener(this);

    // become a PropertyChangeListener to know when the Document has
    // changed.
    editor.addPropertyChangeListener(this);

    // Become a CaretListener
    editor.addCaretListener(this);

    // configure the panel and frame containing it.
    setLayout(new BorderLayout());
    add(new JScrollPane(tree), BorderLayout.CENTER);

    // Add a label above tree to describe what is being shown
    JLabel label = new JLabel("Elements that make up the current document",
            SwingConstants.CENTER);

    label.setFont(new Font("Dialog", Font.BOLD, 14));
    add(label, BorderLayout.NORTH);

    setPreferredSize(new Dimension(400, 400));
}
 
Example 18
Source File: ActionFactory.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@Override
public void actionPerformed (final ActionEvent evt, final JTextComponent target) {
    if (target != null) {
        if (!target.isEditable() || !target.isEnabled()) {
            target.getToolkit().beep();
            return;
        }
        final BaseDocument doc = (BaseDocument) target.getDocument();
        if (doc instanceof GuardedDocument && ((GuardedDocument) doc).isPosGuarded(target.getCaretPosition())) {
            target.getToolkit().beep();
            return;
        }
        doc.runAtomicAsUser (new Runnable () {
            @Override
            public void run () {
                DocumentUtilities.setTypingModification(doc, true);
                try {
                    Element rootElement = doc.getDefaultRootElement();

                    Caret caret = target.getCaret();
                    boolean selection = false;
                    boolean backwardSelection = false;
                    int start = target.getCaretPosition();
                    int end = start;
                    
                    // check if there is a selection
                    if (Utilities.isSelectionShowing(caret)) {
                        int selStart = caret.getDot();
                        int selEnd = caret.getMark();
                        start = Math.min(selStart, selEnd);
                        end =   Math.max(selStart, selEnd) - 1;
                        selection = true;
                        backwardSelection = (selStart >= selEnd);
                    }

                    int zeroBaseStartLineNumber = rootElement.getElementIndex(start);
                    int zeroBaseEndLineNumber = rootElement.getElementIndex(end);

                    if (zeroBaseEndLineNumber == -1) {
                        // could not get line number
                        target.getToolkit().beep();
                    } else {
                        try {
                            // get line text
                            Element startLineElement = rootElement.getElement(zeroBaseStartLineNumber);
                            int startLineStartOffset = startLineElement.getStartOffset();

                            Element endLineElement = rootElement.getElement(zeroBaseEndLineNumber);
                            int endLineEndOffset = endLineElement.getEndOffset();
                            if (endLineEndOffset > doc.getLength()) {
                                return;
                            }

                            String linesText = doc.getText(startLineStartOffset, (endLineEndOffset - startLineStartOffset));

                            Element nextLineElement = rootElement.getElement(zeroBaseEndLineNumber + 1);
                            int nextLineEndOffset = nextLineElement.getEndOffset();

                            int column = start - startLineStartOffset;

                            // insert it after next line
                            if (nextLineEndOffset > doc.getLength()) {
                                doc.insertString(doc.getLength(), "\n" + linesText.substring(0, linesText.length()-1), null);
                            } else {
                                doc.insertString(nextLineEndOffset, linesText, null);
                            }

                            // remove original line
                            removeLineByLine(doc, startLineStartOffset, (endLineEndOffset - startLineStartOffset));
                            if (selection) {
                                // select moved lines
                                if (backwardSelection) {
                                    if (doc.getLength() <  nextLineEndOffset) {
                                        caret.setDot(doc.getLength()  - (endLineEndOffset - startLineStartOffset) + column + 1);
                                        caret.moveDot(doc.getLength());
                                    } else {
                                        caret.setDot(nextLineEndOffset - (endLineEndOffset - startLineStartOffset) + column);
                                        caret.moveDot(nextLineEndOffset - (endLineEndOffset - end - 1));
                                    }
                                } else {
                                    caret.setDot(nextLineEndOffset - (endLineEndOffset - end - 1));
                                    caret.moveDot(nextLineEndOffset  - (endLineEndOffset - startLineStartOffset) + column);
                                }
                            } else {
                                // set caret position
                                target.setCaretPosition(Math.min(doc.getLength(), nextLineEndOffset + column - (endLineEndOffset - startLineStartOffset)));
                            }
                        } catch (BadLocationException ex) {
                            target.getToolkit().beep();
                        }
                    }
                } finally {
                    DocumentUtilities.setTypingModification(doc, false);
                }
            }
        });
    }
}
 
Example 19
Source File: CompletionSupport.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private String getConfirmChars (JTextComponent component) {
    NbEditorDocument doc = (NbEditorDocument) component.getDocument ();
    StringBuffer buf = new StringBuffer();
    int offset = component.getCaret ().getDot ();
    try {
        TokenHierarchy tokenHierarchy = TokenHierarchy.get (doc);
        if (doc instanceof NbEditorDocument) {
            ((NbEditorDocument) doc).readLock ();
        }
        try {
            TokenSequence sequence = tokenHierarchy.tokenSequence ();
            if (sequence.isEmpty()) {
                return ""; // NOI18N
            }
            
            //find most embedded token sequence on the specified offset
            while(true) {
                sequence.move (offset - 1);
                if (!sequence.moveNext()) {
                    return ""; // NOI18N
                }
                TokenSequence embedded = sequence.embedded ();
                if (embedded == null) break;
                sequence = embedded;
            }
            Token token = sequence.token ();
            String tokenType = token.id ().name ();
            String mimeType = sequence.language ().mimeType ();
            Language l = LanguagesManager.getDefault ().getLanguage (mimeType);
            List<Feature> features = l.getFeatureList ().getFeatures (CompletionProviderImpl.COMPLETION, tokenType);
            Iterator<Feature> it = features.iterator ();
            while (it.hasNext ()) {
                Feature feature =  it.next ();
                String confChars = (String) feature.getValue("confirmChars"); // NOI18N
                if (confChars != null) {
                    buf.append(confChars);
                }
            }
        } finally {
            if (doc instanceof NbEditorDocument)
                ((NbEditorDocument) doc).readUnlock ();
        }
    } catch (LanguageDefinitionNotFoundException ex) {
    }
    return buf.toString();
}
 
Example 20
Source File: RestClientEditorDrop.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private boolean doHandleTransfer(final JTextComponent targetComponent) {
    final Document targetDoc = targetComponent.getDocument();
    final FileObject targetSource = NbEditorUtilities.getFileObject(targetDoc);
    Project targetProject = FileOwnerQuery.getOwner(targetSource);
    Method m = method.getWadlMethod();
    if(m == null)
        Exceptions.printStackTrace(new IOException("Wadl method not found"));
    final String displayName = m.getName();
    
    targetFO = getTargetFile(targetDoc);

    if (targetFO == null) {
        return false;
    }

    final List<Exception> errors = new ArrayList<Exception>();
   
    final ProgressDialog dialog = new ProgressDialog(
            NbBundle.getMessage(RestClientEditorDrop.class, "LBL_CodeGenProgress", 
            displayName));

    generatorTask = RequestProcessor.getDefault().create(new Runnable() {
        public void run() {
            try {
                SaasClientCodeGenerator codegen = (SaasClientCodeGenerator) 
                        SaasClientCodeGenerationManager.lookup(method, targetDoc);
                codegen.init(method, targetDoc);
                codegen.setDropLocation(targetComponent);
            
                RestClientSaasBean bean = (RestClientSaasBean) codegen.getBean();
                List<ParameterInfo> allParams = bean.filterParametersByAuth(
                        bean.filterParameters(new ParamFilter[]{ParamFilter.FIXED}));
                boolean response = Util.showDialog(displayName, allParams, targetDoc);
                if(response)
                    Util.doGenerateCode(codegen, dialog, errors);
            } catch (Exception ioe) {
                if(Constants.UNSUPPORTED_DROP.equals(ioe.getMessage())) {
                    Util.showUnsupportedDropMessage(new Object[] {
                        targetSource.getNameExt(), "Java Client"});
                    return;
                }
                errors.add(ioe);
            } finally {
                dialog.close();
            }
        }
    });

    generatorTask.schedule(50);

    dialog.open();

    if (errors.size() > 0) {
        Exceptions.printStackTrace(errors.get(0));
        return false;
    }
    return true;
}