com.intellij.openapi.application.WriteAction Java Examples

The following examples show how to use com.intellij.openapi.application.WriteAction. 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: 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 #2
Source File: AndroidModuleLibraryManager.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public void init41(@Nullable ProgressIndicator indicator) {
  boolean finished = false;
  try {
    //ProjectManagerImpl.initProject(path, this, true, null, null);
    Method method = ReflectionUtil
      .getDeclaredMethod(ProjectManagerImpl.class, "initProject", Path.class, ProjectImpl.class, boolean.class, Project.class,
                         ProgressIndicator.class);
    assert (method != null);
    try {
      method.invoke(null, path, this, true, null, null);
    }
    catch (IllegalAccessException | InvocationTargetException e) {
      throw new RuntimeException(e);
    }
    finished = true;
  }
  finally {
    if (!finished) {
      TransactionGuard.submitTransaction(this, () -> WriteAction.run(() -> Disposer.dispose(this)));
    }
  }
}
 
Example #3
Source File: AndroidModuleLibraryManager.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public void init41(@Nullable ProgressIndicator indicator) {
  boolean finished = false;
  try {
    //ProjectManagerImpl.initProject(path, this, true, null, null);
    Method method = ReflectionUtil
      .getDeclaredMethod(ProjectManagerImpl.class, "initProject", Path.class, ProjectImpl.class, boolean.class, Project.class,
                         ProgressIndicator.class);
    assert (method != null);
    try {
      method.invoke(null, path, this, true, null, null);
    }
    catch (IllegalAccessException | InvocationTargetException e) {
      throw new RuntimeException(e);
    }
    finished = true;
  }
  finally {
    if (!finished) {
      TransactionGuard.submitTransaction(this, () -> WriteAction.run(() -> Disposer.dispose(this)));
    }
  }
}
 
Example #4
Source File: MavenTestCase.java    From intellij-quarkus with Eclipse Public License 2.0 6 votes vote down vote up
private static VirtualFile createProfilesFile(final VirtualFile dir, String content) {
  VirtualFile f = dir.findChild("profiles.xml");
  if (f == null) {
    try {
      f = WriteAction.computeAndWait(() -> {
        VirtualFile res = dir.createChildData(null, "profiles.xml");
        return res;
      });
    }
    catch (IOException e) {
      throw new RuntimeException(e);
    }
  }
  setFileContent(f, content, true);
  return f;
}
 
Example #5
Source File: MavenTestCase.java    From intellij-quarkus with Eclipse Public License 2.0 6 votes vote down vote up
protected VirtualFile createPomFile(final VirtualFile dir,
                                    @Language(value = "XML", prefix = "<project>", suffix = "</project>") String xml) {
  VirtualFile f = dir.findChild("pom.xml");
  if (f == null) {
    try {
      f = WriteAction.computeAndWait(() -> {
        VirtualFile res = dir.createChildData(null, "pom.xml");
        return res;
      });
    }
    catch (IOException e) {
      throw new RuntimeException(e);
    }
    myAllPoms.add(f);
  }
  setFileContent(f, createPomXml(xml), true);
  return f;
}
 
Example #6
Source File: ToggleReadOnlyAttributePanel.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public Consumer<MouseEvent> getClickConsumer() {
  return mouseEvent -> {
    final VirtualFile file = getCurrentFile();
    if (!isReadOnlyApplicableForFile(file)) {
      return;
    }
    FileDocumentManager.getInstance().saveAllDocuments();

    try {
      WriteAction.run(() -> ReadOnlyAttributeUtil.setReadOnlyAttribute(file, file.isWritable()));
      myStatusBar.updateWidget(ID());
    }
    catch (IOException e) {
      Messages.showMessageDialog(getProject(), e.getMessage(), UIBundle.message("error.dialog.title"), Messages.getErrorIcon());
    }
  };
}
 
