Java Code Examples for com.intellij.openapi.application.WriteAction#run()

The following examples show how to use com.intellij.openapi.application.WriteAction#run() . 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: FileDocumentManagerImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
private void doSaveDocument(@Nonnull final Document document, boolean isExplicit) throws IOException, SaveVetoException {
  VirtualFile file = getFile(document);
  if (LOG.isTraceEnabled()) LOG.trace("saving: " + file);

  if (file == null || file instanceof LightVirtualFile || file.isValid() && !isFileModified(file)) {
    removeFromUnsaved(document);
    return;
  }

  if (file.isValid() && needsRefresh(file)) {
    LOG.trace("  refreshing...");
    file.refresh(false, false);
    if (!myUnsavedDocuments.contains(document)) return;
  }

  if (!maySaveDocument(file, document, isExplicit)) {
    throw new SaveVetoException();
  }

  LOG.trace("  writing...");
  WriteAction.run(() -> doSaveDocumentInWriteAction(document, file));
  LOG.trace("  done");
}
 
Example 2
Source File: TemplateCommentPanel.java    From consulo with Apache License 2.0 6 votes vote down vote up
private void showPreview(CopyrightFileConfig options) {
  final String defaultCopyrightText;

  if (myNoCopyright.isSelected()) {
    defaultCopyrightText = "";
  }
  else {
    String evaluate;
    try {
      evaluate = VelocityHelper.evaluate(null, null, null, EntityUtil.decode(CopyrightProfile.DEFAULT_COPYRIGHT_NOTICE));
    }
    catch (Exception e) {
      evaluate = "";
    }
    defaultCopyrightText = FileTypeUtil.buildComment(myCommenter, myAllowSeparator, evaluate, options);
  }

  initEditor();
  WriteAction.run(() -> myDocument.setText(defaultCopyrightText));
}
 
Example 3
Source File: GraphQLProjectConfigurable.java    From js-graphql-intellij-plugin with MIT License 6 votes vote down vote up
public void apply() throws ConfigurationException {
    if (myForm != null) {
        if (myProject.isDefault()) {
            myForm.apply();
        } else {
            WriteAction.run(() -> {
                myForm.apply();
            });
            ApplicationManager.getApplication().invokeLater(() -> {
                if (!myProject.isDisposed()) {
                    DaemonCodeAnalyzer.getInstance(myProject).restart();
                    EditorNotifications.getInstance(myProject).updateAllNotifications();
                }
            }, myProject.getDisposed());
        }
    }
}
 
Example 4
Source File: DirDiffTableModel.java    From consulo with Apache License 2.0 5 votes vote down vote up
public void performCopyFrom(final DirDiffElementImpl element) {
  final DiffElement<?> target = element.getTarget();
  if (target != null) {
    final String path = element.getParentNode().getPath();

    if (target instanceof BackgroundOperatingDiffElement) {
      final Ref<String> errorMessage = new Ref<>();
      final Ref<DiffElement> diff = new Ref<>();
      Runnable onFinish = () -> {
        ApplicationManager.getApplication().assertIsDispatchThread();
        if (!myDisposed) {
          refreshElementAfterCopyFrom(element, diff.get());
          if (!errorMessage.isNull()) {
            reportException(errorMessage.get());
          }
        }
      };
      ((BackgroundOperatingDiffElement)target).copyTo(mySrc, errorMessage, diff, onFinish, element.getSource(), path);
    }
    else {
      WriteAction.run(() -> {
        final DiffElement<?> diffElement = target.copyTo(mySrc, path);
        refreshElementAfterCopyFrom(element, diffElement);
      });
    }
  }
}
 
Example 5
Source File: ArtifactManagerImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public void addElementsToDirectory(@Nonnull Artifact artifact, @Nonnull String relativePath, @Nonnull Collection<? extends PackagingElement<?>> elements) {
  final ModifiableArtifactModel model = createModifiableModel();
  final CompositePackagingElement<?> root = model.getOrCreateModifiableArtifact(artifact).getRootElement();
  myPackagingElementFactory.getOrCreateDirectory(root, relativePath).addOrFindChildren(elements);
  WriteAction.run(model::commit);
}
 
