Java Code Examples for com.intellij.openapi.util.Conditions

The following are top voted examples for showing how to use com.intellij.openapi.util.Conditions. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: intellij-ce-playground   File: LambdaCanBeMethodReferenceInspection.java   Source Code and License 6 votes vote down vote up
private static boolean checkQualifier(PsiElement qualifier) {
  if (qualifier == null) {
    return true;
  }
  final Condition<PsiElement> callExpressionCondition = Conditions.instanceOf(PsiCallExpression.class);
  final Condition<PsiElement> nonFinalFieldRefCondition = new Condition<PsiElement>() {
    @Override
    public boolean value(PsiElement expression) {
      if (expression instanceof PsiReferenceExpression) {
        PsiElement element = ((PsiReferenceExpression)expression).resolve();
        if (element instanceof PsiField && !((PsiField)element).hasModifierProperty(PsiModifier.FINAL)) {
          return true;
        }
      }
      return false;
    }
  };
  return SyntaxTraverser
    .psiTraverser()
    .withRoot(qualifier)
    .filter(Conditions.or(callExpressionCondition, nonFinalFieldRefCondition)).toList().isEmpty();
}
 
Example 2
Project: intellij-ce-playground   File: DfaExpressionFactory.java   Source Code and License 6 votes vote down vote up
private static Condition<String> parseFalseGetters() {
  try {
    String regex = Registry.stringValue("ide.dfa.getters.with.side.effects").trim();
    if (!StringUtil.isEmpty(regex)) {
      final Pattern pattern = Pattern.compile(regex);
      return new Condition<String>() {
        @Override
        public boolean value(String s) {
          return pattern.matcher(s).matches();
        }
      };
    }
  }
  catch (Exception e) {
    LOG.error(e);
  }
  return Conditions.alwaysFalse();
}
 
Example 3
Project: intellij-ce-playground   File: ProjectJdksConfigurable.java   Source Code and License 6 votes vote down vote up
@Override
@Nullable
protected ArrayList<AnAction> createActions(final boolean fromPopup) {
  if (myProjectJdksModel == null) {
    return null;
  }
  final ArrayList<AnAction> actions = new ArrayList<AnAction>();
  DefaultActionGroup group = new DefaultActionGroup(ProjectBundle.message("add.new.jdk.text"), true);
  group.getTemplatePresentation().setIcon(IconUtil.getAddIcon());
  myProjectJdksModel.createAddActions(group, myTree, new Consumer<Sdk>() {
    @Override
    public void consume(final Sdk projectJdk) {
      addNode(new MyNode(new JdkConfigurable(((ProjectJdkImpl)projectJdk), myProjectJdksModel, TREE_UPDATER, myHistory, myProject), false), myRoot);
      selectNodeInTree(findNodeByObject(myRoot, projectJdk));
    }
  });
  actions.add(new MyActionGroupWrapper(group));
  actions.add(new MyDeleteAction(Conditions.<Object[]>alwaysTrue()));
  return actions;
}
 
Example 4
Project: intellij-ce-playground   File: UpdaterTreeState.java   Source Code and License 6 votes vote down vote up
private void invalidateToSelectWithRefsToParent(DefaultMutableTreeNode actionNode) {
  if (actionNode != null) {
    Object readyElement = myUi.getElementFor(actionNode);
    if (readyElement != null) {
      Iterator<Object> toSelect = myToSelect.keySet().iterator();
      while (toSelect.hasNext()) {
        Object eachToSelect = toSelect.next();
        if (readyElement.equals(myUi.getTreeStructure().getParentElement(eachToSelect))) {
          List<Object> children = myUi.getLoadedChildrenFor(readyElement);
          if (!children.contains(eachToSelect)) {
            toSelect.remove();
            if (!myToSelect.containsKey(readyElement) && !myUi.getSelectedElements().contains(eachToSelect)) {
              addAdjustedSelection(eachToSelect, Conditions.alwaysFalse(), null);
            }
          }
        }
      }
    }
  }
}
 
Example 5
Project: intellij-ce-playground   File: ContainingBranchesGetter.java   Source Code and License 6 votes vote down vote up
@NotNull
public Condition<Hash> getContainedInBranchCondition(@NotNull final String branchName, @NotNull final VirtualFile root) {
  LOG.assertTrue(EventQueue.isDispatchThread());
  if (myRefs == null || myGraph == null) return Conditions.alwaysFalse();
  VcsRef branchRef = ContainerUtil.find(myRefs.getBranches(), new Condition<VcsRef>() {
    @Override
    public boolean value(VcsRef vcsRef) {
      return vcsRef.getRoot().equals(root) && vcsRef.getName().equals(branchName);
    }
  });
  if (branchRef == null) return Conditions.alwaysFalse();
  ContainedInBranchCondition condition = myConditions.get(root);
  if (condition == null || !condition.getBranch().equals(branchName)) {
    condition =
      new ContainedInBranchCondition(myGraph.getContainedInBranchCondition(Collections.singleton(myDataHolder.getCommitIndex(branchRef.getCommitHash()))),
                        branchName);
    myConditions.put(root, condition);
  }
  return condition;
}
 
Example 6
Project: intellij-ce-playground   File: InspectionEngine.java   Source Code and License 6 votes vote down vote up
@NotNull
public static Map<String, List<ProblemDescriptor>> inspectEx(@NotNull final List<LocalInspectionToolWrapper> toolWrappers,
                                                             @NotNull final PsiFile file,
                                                             @NotNull final InspectionManager iManager,
                                                             final boolean isOnTheFly,
                                                             boolean failFastOnAcquireReadAction,
                                                             @NotNull final ProgressIndicator indicator) {
  if (toolWrappers.isEmpty()) return Collections.emptyMap();
  final List<PsiElement> elements = new ArrayList<PsiElement>();

  TextRange range = file.getTextRange();
  Divider.divideInsideAndOutside(file, range.getStartOffset(), range.getEndOffset(), range, elements, new ArrayList<ProperTextRange>(),
                                 Collections.<PsiElement>emptyList(), Collections.<ProperTextRange>emptyList(), true, Conditions.<PsiFile>alwaysTrue());

  return inspectElements(toolWrappers, file, iManager, isOnTheFly, failFastOnAcquireReadAction, indicator, elements,
                         calcElementDialectIds(elements));
}
 
