Java Code Examples for com.intellij.util.ObjectUtils

The following examples show how to use com.intellij.util.ObjectUtils. These examples are extracted from open source projects. 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 Project: consulo   Source File: MultipleChangeListBrowser.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected void setInitialSelection(@Nonnull List<? extends ChangeList> changeLists,
                                   @Nonnull List<Object> changes,
                                   @javax.annotation.Nullable ChangeList initialListSelection) {
  myAllChanges = ContainerUtil.newArrayList();
  mySelectedChangeList = initialListSelection;

  for (ChangeList list : changeLists) {
    if (list instanceof LocalChangeList) {
      myAllChanges.addAll(list.getChanges());
      if (initialListSelection == null && ContainerUtil.intersects(list.getChanges(), changes)) {
        mySelectedChangeList = list;
      }
    }
  }

  if (mySelectedChangeList == null) {
    mySelectedChangeList = ObjectUtils.chooseNotNull(findDefaultList(changeLists), ContainerUtil.getFirstItem(changeLists));
  }
}
 
Example 2
protected GeneralCommandLine createDefaultCommandLine() {
            // here just run one command: python freeline.py
            PtyCommandLine commandLine = new PtyCommandLine();
            if (!SystemInfo.isWindows) {
                commandLine.getEnvironment().put("TERM", "xterm-256color");
            }
//            commandLine.withConsoleMode(false);
//            commandLine.withInitialColumns(120);
            ExecutionEnvironment environment = getEnvironment();
            commandLine.setWorkDirectory(environment.getProject().getBasePath());
            String defaultShell = ObjectUtils.notNull(EnvironmentUtil.getValue("SHELL"), "/bin/sh");
            commandLine.setExePath(defaultShell);
//            commandLine.setExePath("npm");
//            commandLine.addParameters("run-script");
//            commandLine.addParameters("start");
            return commandLine;
        }
 
Example 3
Source Project: idea-php-shopware-plugin   Source File: SubscriberIndexUtil.java    License: MIT License 6 votes vote down vote up
/**
 * foo => 'goo'
 * foo => ['goo', ... ]
 */
@Nullable
public static String getMethodNameForEventValue(@NotNull PhpPsiElement value) {
    if(value instanceof StringLiteralExpression) {
        return ((StringLiteralExpression) value).getContents();
    }

    if(value instanceof ArrayCreationExpression) {
        PhpPsiElement firstPsiChild = value.getFirstPsiChild();
        if(firstPsiChild != null && firstPsiChild.getNode().getElementType() == PhpElementTypes.ARRAY_VALUE) {
            StringLiteralExpression stringLiteral = ObjectUtils.tryCast(firstPsiChild.getFirstPsiChild(), StringLiteralExpression.class);
            if(stringLiteral != null) {
                return stringLiteral.getContents();
            }
        }

        return null;
    }

    return null;
}
 
Example 4
Source Project: consulo   Source File: ChangesTreeList.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Color getFileColorFor(Object object) {
  VirtualFile file;
  if (object instanceof FilePath) {
    file = ((FilePath)object).getVirtualFile();
  }
  else if (object instanceof Change) {
    file = ((Change)object).getVirtualFile();
  }
  else {
    file = ObjectUtils.tryCast(object, VirtualFile.class);
  }

  if (file != null) {
    return FileColorManager.getInstance(myProject).getFileColor(file);
  }
  return super.getFileColorFor(object);
}
 
Example 5
Source Project: consulo   Source File: EditorUtil.java    License: Apache License 2.0 6 votes vote down vote up
public static void runBatchFoldingOperationOutsideOfBulkUpdate(@Nonnull Editor editor, @Nonnull Runnable operation) {
  DocumentEx document = ObjectUtils.tryCast(editor.getDocument(), DocumentEx.class);
  if (document != null && document.isInBulkUpdate()) {
    MessageBusConnection connection = ApplicationManager.getApplication().getMessageBus().connect();
    disposeWithEditor(editor, connection::disconnect);
    connection.subscribe(DocumentBulkUpdateListener.TOPIC, new DocumentBulkUpdateListener.Adapter() {
      @Override
      public void updateFinished(@Nonnull Document doc) {
        if (doc == editor.getDocument()) {
          editor.getFoldingModel().runBatchFoldingOperation(operation);
          connection.disconnect();
        }
      }
    });
  }
  else {
    editor.getFoldingModel().runBatchFoldingOperation(operation);
  }
}
 
