public static void closeAndDisposeProjectAndCheckThatNoOpenProjects(
     @NotNull Project projectToClose, @NotNull List<Throwable> exceptions) {
   try {
     ProjectManagerEx projectManager = ProjectManagerEx.getInstanceEx();
     if (projectManager instanceof ProjectManagerImpl) {
       for (Project project : projectManager.closeTestProject(projectToClose)) {
         exceptions.add(
             new IllegalStateException(
                 "Test project is not disposed: "
                     + project
                     + ";\n created in: "
                     + getCreationPlace(project)));
         try {
           ((ProjectManagerImpl) projectManager).closeProject(project, false, true, false);
         } catch (Throwable e) {
           exceptions.add(e);
         }
       }
     }
   } catch (Throwable e) {
     exceptions.add(e);
   } finally {
     AccessToken token = WriteAction.start();
     try {
       Disposer.dispose(projectToClose);
     } catch (Throwable e) {
       exceptions.add(e);
     } finally {
       token.finish();
     }
   }
 }
  public boolean tryToSetUpGroovyFacetOnTheFly(final Module module) {
    final Project project = module.getProject();
    final Library[] libraries = getAllSDKLibraries(project);
    if (libraries.length > 0) {
      final Library library = libraries[0];
      int result =
          Messages.showOkCancelDialog(
              GroovyBundle.message(
                  "groovy.like.library.found.text",
                  module.getName(),
                  library.getName(),
                  getSDKLibVersion(library)),
              GroovyBundle.message("groovy.like.library.found"),
              JetgroovyIcons.Groovy.Groovy_32x32);
      if (result == Messages.OK) {
        AccessToken accessToken = WriteAction.start();

        try {
          ModifiableRootModel model = ModuleRootManager.getInstance(module).getModifiableModel();
          LibraryOrderEntry entry = model.addLibraryEntry(libraries[0]);
          LibrariesUtil.placeEntryToCorrectPlace(model, entry);
          model.commit();
          return true;
        } finally {
          accessToken.finish();
        }
      }
    }
    return false;
  }
 void disposeIndicator() {
   // our offset map should be disposed under write action, so that duringCompletion (read action)
   // won't access it after disposing
   AccessToken token = WriteAction.start();
   try {
     Disposer.dispose(this);
   } finally {
     token.finish();
   }
 }
 @Nullable
 private PsiType inferClosureReturnType() {
   final ExtractClosureHelperImpl mockHelper =
       new ExtractClosureHelperImpl(
           myInfo, "__test___n_", false, new TIntArrayList(), false, 0, false, false, false);
   final PsiType returnType;
   final AccessToken token = WriteAction.start();
   try {
     returnType = ExtractClosureProcessorBase.generateClosure(mockHelper).getReturnType();
   } finally {
     token.finish();
   }
   return returnType;
 }
示例#5
0
  private void insertString(VirtualFile file, int offset, @NotNull CharSequence s)
      throws InterruptedException {
    final Document document = FileDocumentManager.getInstance().getDocument(file);
    assertNotNull(document);
    AccessToken token = WriteAction.start();
    try {
      document.insertString(offset, s);
    } finally {
      token.finish();
    }

    semaphore.down();
    PsiDocumentManager.getInstance(myProject).commitAllDocuments();
    FileDocumentManager.getInstance().saveAllDocuments();
    await();
  }