Example 7
Project: consulo-nodejs   File: NodeJSConfigurationPanelBase.java   Source Code and License 6 votes vote down vote up
@Override
protected void initComponents()
{
	myModuleBox = new ComboBox();
	myModuleBox.setRenderer(new ModuleListCellRenderer());

	myVmParametersComponent = LabeledComponent.create(new RawCommandLineEditor(), "VM arguments");
	myVmParametersComponent.setLabelLocation(BorderLayout.WEST);
	copyDialogCaption(myVmParametersComponent);

	myUseAlternativeBundleCheckBox = new JCheckBox("Use alternative bundle: ");
	ProjectSdksModel projectSdksModel = new ProjectSdksModel();
	projectSdksModel.reset();

	myAlternativeBundleComboBox = new SdkComboBox(projectSdksModel, Conditions.<SdkTypeId>is(NodeJSBundleType.getInstance()), true);
	myAlternativeBundleComboBox.setEnabled(false);
	myUseAlternativeBundleCheckBox.addItemListener(new ItemListener()
	{
		@Override
		public void itemStateChanged(ItemEvent e)
		{
			myAlternativeBundleComboBox.setEnabled(myUseAlternativeBundleCheckBox.isSelected());
		}
	});
	super.initComponents();
}
 
Example 8
Project: tools-idea   File: ProjectJdksConfigurable.java   Source Code and License 6 votes vote down vote up
@Override
@Nullable
protected ArrayList<AnAction> createActions(final boolean fromPopup) {
  final ArrayList<AnAction> actions = new ArrayList<AnAction>();
  DefaultActionGroup group = new DefaultActionGroup(ProjectBundle.message("add.new.jdk.text"), true);
  group.getTemplatePresentation().setIcon(IconUtil.getAddIcon());
  myProjectJdksModel.createAddActions(group, myTree, new Consumer<Sdk>() {
    @Override
    public void consume(final Sdk projectJdk) {
      addNode(new MyNode(new JdkConfigurable(((ProjectJdkImpl)projectJdk), myProjectJdksModel, TREE_UPDATER, myHistory, myProject), false), myRoot);
      selectNodeInTree(findNodeByObject(myRoot, projectJdk));
    }
  });
  actions.add(new MyActionGroupWrapper(group));
  actions.add(new MyDeleteAction(Conditions.<Object[]>alwaysTrue()));
  return actions;
}
 
Example 9
Project: nuxeo-intellij   File: NuxeoSDKsPanel.java   Source Code and License 6 votes vote down vote up
@Override
@Nullable
protected ArrayList<AnAction> createActions(boolean fromPopup) {
    ArrayList<AnAction> result = new ArrayList<AnAction>();
    result.add(new AnAction("Add", "Add", IconUtil.getAddIcon()) {
        {
            registerCustomShortcutSet(CommonShortcuts.INSERT, myTree);
        }

        public void actionPerformed(AnActionEvent event) {
            final VirtualFile sdk = NuxeoSDKChooser.chooseNuxeoSDK(project);
            if (sdk == null)
                return;

            final String name = askForNuxeoSDKName("Register Nuxeo SDK", "");
            if (name == null)
                return;
            final NuxeoSDK nuxeoSDK = new NuxeoSDK(name, sdk.getPath());
            addNuxeoSDKNode(nuxeoSDK);
        }
    });
    result.add(new MyDeleteAction(forAll(Conditions.alwaysTrue())));
    return result;
}
 
Example 10
Project: consulo-javaee   File: JavaEEServerConfigurationEditor.java   Source Code and License 6 votes vote down vote up
@NotNull
@Override
protected JComponent createEditor()
{
	JPanel verticalLayout = new JPanel(new VerticalFlowLayout(0, 0));

	ProjectSdksModel model = new ProjectSdksModel();
	model.reset();

	myBundleBox = new SdkComboBox(model, Conditions.equalTo(myBundleType), true);
	verticalLayout.add(LabeledComponent.left(myBundleBox, J2EEBundle.message("label.run.configuration.properties.application.server")));

	JPanel openBrowserPanel = new JPanel();
	openBrowserPanel.setBorder(IdeBorderFactory.createTitledBorder("Open browser"));
	verticalLayout.add(openBrowserPanel);

	if(myBundleType.isJreCustomizable())
	{
		AlternativeJREPanel panel = new AlternativeJREPanel();
		verticalLayout.add(panel);
	}

	verticalLayout.add(mySettingsWrapper);

	return verticalLayout;
}
 
Example 11
Project: consulo   File: InspectionEngine.java   Source Code and License 6 votes vote down vote up
@Nonnull
public static Map<String, List<ProblemDescriptor>> inspectEx(@Nonnull final List<LocalInspectionToolWrapper> toolWrappers,
                                                             @Nonnull final PsiFile file,
                                                             @Nonnull final InspectionManager iManager,
                                                             final boolean isOnTheFly,
                                                             boolean failFastOnAcquireReadAction,
                                                             @Nonnull final ProgressIndicator indicator) {
  if (toolWrappers.isEmpty()) return Collections.emptyMap();


  TextRange range = file.getTextRange();
  List<Divider.DividedElements> allDivided = new ArrayList<>();
  Divider.divideInsideAndOutsideAllRoots(file, range, range, Conditions.alwaysTrue(), new CommonProcessors.CollectProcessor<>(allDivided));

  List<PsiElement> elements = ContainerUtil.concat(
          (List<List<PsiElement>>)ContainerUtil.map(allDivided, d -> ContainerUtil.concat(d.inside, d.outside, d.parents)));

  return inspectElements(toolWrappers, file, iManager, isOnTheFly, failFastOnAcquireReadAction, indicator, elements,
                         calcElementDialectIds(elements));
}
 
