public void restore(BreakpointTree tree) {
      final List<TreePath> pathsToExpand = getPaths(tree, myExpandedUserObjects);
      if (!pathsToExpand.isEmpty()) {
        TreeUtil.restoreExpandedPaths(tree, pathsToExpand);
      }

      final List<TreePath> pathsToSelect = getPaths(tree, mySelectedUserObjects);
      if (!pathsToSelect.isEmpty()) {
        tree.getSelectionModel().clearSelection();
        tree.setSelectionPaths(pathsToSelect.toArray(new TreePath[pathsToSelect.size()]));
      }
    }
Exemplo n.º 2
0
 protected void download() {
   List<AppUpdate> updates = getUpdatesList();
   updates.addAll(_installs);
   if (!updates.isEmpty()) {
     _downloads = getDownloadList(updates);
     _deletions = getDeletionList(updates);
     if (!_downloads.isEmpty()) {
       getProgressPanel().setText("Downloading files...");
       download(updates); // download & verify updated/new files
     } else if (!_deletions.isEmpty()) {
       setState(State.StopEngine); // skip download & verify
     }
   } else setState(State.Finalise);
 }
Exemplo n.º 3
0
 @Nullable
 public static TextRange findNext(
     @NotNull Editor editor,
     @NotNull String pattern,
     final int offset,
     boolean ignoreCase,
     final boolean forwards) {
   final List<TextRange> results =
       findAll(editor, pattern, 0, -1, shouldIgnoreCase(pattern, ignoreCase));
   if (results.isEmpty()) {
     return null;
   }
   final int size = EditorHelper.getFileSize(editor);
   final TextRange max =
       Collections.max(
           results,
           new Comparator<TextRange>() {
             @Override
             public int compare(TextRange r1, TextRange r2) {
               final int d1 = distance(r1, offset, forwards, size);
               final int d2 = distance(r2, offset, forwards, size);
               if (d1 < 0 && d2 >= 0) {
                 return Integer.MAX_VALUE;
               }
               return d2 - d1;
             }
           });
   if (!Options.getInstance().isSet("wrapscan")) {
     final int start = max.getStartOffset();
     if (forwards && start < offset || start >= offset) {
       return null;
     }
   }
   return max;
 }
Exemplo n.º 4
0
 @NotNull
 private XmlAttribute[] calculateAttributes(final Map<String, String> attributesValueMap) {
   final List<XmlAttribute> result = new ArrayList<XmlAttribute>(10);
   processChildren(
       new PsiElementProcessor() {
         public boolean execute(@NotNull PsiElement element) {
           if (element instanceof XmlAttribute) {
             XmlAttribute attribute = (XmlAttribute) element;
             result.add(attribute);
             cacheOneAttributeValue(attribute.getName(), attribute.getValue(), attributesValueMap);
             myHaveNamespaceDeclarations =
                 myHaveNamespaceDeclarations || attribute.isNamespaceDeclaration();
           } else if (element instanceof XmlToken
               && ((XmlToken) element).getTokenType() == XmlTokenType.XML_TAG_END) {
             return false;
           }
           return true;
         }
       });
   if (result.isEmpty()) {
     return XmlAttribute.EMPTY_ARRAY;
   } else {
     return ContainerUtil.toArray(result, new XmlAttribute[result.size()]);
   }
 }
  @Nullable
  private ProblemDescriptor[] checkMember(
      final PsiDocCommentOwner docCommentOwner,
      final InspectionManager manager,
      final boolean isOnTheFly) {
    final ArrayList<ProblemDescriptor> problems = new ArrayList<ProblemDescriptor>();
    final PsiDocComment docComment = docCommentOwner.getDocComment();
    if (docComment == null) return null;

    final Set<PsiJavaCodeReferenceElement> references = new HashSet<PsiJavaCodeReferenceElement>();
    docComment.accept(getVisitor(references, docCommentOwner, problems, manager, isOnTheFly));
    for (PsiJavaCodeReferenceElement reference : references) {
      final List<PsiClass> classesToImport = new ImportClassFix(reference).getClassesToImport();
      final PsiElement referenceNameElement = reference.getReferenceNameElement();
      problems.add(
          manager.createProblemDescriptor(
              referenceNameElement != null ? referenceNameElement : reference,
              cannotResolveSymbolMessage("<code>" + reference.getText() + "</code>"),
              !isOnTheFly || classesToImport.isEmpty() ? null : new AddImportFix(classesToImport),
              ProblemHighlightType.LIKE_UNKNOWN_SYMBOL,
              isOnTheFly));
    }

    return problems.isEmpty() ? null : problems.toArray(new ProblemDescriptor[problems.size()]);
  }