Example #7
Source File: GradleImportingTestCase.java    From intellij-quarkus with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public void tearDown() throws Exception {
  if (myJdkHome == null) {
    //super.setUp() wasn't called
    return;
  }
  new RunAll(
    () -> {
      Sdk jdk = ProjectJdkTable.getInstance().findJdk(GRADLE_JDK_NAME);
      if (jdk != null) {
        WriteAction.runAndWait(() -> ProjectJdkTable.getInstance().removeJdk(jdk));
      }
    },
    () -> {
      Messages.setTestDialog(TestDialog.DEFAULT);
      deleteBuildSystemDirectory();
    },
    () -> super.tearDown()
  ).run();
}
 
Example #8
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 #9
Source File: XDebuggerUtilImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
public static <P extends XBreakpointProperties> XLineBreakpoint toggleAndReturnLineBreakpoint(@Nonnull final Project project,
                                                                                              @Nonnull final XLineBreakpointType<P> type,
                                                                                              @Nonnull final VirtualFile file,
                                                                                              final int line,
                                                                                              final boolean temporary) {
  return WriteAction.compute(() -> {
    XBreakpointManager breakpointManager = XDebuggerManager.getInstance(project).getBreakpointManager();
    XLineBreakpoint<P> breakpoint = breakpointManager.findBreakpointAtLine(type, file, line);
    if (breakpoint != null) {
      breakpointManager.removeBreakpoint(breakpoint);
      return null;
    }
    else {
      P properties = type.createBreakpointProperties(file, line);
      return breakpointManager.addLineBreakpoint(type, file.getUrl(), line, properties, temporary);
    }
  });
}
 
Example #10
Source File: AndroidModuleLibraryManager.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public void initPre41(@Nullable ProgressIndicator indicator) {
  boolean finished = false;
  try {
    //registerComponents();
    Method method = ReflectionUtil.getDeclaredMethod(ProjectImpl.class, "registerComponents");
    assert (method != null);
    try {
      method.invoke(this);
    }
    catch (IllegalAccessException | InvocationTargetException e) {
      throw new RuntimeException(e);
    }
    getStateStore().setPath(path, true, null);
    super.init(indicator);
    finished = true;
  }
  finally {
    if (!finished) {
      TransactionGuard.submitTransaction(this, () -> WriteAction.run(() -> Disposer.dispose(this)));
    }
  }
}
 
Example #11
Source File: AndroidModuleLibraryManager.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public void initPre41(@Nullable ProgressIndicator indicator) {
  boolean finished = false;
  try {
    //registerComponents();
    Method method = ReflectionUtil.getDeclaredMethod(ProjectImpl.class, "registerComponents");
    assert (method != null);
    try {
      method.invoke(this);
    }
    catch (IllegalAccessException | InvocationTargetException e) {
      throw new RuntimeException(e);
    }
    getStateStore().setPath(path, true, null);
    super.init(indicator);
    finished = true;
  }
  finally {
    if (!finished) {
      TransactionGuard.submitTransaction(this, () -> WriteAction.run(() -> Disposer.dispose(this)));
    }
  }
}
 
Example #12
Source File: AbstractLibraryManager.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
protected void updateLibraryContent(@NotNull Set<String> contentUrls) {
  if (!FlutterModuleUtils.declaresFlutter(project)) {
    // If we have a Flutter library, remove it.
    final LibraryTable libraryTable = LibraryTablesRegistrar.getInstance().getLibraryTable(project);
    final Library existingLibrary = getLibraryByName(getLibraryName());
    if (existingLibrary != null) {
      WriteAction.compute(() -> {
        final LibraryTable.ModifiableModel libraryTableModel = libraryTable.getModifiableModel();
        libraryTableModel.removeLibrary(existingLibrary);
        libraryTableModel.commit();
        return null;
      });
    }
    return;
  }
  updateLibraryContent(getLibraryName(), contentUrls, null);
}
 
