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();
     }
   }
 }
Example #2
0
  @NotNull
  public static Project loadProject(File projectFile) {
    if (!projectFile.exists()) {
      throw new RuntimeException("Can't find project file " + projectFile.getAbsolutePath());
    }

    final ProjectManagerEx projectManager = ProjectManagerEx.getInstanceEx();

    final String filePath = projectFile.getAbsolutePath();

    // this is a workaround for MPS-8840
    final com.intellij.openapi.project.Project[] project =
        new com.intellij.openapi.project.Project[1];

    ThreadUtils.runInUIThreadAndWait(
        new Runnable() {
          public void run() {
            try {
              project[0] = projectManager.loadAndOpenProject(filePath, false);
            } catch (IOException e) {
              throw new RuntimeException(e);
            } catch (JDOMException e) {
              throw new RuntimeException(e);
            } catch (InvalidDataException e) {
              throw new RuntimeException(e);
            }
          }
        });

    if (project[0] == null) {
      // this actually happens
      throw new RuntimeException(
          "ProjectManager could not load project from " + projectFile.getAbsolutePath());
    }

    ModelAccess.instance()
        .runReadAction(
            new Runnable() {
              public void run() {
                new ModuleMaker()
                    .make(
                        new LinkedHashSet<IModule>(
                            MPSModuleRepository.getInstance().getAllModules()),
                        new EmptyProgressMonitor());
              }
            });

    projectManager.openProject(project[0]);
    return project[0].getComponent(MPSProject.class);
  }
  private boolean disposeSelf() {
    myDisposeInProgress = true;
    final CommandProcessor commandProcessor = CommandProcessor.getInstance();
    final Ref<Boolean> canClose = new Ref<Boolean>(Boolean.TRUE);
    for (final Project project : ProjectManagerEx.getInstanceEx().getOpenProjects()) {
      try {
        commandProcessor.executeCommand(
            project,
            new Runnable() {
              public void run() {
                canClose.set(ProjectUtil.closeAndDispose(project));
              }
            },
            ApplicationBundle.message("command.exit"),
            null);
      } catch (Throwable e) {
        LOG.error(e);
      }
      if (!canClose.get()) {
        myDisposeInProgress = false;
        return false;
      }
    }
    Disposer.dispose(this);

    Disposer.assertIsEmpty();
    return true;
  }
  @Override
  protected void setUp() throws Exception {
    super.setUp();
    myFilesToDelete.add(new File(FileUtilRt.getTempDirectory()));
    if (ourTestCase != null) {
      String message =
          "Previous test "
              + ourTestCase
              + " hasn't called tearDown(). Probably overridden without super call.";
      ourTestCase = null;
      fail(message);
    }
    IdeaLogger.ourErrorsOccurred = null;

    LOG.info(getClass().getName() + ".setUp()");

    initApplication();

    myEditorListenerTracker = new EditorListenerTracker();
    myThreadTracker = new ThreadTracker();

    setUpProject();

    storeSettings();
    ourTestCase = this;
    if (myProject != null) {
      ProjectManagerEx.getInstanceEx().openTestProject(myProject);
      CodeStyleSettingsManager.getInstance(myProject).setTemporarySettings(new CodeStyleSettings());
      InjectedLanguageManagerImpl.pushInjectors(getProject());
    }

    DocumentCommitThread.getInstance().clearQueue();
    UIUtil.dispatchAllInvocationEvents();
  }
  private boolean canExit() {
    for (ApplicationListener applicationListener : myDispatcher.getListeners()) {
      if (!applicationListener.canExitApplication()) {
        return false;
      }
    }

    ProjectManagerEx projectManager = (ProjectManagerEx) ProjectManager.getInstance();
    Project[] projects = projectManager.getOpenProjects();
    for (Project project : projects) {
      if (!projectManager.canClose(project)) {
        return false;
      }
    }

    return true;
  }
  @Override
  protected void setUpProject() throws Exception {
    myProjectManager = ProjectManagerEx.getInstanceEx();
    LOG.assertTrue(myProjectManager != null, "Cannot instantiate ProjectManager component");

    File projectFile = getIprFile();
    loadAndSetupProject(projectFile.getPath());
  }