Exemplo n.º 6
0
  public String getAttributeValue(String _name, String namespace) {
    if (namespace == null) {
      return getAttributeValue(_name);
    }

    XmlTagImpl current = this;
    PsiElement parent = getParent();

    while (current != null) {
      BidirectionalMap<String, String> map = current.initNamespaceMaps(parent);
      if (map != null) {
        List<String> keysByValue = map.getKeysByValue(namespace);
        if (keysByValue != null && !keysByValue.isEmpty()) {

          for (String prefix : keysByValue) {
            if (prefix != null && prefix.length() > 0) {
              final String value = getAttributeValue(prefix + ":" + _name);
              if (value != null) return value;
            }
          }
        }
      }

      current = parent instanceof XmlTag ? (XmlTagImpl) parent : null;
      parent = parent.getParent();
    }

    if (namespace.length() == 0 || getNamespace().equals(namespace)) {
      return getAttributeValue(_name);
    }
    return null;
  }
  @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);
              });
    }
  }
Exemplo n.º 8
0
 @NotNull
 public static String toKeyNotation(@NotNull List<KeyStroke> keys) {
   if (keys.isEmpty()) {
     return "<Nop>";
   }
   final StringBuilder builder = new StringBuilder();
   for (KeyStroke key : keys) {
     builder.append(toKeyNotation(key));
   }
   return builder.toString();
 }
 private void setupExternals() {
   List<String> externalFiles =
       Globals.prefs.getStringList(JabRefPreferences.EXTERNAL_JOURNAL_LISTS);
   if (externalFiles.isEmpty()) {
     ExternalFileEntry efe = new ExternalFileEntry();
     externals.add(efe);
   } else {
     for (String externalFile : externalFiles) {
       ExternalFileEntry efe = new ExternalFileEntry(externalFile);
       externals.add(efe);
     }
   }
 }
Exemplo n.º 10
0
 @Nullable
 private static SearchScope getSelectedFilesScope(
     final Project project, @Nullable DataContext dataContext) {
   final VirtualFile[] filesOrDirs =
       dataContext == null ? null : CommonDataKeys.VIRTUAL_FILE_ARRAY.getData(dataContext);
   if (filesOrDirs != null) {
     final List<VirtualFile> selectedFiles =
         ContainerUtil.filter(filesOrDirs, file -> !file.isDirectory());
     if (!selectedFiles.isEmpty()) {
       return GlobalSearchScope.filesScope(project, selectedFiles, "Selected Files");
     }
   }
   return null;
 }