Example #13
Source File: AbstractLibraryManager.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
protected static void addFlutterLibraryDependency(@NotNull Module module, @NotNull Library library) {
  final ModifiableRootModel modifiableModel = ModuleRootManager.getInstance(module).getModifiableModel();

  try {
    for (final OrderEntry orderEntry : modifiableModel.getOrderEntries()) {
      if (orderEntry instanceof LibraryOrderEntry &&
          LibraryTablesRegistrar.PROJECT_LEVEL.equals(((LibraryOrderEntry)orderEntry).getLibraryLevel()) &&
          StringUtil.equals(library.getName(), ((LibraryOrderEntry)orderEntry).getLibraryName())) {
        return; // dependency already exists
      }
    }

    modifiableModel.addLibraryEntry(library);

    ApplicationManager.getApplication().invokeAndWait(() -> WriteAction.run(modifiableModel::commit));
  }
  finally {
    if (!modifiableModel.isDisposed()) {
      modifiableModel.dispose();
    }
  }
}
 
Example #14
Source File: AbstractLibraryManager.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
protected void updateLibraryContent(@NotNull Set<String> contentUrls) {
  if (!FlutterModuleUtils.declaresFlutter(project)) {
    // If we have a Flutter library, remove it.
    final LibraryTable libraryTable = LibraryTablesRegistrar.getInstance().getLibraryTable(project);
    final Library existingLibrary = getLibraryByName(getLibraryName());
    if (existingLibrary != null) {
      WriteAction.compute(() -> {
        final LibraryTable.ModifiableModel libraryTableModel = libraryTable.getModifiableModel();
        libraryTableModel.removeLibrary(existingLibrary);
        libraryTableModel.commit();
        return null;
      });
    }
    return;
  }
  updateLibraryContent(getLibraryName(), contentUrls, null);
}
 
Example #15
Source File: ModuleManagerImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public void afterLoadState() {
  boolean firstLoad = myFirstLoad;
  if (firstLoad) {
    myFirstLoad = false;
  }

  // if file changed, load changes
  if (!firstLoad) {
    ModuleModelImpl model = new ModuleModelImpl(myModuleModel);
    // dispose not exists module
    for (Module module : model.getModules()) {
      ModuleLoadItem item = findModuleByUrl(module.getName(), module.getModuleDirUrl());
      if (item == null) {
        WriteAction.run(() -> model.disposeModule(module));
      }
    }

    loadModules(model, null, false);

    WriteAction.run(model::commit);
  }
  else {
    doFirstModulesLoad();
  }
}
 
Example #16
Source File: HaxeProjectSdkSetupValidator.java    From intellij-haxe with Apache License 2.0 6 votes vote down vote up
private void pruneExcessiveRoots(Project project, VirtualFile file) {
  final Module module = ModuleUtilCore.findModuleForFile(file, project);
  if (module != null && !module.isDisposed()) {
    final Sdk sdk = ModuleRootManager.getInstance(module).getSdk();
    if (sdk != null) {
      final SdkModificator modificator = sdk.getSdkModificator();
      final VirtualFile stdRoot = getDistinctRootsStream(sdk)
        .filter(root -> root.findChild(STD_TYPES_HX) != null)
        .findFirst()
        .orElse(null);

      if (stdRoot != null) {
        modificator.removeAllRoots();
        modificator.addRoot(stdRoot, OrderRootType.CLASSES);
        modificator.addRoot(stdRoot, OrderRootType.SOURCES);
        WriteAction.run(modificator::commitChanges);
      }
    }
  }
}
 
Example #17
Source File: CreateNewLibraryAction.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nullable
public static Library createLibrary(@Nullable final LibraryType type,
                                    @Nonnull final JComponent parentComponent,
                                    @Nonnull final Project project,
                                    @Nonnull final LibrariesModifiableModel modifiableModel) {
  final NewLibraryConfiguration configuration = createNewLibraryConfiguration(type, parentComponent, project);
  if (configuration == null) return null;
  final LibraryType<?> libraryType = configuration.getLibraryType();
  final Library library = modifiableModel
    .createLibrary(LibraryEditingUtil.suggestNewLibraryName(modifiableModel, configuration.getDefaultLibraryName()),
                   libraryType != null ? libraryType.getKind() : null);

  final NewLibraryEditor editor = new NewLibraryEditor(libraryType, configuration.getProperties());
  configuration.addRoots(editor);
  final Library.ModifiableModel model = library.getModifiableModel();
  editor.applyTo((LibraryEx.ModifiableModelEx)model);
  WriteAction.run(model::commit);
  return library;
}
 
