下面列出了怎么用javax.swing.text.Position.Bias的API类实例代码及写法,或者点击链接到github查看源代码。
/**
*@return PositionBounds representing the position of the name of the entity that is being
* refactored or PostionBounds representing the start of the file if the position
* of the entity could not be resolved.
*/
public PositionBounds getPositionBounds(){
if (elementName != null){
try {
BaseDocument doc = getDocument();
String text = doc.getText(0, doc.getLength());
int offset = text.indexOf(elementName);
if (offset > -1){
PositionRef start = editorSupport.createPositionRef(offset, Bias.Forward);
PositionRef end = editorSupport.createPositionRef(offset + elementName.length(), Bias.Backward);
return new PositionBounds(start, end);
}
} catch (BadLocationException ex) {
ErrorManager.getDefault().notify(ex);
}
}
return getDefaultPositionBounds();
}
@Override
public int viewToModel(float x, float y, Shape a, Bias[] bias)
{
// Rectangle alloc = a instanceof Rectangle ? (Rectangle)a :
// a.getBounds();
// if (x < alloc.x + alloc.width) {
// bias[0] = Position.Bias.Forward;
// return getStartOffset(); // LTR
// }
// bias[0] = Position.Bias.Backward;
// return getEndOffset(); //RTL
Rectangle alloc = a instanceof Rectangle ? (Rectangle) a : a
.getBounds();
if (x < alloc.x + (alloc.width / 2))
{
bias[0] = Position.Bias.Forward;
return getStartOffset();
}
bias[0] = Position.Bias.Backward;
return getEndOffset();
}
@Override
public int getNextMatch(String prefix, int startIndex, Bias bias) {
ListModel model = getModel();
if (!(model instanceof TableModel)) {
return super.getNextMatch(prefix, startIndex, bias);
}
TableModel tablesModel = (TableModel)model;
int max = tablesModel.getSize();
int increment = (bias == Bias.Forward) ? 1 : -1;
int index = startIndex;
prefix = prefix.toUpperCase();
do {
Table table = tablesModel.getElementAt(index);
String tableName = table.getName().toUpperCase();
if (tableName.startsWith(prefix)) {
return index;
}
index = (index + increment + max) % max;
} while (index != startIndex);
return -1;
}
@Override
public Shape modelToView(int pos, Shape a, Bias b)
throws BadLocationException
{
int p0 = getStartOffset();
int p1 = getEndOffset();
if ((pos >= p0) && (pos <= p1))
{
Rectangle r = a instanceof Rectangle ? (Rectangle) a : a.getBounds();
if (pos == p1)
{
r.x += r.width;
}
r.width = 0;
return r;
}
throw new BadLocationException(pos + " not in range " + p0 + "," + p1, pos);
}
public void testCRLF197538() throws Exception {
prepareTest("test\r\ntest\r\ntest\r\n");
PositionRef start1 = ces.createPositionRef(5, Bias.Forward);
PositionRef end1 = ces.createPositionRef(9, Bias.Forward);
ModificationResult.Difference diff1 = new ModificationResult.Difference(ModificationResult.Difference.Kind.CHANGE, start1, end1, "test", "abcde", Source.create(testFile));
PositionRef start2 = ces.createPositionRef(10, Bias.Forward);
PositionRef end2 = ces.createPositionRef(13, Bias.Forward);
ModificationResult.Difference diff2 = new ModificationResult.Difference(ModificationResult.Difference.Kind.CHANGE, start2, end2, "tes", "a", Source.create(testFile));
ModificationResult result = new ModificationResult();
result.diffs = new HashMap<FileObject, List<ModificationResult.Difference>>();
result.diffs.put(testFile, Arrays.asList(diff1, diff2));
result.commit();
assertEquals("test\r\nabcde\r\nat\r\n", testFile.asText());
}
@Override
public int viewToModel(float x, float y, Shape a, Bias[] biasReturn)
{
Rectangle alloc = toRect(a);
// Move the y co-ord of the hit onto the baseline. This is because
// TextLayout supports
// italic carets and we do not.
TextLayout layout = getTextLayout();
TextHitInfo hit = layout.hitTestChar(x - (float) alloc.getX(), 0f);
// TextHitInfo hit = layout.hitTestChar(x - box.getAbsoluteContentX(),
// 0f);
int pos = hit.getInsertionIndex();
biasReturn[0] = hit.isLeadingEdge() ? Position.Bias.Forward
: Position.Bias.Backward;
return pos + getStartOffset();
}
private void findResult() {
if (isCanceled())
return;
int len = sdoc.getLength();
if (startOffset >= len || endOffset > len) {
if (!isCanceled() && ERR.isLoggable(ErrorManager.WARNING)) {
ERR.log(ErrorManager.WARNING, "document changed, but not canceled?" );
ERR.log(ErrorManager.WARNING, "len = " + len );
ERR.log(ErrorManager.WARNING, "startOffset = " + startOffset );
ERR.log(ErrorManager.WARNING, "endOffset = " + endOffset );
}
cancel();
return;
}
try {
result[0] = NbDocument.createPosition(sdoc, startOffset, Bias.Forward);
result[1] = NbDocument.createPosition(sdoc, endOffset, Bias.Backward);
} catch (BadLocationException e) {
ERR.notify(ErrorManager.ERROR, e);
}
}
/**
*@return PositionBounds representing the position of the name of the entity that is being
* refactored or PostionBounds representing the start of the file if the position
* of the entity could not be resolved.
*/
public PositionBounds getPositionBounds(){
if (elementName != null){
try {
BaseDocument doc = getDocument();
String text = doc.getText(0, doc.getLength());
int offset = text.indexOf(elementName);
if (offset > -1){
PositionRef start = editorSupport.createPositionRef(offset, Bias.Forward);
PositionRef end = editorSupport.createPositionRef(offset + elementName.length(), Bias.Backward);
return new PositionBounds(start, end);
}
} catch (BadLocationException ex) {
Exceptions.printStackTrace(ex);
}
}
return getDefaultPositionBounds();
}
public void testInputStream() throws Exception {
File file = new File(getDataDir(), "faces-config1.xml");
FileObject fileObject = FileUtil.toFileObject(file);
CloneableEditorSupport editor
= JSFEditorUtilities.findCloneableEditorSupport(DataObject.find(fileObject));
Modifications modifications = new Modifications();
Modifications.Difference difference = new Modifications.Difference(
Modifications.Difference.Kind.CHANGE,
editor.createPositionRef(549, Bias.Forward),
editor.createPositionRef(549+21, Bias.Backward),
"org.ncl.backing.Login", "org.ncl.forward.Login", "");
File outFile = new File(getWorkDir(), "faces-modification.xml");
FileWriter fWriter = new FileWriter(outFile);
modifications.addDifference(fileObject, difference);
List<Difference> differences = new LinkedList();
differences.add(difference);
modifications.commit(fileObject, differences, fWriter);
fWriter.close();
assertFile(outFile, getGoldenFile("gold-modifications.xml"));
}
public float getPreferredSpan(int axis) {
switch (axis) {
case Y_AXIS:
return getEditorUI().getLineHeight();
case X_AXIS:
// try {
int offset = Math.max(0, getEndOffset() - 1);
Shape retShape = modelToView(offset, new Rectangle(), Position.Bias.Forward, false);
int ret = retShape.getBounds().x + retShape.getBounds().width;
return Math.max(ret, 1f);
// } catch (BadLocationException ble) {
// LOG.log(Level.INFO, "Can't determine x-axis span", ble); //NOI18N
// }
}
return 1f;
}
private void refactorElement(ModificationResult modificationResult, CssElementContext.Editor context, CssIndex index) {
//type selector: div
//we do refactor only elements in the current css file, and even this is questionable if makes much sense
Node element = context.getElement();
String elementImage = element.image().toString();
CssFileModel model = CssFileModel.create(context.getParserResult());
List<Difference> diffs = new ArrayList<>();
CloneableEditorSupport editor = GsfUtilities.findCloneableEditorSupport(context.getFileObject());
for (Entry entry : model.getHtmlElements()) {
if (entry.isValidInSourceDocument() && elementImage.equals(entry.getName())) {
diffs.add(new Difference(Difference.Kind.CHANGE,
editor.createPositionRef(entry.getDocumentRange().getStart(), Bias.Forward),
editor.createPositionRef(entry.getDocumentRange().getEnd(), Bias.Backward),
entry.getName(),
refactoring.getNewName(),
NbBundle.getMessage(CssRenameRefactoringPlugin.class, "MSG_Rename_Selector"))); //NOI18N
}
}
if (!diffs.isEmpty()) {
modificationResult.addDifferences(context.getFileObject(), diffs);
}
}
/**
* Find next visual position in Y direction.
* In case of no line-wrap the method should return -1 for a given valid offset.
* and a valid offset when -1 is given as parameter.
* @param offset offset inside line or -1 to "enter" a line at the given x.
*/
int getNextVisualPositionX(ParagraphView pView, int offset, Bias bias, Shape pAlloc, boolean eastDirection, Bias[] biasRet) {
// Children already ensured to be measured by parent
int viewCount = size();
int index = (offset == -1)
? (eastDirection ? 0 : viewCount - 1)
: getViewIndex(pView, offset);
int increment = eastDirection ? 1 : -1;
int retOffset = -1;
// Cycle through individual views in left or right direction
for (; retOffset == -1 && index >= 0 && index < viewCount; index += increment) {
EditorView view = get(index); // Ensure valid children
Shape viewAlloc = getChildAllocation(index, pAlloc);
retOffset = view.getNextVisualPositionFromChecked(offset, bias, viewAlloc,
eastDirection ? SwingConstants.EAST : SwingConstants.WEST, biasRet);
if (retOffset == -1) {
offset = -1; // Continue by entering the paragraph from outside
}
}
return retOffset;
}
static Rectangle2D modelToView(JTextComponent tc, int pos, Position.Bias bias) throws BadLocationException {
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);
rootView.setSize(alloc.width, alloc.height);
Shape s = rootView.modelToView(pos, alloc, bias);
if (s != null) {
return s.getBounds2D();
}
}
} finally {
if (doc instanceof AbstractDocument) {
((AbstractDocument)doc).readUnlock();
}
}
return null;
}
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;
}
@Override
public void damageRange(JTextComponent t, int p0, int p1, Bias p0Bias, Bias p1Bias) {
View rootView = getRootView(getComponent());
boolean doDamageRange = true;
if (rootView.getViewCount() > 0) {
View view = rootView.getView(0);
if (view instanceof LockView) {
LockView lockView = (LockView) view;
lockView.lock();
try {
GapDocumentView docView = (GapDocumentView)view.getView(0);
doDamageRange = docView.checkDamageRange(p0, p1, p0Bias, p1Bias);
} finally {
lockView.unlock();
}
}
}
if (doDamageRange) {
// Patch since this used to be a fallback and the original views' impl cleared char area at p1 too
Document doc = t.getDocument();
if (doc != null && p1 < doc.getLength()) {
p1++;
}
super.damageRange(t, p0, p1, p0Bias, p1Bias);
}
}
@Override
public Shape modelToView(int pos, Shape a, Bias b)
throws BadLocationException
{
int p0 = getStartOffset();
int p1 = getEndOffset();
if ((pos >= p0) && (pos <= p1))
{
Rectangle r = a instanceof Rectangle ? (Rectangle) a : a
.getBounds();
if (pos == p1)
{
r.x += r.width;
}
r.width = 0;
return r;
}
// return null;
// //return box.getAbsoluteBounds();
throw new BadLocationException(pos + " not in range " + p0 + "," + p1,
pos);
}
@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;
}
private void refactorElements(ModificationResult modificationResult, RefactoringElementContext context, Collection<RefactoringElement> elementsToRename, String renameMsg) throws IOException, ParseException {
Map<FileObject, List<Difference>> file2diffs = new HashMap<>();
for (RefactoringElement re : elementsToRename) {
CloneableEditorSupport editor = GsfUtilities.findCloneableEditorSupport(re.getFile());
Difference diff = new Difference(Difference.Kind.CHANGE,
editor.createPositionRef(re.getRange().getStart(), Bias.Forward),
editor.createPositionRef(re.getRange().getEnd(), Bias.Backward),
re.getName(),
refactoring.getNewName(),
renameMsg);
List<Difference> diffs = file2diffs.get(re.getFile());
if (diffs == null) {
diffs = new ArrayList<>();
file2diffs.put(re.getFile(), diffs);
}
diffs.add(diff);
}
for (Entry<FileObject, List<Difference>> entry : file2diffs.entrySet()) {
modificationResult.addDifferences(entry.getKey(), entry.getValue());
}
}
public void writeTo(String s) throws IOException, BadLocationException {
ModificationResult.Difference diff = diffs.size() > 0 ? diffs.get(diffs.size() - 1) : null;
if (diff != null && diff.getKind() == ModificationResult.Difference.Kind.REMOVE && diff.getEndPosition().getOffset() == offset) {
diffs.remove(diffs.size() - 1);
diffs.add(JavaSourceAccessor.getINSTANCE().createDifference(ModificationResult.Difference.Kind.CHANGE, diff.getStartPosition(), diff.getEndPosition(), diff.getOldText(), s, diff.getDescription(), src));
} else {
int off = converter != null ? converter.getOriginalPosition(offset) : offset;
if (off >= 0) {
diffs.add(JavaSourceAccessor.getINSTANCE().createDifference(ModificationResult.Difference.Kind.INSERT, prp.createPosition(off, Bias.Forward), prp.createPosition(off, Bias.Backward), null, s, userInfo.get(offset), src));
}
}
}
public void skipThrough(char[] in, int pos) throws IOException, BadLocationException {
String origText = new String(in, offset, pos - offset);
org.netbeans.api.java.source.ModificationResult.Difference diff = diffs.size() > 0 ? diffs.get(diffs.size() - 1) : null;
if (diff != null && diff.getKind() == org.netbeans.api.java.source.ModificationResult.Difference.Kind.INSERT && diff.getStartPosition().getOffset() == offset) {
diffs.remove(diffs.size() - 1);
diffs.add(JavaSourceAccessor.getINSTANCE().createDifference(ModificationResult.Difference.Kind.CHANGE, diff.getStartPosition(), diff.getEndPosition(), origText, diff.getNewText(), diff.getDescription(), src));
} else {
int off = converter != null ? converter.getOriginalPosition(offset) : offset;
if (off >= 0) {
diffs.add(JavaSourceAccessor.getINSTANCE().createDifference(ModificationResult.Difference.Kind.REMOVE, prp.createPosition(off, Bias.Forward), prp.createPosition(off + origText.length(), Bias.Backward), origText, null, userInfo.get(offset), src));
}
}
offset = pos;
}
private static Position createPositionRef(FileObject file, int position, Position.Bias bias) {
try {
PositionRefProvider prp = PositionRefProvider.get(file);
Position positionRef = prp != null ? prp.createPosition(position, bias) : null;
if (positionRef != null) {
return positionRef;
}
} catch (IOException ex) {
Exceptions.printStackTrace(ex);
}
throw new IllegalStateException("Cannot create PositionRef for file " + file.getPath() + ". CloneableEditorSupport not found");
}
private static Position createPositionRef(FileObject file, int position, Position.Bias bias) {
try {
PositionRefProvider prp = PositionRefProvider.get(file);
Position positionRef = prp != null ? prp.createPosition(position, bias) : null;
if (positionRef != null) {
return positionRef;
}
} catch (IOException ex) {
Exceptions.printStackTrace(ex);
}
throw new IllegalStateException("Cannot create PositionRef for file " + file.getPath() + ". CloneableEditorSupport not found");
}
private ModificationResult prepareInsertResult() throws Exception {
PositionRef start1 = ces.createPositionRef(5, Bias.Forward);
ModificationResult.Difference diff1 = new ModificationResult.Difference(ModificationResult.Difference.Kind.INSERT, start1, start1, "", "new-test1\n", Source.create(testFile));
PositionRef start2 = ces.createPositionRef(10, Bias.Forward);
ModificationResult.Difference diff2 = new ModificationResult.Difference(ModificationResult.Difference.Kind.INSERT, start2, start2, "", "new-test2\n", Source.create(testFile));
ModificationResult result = new ModificationResult();
result.diffs = new HashMap<FileObject, List<ModificationResult.Difference>>();
result.diffs.put(testFile, Arrays.asList(diff1, diff2));
return result;
}
private ModificationResult prepareInsertResultFiltered() throws Exception {
PositionRef start1 = ces.createPositionRef(4, Bias.Forward);
ModificationResult.Difference diff1 = new ModificationResult.Difference(ModificationResult.Difference.Kind.INSERT, start1, start1, "", "new-test1\n", Source.create(testFile));
PositionRef start2 = ces.createPositionRef(8, Bias.Forward);
ModificationResult.Difference diff2 = new ModificationResult.Difference(ModificationResult.Difference.Kind.INSERT, start2, start2, "", "new-test2\n", Source.create(testFile));
ModificationResult result = new ModificationResult();
result.diffs = new HashMap<FileObject, List<ModificationResult.Difference>>();
result.diffs.put(testFile, Arrays.asList(diff1, diff2));
return result;
}
private int visualPositionOnWrapLine(ParagraphView pView,
Shape alloc, Bias[] biasRet, double x, int wrapLineIndex)
{
WrapLine wrapLine = wrapInfo.get(wrapLineIndex);
Shape wrapLineAlloc = wrapLineAlloc(alloc, wrapLineIndex);
IndexAndAlloc indexAndAlloc = findIndexAndAlloc(pView, x, wrapLineAlloc, wrapLine);
double y = ViewUtils.shapeAsRect(indexAndAlloc.alloc).getY();
return viewToModelWithAmbiguousWrapLineCaretAdustment(x, y, indexAndAlloc, biasRet);
}
public int viewToModelChecked(ParagraphView pView, double x, double y, Shape pAlloc, Bias[] biasReturn) {
IndexAndAlloc indexAndAlloc = findIndexAndAlloc(pView, x, y, pAlloc);
int offset = (indexAndAlloc != null)
? viewToModelWithAmbiguousWrapLineCaretAdustment(x, y, indexAndAlloc, biasReturn)
: pView.getStartOffset();
return offset;
}
private void addSetterInPathOccurrence(String propertyPath, String[] pathTokens,
SpringBean bean, TypeMirror beanType, Collection<ExecutableElement> methods, List<Occurrence> result) throws BadLocationException {
Location loc = bean.getLocation();
if (loc == null) {
return;
}
int beanOffset = loc.getOffset();
if (beanOffset == -1) {
return;
}
PropertyChildFinder finder = new PropertyChildFinder(syntaxSupport, beanOffset);
if (!finder.find(propertyPath)) {
return;
}
int foundOffset = finder.getFoundOffset();
String foundValue = finder.getValue();
int index = foundValue.indexOf(propertyPath);
if (index == -1) {
return;
}
PropertyPathElement[] pathElements = evaluatePropertyPath(cc.getElementUtilities(), beanType, pathTokens);
if (pathElements.length <= 1) {
return;
}
PropertyPathElement setterElement = pathElements[pathElements.length - 1];
if (!isSameOrOverrides(setterElement.getProperty().getSetter(), methods)) {
return;
}
String displayText = createPropertyChildDisplayText(foundValue, index + setterElement.getStartIndex(), setterElement.getEndIndex() - setterElement.getStartIndex());
PositionRef startRef = docAccess.createPositionRef(foundOffset + index + setterElement.getStartIndex(), Bias.Forward);
PositionRef endRef = docAccess.createPositionRef(foundOffset + index + setterElement.getEndIndex(), Bias.Backward);
result.add(new PropertyRefOccurrence(displayText, docAccess.getFileObject(), new PositionBounds(startRef, endRef)));
}
public static WhereUsedElement create(int start, int end, CompilationInfo compiler, boolean inTest, boolean inPlatform, boolean inDependency) {
CharSequence content = compiler.getSnapshot().getText();
LineMap lm = compiler.getCompilationUnit().getLineMap();
long line = lm.getLineNumber(start);
long endLine = lm.getLineNumber(end);
long sta = lm.getStartPosition(line);
int eof = content.length();
long lastLine = lm.getLineNumber(eof);
long en = lastLine > endLine ? lm.getStartPosition(endLine + 1) - 1 : eof;
StringBuilder sb = new StringBuilder();
sb.append(UIUtilities.getHtml(trimStart(content.subSequence((int) sta, start).toString())));
sb.append("<b>"); //NOI18N
sb.append(content.subSequence(start, end));
sb.append("</b>");//NOI18N
sb.append(UIUtilities.getHtml(trimEnd(content.subSequence(end, (int) en).toString())));
DataObject dob = null;
try {
dob = DataObject.find(compiler.getFileObject());
} catch (DataObjectNotFoundException ex) {
Exceptions.printStackTrace(ex);
}
CloneableEditorSupport ces = JavaWhereUsedQueryPlugin.findCloneableEditorSupport(dob);
PositionRef ref1 = ces.createPositionRef(start, Bias.Forward);
PositionRef ref2 = ces.createPositionRef(end, Bias.Forward);
PositionBounds bounds = new PositionBounds(ref1, ref2);
return new WhereUsedElement(bounds, sb.toString().trim(),
content.subSequence((int)sta, (int)en).toString(),
compiler.getFileObject(), null, compiler, null, inTest, inPlatform, inDependency, true, false);
}
@Override
public Shape modelToViewChecked(int offset, Shape alloc, Bias bias) {
Shape res = delegate.modelToViewChecked(offset, alloc, bias);
Rectangle2D rect = ViewUtils.shapeAsRect(res);
rect.setRect(rect.getX() + prependedTextWidth, rect.getY(), rect.getWidth(), rect.getHeight());
return rect;
}
@Override
public synchronized void insertUpdate(DocumentEvent e) {
try {
modifiedSpans.add(new Position[] {
doc.createPosition(e.getOffset(), Bias.Backward),
doc.createPosition(e.getOffset() + e.getLength(), Bias.Forward),
});
} catch (BadLocationException ex) {
LOG.log(Level.FINE, null, ex);
}
schedule();
}