Example #1
0
  @NotNull
  private static String[] collectNamesToImport(
      @NotNull PsiJavaFile file, @NotNull Set<String> namesToImportStaticly) {
    Set<String> names = new THashSet<String>();

    final JspFile jspFile = JspPsiUtil.getJspFile(file);
    collectNamesToImport(names, file, namesToImportStaticly, jspFile);
    if (jspFile != null) {
      PsiFile[] files =
          ArrayUtil.mergeArrays(
              JspSpiUtil.getIncludingFiles(jspFile),
              JspSpiUtil.getIncludedFiles(jspFile),
              PsiFile.class);
      for (PsiFile includingFile : files) {
        final PsiFile javaRoot = includingFile.getViewProvider().getPsi(StdLanguages.JAVA);
        if (javaRoot instanceof PsiJavaFile && file != javaRoot) {
          collectNamesToImport(names, (PsiJavaFile) javaRoot, namesToImportStaticly, jspFile);
        }
      }
    }

    addUnresolvedImportNames(names, file, namesToImportStaticly);

    return ArrayUtil.toStringArray(names);
  }
  public static Pair<String[], int[]> listAll(int parentId) {
    try {
      r.lock();
      try {
        final DataInputStream input = readAttribute(parentId, CHILDREN_ATT);
        if (input == null)
          return Pair.create(ArrayUtil.EMPTY_STRING_ARRAY, ArrayUtil.EMPTY_INT_ARRAY);

        final int count = DataInputOutputUtil.readINT(input);
        final int[] ids = ArrayUtil.newIntArray(count);
        final String[] names = ArrayUtil.newStringArray(count);
        for (int i = 0; i < count; i++) {
          int id = DataInputOutputUtil.readINT(input);
          id = id >= 0 ? id + parentId : -id;
          ids[i] = id;
          names[i] = getName(id);
        }
        input.close();
        return Pair.create(names, ids);
      } finally {
        r.unlock();
      }
    } catch (Throwable e) {
      throw DbConnection.handleError(e);
    }
  }
 @Override
 public Object[] getChildElements(Object element) {
   if (element == RootDescriptor.ROOT) {
     return ArrayUtil.toStringArray(myCertificates.keySet());
   } else if (element instanceof String) {
     return ArrayUtil.toObjectArray(myCertificates.get((String) element));
   }
   return ArrayUtil.EMPTY_OBJECT_ARRAY;
 }
 @Override
 public ConfigurableWrapper addChild(Configurable configurable) {
   if (myComparator != null) {
     int index = Arrays.binarySearch(myKids, configurable, myComparator);
     LOG.assertTrue(index < 0, "similar configurable is already exist");
     myKids = ArrayUtil.insert(myKids, -1 - index, configurable);
   } else {
     myKids = ArrayUtil.append(myKids, configurable);
   }
   return this;
 }
