/** * This method causes a transfer to a component from a clipboard or a DND drop operation. The * Transferable represents the data to be imported into the component. * * @param comp The component to receive the transfer. This argument is provided to enable sharing * of TransferHandlers by multiple components. * @param t The data to import * @return <code>true</code> iff the data was inserted into the component. */ public boolean importData(JComponent comp, Transferable t) { JTextComponent c = (JTextComponent) comp; withinSameComponent = c == exportComp; // if we are importing to the same component that we exported from // then don't actually do anything if the drop location is inside // the drag location and set shouldRemove to false so that exportDone // knows not to remove any data if (withinSameComponent && c.getCaretPosition() >= p0 && c.getCaretPosition() <= p1) { shouldRemove = false; return true; } boolean imported = false; DataFlavor importFlavor = getImportFlavor(t.getTransferDataFlavors(), c); if (importFlavor != null) { try { InputContext ic = c.getInputContext(); if (ic != null) ic.endComposition(); Reader r = importFlavor.getReaderForText(t); handleReaderImport(r, c); imported = true; } catch (UnsupportedFlavorException ufe) { ufe.printStackTrace(); } catch (BadLocationException ble) { ble.printStackTrace(); } catch (IOException ioe) { ioe.printStackTrace(); } } return imported; }
@Override protected final void actionPerformed(PhpModule phpModule) { // called via shortcut if (!CakePhpUtils.isCakePHP(phpModule)) { return; } JTextComponent editor = EditorRegistry.lastFocusedComponent(); if (editor == null) { return; } Document document = editor.getDocument(); if (document == null) { return; } FileObject fileObject = NbEditorUtilities.getFileObject(document); if (fileObject == null) { return; } // get go to files CakePhpGoToStatusFactory factory = CakePhpGoToStatusFactory.getInstance(); CakePhpGoToStatus status = factory.create(fileObject, editor.getCaretPosition()); final List<GoToItem> items = getGoToItems(status); if (items == null || items.isEmpty()) { return; } // if there are multiple items, show popup list if (items.size() == 1 && !CakePreferences.isShowPopupForOneItem(phpModule)) { for (GoToItem item : items) { UiUtils.open(item.getFileObject(), item.getOffset()); return; } } // show popup try { Rectangle rectangle = editor.modelToView(editor.getCaretPosition()); final Point point = new Point(rectangle.x, rectangle.y + rectangle.height); SwingUtilities.convertPointToScreen(point, editor); SwingUtilities.invokeLater( new Runnable() { @Override public void run() { String title = getPopupTitle(); if (title == null) { title = ""; // NOI18N } PopupUtil.showPopup(new GoToPopup(title, items), title, point.x, point.y, true, 0); } }); } catch (BadLocationException ex) { Exceptions.printStackTrace(ex); } }
/* * We need to know if the caret is currently positioned on the line we * are about to paint so the line number can be highlighted. */ private boolean isCurrentLine(int rowStartOffset) { int caretPosition = component.getCaretPosition(); Element root = component.getDocument().getDefaultRootElement(); if (root.getElementIndex(rowStartOffset) == root.getElementIndex(caretPosition)) return true; else return false; }
/** {@inheritDoc} */ @Override public void actionPerformed(ActionEvent e) { JTextComponent target = getTextComponent(e); if (target != null) { SyntaxDocument sDoc = ActionUtils.getSyntaxDocument(target); int pos = target.getCaretPosition(); int start = sDoc.getParagraphElement(pos).getStartOffset(); String line = ActionUtils.getLine(target); if (ActionUtils.isEmptyOrBlanks(line)) { try { sDoc.insertString(pos, "}", null); Token t = sDoc.getPairFor(sDoc.getTokenAt(pos)); if (null != t) { String pairLine = ActionUtils.getLineAt(target, t.start); String indent = ActionUtils.getIndent(pairLine); sDoc.replace(start, line.length() + 1, indent + "}", null); } } catch (BadLocationException ble) { target.replaceSelection("}"); } } else { target.replaceSelection("}"); } } }
/** {@inheritDoc} */ public void paint(Graphics g) { if (isVisible() && overwriteMode) { Rectangle r = null; int pos = editor.getCaretPosition(); try { r = editor.modelToView(pos); } catch (BadLocationException e) { } if (r != null && (r.width != 0 || r.height != 0)) { if ((x != r.x) || (y != r.y)) { repaint(); x = r.x; y = r.y; height = r.height; width = editor.getFontMetrics(editor.getFont()).charWidth('W') + 1; } else { g.setColor(editor.getCaretColor()); g.setXORMode(editor.getBackground()); g.fillRect(x, y, width, height); } } } else { super.paint(g); } }
public static void insertMagicString(JTextComponent target, String result) { try { insertMagicString(target, target.getCaretPosition(), result); } catch (BadLocationException ex) { Logger.getLogger(ActionUtils.class.getName()).log(Level.SEVERE, null, ex); } }
private void updateCaretPosition(DocumentFilter.FilterBypass fb) throws BadLocationException { String allText = fb.getDocument().getText(0, fb.getDocument().getLength()); int index = allText.indexOf(':'); if (index != -1) { int minuteLength = allText.length() - index - 1; int hourLength = index; int caretPosition = tf.getCaretPosition(); if (minuteLength >= 2 && caretPosition == allText.length()) { tf.setCaretPosition(0); } else if (hourLength == caretPosition) { if (hourLength >= 2) { tf.setCaretPosition(3); } else if (hourLength == 1) { char c = allText.charAt(0); if (c != '0' && c != '1' && c != '2') { tf.setCaretPosition(2); } } } else if (hourLength + 1 == caretPosition) { if (hourLength == 1) { char c = allText.charAt(0); if (c == '0' || c == '1' || c == '2') { tf.setCaretPosition(caretPosition - 1); } } else if (hourLength == 0) { tf.setCaretPosition(caretPosition - 1); } } } if (allText.length() == 1) { tf.setCaretPosition(0); } }
public void paint(Graphics g, int p0, int p1, Shape bounds, JTextComponent c) { try { if (c.getSelectionStart() == c.getSelectionEnd()) { // if no // selection Rectangle r = c.modelToView(c.getCaretPosition()); g.setColor(col); g.fillRect(0, r.y, c.getWidth(), r.height); } } catch (BadLocationException ignore) { } }
private void updateReplaceComponent() { final int oldCaretPosition = myReplaceTextComponent != null ? myReplaceTextComponent.getCaretPosition() : 0; String oldText = myReplaceTextComponent != null ? myReplaceTextComponent.getText() : myFindModel.getStringToReplace(); if (!updateTextComponent(false)) { return; } if (oldText != null) { myReplaceTextComponent.setText(oldText); } myReplaceTextComponent .getDocument() .addDocumentListener( new DocumentAdapter() { @Override protected void textChanged(DocumentEvent e) { ApplicationManager.getApplication() .invokeLater( new Runnable() { @Override public void run() { replaceFieldDocumentChanged(); } }); } }); if (!getFindModel().isMultiline()) { new ReplaceOnEnterAction(this, myReplaceTextComponent); } // myReplaceTextComponent.setText(myFindModel.getStringToReplace()); ApplicationManager.getApplication() .invokeLater( new Runnable() { @Override public void run() { myReplaceTextComponent.setCaretPosition(oldCaretPosition); } }); new VariantsCompletionAction(myReplaceTextComponent); new NextOccurrenceAction(this, myReplaceFieldWrapper); new PrevOccurrenceAction(this, myReplaceFieldWrapper); myReplaceFieldWrapper.revalidate(); myReplaceFieldWrapper.repaint(); }
// // Implement CaretListener interface // @Override public void caretUpdate(CaretEvent e) { // Get the line the caret is positioned on int caretPosition = component.getCaretPosition(); Element root = component.getDocument().getDefaultRootElement(); int currentLine = root.getElementIndex(caretPosition); // Need to repaint so the correct line number can be highlighted if (lastLine != currentLine) { repaint(); lastLine = currentLine; } }
public static Point getLocationForCaret(JTextComponent pathTextField) { Point point; int position = pathTextField.getCaretPosition(); try { final Rectangle rec = pathTextField.modelToView(position); point = new Point((int) rec.getMaxX(), (int) rec.getMaxY()); } catch (BadLocationException e) { point = pathTextField.getCaret().getMagicCaretPosition(); } SwingUtilities.convertPointToScreen(point, pathTextField); point.y += 2; return point; }
static int indexOfBackSlash(final JTextComponent component) { int caretOffset = component.getCaretPosition(); String c; int i = caretOffset - 1; try { while (--i > -1) { c = component.getText(i, 1); if (c.equals("/")) { return i; } } return -1; } catch (BadLocationException ex) { return -1; } }
private void moveCtrlRight(boolean select) { String text = _textPane.getText(); int pos = _textPane.getCaretPosition() + 1; if (pos > text.length()) { return; } for (; pos < text.length(); ++pos) { if (isToStopAt(text.charAt(pos), text.charAt(pos - 1))) { break; } } if (select) { _textPane.moveCaretPosition(pos); } else { _textPane.setCaretPosition(pos); } }
private void moveCtrlLeft(boolean select) { String text = _textPane.getText(); int pos = _textPane.getCaretPosition() - 1; if (pos < 0) { return; } for (; pos > 0; --pos) { if (isToStopAt(text.charAt(pos - 1), text.charAt(pos))) { break; } } if (select) { _textPane.moveCaretPosition(pos); } else { _textPane.setCaretPosition(pos); } }
protected boolean changed(JComponent comp, String str, Position.Bias bias) { JTextComponent textComp = (JTextComponent) comp; int offset = bias == Position.Bias.Forward ? textComp.getCaretPosition() : textComp.getCaret().getMark() - 1; int index = getNextMatch(textComp, str, offset, bias); if (index != -1) { textComp.select(index, index + str.length()); return true; } else { offset = bias == null || bias == Position.Bias.Forward ? 0 : textComp.getDocument().getLength(); index = getNextMatch(textComp, str, offset, bias); if (index != -1) { textComp.select(index, index + str.length()); return true; } else return false; } }
/** * Insert the given String into the text component. If the string contains the | vertical BAr * char, then it will not be inserted, and the cursor will be set to its location. If there are * TWO vertical bars, then the text between them will be selected If the toInsert String is * multiLine, then indentation of all following lines will be the same as the first line. TAB * characters will be replaced by the number of spaces in the document's TAB property. * * @throws javax.swing.text.BadLocationException */ public static void insertMagicString(JTextComponent target, int dot, String toInsert) throws BadLocationException { Document doc = target.getDocument(); String[] lines = toInsert.split("\n"); if (lines.length > 1) { // multi line strings will need to be indented String tabToSpaces = getTab(target); String currentLine = getLineAt(target, dot); String currentIndent = getIndent(currentLine); StringBuilder sb = new StringBuilder(toInsert.length()); boolean firstLine = true; for (String l : lines) { if (!firstLine) { sb.append(currentIndent); } firstLine = false; // replace tabs with spaces. sb.append(l.replace("\t", tabToSpaces)); sb.append("\n"); } toInsert = sb.toString(); } if (toInsert.indexOf('|') >= 0) { int ofst = toInsert.indexOf('|'); int ofst2 = toInsert.indexOf('|', ofst + 1); toInsert = toInsert.replace("|", ""); doc.insertString(dot, toInsert, null); dot = target.getCaretPosition(); int strLength = toInsert.length(); if (ofst2 > 0) { // note that we already removed the first |, so end offset is now // one less than what it was. target.select(dot + ofst - strLength, dot + ofst2 - strLength - 1); } else { target.setCaretPosition(dot + ofst - strLength); } } else { doc.insertString(dot, toInsert, null); } }
/** Return the line of text at the TextComponent's current position */ public static String getLine(JTextComponent target) { return getLineAt(target, target.getCaretPosition()); }
private void updateSearchComponent() { final int oldCaretPosition = mySearchTextComponent != null ? mySearchTextComponent.getCaretPosition() : 0; String oldText = mySearchTextComponent != null ? mySearchTextComponent.getText() : myFindModel.getStringToFind(); if (!updateTextComponent(true)) { return; } if (oldText != null) { mySearchTextComponent.setText(oldText); } mySearchTextComponent .getDocument() .addDocumentListener( new DocumentAdapter() { @Override protected void textChanged(DocumentEvent e) { ApplicationManager.getApplication() .invokeLater( new Runnable() { @Override public void run() { ApplicationManager.getApplication() .invokeLater( new Runnable() { @Override public void run() { searchFieldDocumentChanged(); } }); } }); } }); mySearchTextComponent.registerKeyboardAction( new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { if (StringUtil.isEmpty(mySearchTextComponent.getText())) { close(); } else { requestFocus(myEditor.getContentComponent()); addTextToRecent(EditorSearchComponent.this.mySearchTextComponent); } } }, KeyStroke.getKeyStroke( KeyEvent.VK_ENTER, SystemInfo.isMac ? InputEvent.META_DOWN_MASK : InputEvent.CTRL_DOWN_MASK), JComponent.WHEN_FOCUSED); ApplicationManager.getApplication() .invokeLater( new Runnable() { @Override public void run() { mySearchTextComponent.setCaretPosition(oldCaretPosition); } }); new RestorePreviousSettingsAction(this, mySearchTextComponent); new VariantsCompletionAction( mySearchTextComponent); // It registers a shortcut set automatically on construction }
private void insertNewlineWithAutoIndent(JTextComponent text) { try { int caretPos = text.getCaretPosition(); StyledDocument doc = (StyledDocument) text.getDocument(); Element map = doc.getDefaultRootElement(); int lineNum = map.getElementIndex(caretPos); Element line = map.getElement(lineNum); int start = line.getStartOffset(); int end = line.getEndOffset() - 1; int len = end - start; String s = doc.getText(start, len); String leadingWS = PythonIndentation.getLeadingWhitespace(doc, start, caretPos - start); StringBuffer sb = new StringBuffer("\n"); sb.append(leadingWS); // TODO better control over automatic indentation indentationLogic.checkIndent(leadingWS, lineNum + 1); // If there is only whitespace between the caret and // the EOL, pressing Enter auto-indents the new line to // the same place as the previous line. int nonWhitespacePos = PythonIndentation.atEndOfLine(doc, caretPos, start, s, len); if (nonWhitespacePos == -1) { if (leadingWS.length() == len) { // If the line was nothing but whitespace, select it // so its contents get removed. text.setSelectionStart(start); } else { // Select the whitespace between the caret and the EOL // to remove it text.setSelectionStart(caretPos); } text.setSelectionEnd(end); text.replaceSelection(sb.toString()); // auto-indentation for python statements like if, while, for, try, // except, def, class and auto-deindentation for break, continue, // pass, return analyseDocument(doc, lineNum, indentationLogic); // auto-completion: add colon if it is obvious if (indentationLogic.shouldAddColon()) { doc.insertString(caretPos, ":", null); indentationLogic.setLastLineEndsWithColon(); } int lastLineChange = indentationLogic.shouldChangeLastLineIndentation(); int nextLineChange = indentationLogic.shouldChangeNextLineIndentation(); if (lastLineChange != 0) { Debug.log(5, "change line %d indentation by %d columns", lineNum + 1, lastLineChange); changeIndentation((DefaultStyledDocument) doc, lineNum, lastLineChange); // nextLineChange was determined based on indentation of last line before // the change nextLineChange += lastLineChange; } if (nextLineChange != 0) { Debug.log(5, "change line %d indentation by %d columns", lineNum + 2, nextLineChange); changeIndentation((DefaultStyledDocument) doc, lineNum + 1, nextLineChange); } } // If there is non-whitespace between the caret and the // EOL, pressing Enter takes that text to the next line // and auto-indents it to the same place as the last // line. Additional auto-indentation or dedentation for // specific python statements is only done for the next line. else { text.setCaretPosition(nonWhitespacePos); doc.insertString(nonWhitespacePos, sb.toString(), null); analyseDocument(doc, lineNum, indentationLogic); int nextLineChange = indentationLogic.shouldChangeNextLineIndentation(); if (nextLineChange != 0) { Debug.log(5, "change line %d indentation by %d columns", lineNum + 2, nextLineChange); changeIndentation((DefaultStyledDocument) doc, lineNum + 1, nextLineChange); } } } catch (BadLocationException ble) { text.replaceSelection("\n"); Debug.error(me + "Problem while inserting new line with auto-indent\n%s", ble.getMessage()); } }