Java Code Examples for com.intellij.util.ObjectUtils#tryCast()

The following examples show how to use com.intellij.util.ObjectUtils#tryCast() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: PhpHighlightPackParametersUsagesHandlerFactory.java    From idea-php-advanced-autocomplete with MIT License 6 votes vote down vote up
@Override
public @Nullable HighlightUsagesHandlerBase createHighlightUsagesHandler(@NotNull Editor editor, @NotNull PsiFile file, @NotNull PsiElement target) {

    ParameterList parameterList = PhpPsiUtil.getParentByCondition(target, true, ParameterList.INSTANCEOF, Statement.INSTANCEOF);
    if (parameterList == null) {
        return null;
    }

    FunctionReference functionCall = ObjectUtils.tryCast(parameterList.getParent(), FunctionReference.class);
    String fqn = resolveFqn(functionCall);
    if (!"\\pack".equals(fqn)) {
        return null;
    }

    PsiElement[] parameters = parameterList.getParameters();
    PsiElement selectedParameter = StreamEx.of(parameters).findFirst((p) -> p.getTextRange().containsOffset(editor.getCaretModel().getOffset())).orElse(null);
    if (selectedParameter == null) {
        return null;
    }

    int selectedIndex = PhpCodeInsightUtil.getParameterIndex(selectedParameter);
    if (selectedIndex < 0 || selectedIndex >= parameters.length) {
        return null;
    }
    return new PhpHighlightPackParametersUsagesHandler(editor, file, 0, selectedIndex, parameters);
}
 
Example 2
Source File: PopupFactoryImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
protected void handleToggleAction() {
  final Object[] selectedValues = getList().getSelectedValues();

  ListPopupStep<Object> listStep = getListStep();
  final ActionPopupStep actionPopupStep = ObjectUtils.tryCast(listStep, ActionPopupStep.class);
  if (actionPopupStep == null) return;

  List<ToggleAction> filtered = ContainerUtil.mapNotNull(selectedValues, o -> getActionByClass(o, actionPopupStep, ToggleAction.class));

  for (ToggleAction action : filtered) {
    actionPopupStep.performAction(action, 0);
  }

  for (ActionItem item : actionPopupStep.getValues()) {
    updateActionItem(item);
  }

  getList().repaint();
}
 
Example 3
Source File: ContainerBuilderStubIndex.java    From idea-php-symfony2-plugin with MIT License 6 votes vote down vote up
@Override
public boolean processAccessVariableInstruction(PhpAccessVariableInstruction instruction) {
    if (instruction.getAccess().isWrite() || instruction.getAccess().isWriteRef() ||
            !containerParameters.contains(instruction.getVariableName())) return true;
    
    MethodReference methodReference = 
            ObjectUtils.tryCast(instruction.getAnchor().getParent(), MethodReference.class);
    if (methodReference == null || !METHODS.contains(methodReference.getName())) return true;
    
    String value = PhpElementsUtil.getFirstArgumentStringValue(methodReference);
    if (value == null) return true;
    
    String methodName = methodReference.getName();
    map.computeIfAbsent(methodName, name -> new ContainerBuilderCall());
    map.get(methodName).addParameter(value);
    
    return true;
}
 
Example 4
Source File: StatusText.java    From consulo with Apache License 2.0 6 votes vote down vote up
private void paintOnComponentUnderViewport(Component component, Graphics g) {
  JBViewport viewport = ObjectUtils.tryCast(myOwner, JBViewport.class);
  if (viewport == null || viewport.getView() != component || viewport.isPaintingNow()) return;

  // We're painting a component which has a viewport as it's ancestor.
  // As the viewport paints status text, we'll erase it, so we need to schedule a repaint for the viewport with status text's bounds.
  // But it causes flicker, so we paint status text over the component first and then schedule the viewport repaint.

  Rectangle textBoundsInViewport = getTextComponentBound();

  int xInOwner = textBoundsInViewport.x - component.getX();
  int yInOwner = textBoundsInViewport.y - component.getY();
  Rectangle textBoundsInOwner = new Rectangle(xInOwner, yInOwner, textBoundsInViewport.width, textBoundsInViewport.height);
  doPaintStatusText(g, textBoundsInOwner);

  viewport.repaint(textBoundsInViewport);
}
 