Example #5
0
 private void removeFromMap(int id, int index) {
   id = unwrap(myFactory.getValue(id)).getID();
   int[] classes = myIdToEqClassesIndices.get(id);
   if (classes != null) {
     int i = ArrayUtil.indexOf(classes, index);
     if (i != -1) {
       classes = ArrayUtil.remove(classes, i);
       myIdToEqClassesIndices.put(id, classes);
     }
   }
 }
  /**
   * check whether statement is return (the statement which provides return value) statement of
   * method or closure.
   *
   * @param st
   * @return
   */
  public static boolean isCertainlyReturnStatement(GrStatement st) {
    final PsiElement parent = st.getParent();
    if (parent instanceof GrOpenBlock) {
      if (st != ArrayUtil.getLastElement(((GrOpenBlock) parent).getStatements())) return false;

      PsiElement pparent = parent.getParent();
      if (pparent instanceof GrMethod) {
        return true;
      }

      if (pparent instanceof GrBlockStatement
          || pparent instanceof GrCatchClause
          || pparent instanceof GrLabeledStatement) {
        pparent = pparent.getParent();
      }
      if (pparent instanceof GrIfStatement
          || pparent instanceof GrControlStatement
          || pparent instanceof GrTryCatchStatement) {
        return isCertainlyReturnStatement((GrStatement) pparent);
      }
    } else if (parent instanceof GrClosableBlock) {
      return st == ArrayUtil.getLastElement(((GrClosableBlock) parent).getStatements());
    } else if (parent instanceof GroovyFileBase) {
      return st == ArrayUtil.getLastElement(((GroovyFileBase) parent).getStatements());
    } else if (parent instanceof GrForStatement
        || parent instanceof GrIfStatement && st != ((GrIfStatement) parent).getCondition()
        || parent instanceof GrSynchronizedStatement
            && st != ((GrSynchronizedStatement) parent).getMonitor()
        || parent instanceof GrWhileStatement && st != ((GrWhileStatement) parent).getCondition()
        || parent instanceof GrConditionalExpression
            && st != ((GrConditionalExpression) parent).getCondition()
        || parent instanceof GrElvisExpression) {
      return isCertainlyReturnStatement((GrStatement) parent);
    } else if (parent instanceof GrCaseSection) {
      final GrStatement[] statements = ((GrCaseSection) parent).getStatements();
      final GrStatement last = ArrayUtil.getLastElement(statements);
      final GrSwitchStatement switchStatement = (GrSwitchStatement) parent.getParent();

      if (last instanceof GrBreakStatement
          && statements.length > 1
          && statements[statements.length - 2] == st) {
        return isCertainlyReturnStatement(switchStatement);
      } else if (st == last) {
        if (st instanceof GrBreakStatement
            || isLastStatementInCaseSection((GrCaseSection) parent, switchStatement)) {
          return isCertainlyReturnStatement(switchStatement);
        }
      }
    }
    return false;
  }
  public static int findRootRecord(String rootUrl) throws IOException {
    try {
      w.lock();
      DbConnection.markDirty();
      final int root = getNames().enumerate(rootUrl);

      final DataInputStream input = readAttribute(1, CHILDREN_ATT);
      int[] names = ArrayUtil.EMPTY_INT_ARRAY;
      int[] ids = ArrayUtil.EMPTY_INT_ARRAY;

      if (input != null) {
        try {
          final int count = DataInputOutputUtil.readINT(input);
          names = ArrayUtil.newIntArray(count);
          ids = ArrayUtil.newIntArray(count);
          for (int i = 0; i < count; i++) {
            final int name = DataInputOutputUtil.readINT(input);
            final int id = DataInputOutputUtil.readINT(input);
            if (name == root) {
              return id;
            }

            names[i] = name;
            ids[i] = id;
          }
        } finally {
          input.close();
        }
      }

      final DataOutputStream output = writeAttribute(1, CHILDREN_ATT, false);
      int id;
      try {
        id = createRecord();
        DataInputOutputUtil.writeINT(output, names.length + 1);
        for (int i = 0; i < names.length; i++) {
          DataInputOutputUtil.writeINT(output, names[i]);
          DataInputOutputUtil.writeINT(output, ids[i]);
        }
        DataInputOutputUtil.writeINT(output, root);
        DataInputOutputUtil.writeINT(output, id);
      } finally {
        output.close();
      }

      return id;
    } finally {
      w.unlock();
    }
  }
 private static int rearrangeOrderEntryOfType(
     ModifiableRootModel rootModel, Class<? extends OrderEntry> orderEntryClass) {
   OrderEntry[] orderEntries = rootModel.getOrderEntries();
   int moduleSourcesIdx = 0;
   for (OrderEntry orderEntry : orderEntries) {
     if (orderEntryClass.isAssignableFrom(orderEntry.getClass())) {
       break;
     }
     moduleSourcesIdx++;
   }
   orderEntries = ArrayUtil.append(orderEntries, orderEntries[moduleSourcesIdx]);
   orderEntries = ArrayUtil.remove(orderEntries, moduleSourcesIdx);
   rootModel.rearrangeOrderEntries(orderEntries);
   return orderEntries.length - 1;
 }
  @Nullable
  protected DaemonCodeAnalyzerStatus getDaemonCodeAnalyzerStatus(
      boolean fillErrorsCount, SeverityRegistrar severityRegistrar) {
    if (myFile == null
        || myProject.isDisposed()
        || !myDaemonCodeAnalyzer.isHighlightingAvailable(myFile)) return null;

    List<String> noInspectionRoots = new ArrayList<String>();
    List<String> noHighlightingRoots = new ArrayList<String>();
    FileViewProvider provider = myFile.getViewProvider();
    Set<Language> languages = provider.getLanguages();
    for (Language language : languages) {
      PsiFile root = provider.getPsi(language);
      if (!HighlightLevelUtil.shouldHighlight(root)) {
        noHighlightingRoots.add(language.getID());
      } else if (!HighlightLevelUtil.shouldInspect(root)) {
        noInspectionRoots.add(language.getID());
      }
    }
    DaemonCodeAnalyzerStatus status = new DaemonCodeAnalyzerStatus();
    status.noInspectionRoots =
        noInspectionRoots.isEmpty() ? null : ArrayUtil.toStringArray(noInspectionRoots);
    status.noHighlightingRoots =
        noHighlightingRoots.isEmpty() ? null : ArrayUtil.toStringArray(noHighlightingRoots);

    status.errorCount = errorCount.clone();
    status.rootsNumber = languages.size();
    fillDaemonCodeAnalyzerErrorsStatus(status, fillErrorsCount, severityRegistrar);
    List<TextEditorHighlightingPass> passes =
        myDaemonCodeAnalyzer.getPassesToShowProgressFor(myDocument);
    status.passStati =
        passes.isEmpty()
            ? Collections.<ProgressableTextEditorHighlightingPass>emptyList()
            : new ArrayList<ProgressableTextEditorHighlightingPass>(passes.size());
    //noinspection ForLoopReplaceableByForEach
    for (int i = 0; i < passes.size(); i++) {
      TextEditorHighlightingPass tepass = passes.get(i);
      if (!(tepass instanceof ProgressableTextEditorHighlightingPass)) continue;
      ProgressableTextEditorHighlightingPass pass = (ProgressableTextEditorHighlightingPass) tepass;

      if (pass.getProgress() < 0) continue;
      status.passStati.add(pass);
    }
    status.errorAnalyzingFinished = myDaemonCodeAnalyzer.isAllAnalysisFinished(myFile);
    status.enabled = myDaemonCodeAnalyzer.isUpdateByTimerEnabled();

    return status;
  }
  public static String[] getParameterString(ExtractInfoHelper helper, boolean useCanonicalText) {
    int i = 0;
    ParameterInfo[] infos = helper.getParameterInfos();
    int number = 0;
    for (ParameterInfo info : infos) {
      if (info.passAsParameter()) number++;
    }
    ArrayList<String> params = new ArrayList<String>();
    for (ParameterInfo info : infos) {
      if (info.passAsParameter()) {
        PsiType paramType = info.getType();
        final PsiPrimitiveType unboxed = PsiPrimitiveType.getUnboxedType(paramType);
        if (unboxed != null) paramType = unboxed;
        String paramTypeText;

        if (paramType == null || paramType.equalsToText(CommonClassNames.JAVA_LANG_OBJECT)) {
          paramTypeText = "";
        } else {
          paramTypeText =
              (useCanonicalText ? paramType.getCanonicalText() : paramType.getPresentableText())
                  + " ";
        }
        params.add(paramTypeText + info.getName() + (i < number - 1 ? ", " : ""));
        i++;
      }
    }
    return ArrayUtil.toStringArray(params);
  }
  @NotNull
  @Override
  public SuggestedNameInfo suggestUniqueVariableName(
      @NotNull final SuggestedNameInfo baseNameInfo,
      PsiElement place,
      boolean ignorePlaceName,
      boolean lookForward) {
    final String[] names = baseNameInfo.names;
    final LinkedHashSet<String> uniqueNames = new LinkedHashSet<String>(names.length);
    for (String name : names) {
      if (ignorePlaceName && place instanceof PsiNamedElement) {
        final String placeName = ((PsiNamedElement) place).getName();
        if (Comparing.strEqual(placeName, name)) {
          uniqueNames.add(name);
          continue;
        }
      }
      uniqueNames.add(suggestUniqueVariableName(name, place, lookForward));
    }

    return new SuggestedNameInfo(ArrayUtil.toStringArray(uniqueNames)) {
      @Override
      public void nameChosen(String name) {
        baseNameInfo.nameChosen(name);
      }
    };
  }
    public Object[] get(final PsiElement context, CompletionContext completionContext) {
      XmlFile containingFile = null;
      XmlFile descriptorFile = null;
      final XmlTag tag = PsiTreeUtil.getParentOfType(context, XmlTag.class);

      if (tag != null) {
        containingFile = (XmlFile) tag.getContainingFile();
        descriptorFile = findDescriptorFile(tag, containingFile);
      } else {
        final XmlDocument document = PsiTreeUtil.getParentOfType(context, XmlDocument.class);

        if (document != null) {
          containingFile = (XmlFile) document.getContainingFile();

          final FileType ft = containingFile.getFileType();

          if (ft != StdFileTypes.XML) {
            final String namespace =
                ft == StdFileTypes.XHTML || ft == StdFileTypes.JSPX
                    ? XmlUtil.XHTML_URI
                    : XmlUtil.HTML_URI;
            final XmlNSDescriptor nsDescriptor = document.getDefaultNSDescriptor(namespace, true);

            if (nsDescriptor != null) {
              descriptorFile = nsDescriptor.getDescriptorFile();
            }
          }
        }
      }

      if (descriptorFile != null) {
        final List<Object> results = new ArrayList<Object>();
        final boolean acceptSystemEntities = containingFile.getFileType() == StdFileTypes.XML;

        final PsiElementProcessor processor =
            new PsiElementProcessor() {
              public boolean execute(@NotNull final PsiElement element) {
                if (element instanceof XmlEntityDecl) {
                  final XmlEntityDecl xmlEntityDecl = (XmlEntityDecl) element;
                  if (xmlEntityDecl.isInternalReference() || acceptSystemEntities) {
                    final String name = xmlEntityDecl.getName();
                    final Object _item = getLookupItem(xmlEntityDecl);
                    results.add(_item == null ? name : _item);
                  }
                }
                return true;
              }
            };

        XmlUtil.processXmlElements(descriptorFile, processor, true);
        if (descriptorFile != containingFile && containingFile.getFileType() == StdFileTypes.XML) {
          final XmlProlog element = containingFile.getDocument().getProlog();
          if (element != null) XmlUtil.processXmlElements(element, processor, true);
        }

        return ArrayUtil.toObjectArray(results);
      }

      return ArrayUtil.EMPTY_OBJECT_ARRAY;
    }
 static String suggestUniqueParameterName(
     JavaCodeStyleManager codeStyleManager,
     PsiExpression expression,
     PsiType exprType,
     Set<String> existingNames) {
   SuggestedNameInfo nameInfo =
       codeStyleManager.suggestVariableName(VariableKind.PARAMETER, null, expression, exprType);
   @NonNls String[] names = nameInfo.names;
   if (expression instanceof PsiReferenceExpression) {
     final PsiElement resolve = ((PsiReferenceExpression) expression).resolve();
     if (resolve instanceof PsiVariable) {
       final VariableKind variableKind = codeStyleManager.getVariableKind((PsiVariable) resolve);
       final String propertyName =
           codeStyleManager.variableNameToPropertyName(
               ((PsiVariable) resolve).getName(), variableKind);
       final String parameterName =
           codeStyleManager.propertyNameToVariableName(propertyName, VariableKind.PARAMETER);
       names = ArrayUtil.mergeArrays(new String[] {parameterName}, names);
     }
   }
   if (names.length == 0) names = new String[] {"param"};
   int suffix = 0;
   while (true) {
     for (String name : names) {
       String suggested = name + (suffix == 0 ? "" : String.valueOf(suffix));
       if (existingNames.add(suggested)) {
         return suggested;
       }
     }
     suffix++;
   }
 }
 @NotNull
 private Trinity<String[], VirtualFile[], VirtualFile[]> cacheThings() {
   Trinity<String[], VirtualFile[], VirtualFile[]> result;
   if (myList.isEmpty()) {
     result = EMPTY;
   } else {
     VirtualFilePointer[] vf = myList.toArray(new VirtualFilePointer[myList.size()]);
     List<VirtualFile> cachedFiles = new ArrayList<VirtualFile>(vf.length);
     List<String> cachedUrls = new ArrayList<String>(vf.length);
     List<VirtualFile> cachedDirectories = new ArrayList<VirtualFile>(vf.length / 3);
     boolean allFilesAreDirs = true;
     for (VirtualFilePointer v : vf) {
       VirtualFile file = v.getFile();
       String url = v.getUrl();
       cachedUrls.add(url);
       if (file != null) {
         cachedFiles.add(file);
         if (file.isDirectory()) {
           cachedDirectories.add(file);
         } else {
           allFilesAreDirs = false;
         }
       }
     }
     VirtualFile[] directories = VfsUtilCore.toVirtualFileArray(cachedDirectories);
     VirtualFile[] files =
         allFilesAreDirs ? directories : VfsUtilCore.toVirtualFileArray(cachedFiles);
     String[] urlsArray = ArrayUtil.toStringArray(cachedUrls);
     result = Trinity.create(urlsArray, files, directories);
   }
   myCachedThings = result;
   myTimeStampOfCachedThings = myVirtualFilePointerManager.getModificationCount();
   return result;
 }
  @Override
  @Nullable
  public Object deserialize(Object o, @NotNull Object... nodes) {
    assert nodes.length > 0;
    Object[] children;
    if (nodes.length == 1) {
      children = JDOMUtil.getContent((Element) nodes[0]);
    } else {
      String name = ((Element) nodes[0]).getName();
      List<Content> childrenList = new SmartList<Content>();
      for (Object node : nodes) {
        assert ((Element) node).getName().equals(name);
        childrenList.addAll(((Element) node).getContent());
      }
      children = ArrayUtil.toObjectArray(childrenList);
    }

    if (children.length == 0) {
      children = new Object[] {new Text(myTagAnnotation.textIfEmpty())};
    }

    assert myBinding != null;
    Object v = myBinding.deserialize(myAccessor.read(o), children);
    Object value = XmlSerializerImpl.convert(v, myAccessor.getValueClass());
    myAccessor.write(o, value);
    return o;
  }
