javax.swing.text.Position Java Examples

The following examples show how to use javax.swing.text.Position. 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: DefaultIndentEngine.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
public int indentLine(Document doc, int offset) {
    Indent indent = Indent.get(doc);
    indent.lock();
    try {
        if (doc instanceof BaseDocument) {
            ((BaseDocument) doc).atomicLock();
        }
        try {
            Position pos = doc.createPosition(offset);
            indent.reindent(offset);
            return pos.getOffset();
        } catch (BadLocationException ble) {
            return offset;
        } finally {
            if (doc instanceof BaseDocument) {
                ((BaseDocument) doc).atomicUnlock();
            }
        }
    } finally {
        indent.unlock();
    }
}
 
Example #2
Source File: FormatTokenPositionSupport.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/** Add the save-set to the registry and perform the checking
 * whether the offsets are OK.
 */
synchronized void addSaveSet(int baseOffset, int writtenLen,
int[] offsets, Position.Bias[] biases) {
    // Check whether the offsets are OK
    for (int i = 0; i < offsets.length; i++) {
        if (offsets[i] < 0 || offsets[i] > writtenLen) {
            throw new IllegalArgumentException(
                "Invalid save-offset=" + offsets[i] + " at index=" + i // NOI18N
                + ". Written length is " + writtenLen); // NOI18N
        }
    }

    SaveSet newSet = new SaveSet(baseOffset, offsets, biases);

    if (firstSet != null) {
        lastSet.next = newSet;
        lastSet = newSet;

    } else { // first set
        firstSet = lastSet = newSet;
    }
}
 
Example #3
Source File: GrammarManager.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/**
     * Notification from invalidator thread, the grammar need to be reloaded.
     */
    public synchronized void invalidateGrammar() {
        
        // make current loader a zombie
        if (state == VALID) {
            String msg = NbBundle.getMessage(GrammarManager.class, "MSG_loading_cancel");
            StatusDisplayer.getDefault().setStatusText(msg);
        }
        
        doc.removeDocumentListener(this);
        
        //remove FileChangeListeners from the external DTD files
        for(FileObject fo : externalDTDs) {
//            System.out.println("[GrammarManager] removed FileObjectListener from " + fo.getPath());
            fo.removeFileChangeListener(this);
        }
        externalDTDs.clear();
        
        guarded = new Position[0];
        state = INVALID;
    }
 
Example #4
Source File: TabView.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
public Shape modelToViewChecked(int offset, Shape alloc, Position.Bias bias) {
    int startOffset = getStartOffset();
    Rectangle2D.Double mutableBounds = ViewUtils.shape2Bounds(alloc);
    int charIndex = offset - startOffset;
    if (charIndex == 1) {
        mutableBounds.x += firstTabWidth;
    } else if (charIndex > 1) {
        int extraTabCount = getLength() - 1;
        if (extraTabCount > 0) {
            mutableBounds.x += firstTabWidth + (charIndex - 1) * ((width - firstTabWidth) / extraTabCount);
        }
    }
    mutableBounds.width = 1;
    return mutableBounds;
}
 
Example #5
Source File: HintsControllerImpl.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public static PositionBounds linePart(FileObject file, int start, int end) {
    try {
        DataObject od = DataObject.find(file);
        
        if (od == null)
            return null;
        
        EditorCookie ec = od.getCookie(EditorCookie.class);
        
        if (!(ec instanceof CloneableEditorSupport)) {
            return null;
        }
        
        final CloneableEditorSupport ces = (CloneableEditorSupport) ec;
        
        checkOffsetsAndLog(start, end);
        
        return new PositionBounds(ces.createPositionRef(start, Position.Bias.Forward), ces.createPositionRef(end, Position.Bias.Backward));
    } catch (IOException e) {
        LOG.log(Level.INFO, null, e);
        return null;
    }
}
 