Exemplo n.º 11
0
 public String getPrefixByNamespace(String namespace) {
   final PsiElement parent = getParent();
   BidirectionalMap<String, String> map = initNamespaceMaps(parent);
   if (map != null) {
     List<String> keysByValue = map.getKeysByValue(namespace);
     final String ns = keysByValue == null || keysByValue.isEmpty() ? null : keysByValue.get(0);
     if (ns != null) return ns;
   }
   if (parent instanceof XmlTag) return ((XmlTag) parent).getPrefixByNamespace(namespace);
   // The prefix 'xml' is by definition bound to the namespace name
   // http://www.w3.org/XML/1998/namespace. It MAY, but need not, be declared
   if (XmlUtil.XML_NAMESPACE_URI.equals(namespace)) return XML_NS_PREFIX;
   return null;
 }
 public void enableBreakpoints(final DebugProcessImpl debugProcess) {
   final List<Breakpoint> breakpoints = getBreakpoints();
   if (!breakpoints.isEmpty()) {
     for (Breakpoint breakpoint : breakpoints) {
       breakpoint.markVerified(false); // clean cached state
       breakpoint.createRequest(debugProcess);
     }
     SwingUtilities.invokeLater(
         new Runnable() {
           @Override
           public void run() {
             updateBreakpointsUI();
           }
         });
   }
 }
 // interaction with RequestManagerImpl
 public void disableBreakpoints(@NotNull final DebugProcessImpl debugProcess) {
   final List<Breakpoint> breakpoints = getBreakpoints();
   if (!breakpoints.isEmpty()) {
     final RequestManagerImpl requestManager = debugProcess.getRequestsManager();
     for (Breakpoint breakpoint : breakpoints) {
       breakpoint.markVerified(requestManager.isVerified(breakpoint));
       requestManager.deleteRequest(breakpoint);
     }
     SwingUtilities.invokeLater(
         new Runnable() {
           @Override
           public void run() {
             updateBreakpointsUI();
           }
         });
   }
 }
  private static int getItemToSelect(
      LookupImpl lookup,
      List<LookupElement> items,
      boolean onExplicitAction,
      @Nullable LookupElement mostRelevant) {
    if (items.isEmpty() || lookup.getFocusDegree() == LookupImpl.FocusDegree.UNFOCUSED) {
      return 0;
    }

    if (lookup.isSelectionTouched() || !onExplicitAction) {
      final LookupElement lastSelection = lookup.getCurrentItem();
      int old = ContainerUtil.indexOfIdentity(items, lastSelection);
      if (old >= 0) {
        return old;
      }

      Object selectedValue = ((LookupImpl) lookup).getList().getSelectedValue();
      if (selectedValue instanceof EmptyLookupItem
          && ((EmptyLookupItem) selectedValue).isLoading()) {
        int index = ((LookupImpl) lookup).getList().getSelectedIndex();
        if (index >= 0 && index < items.size()) {
          return index;
        }
      }

      for (int i = 0; i < items.size(); i++) {
        String invariant = PRESENTATION_INVARIANT.get(items.get(i));
        if (invariant != null && invariant.equals(PRESENTATION_INVARIANT.get(lastSelection))) {
          return i;
        }
      }
    }

    String selectedText = lookup.getEditor().getSelectionModel().getSelectedText();
    for (int i = 0; i < items.size(); i++) {
      LookupElement item = items.get(i);
      if (isPrefixItem(lookup, item, true) && !isLiveTemplate(item)
          || item.getLookupString().equals(selectedText)) {
        return i;
      }
    }

    return Math.max(0, ContainerUtil.indexOfIdentity(items, mostRelevant));
  }
  /** This is called when rebase is pressed: executes rebase in background. */
  private void rebase() {
    final List<VcsException> exceptions = new ArrayList<VcsException>();
    final RebaseInfo rebaseInfo = collectRebaseInfo();

    ProgressManager.getInstance()
        .runProcessWithProgressSynchronously(
            new Runnable() {
              public void run() {
                executeRebase(exceptions, rebaseInfo);
              }
            },
            GitBundle.getString("push.active.rebasing"),
            true,
            myProject);
    if (!exceptions.isEmpty()) {
      GitUIUtil.showOperationErrors(myProject, exceptions, "git rebase");
    }
    refreshTree(false, rebaseInfo.uncheckedCommits);
    VcsFileUtil.refreshFiles(myProject, rebaseInfo.roots);
  }
Exemplo n.º 16
0
  /**
   * Add all the menu currently available to the menu. This may be called any time BlueJ feels that
   * the menu needs to be updated.
   *
   * @param onThisProject a specific project to look for, or null for all projects.
   */
  public void addExtensionMenu(Project onThisProject) {
    // Get all menus that can be possibly be generated now.
    List<JMenuItem> menuItems = extMgr.getMenuItems(menuGenerator, onThisProject);

    // Retrieve all the items from the current menu
    MenuElement[] elements = popupMenu.getSubElements();

    for (int index = 0; index < elements.length; index++) {
      JComponent aComponent = (JComponent) elements[index].getComponent();

      if (aComponent == null) {
        continue;
      }

      if (!(aComponent instanceof JMenuItem)) {
        continue;
      }

      ExtensionWrapper aWrapper =
          (ExtensionWrapper) aComponent.getClientProperty("bluej.extmgr.ExtensionWrapper");

      if (aWrapper == null) {
        continue;
      }

      popupMenu.remove(aComponent);
    }

    popupMenu.remove(menuSeparator);

    // If the provided menu is empty we are done here.
    if (menuItems.isEmpty()) {
      return;
    }

    popupMenu.add(menuSeparator);

    for (JMenuItem menuItem : menuItems) {
      popupMenu.add(menuItem);
    }
  }