Example #16
0
  @NotNull
  public static String[] getThrownExceptions(
      @NotNull FunctionDescriptor function, @NotNull final JetTypeMapper mapper) {
    AnnotationDescriptor annotation =
        function.getAnnotations().findAnnotation(new FqName("kotlin.throws"));
    if (annotation == null) {
      annotation = function.getAnnotations().findAnnotation(new FqName("kotlin.jvm.Throws"));
    }

    if (annotation == null) return ArrayUtil.EMPTY_STRING_ARRAY;

    Collection<ConstantValue<?>> values = annotation.getAllValueArguments().values();
    if (values.isEmpty()) return ArrayUtil.EMPTY_STRING_ARRAY;

    Object value = values.iterator().next();
    if (!(value instanceof ArrayValue)) return ArrayUtil.EMPTY_STRING_ARRAY;
    ArrayValue arrayValue = (ArrayValue) value;

    List<String> strings =
        ContainerUtil.mapNotNull(
            arrayValue.getValue(),
            new Function<ConstantValue<?>, String>() {
              @Override
              public String fun(ConstantValue<?> constant) {
                if (constant instanceof KClassValue) {
                  KClassValue classValue = (KClassValue) constant;
                  ClassDescriptor classDescriptor =
                      DescriptorUtils.getClassDescriptorForType(classValue.getValue());
                  return mapper.mapClass(classDescriptor).getInternalName();
                }
                return null;
              }
            });
    return ArrayUtil.toStringArray(strings);
  }
 @Override
 public Object getValue() {
   JTextField text = getComboText();
   if (text == null) {
     return myBooleanResourceValue == null
         ? Boolean.toString(myCheckBox.isSelected())
         : myBooleanResourceValue;
   }
   String value = text.getText();
   if (value == StringsComboEditor.UNSET || StringUtil.isEmpty(value)) {
     return null;
   }
   if (myIsDimension
       && !value.startsWith("@")
       && !value.endsWith("dip")
       && !value.equalsIgnoreCase("wrap_content")
       && !value.equalsIgnoreCase("fill_parent")
       && !value.equalsIgnoreCase("match_parent")) {
     if (value.length() <= 2) {
       return value + "dp";
     }
     int index = value.length() - 2;
     String dimension = value.substring(index);
     if (ArrayUtil.indexOf(ResourceRenderer.DIMENSIONS, dimension) == -1) {
       return value + "dp";
     }
   }
   return value;
 }
      @Override
      public void run(AnActionButton button) {
        int row = table.getEditingRow();
        int col = table.getEditingColumn();
        TableUtil.stopEditing(table);
        int[] idx = table.getSelectedRows();
        Arrays.sort(idx);
        if (delta > 0) {
          idx = ArrayUtil.reverseArray(idx);
        }

        if (idx.length == 0) return;
        if (idx[0] + delta < 0) return;
        if (idx[idx.length - 1] + delta > table.getModel().getRowCount()) return;

        for (int i = 0; i < idx.length; i++) {
          tableModel.exchangeRows(idx[i], idx[i] + delta);
          idx[i] += delta;
        }
        TableUtil.selectRows(table, idx);
        table.requestFocus();
        if (row > 0 && col != -1) {
          table.editCellAt(row - 1, col);
        }
      }
