예제 #1
0
  @SuppressWarnings("unchecked")
  @Nullable
  public static <T> T getToolWindowElement(
      @NotNull Class<T> clazz,
      @NotNull Project project,
      @NotNull DataKey<T> key,
      @NotNull ProjectSystemId externalSystemId) {
    if (project.isDisposed() || !project.isOpen()) {
      return null;
    }
    final ToolWindowManager toolWindowManager = ToolWindowManager.getInstance(project);
    if (toolWindowManager == null) {
      return null;
    }
    final ToolWindow toolWindow = ensureToolWindowContentInitialized(project, externalSystemId);
    if (toolWindow == null) {
      return null;
    }

    final ContentManager contentManager = toolWindow.getContentManager();
    if (contentManager == null) {
      return null;
    }

    for (Content content : contentManager.getContents()) {
      final JComponent component = content.getComponent();
      if (component instanceof DataProvider) {
        final Object data = ((DataProvider) component).getData(key.getName());
        if (data != null && clazz.isInstance(data)) {
          return (T) data;
        }
      }
    }
    return null;
  }
예제 #2
0
    private void processOrphanModules() {
      if (myProject.isDisposed()) return;
      if (ExternalSystemDebugEnvironment.DEBUG_ORPHAN_MODULES_PROCESSING) {
        LOG.info(
            String.format(
                "Checking for orphan modules. External paths returned by external system: '%s'",
                myExternalModulePaths));
      }
      PlatformFacade platformFacade = ServiceManager.getService(PlatformFacade.class);
      List<Module> orphanIdeModules = ContainerUtilRt.newArrayList();
      String externalSystemIdAsString = myExternalSystemId.toString();

      for (Module module : platformFacade.getModules(myProject)) {
        String s = module.getOptionValue(ExternalSystemConstants.EXTERNAL_SYSTEM_ID_KEY);
        String p = module.getOptionValue(ExternalSystemConstants.LINKED_PROJECT_PATH_KEY);
        if (ExternalSystemDebugEnvironment.DEBUG_ORPHAN_MODULES_PROCESSING) {
          LOG.info(
              String.format(
                  "IDE module: EXTERNAL_SYSTEM_ID_KEY - '%s', LINKED_PROJECT_PATH_KEY - '%s'.",
                  s, p));
        }
        if (externalSystemIdAsString.equals(s) && !myExternalModulePaths.contains(p)) {
          orphanIdeModules.add(module);
          if (ExternalSystemDebugEnvironment.DEBUG_ORPHAN_MODULES_PROCESSING) {
            LOG.info(
                String.format(
                    "External paths doesn't contain IDE module LINKED_PROJECT_PATH_KEY anymore => add to orphan IDE modules."));
          }
        }
      }

      if (!orphanIdeModules.isEmpty()) {
        ruleOrphanModules(orphanIdeModules, myProject, myExternalSystemId);
      }
    }
 @Nullable
 public CvsTabbedWindow openTabbedWindow(final CvsHandler output) {
   if (ApplicationManager.getApplication().isUnitTestMode()) return null;
   if (myProject != null && myProject.isDefault()) return null;
   if (myProject != null) {
     if (myConfiguration != null && myConfiguration.SHOW_OUTPUT && !myIsQuietOperation) {
       if (ApplicationManager.getApplication().isDispatchThread()) {
         connectToOutput(output);
       } else {
         ApplicationManager.getApplication()
             .invokeAndWait(
                 new Runnable() {
                   public void run() {
                     connectToOutput(output);
                   }
                 },
                 ModalityState.defaultModalityState());
       }
     }
     if (!myProject.isDisposed()) {
       return CvsTabbedWindow.getInstance(myProject);
     }
   }
   return null;
 }
 private void updateImmediately() {
   if (myProject.isDisposed()) return;
   checkNodeValidity((DefaultMutableTreeNode) myTree.getModel().getRoot());
   if (myUsagePreviewPanel != null) {
     myUsagePreviewPanel.updateLayout(getSelectedUsageInfos());
   }
 }
  public void commitSynchronously(
      @NotNull Document document, @NotNull Project project, PsiFile excludeFile) {
    assert !isDisposed;

    if (!project.isInitialized() && !project.isDefault()) {
      @NonNls
      String s = project + "; Disposed: " + project.isDisposed() + "; Open: " + project.isOpen();
      s += "; SA Passed: ";
      try {
        s += ((StartupManagerImpl) StartupManager.getInstance(project)).startupActivityPassed();
      } catch (Exception e) {
        s += e;
      }
      throw new RuntimeException(s);
    }

    ApplicationManager.getApplication().assertWriteAccessAllowed();
    synchronized (documentsToCommit) {
      setCommitStage(document, CommitStage.ABOUT_TO_BE_SYNC_COMMITTED, true);
      removeCommitFromQueue(document);
    }

    ProgressIndicatorBase indicator = new ProgressIndicatorBase();
    indicator.start();
    log("About to commit sync", document, true, indicator);
    Runnable finish = commit(document, project, excludeFile, indicator, true, "Sync commit");
    log("Committed sync", document, true, finish, indicator);

    assert finish != null;
    finish.run();
  }
  @Override
  public void moduleAdded() {
    if (!myModuleInitialized) {
      myConnection.subscribe(
          ProjectTopics.PROJECT_ROOTS,
          new ModuleRootAdapter() {
            @Override
            public void rootsChanged(ModuleRootEvent event) {
              scheduleUpdate();
            }
          });
      myConnection.subscribe(GoLibrariesService.LIBRARIES_TOPIC, newRootUrls -> scheduleUpdate());

      Project project = myModule.getProject();
      StartupManager.getInstance(project)
          .runWhenProjectIsInitialized(
              () -> {
                if (!project.isDisposed() && !myModule.isDisposed()) {
                  for (PsiFileSystemItem vendor :
                      FilenameIndex.getFilesByName(
                          project, GoConstants.VENDOR, GoUtil.moduleScope(myModule), true)) {
                    if (vendor.isDirectory()) {
                      showVendoringNotification();
                      break;
                    }
                  }
                }
              });

      VirtualFileManager.getInstance().addVirtualFileListener(myFilesListener);
    }
    scheduleUpdate(0);
    myModuleInitialized = true;
  }
 @Override
 @NotNull
 public Project[] getOpenProjects() {
   synchronized (myOpenProjects) {
     if (myOpenProjectsArrayCache.length != myOpenProjects.size()) {
       LOG.error(
           "Open projects: "
               + myOpenProjects
               + "; cache: "
               + Arrays.asList(myOpenProjectsArrayCache));
     }
     if (myOpenProjectsArrayCache.length > 0
         && myOpenProjectsArrayCache[0] != myOpenProjects.get(0)) {
       LOG.error(
           "Open projects cache corrupted. Open projects: "
               + myOpenProjects
               + "; cache: "
               + Arrays.asList(myOpenProjectsArrayCache));
     }
     if (ApplicationManager.getApplication().isUnitTestMode()) {
       Project[] testProjects = myTestProjects.toArray(new Project[myTestProjects.size()]);
       for (Project testProject : testProjects) {
         assert !testProject.isDisposed() : testProject;
       }
       return ArrayUtil.mergeArrays(myOpenProjectsArrayCache, testProjects);
     }
     return myOpenProjectsArrayCache;
   }
 }
  @Override
  public String getDescription(@NotNull final String refSuffix, @NotNull final Editor editor) {
    final Project project = editor.getProject();
    if (project == null) {
      LOG.error(editor);
      return null;
    }
    if (project.isDisposed()) return null;
    final PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument());
    if (file == null) {
      return null;
    }

    final InspectionProfile profile = InspectionProfileManager.getInstance().getCurrentProfile();
    final InspectionToolWrapper toolWrapper = profile.getInspectionTool(refSuffix, file);
    if (toolWrapper == null) return null;

    String description = toolWrapper.loadDescription();
    if (description == null) {
      LOG.warn("No description for inspection '" + refSuffix + "'");
      description =
          InspectionsBundle.message("inspection.tool.description.under.construction.text");
    }
    return description;
  }