示例#6
0
 @Override
 protected void moveOffsetAfter(boolean success) {
   RangeMarker exprMarker = getExprMarker();
   final AccessToken accessToken = WriteAction.start();
   try {
     Document document = myEditor.getDocument();
     // todo restore original expression if not success
     PsiDocumentManager.getInstance(myProject).commitDocument(document);
     if (exprMarker != null && exprMarker.isValid()) {
       myEditor.getCaretModel().moveToOffset(exprMarker.getStartOffset());
       myEditor.getScrollingModel().scrollToCaret(ScrollType.MAKE_VISIBLE);
       exprMarker.dispose();
     }
   } finally {
     accessToken.finish();
   }
 }
 protected void deleteClassFile(final String className) throws IOException {
   AccessToken token = WriteAction.start();
   try {
     if (useJps()) {
       //noinspection ConstantConditions
       touch(
           JavaPsiFacade.getInstance(getProject())
               .findClass(className)
               .getContainingFile()
               .getVirtualFile());
     } else {
       //noinspection ConstantConditions
       findClassFile(className).delete(this);
     }
   } finally {
     token.finish();
   }
 }
 private static boolean undoEvents(
     LookupImpl lookup, @NotNull final LinkedList<EditorChangeAction> events) {
   AccessToken token = WriteAction.start();
   try {
     return lookup.performGuardedChange(
         new Runnable() {
           @Override
           public void run() {
             for (EditorChangeAction event : events) {
               event.performUndo();
             }
           }
         },
         events.toString());
   } finally {
     token.finish();
   }
 }
  public static VirtualFile createTestProjectStructure(
      String tempName,
      Module module,
      String rootPath,
      Collection<File> filesToDelete,
      boolean addProjectRoots)
      throws IOException {
    File dir = FileUtil.createTempDirectory(tempName, null, false);
    filesToDelete.add(dir);

    VirtualFile vDir =
        LocalFileSystem.getInstance()
            .refreshAndFindFileByPath(dir.getCanonicalPath().replace(File.separatorChar, '/'));
    assert vDir != null && vDir.isDirectory() : dir;
    PlatformTestCase.synchronizeTempDirVfs(vDir);

    EdtTestUtil.runInEdtAndWait(
        () -> {
          AccessToken token = WriteAction.start();
          try {
            if (rootPath != null) {
              VirtualFile vDir1 =
                  LocalFileSystem.getInstance()
                      .findFileByPath(rootPath.replace(File.separatorChar, '/'));
              if (vDir1 == null) {
                throw new Exception(rootPath + " not found");
              }
              VfsUtil.copyDirectory(null, vDir1, vDir, null);
            }

            if (addProjectRoots) {
              addSourceContentToRoots(module, vDir);
            }
          } finally {
            token.finish();
          }
        });
    return vDir;
  }
  @Override
  public void updateProjectStructure(final @NotNull Module module) {
    if (!MvcModuleStructureUtil.isEnabledStructureUpdate()) return;

    final VirtualFile root = findAppRoot(module);
    if (root == null) return;

    AccessToken token = WriteAction.start();
    try {
      MvcModuleStructureUtil.updateModuleStructure(
          module, createProjectStructure(module, false), root);

      if (hasSupport(module)) {
        MvcModuleStructureUtil.updateAuxiliaryPluginsModuleRoots(module, this);
        MvcModuleStructureUtil.updateGlobalPluginModule(module.getProject(), this);
      }
    } finally {
      token.finish();
    }

    final Project project = module.getProject();
    ChangeListManager.getInstance(project)
        .addFilesToIgnore(IgnoredBeanFactory.ignoreUnderDirectory(getUserHomeGriffon(), project));
  }
  public static VirtualFile[] configureByFiles(
      @Nullable VirtualFile rawProjectRoot,
      VirtualFile[] files,
      @Nullable VirtualFile[] auxiliaryFiles,
      Module module,
      @Nullable
          TripleFunction<ModifiableRootModel, VirtualFile, List<String>, Void> moduleInitializer)
      throws Exception {
    return WriteAction.compute(
        () -> {
          VirtualFile dummyRoot = VirtualFileManager.getInstance().findFileByUrl("temp:///");
          //noinspection ConstantConditions
          dummyRoot.refresh(false, false);
          final VirtualFile sourceDir = dummyRoot.createChildDirectory(DesignerTests.class, "s");
          assert sourceDir != null;

          final IndexableFileSet indexableFileSet =
              new IndexableFileSet() {
                @Override
                public boolean isInSet(@NotNull final VirtualFile file) {
                  return file.getFileSystem() == sourceDir.getFileSystem();
                }

                @Override
                public void iterateIndexableFilesIn(
                    @NotNull final VirtualFile file, @NotNull final ContentIterator iterator) {
                  if (file.isDirectory()) {
                    for (VirtualFile child : file.getChildren()) {
                      iterateIndexableFilesIn(child, iterator);
                    }
                  } else {
                    iterator.processFile(file);
                  }
                }
              };
          FileBasedIndex.getInstance().registerIndexableSet(indexableFileSet, module.getProject());

          Disposer.register(
              module,
              new Disposable() {
                @Override
                public void dispose() {
                  FileBasedIndex.getInstance().removeIndexableSet(indexableFileSet);
                  ApplicationManager.getApplication()
                      .runWriteAction(
                          () -> {
                            try {
                              sourceDir.delete(null);
                            } catch (IOException e) {
                              throw new RuntimeException(e);
                            }
                          });
                }
              });

          final ModifiableRootModel rootModel =
              ModuleRootManager.getInstance(module).getModifiableModel();

          VirtualFile[] toFiles = copyFiles(files, sourceDir, rawProjectRoot);
          if (auxiliaryFiles != null) {
            copyFiles(auxiliaryFiles, sourceDir, rawProjectRoot);
          }

          rootModel.addContentEntry(sourceDir).addSourceFolder(sourceDir, false);
          final List<String> libs = new ArrayList<>();
          if (moduleInitializer != null) {
            moduleInitializer.fun(rootModel, sourceDir, libs);
          }
          rootModel.commit();

          for (String path : libs) {
            VirtualFile virtualFile = path.charAt(0) != '/' ? getFile("lib", path) : getFile(path);
            FlexTestUtils.addLibrary(
                module, path, virtualFile.getParent().getPath(), virtualFile.getName(), null, null);
          }
          return toFiles;
        });
  }
  @Override
  public void actionPerformed(AnActionEvent e) {
    DataContext dataContext = e.getDataContext();
    final Editor editor = CommonDataKeys.EDITOR.getData(dataContext);
    PsiFile file = CommonDataKeys.PSI_FILE.getData(dataContext);

    final Project project = file.getProject();
    PsiDocumentManager.getInstance(project).commitAllDocuments();

    final TextRange selection =
        new TextRange(
            editor.getSelectionModel().getSelectionStart(),
            editor.getSelectionModel().getSelectionEnd());
    PsiElement current = file.findElementAt(selection.getStartOffset());
    int startOffset = selection.getStartOffset();
    while (current instanceof PsiWhiteSpace) {
      current = current.getNextSibling();
      if (current == null) break;
      startOffset = current.getTextRange().getStartOffset();
    }

    if (startOffset >= selection.getEndOffset()) startOffset = selection.getStartOffset();

    final PsiElement[] psiElements =
        PsiTreeUtil.collectElements(
            file,
            new PsiElementFilter() {
              @Override
              public boolean isAccepted(PsiElement element) {
                return selection.contains(element.getTextRange())
                    && element.getReferences().length > 0;
              }
            });

    final Document document =
        EditorFactory.getInstance()
            .createDocument(
                editor.getDocument().getText().substring(startOffset, selection.getEndOffset()));
    final boolean isXml = file.getLanguage().is(StdLanguages.XML);
    final int offsetDelta = startOffset;
    new WriteCommandAction.Simple(project, (String) null) {
      @Override
      protected void run() throws Throwable {
        Map<RangeMarker, String> rangeToText = new HashMap<RangeMarker, String>();

        for (PsiElement element : psiElements) {
          for (PsiReference reference : element.getReferences()) {
            if (!(reference instanceof PsiQualifiedReference)
                || ((PsiQualifiedReference) reference).getQualifier() == null) {
              String canonicalText = reference.getCanonicalText();
              LOG.assertTrue(canonicalText != null, reference.getClass());
              TextRange referenceRange = reference.getRangeInElement();
              final TextRange elementTextRange = element.getTextRange();
              LOG.assertTrue(elementTextRange != null, elementTextRange);
              final TextRange range =
                  elementTextRange.cutOut(referenceRange).shiftRight(-offsetDelta);
              final String oldText = document.getText(range);
              // workaround for Java references: canonicalText contains generics, and we need to cut
              // them off because otherwise
              // they will be duplicated
              int pos = canonicalText.indexOf('<');
              if (pos > 0 && !oldText.contains("<")) {
                canonicalText = canonicalText.substring(0, pos);
              }
              if (isXml) { // strip namespace prefixes
                pos = canonicalText.lastIndexOf(':');
                if (pos >= 0 && pos < canonicalText.length() - 1 && !oldText.contains(":")) {
                  canonicalText = canonicalText.substring(pos + 1);
                }
              }
              if (!canonicalText.equals(oldText)) {
                rangeToText.put(document.createRangeMarker(range), canonicalText);
              }
            }
          }
        }

        for (Map.Entry<RangeMarker, String> entry : rangeToText.entrySet()) {
          document.replaceString(
              entry.getKey().getStartOffset(), entry.getKey().getEndOffset(), entry.getValue());
        }
      }
    }.execute();

    final TemplateImpl template =
        new TemplateImpl(
            TemplateListPanel.ABBREVIATION, document.getText(), TemplateSettings.USER_GROUP_NAME);
    template.setToReformat(true);

    PsiFile copy;
    AccessToken token = WriteAction.start();
    try {
      copy = TemplateManagerImpl.insertDummyIdentifier(editor, file);
    } finally {
      token.finish();
    }
    Set<TemplateContextType> applicable =
        TemplateManagerImpl.getApplicableContextTypes(copy, startOffset);

    for (TemplateContextType contextType : TemplateManagerImpl.getAllContextTypes()) {
      template.getTemplateContext().setEnabled(contextType, applicable.contains(contextType));
    }

    final LiveTemplatesConfigurable configurable = new LiveTemplatesConfigurable();
    ShowSettingsUtil.getInstance()
        .editConfigurable(
            project, configurable, () -> configurable.getTemplateListPanel().addTemplate(template));
  }