Example #19
0
  @Override
  public int getId(
      @NotNull VirtualFile parent, @NotNull String childName, @NotNull NewVirtualFileSystem fs) {
    int parentId = getFileId(parent);
    int[] children = FSRecords.list(parentId);

    if (children.length > 0) {
      // fast path, check that some child has same nameId as given name, this avoid O(N) on
      // retrieving names for processing non-cached children
      int nameId = FSRecords.getNameId(childName);
      for (final int childId : children) {
        if (nameId == FSRecords.getNameId(childId)) {
          return childId;
        }
      }
      // for case sensitive system the above check is exhaustive in consistent state of vfs
    }

    for (final int childId : children) {
      if (namesEqual(fs, childName, FSRecords.getName(childId))) return childId;
    }

    final VirtualFile fake = new FakeVirtualFile(parent, childName);
    final FileAttributes attributes = fs.getAttributes(fake);
    if (attributes != null) {
      final int child = createAndFillRecord(fs, fake, parentId, attributes);
      FSRecords.updateList(parentId, ArrayUtil.append(children, child));
      return child;
    }

    return 0;
  }
 private static boolean shouldBeBuiltByExternalSystem(@NotNull Module module) {
   for (Facet facet : FacetManager.getInstance(module).getAllFacets()) {
     if (ArrayUtil.contains(facet.getName(), "Android", "Android-Gradle", "Java-Gradle"))
       return true;
   }
   return false;
 }
  @NotNull
  public static String[] getCreateProjectCommand(
      @NotNull SymfonyInstallerVersion version,
      @NotNull String installerPath,
      @NotNull String newProjectPath,
      @NotNull String phpPath,
      @Nullable String commandLineOptions) {

    List<String> commands = new ArrayList<>();

    commands.add(phpPath);
    commands.add(installerPath);

    // "php symfony demo"
    if ("demo".equals(version.getVersion())) {
      commands.add("demo");
      commands.add(newProjectPath + "/" + PROJECT_SUB_FOLDER);
    } else {
      commands.add("new");
      commands.add(newProjectPath + "/" + PROJECT_SUB_FOLDER);
      commands.add(version.getVersion());
    }

    if (commandLineOptions != null) {
      commands.add(commandLineOptions);
    }

    return ArrayUtil.toStringArray(commands);
  }
 public String[] getTemplateNames() {
   final Set<String> names = new LinkedHashSet<String>();
   for (TemplateResource resource : getAllTemplates()) {
     names.add(getTemplateBaseName(resource));
   }
   return ArrayUtil.toStringArray(names);
 }
 @Override
 public void doApply(
     @NotNull Editor editor,
     @NotNull PySmartEnterProcessor processor,
     @NotNull PyWithStatement withStatement)
     throws IncorrectOperationException {
   final PsiElement colonToken = PyUtil.getFirstChildOfType(withStatement, PyTokenTypes.COLON);
   final PsiElement withToken =
       PyUtil.getFirstChildOfType(withStatement, PyTokenTypes.WITH_KEYWORD);
   final Document document = editor.getDocument();
   if (colonToken == null && withToken != null) {
     int insertAt = withToken.getTextRange().getEndOffset();
     String textToInsert = ":";
     final PyWithItem lastItem = ArrayUtil.getLastElement(withStatement.getWithItems());
     if (lastItem == null || lastItem.getExpression() == null) {
       textToInsert = " :";
       processor.registerUnresolvedError(insertAt + 1);
     } else {
       final PyExpression expression = lastItem.getExpression();
       insertAt = expression.getTextRange().getEndOffset();
       final PsiElement asToken = PyUtil.getFirstChildOfType(lastItem, PyTokenTypes.AS_KEYWORD);
       if (asToken != null) {
         insertAt = asToken.getTextRange().getEndOffset();
         final PyExpression target = lastItem.getTarget();
         if (target != null) {
           insertAt = target.getTextRange().getEndOffset();
         } else {
           textToInsert = " :";
           processor.registerUnresolvedError(insertAt + 1);
         }
       }
     }
     document.insertString(insertAt, textToInsert);
   }
 }
 public boolean checkConflicts(final ExtractSuperclassDialog dialog) {
   final MemberInfo[] infos =
       ArrayUtil.toObjectArray(dialog.getSelectedMemberInfos(), MemberInfo.class);
   final PsiDirectory targetDirectory = dialog.getTargetDirectory();
   final PsiPackage targetPackage;
   if (targetDirectory != null) {
     targetPackage = JavaDirectoryService.getInstance().getPackage(targetDirectory);
   } else {
     targetPackage = null;
   }
   final MultiMap<PsiElement, String> conflicts = new MultiMap<PsiElement, String>();
   if (!ProgressManager.getInstance()
       .runProcessWithProgressSynchronously(
           new Runnable() {
             public void run() {
               final PsiClass superClass =
                   mySubclass.getExtendsListTypes().length > 0 ? mySubclass.getSuperClass() : null;
               conflicts.putAllValues(
                   PullUpConflictsUtil.checkConflicts(
                       infos,
                       mySubclass,
                       superClass,
                       targetPackage,
                       targetDirectory,
                       dialog.getContainmentVerifier(),
                       false));
             }
           },
           RefactoringBundle.message("detecting.possible.conflicts"),
           true,
           myProject)) return false;
   ExtractSuperClassUtil.checkSuperAccessible(targetDirectory, conflicts, mySubclass);
   return ExtractSuperClassUtil.showConflicts(dialog, conflicts, myProject);
 }
 private void addTextSize(String staticText, int size, int wrap, int fill) {
   if (staticText == null) {
     if (size == wrap) {
       myTextFeedback.snap("wrap_content");
     } else if (size == fill) {
       myTextFeedback.snap("match_parent");
     } else {
       myTextFeedback.append(Integer.toString(size));
       myTextFeedback.dimension("dp");
     }
   } else {
     if (staticText.length() > 2) {
       int index = staticText.length() - 2;
       String dimension = staticText.substring(index);
       if (ArrayUtil.indexOf(ResourceRenderer.DIMENSIONS, dimension) != -1) {
         myTextFeedback.append(staticText.substring(0, index));
         myTextFeedback.dimension(dimension);
       } else {
         myTextFeedback.append(staticText);
       }
     } else {
       myTextFeedback.append(staticText);
     }
   }
 }
  public Object deserializeInto(@NotNull Object result, @NotNull Element element) {
    Set<Binding> bindings = myPropertyBindings.keySet();
    MultiMap<Binding, Object> data = MultiMap.createSmartList();
    nextNode:
    for (Object child : ContainerUtil.concat(element.getContent(), element.getAttributes())) {
      if (XmlSerializerImpl.isIgnoredNode(child)) {
        continue;
      }

      for (Binding binding : bindings) {
        if (binding.isBoundTo(child)) {
          data.putValue(binding, child);
          continue nextNode;
        }
      }

      final String message = "Format error: no binding for " + child + " inside " + this;
      LOG.debug(message);
      Logger.getInstance(myBeanClass.getName()).debug(message);
      Logger.getInstance("#" + myBeanClass.getName()).debug(message);
    }

    for (Binding binding : data.keySet()) {
      binding.deserialize(result, ArrayUtil.toObjectArray(data.get(binding)));
    }

    return result;
  }
  @NotNull
  public static PsiClassType[] getExtendsListTypes(GrTypeDefinition grType) {
    final PsiClassType[] extendsTypes = getReferenceListTypes(grType.getExtendsClause());
    if (grType.isInterface()) {
      return extendsTypes;
    }

    for (PsiClassType type : extendsTypes) {
      final PsiClass superClass = type.resolve();
      if (superClass instanceof GrTypeDefinition && !superClass.isInterface()
          || superClass != null
              && GroovyCommonClassNames.GROOVY_OBJECT_SUPPORT.equals(
                  superClass.getQualifiedName())) {
        return extendsTypes;
      }
    }

    PsiClass grObSupport =
        GroovyPsiManager.getInstance(grType.getProject())
            .findClassWithCache(
                GroovyCommonClassNames.GROOVY_OBJECT_SUPPORT, grType.getResolveScope());
    if (grObSupport != null) {
      final PsiClassType type =
          JavaPsiFacade.getInstance(grType.getProject())
              .getElementFactory()
              .createType(grObSupport);
      return ArrayUtil.append(extendsTypes, type, PsiClassType.ARRAY_FACTORY);
    }
    return extendsTypes;
  }