예제 #9
0
 public static boolean justOneGitRepository(Project project) {
   if (project.isDisposed()) {
     return true;
   }
   GitRepositoryManager manager = getRepositoryManager(project);
   return !manager.moreThanOneRoot();
 }
 @Override
 public UpdateInfoTree showUpdateProjectInfo(
     UpdatedFiles updatedFiles,
     String displayActionName,
     ActionInfo actionInfo,
     boolean canceled) {
   if (!myProject.isOpen() || myProject.isDisposed()) return null;
   ContentManager contentManager = getContentManager();
   if (contentManager == null) {
     return null; // content manager is made null during dispose; flag is set later
   }
   final UpdateInfoTree updateInfoTree =
       new UpdateInfoTree(contentManager, myProject, updatedFiles, displayActionName, actionInfo);
   Content content =
       ContentFactory.SERVICE
           .getInstance()
           .createContent(
               updateInfoTree,
               canceled
                   ? VcsBundle.message(
                       "toolwindow.title.update.action.canceled.info", displayActionName)
                   : VcsBundle.message("toolwindow.title.update.action.info", displayActionName),
               true);
   Disposer.register(content, updateInfoTree);
   ContentsUtil.addContent(contentManager, content, true);
   ToolWindowManager.getInstance(myProject).getToolWindow(ToolWindowId.VCS).activate(null);
   updateInfoTree.expandRootChildren();
   return updateInfoTree;
 }
 @Override
 @Nullable
 public AbstractVcs findVcsByName(String name) {
   if (name == null) return null;
   if (myProject.isDisposed()) return null;
   return AllVcses.getInstance(myProject).getByName(name);
 }
 @Override
 @Nullable
 public VcsDescriptor getDescriptor(final String name) {
   if (name == null) return null;
   if (myProject.isDisposed()) return null;
   return AllVcses.getInstance(myProject).getDescriptor(name);
 }