Example 6
Source Project: consulo   Source File: EditorTextFieldCellRenderer.java    License: Apache License 2.0 6 votes vote down vote up
@Nonnull
private static Pair<EditorTextField, EditorEx> createEditor(Project project, @Nullable FileType fileType, boolean inheritFontFromLaF) {
  EditorTextField field = new EditorTextField(new EditorTextFieldRendererDocument(), project, fileType, false, false);
  field.setSupplementary(true);
  field.setFontInheritedFromLAF(inheritFontFromLaF);
  field.addNotify(); // creates editor

  EditorEx editor = (EditorEx)ObjectUtils.assertNotNull(field.getEditor());
  editor.setRendererMode(true);

  editor.setColorsScheme(editor.createBoundColorSchemeDelegate(null));
  editor.getSettings().setCaretRowShown(false);

  editor.getScrollPane().setBorder(null);

  return Pair.create(field, editor);
}
 
Example 7
Source Project: consulo   Source File: PopupFactoryImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void handleSelect(boolean handleFinalChoices, InputEvent e) {
  final Object selectedValue = getList().getSelectedValue();
  final ActionPopupStep actionPopupStep = ObjectUtils.tryCast(getListStep(), ActionPopupStep.class);

  if (actionPopupStep != null) {
    KeepingPopupOpenAction dontClosePopupAction = getActionByClass(selectedValue, actionPopupStep, KeepingPopupOpenAction.class);
    if (dontClosePopupAction != null) {
      actionPopupStep.performAction((AnAction)dontClosePopupAction, e != null ? e.getModifiers() : 0, e);
      for (ActionItem item : actionPopupStep.getValues()) {
        updateActionItem(item);
      }
      getList().repaint();
      return;
    }
  }

  super.handleSelect(handleFinalChoices, e);
}
 
Example 8
Source Project: consulo   Source File: AbstractCommonCheckinAction.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void actionPerformed(@Nonnull VcsContext context) {
  LOG.debug("actionPerformed. ");
  Project project = ObjectUtils.notNull(context.getProject());

  if (ChangeListManager.getInstance(project).isFreezedWithNotification("Can not " + getMnemonicsFreeActionName(context) + " now")) {
    LOG.debug("ChangeListManager is freezed. returning.");
  }
  else if (ProjectLevelVcsManager.getInstance(project).isBackgroundVcsOperationRunning()) {
    LOG.debug("Background operation is running. returning.");
  }
  else {
    FilePath[] roots = prepareRootsForCommit(getRoots(context), project);
    ChangeListManager.getInstance(project)
            .invokeAfterUpdate(() -> performCheckIn(context, project, roots), InvokeAfterUpdateMode.SYNCHRONOUS_CANCELLABLE,
                               VcsBundle.message("waiting.changelists.update.for.show.commit.dialog.message"), ModalityState.current());
  }
}
 
Example 9
Source Project: consulo   Source File: QuickEditAction.java    License: Apache License 2.0 5 votes vote down vote up
public QuickEditHandler invokeImpl(@Nonnull final Project project, final Editor editor, PsiFile file) throws IncorrectOperationException {
  int offset = editor.getCaretModel().getOffset();
  Pair<PsiElement, TextRange> pair = ObjectUtils.assertNotNull(getRangePair(file, editor));

  PsiFile injectedFile = (PsiFile)pair.first;
  QuickEditHandler handler = getHandler(project, injectedFile, editor, file);

  if (!ApplicationManager.getApplication().isUnitTestMode()) {
    DocumentWindow documentWindow = InjectedLanguageUtil.getDocumentWindow(injectedFile);
    if (documentWindow != null) {
      handler.navigate(InjectedLanguageUtil.hostToInjectedUnescaped(documentWindow, offset));
    }
  }
  return handler;
}
 