Example 12
Project: consulo   File: ContainingBranchesGetter.java   Source Code and License 6 votes vote down vote up
@Nonnull
public Condition<CommitId> getContainedInBranchCondition(@Nonnull final String branchName, @Nonnull final VirtualFile root) {
  LOG.assertTrue(EventQueue.isDispatchThread());

  DataPack dataPack = myLogData.getDataPack();
  if (dataPack == DataPack.EMPTY) return Conditions.alwaysFalse();

  PermanentGraph<Integer> graph = dataPack.getPermanentGraph();
  VcsLogRefs refs = dataPack.getRefsModel();

  ContainedInBranchCondition condition = myConditions.get(root);
  if (condition == null || !condition.getBranch().equals(branchName)) {
    VcsRef branchRef = ContainerUtil.find(refs.getBranches(),
                                          vcsRef -> vcsRef.getRoot().equals(root) && vcsRef.getName().equals(branchName));
    if (branchRef == null) return Conditions.alwaysFalse();
    condition = new ContainedInBranchCondition(graph.getContainedInBranchCondition(
      Collections.singleton(myLogData.getCommitIndex(branchRef.getCommitHash(), branchRef.getRoot()))), branchName);
    myConditions.put(root, condition);
  }
  return condition;
}
 
Example 13
Project: consulo   File: CurrentBranchHighlighter.java   Source Code and License 6 votes vote down vote up
@Nonnull
@Override
public VcsCommitStyle getStyle(@Nonnull VcsShortCommitDetails details, boolean isSelected) {
  if (isSelected || !myLogUi.isHighlighterEnabled(Factory.ID)) return VcsCommitStyle.DEFAULT;
  Condition<CommitId> condition = myConditions.get(details.getRoot());
  if (condition == null) {
    VcsLogProvider provider = myLogData.getLogProvider(details.getRoot());
    String currentBranch = provider.getCurrentBranch(details.getRoot());
    if (!HEAD.equals(mySingleFilteredBranch) && currentBranch != null && !(currentBranch.equals(mySingleFilteredBranch))) {
      condition = myLogData.getContainingBranchesGetter().getContainedInBranchCondition(currentBranch, details.getRoot());
      myConditions.put(details.getRoot(), condition);
    }
    else {
      condition = Conditions.alwaysFalse();
    }
  }
  if (condition != null && condition.value(new CommitId(details.getId(), details.getRoot()))) {
    return VcsCommitStyleFactory.background(CURRENT_BRANCH_BG);
  }
  return VcsCommitStyle.DEFAULT;
}
 
Example 14
Project: consulo   File: VcsSelectionHistoryDialog.java   Source Code and License 6 votes vote down vote up
@Override
public Object getData(@Nonnull @NonNls Key<?> dataId) {
  if (CommonDataKeys.PROJECT == dataId) {
    return myProject;
  }
  else if (VcsDataKeys.VCS_VIRTUAL_FILE == dataId) {
    return myFile;
  }
  else if (VcsDataKeys.VCS_FILE_REVISION == dataId) {
    VcsFileRevision selectedObject = myList.getSelectedObject();
    return selectedObject instanceof CurrentRevision ? null : selectedObject;
  }
  else if (VcsDataKeys.VCS_FILE_REVISIONS == dataId) {
    List<VcsFileRevision> revisions = ContainerUtil.filter(myList.getSelectedObjects(), Conditions.notEqualTo(myLocalRevision));
    return ArrayUtil.toObjectArray(revisions, VcsFileRevision.class);
  }
  else if (VcsDataKeys.VCS == dataId) {
    return myActiveVcs.getKeyInstanceMethod();
  }
  else if (PlatformDataKeys.HELP_ID == dataId) {
    return myHelpId;
  }
  return null;
}
 
Example 15
Project: consulo   File: SdksConfigurable.java   Source Code and License 6 votes vote down vote up
@Override
@Nullable
protected ArrayList<AnAction> createActions(final boolean fromPopup) {
  final ArrayList<AnAction> actions = new ArrayList<AnAction>();
  DefaultActionGroup group = new DefaultActionGroup(ProjectBundle.message("add.action.name"), true);
  group.getTemplatePresentation().setIcon(IconUtil.getAddIcon());
  myProjectSdksModel.createAddActions(group, myTree, new Consumer<Sdk>() {
    @Override
    public void consume(final Sdk projectJdk) {
      addNode(new MyNode(new SdkConfigurable(((SdkImpl)projectJdk), myProjectSdksModel, TREE_UPDATER, myHistory, myProject), false), myRoot);
      selectNodeInTree(findNodeByObject(myRoot, projectJdk));
    }
  }, SdkListConfigurable.ADD_SDK_FILTER);
  actions.add(new MyActionGroupWrapper(group));
  actions.add(new MyDeleteAction(forAll(Conditions.alwaysTrue())));
  return actions;
}
 
Example 16
Project: consulo-java   File: LambdaCanBeMethodReferenceInspection.java   Source Code and License 6 votes vote down vote up
public static boolean checkQualifier(@Nullable PsiElement qualifier)
{
	if(qualifier == null)
	{
		return true;
	}
	final Condition<PsiElement> callExpressionCondition = Conditions.instanceOf(PsiCallExpression.class);
	final Condition<PsiElement> nonFinalFieldRefCondition = expression -> {
		if(expression instanceof PsiReferenceExpression)
		{
			PsiElement element = ((PsiReferenceExpression) expression).resolve();
			if(element instanceof PsiField && !((PsiField) element).hasModifierProperty(PsiModifier.FINAL))
			{
				return true;
			}
		}
		return false;
	};
	return SyntaxTraverser.psiTraverser().withRoot(qualifier).filter(Conditions.or(callExpressionCondition, nonFinalFieldRefCondition)).toList().isEmpty();
}
 
Example 17
Project: educational-plugin   File: EduCCModuleBuilder.java   Source Code and License 5 votes vote down vote up
@Nullable
@Override
public ModuleWizardStep modifySettingsStep(@NotNull SettingsStep settingsStep) {
  ModuleWizardStep javaSettingsStep =
    ProjectWizardStepFactory.getInstance().createJavaSettingsStep(settingsStep, this, Conditions.alwaysTrue());
  Function<JTextField, String> getValue = JTextComponent::getText;
  getWizardInputField("ccname", "", "Name:", myPanel.getNameField(), getValue).addToSettings(settingsStep);
  getWizardInputField("ccauthor", "", "Author:", myPanel.getAuthorField(), getValue).addToSettings(settingsStep);

  myLanguageComboBox.removeAllItems();
  for (LanguageExtensionPoint extension : Extensions.<LanguageExtensionPoint>getExtensions(EduPluginConfigurator.EP_NAME, null)) {
    String languageId = extension.getKey();
    Language language = Language.findLanguageByID(languageId);
    if (language == null) {
      LOG.info("Language with id " + languageId + " not found");
      continue;
    }
    myLanguageComboBox.addItem(new LanguageWrapper(language));
  }
  getWizardInputField("cclang", "", "Language:", myLanguageComboBox, comboBox -> (String) comboBox.getSelectedItem())
    .addToSettings(settingsStep);
  JTextArea descriptionField = myPanel.getDescriptionField();
  descriptionField.setRows(4);
  descriptionField.setBorder(null);
  descriptionField.invalidate();
  JBScrollPane scrollPane = new JBScrollPane(descriptionField);
  scrollPane.setMinimumSize(scrollPane.getUI().getPreferredSize(descriptionField));
  getWizardInputField("ccdescr", "", "Description:", scrollPane, pane -> descriptionField.getText()).addToSettings(settingsStep);
  return javaSettingsStep;
}
 