예제 #13
0
  private void removeFromEditor() {
    Editor editor = mySearchResults.getEditor();
    if (myReplacementBalloon != null) {
      myReplacementBalloon.hide();
    }

    if (editor != null) {

      for (VisibleAreaListener visibleAreaListener : myVisibleAreaListenersToRemove) {
        editor.getScrollingModel().removeVisibleAreaListener(visibleAreaListener);
      }
      myVisibleAreaListenersToRemove.clear();
      Project project = mySearchResults.getProject();
      if (project != null && !project.isDisposed()) {
        for (RangeHighlighter h : myHighlighters) {
          HighlightManager.getInstance(project).removeSegmentHighlighter(editor, h);
        }
        if (myCursorHighlighter != null) {
          HighlightManager.getInstance(project)
              .removeSegmentHighlighter(editor, myCursorHighlighter);
          myCursorHighlighter = null;
        }
      }
      myHighlighters.clear();
      if (myListeningSelection) {
        editor.getSelectionModel().removeSelectionListener(this);
        myListeningSelection = false;
      }
    }
  }
예제 #14
0
 @Nullable
 public static GitVcs getInstance(Project project) {
   if (project == null || project.isDisposed()) {
     return null;
   }
   return (GitVcs) ProjectLevelVcsManager.getInstance(project).findVcsByName(NAME);
 }
 @NotNull
 private ISVNRepositoryPool getPool(@NotNull ISVNAuthenticationManager manager) {
   if (myProject.isDisposed()) {
     throw new ProcessCanceledException();
   }
   return new PrimitivePool(manager, getSvnOptions());
 }
 /**
  * Updates editors' highlighters. This should be done when the opened file changes its file type.
  */
 private void updateHighlighters() {
   if (!myProject.isDisposed()) {
     final EditorHighlighter highlighter =
         EditorHighlighterFactory.getInstance().createEditorHighlighter(myProject, myFile);
     ((EditorEx) myEditor).setHighlighter(highlighter);
   }
 }
 /**
  * Prepare delete files handler.
  *
  * @param project the project
  * @param root a vcs root
  * @param files a files to commit
  * @param message a message file to use
  * @param nextCommitAuthor a author for the next commit
  * @param nextCommitAmend true, if the commit should be amended
  * @param nextCommitAuthorDate Author date timestamp to override the date of the commit or null if
  *     this overriding is not needed.
  * @return a simple handler that does the task
  * @throws VcsException in case of git problem
  */
 private static void commit(
     Project project,
     VirtualFile root,
     Collection<FilePath> files,
     File message,
     final String nextCommitAuthor,
     boolean nextCommitAmend,
     Date nextCommitAuthorDate)
     throws VcsException {
   boolean amend = nextCommitAmend;
   for (List<String> paths : VcsFileUtil.chunkPaths(root, files)) {
     GitSimpleHandler handler = new GitSimpleHandler(project, root, GitCommand.COMMIT);
     handler.setStdoutSuppressed(false);
     if (amend) {
       handler.addParameters("--amend");
     } else {
       amend = true;
     }
     handler.addParameters("--only", "-F", message.getAbsolutePath());
     if (nextCommitAuthor != null) {
       handler.addParameters("--author=" + nextCommitAuthor);
     }
     if (nextCommitAuthorDate != null) {
       handler.addParameters("--date", COMMIT_DATE_FORMAT.format(nextCommitAuthorDate));
     }
     handler.endOptions();
     handler.addParameters(paths);
     handler.run();
   }
   if (!project.isDisposed()) {
     GitRepositoryManager manager = GitUtil.getRepositoryManager(project);
     manager.updateRepository(root);
   }
 }
  @Override
  public void compileAndRun(
      @NotNull final Runnable startRunnable,
      @NotNull final ExecutionEnvironment environment,
      @Nullable final RunProfileState state,
      @Nullable final Runnable onCancelRunnable) {
    long id = environment.getExecutionId();
    if (id == 0) {
      id = environment.assignNewExecutionId();
    }

    RunProfile profile = environment.getRunProfile();
    if (!(profile instanceof RunConfiguration)) {
      startRunnable.run();
      return;
    }

    final RunConfiguration runConfiguration = (RunConfiguration) profile;
    final List<BeforeRunTask> beforeRunTasks =
        RunManagerEx.getInstanceEx(myProject).getBeforeRunTasks(runConfiguration);
    if (beforeRunTasks.isEmpty()) {
      startRunnable.run();
    } else {
      DataContext context = environment.getDataContext();
      final DataContext projectContext =
          context != null ? context : SimpleDataContext.getProjectContext(myProject);
      final long finalId = id;
      final Long executionSessionId = new Long(id);
      ApplicationManager.getApplication()
          .executeOnPooledThread(
              () -> {
                for (BeforeRunTask task : beforeRunTasks) {
                  if (myProject.isDisposed()) {
                    return;
                  }
                  @SuppressWarnings("unchecked")
                  BeforeRunTaskProvider<BeforeRunTask> provider =
                      BeforeRunTaskProvider.getProvider(myProject, task.getProviderId());
                  if (provider == null) {
                    LOG.warn(
                        "Cannot find BeforeRunTaskProvider for id='" + task.getProviderId() + "'");
                    continue;
                  }
                  ExecutionEnvironment taskEnvironment =
                      new ExecutionEnvironmentBuilder(environment).contentToReuse(null).build();
                  taskEnvironment.setExecutionId(finalId);
                  EXECUTION_SESSION_ID_KEY.set(taskEnvironment, executionSessionId);
                  if (!provider.executeTask(
                      projectContext, runConfiguration, taskEnvironment, task)) {
                    if (onCancelRunnable != null) {
                      SwingUtilities.invokeLater(onCancelRunnable);
                    }
                    return;
                  }
                }

                doRun(environment, startRunnable);
              });
    }
  }