Example 10
Source Project: consulo   Source File: IgnoredFilesCompositeHolder.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void notifyVcsStarted(AbstractVcs vcs) {
  myCurrentVcs = vcs;
  if (myVcsIgnoredHolderMap.containsKey(vcs)) return;

  IgnoredFilesHolder ignoredFilesHolder =
          ObjectUtils.chooseNotNull(getHolderFromEP(vcs, myProject), new RecursiveFileHolder<>(myProject, HolderType.IGNORED));
  ignoredFilesHolder.notifyVcsStarted(vcs);
  myVcsIgnoredHolderMap.put(vcs, ignoredFilesHolder);
}
 
Example 11
Source Project: intellij-swagger   Source File: JsonSchemaInspection.java    License: MIT License 5 votes vote down vote up
private PsiElementVisitor createVisitor(
    final String schemaFileName,
    final ProblemsHolder holder,
    final LocalInspectionToolSession session,
    final PsiFile file) {

  JsonValue root =
      file instanceof JsonFile
          ? ObjectUtils.tryCast(file.getFirstChild(), JsonValue.class)
          : null;
  if (root == null) return PsiElementVisitor.EMPTY_VISITOR;

  JsonSchemaService service = JsonSchemaService.Impl.get(file.getProject());

  final URL url = ResourceUtil.getResource(getClass(), "schemas", schemaFileName);
  final VirtualFile virtualFile = VfsUtil.findFileByURL(url);

  final JsonSchemaObject schema = service.getSchemaObjectForSchemaFile(virtualFile);

  return new JsonElementVisitor() {
    @Override
    public void visitElement(PsiElement element) {
      if (element == root) {
        final JsonLikePsiWalker walker = JsonLikePsiWalker.getWalker(element, schema);
        if (walker == null) return;

        JsonComplianceCheckerOptions options = new JsonComplianceCheckerOptions(false);

        new JsonSchemaComplianceChecker(schema, holder, walker, session, options)
            .annotate(element);
      }
    }
  };
}
 
Example 12
Source Project: consulo   Source File: ChangesBrowserBase.java    License: 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 13
Source Project: consulo   Source File: RunConfigurationsSEContributor.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public boolean processSelectedItem(@Nonnull ChooseRunConfigurationPopup.ItemWrapper selected, int modifiers, @Nonnull String searchText) {
  RunnerAndConfigurationSettings settings = ObjectUtils.tryCast(selected.getValue(), RunnerAndConfigurationSettings.class);
  if (settings != null) {
    int mode = getMode(searchText, modifiers);
    Executor executor = findExecutor(settings, mode);
    if (executor != null) {
      DataManager dataManager = DataManager.getInstance();
      selected.perform(myProject, executor, dataManager.getDataContext(myContextComponent));
    }
  }

  return true;
}
 
Example 14
Source Project: consulo   Source File: RunIdeConsoleAction.java    License: Apache License 2.0 5 votes vote down vote up
@Nonnull
private static String getCommandText(@Nonnull Project project, @Nonnull Editor editor) {
  TextRange selectedRange = EditorUtil.getSelectionInAnyMode(editor);
  Document document = editor.getDocument();
  if (selectedRange.isEmpty()) {
    int line = document.getLineNumber(selectedRange.getStartOffset());
    selectedRange = TextRange.create(document.getLineStartOffset(line), document.getLineEndOffset(line));

    // try detect a non-trivial composite PSI element if there's a PSI file
    PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument());
    if (file != null && file.getFirstChild() != null && file.getFirstChild() != file.getLastChild()) {
      PsiElement e1 = file.findElementAt(selectedRange.getStartOffset());
      PsiElement e2 = file.findElementAt(selectedRange.getEndOffset());
      while (e1 != e2 && (e1 instanceof PsiWhiteSpace || e1 != null && StringUtil.isEmptyOrSpaces(e1.getText()))) {
        e1 = ObjectUtils.chooseNotNull(e1.getNextSibling(), PsiTreeUtil.getDeepestFirst(e1.getParent()));
      }
      while (e1 != e2 && (e2 instanceof PsiWhiteSpace || e2 != null && StringUtil.isEmptyOrSpaces(e2.getText()))) {
        e2 = ObjectUtils.chooseNotNull(e2.getPrevSibling(), PsiTreeUtil.getDeepestLast(e2.getParent()));
      }
      if (e1 instanceof LeafPsiElement) e1 = e1.getParent();
      if (e2 instanceof LeafPsiElement) e2 = e2.getParent();
      PsiElement parent = e1 == null ? e2 : e2 == null ? e1 : PsiTreeUtil.findCommonParent(e1, e2);
      if (parent != null && parent != file) {
        selectedRange = parent.getTextRange();
      }
    }
  }
  return document.getText(selectedRange);
}
 