Example 5
Source File: CheckBoxList.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
private static Dimension getCheckBoxDimension(@Nonnull JCheckBox checkBox) {
  Icon icon = null;
  BasicRadioButtonUI ui = ObjectUtils.tryCast(checkBox.getUI(), BasicRadioButtonUI.class);
  if (ui != null) {
    icon = ui.getDefaultIcon();
  }
  if (icon == null) {
    // com.intellij.ide.ui.laf.darcula.ui.DarculaCheckBoxUI.getDefaultIcon()
    icon = JBUI.scale(EmptyIcon.create(20));
  }
  Insets margin = checkBox.getMargin();
  return new Dimension(margin.left + icon.getIconWidth(), margin.top + icon.getIconHeight());
}
 
Example 6
Source File: AnnotationPresentation.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public List<AnAction> getActions(int line) {
  int correctedNumber = myUpToDateLineNumberProvider.getLineNumber(line);
  for (AnAction action : myActions) {
    UpToDateLineNumberListener upToDateListener = ObjectUtils.tryCast(action, UpToDateLineNumberListener.class);
    if (upToDateListener != null) upToDateListener.consume(correctedNumber);

    LineNumberListener listener = ObjectUtils.tryCast(action, LineNumberListener.class);
    if (listener != null) listener.consume(line);
  }

  return myActions;
}
 
Example 7
Source File: RunIdeConsoleAction.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public void write(char[] cbuf, int off, int len) throws IOException {
  RunContentDescriptor descriptor = myDescriptor.get();
  ConsoleViewImpl console = ObjectUtils.tryCast(descriptor != null ? descriptor.getExecutionConsole() : null, ConsoleViewImpl.class);
  if (console == null) {
    //TODO ignore ?
    throw new IOException("The console is not available.");
  }
  console.print(new String(cbuf, off, len), myOutputType);
}
 
Example 8
Source File: YamlHelper.java    From idea-php-symfony2-plugin with MIT License 5 votes vote down vote up
/**
 * Try to find a valid indent value, which are spaces which we need to fill
 */
public static int getIndentSpaceForFile(@NotNull YAMLFile yamlFile) {
    List<YAMLDocument> documents = yamlFile.getDocuments();

    YAMLMapping mapping = ObjectUtils.tryCast(documents.get(0).getTopLevelValue(), YAMLMapping.class);
    if(mapping != null) {
        // first first INDENT element in mapping
        PsiElementPattern.Capture<PsiElement> pattern = PlatformPatterns
            .psiElement(YAMLTokenTypes.INDENT)
            .with(new PsiElementPatternCondition());

        for (YAMLPsiElement yamlPsiElement : mapping.getKeyValues()) {
            // get first value
            PsiElement firstChild = yamlPsiElement.getFirstChild();
            if(firstChild == null) {
                continue;
            }

            // first valid INDENT
            PsiElement nextSiblingOfType = PsiElementUtils.getNextSiblingOfType(firstChild, pattern);
            if(nextSiblingOfType != null && nextSiblingOfType.getTextLength() > 0) {
                return nextSiblingOfType.getTextLength();
            }
        }
    }

    // default value
    return 4;
}
 
Example 9
Source File: EventAnnotationStubIndex.java    From idea-php-symfony2-plugin with MIT License 5 votes vote down vote up
private void visitPhpDocTag(PhpDocTag element) {
    String name = StringUtils.stripStart(element.getName(), "@");
    if(!"Event".equalsIgnoreCase(name)) {
        return;
    }

    PhpDocComment phpDocComment = ObjectUtils.tryCast(element.getParent(), PhpDocComment.class);
    if(phpDocComment == null) {
        return;
    }

    PhpPsiElement nextPsiSibling = phpDocComment.getNextPsiSibling();
    if(nextPsiSibling == null || nextPsiSibling.getNode().getElementType() != PhpElementTypes.CLASS_CONSTANTS) {
        return;
    }

    ClassConstImpl childOfAnyType = PsiTreeUtil.findChildOfAnyType(nextPsiSibling, ClassConstImpl.class);
    if(childOfAnyType == null) {
        return;
    }

    PsiElement defaultValue = childOfAnyType.getDefaultValue();
    if(!(defaultValue instanceof StringLiteralExpression)) {
        return;
    }

    String contents = ((StringLiteralExpression) defaultValue).getContents();

    String fqn = StringUtils.stripStart(childOfAnyType.getFQN(), "\\");

    map.put(contents, new DispatcherEvent(
        fqn,
        findClassInstance(phpDocComment, element))
    );
}
 