Example #28
0
  private NamesByExprInfo suggestVariableNameByExpression(
      PsiExpression expr, VariableKind variableKind, boolean correctKeywords) {

    final LinkedHashSet<String> names = new LinkedHashSet<String>();
    final String[] fromLiterals =
        suggestVariableNameFromLiterals(expr, variableKind, correctKeywords);
    if (fromLiterals != null) {
      ContainerUtil.addAll(names, fromLiterals);
    }

    ContainerUtil.addAll(
        names,
        suggestVariableNameByExpressionOnly(expr, variableKind, correctKeywords, false).names);
    ContainerUtil.addAll(
        names, suggestVariableNameByExpressionPlace(expr, variableKind, correctKeywords).names);

    PsiType type = expr.getType();
    if (type != null) {
      ContainerUtil.addAll(names, suggestVariableNameByType(type, variableKind, correctKeywords));
    }
    ContainerUtil.addAll(
        names,
        suggestVariableNameByExpressionOnly(expr, variableKind, correctKeywords, true).names);

    String[] namesArray = ArrayUtil.toStringArray(names);
    String propertyName =
        suggestVariableNameByExpressionOnly(expr, variableKind, correctKeywords, false).propertyName
                != null
            ? suggestVariableNameByExpressionOnly(expr, variableKind, correctKeywords, false)
                .propertyName
            : suggestVariableNameByExpressionPlace(expr, variableKind, correctKeywords)
                .propertyName;
    return new NamesByExprInfo(propertyName, namesArray);
  }
 private void appendChosenAnnotationsRoot(
     @NotNull final OrderEntry entry, @NotNull final VirtualFile vFile) {
   if (entry instanceof LibraryOrderEntry) {
     Library library = ((LibraryOrderEntry) entry).getLibrary();
     LOG.assertTrue(library != null);
     final ModifiableRootModel rootModel =
         ModuleRootManager.getInstance(entry.getOwnerModule()).getModifiableModel();
     final Library.ModifiableModel model = library.getModifiableModel();
     model.addRoot(vFile, AnnotationOrderRootType.getInstance());
     model.commit();
     rootModel.commit();
   } else if (entry instanceof ModuleSourceOrderEntry) {
     final ModifiableRootModel model =
         ModuleRootManager.getInstance(entry.getOwnerModule()).getModifiableModel();
     final JavaModuleExternalPaths extension =
         model.getModuleExtension(JavaModuleExternalPaths.class);
     extension.setExternalAnnotationUrls(
         ArrayUtil.mergeArrays(extension.getExternalAnnotationsUrls(), vFile.getUrl()));
     model.commit();
   } else if (entry instanceof JdkOrderEntry) {
     final SdkModificator sdkModificator = ((JdkOrderEntry) entry).getJdk().getSdkModificator();
     sdkModificator.addRoot(vFile, AnnotationOrderRootType.getInstance());
     sdkModificator.commitChanges();
   }
   myExternalAnnotations.clear();
 }
Example #30
0
  private static String[] getSuggestionsByValue(final String stringValue) {
    List<String> result = new ArrayList<String>();
    StringBuffer currentWord = new StringBuffer();

    boolean prevIsUpperCase = false;

    for (int i = 0; i < stringValue.length(); i++) {
      final char c = stringValue.charAt(i);
      if (Character.isUpperCase(c)) {
        if (currentWord.length() > 0 && !prevIsUpperCase) {
          result.add(currentWord.toString());
          currentWord = new StringBuffer();
        }
        currentWord.append(c);
      } else if (Character.isLowerCase(c)) {
        currentWord.append(Character.toUpperCase(c));
      } else if (Character.isJavaIdentifierPart(c) && c != '_') {
        if (Character.isJavaIdentifierStart(c) || currentWord.length() > 0 || !result.isEmpty()) {
          currentWord.append(c);
        }
      } else {
        if (currentWord.length() > 0) {
          result.add(currentWord.toString());
          currentWord = new StringBuffer();
        }
      }

      prevIsUpperCase = Character.isUpperCase(c);
    }

    if (currentWord.length() > 0) {
      result.add(currentWord.toString());
    }
    return ArrayUtil.toStringArray(result);
  }