Example 15
Source Project: consulo   Source File: PushController.java    License: Apache License 2.0 5 votes vote down vote up
@Nullable
private static PushTarget getCommonTarget(@Nonnull Collection<MyRepoModel<?, ?, ?>> selectedNodes) {
  final PushTarget commonTarget = ObjectUtils.assertNotNull(ContainerUtil.getFirstItem(selectedNodes)).getTarget();
  return commonTarget != null && !ContainerUtil.exists(selectedNodes, new Condition<MyRepoModel<?, ?, ?>>() {
    @Override
    public boolean value(MyRepoModel model) {
      return !commonTarget.equals(model.getTarget());
    }
  }) ? commonTarget : null;
}
 
Example 16
Source Project: react-templates-plugin   Source File: RTFileUtil.java    License: 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 17
Source Project: idea-php-shopware-plugin   Source File: HookSubscriberUtil.java    License: 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 18
Source Project: consulo   Source File: MoveChangesToAnotherListAction.java    License: Apache License 2.0 5 votes vote down vote up
@javax.annotation.Nullable
private static ChangeList guessPreferredList(@Nonnull List<LocalChangeList> lists) {
  LocalChangeList activeChangeList = ContainerUtil.find(lists, LocalChangeList::isDefault);
  if (activeChangeList != null) return activeChangeList;

  LocalChangeList emptyList = ContainerUtil.find(lists, list -> list.getChanges().isEmpty());

  return ObjectUtils.chooseNotNull(emptyList, ContainerUtil.getFirstItem(lists));
}
 
Example 19
Source Project: intellij-pants-plugin   Source File: PantsUtil.java    License: Apache License 2.0 5 votes vote down vote up
public static void copyDirContent(@NotNull File fromDir, @NotNull File toDir) throws IOException {
  final File[] children = ObjectUtils.notNull(fromDir.listFiles(), ArrayUtil.EMPTY_FILE_ARRAY);
  for (File child : children) {
    final File target = new File(toDir, child.getName());
    if (child.isFile()) {
      FileUtil.copy(child, target);
    }
    else {
      FileUtil.copyDir(child, target, false);
    }
  }
}
 
Example 20
Source Project: eslint-plugin   Source File: ESLintConfigFileUtil.java    License: 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 21
Source Project: consulo   Source File: AbstractGotoSEContributor.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void fetchWeightedElements(@Nonnull String pattern, @Nonnull ProgressIndicator progressIndicator, @Nonnull Processor<? super FoundItemDescriptor<Object>> consumer) {
  if (myProject == null) return; //nowhere to search
  if (!isEmptyPatternSupported() && pattern.isEmpty()) return;

  ProgressIndicatorUtils.yieldToPendingWriteActions();
  ProgressIndicatorUtils.runInReadActionWithWriteActionPriority(() -> {
    if (!isDumbAware() && DumbService.isDumb(myProject)) return;

    FilteringGotoByModel<?> model = createModel(myProject);
    if (progressIndicator.isCanceled()) return;

    PsiElement context = psiContext != null && psiContext.isValid() ? psiContext : null;
    ChooseByNamePopup popup = ChooseByNamePopup.createPopup(myProject, model, context);
    try {
      ChooseByNameItemProvider provider = popup.getProvider();
      GlobalSearchScope scope = Registry.is("search.everywhere.show.scopes") ? (GlobalSearchScope)ObjectUtils.notNull(myScopeDescriptor.getScope()) : null;

      boolean everywhere = scope == null ? myEverywhere : scope.isSearchInLibraries();
      if (scope != null && provider instanceof ChooseByNameInScopeItemProvider) {
        FindSymbolParameters parameters = FindSymbolParameters.wrap(pattern, scope);
        ((ChooseByNameInScopeItemProvider)provider)
                .filterElementsWithWeights(popup, parameters, progressIndicator, item -> processElement(progressIndicator, consumer, model, item.getItem(), item.getWeight()));
      }
      else if (provider instanceof ChooseByNameWeightedItemProvider) {
        ((ChooseByNameWeightedItemProvider)provider)
                .filterElementsWithWeights(popup, pattern, everywhere, progressIndicator, item -> processElement(progressIndicator, consumer, model, item.getItem(), item.getWeight()));
      }
      else {
        provider.filterElements(popup, pattern, everywhere, progressIndicator, element -> processElement(progressIndicator, consumer, model, element, getElementPriority(element, pattern)));
      }
    }
    finally {
      Disposer.dispose(popup);
    }
  }, progressIndicator);
}
 