Example #6
Source File: Utilities.java    From netbeans with Apache License 2.0 6 votes vote down vote up
static int viewToModel(JTextComponent tc, double x, double y, Position.Bias[] biasReturn) {
int offs = -1;
Document doc = tc.getDocument();
if (doc instanceof AbstractDocument) {
    ((AbstractDocument)doc).readLock();
}
try {
    Rectangle alloc = getVisibleEditorRect(tc);
    if (alloc != null) {
               View rootView = tc.getUI().getRootView(tc);
               View documentView = rootView.getView(0);
               if (documentView instanceof EditorView) {
                   documentView.setSize(alloc.width, alloc.height);
                   offs = ((EditorView) documentView).viewToModelChecked(x, y, alloc, biasReturn);
               } else {
                   rootView.setSize(alloc.width, alloc.height);
                   offs = rootView.viewToModel((float) x, (float) y, alloc, biasReturn);
               }
    }
} finally {
    if (doc instanceof AbstractDocument) {
	((AbstractDocument)doc).readUnlock();
    }
}
       return offs;
   }
 
Example #7
Source File: AbstractRefactoringElement.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public PositionBounds getPosition() {
    try {
        DataObject dobj = DataObject.find(getParentFile());
        if (dobj != null) {
            EditorCookie.Observable obs = (EditorCookie.Observable)dobj.getCookie(EditorCookie.Observable.class);
            if (obs != null && obs instanceof CloneableEditorSupport) {
                CloneableEditorSupport supp = (CloneableEditorSupport)obs;

                if (loc == null) {
                    loc = location();
                }
            PositionBounds bounds = new PositionBounds(
                    supp.createPositionRef(loc[0], Position.Bias.Forward),
                    supp.createPositionRef(Math.max(loc[0], loc[1]), Position.Bias.Forward)
                    );
            
            return bounds;
        }
        }
    } catch (DataObjectNotFoundException ex) {
        ex.printStackTrace();
    }
    return null;
}
 
Example #8
Source File: OffsetRegion.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/**
 * Return union of this region with the given region.
 * <br>
 * If the given region is empty then return "this" region.
 * 
 * @param region region to union with.
 * @param ignoreEmpty if false and "this" region is empty (or region.isEmpty())
 *  then the returned region will "include" bounds of the empty region.
 * @return new region instance which is union of the given bounds
 */
public OffsetRegion union(OffsetRegion region, boolean ignoreEmpty) {
    int thisStartOffset = this.startOffset();
    int thisEndOffset = this.endOffset();
    if (ignoreEmpty) {
        if (region.isEmpty()) {
            return this;
        }
        if (thisStartOffset == thisEndOffset) {
            return region;
        }
    }
    if (region.startOffset() >= thisStartOffset) {
        if (region.endOffset() <= thisEndOffset) {
            return this; // Included
        } else { // endOffset > this.endOffset
            return new OffsetRegion(this.startPos, region.endPos);
        }
    } else { // startOffset < this.startOffset
        Position endP = (region.endOffset() > thisEndOffset) ? region.endPos : this.endPos;
        return new OffsetRegion(region.startPos, endP);
    }
}
 
Example #9
Source File: EditorDocumentContentTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void testBackwardBiasPositions() throws Exception {
        RandomTestContainer container = createContainer();
        RandomTestContainer.Context context = container.context();

        DocumentContentTesting.insert(context, 0, "ahoj cau");
        Position bbPos1 = DocumentContentTesting.createPosition(context, 1, true);
//        Position pos2 = DocumentContentTesting.createPosition(context, 2);
        Position bbPos3 = DocumentContentTesting.createPosition(context, 3, true);
        DocumentContentTesting.insert(context, 3, "test");
        container.runChecks(context);
        DocumentContentTesting.remove(context, 0, 4);
        container.runChecks(context);
        DocumentContentTesting.undo(context, 1); // checkContent() automatic
        DocumentContentTesting.undo(context, 1); // checkContent() automatic
        DocumentContentTesting.redo(context, 1); // checkContent() automatic
        DocumentContentTesting.redo(context, 1); // checkContent() automatic
        container.runChecks(context);
    }
 