Example #18
Source File: SourceJarGenerator.java    From intellij-pants-plugin with Apache License 2.0 6 votes vote down vote up
public static void attachSourceJar(@NotNull File sourceJar, @NotNull Collection<? extends Library> libraries) {
  VirtualFile srcFile = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(sourceJar);
  if (srcFile == null) return;

  VirtualFile jarRoot = JarFileSystem.getInstance().getJarRootForLocalFile(srcFile);
  if (jarRoot == null) return;

  WriteAction.run(() -> {
    for (Library library : libraries) {
      Library.ModifiableModel model = library.getModifiableModel();
      List<VirtualFile> alreadyExistingFiles = Arrays.asList(model.getFiles(OrderRootType.SOURCES));

      if (!alreadyExistingFiles.contains(jarRoot)) {
        model.addRoot(jarRoot, OrderRootType.SOURCES);
      }
      model.commit();
    }
  });
}
 
Example #19
Source File: LocalFileSystemTest.java    From consulo with Apache License 2.0 6 votes vote down vote up
public void testDuplicateViaRename() throws Exception {
  WriteAction.run(() -> {
    VirtualFile tempDir = myFS.refreshAndFindFileByIoFile(createTempDirectory());
    assertNotNull(tempDir);

    VirtualFile file1 = tempDir.createChildData(this, "a.txt");
    FileUtil.delete(VfsUtilCore.virtualToIoFile(file1));

    VirtualFile file2 = tempDir.createChildData(this, "b.txt");
    try {
      file2.rename(this, "a.txt");
      fail("duplicate file name should have been rejected");
    }
    catch (IOException e) {
      assertEquals(VfsBundle.message("vfs.target.already.exists.error", file1.getPath()), e.getMessage());
    }
  });
}
 
Example #20
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 #21
Source File: VirtualFileListenerTest.java    From consulo with Apache License 2.0 6 votes vote down vote up
public void testFireEvent() throws IOException {
  final VirtualFile dir = getVirtualFile(createTempDir("vDir"));
  assertNotNull(dir);
  dir.getChildren();
  final Ref<Boolean> eventFired = Ref.create(false);
  VirtualFileManager.getInstance().addVirtualFileListener(new VirtualFileAdapter() {
    @Override
    public void fileCreated(@Nonnull VirtualFileEvent event) {
      eventFired.set(true);
    }
  }, myTestRootDisposable);

  WriteAction.run(() -> {
    try {
      dir.createChildData(this, "x.txt");
    }
    catch (IOException e) {
      throw new RuntimeException(e);
    }
  });

  assertTrue(eventFired.get());
}
 
Example #22
Source File: VfsUtilTest.java    From consulo with Apache License 2.0 6 votes vote down vote up
public void testDirAttributeRefreshes() throws IOException {
  File tempDir = WriteAction.compute(() -> {
    File res = createTempDirectory();
    return res;
  });
  VirtualFile vDir = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(tempDir);
  assertNotNull(vDir);
  assertTrue(vDir.isDirectory());

  File file = FileUtil.createTempFile(tempDir, "xxx", "yyy", true);
  assertNotNull(file);
  VirtualFile vFile = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(file);
  assertNotNull(vFile);
  assertFalse(vFile.isDirectory());

  boolean deleted = file.delete();
  assertTrue(deleted);
  boolean created = file.mkdir();
  assertTrue(created);
  assertTrue(file.exists());

  VirtualFile vFile2 = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(file);
  assertNotNull(vFile2);
  assertTrue(vFile2.isDirectory());
}
 