Example 22
Source Project: consulo   Source File: DarculaComboBoxUI.java    License: Apache License 2.0 5 votes vote down vote up
private Color getBackgroundColor() {
  if (comboBox.isEditable() && editor != null) {
    return comboBox.isEnabled() ? editor.getBackground() : comboBox.getBackground();
  }
  else {
    Color bg = comboBox.getBackground();
    Object value = comboBox.getSelectedItem();
    Color coloredItemColor = value instanceof ColoredItem ? ((ColoredItem)value).getColor() : null;
    return ObjectUtils.notNull(coloredItemColor, !comboBox.isEnabled() || comboBox.isBackgroundSet() && !(bg instanceof UIResource) ? bg : NON_EDITABLE_BACKGROUND);
  }
}
 
Example 23
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 24
@NotNull
@Override
public Result checkAutoPopup(char charTyped, @NotNull Project project, @NotNull Editor editor, @NotNull PsiFile file) {

    if (!(file instanceof PhpFile)) {
        return Result.CONTINUE;
    }

    if (charTyped != '%') {
        return Result.CONTINUE;
    }

    int offset = editor.getCaretModel().getOffset();
    PsiElement psiElement = file.findElementAt(offset);

    ParameterList parameterList = PhpPsiUtil.getParentByCondition(psiElement, true, ParameterList.INSTANCEOF, Statement.INSTANCEOF);
    if (parameterList != null) {
        FunctionReference functionCall = ObjectUtils.tryCast(parameterList.getParent(), FunctionReference.class);
        String fqn = PhpElementsUtil.resolveFqn(functionCall);

        if (/*charTyped == '%' &&*/ PhpElementsUtil.isFormatFunction(fqn)) {
            if (StringUtil.getPrecedingCharNum(editor.getDocument().getCharsSequence(), offset, '%') % 2 == 0) {
                PhpCompletionUtil.showCompletion(editor);
            }
        }
    }

    return Result.CONTINUE;
}
 
Example 25
Source Project: consulo   Source File: ApplyPatchAction.java    License: Apache License 2.0 5 votes vote down vote up
@Nonnull
private static ApplyFilePatch.Result tryApplyPatch(@javax.annotation.Nullable final Project project,
                                                   @Nonnull final ApplyFilePatchBase patch,
                                                   @javax.annotation.Nullable final ApplyPatchContext context,
                                                   @Nonnull final VirtualFile file,
                                                   @javax.annotation.Nullable final CommitContext commitContext) {
  final FilePatch patchBase = patch.getPatch();
  return ApplicationManager.getApplication().runWriteAction(
          new Computable<ApplyFilePatch.Result>() {
            @Override
            public ApplyFilePatch.Result compute() {
              try {
                return patch.apply(file, context, project, VcsUtil.getFilePath(file), new Getter<CharSequence>() {
                  @Override
                  public CharSequence get() {
                    final BaseRevisionTextPatchEP baseRevisionTextPatchEP =
                            Extensions.findExtension(PatchEP.EP_NAME, project, BaseRevisionTextPatchEP.class);
                    final String path = ObjectUtils.chooseNotNull(patchBase.getBeforeName(), patchBase.getAfterName());
                    return baseRevisionTextPatchEP.provideContent(path, commitContext);
                  }
                }, commitContext);
              }
              catch (IOException e) {
                LOG.error(e);
                return ApplyFilePatch.Result.createThrow(e);
              }
            }
          });
}
 