Example 18
Project: intellij-nette-tester   File: TesterTestCreator.java   Source Code and License 5 votes vote down vote up
@Nullable
static PhpClass findClass(PsiFile psiFile) {
    if (psiFile instanceof PhpFile) {
        PhpClass phpClass = PhpPsiUtil.findClass((PhpFile) psiFile, Conditions.alwaysTrue());
        if (phpClass != null && !TesterUtil.isTestClass(phpClass)) {
            return phpClass;
        }
    }

    return null;
}
 
Example 19
Project: intellij-ce-playground   File: JavaPsiFacadeImpl.java   Source Code and License 5 votes vote down vote up
private static Condition<PsiClass> getFilterFromFinders(@NotNull GlobalSearchScope scope, @NotNull PsiElementFinder[] finders) {
  Condition<PsiClass> filter = null;
  for (PsiElementFinder finder : finders) {
    Condition<PsiClass> finderFilter = finder.getClassesFilter(scope);
    if (finderFilter != null) {
      filter = filter == null ? finderFilter : Conditions.and(filter, finderFilter);
    }
  }
  return filter;
}
 
Example 20
Project: intellij-ce-playground   File: HighlightExceptionsHandlerFactory.java   Source Code and License 5 votes vote down vote up
@Nullable
private static HighlightUsagesHandlerBase createHighlightTryHandler(final Editor editor,
                                                                    final PsiFile file,
                                                                    final PsiElement target,
                                                                    final PsiElement parent) {
  final PsiTryStatement tryStatement = (PsiTryStatement)parent;
  FeatureUsageTracker.getInstance().triggerFeatureUsed("codeassists.highlight.throws");
  final PsiCodeBlock tryBlock = tryStatement.getTryBlock();
  if (tryBlock == null) return null;
  final Collection<PsiClassType> psiClassTypes = ExceptionUtil.collectUnhandledExceptions(tryBlock, tryBlock);
  return new HighlightExceptionsHandler(editor, file, target, psiClassTypes.toArray(new PsiClassType[psiClassTypes.size()]), tryBlock, Conditions.<PsiType>alwaysTrue());
}
 
Example 21
Project: intellij-ce-playground   File: HighlightExceptionsHandlerFactory.java   Source Code and License 5 votes vote down vote up
@Nullable
private static HighlightUsagesHandlerBase createThrowsHandler(final Editor editor, final PsiFile file, final PsiElement target) {
  FeatureUsageTracker.getInstance().triggerFeatureUsed("codeassists.highlight.throws");
  PsiElement grand = target.getParent().getParent();
  if (!(grand instanceof PsiMethod)) return null;
  PsiMethod method = (PsiMethod)grand;
  if (method.getBody() == null) return null;

  final Collection<PsiClassType> psiClassTypes = ExceptionUtil.collectUnhandledExceptions(method.getBody(), method.getBody());

  return new HighlightExceptionsHandler(editor, file, target, psiClassTypes.toArray(new PsiClassType[psiClassTypes.size()]), method.getBody(), Conditions.<PsiType>alwaysTrue());
}
 
Example 22
Project: intellij-ce-playground   File: TreeJavaClassChooserDialog.java   Source Code and License 5 votes vote down vote up
public InheritanceJavaClassFilterImpl(PsiClass base,
                                      boolean acceptsSelf,
                                      boolean acceptInner,
                                      @Nullable
                                      Condition<? super PsiClass> additionalCondition) {
  myAcceptsSelf = acceptsSelf;
  myAcceptsInner = acceptInner;
  if (additionalCondition == null) {
    additionalCondition = Conditions.alwaysTrue();
  }
  myAdditionalCondition = additionalCondition;
  myBase = base;
}
 
Example 23
Project: intellij-ce-playground   File: JdkComboBox.java   Source Code and License 5 votes vote down vote up
private static Condition<Sdk> getSdkFilter(@Nullable final Condition<SdkTypeId> filter) {
  return filter == null ? Conditions.<Sdk>alwaysTrue() : new Condition<Sdk>() {
    @Override
    public boolean value(Sdk sdk) {
      return filter.value(sdk.getSdkType());
    }
  };
}
 
Example 24
Project: intellij-ce-playground   File: TestValueNode.java   Source Code and License 5 votes vote down vote up
@NotNull
public Promise<Content> loadChildren(@NotNull XValue value) {
  TestCompositeNode childrenNode = new TestCompositeNode();
  value.computeChildren(childrenNode);
  return childrenNode.loadContent(Conditions.<XValueGroup>alwaysFalse(), Conditions.<VariableView>alwaysFalse())
    .done(new Consumer<Content>() {
      @Override
      public void consume(Content content) {
        children = content;
      }
    });
}
 
Example 25
Project: intellij-ce-playground   File: NettyUtil.java   Source Code and License 5 votes vote down vote up
@Nullable
public static Channel connect(@NotNull Bootstrap bootstrap, @NotNull InetSocketAddress remoteAddress, @Nullable AsyncPromise<?> promise, int maxAttemptCount, @Nullable Condition<Void> stopCondition) {
  try {
    return doConnect(bootstrap, remoteAddress, promise, maxAttemptCount, stopCondition == null ? Conditions.<Void>alwaysFalse() : stopCondition);
  }
  catch (Throwable e) {
    if (promise != null) {
      promise.setError(e);
    }
    return null;
  }
}
 