예제 #19
0
  @CalledInAwt
  public static void refreshPassedFilesAndMoveToChangelist(
      @NotNull final Project project,
      final Collection<FilePath> directlyAffected,
      final Collection<VirtualFile> indirectlyAffected,
      final Consumer<Collection<FilePath>> targetChangelistMover) {
    final LocalFileSystem lfs = LocalFileSystem.getInstance();
    for (FilePath filePath : directlyAffected) {
      lfs.refreshAndFindFileByIoFile(filePath.getIOFile());
    }
    if (project.isDisposed()) return;

    final ChangeListManager changeListManager = ChangeListManager.getInstance(project);
    if (!directlyAffected.isEmpty() && targetChangelistMover != null) {
      changeListManager.invokeAfterUpdate(
          new Runnable() {
            @Override
            public void run() {
              targetChangelistMover.consume(directlyAffected);
            }
          },
          InvokeAfterUpdateMode.SYNCHRONOUS_CANCELLABLE,
          VcsBundle.message("change.lists.manager.move.changes.to.list"),
          new Consumer<VcsDirtyScopeManager>() {
            @Override
            public void consume(final VcsDirtyScopeManager vcsDirtyScopeManager) {
              markDirty(vcsDirtyScopeManager, directlyAffected, indirectlyAffected);
            }
          },
          null);
    } else {
      markDirty(VcsDirtyScopeManager.getInstance(project), directlyAffected, indirectlyAffected);
    }
  }
 @Override
 public boolean isAvailable(@NotNull Project project, Editor editor, PsiFile file) {
   for (Module module : myModules) {
     if (module.isDisposed()) return false;
   }
   return !project.isDisposed() && !myModules.isEmpty() && !myCurrentModule.isDisposed();
 }