Example 10
Source File: ChangesBrowserBase.java    From consulo with Apache License 2.0 5 votes vote down vote up
public void setSelected(AnActionEvent e, boolean state) {
  T change = ObjectUtils.tryCast(e.getData(VcsDataKeys.CURRENT_CHANGE), myClass);
  if (change == null) return;

  if (state) {
    myViewer.includeChange(change);
  }
  else {
    myViewer.excludeChange(change);
  }
}
 
Example 11
Source File: ESLintConfigFileUtil.java    From eslint-plugin with MIT License 5 votes vote down vote up
@Nullable
public static JSProperty getProperty(@NotNull PsiElement position) {
    JSProperty property = PsiTreeUtil.getParentOfType(position, JSProperty.class, false);
    if (property != null) {
        JSObjectLiteralExpression objectLiteralExpression = ObjectUtils.tryCast(property.getParent(), JSObjectLiteralExpression.class);
        if (objectLiteralExpression != null) {
            return property;
        }
    }
    return null;
}
 
Example 12
Source File: HookSubscriberUtil.java    From idea-php-shopware-plugin with MIT License 5 votes vote down vote up
public static void visitSubscriberEvents(@NotNull PhpReturn phpReturn, @NotNull SubscriberEventsVisitor visitor) {
    ArrayCreationExpression arrayCreationExpression = ObjectUtils.tryCast(phpReturn.getArgument(), ArrayCreationExpression.class);
    if(arrayCreationExpression == null) {
        return;
    }

    for (ArrayHashElement entry : arrayCreationExpression.getHashElements()) {
        StringLiteralExpression keyString = ObjectUtils.tryCast(entry.getKey(), StringLiteralExpression.class);
        if(keyString == null) {
            continue;
        }

        String fullEvent = keyString.getContents();
        if(StringUtils.isBlank(fullEvent)) {
            continue;
        }

        PhpPsiElement value = entry.getValue();
        if(value == null) {
            continue;
        }

        String methodName = SubscriberIndexUtil.getMethodNameForEventValue(value);
        if(methodName == null || StringUtils.isBlank(methodName)) {
            continue;
        }

        visitor.visit(fullEvent, methodName, keyString);
    }
}
 
Example 13
Source File: RTFileUtil.java    From react-templates-plugin with MIT License 5 votes vote down vote up
@Nullable
public static JSProperty getProperty(@NotNull PsiElement position) {
    JSProperty property = PsiTreeUtil.getParentOfType(position, JSProperty.class, false);
    if (property != null) {
        JSObjectLiteralExpression objectLiteralExpression = ObjectUtils.tryCast(property.getParent(), JSObjectLiteralExpression.class);
        if (objectLiteralExpression != null) {
            return property;
        }
    }
    return null;
}
 
Example 14
Source File: RTFileUtil.java    From react-templates-plugin with MIT License 5 votes vote down vote up
@Nullable
public static JSProperty getProperty(@NotNull PsiElement position) {
    JSProperty property = PsiTreeUtil.getParentOfType(position, JSProperty.class, false);
    if (property != null) {
        JSObjectLiteralExpression objectLiteralExpression = ObjectUtils.tryCast(property.getParent(), JSObjectLiteralExpression.class);
        if (objectLiteralExpression != null) {
            return property;
        }
    }
    return null;
}
 