Example #7
0
  public void _testCloseAndOpenProject() throws Exception {
    File temp = createTempDirectory();
    final Project alienProject = createProject(temp + "/t.ipr", DebugUtil.currentStackTrace());
    assertTrue(ProjectManagerEx.getInstanceEx().openProject(alienProject));
    UIUtil.dispatchAllInvocationEvents(); // startup activities

    openAndWait(configureByFiles("injectedAS/Transitions.mxml")[0], "injectedAS/Transitions.mxml");
  }
  protected void setUpProject() throws Exception {
    myProjectManager = ProjectManagerEx.getInstanceEx();
    assertNotNull("Cannot instantiate ProjectManager component", myProjectManager);

    File projectFile = getIprFile();

    myProject = doCreateProject(projectFile);
    myProjectManager.openTestProject(myProject);
    LocalFileSystem.getInstance().refreshIoFiles(myFilesToDelete);

    setUpModule();

    setUpJdk();

    LightPlatformTestCase.clearUncommittedDocuments(getProject());

    runStartupActivities();
    ((FileTypeManagerImpl) FileTypeManager.getInstance()).drainReDetectQueue();
  }
Example #9
0
  public static void doTearDown() throws Exception {
    UsefulTestCase.doPostponedFormatting(ourProject);

    LookupManager.getInstance(ourProject).hideActiveLookup();

    InspectionProfileManager.getInstance().deleteProfile(PROFILE);
    assertNotNull("Application components damaged", ProjectManager.getInstance());

    ApplicationManager.getApplication()
        .runWriteAction(
            new Runnable() {
              public void run() {
                try {
                  final VirtualFile[] children = ourSourceRoot.getChildren();
                  for (VirtualFile child : children) {
                    child.delete(this);
                  }
                } catch (IOException e) {
                  //noinspection CallToPrintStackTrace
                  e.printStackTrace();
                }
                FileDocumentManager manager = FileDocumentManager.getInstance();
                if (manager instanceof FileDocumentManagerImpl) {
                  ((FileDocumentManagerImpl) manager).dropAllUnsavedDocuments();
                }
              }
            });
    //    final Project[] openProjects = ProjectManagerEx.getInstanceEx().getOpenProjects();
    //    assertTrue(Arrays.asList(openProjects).contains(ourProject));
    assertFalse(PsiManager.getInstance(getProject()).isDisposed());
    if (!ourAssertionsInTestDetected) {
      if (IdeaLogger.ourErrorsOccurred != null) {
        throw IdeaLogger.ourErrorsOccurred;
      }
      // assertTrue("Logger errors occurred. ", IdeaLogger.ourErrorsOccurred == null);
    }
    ((PsiDocumentManagerImpl) PsiDocumentManager.getInstance(getProject()))
        .clearUncommitedDocuments();

    ((UndoManagerImpl) UndoManager.getGlobalInstance()).dropHistoryInTests();

    ProjectManagerEx.getInstanceEx().setCurrentTestProject(null);
    ourApplication.setDataProvider(null);
    ourTestCase = null;
    ((PsiManagerImpl) ourPsiManager).cleanupForNextTest();

    final Editor[] allEditors = EditorFactory.getInstance().getAllEditors();
    if (allEditors.length > 0) {
      for (Editor allEditor : allEditors) {
        EditorFactory.getInstance().releaseEditor(allEditor);
      }
      fail("Unreleased editors: " + allEditors.length);
    }
  }
  public void testExternalFileModificationWhileProjectClosed() throws Exception {
    VirtualFile root = ProjectRootManager.getInstance(myProject).getContentRoots()[0];

    PsiClass objectClass =
        myJavaFacade.findClass(
            CommonClassNames.JAVA_LANG_OBJECT, GlobalSearchScope.allScope(getProject()));
    assertNotNull(objectClass);
    checkUsages(objectClass, new String[] {});
    FileBasedIndex.getInstance()
        .getContainingFiles(
            TodoIndex.NAME,
            new TodoIndexEntry("todo", true),
            GlobalSearchScope.allScope(getProject()));

    final String projectLocation = myProject.getPresentableUrl();
    assert projectLocation != null : myProject;
    PlatformTestUtil.saveProject(myProject);
    final VirtualFile content = ModuleRootManager.getInstance(getModule()).getContentRoots()[0];
    Project project = myProject;
    ProjectUtil.closeAndDispose(project);
    InjectedLanguageManagerImpl.checkInjectorsAreDisposed(project);

    assertTrue("Project was not disposed", myProject.isDisposed());
    myModule = null;

    final File file = new File(root.getPath(), "1.java");
    assertTrue(file.exists());

    FileUtil.writeToFile(file, "class A{ Object o;}".getBytes(CharsetToolkit.UTF8_CHARSET));
    root.refresh(false, true);

    LocalFileSystem.getInstance().refresh(false);

    myProject = ProjectManager.getInstance().loadAndOpenProject(projectLocation);
    InjectedLanguageManagerImpl.pushInjectors(getProject());

    setUpModule();
    setUpJdk();
    ProjectManagerEx.getInstanceEx().openTestProject(myProject);
    UIUtil.dispatchAllInvocationEvents(); // startup activities

    runStartupActivities();
    PsiTestUtil.addSourceContentToRoots(getModule(), content);

    assertNotNull(myProject);
    myPsiManager = (PsiManagerImpl) PsiManager.getInstance(myProject);
    myJavaFacade = JavaPsiFacadeEx.getInstanceEx(myProject);

    objectClass =
        myJavaFacade.findClass(
            CommonClassNames.JAVA_LANG_OBJECT, GlobalSearchScope.allScope(getProject()));
    assertNotNull(objectClass);
    checkUsages(objectClass, new String[] {"1.java"});
  }
  @NotNull
  public static Project createProject(@NotNull String path, String creationPlace) {
    String fileName = PathUtilRt.getFileName(path);
    String projectName = FileUtilRt.getNameWithoutExtension(fileName);
    VirtualFile projectBase =
        LocalFileSystem.getInstance()
            .findFileByPath(
                FileUtil.toSystemIndependentName(
                    fileName.endsWith(ProjectFileType.DOT_DEFAULT_EXTENSION)
                        ? PathUtilRt.getParentPath(path)
                        : path));
    if (projectBase != null) {
      // must be leftovers from the previous test run
      for (VirtualFile file : ((NewVirtualFile) projectBase).iterInDbChildren()) {
        delete(file);
      }
    }

    try {
      Project project =
          ProjectManagerEx.getInstanceEx().newProject(projectName, path, false, false);
      assert project != null;

      project.putUserData(CREATION_PLACE, creationPlace);
      return project;
    } catch (TooManyProjectLeakedException e) {
      StringBuilder leakers = new StringBuilder();
      leakers.append("Too many projects leaked: \n");
      for (Project project : e.getLeakedProjects()) {
        String presentableString = getCreationPlace(project);
        leakers.append(presentableString);
        leakers.append("\n");
      }

      fail(leakers.toString());
      return null;
    }
  }