Example 26
Project: intellij-ce-playground   File: CommandProcessor.java   Source Code and License 5 votes vote down vote up
public FinalizableCommand takeNextCommand() {
  FinalizableCommand command = myList.remove(0);
  if (isEmpty()) {
    // memory leak otherwise
    myExpireCondition = Conditions.alwaysTrue();
  }
  return command;
}
 
Example 27
Project: intellij-ce-playground   File: LaterInvocatorTest.java   Source Code and License 5 votes vote down vote up
public void testExpired() throws Exception {
  UIUtil.invokeAndWaitIfNeeded(new Runnable() {
    @Override
    public void run() {
      final ArrayList<String> consumed = new ArrayList<>();
      synchronized (LaterInvocatorTest.this) {
        blockSwingThread();
        ApplicationManager.getApplication().getInvokator().invokeLater(new Runnable() {
          @Override
          public void run() {
            ApplicationManager.getApplication().invokeLater(new MyRunnable("1") {
              @Override
              public void run() {
                super.run();
                TestCase.fail("Should not be executed");
              }
            }, Conditions.alwaysTrue());
          }
        }, ModalityState.NON_MODAL).doWhenDone(() -> consumed.add("1"));
        ApplicationManager.getApplication().getInvokator().invokeLater(new MyRunnable("2"), ModalityState.NON_MODAL)
          .doWhenDone(() -> consumed.add("2"));
      }
      flushSwingQueue();

      TestCase.assertEquals(consumed.toString(), 2, consumed.size());
    }
  });
}
 
Example 28
Project: intellij-ce-playground   File: TransferToEDTQueue.java   Source Code and License 5 votes vote down vote up
public static TransferToEDTQueue<Runnable> createRunnableMerger(@NotNull @NonNls String name, int maxUnitOfWorkThresholdMs) {
  return new TransferToEDTQueue<Runnable>(name, new Processor<Runnable>() {
    @Override
    public boolean process(Runnable runnable) {
      runnable.run();
      return true;
    }
  }, Conditions.alwaysFalse(), maxUnitOfWorkThresholdMs);
}
 
Example 29
Project: intellij-ce-playground   File: PostfixLiveTemplate.java   Source Code and License 5 votes vote down vote up
private static Condition<PostfixTemplate> createIsApplicationTemplateFunction(@NotNull final PostfixTemplateProvider provider,
                                                                              @NotNull String key,
                                                                              @NotNull PsiFile file,
                                                                              @NotNull Editor editor) {
  int currentOffset = editor.getCaretModel().getOffset();
  final int newOffset = currentOffset - key.length();
  CharSequence fileContent = editor.getDocument().getCharsSequence();
  StringBuilder fileContentWithoutKey = new StringBuilder();
  fileContentWithoutKey.append(fileContent.subSequence(0, newOffset));
  fileContentWithoutKey.append(fileContent.subSequence(currentOffset, fileContent.length()));
  PsiFile copyFile = copyFile(file, fileContentWithoutKey);
  Document copyDocument = copyFile.getViewProvider().getDocument();
  if (copyDocument == null) {
    return Conditions.alwaysFalse();
  }

  copyFile = provider.preCheck(copyFile, editor, newOffset);
  copyDocument = copyFile.getViewProvider().getDocument();
  if (copyDocument == null) {
    return Conditions.alwaysFalse();
  }

  final PsiElement context = CustomTemplateCallback.getContext(copyFile, positiveOffset(newOffset));
  final Document finalCopyDocument = copyDocument;
  return new Condition<PostfixTemplate>() {
    @Override
    public boolean value(PostfixTemplate template) {
      return template != null && template.isEnabled(provider) && template.isApplicable(context, finalCopyDocument, newOffset);
    }
  };
}
 
Example 30
Project: intellij-ce-playground   File: ConsoleExecuteAction.java   Source Code and License 5 votes vote down vote up
public ConsoleExecuteAction(@NotNull LanguageConsoleView consoleView,
                             @NotNull ConsoleExecuteActionHandler executeActionHandler,
                             @NotNull String emptyExecuteActionId,
                             @Nullable Condition<LanguageConsoleView> enabledCondition) {
  super(null, null, AllIcons.Actions.Execute);

  myConsoleView = consoleView;
  myExecuteActionHandler = executeActionHandler;
  myEnabledCondition = enabledCondition == null ? Conditions.<LanguageConsoleView>alwaysTrue() : enabledCondition;

  EmptyAction.setupAction(this, emptyExecuteActionId, null);
}
 
Example 31
Project: intellij-ce-playground   File: FindInProjectTask.java   Source Code and License 5 votes vote down vote up
FindInProjectTask(@NotNull final FindModel findModel, @NotNull final Project project) {
  myFindModel = findModel;
  myProject = project;
  myDirectory = FindInProjectUtil.getDirectory(findModel);
  myPsiManager = PsiManager.getInstance(project);

  final String moduleName = findModel.getModuleName();
  myModule = moduleName == null ? null : ApplicationManager.getApplication().runReadAction(new Computable<Module>() {
    @Override
    public Module compute() {
      return ModuleManager.getInstance(project).findModuleByName(moduleName);
    }
  });
  myProjectFileIndex = ProjectRootManager.getInstance(project).getFileIndex();
  myFileIndex = myModule == null ? myProjectFileIndex : ModuleRootManager.getInstance(myModule).getFileIndex();

  final String filter = findModel.getFileFilter();
  final Pattern pattern = FindInProjectUtil.createFileMaskRegExp(filter);

  myFileMask = pattern == null ? Conditions.<VirtualFile>alwaysTrue() : new Condition<VirtualFile>() {
    @Override
    public boolean value(VirtualFile file) {
      return file != null && pattern.matcher(file.getName()).matches();
    }
  };

  final ProgressIndicator progress = ProgressManager.getInstance().getProgressIndicator();
  myProgress = progress != null ? progress : new EmptyProgressIndicator();
}
 
