private boolean getExistingInfo(Ref<RunningInfo> ref, Pair<Target, Parameters> key) {
   Info info;
   synchronized (myProcMap) {
     info = myProcMap.get(key);
     try {
       while (info != null
           && (!(info instanceof RunningInfo)
               || info.handler.isProcessTerminating()
               || info.handler.isProcessTerminated())) {
         myProcMap.wait(1000);
         ProgressManager.checkCanceled();
         info = myProcMap.get(key);
       }
     } catch (InterruptedException e) {
       ProgressManager.checkCanceled();
     }
     if (info == null) {
       myProcMap.put(key, new PendingInfo(ref, null));
     }
   }
   if (info instanceof RunningInfo) {
     //noinspection SynchronizationOnLocalVariableOrMethodParameter
     synchronized (ref) {
       ref.set((RunningInfo) info);
       ref.notifyAll();
     }
   }
   return info != null;
 }
  public EntryPoint acquire(@NotNull Target target, @NotNull Parameters configuration)
      throws Exception {
    ApplicationManagerEx.getApplicationEx().assertTimeConsuming();

    Ref<RunningInfo> ref = Ref.create(null);
    Pair<Target, Parameters> key = Pair.create(target, configuration);
    if (!getExistingInfo(ref, key)) {
      startProcess(target, configuration, key);
      if (ref.isNull()) {
        try {
          //noinspection SynchronizationOnLocalVariableOrMethodParameter
          synchronized (ref) {
            while (ref.isNull()) {
              ref.wait(1000);
              ProgressManager.checkCanceled();
            }
          }
        } catch (InterruptedException e) {
          ProgressManager.checkCanceled();
        }
      }
    }
    if (ref.isNull())
      throw new RuntimeException("Unable to acquire remote proxy for: " + getName(target));
    RunningInfo info = ref.get();
    if (info.handler == null) {
      String message = info.name;
      if (message != null && message.startsWith("ERROR: transport error 202:")) {
        message =
            "Unable to start java process in debug mode: -Xdebug parameters are already in use.";
      }
      throw new ExecutionException(message);
    }
    return acquire(info);
  }
  public static boolean runContributors(
      @NotNull PsiType qualifierType,
      @NotNull PsiScopeProcessor processor,
      @NotNull PsiElement place,
      @NotNull ResolveState state) {

    MyDelegatingScopeProcessor delegatingProcessor = new MyDelegatingScopeProcessor(processor);

    ensureInit();

    final PsiClass aClass = PsiTypesUtil.getPsiClass(qualifierType);

    if (aClass != null) {
      for (String superClassName : TypesUtil.getSuperClassesWithCache(aClass).keySet()) {
        for (NonCodeMembersContributor enhancer :
            ourClassSpecifiedContributors.get(superClassName)) {
          ProgressManager.checkCanceled();
          enhancer.processDynamicElements(qualifierType, aClass, delegatingProcessor, place, state);
          if (!delegatingProcessor.wantMore) {
            return false;
          }
        }
      }
    }

    for (NonCodeMembersContributor contributor : ourAllTypeContributors) {
      ProgressManager.checkCanceled();
      contributor.processDynamicElements(qualifierType, aClass, delegatingProcessor, place, state);
      if (!delegatingProcessor.wantMore) {
        return false;
      }
    }

    return GroovyDslFileIndex.processExecutors(qualifierType, place, processor, state);
  }
  public static LinkedHashSet<String> sortMatching(
      final PrefixMatcher matcher, Collection<String> _names) {
    ProgressManager.checkCanceled();

    List<String> sorted = new ArrayList<String>();
    for (String name : _names) {
      if (matcher.prefixMatches(name)) {
        sorted.add(name);
      }
    }

    ProgressManager.checkCanceled();
    Collections.sort(sorted, String.CASE_INSENSITIVE_ORDER);
    ProgressManager.checkCanceled();

    LinkedHashSet<String> result = new LinkedHashSet<String>();
    for (String name : sorted) {
      if (matcher.isStartMatch(name)) {
        result.add(name);
      }
    }

    ProgressManager.checkCanceled();

    result.addAll(sorted);
    return result;
  }
  @Nullable
  public static PsiClass[] getAllTestClasses(final TestClassFilter filter, boolean sync) {
    final PsiClass[][] holder = new PsiClass[1][];
    final Runnable process =
        () -> {
          final ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator();

          final Collection<PsiClass> set = new LinkedHashSet<>();
          final PsiManager manager = PsiManager.getInstance(filter.getProject());
          final GlobalSearchScope projectScope =
              GlobalSearchScope.projectScope(manager.getProject());
          final GlobalSearchScope scope = projectScope.intersectWith(filter.getScope());
          for (final PsiClass psiClass : AllClassesSearch.search(scope, manager.getProject())) {
            if (filter.isAccepted(psiClass)) {
              if (indicator != null) {
                indicator.setText2(
                    "Found test class " + ReadAction.compute(psiClass::getQualifiedName));
              }
              set.add(psiClass);
            }
          }
          holder[0] = set.toArray(new PsiClass[set.size()]);
        };
    if (sync) {
      ProgressManager.getInstance()
          .runProcessWithProgressSynchronously(
              process, "Searching For Tests...", true, filter.getProject());
    } else {
      process.run();
    }
    return holder[0];
  }
  @MethodCandidateInfo.ApplicabilityLevelConstant
  public int checkApplicability(@NotNull List<CandidateInfo> conflicts) {
    @MethodCandidateInfo.ApplicabilityLevelConstant int maxApplicabilityLevel = 0;
    boolean toFilter = false;
    for (CandidateInfo conflict : conflicts) {
      ProgressManager.checkCanceled();
      @MethodCandidateInfo.ApplicabilityLevelConstant
      final int level = getPertinentApplicabilityLevel((MethodCandidateInfo) conflict);
      if (maxApplicabilityLevel > 0 && maxApplicabilityLevel != level) {
        toFilter = true;
      }
      if (level > maxApplicabilityLevel) {
        maxApplicabilityLevel = level;
      }
    }

    if (toFilter) {
      for (Iterator<CandidateInfo> iterator = conflicts.iterator(); iterator.hasNext(); ) {
        ProgressManager.checkCanceled();
        CandidateInfo info = iterator.next();
        final int level = getPertinentApplicabilityLevel((MethodCandidateInfo) info);
        if (level < maxApplicabilityLevel) {
          iterator.remove();
        }
      }
    }

    return maxApplicabilityLevel;
  }
  public static void openAttachment(
      final Project project, String name, EntityRef parent, int size) {
    try {
      final File file;
      boolean agmLink = name.endsWith(".agmlink");
      if (agmLink) {
        // for the file to open correctly, there must be no trailing extension
        file = File.createTempFile("tmp", "_" + name.replaceFirst("\\.agmlink$", ""));
      } else {
        file = File.createTempFile("tmp", "_" + name);
      }
      final Runnable openFile =
          new Runnable() {
            @Override
            public void run() {
              String url =
                  VirtualFileManager.constructUrl(
                      LocalFileSystem.PROTOCOL,
                      FileUtil.toSystemIndependentName(file.getAbsolutePath()));
              final VirtualFile virtualFile =
                  VirtualFileManager.getInstance().refreshAndFindFileByUrl(url);
              UIUtil.invokeLaterIfNeeded(
                  new Runnable() {
                    public void run() {
                      if (virtualFile != null) {
                        FileEditor[] editors =
                            project
                                .getComponent(FileEditorManager.class)
                                .openFile(virtualFile, true);
                        if (editors.length > 0) {
                          return;
                        }

                        FileType type =
                            FileTypeManager.getInstance()
                                .getKnownFileTypeOrAssociate(virtualFile, project);
                        if (type instanceof INativeFileType
                            && ((INativeFileType) type)
                                .openFileInAssociatedApplication(project, virtualFile)) {
                          return;
                        }
                      }
                      Messages.showWarningDialog(
                          "No editor seems to be associated with this file type. Try to download and open the file manually.",
                          "Not Supported");
                    }
                  });
            }
          };
      if (agmLink) {
        ProgressManager.getInstance()
            .run(new AttachmentAgmLinkDownloadTask(project, file, name, size, parent, openFile));
      } else {
        ProgressManager.getInstance()
            .run(new AttachmentDownloadTask(project, file, name, size, parent, openFile));
      }
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }
  public static void writeFileImpl(String folder, @NonNls String fileName, CharSequence buf)
      throws IOException {
    ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator();
    final String fullPath = folder + File.separator + fileName;

    if (indicator != null) {
      ProgressManager.checkCanceled();
      indicator.setText(
          InspectionsBundle.message("inspection.export.generating.html.for", fullPath));
    }

    FileWriter writer = null;
    try {
      File folderFile = new File(folder);
      folderFile.mkdirs();
      new File(fullPath).getParentFile().mkdirs();
      writer = new FileWriter(fullPath);
      writer.write(buf.toString().toCharArray());
    } finally {
      if (writer != null) {
        try {
          writer.close();
        } catch (IOException e) {
          // Cannot do anything in case of exception
        }
      }
    }
  }
  @Override
  public void computeUsages(List<PsiLiteralExpression> targets) {
    final Project project = myTarget.getProject();
    final PsiElement parent = myTarget.getParent().getParent();
    final LocalInspectionsPass pass =
        new LocalInspectionsPass(
            myFile,
            myFile.getViewProvider().getDocument(),
            parent.getTextRange().getStartOffset(),
            parent.getTextRange().getEndOffset(),
            LocalInspectionsPass.EMPTY_PRIORITY_RANGE,
            false,
            HighlightInfoProcessor.getEmpty());
    final InspectionProfile inspectionProfile =
        InspectionProjectProfileManager.getInstance(project).getInspectionProfile();
    for (PsiLiteralExpression target : targets) {
      final Object value = target.getValue();
      if (!(value instanceof String)) {
        continue;
      }
      InspectionToolWrapper toolWrapperById =
          ((InspectionProfileImpl) inspectionProfile).getToolById((String) value, target);
      if (!(toolWrapperById instanceof LocalInspectionToolWrapper)) {
        continue;
      }
      final LocalInspectionToolWrapper toolWrapper =
          ((LocalInspectionToolWrapper) toolWrapperById).createCopy();
      final InspectionManagerEx managerEx =
          (InspectionManagerEx) InspectionManager.getInstance(project);
      final GlobalInspectionContextImpl context = managerEx.createNewGlobalContext(false);
      toolWrapper.initialize(context);
      ((RefManagerImpl) context.getRefManager()).inspectionReadActionStarted();
      ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator();
      Runnable inspect =
          new Runnable() {
            @Override
            public void run() {
              pass.doInspectInBatch(
                  context,
                  managerEx,
                  Collections.<LocalInspectionToolWrapper>singletonList(toolWrapper));
            }
          };
      if (indicator == null) {
        ProgressManager.getInstance()
            .executeProcessUnderProgress(inspect, new ProgressIndicatorBase());
      } else {
        inspect.run();
      }

      for (HighlightInfo info : pass.getInfos()) {
        final PsiElement element =
            CollectHighlightsUtil.findCommonParent(myFile, info.startOffset, info.endOffset);
        if (element != null) {
          addOccurrence(element);
        }
      }
    }
  }
  private boolean processFilesConcurrently(
      @NotNull Set<VirtualFile> files,
      @NotNull final ProgressIndicator indicator,
      @NotNull final Processor<VirtualFile> processor) {
    final List<VirtualFile> fileList = new ArrayList<VirtualFile>(files);
    // fine but grabs all CPUs
    // return JobLauncher.getInstance().invokeConcurrentlyUnderProgress(fileList, indicator, false,
    // false, processor);

    int parallelism = CacheUpdateRunner.indexingThreadCount();
    final Callable<Boolean> processFileFromSet =
        () -> {
          final boolean[] result = {true};
          ProgressManager.getInstance()
              .executeProcessUnderProgress(
                  () -> {
                    while (true) {
                      ProgressManager.checkCanceled();
                      VirtualFile file;
                      synchronized (fileList) {
                        file = fileList.isEmpty() ? null : fileList.remove(fileList.size() - 1);
                      }
                      if (file == null) {
                        break;
                      }
                      if (!processor.process(file)) {
                        result[0] = false;
                        break;
                      }
                    }
                  },
                  indicator);
          return result[0];
        };
    List<Future<Boolean>> futures =
        ContainerUtil.map(
            Collections.nCopies(parallelism, ""),
            s -> myApplication.executeOnPooledThread(processFileFromSet));

    List<Boolean> results =
        ContainerUtil.map(
            futures,
            future -> {
              try {
                return future.get();
              } catch (Exception e) {
                LOG.error(e);
              }
              return false;
            });

    return !ContainerUtil.exists(
        results,
        result -> {
          return result != null && !result; // null means PCE
        });
  }
  private void loadCommitsData(
      @NotNull final TIntIntHashMap commits,
      @NotNull final Consumer<List<T>> consumer,
      @Nullable ProgressIndicator indicator) {
    final List<T> result = ContainerUtil.newArrayList();
    final TIntHashSet toLoad = new TIntHashSet();

    long taskNumber = myCurrentTaskIndex++;

    for (int id : commits.keys()) {
      T details = getFromCache(id);
      if (details == null || details instanceof LoadingDetails) {
        toLoad.add(id);
        cacheCommit(id, taskNumber);
      } else {
        result.add(details);
      }
    }

    if (toLoad.isEmpty()) {
      sortCommitsByRow(result, commits);
      consumer.consume(result);
    } else {
      Task.Backgroundable task =
          new Task.Backgroundable(
              null, "Loading Selected Details", true, PerformInBackgroundOption.ALWAYS_BACKGROUND) {
            @Override
            public void run(@NotNull final ProgressIndicator indicator) {
              indicator.checkCanceled();
              try {
                TIntObjectHashMap<T> map = preLoadCommitData(toLoad);
                map.forEachValue(
                    value -> {
                      result.add(value);
                      return true;
                    });
                sortCommitsByRow(result, commits);
                notifyLoaded();
              } catch (VcsException e) {
                LOG.error(e);
              }
            }

            @Override
            public void onSuccess() {
              consumer.consume(result);
            }
          };
      if (indicator != null) {
        ProgressManager.getInstance().runProcessWithProgressAsynchronously(task, indicator);
      } else {
        ProgressManager.getInstance().run(task);
      }
    }
  }
  public ShelvedChangeList shelveChanges(
      final Collection<Change> changes, final String commitMessage, final boolean rollback)
      throws IOException, VcsException {
    final List<Change> textChanges = new ArrayList<Change>();
    final List<ShelvedBinaryFile> binaryFiles = new ArrayList<ShelvedBinaryFile>();
    for (Change change : changes) {
      if (ChangesUtil.getFilePath(change).isDirectory()) {
        continue;
      }
      if (change.getBeforeRevision() instanceof BinaryContentRevision
          || change.getAfterRevision() instanceof BinaryContentRevision) {
        binaryFiles.add(shelveBinaryFile(change));
      } else {
        textChanges.add(change);
      }
    }

    final ShelvedChangeList changeList;
    try {
      File patchPath = getPatchPath(commitMessage);
      ProgressManager.checkCanceled();
      final List<FilePatch> patches =
          IdeaTextPatchBuilder.buildPatch(
              myProject, textChanges, myProject.getBaseDir().getPresentableUrl(), false);
      ProgressManager.checkCanceled();

      CommitContext commitContext = new CommitContext();
      baseRevisionsOfDvcsIntoContext(textChanges, commitContext);
      myFileProcessor.savePathFile(
          new CompoundShelfFileProcessor.ContentProvider() {
            public void writeContentTo(final Writer writer, CommitContext commitContext)
                throws IOException {
              UnifiedDiffWriter.write(myProject, patches, writer, "\n", commitContext);
            }
          },
          patchPath,
          commitContext);

      changeList =
          new ShelvedChangeList(
              patchPath.toString(), commitMessage.replace('\n', ' '), binaryFiles);
      myShelvedChangeLists.add(changeList);
      ProgressManager.checkCanceled();

      if (rollback) {
        new RollbackWorker(myProject, false)
            .doRollback(changes, true, null, VcsBundle.message("shelve.changes.action"));
      }
    } finally {
      notifyStateChanged();
    }

    return changeList;
  }
Example #13
0
 @Override
 public boolean process(PsiClass inheritor) {
   ProgressManager.checkCanceled();
   for (PsiClassType interfaceType : inheritor.getImplementsListTypes()) {
     ProgressManager.checkCanceled();
     PsiClass anInterface = interfaceType.resolveGenerics().getElement();
     if (anInterface != null && myCheckedInterfaces.add(PsiAnchor.create(anInterface))) {
       processInterface(inheritor, anInterface);
     }
   }
   return !myRemainingMethods.isEmpty();
 }
  void duringCompletion(CompletionInitializationContext initContext) {
    if (isAutopopupCompletion()) {
      if (shouldFocusLookup(myParameters)) {
        myLookup.setFocused(true);
      } else if (FeatureUsageTracker.getInstance()
          .isToBeAdvertisedInLookup(
              CodeCompletionFeatures.EDITING_COMPLETION_CONTROL_ENTER, getProject())) {
        myLookup.addAdvertisement(
            "Press "
                + CompletionContributor.getActionShortcut(
                    IdeActions.ACTION_CHOOSE_LOOKUP_ITEM_ALWAYS)
                + " to choose the first suggestion");
      }
      if (!myEditor.isOneLineMode()
          && FeatureUsageTracker.getInstance()
              .isToBeAdvertisedInLookup(
                  CodeCompletionFeatures.EDITING_COMPLETION_CONTROL_ARROWS, getProject())) {
        myLookup.addAdvertisement(
            CompletionContributor.getActionShortcut(IdeActions.ACTION_LOOKUP_DOWN)
                + " and "
                + CompletionContributor.getActionShortcut(IdeActions.ACTION_LOOKUP_UP)
                + " will move caret down and up in the editor");
      }
    }

    ProgressManager.checkCanceled();

    if (!initContext
        .getOffsetMap()
        .wasModified(CompletionInitializationContext.IDENTIFIER_END_OFFSET)) {
      try {
        final int selectionEndOffset = initContext.getSelectionEndOffset();
        final PsiReference reference = initContext.getFile().findReferenceAt(selectionEndOffset);
        if (reference != null) {
          initContext.setReplacementOffset(findReplacementOffset(selectionEndOffset, reference));
        }
      } catch (IndexNotReadyException ignored) {
      }
    }

    for (CompletionContributor contributor :
        CompletionContributor.forLanguage(initContext.getPositionLanguage())) {
      ProgressManager.checkCanceled();
      if (DumbService.getInstance(initContext.getProject()).isDumb()
          && !DumbService.isDumbAware(contributor)) {
        continue;
      }

      contributor.duringCompletion(initContext);
    }
  }
 protected static int initOccurrencesNumber(PsiNameIdentifierOwner nameIdentifierOwner) {
   final ProgressManager progressManager = ProgressManager.getInstance();
   final PsiSearchHelper searchHelper =
       PsiSearchHelper.SERVICE.getInstance(nameIdentifierOwner.getProject());
   final GlobalSearchScope scope =
       GlobalSearchScope.projectScope(nameIdentifierOwner.getProject());
   final String name = nameIdentifierOwner.getName();
   final boolean isCheapToSearch =
       name != null
           && searchHelper.isCheapEnoughToSearch(
                   name, scope, null, progressManager.getProgressIndicator())
               != PsiSearchHelper.SearchCostResult.TOO_MANY_OCCURRENCES;
   return isCheapToSearch ? ReferencesSearch.search(nameIdentifierOwner).findAll().size() : -1;
 }
  private LookupElement[] calculateItems(
      CompletionInitializationContext initContext, WeighingDelegate weigher) {
    duringCompletion(initContext);
    ProgressManager.checkCanceled();

    LookupElement[] result =
        CompletionService.getCompletionService().performCompletion(myParameters, weigher);
    ProgressManager.checkCanceled();

    weigher.waitFor();
    ProgressManager.checkCanceled();

    return result;
  }
Example #17
0
  protected Map<
          ModuleDescriptor, Map<File, List<FacetDetectionProcessor.DetectedInWizardFacetInfo>>>
      calculate() {
    myLastRoots = getRoots();

    ProgressIndicator progressIndicator = ProgressManager.getInstance().getProgressIndicator();

    Map<ModuleDescriptor, Map<File, List<FacetDetectionProcessor.DetectedInWizardFacetInfo>>>
        result =
            new HashMap<
                ModuleDescriptor,
                Map<File, List<FacetDetectionProcessor.DetectedInWizardFacetInfo>>>();
    for (ModuleDescriptor moduleDescriptor : getModuleDescriptors()) {

      Map<File, List<FacetDetectionProcessor.DetectedInWizardFacetInfo>> root2Facets =
          new HashMap<File, List<FacetDetectionProcessor.DetectedInWizardFacetInfo>>();
      for (File root : moduleDescriptor.getContentRoots()) {
        FacetDetectionProcessor processor =
            new FacetDetectionProcessor(progressIndicator, myModuleType);
        processor.process(root);
        List<FacetDetectionProcessor.DetectedInWizardFacetInfo> facets =
            processor.getDetectedFacetsInfos();
        if (!facets.isEmpty()) {
          root2Facets.put(root, facets);
        }
      }

      if (!root2Facets.isEmpty()) {
        result.put(moduleDescriptor, root2Facets);
      }
    }

    return result;
  }
  public static void deleteFile(Project project, final VirtualFile file) throws ExecutionException {
    final Ref<IOException> error = new Ref<IOException>();

    final Runnable runnable =
        new Runnable() {
          public void run() {
            ApplicationManager.getApplication()
                .runWriteAction(
                    new Runnable() {
                      public void run() {
                        try {
                          if (file.isValid()) {
                            file.delete(this);
                          }
                        } catch (IOException e) {
                          error.set(e);
                        }
                      }
                    });
          }
        };

    if (ApplicationManager.getApplication().isDispatchThread()) {
      runnable.run();
    } else {
      ProgressIndicator pi = ProgressManager.getInstance().getProgressIndicator();
      ApplicationManager.getApplication()
          .invokeAndWait(runnable, pi != null ? pi.getModalityState() : ModalityState.NON_MODAL);
    }
    if (!error.isNull()) {
      //noinspection ThrowableResultOfMethodCallIgnored
      throw new ExecutionException(error.get().getMessage());
    }
  }
  private void highlightInjectedSyntax(
      @NotNull PsiFile injectedPsi, @NotNull HighlightInfoHolder holder) {
    List<Trinity<IElementType, SmartPsiElementPointer<PsiLanguageInjectionHost>, TextRange>>
        tokens = InjectedLanguageUtil.getHighlightTokens(injectedPsi);
    if (tokens == null) return;

    final Language injectedLanguage = injectedPsi.getLanguage();
    Project project = injectedPsi.getProject();
    SyntaxHighlighter syntaxHighlighter =
        SyntaxHighlighterFactory.getSyntaxHighlighter(
            injectedLanguage, project, injectedPsi.getVirtualFile());
    final TextAttributes defaultAttrs = myGlobalScheme.getAttributes(HighlighterColors.TEXT);

    for (Trinity<IElementType, SmartPsiElementPointer<PsiLanguageInjectionHost>, TextRange> token :
        tokens) {
      ProgressManager.checkCanceled();
      IElementType tokenType = token.getFirst();
      PsiLanguageInjectionHost injectionHost = token.getSecond().getElement();
      if (injectionHost == null) continue;
      TextRange textRange = token.getThird();
      TextAttributesKey[] keys = syntaxHighlighter.getTokenHighlights(tokenType);
      if (textRange.getLength() == 0) continue;

      TextRange annRange = textRange.shiftRight(injectionHost.getTextRange().getStartOffset());
      // force attribute colors to override host' ones
      TextAttributes attributes = null;
      for (TextAttributesKey key : keys) {
        TextAttributes attrs2 = myGlobalScheme.getAttributes(key);
        if (attrs2 != null) {
          attributes = attributes == null ? attrs2 : TextAttributes.merge(attributes, attrs2);
        }
      }
      TextAttributes forcedAttributes;
      if (attributes == null || attributes.isEmpty() || attributes.equals(defaultAttrs)) {
        forcedAttributes = TextAttributes.ERASE_MARKER;
      } else {
        HighlightInfo info =
            HighlightInfo.newHighlightInfo(HighlightInfoType.INJECTED_LANGUAGE_FRAGMENT)
                .range(annRange)
                .textAttributes(TextAttributes.ERASE_MARKER)
                .createUnconditionally();
        holder.add(info);

        forcedAttributes =
            new TextAttributes(
                attributes.getForegroundColor(),
                attributes.getBackgroundColor(),
                attributes.getEffectColor(),
                attributes.getEffectType(),
                attributes.getFontType());
      }

      HighlightInfo info =
          HighlightInfo.newHighlightInfo(HighlightInfoType.INJECTED_LANGUAGE_FRAGMENT)
              .range(annRange)
              .textAttributes(forcedAttributes)
              .createUnconditionally();
      holder.add(info);
    }
  }
Example #20
0
 private static void addToHistory(
     final SMTestProxy.SMRootTestProxy root,
     TestConsoleProperties consoleProperties,
     Disposable parentDisposable) {
   final RunProfile configuration = consoleProperties.getConfiguration();
   if (configuration instanceof RunConfiguration
       && !(consoleProperties instanceof ImportedTestConsoleProperties)) {
     final MySaveHistoryTask backgroundable =
         new MySaveHistoryTask(consoleProperties, root, (RunConfiguration) configuration);
     final BackgroundableProcessIndicator processIndicator =
         new BackgroundableProcessIndicator(backgroundable);
     Disposer.register(
         parentDisposable,
         new Disposable() {
           @Override
           public void dispose() {
             processIndicator.cancel();
             backgroundable.dispose();
           }
         });
     Disposer.register(parentDisposable, processIndicator);
     ProgressManager.getInstance()
         .runProcessWithProgressAsynchronously(backgroundable, processIndicator);
   }
 }
Example #21
0
 public void updateTargetsView(final DependencyViewerScope sourceScope) {
   myScope = sourceScope;
   final Wrappers._T<SearchResults<SNode>> results =
       new Wrappers._T<SearchResults<SNode>>(new SearchResults<SNode>());
   ProgressManager.getInstance()
       .run(
           new Task.Modal(myProject, "Analyzing dependencies", true) {
             public void run(@NotNull final ProgressIndicator indicator) {
               ModelAccess.instance()
                   .runReadAction(
                       new Runnable() {
                         public void run() {
                           ProgressMonitor monitor = new ProgressMonitorAdapter(indicator);
                           try {
                             monitor.start(null, 100);
                             List<SNode> nodes =
                                 myReferencesFinder.getNodes(sourceScope, monitor.subTask(20));
                             mySourceNodes = nodes;
                             results.value =
                                 (myIsMeta
                                     ? myReferencesFinder.getUsedLanguagesSearchResults(
                                         nodes, sourceScope, monitor.subTask(80))
                                     : myReferencesFinder.getTargetSearchResults(
                                         nodes, sourceScope, monitor.subTask(80)));
                           } finally {
                             monitor.done();
                           }
                         }
                       });
             }
           });
   myTargetsView.setContents(results.value);
   updateReferencesView(null);
 }
  public synchronized void addItem(final CompletionResult item) {
    if (!isRunning()) return;
    ProgressManager.checkCanceled();

    final boolean unitTestMode = ApplicationManager.getApplication().isUnitTestMode();
    if (!unitTestMode) {
      LOG.assertTrue(!ApplicationManager.getApplication().isDispatchThread());
    }

    LOG.assertTrue(myParameters.getPosition().isValid());

    myItemSorters.put(item.getLookupElement(), (CompletionSorterImpl) item.getSorter());
    myLookup.addItem(item.getLookupElement(), item.getPrefixMatcher());
    myCount++;

    if (myCount == 1) {
      ApplicationManager.getApplication()
          .executeOnPooledThread(
              new Runnable() {
                public void run() {
                  try {
                    Thread.sleep(300);
                  } catch (InterruptedException ignore) {
                  } finally {
                    myFreezeSemaphore.up();
                  }
                }
              });
    }
    myQueue.queue(myUpdate);
  }
  private void checkDuplicateAttribute(XmlTag tag, final XmlAttribute attribute) {
    if (skipValidation(tag)) {
      return;
    }

    final XmlAttribute[] attributes = tag.getAttributes();
    final PsiFile containingFile = tag.getContainingFile();
    final XmlExtension extension =
        containingFile instanceof XmlFile
            ? XmlExtension.getExtension(containingFile)
            : XmlExtension.DEFAULT_EXTENSION;
    for (XmlAttribute tagAttribute : attributes) {
      ProgressManager.checkCanceled();
      if (attribute != tagAttribute
          && Comparing.strEqual(attribute.getName(), tagAttribute.getName())) {
        final String localName = attribute.getLocalName();

        if (extension.canBeDuplicated(tagAttribute))
          continue; // multiple import attributes are allowed in jsp directive

        HighlightInfo highlightInfo =
            HighlightInfo.createHighlightInfo(
                getTagProblemInfoType(tag),
                XmlChildRole.ATTRIBUTE_NAME_FINDER.findChild(
                    SourceTreeToPsiMap.psiElementToTree(attribute)),
                XmlErrorMessages.message("duplicate.attribute", localName));
        addToResults(highlightInfo);

        IntentionAction intentionAction = new RemoveAttributeIntentionFix(localName, attribute);

        QuickFixAction.registerQuickFixAction(highlightInfo, intentionAction);
      }
    }
  }
  private static void visitParameterList(
      @NotNull ProblemsHolder holder,
      @Nullable GoParameters parameters,
      @NotNull String ownerType,
      @NotNull String what) {

    if (parameters == null || parameters.getParameterDeclarationList().isEmpty()) return;
    boolean hasNamed = false;
    boolean hasUnnamed = false;
    for (GoParameterDeclaration parameterDeclaration : parameters.getParameterDeclarationList()) {
      ProgressManager.checkCanceled();
      if (parameterDeclaration.getParamDefinitionList().isEmpty()) {
        hasUnnamed = true;
      } else {
        hasNamed = true;
      }

      if (hasNamed && hasUnnamed) {
        holder.registerProblem(
            parameters,
            ownerType + " has both named and unnamed " + what + " <code>#ref</code> #loc",
            ProblemHighlightType.GENERIC_ERROR_OR_WARNING);
        return;
      }
    }
  }
  public byte[] loadContent() throws IOException, VcsException {
    ContentLoader loader = new ContentLoader(myURL, myRevision, myPegRevision);
    if (ApplicationManager.getApplication().isDispatchThread() && !myRevision.isLocal()) {
      ProgressManager.getInstance()
          .runProcessWithProgressSynchronously(
              loader,
              SvnBundle.message("progress.title.loading.file.content"),
              false,
              myVCS.getProject());
    } else {
      loader.run();
    }

    VcsException exception = loader.getException();
    if (exception == null) {
      final byte[] contents = loader.getContents();
      ContentRevisionCache.checkContentsSize(myURL, contents.length);
      return contents;
    } else {
      LOG.info(
          "Failed to load file '"
              + myURL
              + "' content at revision: "
              + myRevision
              + "\n"
              + exception.getMessage(),
          exception);
      throw exception;
    }
  }
  private static boolean checkRemoteFolder(
      Project project,
      final SvnVcs17 activeVcs,
      final String parent,
      ProgressManager progressManager)
      throws VcsException {
    final SVNException[] exc = new SVNException[1];
    final boolean[] folderEmpty = new boolean[1];

    progressManager.runProcessWithProgressSynchronously(
        new Runnable() {
          @Override
          public void run() {
            try {
              folderEmpty[0] = SvnUtil.remoteFolderIsEmpty(activeVcs, parent);
            } catch (SVNException e) {
              exc[0] = e;
            }
          }
        },
        "Check remote folder contents",
        false,
        project);
    if (exc[0] != null) {
      throw new VcsException(exc[0]);
    }
    return folderEmpty[0];
  }
  public synchronized void addItem(final CompletionResult item) {
    if (!isRunning()) return;
    ProgressManager.checkCanceled();

    final boolean unitTestMode = ApplicationManager.getApplication().isUnitTestMode();
    if (!unitTestMode) {
      LOG.assertTrue(!ApplicationManager.getApplication().isDispatchThread());
    }

    LOG.assertTrue(myParameters.getPosition().isValid());

    myItemSorters.put(item.getLookupElement(), (CompletionSorterImpl) item.getSorter());
    myLookup.addItem(item.getLookupElement(), item.getPrefixMatcher());
    myCount++;

    if (myCount == 1) {
      new Alarm(Alarm.ThreadToUse.SHARED_THREAD, this)
          .addRequest(
              new Runnable() {
                @Override
                public void run() {
                  myFreezeSemaphore.up();
                }
              },
              300);
    }
    myQueue.queue(myUpdate);
  }
 public boolean checkConflicts(final ExtractSuperclassDialog dialog) {
   final MemberInfo[] infos =
       ArrayUtil.toObjectArray(dialog.getSelectedMemberInfos(), MemberInfo.class);
   final PsiDirectory targetDirectory = dialog.getTargetDirectory();
   final PsiPackage targetPackage;
   if (targetDirectory != null) {
     targetPackage = JavaDirectoryService.getInstance().getPackage(targetDirectory);
   } else {
     targetPackage = null;
   }
   final MultiMap<PsiElement, String> conflicts = new MultiMap<PsiElement, String>();
   if (!ProgressManager.getInstance()
       .runProcessWithProgressSynchronously(
           new Runnable() {
             public void run() {
               final PsiClass superClass =
                   mySubclass.getExtendsListTypes().length > 0 ? mySubclass.getSuperClass() : null;
               conflicts.putAllValues(
                   PullUpConflictsUtil.checkConflicts(
                       infos,
                       mySubclass,
                       superClass,
                       targetPackage,
                       targetDirectory,
                       dialog.getContainmentVerifier(),
                       false));
             }
           },
           RefactoringBundle.message("detecting.possible.conflicts"),
           true,
           myProject)) return false;
   ExtractSuperClassUtil.checkSuperAccessible(targetDirectory, conflicts, mySubclass);
   return ExtractSuperClassUtil.showConflicts(dialog, conflicts, myProject);
 }
 public void actionPerformed(final AnActionEvent e) {
   final AnalysisScope scope = getScope();
   LOG.assertTrue(scope != null);
   final DependenciesBuilder builder;
   if (!myForward) {
     builder = new BackwardDependenciesBuilder(myProject, scope, myScopeOfInterest);
   } else {
     builder = new ForwardDependenciesBuilder(myProject, scope, myTransitiveBorder);
   }
   ProgressManager.getInstance()
       .runProcessWithProgressAsynchronously(
           myProject,
           AnalysisScopeBundle.message("package.dependencies.progress.title"),
           new Runnable() {
             public void run() {
               builder.analyze();
             }
           },
           new Runnable() {
             public void run() {
               myBuilders.add(builder);
               myDependencies.putAll(builder.getDependencies());
               myIllegalDependencies.putAll(builder.getIllegalDependencies());
               exclude(myExcluded);
               rebuild();
             }
           },
           null,
           new PerformAnalysisInBackgroundOption(myProject));
 }
 private void doIndexing(
     @NotNull final VirtualFile virtualFile, @NotNull final ProgressIndicator indicator) {
   final int fileId = FileBasedIndex.getFileId(virtualFile);
   indicator.setText("IntelliJence Advisor plugin indexing...");
   indicator.setText2(virtualFile.getCanonicalPath());
   final Long timestamp = getTimestamp(fileId);
   ProgressManager.checkCanceled();
   final long currentTimeStamp = virtualFile.getModificationStamp();
   if (timestamp == null || timestamp != currentTimeStamp) {
     putTimestamp(fileId, currentTimeStamp);
     final ClassReader reader;
     try {
       reader = new ClassReader(virtualFile.contentsToByteArray());
     } catch (IOException e) {
       removeTimestamp(fileId);
       return;
     }
     try {
       for (final AdvisorBaseIndex index : indexes) {
         index.update(fileId, reader);
       }
     } catch (RuntimeException e) {
       log.error(String.format("can't index file: %s", virtualFile.getCanonicalPath()));
       // TODO delete it
       e.printStackTrace();
       throw e;
     }
   }
 }