Example 15
Source File: ChangesBrowserBase.java    From consulo with Apache License 2.0 5 votes vote down vote up
public void calcData(Key<?> key, DataSink sink) {
  if (key == VcsDataKeys.CHANGES) {
    List<Change> list = getSelectedChanges();
    if (list.isEmpty()) list = getAllChanges();
    sink.put(VcsDataKeys.CHANGES, list.toArray(new Change[list.size()]));
  }
  else if (key == VcsDataKeys.CHANGES_SELECTION) {
    sink.put(VcsDataKeys.CHANGES_SELECTION, getChangesSelection());
  }
  else if (key == VcsDataKeys.CHANGE_LISTS) {
    sink.put(VcsDataKeys.CHANGE_LISTS, getSelectedChangeLists());
  }
  else if (key == VcsDataKeys.CHANGE_LEAD_SELECTION) {
    final Change highestSelection = ObjectUtils.tryCast(myViewer.getHighestLeadSelection(), Change.class);
    sink.put(VcsDataKeys.CHANGE_LEAD_SELECTION, (highestSelection == null) ? new Change[]{} : new Change[]{highestSelection});
  }
  else if (key == CommonDataKeys.VIRTUAL_FILE_ARRAY) {
    sink.put(CommonDataKeys.VIRTUAL_FILE_ARRAY, getSelectedFiles().toArray(VirtualFile[]::new));
  }
  else if (key == CommonDataKeys.NAVIGATABLE_ARRAY) {
    sink.put(CommonDataKeys.NAVIGATABLE_ARRAY, getNavigatableArray(myProject, getSelectedFiles()));
  }
  else if (VcsDataKeys.IO_FILE_ARRAY.equals(key)) {
    sink.put(VcsDataKeys.IO_FILE_ARRAY, getSelectedIoFiles());
  }
  else if (key == DATA_KEY) {
    sink.put(DATA_KEY, this);
  }
  else if (VcsDataKeys.SELECTED_CHANGES_IN_DETAILS.equals(key)) {
    final List<Change> selectedChanges = getSelectedChanges();
    sink.put(VcsDataKeys.SELECTED_CHANGES_IN_DETAILS, selectedChanges.toArray(new Change[selectedChanges.size()]));
  }
  else if (UNVERSIONED_FILES_DATA_KEY.equals(key)) {
    sink.put(UNVERSIONED_FILES_DATA_KEY, getVirtualFiles(myViewer.getSelectionPaths(), UNVERSIONED_FILES_TAG));
  }
  else if (PlatformDataKeys.DELETE_ELEMENT_PROVIDER.equals(key)) {
    sink.put(PlatformDataKeys.DELETE_ELEMENT_PROVIDER, myDeleteProvider);
  }
}
 
Example 16
Source File: RunIdeConsoleAction.java    From consulo with Apache License 2.0 5 votes vote down vote up
private static void ensureOutputIsRedirected(@Nonnull IdeScriptEngine engine, @Nonnull RunContentDescriptor descriptor) {
  ConsoleWriter stdOutWriter = ObjectUtils.tryCast(engine.getStdOut(), ConsoleWriter.class);
  ConsoleWriter stdErrWriter = ObjectUtils.tryCast(engine.getStdErr(), ConsoleWriter.class);
  if (stdOutWriter != null && stdOutWriter.getDescriptor() == descriptor &&
      stdErrWriter != null && stdErrWriter.getDescriptor() == descriptor) {
    return;
  }

  WeakReference<RunContentDescriptor> ref = new WeakReference<>(descriptor);
  engine.setStdOut(new ConsoleWriter(ref, ConsoleViewContentType.NORMAL_OUTPUT));
  engine.setStdErr(new ConsoleWriter(ref, ConsoleViewContentType.ERROR_OUTPUT));
}
 
Example 17
Source File: AbstractProjectViewPane.java    From consulo with Apache License 2.0 4 votes vote down vote up
/**
 * @see TreeUtil#getUserObject(Object)
 * @deprecated AbstractProjectViewPane#getSelectedPath
 */
@Deprecated
public final DefaultMutableTreeNode getSelectedNode() {
  TreePath path = getSelectedPath();
  return path == null ? null : ObjectUtils.tryCast(path.getLastPathComponent(), DefaultMutableTreeNode.class);
}
 
Example 18
Source File: InstalledPackagesPanel.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Nullable
private PackageManagementServiceEx getServiceEx() {
  return ObjectUtils.tryCast(myPackageManagementService, PackageManagementServiceEx.class);
}
 
Example 19
Source File: ChangesBrowserBase.java    From consulo with Apache License 2.0 4 votes vote down vote up
public boolean isSelected(AnActionEvent e) {
  T change = ObjectUtils.tryCast(e.getData(VcsDataKeys.CURRENT_CHANGE), myClass);
  if (change == null) return false;

  return myViewer.isIncluded(change);
}
 
Example 20
Source File: ContextMenuPopupHandler.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Nullable
private static ActionGroup getGroupForId(@Nullable String groupId) {
  return groupId == null ? null : ObjectUtils.tryCast(CustomActionsSchema.getInstance().getCorrectedAction(groupId), ActionGroup.class);
}