Example #10
Source File: FormatWriter.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public synchronized void write(char[] cbuf, int off, int len,
int[] saveOffsets, Position.Bias[] saveBiases) throws IOException {
    if (simple) {
        underWriter.write(cbuf, off, len);
        return;
    }

    if (saveOffsets != null) {
        ftps.addSaveSet(bufferSize, len, saveOffsets, saveBiases);
    }

    lastFlush = false; // signal write() was the last so flush() can be done

    if (debug) {
        System.err.println("FormatWriter.write(): '" // NOI18N
                + org.netbeans.editor.EditorDebug.debugChars(cbuf, off, len)
                + "', length=" + len + ", bufferSize=" + bufferSize); // NOI18N
    }

    // Add the chars to the buffer for formatting
    addToBuffer(cbuf, off, len);
}
 
Example #11
Source File: PositionsBagTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void testRemoveAligned2Clip() {
    PositionsBag hs = new PositionsBag(doc);
    SimpleAttributeSet attribsA = new SimpleAttributeSet();
    
    attribsA.addAttribute("set-name", "attribsA");
    
    hs.addHighlight(pos(10), pos(40), attribsA);
    hs.removeHighlights(pos(10), pos(20), true);
    GapList<Position> marks = hs.getMarks();
    GapList<AttributeSet> atttributes = hs.getAttributes();
    
    assertEquals("Wrong number of highlights", 2, marks.size());
    assertEquals("1. highlight - wrong start offset", 20, marks.get(0).getOffset());
    assertEquals("1. highlight - wrong end offset", 40, marks.get(1).getOffset());
    assertEquals("1. highlight - wrong attribs", "attribsA", atttributes.get(0).getAttribute("set-name"));
    assertNull("  1. highlight - wrong end", atttributes.get(1));
    
    hs.removeHighlights(pos(30), pos(40), true);
    
    assertEquals("Wrong number of highlights", 2, marks.size());
    assertEquals("1. highlight - wrong start offset", 20, marks.get(0).getOffset());
    assertEquals("1. highlight - wrong end offset", 30, marks.get(1).getOffset());
    assertEquals("1. highlight - wrong attribs", "attribsA", atttributes.get(0).getAttribute("set-name"));
    assertNull("  1. highlight - wrong end", atttributes.get(1));
}
 
Example #12
Source File: JPACompletionItem.java    From netbeans with Apache License 2.0 6 votes vote down vote up
protected void substituteText(JTextComponent c, int offset, int len, String toAdd) {
    BaseDocument doc = (BaseDocument) c.getDocument();
    CharSequence prefix = getInsertPrefix();
    String text = prefix.toString();
    if (toAdd != null) {
        text += toAdd;
    }

    doc.atomicLock();
    try {
        Position position = doc.createPosition(offset);
        doc.remove(offset, len);
        doc.insertString(position.getOffset(), text.toString(), null);
    } catch (BadLocationException ble) {
        // nothing can be done to update
    } finally {
        doc.atomicUnlock();
    }
}
 
Example #13
Source File: PositionsBag.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private int [] addHighlightImpl(Position startPosition, Position endPosition, AttributeSet attributes) {
    if (startPosition.getOffset() == endPosition.getOffset()) {
        return null;
    } else {
        assert startPosition.getOffset() < endPosition.getOffset() : 
            "Start position must be before the end position."; //NOI18N
        assert attributes != null : "Highlight attributes must not be null."; //NOI18N
    }

    if (mergeHighlights) {
        merge(startPosition, endPosition, attributes);
    } else {
        trim(startPosition, endPosition, attributes);
    }

    return new int [] { startPosition.getOffset(), endPosition.getOffset() };
}
 
Example #14
Source File: ComputeAnnotations.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private static Position getPosition(final StyledDocument doc, final int offset) {
    class Impl implements Runnable {
        private Position pos;
        public void run() {
            if (offset < 0 || offset >= doc.getLength())
                return ;

            try {
                pos = doc.createPosition(offset - NbDocument.findLineColumn(doc, offset));
            } catch (BadLocationException ex) {
                //should not happen?
                Logger.getLogger(ComputeAnnotations.class.getName()).log(Level.FINE, null, ex);
            }
        }
    }

    Impl i = new Impl();

    doc.render(i);

    return i.pos;
}
 
Example #15
Source File: FormatSupport.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/** Get the previous position of the position given by parameters.
 * It can be either just offset decreasing but it can be movement
 * to the previous token for the token boundary.
 * @return next token-position or null for the first position in the chain
 */