Example 32
Project: intellij-ce-playground   File: PyClassNameCompletionContributor.java   Source Code and License 5 votes vote down vote up
@Override
public void fillCompletionVariants(@NotNull CompletionParameters parameters, @NotNull CompletionResultSet result) {
  if (parameters.isExtendedCompletion()) {
    final PsiElement element = parameters.getPosition();
    final PsiElement parent = element.getParent();
    if (parent instanceof PyReferenceExpression && ((PyReferenceExpression)parent).isQualified()) {
      return;
    }
    if (parent instanceof PyStringLiteralExpression) {
      String prefix = parent.getText().substring(0, parameters.getOffset() - parent.getTextRange().getStartOffset());
      if (prefix.contains(".")) {
        return;
      }
    }
    final FileViewProvider provider = element.getContainingFile().getViewProvider();
    if (provider instanceof MultiplePsiFilesPerDocumentFileViewProvider) return;
    if (PsiTreeUtil.getParentOfType(element, PyImportStatementBase.class) != null) {
      return;
    }
    final PsiFile originalFile = parameters.getOriginalFile();
    addVariantsFromIndex(result, originalFile, PyClassNameIndex.KEY,
                         parent instanceof PyStringLiteralExpression ? STRING_LITERAL_INSERT_HANDLER : IMPORTING_INSERT_HANDLER,
                         Conditions.<PyClass>alwaysTrue(), PyClass.class);
    addVariantsFromIndex(result, originalFile, PyFunctionNameIndex.KEY,
                         getFunctionInsertHandler(parent), IS_TOPLEVEL, PyFunction.class);
    addVariantsFromIndex(result, originalFile, PyVariableNameIndex.KEY,
                         parent instanceof PyStringLiteralExpression ? STRING_LITERAL_INSERT_HANDLER : IMPORTING_INSERT_HANDLER,
                         IS_TOPLEVEL, PyTargetExpression.class);
    addVariantsFromModules(result, originalFile, parent instanceof PyStringLiteralExpression);
  }
}
 
Example 33
Project: consulo-nodejs   File: NodeJSNewModuleBuilderPanel.java   Source Code and License 5 votes vote down vote up
public NodeJSNewModuleBuilderPanel()
{
	super(new VerticalFlowLayout());

	ProjectSdksModel model = new ProjectSdksModel();
	model.reset();

	myComboBox = new SdkComboBox(model, Conditions.equalTo(NodeJSBundleType.getInstance()), false);

	add(LabeledComponent.create(myComboBox, "Bundle").setLabelLocation(BorderLayout.WEST));
}
 
Example 34
Project: tools-idea   File: TreeJavaClassChooserDialog.java   Source Code and License 5 votes vote down vote up
public InheritanceJavaClassFilterImpl(PsiClass base,
                                      boolean acceptsSelf,
                                      boolean acceptInner,
                                      Condition<? super PsiClass> additionalCondition) {
  myAcceptsSelf = acceptsSelf;
  myAcceptsInner = acceptInner;
  if (additionalCondition == null) {
    additionalCondition = Conditions.alwaysTrue();
  }
  myAdditionalCondition = additionalCondition;
  myBase = base;
}
 
Example 35
Project: tools-idea   File: JdkComboBox.java   Source Code and License 5 votes vote down vote up
private static Condition<Sdk> getSdkFilter(@Nullable final Condition<SdkTypeId> filter) {
  return filter == null ? Conditions.<Sdk>alwaysTrue() : new Condition<Sdk>() {
    @Override
    public boolean value(Sdk sdk) {
      return filter.value(sdk.getSdkType());
    }
  };
}
 
Example 36
Project: consulo-csharp   File: UsingNamespaceFix.java   Source Code and License 5 votes vote down vote up
@RequiredReadAction
private static void collectAvailableNamespaces(final CSharpReferenceExpression ref, Set<NamespaceReference> set, String referenceName)
{
	if(ref.getQualifier() != null)
	{
		return;
	}
	Collection<DotNetTypeDeclaration> tempTypes;
	Collection<DotNetLikeMethodDeclaration> tempMethods;

	PsiElement parent = ref.getParent();
	if(parent instanceof CSharpAttribute)
	{
		final Condition<DotNetTypeDeclaration> cond = typeDeclaration -> DotNetInheritUtil.isAttribute(typeDeclaration);

		tempTypes = getTypesWithGeneric(ref, referenceName);
		collect(set, tempTypes, cond);

		tempTypes = getTypesWithGeneric(ref, referenceName + AttributeByNameSelector.AttributeSuffix);
		collect(set, tempTypes, cond);
	}
	else
	{
		tempTypes = getTypesWithGeneric(ref, referenceName);

		collect(set, tempTypes, Conditions.<DotNetTypeDeclaration>alwaysTrue());

		tempMethods = MethodIndex.getInstance().get(referenceName, ref.getProject(), ref.getResolveScope());

		collect(set, tempMethods, method -> (method.getParent() instanceof DotNetNamespaceDeclaration || method.getParent() instanceof PsiFile) && method instanceof CSharpMethodDeclaration && (
				(CSharpMethodDeclaration) method).isDelegate());
	}
}
 
Example 37
Project: consulo-dotnet   File: TypeInheritorsSearch.java   Source Code and License 5 votes vote down vote up
public SearchParameters(Project project,
		@NotNull final String aClassQName,
		@NotNull SearchScope scope,
		final boolean checkDeep,
		final boolean checkInheritance,
		Function<DotNetTypeDeclaration, DotNetTypeDeclaration> transformer)
{
	this(project, aClassQName, scope, checkDeep, checkInheritance, Conditions.<String>alwaysTrue(), transformer);
}
 
Example 38
Project: consulo   File: CommandProcessorBase.java   Source Code and License 5 votes vote down vote up
public FinalizableCommand takeNextCommand() {
  FinalizableCommand command = myList.remove(0);
  if (isEmpty()) {
    // memory leak otherwise
    myExpireCondition = Conditions.alwaysTrue();
  }
  return command;
}
 
Example 39
Project: consulo   File: LaterInvocator.java   Source Code and License 5 votes vote down vote up
static void invokeAndWait(@Nonnull final Runnable runnable, @Nonnull ModalityState modalityState) {
  LOG.assertTrue(!isDispatchThread());

  final Semaphore semaphore = new Semaphore();
  semaphore.down();
  final Ref<Throwable> exception = Ref.create();
  Runnable runnable1 = new Runnable() {
    @Override
    public void run() {
      try {
        runnable.run();
      }
      catch (Throwable e) {
        exception.set(e);
      }
      finally {
        semaphore.up();
      }
    }

    @Override
    @NonNls
    public String toString() {
      return "InvokeAndWait[" + runnable + "]";
    }
  };
  invokeLaterWithCallback(runnable1, modalityState, Conditions.FALSE, null);
  semaphore.waitFor();
  if (!exception.isNull()) {
    Throwable cause = exception.get();
    if (SystemPropertyUtil.getBoolean("invoke.later.wrap.error", true)) {
      // wrap everything to keep the current thread stacktrace
      // also TC ComparisonFailure feature depends on this
      throw new RuntimeException(cause);
    }
    else {
      ExceptionUtil.rethrow(cause);
    }
  }
}
 