Example 6
Source File: ArtifactsStructureConfigurable.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public void apply() throws ConfigurationException {
  myPackagingEditorContext.saveEditorSettings();
  super.apply();

  final ModifiableArtifactModel modifiableModel = myPackagingEditorContext.getActualModifiableModel();
  if (modifiableModel != null) {
    WriteAction.run(() -> modifiableModel.commit());
    myPackagingEditorContext.resetModifiableModel();
  }

  reset(); // TODO: fix to not reset on apply!
}
 
Example 7
Source File: ShowIntentionActionsHandler.java    From consulo with Apache License 2.0 5 votes vote down vote up
private static void invokeIntention(@Nonnull IntentionAction action, @Nullable Editor editor, @Nonnull PsiFile file) {
  //IntentionsCollector.getInstance().record(file.getProject(), action, file.getLanguage());
  PsiElement elementToMakeWritable = action.getElementToMakeWritable(file);
  if (elementToMakeWritable != null && !FileModificationService.getInstance().preparePsiElementsForWrite(elementToMakeWritable)) {
    return;
  }

  Runnable r = () -> action.invoke(file.getProject(), editor, file);
  if (action.startInWriteAction()) {
    WriteAction.run(r::run);
  }
  else {
    r.run();
  }
}
 
Example 8
Source File: ArtifactsTestCase.java    From consulo with Apache License 2.0 5 votes vote down vote up
public static void renameFile(final VirtualFile file, final String newName) {
  WriteAction.run(() -> {
    try {
      file.rename(IdeaTestCase.class, newName);
    }
    catch (IOException e) {
      throw new RuntimeException(e);
    }
  });
}
 
Example 9
Source File: PlatformTestCase.java    From consulo with Apache License 2.0 5 votes vote down vote up
protected static void delete(@Nonnull final VirtualFile file) {
  WriteAction.run(() -> {
    try {
      file.delete(null);
    }
    catch (IOException e) {
      fail();
    }
  });
}
 
Example 10
Source File: XBreakpointItem.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public void removed(Project project) {
  final XBreakpointManagerImpl breakpointManager = getManager();
  WriteAction.run(() -> {
    breakpointManager.removeBreakpoint(myBreakpoint);
  });
}
 
Example 11
Source File: CodeCompletionHandlerBase.java    From consulo with Apache License 2.0 5 votes vote down vote up
private static WatchingInsertionContext insertItemHonorBlockSelection(CompletionProcessEx indicator, LookupElement item, char completionChar, StatisticsUpdate update) {
  final Editor editor = indicator.getEditor();

  final int caretOffset = indicator.getCaret().getOffset();
  final int idEndOffset = calcIdEndOffset(indicator);
  final int idEndOffsetDelta = idEndOffset - caretOffset;

  WatchingInsertionContext context;
  if (editor.getCaretModel().supportsMultipleCarets()) {
    Ref<WatchingInsertionContext> lastContext = Ref.create();
    Editor hostEditor = InjectedLanguageUtil.getTopLevelEditor(editor);
    boolean wasInjected = hostEditor != editor;
    OffsetsInFile topLevelOffsets = indicator.getHostOffsets();
    hostEditor.getCaretModel().runForEachCaret(caret -> {
      OffsetsInFile targetOffsets = findInjectedOffsetsIfAny(caret, wasInjected, topLevelOffsets, hostEditor);
      PsiFile targetFile = targetOffsets.getFile();
      Editor targetEditor = InjectedLanguageUtil.getInjectedEditorForInjectedFile(hostEditor, targetFile);
      int targetCaretOffset = targetEditor.getCaretModel().getOffset();
      int idEnd = targetCaretOffset + idEndOffsetDelta;
      if (idEnd > targetEditor.getDocument().getTextLength()) {
        idEnd = targetCaretOffset; // no replacement by Tab when offsets gone wrong for some reason
      }
      WatchingInsertionContext currentContext = insertItem(indicator.getLookup(), item, completionChar, update, targetEditor, targetFile, targetCaretOffset, idEnd, targetOffsets.getOffsets());
      lastContext.set(currentContext);
    });
    context = lastContext.get();
  }
  else {
    PsiFile psiFile = PsiUtilBase.getPsiFileInEditor(editor, indicator.getProject());
    context = insertItem(indicator.getLookup(), item, completionChar, update, editor, psiFile, caretOffset, idEndOffset, indicator.getOffsetMap());
  }
  if (context.shouldAddCompletionChar()) {
    WriteAction.run(() -> addCompletionChar(context, item));
  }
  checkPsiTextConsistency(indicator);

  return context;
}
 