public FormatTokenPosition getPreviousPosition(TokenItem token, int offset,
Position.Bias bias) {
    FormatTokenPosition ret = null;
    if (token == null) { // end of chain
        TokenItem lastToken = findNonEmptyToken(getLastToken(), true);
        if (lastToken != null) { // regular last token
            ret = getPosition(lastToken, lastToken.getImage().length() - 1,
                    Position.Bias.Forward);
        }

    } else { // regular token
        offset--;

        if (offset < 0) {
            token = token.getPrevious();
            if (token != null) { // was first pos in first token
                ret = getPosition(token, token.getImage().length() - 1,
                        Position.Bias.Forward);
            }

        } else { // still inside token
            ret = getPosition(token, offset,
                    Position.Bias.Forward);
        }
    }

    return ret;
}
 
Example #16
Source File: DoubleFoldManagerTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public boolean reject(Object o) {
    return (o == fold.getType())
        || (o == fold.getDescription()) // requires non-null description during construction
        || (o == fold.getParent())
        || (o instanceof FoldOperationImpl)
        || (o instanceof Position);
    
    // Will count possible FoldChildren and ExtraInfo
}
 
Example #17
Source File: MultiTextUI.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Invokes the <code>modelToView</code> method on each UI handled by this object.
 *
 * @return the value obtained from the first UI, which is
 * the UI obtained from the default <code>LookAndFeel</code>
 */
public Rectangle modelToView(JTextComponent a, int b, Position.Bias c)
        throws BadLocationException {
    Rectangle returnValue =
        ((TextUI) (uis.elementAt(0))).modelToView(a,b,c);
    for (int i = 1; i < uis.size(); i++) {
        ((TextUI) (uis.elementAt(i))).modelToView(a,b,c);
    }
    return returnValue;
}
 
Example #18
Source File: MultiTextUI.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Invokes the <code>viewToModel</code> method on each UI handled by this object.
 *
 * @return the value obtained from the first UI, which is
 * the UI obtained from the default <code>LookAndFeel</code>
 */
public int viewToModel(JTextComponent a, Point b, Position.Bias[] c) {
    int returnValue =
        ((TextUI) (uis.elementAt(0))).viewToModel(a,b,c);
    for (int i = 1; i < uis.size(); i++) {
        ((TextUI) (uis.elementAt(i))).viewToModel(a,b,c);
    }
    return returnValue;
}
 
Example #19
Source File: JavaSemanticTokenList.java    From netbeans with Apache License 2.0 5 votes vote down vote up
static void handleIdentifier(Document doc, List<Position[]> p, int[] span, String name) {
    if (span == null)
        return ;
    
    List<int[]> spans = new LinkedList<int[]>();
    List<String> separatedWords = separateWords(name, spans);
    
    for (int[] s : spans) {
        try {
            p.add(new Position[]{doc.createPosition(span[0] + s[0]), doc.createPosition(span[0] + s[1])});
        } catch (BadLocationException ex) {
            Exceptions.printStackTrace(ex);
        }
    }
}
 
Example #20
Source File: LockView.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public Shape modelToView(int pos, Shape a, Position.Bias b) throws BadLocationException {
    lock();
    try {
        
        if (view != null) {
            return view.modelToView(pos, a, b);
        }
        return null;

    } finally {
        unlock();
    }
}
 
Example #21
Source File: MultiTextUI.java    From JDKSourceCode1.8 with MIT License 5 votes vote down vote up
/**
 * Invokes the <code>getNextVisualPositionFrom</code> method on each UI handled by this object.
 *
 * @return the value obtained from the first UI, which is
 * the UI obtained from the default <code>LookAndFeel</code>
 */
public int getNextVisualPositionFrom(JTextComponent a, int b, Position.Bias c, int d, Position.Bias[] e)
        throws BadLocationException {
    int returnValue =
        ((TextUI) (uis.elementAt(0))).getNextVisualPositionFrom(a,b,c,d,e);
    for (int i = 1; i < uis.size(); i++) {
        ((TextUI) (uis.elementAt(i))).getNextVisualPositionFrom(a,b,c,d,e);
    }
    return returnValue;
}
 