Example #23
Source File: AbstractLibraryManager.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
protected static void removeFlutterLibraryDependency(@NotNull Module module, @NotNull Library library) {
  final ModifiableRootModel modifiableModel = ModuleRootManager.getInstance(module).getModifiableModel();

  try {
    boolean wasFound = false;

    for (final OrderEntry orderEntry : modifiableModel.getOrderEntries()) {
      if (orderEntry instanceof LibraryOrderEntry &&
          LibraryTablesRegistrar.PROJECT_LEVEL.equals(((LibraryOrderEntry)orderEntry).getLibraryLevel()) &&
          StringUtil.equals(library.getName(), ((LibraryOrderEntry)orderEntry).getLibraryName())) {
        wasFound = true;
        modifiableModel.removeOrderEntry(orderEntry);
      }
    }

    if (wasFound) {
      ApplicationManager.getApplication().invokeAndWait(() -> WriteAction.run(modifiableModel::commit));
    }
  }
  finally {
    if (!modifiableModel.isDisposed()) {
      modifiableModel.dispose();
    }
  }
}
 
Example #24
Source File: AbstractLibraryManager.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
protected static void addFlutterLibraryDependency(@NotNull Module module, @NotNull Library library) {
  final ModifiableRootModel modifiableModel = ModuleRootManager.getInstance(module).getModifiableModel();

  try {
    for (final OrderEntry orderEntry : modifiableModel.getOrderEntries()) {
      if (orderEntry instanceof LibraryOrderEntry &&
          LibraryTablesRegistrar.PROJECT_LEVEL.equals(((LibraryOrderEntry)orderEntry).getLibraryLevel()) &&
          StringUtil.equals(library.getName(), ((LibraryOrderEntry)orderEntry).getLibraryName())) {
        return; // dependency already exists
      }
    }

    modifiableModel.addLibraryEntry(library);

    ApplicationManager.getApplication().invokeAndWait(() -> WriteAction.run(modifiableModel::commit));
  }
  finally {
    if (!modifiableModel.isDisposed()) {
      modifiableModel.dispose();
    }
  }
}
 
Example #25
Source File: XDebuggerTestUtil.java    From consulo with Apache License 2.0 5 votes vote down vote up
public static <T extends XBreakpointType> XBreakpoint addBreakpoint(@Nonnull final Project project, @Nonnull final Class<T> exceptionType, @Nonnull final XBreakpointProperties properties) {
  final XBreakpointManager breakpointManager = XDebuggerManager.getInstance(project).getBreakpointManager();
  List<XBreakpointType> types = XBreakpointUtil.getBreakpointTypes();
  final Ref<XBreakpoint> breakpoint = Ref.create(null);
  for (XBreakpointType type : types) {
    if (exceptionType.isInstance(type)) {
      final T breakpointType = exceptionType.cast(type);
      WriteAction.run(() -> breakpoint.set(breakpointManager.addBreakpoint(breakpointType, properties)));
      break;
    }
  }
  return breakpoint.get();
}
 
Example #26
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 #27
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 #28
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 #29
Source File: PackagingElementsTestCase.java    From consulo with Apache License 2.0 5 votes vote down vote up
static Library addProjectLibrary(final Project project, final @javax.annotation.Nullable Module module, final String name, final DependencyScope scope, final VirtualFile[] jars) {
  return WriteAction.compute(() -> {
    final Library library = LibraryTablesRegistrar.getInstance().getLibraryTable(project).createLibrary(name);
    final Library.ModifiableModel libraryModel = library.getModifiableModel();
    for (VirtualFile jar : jars) {
      libraryModel.addRoot(jar, BinariesOrderRootType.getInstance());
    }
    libraryModel.commit();
    if (module != null) {
      ModuleRootModificationUtil.addDependency(module, library, scope, false);
    }
    return library;
  });
}
 
Example #30
Source File: PlatformTestCase.java    From consulo with Apache License 2.0 5 votes vote down vote up
protected static VirtualFile createChildData(@Nonnull final VirtualFile dir, @Nonnull @NonNls final String name) {
  try {
    return WriteAction.compute(() -> dir.createChildData(null, name));
  }
  catch (IOException e) {
    throw new RuntimeException(e);
  }
}