Example 12
Source File: EditorUtil.java    From consulo with Apache License 2.0 5 votes vote down vote up
public static void fillVirtualSpaceUntil(@Nonnull final Editor editor, int columnNumber, int lineNumber) {
  final int offset = editor.logicalPositionToOffset(new LogicalPosition(lineNumber, columnNumber));
  final String filler = EditorModificationUtil.calcStringToFillVirtualSpace(editor);
  if (!filler.isEmpty()) {
    WriteAction.run(() -> {
      editor.getDocument().insertString(offset, filler);
      editor.getCaretModel().moveToOffset(offset + filler.length());
    });
  }
}
 
Example 13
Source File: DirDiffTableModel.java    From consulo with Apache License 2.0 5 votes vote down vote up
public void performCopyTo(final DirDiffElementImpl element) {
  final DiffElement<?> source = element.getSource();
  if (source != null) {
    final String path = element.getParentNode().getPath();

    if (source instanceof BackgroundOperatingDiffElement) {
      final Ref<String> errorMessage = new Ref<>();
      final Ref<DiffElement> diff = new Ref<>();
      Runnable onFinish = () -> {
        ApplicationManager.getApplication().assertIsDispatchThread();
        if (!myDisposed) {
          DiffElement newElement = diff.get();
          if (newElement == null && element.getTarget() != null) {
            final int row = myElements.indexOf(element);
            element.updateTargetData();
            fireTableRowsUpdated(row, row);
          }
          refreshElementAfterCopyTo(newElement, element);
          if (!errorMessage.isNull()) {
            reportException(errorMessage.get());
          }
        }
      };
      ((BackgroundOperatingDiffElement)source).copyTo(myTrg, errorMessage, diff, onFinish, element.getTarget(), path);
    }
    else {
      WriteAction.run(() -> {
        final DiffElement<?> diffElement = source.copyTo(myTrg, path);
        refreshElementAfterCopyTo(diffElement, element);
      });
    }
  }
}
 
Example 14
Source File: XDebuggerTestUtil.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
public static String getConsoleText(final @Nonnull ConsoleViewImpl consoleView) {
  WriteAction.run(() -> {
    consoleView.flushDeferredText();
  });

  return consoleView.getEditor().getDocument().getText();
}
 
Example 15
Source File: JdksTest.java    From intellij with Apache License 2.0 5 votes vote down vote up
private void setJdks(List<Sdk> jdks) {
  List<Sdk> currentJdks =
      ReadAction.compute(
          () -> ProjectJdkTable.getInstance().getSdksOfType(JavaSdk.getInstance()));
  WriteAction.run(
      () -> {
        currentJdks.forEach(jdk -> ProjectJdkTable.getInstance().removeJdk(jdk));
        jdks.forEach(jdk -> ProjectJdkTable.getInstance().addJdk(jdk));
      });
}
 
Example 16
Source File: XDebuggerTestUtil.java    From consulo with Apache License 2.0 5 votes vote down vote up
public static void disposeDebugSession(final XDebugSession debugSession) {
  WriteAction.run(() -> {
    XDebugSessionImpl session = (XDebugSessionImpl)debugSession;
    Disposer.dispose(session.getSessionTab());
    Disposer.dispose(session.getConsoleView());
  });
}
 