예제 #21
0
        @Override
        public void caretPositionChanged(CaretEvent event) {

          if (project.isDisposed()) {
            return;
          }

          VirtualFile file =
              FileDocumentManager.getInstance().getFile(event.getEditor().getDocument());

          // Make sure file exists
          if (file == null) {
            return;
          }

          // Make sure file is in the project
          if (!ProjectFileIndex.SERVICE.getInstance(project).isInSource(file)) {
            return;
          }

          int offset = event.getEditor().logicalPositionToOffset(event.getNewPosition());

          // Get path relative to project root (e.g. src/Sample.java)
          Path basePath = Paths.get(project.getBasePath());
          Path absoluteFilePath = Paths.get(file.getPath());
          String relativeFilePath = basePath.relativize(absoluteFilePath).toString();

          CursorMovement cursorMovement = new CursorMovement(-1, relativeFilePath, offset);

          for (EditorEvent editorEvent : events) {
            editorEvent.sendCursorMovement(cursorMovement);
          }
        }
    @Override
    public void processTerminated(ProcessEvent event) {
      if (myProject.isDisposed()) return;
      if (!myTerminateNotified.compareAndSet(false, true)) return;

      ApplicationManager.getApplication()
          .invokeLater(
              () -> {
                RunnerLayoutUi ui = myDescriptor.getRunnerLayoutUi();
                if (ui != null && !ui.isDisposed()) {
                  ui.updateActionsNow();
                }
              },
              ModalityState.any());

      myProject
          .getMessageBus()
          .syncPublisher(EXECUTION_TOPIC)
          .processTerminated(myExecutorId, myEnvironment, myProcessHandler, event.getExitCode());

      SaveAndSyncHandler saveAndSyncHandler = SaveAndSyncHandler.getInstance();
      if (saveAndSyncHandler != null) {
        saveAndSyncHandler.scheduleRefresh();
      }
    }
 protected void doRun(
     @NotNull final ExecutionEnvironment environment, @NotNull final Runnable startRunnable) {
   Boolean allowSkipRun = environment.getUserData(EXECUTION_SKIP_RUN);
   if (allowSkipRun != null && allowSkipRun) {
     environment
         .getProject()
         .getMessageBus()
         .syncPublisher(EXECUTION_TOPIC)
         .processNotStarted(environment.getExecutor().getId(), environment);
   } else {
     // important! Do not use DumbService.smartInvokeLater here because it depends on modality
     // state
     // and execution of startRunnable could be skipped if modality state check fails
     //noinspection SSBasedInspection
     SwingUtilities.invokeLater(
         () -> {
           if (!myProject.isDisposed()) {
             if (!Registry.is("dumb.aware.run.configurations")) {
               DumbService.getInstance(myProject).runWhenSmart(startRunnable);
             } else {
               try {
                 DumbService.getInstance(myProject).setAlternativeResolveEnabled(true);
                 startRunnable.run();
               } catch (IndexNotReadyException ignored) {
                 ExecutionUtil.handleExecutionError(
                     environment,
                     new ExecutionException("cannot start while indexing is in progress."));
               } finally {
                 DumbService.getInstance(myProject).setAlternativeResolveEnabled(false);
               }
             }
           }
         });
   }
 }
  public boolean finishCommit(
      @NotNull final Document document,
      @NotNull final List<Processor<Document>> finishProcessors,
      final boolean synchronously,
      @NotNull final Object reason) {
    assert !myProject.isDisposed() : "Already disposed";
    final boolean[] ok = {true};
    ApplicationManager.getApplication()
        .runWriteAction(
            new CommitToPsiFileAction(document, myProject) {
              @Override
              public void run() {
                ok[0] = finishCommitInWriteAction(document, finishProcessors, synchronously);
              }
            });

    if (ok[0]) {
      // otherwise changes maybe not synced to the document yet, and injectors will crash
      if (!mySynchronizer.isDocumentAffectedByTransactions(document)) {
        final InjectedLanguageManager injectedLanguageManager =
            InjectedLanguageManager.getInstance(myProject);
        if (injectedLanguageManager != null)
          injectedLanguageManager.startRunInjectors(document, synchronously);
      }
      // run after commit actions outside write action
      runAfterCommitActions(document);
      if (DebugUtil.DO_EXPENSIVE_CHECKS) {
        checkAllElementsValid(document, reason);
      }
    }
    return ok[0];
  }