Exemplo n.º 17
0
 /** Get iterator over one image */
 public LineIterator getLineIterator(
     ProgressHandle progh,
     EvStack stack,
     EvImage im,
     final String channel,
     final EvDecimal frame,
     final double z) {
   List<ROI> subRoi = getSubRoi();
   if (imageInRange(channel, frame, z) && !subRoi.isEmpty()) {
     LineIterator li = subRoi.get(0).getLineIterator(progh, stack, im, channel, frame, z);
     for (int i = 1; i < subRoi.size(); i++)
       li =
           new ThisLineIterator(
               im,
               subRoi.get(i).getLineIterator(progh, stack, im, channel, frame, z),
               li,
               channel,
               frame,
               z);
     return li;
   } else return new EmptyLineIterator();
 }
  @Nullable
  private LocalQuickFix[] createNPEFixes(
      PsiExpression qualifier, PsiExpression expression, boolean onTheFly) {
    if (qualifier == null || expression == null) return null;
    if (qualifier instanceof PsiMethodCallExpression) return null;

    try {
      final List<LocalQuickFix> fixes = new SmartList<LocalQuickFix>();

      if (!(qualifier instanceof PsiLiteralExpression
          && ((PsiLiteralExpression) qualifier).getValue() == null)) {
        if (PsiUtil.getLanguageLevel(qualifier).isAtLeast(LanguageLevel.JDK_1_4)) {
          final Project project = qualifier.getProject();
          final PsiElementFactory elementFactory =
              JavaPsiFacade.getInstance(project).getElementFactory();
          final PsiBinaryExpression binary =
              (PsiBinaryExpression) elementFactory.createExpressionFromText("a != null", null);
          binary.getLOperand().replace(qualifier);
          ContainerUtil.addIfNotNull(fixes, createAssertFix(binary, expression));
        }

        addSurroundWithIfFix(qualifier, fixes, onTheFly);

        if (ReplaceWithTernaryOperatorFix.isAvailable(qualifier, expression)) {
          fixes.add(new ReplaceWithTernaryOperatorFix(qualifier));
        }
      }

      ContainerUtil.addIfNotNull(
          fixes, DfaOptionalSupport.registerReplaceOptionalOfWithOfNullableFix(qualifier));
      return fixes.isEmpty() ? null : fixes.toArray(new LocalQuickFix[fixes.size()]);
    } catch (IncorrectOperationException e) {
      LOG.error(e);
      return null;
    }
  }
