private RenameSupport undoAndCreateRenameSupport(String newName) throws CoreException { // Assumption: the linked mode model should be shut down by now. final ISourceViewer viewer = fEditor.getViewer(); try { if (!fOriginalName.equals(newName)) { fEditor .getSite() .getWorkbenchWindow() .run( false, true, new IRunnableWithProgress() { @Override public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { if (viewer instanceof ITextViewerExtension6) { IUndoManager undoManager = ((ITextViewerExtension6) viewer).getUndoManager(); if (undoManager instanceof IUndoManagerExtension) { IUndoManagerExtension undoManagerExtension = (IUndoManagerExtension) undoManager; IUndoContext undoContext = undoManagerExtension.getUndoContext(); IOperationHistory operationHistory = OperationHistoryFactory.getOperationHistory(); while (undoManager.undoable()) { if (fStartingUndoOperation != null && fStartingUndoOperation.equals( operationHistory.getUndoOperation(undoContext))) { return; } undoManager.undo(); } } } } }); } } catch (InvocationTargetException e) { throw new CoreException( new Status( IStatus.ERROR, DartToolsPlugin.getPluginId(), ReorgMessages.RenameLinkedMode_error_saving_editor, e)); } catch (InterruptedException e) { // canceling is OK return null; } finally { DartModelUtil.reconcile(getCompilationUnit()); } viewer.setSelectedRange(fOriginalSelection.x, fOriginalSelection.y); if (newName.length() == 0) { return null; } return RefactoringExecutionStarter.createRenameSupport(fDartElement, newName, 0); }
/** * On-save operations : * * <p>* Un-wrapping if needed * * <p>* Auto section markers normalization * * <p>* Auto formating when the editor saves the file * * @param aSourceViewer The editor source viewer */ public void onEditorPerformSave(final ISourceViewer aSourceViewer) { final IDocument document = aSourceViewer.getDocument(); if (pPreferenceStore.getBoolean(IEditorPreferenceConstants.EDITOR_SAVE_RESET_MARKERS)) { // Auto section blocks normalization RestContentOutlinePage outlinePage = null; if (pEditor != null) { outlinePage = pEditor.getOutlinePage(); } if (outlinePage != null) { // Don't forget to refresh the tree ! outlinePage.update(); OutlineUtil.normalizeSectionsMarker( pEditor.getOutlinePage().getContentProvider().getRoot()); } } // Formatting text _must_ be the last thing to do : it modifies the // document content, therefore it may induce unpredictable behavior for // next document readers if (pPreferenceStore.getBoolean(IEditorPreferenceConstants.EDITOR_SAVE_FORMAT)) { // Text format on save // Doc informations IRegion docRegion = new Region(0, document.getLength()); // Store current pointer location Point currentLocation = aSourceViewer.getSelectedRange(); // Format the document pDocFormatter.format(document, docRegion); // Reset point location aSourceViewer.setSelectedRange(currentLocation.x, currentLocation.y); } if (LineWrapUtil.get().isActiveMode(LineWrapMode.SOFT)) { // Soft wrap mode : remove all added end-of-line pAutoEditLineWrap.unregisterListener(); pAutoEditLineWrap.removeWrapping(); } }
/** * If the given caret location string contains a selection range, select that range in the given * viewer * * @param viewer the viewer to contain the selection * @param caretLocation the location string */ protected int updateCaret(ISourceViewer viewer, String caretLocation) { assertTrue(caretLocation, caretLocation.contains("^")); // $NON-NLS-1$ int caretDelta = caretLocation.indexOf("^"); // $NON-NLS-1$ assertTrue(caretLocation, caretDelta != -1); String text = viewer.getTextWidget().getText(); int length = 0; // String around caret/range without the range and caret marker // characters String caretContext; if (caretLocation.contains("[^")) { // $NON-NLS-1$ caretDelta--; assertTrue(caretLocation, caretLocation.startsWith("[^", caretDelta)); // $NON-NLS-1$ int caretRangeEnd = caretLocation.indexOf(']', caretDelta + 2); assertTrue(caretLocation, caretRangeEnd != -1); length = caretRangeEnd - caretDelta - 2; assertTrue(length > 0); caretContext = caretLocation.substring(0, caretDelta) + caretLocation.substring(caretDelta + 2, caretRangeEnd) + caretLocation.substring(caretRangeEnd + 1); } else { caretContext = caretLocation.substring(0, caretDelta) + caretLocation.substring(caretDelta + 1); // +1: // skip // "^" } int caretContextIndex = text.indexOf(caretContext); assertTrue("Caret content " + caretContext + " not found in file", caretContextIndex != -1); int offset = caretContextIndex + caretDelta; viewer.setSelectedRange(offset, length); return offset; }
private RenameSupport undoAndCreateRenameSupport(String newName) throws CoreException { // Assumption: the linked mode model should be shut down by now. final ISourceViewer viewer = fEditor.getViewer(); try { if (!fOriginalName.equals(newName)) { IWorkbenchWindow workbenchWindow = fEditor.getSite().getWorkbenchWindow(); // undo workbenchWindow.run( false, true, new IRunnableWithProgress() { @Override public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { if (viewer instanceof ITextViewerExtension6) { IUndoManager undoManager = ((ITextViewerExtension6) viewer).getUndoManager(); if (undoManager instanceof IUndoManagerExtension) { IUndoManagerExtension undoManagerExtension = (IUndoManagerExtension) undoManager; IUndoContext undoContext = undoManagerExtension.getUndoContext(); IOperationHistory operationHistory = OperationHistoryFactory.getOperationHistory(); while (undoManager.undoable()) { if (fStartingUndoOperation != null && fStartingUndoOperation.equals( operationHistory.getUndoOperation(undoContext))) { return; } undoManager.undo(); } } } } }); // wait for analysis IProgressService progressService = PlatformUI.getWorkbench().getProgressService(); progressService.busyCursorWhile( new IRunnableWithProgress() { @Override public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { monitor.beginTask("Waiting for background analysis...", IProgressMonitor.UNKNOWN); try { RefactoringUtils.waitResolvedCompilationUnit(fEditor, monitor); RefactoringUtils.waitReadyForRefactoring(monitor); } finally { monitor.done(); } } }); // by some reason "busyCursorWhile" looses focus, so restore it fEditor.setFocus(); // get new Element, after background build finished prepareElement(); if (fDartElement == null) { return null; } } } catch (InvocationTargetException e) { throw new CoreException( new Status( IStatus.ERROR, DartToolsPlugin.getPluginId(), ReorgMessages.RenameLinkedMode_error_saving_editor, e)); } catch (InterruptedException e) { // canceling is OK return null; } viewer.setSelectedRange(fOriginalSelection.x, fOriginalSelection.y); if (newName.length() == 0) { return null; } return RenameSupport.create(fDartElement, newName); }
public void start() { if (getActiveLinkedMode() != null) { // for safety; should already be handled in RenameDartElementAction fgActiveLinkedMode.startFullDialog(); return; } ISourceViewer viewer = fEditor.getViewer(); IDocument document = viewer.getDocument(); fOriginalSelection = viewer.getSelectedRange(); int offset = fOriginalSelection.x; try { fLinkedPositionGroup = new LinkedPositionGroup(); prepareElement(); if (fDartElement == null) { return; } if (viewer instanceof ITextViewerExtension6) { IUndoManager undoManager = ((ITextViewerExtension6) viewer).getUndoManager(); if (undoManager instanceof IUndoManagerExtension) { IUndoManagerExtension undoManagerExtension = (IUndoManagerExtension) undoManager; IUndoContext undoContext = undoManagerExtension.getUndoContext(); IOperationHistory operationHistory = OperationHistoryFactory.getOperationHistory(); fStartingUndoOperation = operationHistory.getUndoOperation(undoContext); } } fOriginalName = nameNode.getName(); final int pos = nameNode.getOffset(); final List<ASTNode> sameNodes = Lists.newArrayList(); nameNode .getRoot() .accept( new RecursiveASTVisitor<Void>() { @Override public Void visitSimpleIdentifier(SimpleIdentifier node) { Element element = node.getElement(); element = getCanonicalElement(element); if (Objects.equal(element, fDartElement)) { sameNodes.add(node); } return super.visitSimpleIdentifier(node); } }); // TODO: copied from LinkedNamesAssistProposal#apply(..): // sort for iteration order, starting with the node @ offset Collections.sort( sameNodes, new Comparator<ASTNode>() { @Override public int compare(ASTNode o1, ASTNode o2) { return rank(o1) - rank(o2); } /** * Returns the absolute rank of an <code>ASTNode</code>. Nodes preceding <code>pos * </code> are ranked last. * * @param node the node to compute the rank for * @return the rank of the node with respect to the invocation offset */ private int rank(ASTNode node) { int relativeRank = node.getOffset() + node.getLength() - pos; if (relativeRank < 0) { return Integer.MAX_VALUE + relativeRank; } else { return relativeRank; } } }); for (int i = 0; i < sameNodes.size(); i++) { ASTNode elem = sameNodes.get(i); LinkedPosition linkedPosition = new LinkedPosition(document, elem.getOffset(), elem.getLength(), i); if (i == 0) { fNamePosition = linkedPosition; } fLinkedPositionGroup.addPosition(linkedPosition); } fLinkedModeModel = new LinkedModeModel(); fLinkedModeModel.addGroup(fLinkedPositionGroup); fLinkedModeModel.forceInstall(); fLinkedModeModel.addLinkingListener(new EditorHighlightingSynchronizer(fEditor)); fLinkedModeModel.addLinkingListener(new EditorSynchronizer()); LinkedModeUI ui = new EditorLinkedModeUI(fLinkedModeModel, viewer); ui.setExitPosition(viewer, offset, 0, Integer.MAX_VALUE); ui.setExitPolicy(new ExitPolicy(document)); ui.enter(); viewer.setSelectedRange( fOriginalSelection.x, fOriginalSelection.y); // by default, full word is selected; restore original selection if (viewer instanceof IEditingSupportRegistry) { IEditingSupportRegistry registry = (IEditingSupportRegistry) viewer; registry.register(fFocusEditingSupport); } openSecondaryPopup(); // startAnimation(); fgActiveLinkedMode = this; } catch (BadLocationException e) { DartToolsPlugin.log(e); } }
/** * (non-Javadoc) * * @see org.eclipse.swt.custom.VerifyKeyListener#verifyKey(org.eclipse.swt.events.VerifyEvent) */ @SuppressWarnings("fallthrough") public void verifyKey(VerifyEvent event) { if (!event.doit || getInsertMode() != SMART_INSERT) { return; } ISourceViewer sourceViewer = getSourceViewer(); IDocument document = sourceViewer.getDocument(); final Point selection = sourceViewer.getSelectedRange(); final int offset = selection.x; final int length = selection.y; switch (event.character) { case ']': if (!this.fCloseBrackets) { return; } // Fall through case ')': if (hasCharacterAtOffset(document, offset + length, event.character)) { sourceViewer.setSelectedRange(offset + length + 1, 0); event.doit = false; return; } break; case '(': if (hasCharacterToTheRight(document, offset + length, '(')) return; // fall through case '[': if (!this.fCloseBrackets) return; if (hasIdentifierToTheRight(document, offset + length)) return; // fall through case '\'': if (event.character == '\'') { if (!this.fCloseStrings) return; if (hasCharacterAtOffset(document, offset - 1, '\\')) { return; } if (hasCharacterAtOffset(document, offset + length, '\'')) { sourceViewer.setSelectedRange(offset + length + 1, 0); event.doit = false; return; } if (hasIdentifierToTheLeft(document, offset) || hasIdentifierToTheRight(document, offset + length)) { return; } } // fall through case '"': if (event.character == '"') { if (!this.fCloseStrings) return; if (hasCharacterAtOffset(document, offset - 1, '\\')) { return; } if (hasCharacterAtOffset(document, offset + length, '"')) { sourceViewer.setSelectedRange(offset + length + 1, 0); event.doit = false; return; } if (hasIdentifierToTheLeft(document, offset) || hasIdentifierToTheRight(document, offset + length)) return; } try { // ITypedRegion partition= TextUtilities.getPartition(document, // IJavaPartitions.JAVA_PARTITIONING, offset, true); //// if (! IDocument.DEFAULT_CONTENT_TYPE.equals(partition.getType()) && // partition.getOffset() != offset) // if (! IDocument.DEFAULT_CONTENT_TYPE.equals(partition.getType())) // return; // if (!validateEditorInputState()) { return; } final StringBuffer buffer = new StringBuffer(); buffer.append(event.character); buffer.append(getPeerCharacter(event.character)); document.replace(offset, length, buffer.toString()); // move to the right of the inserted element sourceViewer.setSelectedRange(offset + 1, 0); // // BracketLevel level= new BracketLevel(); // fBracketLevelStack.push(level); // // LinkedPositionGroup group= new LinkedPositionGroup(); // group.addPosition(new LinkedPosition(document, offset + 1, 0, // LinkedPositionGroup.NO_STOP)); // // LinkedModeModel model= new LinkedModeModel(); // model.addLinkingListener(this); // model.addGroup(group); // model.forceInstall(); // // level.fOffset= offset; // level.fLength= 2; // // // set up position tracking for our magic peers // if (fBracketLevelStack.size() == 1) { // document.addPositionCategory(CATEGORY); // document.addPositionUpdater(fUpdater); // } // level.fFirstPosition= new Position(offset, 1); // level.fSecondPosition= new Position(offset + 1, 1); // document.addPosition(CATEGORY, level.fFirstPosition); // document.addPosition(CATEGORY, level.fSecondPosition); // // level.fUI= new EditorLinkedModeUI(model, sourceViewer); // level.fUI.setSimpleMode(true); // level.fUI.setExitPolicy(new ExitPolicy(closingCharacter, // getEscapeCharacter(closingCharacter), fBracketLevelStack)); // level.fUI.setExitPosition(sourceViewer, offset + 2, 0, Integer.MAX_VALUE); // level.fUI.setCyclingMode(LinkedModeUI.CYCLE_NEVER); // level.fUI.enter(); // // // IRegion newSelection= level.fUI.getSelectedRegion(); // sourceViewer.setSelectedRange(newSelection.getOffset(), newSelection.getLength()); event.doit = false; } catch (BadLocationException e) { BPELUIPlugin.log(e); } // catch (BadPositionCategoryException e) { // BPELUIPlugin.log(e); // } break; } }
protected void assertContentAssistResults( int offset, int length, String[] expected, boolean isCompletion, boolean isTemplate, boolean filterResults, int compareType) throws Exception { if (CTestPlugin.getDefault().isDebugging()) { System.out.println("\n\n\n\n\nTesting " + this.getClass().getName()); } // Call the CContentAssistProcessor ISourceViewer sourceViewer = EditorTestHelper.getSourceViewer((AbstractTextEditor) fEditor); String contentType = TextUtilities.getContentType( sourceViewer.getDocument(), ICPartitions.C_PARTITIONING, offset, true); boolean isCode = IDocument.DEFAULT_CONTENT_TYPE.equals(contentType); ContentAssistant assistant = new ContentAssistant(); CContentAssistProcessor processor = new CContentAssistProcessor(fEditor, assistant, contentType); long startTime = System.currentTimeMillis(); sourceViewer.setSelectedRange(offset, length); Object[] results = isCompletion ? (Object[]) processor.computeCompletionProposals(sourceViewer, offset) : (Object[]) processor.computeContextInformation(sourceViewer, offset); long endTime = System.currentTimeMillis(); assertTrue(results != null); if (filterResults) { if (isTemplate) { results = filterResultsKeepTemplates(results); } else { results = filterResults(results, isCode); } } String[] resultStrings = toStringArray(results, compareType); Arrays.sort(expected); Arrays.sort(resultStrings); if (CTestPlugin.getDefault().isDebugging()) { System.out.println("Time (ms): " + (endTime - startTime)); for (String proposal : resultStrings) { System.out.println("Result: " + proposal); } } boolean allFound = true; // for the time being, let's be optimistic for (String element : expected) { boolean found = false; for (String proposal : resultStrings) { if (element.equals(proposal)) { found = true; if (CTestPlugin.getDefault().isDebugging()) { System.out.println("Lookup success for " + element); } break; } } if (!found) { allFound = false; if (CTestPlugin.getDefault().isDebugging()) { System.out.println("Lookup failed for " + element); // $NON-NLS-1$ } } } if (!allFound) { assertEquals("Missing results!", toString(expected), toString(resultStrings)); } else if (doCheckExtraResults()) { assertEquals("Extra results!", toString(expected), toString(resultStrings)); } }
public void start() { if (getActiveLinkedMode() != null) { // for safety; should already be handled in RenameDartElementAction fgActiveLinkedMode.startFullDialog(); return; } ISourceViewer viewer = fEditor.getViewer(); IDocument document = viewer.getDocument(); fOriginalSelection = viewer.getSelectedRange(); int offset = fOriginalSelection.x; try { DartUnit root = ASTProvider.getASTProvider().getAST(getCompilationUnit(), ASTProvider.WAIT_YES, null); fLinkedPositionGroup = new LinkedPositionGroup(); DartNode selectedNode = NodeFinder.perform(root, fOriginalSelection.x, fOriginalSelection.y); if (!(selectedNode instanceof DartIdentifier)) { return; // TODO: show dialog } DartIdentifier nameNode = (DartIdentifier) selectedNode; if (viewer instanceof ITextViewerExtension6) { IUndoManager undoManager = ((ITextViewerExtension6) viewer).getUndoManager(); if (undoManager instanceof IUndoManagerExtension) { IUndoManagerExtension undoManagerExtension = (IUndoManagerExtension) undoManager; IUndoContext undoContext = undoManagerExtension.getUndoContext(); IOperationHistory operationHistory = OperationHistoryFactory.getOperationHistory(); fStartingUndoOperation = operationHistory.getUndoOperation(undoContext); } } fOriginalName = nameNode.getName(); final int pos = nameNode.getSourceInfo().getOffset(); DartNode[] sameNodes = LinkedNodeFinder.findByNode(root, nameNode); // TODO: copied from LinkedNamesAssistProposal#apply(..): // sort for iteration order, starting with the node @ offset Arrays.sort( sameNodes, new Comparator<DartNode>() { @Override public int compare(DartNode o1, DartNode o2) { return rank(o1) - rank(o2); } /** * Returns the absolute rank of an <code>DartNode</code>. Nodes preceding <code>pos * </code> are ranked last. * * @param node the node to compute the rank for * @return the rank of the node with respect to the invocation offset */ private int rank(DartNode node) { int relativeRank = node.getSourceInfo().getOffset() + node.getSourceInfo().getLength() - pos; if (relativeRank < 0) { return Integer.MAX_VALUE + relativeRank; } else { return relativeRank; } } }); for (int i = 0; i < sameNodes.length; i++) { DartNode elem = sameNodes[i]; LinkedPosition linkedPosition = new LinkedPosition( document, elem.getSourceInfo().getOffset(), elem.getSourceInfo().getLength(), i); if (i == 0) { fNamePosition = linkedPosition; } fLinkedPositionGroup.addPosition(linkedPosition); } fLinkedModeModel = new LinkedModeModel(); fLinkedModeModel.addGroup(fLinkedPositionGroup); fLinkedModeModel.forceInstall(); fLinkedModeModel.addLinkingListener(new EditorHighlightingSynchronizer(fEditor)); fLinkedModeModel.addLinkingListener(new EditorSynchronizer()); LinkedModeUI ui = new EditorLinkedModeUI(fLinkedModeModel, viewer); ui.setExitPosition(viewer, offset, 0, Integer.MAX_VALUE); ui.setExitPolicy(new ExitPolicy(document)); ui.enter(); viewer.setSelectedRange( fOriginalSelection.x, fOriginalSelection.y); // by default, full word is selected; restore original selection if (viewer instanceof IEditingSupportRegistry) { IEditingSupportRegistry registry = (IEditingSupportRegistry) viewer; registry.register(fFocusEditingSupport); } openSecondaryPopup(); // startAnimation(); fgActiveLinkedMode = this; } catch (BadLocationException e) { DartToolsPlugin.log(e); } }