예제 #25
0
 private void removeAllContents(Project project, Content notRemove) {
   if (project.isDisposed()) {
     return;
   }
   final MessageView messageView = MessageView.SERVICE.getInstance(project);
   Content[] contents = messageView.getContentManager().getContents();
   for (Content content : contents) {
     if (content.isPinned()) {
       continue;
     }
     if (content == notRemove) {
       continue;
     }
     boolean toRemove = CONTENT_ID_KEY.get(content) == myContentId;
     if (!toRemove) {
       final Object contentSessionId = SESSION_ID_KEY.get(content);
       toRemove =
           contentSessionId != null
               && contentSessionId != mySessionId; // the content was added by previous compilation
     }
     if (toRemove) {
       messageView.getContentManager().removeContent(content, true);
     }
   }
 }
 @Override
 public void openTestProject(@NotNull final Project project) {
   synchronized (myOpenProjects) {
     assert ApplicationManager.getApplication().isUnitTestMode();
     assert !project.isDisposed() : "Must not open already disposed project";
     myTestProjects.add(project);
   }
 }
    @Override
    public void exitDumbMode() {
      if (!ProjectPane.isShowGenStatus()) return;

      Project p = myTree.getProject();
      if (p.isDisposed()) return;

      myGenStatusVisitor.dispatchForHierarchy(myTree.getRootNode());
    }
예제 #28
0
 public static HgFile getOriginalHgFile(Project project, VirtualFile root) {
   HgFile hgFile = new HgFile(root, VcsUtil.getFilePath(root.getPath()));
   if (project.isDisposed()) {
     return hgFile;
   }
   FilePath originalFileName =
       HgUtil.getOriginalFileName(hgFile.toFilePath(), ChangeListManager.getInstance(project));
   return new HgFile(hgFile.getRepo(), originalFileName);
 }
예제 #29
0
 @Override
 public IdeFocusManager getFocusManager() {
   Project project = getProject();
   if (project != null && !project.isDisposed()) {
     return IdeFocusManager.getInstance(project);
   } else {
     return IdeFocusManager.findInstance();
   }
 }
 @Override
 @Nullable
 public VirtualFile getVcsRootFor(final FilePath file) {
   if (myProject.isDisposed()) return null;
   VirtualFile vFile = ChangesUtil.findValidParentAccurately(file);
   if (vFile != null) {
     return getVcsRootFor(vFile);
   }
   return null;
 }