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);
  }
  @Override
  public void toggleLineBreakpoints(IWorkbenchPart part, ISelection selection)
      throws CoreException {
    CompilationUnitEditor editor = getEditor(part);

    if (editor != null) {
      IResource resource = (IResource) editor.getEditorInput().getAdapter(IResource.class);

      ITextSelection textSelection = (ITextSelection) selection;

      int lineNumber = textSelection.getStartLine();

      IBreakpoint[] breakpoints =
          DebugPlugin.getDefault()
              .getBreakpointManager()
              .getBreakpoints(DartDebugCorePlugin.DEBUG_MODEL_ID);

      for (int i = 0; i < breakpoints.length; i++) {
        IBreakpoint breakpoint = breakpoints[i];
        if (resource.equals(breakpoint.getMarker().getResource())) {
          if (((ILineBreakpoint) breakpoint).getLineNumber() == lineNumber + 1) {
            breakpoint.delete();
            return;
          }
        }
      }

      // Line numbers start with 0 in V8, with 1 in Eclipse.
      DartBreakpoint breakpoint = new DartBreakpoint(resource, lineNumber + 1);

      DebugPlugin.getDefault().getBreakpointManager().addBreakpoint(breakpoint);
    }
  }
  private void linkedModeLeft() {
    fgActiveLinkedMode = null;
    if (fInfoPopup != null) {
      fInfoPopup.close();
    }

    ISourceViewer viewer = fEditor.getViewer();
    if (viewer instanceof IEditingSupportRegistry) {
      IEditingSupportRegistry registry = (IEditingSupportRegistry) viewer;
      registry.unregister(fFocusEditingSupport);
    }
  }
 private void restoreFullSelection() {
   if (fOriginalSelection.y != 0) {
     int originalOffset = fOriginalSelection.x;
     LinkedPosition[] positions = fLinkedPositionGroup.getPositions();
     for (int i = 0; i < positions.length; i++) {
       LinkedPosition position = positions[i];
       if (!position.isDeleted() && position.includes(originalOffset)) {
         fEditor.getViewer().setSelectedRange(position.offset, position.length);
         return;
       }
     }
   }
 }
 public LinkedPosition getCurrentLinkedPosition() {
   Point selection = fEditor.getViewer().getSelectedRange();
   int start = selection.x;
   int end = start + selection.y;
   LinkedPosition[] positions = fLinkedPositionGroup.getPositions();
   for (int i = 0; i < positions.length; i++) {
     LinkedPosition position = positions[i];
     if (position.includes(start) && position.includes(end)) {
       return position;
     }
   }
   return null;
 }
  public void startFullDialog() {
    cancel();

    try {
      String newName = fNamePosition.getContent();
      RenameSupport renameSupport = undoAndCreateRenameSupport(newName);
      if (renameSupport != null) {
        renameSupport.openDialog(fEditor.getSite().getShell());
      }
    } catch (CoreException e) {
      DartToolsPlugin.log(e);
    } catch (BadLocationException e) {
      DartToolsPlugin.log(e);
    }
  }
 private int addEditorAction(IMenuManager menu, String actionID) {
   if (fEditor == null) {
     return 0;
   }
   IAction action = fEditor.getAction(actionID);
   if (action == null) {
     return 0;
   }
   if (action instanceof IUpdate) {
     ((IUpdate) action).update();
   }
   if (action.isEnabled()) {
     menu.add(action);
     return 1;
   }
   return 0;
 }
  void doRename(boolean showPreview) {
    cancel();

    Image image = null;
    Label label = null;

    fShowPreview |= showPreview;
    try {
      ISourceViewer viewer = fEditor.getViewer();
      if (viewer instanceof SourceViewer) {
        SourceViewer sourceViewer = (SourceViewer) viewer;
        Control viewerControl = sourceViewer.getControl();
        if (viewerControl instanceof Composite) {
          Composite composite = (Composite) viewerControl;
          Display display = composite.getDisplay();

          // Flush pending redraw requests:
          while (!display.isDisposed() && display.readAndDispatch()) {}

          // Copy editor area:
          GC gc = new GC(composite);
          Point size;
          try {
            size = composite.getSize();
            image = new Image(gc.getDevice(), size.x, size.y);
            gc.copyArea(image, 0, 0);
          } finally {
            gc.dispose();
            gc = null;
          }

          // Persist editor area while executing refactoring:
          label = new Label(composite, SWT.NONE);
          label.setImage(image);
          label.setBounds(0, 0, size.x, size.y);
          label.moveAbove(null);
        }
      }

      String newName = fNamePosition.getContent();
      if (fOriginalName.equals(newName)) {
        return;
      }
      RenameSupport renameSupport = undoAndCreateRenameSupport(newName);
      if (renameSupport == null) {
        return;
      }

      Shell shell = fEditor.getSite().getShell();
      boolean executed;
      if (fShowPreview) { // could have been updated by undoAndCreateRenameSupport(..)
        executed = renameSupport.openDialog(shell, true);
      } else {
        renameSupport.perform(shell, fEditor.getSite().getWorkbenchWindow());
        executed = true;
      }
      if (executed) {
        restoreFullSelection();
      }
      DartModelUtil.reconcile(getCompilationUnit());
    } catch (CoreException ex) {
      DartToolsPlugin.log(ex);
    } catch (InterruptedException ex) {
      // canceling is OK -> redo text changes in that case?
    } catch (InvocationTargetException ex) {
      DartToolsPlugin.log(ex);
    } catch (BadLocationException e) {
      DartToolsPlugin.log(e);
    } finally {
      if (label != null) {
        label.dispose();
      }
      if (image != null) {
        image.dispose();
      }
    }
  }
  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);
    }
  }
  /**
   * Note: This constructor is for internal use only. Clients should not call this constructor.
   *
   * @param editor the compilation unit editor
   * @param groupName the group name to add the action to
   */
  public GenerateActionGroup(CompilationUnitEditor editor, String groupName) {
    fSite = editor.getSite();
    fEditor = editor;
    fGroupName = groupName;

    DartX.todo();
    //    fSortMembers = new MultiSortMembersAction(editor);
    //    fSortMembers.setActionDefinitionId(DartEditorActionDefinitionIds.SORT_MEMBERS);
    //    editor.setAction("SortMembers", fSortMembers); //$NON-NLS-1$

    //		IAction pastAction=
    // editor.getAction(ITextEditorActionConstants.PASTE);//IWorkbenchActionDefinitionIds.PASTE);
    //		fCopyQualifiedNameAction= new CopyQualifiedNameAction(editor, null, pastAction);
    //
    //	fCopyQualifiedNameAction.setActionDefinitionId(CopyQualifiedNameAction.JAVA_EDITOR_ACTION_DEFINITIONS_ID);
    //		editor.setAction("CopyQualifiedName", fCopyQualifiedNameAction); //$NON-NLS-1$

    //    if (IUIConstants.SUPPORT_REFACTORING) {
    //      fOverrideMethods = new OverrideMethodsAction(editor);
    //      fOverrideMethods.setActionDefinitionId(DartEditorActionDefinitionIds.OVERRIDE_METHODS);
    //      editor.setAction("OverrideMethods", fOverrideMethods); //$NON-NLS-1$
    //
    //      fAddGetterSetter = new AddGetterSetterAction(editor);
    //
    // fAddGetterSetter.setActionDefinitionId(DartEditorActionDefinitionIds.CREATE_GETTER_SETTER);
    //      editor.setAction("AddGetterSetter", fAddGetterSetter); //$NON-NLS-1$
    //
    //      fAddDelegateMethods = new AddDelegateMethodsAction(editor);
    //
    // fAddDelegateMethods.setActionDefinitionId(DartEditorActionDefinitionIds.CREATE_DELEGATE_METHODS);
    //      editor.setAction("AddDelegateMethods", fAddDelegateMethods); //$NON-NLS-1$
    //
    ////		fAddUnimplementedConstructors= new AddUnimplementedConstructorsAction(editor);
    ////
    //	fAddUnimplementedConstructors.setActionDefinitionId(DartEditorActionDefinitionIds.ADD_UNIMPLEMENTED_CONTRUCTORS);
    ////		editor.setAction("AddUnimplementedConstructors", fAddUnimplementedConstructors);
    // //$NON-NLS-1$
    //
    //      fGenerateConstructorUsingFields = new GenerateNewConstructorUsingFieldsAction(
    //          editor);
    //
    // fGenerateConstructorUsingFields.setActionDefinitionId(DartEditorActionDefinitionIds.GENERATE_CONSTRUCTOR_USING_FIELDS);
    //      editor.setAction(
    //          "GenerateConstructorUsingFields", fGenerateConstructorUsingFields); //$NON-NLS-1$
    //    }

    //		fHashCodeEquals= new GenerateHashCodeEqualsAction(editor);
    //
    //	fHashCodeEquals.setActionDefinitionId(DartEditorActionDefinitionIds.GENERATE_HASHCODE_EQUALS);
    //		editor.setAction("GenerateHashCodeEquals", fHashCodeEquals); //$NON-NLS-1$

    //    fAddJavaDocStub = new AddJavaDocStubAction(editor);
    //    fAddJavaDocStub.setActionDefinitionId(DartEditorActionDefinitionIds.ADD_JAVADOC_COMMENT);
    //    editor.setAction("AddJavadocComment", fAddJavaDocStub); //$NON-NLS-1$

    //    fCleanUp = new AllCleanUpsAction(editor);
    //    fCleanUp.setActionDefinitionId(DartEditorActionDefinitionIds.CLEAN_UP);
    //    editor.setAction("CleanUp", fCleanUp); //$NON-NLS-1$

    //    if (IUIConstants.SUPPORT_REFACTORING) {
    //      fExternalizeStrings = new ExternalizeStringsAction(editor);
    //
    // fExternalizeStrings.setActionDefinitionId(DartEditorActionDefinitionIds.EXTERNALIZE_STRINGS);
    //      editor.setAction("ExternalizeStrings", fExternalizeStrings); //$NON-NLS-1$
    //    }

    installQuickAccessAction();
  }