Example 40
Project: consulo   File: TransferToEDTQueue.java   Source Code and License 5 votes vote down vote up
public static TransferToEDTQueue<Runnable> createRunnableMerger(@Nonnull @NonNls String name, int maxUnitOfWorkThresholdMs) {
  return new TransferToEDTQueue<Runnable>(name, new Processor<Runnable>() {
    @Override
    public boolean process(Runnable runnable) {
      runnable.run();
      return true;
    }
  }, Conditions.alwaysFalse(), maxUnitOfWorkThresholdMs);
}
 
Example 41
Project: consulo   File: SdkComboBox.java   Source Code and License 5 votes vote down vote up
private static Condition<Sdk> getSdkFilter(@Nullable final Condition<SdkTypeId> filter) {
  return filter == null ? Conditions.<Sdk>alwaysTrue() : new Condition<Sdk>() {
    @Override
    public boolean value(Sdk sdk) {
      return filter.value(sdk.getSdkType());
    }
  };
}
 
Example 42
Project: consulo   File: BraceHighlightingHandler.java   Source Code and License 5 votes vote down vote up
@Nonnull
static EditorHighlighter getLazyParsableHighlighterIfAny(Project project, Editor editor, PsiFile psiFile) {
  if (!PsiDocumentManager.getInstance(project).isCommitted(editor.getDocument())) {
    return ((EditorEx)editor).getHighlighter();
  }
  PsiElement elementAt = psiFile.findElementAt(editor.getCaretModel().getOffset());
  for (PsiElement e : SyntaxTraverser.psiApi().parents(elementAt).takeWhile(Conditions.notEqualTo(psiFile))) {
    if (!(PsiUtilCore.getElementType(e) instanceof ILazyParseableElementType)) continue;
    Language language = ILazyParseableElementType.LANGUAGE_KEY.get(e.getNode());
    if (language == null) continue;
    TextRange range = e.getTextRange();
    final int offset = range.getStartOffset();
    SyntaxHighlighter syntaxHighlighter =
            SyntaxHighlighterFactory.getSyntaxHighlighter(language, project, psiFile.getVirtualFile());
    LexerEditorHighlighter highlighter = new LexerEditorHighlighter(syntaxHighlighter, editor.getColorsScheme()) {
      @Nonnull
      @Override
      public HighlighterIterator createIterator(int startOffset) {
        return new HighlighterIteratorWrapper(super.createIterator(Math.max(startOffset - offset, 0))) {
          @Override
          public int getStart() {
            return super.getStart() + offset;
          }

          @Override
          public int getEnd() {
            return super.getEnd() + offset;
          }
        };
      }
    };
    highlighter.setText(editor.getDocument().getText(range));
    return highlighter;
  }
  return ((EditorEx)editor).getHighlighter();
}
 
Example 43
Project: consulo   File: ReformatCodeAction.java   Source Code and License 5 votes vote down vote up
private static Condition<CharSequence> getFileTypeMaskPattern(@Nullable String mask) {
  try {
    return FindInProjectUtil.createFileMaskCondition(mask);
  } catch (PatternSyntaxException e) {
    LOG.info("Error while processing file mask: ", e);
    return Conditions.alwaysTrue();
  }
}
 
Example 44
Project: consulo   File: ConsoleExecuteAction.java   Source Code and License 5 votes vote down vote up
public ConsoleExecuteAction(@Nonnull LanguageConsoleView consoleView,
                            @Nonnull ConsoleExecuteActionHandler executeActionHandler,
                            @Nonnull String emptyExecuteActionId,
                            @Nullable Condition<LanguageConsoleView> enabledCondition) {
  super(null, null, AllIcons.Actions.Execute);

  myConsoleView = consoleView;
  myExecuteActionHandler = executeActionHandler;
  myEnabledCondition = enabledCondition == null ? Conditions.<LanguageConsoleView>alwaysTrue() : enabledCondition;

  EmptyAction.setupAction(this, emptyExecuteActionId, null);
}
 
Example 45
Project: consulo   File: FindInProjectUtil.java   Source Code and License 5 votes vote down vote up
@Nonnull
public static Condition<CharSequence> createFileMaskCondition(@Nullable String filter) throws PatternSyntaxException {
  if (filter == null) {
    return Conditions.alwaysTrue();
  }

  String pattern = "";
  String negativePattern = "";
  final List<String> masks = StringUtil.split(filter, ",");

  for (String mask : masks) {
    mask = mask.trim();
    if (StringUtil.startsWith(mask, "!")) {
      negativePattern += (negativePattern.isEmpty() ? "" : "|") + "(" + PatternUtil.convertToRegex(mask.substring(1)) + ")";
    }
    else {
      pattern += (pattern.isEmpty() ? "" : "|") + "(" + PatternUtil.convertToRegex(mask) + ")";
    }
  }

  if (pattern.isEmpty()) pattern = PatternUtil.convertToRegex("*");
  final String finalPattern = pattern;
  final String finalNegativePattern = negativePattern;

  return new Condition<CharSequence>() {
    final Pattern regExp = Pattern.compile(finalPattern, Pattern.CASE_INSENSITIVE);
    final Pattern negativeRegExp = StringUtil.isEmpty(finalNegativePattern) ? null : Pattern.compile(finalNegativePattern, Pattern.CASE_INSENSITIVE);

    @Override
    public boolean value(CharSequence input) {
      return regExp.matcher(input).matches() && (negativeRegExp == null || !negativeRegExp.matcher(input).matches());
    }
  };
}
 