Example #12
0
  public static void doSetup(
      final LightProjectDescriptor descriptor,
      final LocalInspectionTool[] localInspectionTools,
      final Map<String, InspectionTool> availableInspectionTools)
      throws Exception {
    assertNull(
        "Previous test "
            + ourTestCase
            + " hasn't called tearDown(). Probably overriden without super call.",
        ourTestCase);
    IdeaLogger.ourErrorsOccurred = null;

    if (ourProject == null || !ourProjectDescriptor.equals(descriptor)) {
      initProject(descriptor);
    }

    ProjectManagerEx.getInstanceEx().setCurrentTestProject(ourProject);

    ((PsiDocumentManagerImpl) PsiDocumentManager.getInstance(getProject()))
        .clearUncommitedDocuments();

    for (LocalInspectionTool tool : localInspectionTools) {
      enableInspectionTool(availableInspectionTools, new LocalInspectionToolWrapper(tool));
    }

    final InspectionProfileImpl profile =
        new InspectionProfileImpl("Configurable") {
          @NotNull
          public InspectionProfileEntry[] getInspectionTools(PsiElement element) {
            if (availableInspectionTools != null) {
              final Collection<InspectionTool> tools = availableInspectionTools.values();
              return tools.toArray(new InspectionTool[tools.size()]);
            }
            return new InspectionTool[0];
          }

          @Override
          public List<ToolsImpl> getAllEnabledInspectionTools() {
            List<ToolsImpl> result = new ArrayList<ToolsImpl>();
            for (InspectionProfileEntry entry : getInspectionTools(null)) {
              result.add(new ToolsImpl(entry, entry.getDefaultLevel(), true));
            }
            return result;
          }

          public boolean isToolEnabled(HighlightDisplayKey key, PsiElement element) {
            return key != null && availableInspectionTools.containsKey(key.toString());
          }

          public HighlightDisplayLevel getErrorLevel(
              @NotNull HighlightDisplayKey key, PsiElement element) {
            InspectionTool localInspectionTool = availableInspectionTools.get(key.toString());
            return localInspectionTool != null
                ? localInspectionTool.getDefaultLevel()
                : HighlightDisplayLevel.WARNING;
          }

          public InspectionTool getInspectionTool(
              @NotNull String shortName, @NotNull PsiElement element) {
            if (availableInspectionTools.containsKey(shortName)) {
              return availableInspectionTools.get(shortName);
            }
            return null;
          }
        };
    final InspectionProfileManager inspectionProfileManager =
        InspectionProfileManager.getInstance();
    inspectionProfileManager.addProfile(profile);
    inspectionProfileManager.setRootProfile(profile.getName());
    InspectionProjectProfileManager.getInstance(getProject()).updateProfile(profile);
    InspectionProjectProfileManager.getInstance(getProject()).setProjectProfile(profile.getName());

    assertFalse(getPsiManager().isDisposed());

    CodeStyleSettingsManager.getInstance(getProject())
        .setTemporarySettings(new CodeStyleSettings());
  }
 /** @param project cannot be null */
 public static boolean closeAndDispose(@NotNull final Project project) {
   return ProjectManagerEx.getInstanceEx().closeAndDispose(project);
 }
  @Nullable
  public static Project openProject(
      final String path, @Nullable Project projectToClose, boolean forceOpenInNewFrame) {
    File file = new File(path);
    if (!file.exists()) {
      Messages.showErrorDialog(
          IdeBundle.message("error.project.file.does.not.exist", path),
          CommonBundle.getErrorTitle());
      return null;
    }

    if (file.isDirectory() && !new File(file, Project.DIRECTORY_STORE_FOLDER).exists()) {
      String message =
          IdeBundle.message(
              "error.project.file.does.not.exist",
              new File(file, Project.DIRECTORY_STORE_FOLDER).getPath());
      Messages.showErrorDialog(message, CommonBundle.getErrorTitle());
      return null;
    }

    Project[] openProjects = ProjectManager.getInstance().getOpenProjects();
    for (Project project : openProjects) {
      if (!project.isDefault() && isSameProject(path, project)) {
        focusProjectWindow(project, false);
        return project;
      }
    }

    if (!forceOpenInNewFrame && openProjects.length > 0) {
      int exitCode = confirmOpenNewProject(false);
      if (exitCode == GeneralSettings.OPEN_PROJECT_SAME_WINDOW) {
        final Project toClose =
            projectToClose != null ? projectToClose : openProjects[openProjects.length - 1];
        if (!closeAndDispose(toClose)) return null;
      } else if (exitCode != GeneralSettings.OPEN_PROJECT_NEW_WINDOW) {
        return null;
      }
    }

    ProjectManagerEx projectManager = ProjectManagerEx.getInstanceEx();
    Project project = null;
    try {
      project = projectManager.loadAndOpenProject(path);
    } catch (IOException e) {
      Messages.showMessageDialog(
          IdeBundle.message("error.cannot.load.project", e.getMessage()),
          IdeBundle.message("title.cannot.load.project"),
          Messages.getErrorIcon());
    } catch (JDOMException e) {
      LOG.info(e);
      Messages.showMessageDialog(
          IdeBundle.message("error.project.file.is.corrupted"),
          IdeBundle.message("title.cannot.load.project"),
          Messages.getErrorIcon());
    } catch (InvalidDataException e) {
      LOG.info(e);
      Messages.showMessageDialog(
          IdeBundle.message("error.project.file.is.corrupted"),
          IdeBundle.message("title.cannot.load.project"),
          Messages.getErrorIcon());
    }
    return project;
  }
  /**
   * Constructs new dialog. Loads settings, registers listeners.
   *
   * @param project the project
   * @param vcsRoots the vcs roots
   * @param roots the loaded information about roots
   */
  private GitPushActiveBranchesDialog(
      final Project project, List<VirtualFile> vcsRoots, List<Root> roots) {
    super(project, true);
    myVcs = GitVcs.getInstance(project);
    myProject = project;
    myVcsRoots = vcsRoots;
    myGeneralSettings = GeneralSettings.getInstance();
    myProjectManager = ProjectManagerEx.getInstanceEx();

    updateTree(roots, null);
    updateUI();

    final GitVcsSettings settings = GitVcsSettings.getInstance(project);
    if (settings != null) {
      UpdatePolicyUtils.updatePolicyItem(
          settings.getPushActiveBranchesRebaseSavePolicy(),
          myStashRadioButton,
          myShelveRadioButton);
    }
    ChangeListener listener =
        new ChangeListener() {
          public void stateChanged(ChangeEvent e) {
            if (settings != null) {
              settings.setPushActiveBranchesRebaseSavePolicy(
                  UpdatePolicyUtils.getUpdatePolicy(myStashRadioButton, myShelveRadioButton));
            }
          }
        };
    myStashRadioButton.addChangeListener(listener);
    myShelveRadioButton.addChangeListener(listener);
    myCommitTree
        .getSelectionModel()
        .addTreeSelectionListener(
            new TreeSelectionListener() {
              public void valueChanged(TreeSelectionEvent e) {
                TreePath path = myCommitTree.getSelectionModel().getSelectionPath();
                if (path == null) {
                  myViewButton.setEnabled(false);
                  return;
                }
                DefaultMutableTreeNode node = (DefaultMutableTreeNode) path.getLastPathComponent();
                myViewButton.setEnabled(
                    node != null
                        && myCommitTree.getSelectionCount() == 1
                        && node.getUserObject() instanceof Commit);
              }
            });
    myViewButton.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            TreePath path = myCommitTree.getSelectionModel().getSelectionPath();
            if (path == null) {
              return;
            }
            DefaultMutableTreeNode node = (DefaultMutableTreeNode) path.getLastPathComponent();
            if (node == null || !(node.getUserObject() instanceof Commit)) {
              return;
            }
            Commit c = (Commit) node.getUserObject();
            GitShowAllSubmittedFilesAction.showSubmittedFiles(
                project, c.revision.asString(), c.root.root);
          }
        });
    myFetchButton.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            fetch();
          }
        });
    myRebaseButton.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            rebase();
          }
        });

    myPushButton.addActionListener(
        new ActionListener() {
          @Override
          public void actionPerformed(ActionEvent e) {
            push();
          }
        });

    setTitle(GitBundle.getString("push.active.title"));
    setOKButtonText(GitBundle.getString("push.active.rebase.and.push"));
    setCancelButtonText(GitBundle.getString("git.push.active.close"));
    init();
  }
  public void testDocumentFromAlienProjectDoesNotEndsUpInMyUncommittedList() throws Exception {
    PsiFile file = getPsiManager().findFile(createFile());

    final Document document = getPsiDocumentManager().getDocument(file);

    File temp = createTempDirectory();
    final Project alienProject =
        createProject(new File(temp, "alien.ipr"), DebugUtil.currentStackTrace());
    boolean succ2 = ProjectManagerEx.getInstanceEx().openProject(alienProject);
    assertTrue(succ2);

    try {
      PsiManager alienManager = PsiManager.getInstance(alienProject);
      final String alienText = "alien";

      LightVirtualFile alienVirt = new LightVirtualFile("foo.java", alienText);
      final PsiFile alienFile = alienManager.findFile(alienVirt);
      final PsiDocumentManagerImpl alienDocManager =
          (PsiDocumentManagerImpl) PsiDocumentManager.getInstance(alienProject);
      final Document alienDocument = alienDocManager.getDocument(alienFile);
      // alienDocument.putUserData(CACHED_VIEW_PROVIDER, new MockFileViewProvider(alienFile));
      assertEquals(0, alienDocManager.getUncommittedDocuments().length);
      assertEquals(0, getPsiDocumentManager().getUncommittedDocuments().length);

      ApplicationManager.getApplication()
          .runWriteAction(
              new Runnable() {
                public void run() {
                  getPsiDocumentManager()
                      .documentChanged(
                          new DocumentEventImpl(
                              alienDocument,
                              0,
                              "",
                              "",
                              alienDocument.getModificationStamp(),
                              false));
                  assertEquals(0, getPsiDocumentManager().getUncommittedDocuments().length);
                  assertEquals(0, alienDocManager.getUncommittedDocuments().length);

                  alienDocManager.documentChanged(
                      new DocumentEventImpl(
                          alienDocument, 0, "", "", alienDocument.getModificationStamp(), false));
                  assertEquals(0, getPsiDocumentManager().getUncommittedDocuments().length);
                  assertEquals(1, alienDocManager.getUncommittedDocuments().length);

                  getPsiDocumentManager()
                      .documentChanged(
                          new DocumentEventImpl(
                              document, 0, "", "", document.getModificationStamp(), false));
                  assertEquals(1, getPsiDocumentManager().getUncommittedDocuments().length);
                  assertEquals(1, alienDocManager.getUncommittedDocuments().length);

                  alienDocManager.documentChanged(
                      new DocumentEventImpl(
                          document, 0, "", "", document.getModificationStamp(), false));
                  assertEquals(1, getPsiDocumentManager().getUncommittedDocuments().length);
                  assertEquals(1, alienDocManager.getUncommittedDocuments().length);
                }
              });
    } finally {
      ProjectUtil.closeAndDispose(alienProject);
    }
  }