Example #22
Source File: PositionsBagTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testRemoveMiddleEmptyHighlight() {
    PositionsBag hs = new PositionsBag(doc);
    SimpleAttributeSet attribsA = new SimpleAttributeSet();
    
    attribsA.addAttribute("set-name", "attribsA");
    
    hs.addHighlight(pos(10), pos(20), attribsA);
    hs.removeHighlights(pos(15), pos(15), false);
    GapList<Position> marks = hs.getMarks();
    
    assertEquals("Wrong number of highlights", 0, marks.size());
}
 
Example #23
Source File: TextRegion.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void updateBounds(Position startPos, Position endPos) {
    if (textRegionManager() != null)
        throw new IllegalStateException("Change of bounds of region " + // NOI18N
                "connected to textRegionManager prohibited."); // NOI18N
    if (startPos != null)
        setStartPos(startPos);
    if (endPos != null)
        setEndPos(endPos);
}
 
Example #24
Source File: MultiTextUI.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Override
public Rectangle2D modelToView2D(JTextComponent a, int b, Position.Bias c) throws BadLocationException {
    Rectangle2D returnValue =
        ((TextUI) (uis.elementAt(0))).modelToView2D(a,b,c);
    for (int i = 1; i < uis.size(); i++) {
        ((TextUI) (uis.elementAt(i))).modelToView2D(a,b,c);
    }
    return returnValue;
}
 
Example #25
Source File: JavaSemanticTokenList.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public Void visitClass(ClassTree node, List<Position[]> p) {
    int[] span = info.getTreeUtilities().findNameSpan(node);

    handleIdentifier(doc, p, span, node.getSimpleName().toString());
    
    return super.visitClass(node, p);
}
 
Example #26
Source File: SimpleTestStepLocation.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public void moveDot(NavigationFilter.FilterBypass bypass,
                   int dot,
                   Position.Bias bias) {
    if (dot > classNameLength) {
        bypass.moveDot(classNameLength, bias);
    } else {
        super.moveDot(bypass, dot, bias);
    }
}
 
Example #27
Source File: BraceMatchingSidebarComponent.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public void matchHighlighted(final MatchEvent evt) {
    final BraceContext[] ctx = new BraceContext[1];
    if (evt.getLocator() != null) {
        ctx[0] = evt.getLocator().findContext(evt.getOrigin()[0].getOffset());
    }
    
    editor.getDocument().render(new Runnable() {
        public void run() {
            if (ctx[0] == null) {
                Position[] range = findTooltipRange(evt.getOrigin(), evt.getMatches());
                if (range == null) {
                    ctx[0] = null;
                    return;
                }
                ctx[0] = BraceContext.create(range[0], range[1]);
            }
        }
    });
    SwingUtilities.invokeLater(new Runnable() {
       public void run() {
        braceContext = ctx[0];
        if (ctx[0] == null) {
            return;
        }
        if (!isEditorValid()) {
            return;
        }
        origin = evt.getOrigin();
        matches = evt.getMatches();
        repaint();
        showTooltip();
       } 
    });
}
 
Example #28
Source File: DocumentContent.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public Position createBiasPosition(int offset, Position.Bias bias)
    throws BadLocationException {
        checkOffset(offset);
        BasePosition pos = new BasePosition();
//        registerStack(pos);
        markVector.insert(markVector.createBiasMark(pos, offset, bias));
        return pos;
    }
 
Example #29
Source File: DocumentView.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public int getViewIndex(int offset, Position.Bias b) {
    if (b == Position.Bias.Backward) {
        offset--;
    }
    return getViewIndex(offset);
}
 
Example #30
Source File: RectangularSelectionUtils.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public static void resetRectangularSelection(JTextComponent c) {
    c.getCaretPosition();
    c.putClientProperty(RECTANGULAR_SELECTION_REGIONS_PROPERTY, new ArrayList<Position>());
    boolean value = !isRectangularSelection(c);
    RectangularSelectionUtils.setRectangularSelection(c, Boolean.valueOf(value) );
    RectangularSelectionUtils.setRectangularSelection(c, Boolean.valueOf(!value));
}