Example 46
Project: consulo   File: LogFilesManager.java   Source Code and License 5 votes vote down vote up
public void addLogConsoles(@Nonnull RunConfigurationBase runConfiguration, @Nullable ProcessHandler startedProcess) {
  for (LogFileOptions logFileOptions : runConfiguration.getAllLogFiles()) {
    if (logFileOptions.isEnabled()) {
      addConfigurationConsoles(logFileOptions, Conditions.<String>alwaysTrue(), logFileOptions.getPaths(), runConfiguration);
    }
  }
  runConfiguration.createAdditionalTabComponents(myManager, startedProcess);
}
 
Example 47
Project: consulo-java   File: JavaNewModuleBuilderPanel.java   Source Code and License 5 votes vote down vote up
public JavaNewModuleBuilderPanel()
{
	super(new VerticalFlowLayout());

	ProjectSdksModel sdksModel = new ProjectSdksModel();
	sdksModel.reset();

	myComboBox = new SdkComboBox(sdksModel, Conditions.instanceOf(JavaSdk.class), false);

	add(LabeledComponent.create(myComboBox, "JDK").setLabelLocation(BorderLayout.WEST));
}
 
Example 48
Project: consulo-java   File: JavaDocCompletionContributor.java   Source Code and License 5 votes vote down vote up
@NotNull
private List<LookupElement> completeJavadocReference(PsiElement position, PsiJavaReference ref)
{
	JavaCompletionProcessor processor = new JavaCompletionProcessor(position, TrueFilter.INSTANCE, JavaCompletionProcessor.Options.CHECK_NOTHING, Conditions.alwaysTrue());
	ref.processVariants(processor);
	return ContainerUtil.map(processor.getResults(), (completionResult) ->
	{
		LookupElement item = createReferenceLookupItem(completionResult.getElement());
		item.putUserData(JavaCompletionUtil.FORCE_SHOW_SIGNATURE_ATTR, Boolean.TRUE);
		return item;
	});
}
 
Example 49
Project: consulo-java   File: TreeJavaClassChooserDialog.java   Source Code and License 5 votes vote down vote up
public InheritanceJavaClassFilterImpl(PsiClass base,
                                      boolean acceptsSelf,
                                      boolean acceptInner,
                                      Condition<? super PsiClass> additionalCondition) {
  myAcceptsSelf = acceptsSelf;
  myAcceptsInner = acceptInner;
  if (additionalCondition == null) {
    additionalCondition = Conditions.alwaysTrue();
  }
  myAdditionalCondition = additionalCondition;
  myBase = base;
}
 
Example 50
Project: educational-plugin   File: EduCustomCourseModuleBuilder.java   Source Code and License 4 votes vote down vote up
@Nullable
@Override
public ModuleWizardStep modifySettingsStep(@NotNull SettingsStep settingsStep) {
  return ProjectWizardStepFactory.getInstance().createJavaSettingsStep(settingsStep, this, Conditions.alwaysTrue());
}
 
Example 51
Project: educational-plugin   File: EduKotlinKoansModuleBuilder.java   Source Code and License 4 votes vote down vote up
@Nullable
@Override
public ModuleWizardStep modifySettingsStep(@NotNull SettingsStep settingsStep) {
  return ProjectWizardStepFactory.getInstance().createJavaSettingsStep(settingsStep, this, Conditions.alwaysTrue());
}
 
Example 52
Project: intellij-ce-playground   File: ArtifactCompilerInstructionCreatorBase.java   Source Code and License 4 votes vote down vote up
@Override
public void addExtractDirectoryInstruction(@NotNull File jarFile, @NotNull String pathInJar) {
  addExtractDirectoryInstruction(jarFile, pathInJar, Conditions.<String>alwaysTrue());
}
 
Example 53
Project: intellij-ce-playground   File: AllClassesSearch.java   Source Code and License 4 votes vote down vote up
public SearchParameters(@NotNull SearchScope scope, @NotNull Project project) {
  this(scope, project, Conditions.<String>alwaysTrue());
}
 
Example 54
Project: intellij-ce-playground   File: ClassInheritorsSearch.java   Source Code and License 4 votes vote down vote up
public SearchParameters(@NotNull final PsiClass aClass, @NotNull SearchScope scope, final boolean checkDeep, final boolean checkInheritance, boolean includeAnonymous) {
  this(aClass, scope, checkDeep, checkInheritance, includeAnonymous, Conditions.<String>alwaysTrue());
}
 
Example 55
Project: intellij-ce-playground   File: JavaPostfixTemplatesUtils.java   Source Code and License 4 votes vote down vote up
public static PostfixTemplateExpressionSelector selectorTopmost() {
  return selectorTopmost(Conditions.<PsiElement>alwaysTrue());
}
 
Example 56
Project: intellij-ce-playground   File: JavaPostfixTemplatesUtils.java   Source Code and License 4 votes vote down vote up
public static PostfixTemplateExpressionSelector selectorAllExpressionsWithCurrentOffset() {
  return selectorAllExpressionsWithCurrentOffset(Conditions.<PsiElement>alwaysTrue());
}
 
Example 57
Project: intellij-ce-playground   File: MasterDetailsComponent.java   Source Code and License 4 votes vote down vote up
public MyDeleteAction() {
  this(Conditions.<Object[]>alwaysTrue());
}
 
Example 58
Project: intellij-ce-playground   File: Tree.java   Source Code and License 4 votes vote down vote up
/**
 * @return    a strategy which determines if a wide selection should be drawn for a target row (it's number is
 *            {@link Condition#value(Object) given} as an argument to the strategy)
 */
@SuppressWarnings("unchecked")
@NotNull
protected Condition<Integer> getWideSelectionBackgroundCondition() {
  return Conditions.alwaysTrue();
}
 
Example 59
Project: intellij-ce-playground   File: QueueProcessor.java   Source Code and License 4 votes vote down vote up
/**
 * Constructs a QueueProcessor, which will autostart as soon as the first element is added to it.
 */
public QueueProcessor(@NotNull Consumer<T> processor) {
  this(processor, Conditions.alwaysFalse());
}
 
Example 60
Project: intellij-ce-playground   File: QueueProcessor.java   Source Code and License 4 votes vote down vote up
@NotNull
public static QueueProcessor<Runnable> createRunnableQueueProcessor(ThreadToUse threadToUse) {
  return new QueueProcessor<Runnable>(wrappingProcessor(new RunnableConsumer()), true, threadToUse, Conditions.FALSE);
}