Example 26
Source Project: consulo   Source File: AbstractAutoTestManager.java    License: Apache License 2.0 5 votes vote down vote up
public static void saveConfigurationState(State state, RunProfile profile) {
  RunConfiguration runConfiguration = ObjectUtils.tryCast(profile, RunConfiguration.class);
  if (runConfiguration != null) {
    RunConfigurationDescriptor descriptor = new RunConfigurationDescriptor();
    descriptor.myType = runConfiguration.getType().getId();
    descriptor.myName = runConfiguration.getName();
    state.myEnabledRunConfigurations.add(descriptor);
  }
}
 
Example 27
Source Project: consulo   Source File: GroupNode.java    License: Apache License 2.0 5 votes vote down vote up
@Nonnull
@SuppressWarnings("unchecked")
List<Node> getSwingChildren() {
  // on java 9 - children is Vector<TreeNode>
  List children = this.children;
  return ObjectUtils.notNull(children, Collections.<Node>emptyList());
}
 
Example 28
Source Project: consulo   Source File: CreatePatchConfigurationPanel.java    License: Apache License 2.0 5 votes vote down vote up
public CreatePatchConfigurationPanel(@Nonnull final Project project) {
  myProject = project;
  initMainPanel();

  myFileNameField.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
      final FileSaverDialog dialog =
              FileChooserFactory.getInstance().createSaveFileDialog(
                      new FileSaverDescriptor("Save Patch to", ""), myMainPanel);
      final String path = FileUtil.toSystemIndependentName(getFileName());
      final int idx = path.lastIndexOf("/");
      VirtualFile baseDir = idx == -1 ? project.getBaseDir() :
                            (LocalFileSystem.getInstance().refreshAndFindFileByIoFile(new File(path.substring(0, idx))));
      baseDir = baseDir == null ? project.getBaseDir() : baseDir;
      final String name = idx == -1 ? path : path.substring(idx + 1);
      final VirtualFileWrapper fileWrapper = dialog.save(baseDir, name);
      if (fileWrapper != null) {
        myFileNameField.setText(fileWrapper.getFile().getPath());
      }
    }
  });

  myFileNameField.setTextFieldPreferredWidth(TEXT_FIELD_WIDTH);
  myBasePathField.setTextFieldPreferredWidth(TEXT_FIELD_WIDTH);
  myBasePathField.addBrowseFolderListener(new TextBrowseFolderListener(FileChooserDescriptorFactory.createSingleFolderDescriptor()));
  myWarningLabel.setForeground(JBColor.RED);
  selectBasePath(ObjectUtils.assertNotNull(myProject.getBaseDir()));
  initEncodingCombo();
}
 
Example 29
Source Project: consulo   Source File: CheckBoxList.java    License: 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 30
Source Project: consulo   Source File: LoadTextUtil.java    License: Apache License 2.0 5 votes vote down vote up
@Nonnull
private static Pair.NonNull<Charset, byte[]> getOverriddenCharsetByBOM(@Nonnull byte[] content, @Nonnull Charset charset) {
  if (charset.name().contains(CharsetToolkit.UTF8) && CharsetToolkit.hasUTF8Bom(content)) {
    return Pair.createNonNull(charset, CharsetToolkit.UTF8_BOM);
  }
  Charset charsetFromBOM = CharsetToolkit.guessFromBOM(content);
  if (charsetFromBOM != null) {
    byte[] bom = ObjectUtils.notNull(CharsetToolkit.getMandatoryBom(charsetFromBOM), ArrayUtilRt.EMPTY_BYTE_ARRAY);
    return Pair.createNonNull(charsetFromBOM, bom);
  }

  return Pair.createNonNull(charset, ArrayUtilRt.EMPTY_BYTE_ARRAY);
}