Exemplo n.º 19
0
  @NotNull
  @Override
  public List<SearchScope> getPredefinedScopes(
      @NotNull final Project project,
      @Nullable final DataContext dataContext,
      boolean suggestSearchInLibs,
      boolean prevSearchFiles,
      boolean currentSelection,
      boolean usageView,
      boolean showEmptyScopes) {
    Collection<SearchScope> result = ContainerUtil.newLinkedHashSet();
    result.add(GlobalSearchScope.projectScope(project));
    if (suggestSearchInLibs) {
      result.add(GlobalSearchScope.allScope(project));
    }

    if (ModuleUtil.isSupportedRootType(project, JavaSourceRootType.TEST_SOURCE)) {
      result.add(GlobalSearchScopesCore.projectProductionScope(project));
      result.add(GlobalSearchScopesCore.projectTestScope(project));
    }

    final GlobalSearchScope openFilesScope = GlobalSearchScopes.openFilesScope(project);
    if (openFilesScope != GlobalSearchScope.EMPTY_SCOPE) {
      result.add(openFilesScope);
    } else if (showEmptyScopes) {
      result.add(
          new LocalSearchScope(PsiElement.EMPTY_ARRAY, IdeBundle.message("scope.open.files")));
    }

    final Editor selectedTextEditor =
        ApplicationManager.getApplication().isDispatchThread()
            ? FileEditorManager.getInstance(project).getSelectedTextEditor()
            : null;
    final PsiFile psiFile =
        (selectedTextEditor != null)
            ? PsiDocumentManager.getInstance(project).getPsiFile(selectedTextEditor.getDocument())
            : null;
    PsiFile currentFile = psiFile;

    if (dataContext != null) {
      PsiElement dataContextElement = CommonDataKeys.PSI_FILE.getData(dataContext);
      if (dataContextElement == null) {
        dataContextElement = CommonDataKeys.PSI_ELEMENT.getData(dataContext);
      }

      if (dataContextElement == null && psiFile != null) {
        dataContextElement = psiFile;
      }

      if (dataContextElement != null) {
        if (!PlatformUtils.isCidr()) { // TODO: have an API to disable module scopes.
          Module module = ModuleUtilCore.findModuleForPsiElement(dataContextElement);
          if (module == null) {
            module = LangDataKeys.MODULE.getData(dataContext);
          }
          if (module != null && !(ModuleType.get(module) instanceof InternalModuleType)) {
            result.add(module.getModuleScope());
          }
        }
        if (currentFile == null) {
          currentFile = dataContextElement.getContainingFile();
        }
      }
    }

    if (currentFile != null || showEmptyScopes) {
      PsiElement[] scope =
          currentFile != null ? new PsiElement[] {currentFile} : PsiElement.EMPTY_ARRAY;
      result.add(new LocalSearchScope(scope, IdeBundle.message("scope.current.file")));
    }

    if (currentSelection && selectedTextEditor != null && psiFile != null) {
      SelectionModel selectionModel = selectedTextEditor.getSelectionModel();
      if (selectionModel.hasSelection()) {
        int start = selectionModel.getSelectionStart();
        final PsiElement startElement = psiFile.findElementAt(start);
        if (startElement != null) {
          int end = selectionModel.getSelectionEnd();
          final PsiElement endElement = psiFile.findElementAt(end);
          if (endElement != null) {
            final PsiElement parent = PsiTreeUtil.findCommonParent(startElement, endElement);
            if (parent != null) {
              final List<PsiElement> elements = new ArrayList<PsiElement>();
              final PsiElement[] children = parent.getChildren();
              TextRange selection = new TextRange(start, end);
              for (PsiElement child : children) {
                if (!(child instanceof PsiWhiteSpace)
                    && child.getContainingFile() != null
                    && selection.contains(child.getTextOffset())) {
                  elements.add(child);
                }
              }
              if (!elements.isEmpty()) {
                SearchScope local =
                    new LocalSearchScope(
                        PsiUtilCore.toPsiElementArray(elements),
                        IdeBundle.message("scope.selection"));
                result.add(local);
              }
            }
          }
        }
      }
    }

    if (usageView) {
      addHierarchyScope(project, result);
      UsageView selectedUsageView = UsageViewManager.getInstance(project).getSelectedUsageView();
      if (selectedUsageView != null && !selectedUsageView.isSearchInProgress()) {
        final Set<Usage> usages = ContainerUtil.newTroveSet(selectedUsageView.getUsages());
        usages.removeAll(selectedUsageView.getExcludedUsages());
        final List<PsiElement> results = new ArrayList<PsiElement>(usages.size());

        if (prevSearchFiles) {
          final Set<VirtualFile> files = collectFiles(usages, true);
          if (!files.isEmpty()) {
            GlobalSearchScope prev =
                new GlobalSearchScope(project) {
                  private Set<VirtualFile> myFiles = null;

                  @NotNull
                  @Override
                  public String getDisplayName() {
                    return IdeBundle.message("scope.files.in.previous.search.result");
                  }

                  @Override
                  public synchronized boolean contains(@NotNull VirtualFile file) {
                    if (myFiles == null) {
                      myFiles = collectFiles(usages, false);
                    }
                    return myFiles.contains(file);
                  }

                  @Override
                  public int compare(@NotNull VirtualFile file1, @NotNull VirtualFile file2) {
                    return 0;
                  }

                  @Override
                  public boolean isSearchInModuleContent(@NotNull Module aModule) {
                    return true;
                  }

                  @Override
                  public boolean isSearchInLibraries() {
                    return true;
                  }
                };
            result.add(prev);
          }
        } else {
          for (Usage usage : usages) {
            if (usage instanceof PsiElementUsage) {
              final PsiElement element = ((PsiElementUsage) usage).getElement();
              if (element != null && element.isValid() && element.getContainingFile() != null) {
                results.add(element);
              }
            }
          }

          if (!results.isEmpty()) {
            result.add(
                new LocalSearchScope(
                    PsiUtilCore.toPsiElementArray(results),
                    IdeBundle.message("scope.previous.search.results")));
          }
        }
      }
    }

    final FavoritesManager favoritesManager = FavoritesManager.getInstance(project);
    if (favoritesManager != null) {
      for (final String favorite : favoritesManager.getAvailableFavoritesListNames()) {
        final Collection<TreeItem<Pair<AbstractUrl, String>>> rootUrls =
            favoritesManager.getFavoritesListRootUrls(favorite);
        if (rootUrls.isEmpty()) continue; // ignore unused root
        result.add(
            new GlobalSearchScope(project) {
              @NotNull
              @Override
              public String getDisplayName() {
                return "Favorite \'" + favorite + "\'";
              }

              @Override
              public boolean contains(@NotNull final VirtualFile file) {
                return ApplicationManager.getApplication()
                    .runReadAction(
                        (Computable<Boolean>) () -> favoritesManager.contains(favorite, file));
              }

              @Override
              public int compare(
                  @NotNull final VirtualFile file1, @NotNull final VirtualFile file2) {
                return 0;
              }

              @Override
              public boolean isSearchInModuleContent(@NotNull final Module aModule) {
                return true;
              }

              @Override
              public boolean isSearchInLibraries() {
                return true;
              }
            });
      }
    }

    ContainerUtil.addIfNotNull(result, getSelectedFilesScope(project, dataContext));

    return ContainerUtil.newArrayList(result);
  }
  public boolean setProjectRoot(@NotNull final VirtualFile projectRoot) {
    if (projectRoot.equals(myProjectRoot)) {
      return true;
    }

    boolean unitTestMode = ApplicationManager.getApplication().isUnitTestMode();

    myProjectRoot = projectRoot;
    if (!unitTestMode && projectRoot instanceof VirtualDirectoryImpl) {
      ((VirtualDirectoryImpl) projectRoot).refreshAndFindChild("deps");
    }

    ProgressManager.getInstance()
        .run(
            new Task.Modal(getCurrentProject(), "Scanning Rebar projects", true) {
              public void run(@NotNull final ProgressIndicator indicator) {

                List<VirtualFile> rebarConfigFiles = findRebarConfigs(myProjectRoot, indicator);
                final LinkedHashSet<ImportedOtpApp> importedOtpApps =
                    new LinkedHashSet<ImportedOtpApp>(rebarConfigFiles.size());

                VfsUtilCore.visitChildrenRecursively(
                    projectRoot,
                    new VirtualFileVisitor() {
                      @Override
                      public boolean visitFile(@NotNull VirtualFile file) {
                        indicator.checkCanceled();

                        if (file.isDirectory()) {
                          indicator.setText2(file.getPath());
                          if (isExamplesDirectory(file)
                              || isRelDirectory(projectRoot.getPath(), file.getPath()))
                            return false;
                        }

                        ContainerUtil.addAllNotNull(importedOtpApps, createImportedOtpApp(file));
                        return true;
                      }
                    });

                myFoundOtpApps = ContainerUtil.newArrayList(importedOtpApps);
              }
            });

    Collections.sort(
        myFoundOtpApps,
        new Comparator<ImportedOtpApp>() {
          @Override
          public int compare(ImportedOtpApp o1, ImportedOtpApp o2) {
            int nameCompareResult =
                String.CASE_INSENSITIVE_ORDER.compare(o1.getName(), o2.getName());
            if (nameCompareResult == 0) {
              return String.CASE_INSENSITIVE_ORDER.compare(
                  o1.getRoot().getPath(), o2.getRoot().getPath());
            }
            return nameCompareResult;
          }
        });

    mySelectedOtpApps = myFoundOtpApps;
    return !myFoundOtpApps.isEmpty();
  }
 @Nullable
 public static PsiMethod findMethodBySignature(
     @NotNull PsiClass aClass, @NotNull PsiMethod patternMethod, final boolean checkBases) {
   final List<PsiMethod> result = findMethodsBySignature(aClass, patternMethod, checkBases, true);
   return result.isEmpty() ? null : result.get(0);
 }
 @Nullable
 public static PsiField findFieldByName(
     @NotNull PsiClass aClass, String name, boolean checkBases) {
   List<PsiMember> byMap = findByMap(aClass, name, checkBases, MemberType.FIELD);
   return byMap.isEmpty() ? null : (PsiField) byMap.get(0);
 }
  @Override
  public void restartRunProfile(@NotNull final ExecutionEnvironment environment) {
    RunnerAndConfigurationSettings configuration = environment.getRunnerAndConfigurationSettings();

    List<RunContentDescriptor> runningIncompatible;
    if (configuration == null) {
      runningIncompatible = Collections.emptyList();
    } else {
      runningIncompatible = getIncompatibleRunningDescriptors(configuration);
    }

    RunContentDescriptor contentToReuse = environment.getContentToReuse();
    final List<RunContentDescriptor> runningOfTheSameType = new SmartList<>();
    if (configuration != null && configuration.isSingleton()) {
      runningOfTheSameType.addAll(getRunningDescriptorsOfTheSameConfigType(configuration));
    } else if (isProcessRunning(contentToReuse)) {
      runningOfTheSameType.add(contentToReuse);
    }

    List<RunContentDescriptor> runningToStop =
        ContainerUtil.concat(runningOfTheSameType, runningIncompatible);
    if (!runningToStop.isEmpty()) {
      if (configuration != null) {
        if (!runningOfTheSameType.isEmpty()
            && (runningOfTheSameType.size() > 1
                || contentToReuse == null
                || runningOfTheSameType.get(0) != contentToReuse)
            && !userApprovesStopForSameTypeConfigurations(
                environment.getProject(), configuration.getName(), runningOfTheSameType.size())) {
          return;
        }
        if (!runningIncompatible.isEmpty()
            && !userApprovesStopForIncompatibleConfigurations(
                myProject, configuration.getName(), runningIncompatible)) {
          return;
        }
      }

      for (RunContentDescriptor descriptor : runningToStop) {
        stop(descriptor);
      }
    }

    if (myAwaitingRunProfiles.get(environment.getRunProfile()) == environment) {
      // defense from rerunning exactly the same ExecutionEnvironment
      return;
    }
    myAwaitingRunProfiles.put(environment.getRunProfile(), environment);

    awaitTermination(
        new Runnable() {
          @Override
          public void run() {
            if (myAwaitingRunProfiles.get(environment.getRunProfile()) != environment) {
              // a new rerun has been requested before starting this one, ignore this rerun
              return;
            }
            if ((DumbService.getInstance(myProject).isDumb()
                    && !Registry.is("dumb.aware.run.configurations"))
                || ExecutorRegistry.getInstance().isStarting(environment)) {
              awaitTermination(this, 100);
              return;
            }

            for (RunContentDescriptor descriptor : runningOfTheSameType) {
              ProcessHandler processHandler = descriptor.getProcessHandler();
              if (processHandler != null && !processHandler.isProcessTerminated()) {
                awaitTermination(this, 100);
                return;
              }
            }
            myAwaitingRunProfiles.remove(environment.getRunProfile());
            start(environment);
          }
        },
        50);
  }
Exemplo n.º 24
0
  /**
   * Returns the default <tt>ContactDetail</tt> to use for any operations depending to the given
   * <tt>OperationSet</tt> class.
   *
   * @param opSetClass the <tt>OperationSet</tt> class we're interested in
   * @return the default <tt>ContactDetail</tt> to use for any operations depending to the given
   *     <tt>OperationSet</tt> class
   */
  public UIContactDetail getDefaultContactDetail(Class<? extends OperationSet> opSetClass) {
    List<UIContactDetail> details = getContactDetailsForOperationSet(opSetClass);

    return (details != null && !details.isEmpty()) ? details.get(0) : null;
  }