Example 17
Source File: EndHandler.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Override
protected void doExecute(@Nonnull final Editor editor, Caret caret, DataContext dataContext) {
  CodeInsightSettings settings = CodeInsightSettings.getInstance();
  if (!settings.SMART_END_ACTION) {
    if (myOriginalHandler != null) {
      myOriginalHandler.execute(editor, caret, dataContext);
    }
    return;
  }

  final Project project = DataManager.getInstance().getDataContext(editor.getComponent()).getData(CommonDataKeys.PROJECT);
  if (project == null) {
    if (myOriginalHandler != null) {
      myOriginalHandler.execute(editor, caret, dataContext);
    }
    return;
  }
  final Document document = editor.getDocument();
  final PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(document);

  if (file == null) {
    if (myOriginalHandler != null){
      myOriginalHandler.execute(editor, caret, dataContext);
    }
    return;
  }

  final EditorNavigationDelegate[] extensions = EditorNavigationDelegate.EP_NAME.getExtensions();
  for (EditorNavigationDelegate delegate : extensions) {
    if (delegate.navigateToLineEnd(editor, dataContext) == EditorNavigationDelegate.Result.STOP) {
      return;
    }
  }

  final CaretModel caretModel = editor.getCaretModel();
  final int caretOffset = caretModel.getOffset();
  CharSequence chars = editor.getDocument().getCharsSequence();
  int length = editor.getDocument().getTextLength();

  if (caretOffset < length) {
    final int offset1 = CharArrayUtil.shiftBackward(chars, caretOffset - 1, " \t");
    if (offset1 < 0 || chars.charAt(offset1) == '\n' || chars.charAt(offset1) == '\r') {
      final int offset2 = CharArrayUtil.shiftForward(chars, offset1 + 1, " \t");
      boolean isEmptyLine = offset2 >= length || chars.charAt(offset2) == '\n' || chars.charAt(offset2) == '\r';
      if (isEmptyLine) {

        // There is a possible case that indent string is not calculated for particular document (that is true at least for plain text
        // documents). Hence, we check that and don't finish processing in case we have such a situation.
        boolean stopProcessing = true;
        PsiDocumentManager.getInstance(project).commitAllDocuments();
        CodeStyleManager styleManager = CodeStyleManager.getInstance(project);
        final String lineIndent = styleManager.getLineIndent(file, caretOffset);
        if (lineIndent != null) {
          int col = calcColumnNumber(lineIndent, editor.getSettings().getTabSize(project));
          int line = caretModel.getVisualPosition().line;
          caretModel.moveToVisualPosition(new VisualPosition(line, col));

          if (caretModel.getLogicalPosition().column != col){
            if (!ApplicationManager.getApplication().isWriteAccessAllowed() &&
                !FileDocumentManager.getInstance().requestWriting(editor.getDocument(), project)) {
              return;
            }
            editor.getSelectionModel().removeSelection();
            WriteAction.run(() -> document.replaceString(offset1 + 1, offset2, lineIndent));
          }
        }
        else {
          stopProcessing = false;
        }

        editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE);
        editor.getSelectionModel().removeSelection();
        if (stopProcessing) {
          return;
        }
      }
    }
  }

  if (myOriginalHandler != null){
    myOriginalHandler.execute(editor, caret, dataContext);
  }
}
 
Example 18
Source File: XDebuggerUtilImpl.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Override
public void removeBreakpoint(final Project project, final XBreakpoint<?> breakpoint) {
  WriteAction.run(() -> {
    XDebuggerManager.getInstance(project).getBreakpointManager().removeBreakpoint(breakpoint);
  });
}
 
Example 19
Source File: UnityEmptyMagicMethodInspection.java    From consulo-unity3d with Apache License 2.0 4 votes vote down vote up
@Override
public void invoke(@Nonnull Project project, @Nonnull PsiFile psiFile, @Nonnull PsiElement psiElement, @Nonnull PsiElement psiElement1)
{
	WriteAction.run(psiElement::delete);
}
 
Example 20
Source File: ModuleRootModificationUtil.java    From consulo with Apache License 2.0 4 votes vote down vote up
private static void doCommit(final ModifiableRootModel model) {
  WriteAction.run(model::commit);
}