private void updateRightTreeModel() {
   Set<PsiFile> deps = new HashSet<PsiFile>();
   Set<PsiFile> scope = getSelectedScope(myLeftTree);
   myIllegalsInRightTree = new HashSet<PsiFile>();
   for (PsiFile psiFile : scope) {
     Map<DependencyRule, Set<PsiFile>> illegalDeps = myIllegalDependencies.get(psiFile);
     if (illegalDeps != null) {
       for (final DependencyRule rule : illegalDeps.keySet()) {
         myIllegalsInRightTree.addAll(illegalDeps.get(rule));
       }
     }
     final Set<PsiFile> psiFiles = myDependencies.get(psiFile);
     if (psiFiles != null) {
       for (PsiFile file : psiFiles) {
         if (file != null && file.isValid()) {
           deps.add(file);
         }
       }
     }
   }
   deps.removeAll(scope);
   myRightTreeExpansionMonitor.freeze();
   myRightTree.setModel(buildTreeModel(deps, myRightTreeMarker));
   myRightTreeExpansionMonitor.restore();
   expandFirstLevel(myRightTree);
 }
  private static void checkResult(
      String[] fileNames,
      final ArrayList<PsiFile> filesList,
      int[] starts,
      final IntArrayList startsList,
      int[] ends,
      final IntArrayList endsList) {
    List<SearchResult> expected = new ArrayList<SearchResult>();
    for (int i = 0; i < fileNames.length; i++) {
      String fileName = fileNames[i];
      expected.add(
          new SearchResult(
              fileName, i < starts.length ? starts[i] : -1, i < ends.length ? ends[i] : -1));
    }

    List<SearchResult> actual = new ArrayList<SearchResult>();
    for (int i = 0; i < filesList.size(); i++) {
      PsiFile psiFile = filesList.get(i);
      actual.add(
          new SearchResult(
              psiFile.getName(),
              i < starts.length ? startsList.get(i) : -1,
              i < ends.length ? endsList.get(i) : -1));
    }

    Collections.sort(expected);
    Collections.sort(actual);

    assertEquals("Usages don't match", expected, actual);
  }
  private void updateEditorText() {
    disposeNonTextEditor();

    final PsiElement elt = myElements[myIndex].getNavigationElement();
    Project project = elt.getProject();
    PsiFile psiFile = getContainingFile(elt);
    final VirtualFile vFile = psiFile.getVirtualFile();
    if (vFile == null) return;
    final FileEditorProvider[] providers =
        FileEditorProviderManager.getInstance().getProviders(project, vFile);
    for (FileEditorProvider provider : providers) {
      if (provider instanceof TextEditorProvider) {
        updateTextElement(elt);
        myBinarySwitch.show(myViewingPanel, TEXT_PAGE_KEY);
        break;
      } else if (provider.accept(project, vFile)) {
        myCurrentNonTextEditorProvider = provider;
        myNonTextEditor = myCurrentNonTextEditorProvider.createEditor(project, vFile);
        myBinaryPanel.removeAll();
        myBinaryPanel.add(myNonTextEditor.getComponent());
        myBinarySwitch.show(myViewingPanel, BINARY_PAGE_KEY);
        break;
      }
    }
  }
  public AddModuleDependencyFix(
      Module currentModule, VirtualFile classVFile, PsiClass[] classes, PsiReference reference) {
    final PsiElement psiElement = reference.getElement();
    final Project project = psiElement.getProject();
    final JavaPsiFacade facade = JavaPsiFacade.getInstance(project);
    final ProjectFileIndex fileIndex = ProjectRootManager.getInstance(project).getFileIndex();

    for (PsiClass aClass : classes) {
      if (!facade.getResolveHelper().isAccessible(aClass, psiElement, aClass)) continue;
      PsiFile psiFile = aClass.getContainingFile();
      if (psiFile == null) continue;
      VirtualFile virtualFile = psiFile.getVirtualFile();
      if (virtualFile == null) continue;
      final Module classModule = fileIndex.getModuleForFile(virtualFile);
      if (classModule != null
          && classModule != currentModule
          && !ModuleRootManager.getInstance(currentModule).isDependsOn(classModule)) {
        myModules.add(classModule);
      }
    }
    myCurrentModule = currentModule;
    myClassVFile = classVFile;
    myClasses = classes;
    myReference = reference;
  }
Exemplo n.º 5
0
  @Override
  public PsiElement getTopLevelElement(PsiElement element) {
    PsiFile file = element.getContainingFile();
    if (file == null || !(file instanceof JetFile)) return null;

    VirtualFile virtualFile = file.getVirtualFile();
    if (!fileInRoots(virtualFile)) return file;

    PsiElement current = element;
    while (current != null) {
      if (isSelectable(current)) break;
      current = current.getParent();
    }

    if (current instanceof JetFile) {
      List<JetDeclaration> declarations = ((JetFile) current).getDeclarations();
      String nameWithoutExtension =
          virtualFile != null ? virtualFile.getNameWithoutExtension() : file.getName();
      if (declarations.size() == 1
          && declarations.get(0) instanceof JetClassOrObject
          && nameWithoutExtension.equals(declarations.get(0).getName())) {
        current = declarations.get(0);
      }
    }

    return current != null ? current : file;
  }
Exemplo n.º 6
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);
  }
 /**
  * Retrieves indent options for PSI file from an associated document or (if not defined in the
  * document) from file indent options providers.
  *
  * @param file The PSI file to retrieve options for.
  * @param formatRange The text range within the file for formatting purposes or null if there is
  *     either no specific range or multiple ranges. If the range covers the entire file (full
  *     reformat), options stored in the document are ignored and indent options are taken from
  *     file indent options providers.
  * @param ignoreDocOptions Ignore options stored in the document and use file indent options
  *     providers even if there is no text range or the text range doesn't cover the entire file.
  * @param providerProcessor A callback object containing a reference to indent option provider
  *     which has returned indent options.
  * @return Indent options from the associated document or file indent options providers.
  * @see com.intellij.psi.codeStyle.FileIndentOptionsProvider
  */
 @NotNull
 public IndentOptions getIndentOptionsByFile(
     @Nullable PsiFile file,
     @Nullable TextRange formatRange,
     boolean ignoreDocOptions,
     @Nullable Processor<FileIndentOptionsProvider> providerProcessor) {
   if (file != null && file.isValid() && file.isWritable()) {
     boolean isFullReformat = isFileFullyCoveredByRange(file, formatRange);
     if (!ignoreDocOptions && !isFullReformat) {
       IndentOptions docOptions = IndentOptions.retrieveFromAssociatedDocument(file);
       if (docOptions != null) return docOptions;
     }
     FileIndentOptionsProvider[] providers =
         Extensions.getExtensions(FileIndentOptionsProvider.EP_NAME);
     for (FileIndentOptionsProvider provider : providers) {
       if (!isFullReformat || provider.useOnFullReformat()) {
         IndentOptions indentOptions = provider.getIndentOptions(this, file);
         if (indentOptions != null) {
           if (providerProcessor != null) {
             providerProcessor.process(provider);
           }
           logIndentOptions(file, provider, indentOptions);
           return indentOptions;
         }
       }
     }
     return getIndentOptions(file.getFileType());
   } else return OTHER_INDENT_OPTIONS;
 }
  private boolean getStringToReplace(
      int textOffset,
      int textEndOffset,
      Document document,
      FindModel findModel,
      Ref<String> stringToReplace)
      throws FindManager.MalformedReplacementStringException {
    if (textOffset < 0 || textOffset >= document.getTextLength()) {
      return false;
    }
    if (textEndOffset < 0 || textOffset > document.getTextLength()) {
      return false;
    }
    FindManager findManager = FindManager.getInstance(myProject);
    final CharSequence foundString =
        document.getCharsSequence().subSequence(textOffset, textEndOffset);
    PsiFile file = PsiDocumentManager.getInstance(myProject).getPsiFile(document);
    FindResult findResult =
        findManager.findString(
            document.getCharsSequence(),
            textOffset,
            findModel,
            file != null ? file.getVirtualFile() : null);
    if (!findResult.isStringFound()) {
      return false;
    }

    stringToReplace.set(
        FindManager.getInstance(myProject)
            .getStringToReplace(foundString.toString(), findModel, textOffset, document.getText()));

    return true;
  }
Exemplo n.º 9
0
  public static TextWithImports getEditorText(final Editor editor) {
    if (editor == null) {
      return null;
    }
    final Project project = editor.getProject();
    if (project == null) return null;

    String defaultExpression = editor.getSelectionModel().getSelectedText();
    if (defaultExpression == null) {
      int offset = editor.getCaretModel().getOffset();
      PsiFile psiFile = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument());
      if (psiFile != null) {
        PsiElement elementAtCursor = psiFile.findElementAt(offset);
        if (elementAtCursor != null) {
          final EditorTextProvider textProvider =
              EditorTextProvider.EP.forLanguage(elementAtCursor.getLanguage());
          if (textProvider != null) {
            final TextWithImports editorText = textProvider.getEditorText(elementAtCursor);
            if (editorText != null) return editorText;
          }
        }
      }
    } else {
      return new TextWithImportsImpl(CodeFragmentKind.EXPRESSION, defaultExpression);
    }
    return null;
  }
  protected void moveCaretInsideBracesIfAny(
      @NotNull final Editor editor, @NotNull final PsiFile file)
      throws IncorrectOperationException {
    int caretOffset = editor.getCaretModel().getOffset();
    final CharSequence chars = editor.getDocument().getCharsSequence();

    if (CharArrayUtil.regionMatches(chars, caretOffset, "{}")) {
      caretOffset += 2;
    } else if (CharArrayUtil.regionMatches(chars, caretOffset, "{\n}")) {
      caretOffset += 3;
    }

    caretOffset = CharArrayUtil.shiftBackward(chars, caretOffset - 1, " \t") + 1;

    if (CharArrayUtil.regionMatches(chars, caretOffset - "{}".length(), "{}")
        || CharArrayUtil.regionMatches(chars, caretOffset - "{\n}".length(), "{\n}")) {
      commit(editor);
      final CodeStyleSettings settings = CodeStyleSettingsManager.getSettings(file.getProject());
      final boolean old = settings.KEEP_SIMPLE_BLOCKS_IN_ONE_LINE;
      settings.KEEP_SIMPLE_BLOCKS_IN_ONE_LINE = false;
      PsiElement elt =
          PsiTreeUtil.getParentOfType(file.findElementAt(caretOffset - 1), PsiCodeBlock.class);
      reformat(elt);
      settings.KEEP_SIMPLE_BLOCKS_IN_ONE_LINE = old;
      editor.getCaretModel().moveToOffset(caretOffset - 1);
    }
  }
Exemplo n.º 11
0
  public static ArrayList<TwigMacro> getImportedMacrosNamespaces(PsiFile psiFile) {

    ArrayList<TwigMacro> macros = new ArrayList<TwigMacro>();

    String str = psiFile.getText();

    // {% import '@foo/bar.html.twig' as macro1 %}
    String regex = "\\{%\\s?import\\s?['\"](.*?)['\"]\\s?as\\s?(.*?)\\s?%}";
    Matcher matcher = Pattern.compile(regex).matcher(str.replace("\n", " "));

    Map<String, TwigFile> twigFilesByName = TwigHelper.getTwigFilesByName(psiFile.getProject());
    while (matcher.find()) {

      String templateName = matcher.group(1);
      String asName = matcher.group(2);

      if (twigFilesByName.containsKey(templateName)) {
        for (Map.Entry<String, String> entry :
            new TwigMarcoParser().getMacros(twigFilesByName.get(templateName)).entrySet()) {
          macros.add(new TwigMacro(asName + '.' + entry.getKey(), templateName));
        }
      }
    }

    return macros;
  }
  public boolean commitTransaction(final Document document) {
    ApplicationManager.getApplication().assertIsDispatchThread();
    final DocumentChangeTransaction documentChangeTransaction = removeTransaction(document);
    if (documentChangeTransaction == null) return false;
    final PsiFile changeScope = documentChangeTransaction.myChangeScope;
    try {
      mySyncDocument = document;

      final PsiTreeChangeEventImpl fakeEvent = new PsiTreeChangeEventImpl(changeScope.getManager());
      fakeEvent.setParent(changeScope);
      fakeEvent.setFile(changeScope);
      checkPsiModificationAllowed(fakeEvent);
      doSync(
          fakeEvent,
          true,
          new DocSyncAction() {
            @Override
            public void syncDocument(
                @NotNull Document document, @NotNull PsiTreeChangeEventImpl event) {
              doCommitTransaction(document, documentChangeTransaction);
            }
          });
      myBus
          .syncPublisher(PsiDocumentTransactionListener.TOPIC)
          .transactionCompleted(document, changeScope);
    } catch (Throwable e) {
      myPsiDocumentManager.forceReload(
          changeScope.getViewProvider().getVirtualFile(), changeScope.getViewProvider());
      ExceptionUtil.rethrowAllAsUnchecked(e);
    } finally {
      mySyncDocument = null;
    }
    return true;
  }
  private void doSync(
      @NotNull final PsiTreeChangeEvent event,
      boolean force,
      @NotNull final DocSyncAction syncAction) {
    if (!toProcessPsiEvent()) return;
    final PsiFile psiFile = event.getFile();
    if (!(psiFile instanceof PsiFileEx) || !((PsiFileEx) psiFile).isContentsLoaded()) return;

    final DocumentEx document = getCachedDocument(psiFile, force);
    if (document == null) return;

    performAtomically(
        psiFile,
        new Runnable() {
          @Override
          public void run() {
            syncAction.syncDocument(document, (PsiTreeChangeEventImpl) event);
          }
        });

    final boolean insideTransaction = myTransactionsMap.containsKey(document);
    if (!insideTransaction) {
      document.setModificationStamp(psiFile.getViewProvider().getModificationStamp());
    }
  }
 public String getReportText() {
   final Element rootElement = new Element("root");
   rootElement.setAttribute("isBackward", String.valueOf(!myForward));
   final List<PsiFile> files = new ArrayList<PsiFile>(myDependencies.keySet());
   Collections.sort(
       files,
       new Comparator<PsiFile>() {
         @Override
         public int compare(PsiFile f1, PsiFile f2) {
           final VirtualFile virtualFile1 = f1.getVirtualFile();
           final VirtualFile virtualFile2 = f2.getVirtualFile();
           if (virtualFile1 != null && virtualFile2 != null) {
             return virtualFile1.getPath().compareToIgnoreCase(virtualFile2.getPath());
           }
           return 0;
         }
       });
   for (PsiFile file : files) {
     final Element fileElement = new Element("file");
     fileElement.setAttribute("path", file.getVirtualFile().getPath());
     for (PsiFile dep : myDependencies.get(file)) {
       Element depElement = new Element("dependency");
       depElement.setAttribute("path", dep.getVirtualFile().getPath());
       fileElement.addContent(depElement);
     }
     rootElement.addContent(fileElement);
   }
   PathMacroManager.getInstance(myProject).collapsePaths(rootElement);
   return JDOMUtil.writeDocument(new Document(rootElement), SystemProperties.getLineSeparator());
 }
Exemplo n.º 15
0
  @Override
  public boolean isInProject(@NotNull PsiElement element) {
    PsiFile file = element.getContainingFile();
    if (file != null
        && file.isPhysical()
        && file.getViewProvider().getVirtualFile() instanceof LightVirtualFile) return true;

    if (element instanceof PsiDirectoryContainer) {
      PsiDirectory[] dirs = ((PsiDirectoryContainer) element).getDirectories();
      for (PsiDirectory dir : dirs) {
        if (!isInProject(dir)) return false;
      }
      return true;
    }

    VirtualFile virtualFile = null;
    if (file != null) {
      virtualFile = file.getViewProvider().getVirtualFile();
    } else if (element instanceof PsiFileSystemItem) {
      virtualFile = ((PsiFileSystemItem) element).getVirtualFile();
    }

    if (virtualFile != null) {
      return myExcludedFileIndex.isInContent(virtualFile);
    }
    return false;
  }
 public XmlTagTreeHighlightingPass(@NotNull PsiFile file, @NotNull EditorEx editor) {
   super(file.getProject(), editor.getDocument(), true);
   myFile = file;
   myEditor = editor;
   final FileViewProvider viewProvider = file.getManager().findViewProvider(file.getVirtualFile());
   myInfoProvider = BreadcrumbsXmlWrapper.findInfoProvider(viewProvider);
 }
 @Nullable
 private static PsiElement getSelectedPsiElement(
     final DataContext dataContext, final Project project) {
   PsiElement element = null;
   final Editor editor = CommonDataKeys.EDITOR.getData(dataContext);
   if (editor != null) {
     final PsiFile psiFile =
         PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument());
     if (psiFile != null) {
       final int offset = editor.getCaretModel().getOffset();
       element = psiFile.findElementAt(offset);
       if (element == null && offset > 0 && offset == psiFile.getTextLength()) {
         element = psiFile.findElementAt(offset - 1);
       }
     }
   }
   if (element == null) {
     final PsiElement[] elements = LangDataKeys.PSI_ELEMENT_ARRAY.getData(dataContext);
     element = elements != null && elements.length > 0 ? elements[0] : null;
   }
   if (element == null) {
     final VirtualFile[] files = CommonDataKeys.VIRTUAL_FILE_ARRAY.getData(dataContext);
     if (files != null && files.length > 0) {
       element = PsiManager.getInstance(project).findFile(files[0]);
     }
   }
   return element;
 }
  @Override
  @Nullable
  public GlobalSearchScope getSearchScope() {
    GlobalSearchScope scope = null;

    Module[] modules = getConvertContextModules();
    if (modules.length != 0) {

      PsiFile file = getFile();
      file = file.getOriginalFile();
      VirtualFile virtualFile = file.getVirtualFile();
      if (virtualFile != null) {
        ProjectFileIndex fileIndex =
            ProjectRootManager.getInstance(file.getProject()).getFileIndex();
        boolean tests = fileIndex.isInTestSourceContent(virtualFile);

        for (Module module : modules) {
          if (scope == null) {
            scope = module.getModuleRuntimeScope(tests);
          } else {
            scope = scope.union(module.getModuleRuntimeScope(tests));
          }
        }
      }
    }
    return scope; // ??? scope == null ? GlobalSearchScope.allScope(getProject()) : scope; ???
  }
Exemplo n.º 19
0
  /**
   * @return true, if the element contains a reference to a different class than fullyQualifiedName
   *     but which has the same class name
   */
  public static boolean containsConflictingReference(PsiFile element, String fullyQualifiedName) {
    final Map<String, Boolean> cachedValue =
        CachedValuesManager.getManager(element.getProject())
            .getCachedValue(
                element,
                new CachedValueProvider<Map<String, Boolean>>() {
                  @Nullable
                  @Override
                  public Result<Map<String, Boolean>> compute() {
                    return new Result<Map<String, Boolean>>(
                        Collections.synchronizedMap(new HashMap<String, Boolean>()),
                        PsiModificationTracker.MODIFICATION_COUNT);
                  }
                });
    Boolean conflictingRef = cachedValue.get(fullyQualifiedName);
    if (conflictingRef != null) {
      return conflictingRef.booleanValue();
    }

    final ConflictingClassReferenceVisitor visitor =
        new ConflictingClassReferenceVisitor(fullyQualifiedName);
    element.accept(visitor);
    conflictingRef = visitor.isConflictingReferenceFound();
    cachedValue.put(fullyQualifiedName, conflictingRef);

    return conflictingRef.booleanValue();
  }
 public void testNoRecursiveImports() throws Exception {
   myFixture.addFileToProject("file2.dart", "inFile2(){}");
   myFixture.addFileToProject("file1.dart", "import 'file2.dart'\n inFile1(){}");
   myFixture.addFileToProject(
       "file.dart",
       "library fileLib;\n"
           + "import 'file1.dart';\n"
           + "part 'filePart1.dart';\n"
           + "part 'filePart2.dart';\n"
           + "inFile(){}");
   myFixture.addFileToProject("filePart1.dart", "part of fileLib;\n" + "inFilePart1(){}");
   final PsiFile file =
       myFixture.addFileToProject(
           "filePart2.dart",
           "part of fileLib;\n"
               + "inFilePart2(){\n"
               + "  <caret expected='filePart1.dart -> inFilePart1'>inFilePart1()\n"
               + "  <caret expected='filePart2.dart -> inFilePart2'>inFilePart2()\n"
               + "  <caret expected='file.dart -> inFile'>inFile()\n"
               + "  <caret expected='file1.dart -> inFile1'>inFile1()\n"
               + "  <caret expected=''>inFile2()\n"
               + "}");
   myFixture.openFileInEditor(file.getVirtualFile());
   doTest(myFixture);
 }
Exemplo n.º 21
0
  private static void logStats(Collection<PsiFile> otherFiles, long start) {
    long time = System.currentTimeMillis() - start;

    final Multiset<String> stats = HashMultiset.create();
    for (PsiFile file : otherFiles) {
      stats.add(
          StringUtil.notNullize(file.getViewProvider().getVirtualFile().getExtension())
              .toLowerCase());
    }

    List<String> extensions = ContainerUtil.newArrayList(stats.elementSet());
    Collections.sort(
        extensions,
        new Comparator<String>() {
          @Override
          public int compare(String o1, String o2) {
            return stats.count(o2) - stats.count(o1);
          }
        });

    String message =
        "Search in "
            + otherFiles.size()
            + " files with unknown types took "
            + time
            + "ms.\n"
            + "Mapping their extensions to an existing file type (e.g. Plain Text) might speed up the search.\n"
            + "Most frequent non-indexed file extensions: ";
    for (int i = 0; i < Math.min(10, extensions.size()); i++) {
      String extension = extensions.get(i);
      message += extension + "(" + stats.count(extension) + ") ";
    }
    LOG.info(message);
  }
 public void testTransitiveShowHide() throws Exception {
   myFixture.addFileToProject(
       "file1part.dart",
       "part of file1lib;\n" + "var foo1, foo2, foo3, foo4, foo5, foo6, foo7, foo8, foo9;");
   myFixture.addFileToProject("file1.dart", "library file1lib;\n" + "part 'file1part.dart';");
   myFixture.addFileToProject("file2.dart", "export 'file1.dart' show foo1, foo2, foo3, foo4;");
   myFixture.addFileToProject("file3.dart", "export 'file1.dart' show foo5, foo6, foo7, foo8;");
   myFixture.addFileToProject(
       "file4.dart", "export 'file2.dart' show foo1, foo2, foo3, foo5, foo6, foo7, foo8, foo9;");
   myFixture.addFileToProject("file5.dart", "export 'file3.dart' hide foo7, foo8;");
   myFixture.addFileToProject(
       "file.dart",
       "library filelib;\n"
           + "import 'file4.dart' hide foo3;\n"
           + "import 'file5.dart' show foo1, foo2, foo3, foo4, foo5, foo7, foo8, foo9;\n"
           + "part 'filepart.dart';");
   final PsiFile file =
       myFixture.addFileToProject(
           "filepart.dart",
           "part of filelib;\n"
               + "main(){\n"
               + "  <caret expected='file1part.dart -> foo1'>foo1;\n"
               + "  <caret expected='file1part.dart -> foo2'>foo2;\n"
               + "  <caret expected=''>foo3;\n"
               + "  <caret expected=''>foo4;\n"
               + "  <caret expected='file1part.dart -> foo5'>foo5;\n"
               + "  <caret expected=''>foo6;\n"
               + "  <caret expected=''>foo7;\n"
               + "  <caret expected=''>foo8;\n"
               + "  <caret expected=''>foo9;\n"
               + "}");
   myFixture.openFileInEditor(file.getVirtualFile());
   doTest(myFixture);
 }
  private void checkPsiIsCorrect(final FileViewProvider key) {
    PsiFile actualPsi = key.getPsi(key.getBaseLanguage());

    PsiTreeDebugBuilder treeDebugBuilder =
        new PsiTreeDebugBuilder().setShowErrorElements(false).setShowWhiteSpaces(false);

    String actualPsiTree = treeDebugBuilder.psiToString(actualPsi);

    String fileName = key.getVirtualFile().getName();
    PsiFile psi =
        PsiFileFactory.getInstance(myProject)
            .createFileFromText(
                fileName,
                FileTypeManager.getInstance().getFileTypeByFileName(fileName),
                actualPsi.getNode().getText(),
                LocalTimeCounter.currentTime(),
                false);

    if (actualPsi.getClass().equals(psi.getClass())) {
      String expectedPsi = treeDebugBuilder.psiToString(psi);

      if (!expectedPsi.equals(actualPsiTree)) {
        myReformatElements.clear();
        assert expectedPsi.equals(actualPsiTree)
            : "Refactored psi should be the same as result of parsing";
      }
    }
  }
  public void testTransitivePathPackageDependencies() {
    myFixture.addFileToProject(
        "project1/pubspec.yaml",
        "name: project1\n" + "dependencies:\n" + "  project2:\n" + "    path: ../project2\n");
    myFixture.addFileToProject(
        "project1/.packages",
        "project1:lib/\n" + "project2:../project2/lib/\n" + "project3:../project3/lib/\n");
    myFixture.addFileToProject(
        "project2/pubspec.yaml",
        "name: project2\n"
            + "dependencies:\n"
            + "  project1:\n"
            + "    path: ../project1\n"
            + "  project3:\n"
            + "    path: ../project3\n");
    myFixture.addFileToProject("project3/pubspec.yaml", "name: project3\n");
    myFixture.addFileToProject("project3/.packages", "project3:lib/\n");

    myFixture.addFileToProject("project2/lib/in_lib2.dart", "inLib2(){}");
    myFixture.addFileToProject("project3/lib/in_lib3.dart", "inLib3(){}");

    final PsiFile psiFile =
        myFixture.addFileToProject(
            "project1/lib/foo.dart",
            "import 'package:project2/in_lib2.dart';\n"
                + "import 'package:project3/in_lib3.dart';\n"
                + "main(){\n"
                + "  inLib2<caret expected='project2/lib/in_lib2.dart -> inLib2'>();\n"
                + "  inLib3<caret expected='project3/lib/in_lib3.dart -> inLib3'>();\n"
                + "}");
    myFixture.openFileInEditor(psiFile.getVirtualFile());
    doTest(myFixture);
  }
  private void highlightInjectedSyntax(
      @NotNull PsiFile injectedPsi, @NotNull HighlightInfoHolder holder) {
    List<Trinity<IElementType, SmartPsiElementPointer<PsiLanguageInjectionHost>, TextRange>>
        tokens = InjectedLanguageUtil.getHighlightTokens(injectedPsi);
    if (tokens == null) return;

    final Language injectedLanguage = injectedPsi.getLanguage();
    Project project = injectedPsi.getProject();
    SyntaxHighlighter syntaxHighlighter =
        SyntaxHighlighterFactory.getSyntaxHighlighter(
            injectedLanguage, project, injectedPsi.getVirtualFile());
    final TextAttributes defaultAttrs = myGlobalScheme.getAttributes(HighlighterColors.TEXT);

    for (Trinity<IElementType, SmartPsiElementPointer<PsiLanguageInjectionHost>, TextRange> token :
        tokens) {
      ProgressManager.checkCanceled();
      IElementType tokenType = token.getFirst();
      PsiLanguageInjectionHost injectionHost = token.getSecond().getElement();
      if (injectionHost == null) continue;
      TextRange textRange = token.getThird();
      TextAttributesKey[] keys = syntaxHighlighter.getTokenHighlights(tokenType);
      if (textRange.getLength() == 0) continue;

      TextRange annRange = textRange.shiftRight(injectionHost.getTextRange().getStartOffset());
      // force attribute colors to override host' ones
      TextAttributes attributes = null;
      for (TextAttributesKey key : keys) {
        TextAttributes attrs2 = myGlobalScheme.getAttributes(key);
        if (attrs2 != null) {
          attributes = attributes == null ? attrs2 : TextAttributes.merge(attributes, attrs2);
        }
      }
      TextAttributes forcedAttributes;
      if (attributes == null || attributes.isEmpty() || attributes.equals(defaultAttrs)) {
        forcedAttributes = TextAttributes.ERASE_MARKER;
      } else {
        HighlightInfo info =
            HighlightInfo.newHighlightInfo(HighlightInfoType.INJECTED_LANGUAGE_FRAGMENT)
                .range(annRange)
                .textAttributes(TextAttributes.ERASE_MARKER)
                .createUnconditionally();
        holder.add(info);

        forcedAttributes =
            new TextAttributes(
                attributes.getForegroundColor(),
                attributes.getBackgroundColor(),
                attributes.getEffectColor(),
                attributes.getEffectType(),
                attributes.getFontType());
      }

      HighlightInfo info =
          HighlightInfo.newHighlightInfo(HighlightInfoType.INJECTED_LANGUAGE_FRAGMENT)
              .range(annRange)
              .textAttributes(forcedAttributes)
              .createUnconditionally();
      holder.add(info);
    }
  }
  @Nullable
  private Navigatable getSelectedNavigatable(
      final CommonProblemDescriptor descriptor, final PsiElement psiElement) {
    if (descriptor instanceof ProblemDescriptorBase) {
      Navigatable navigatable = ((ProblemDescriptorBase) descriptor).getNavigatable();
      if (navigatable != null) {
        return navigatable;
      }
    }
    if (psiElement == null || !psiElement.isValid()) return null;
    PsiFile containingFile = psiElement.getContainingFile();
    VirtualFile virtualFile = containingFile == null ? null : containingFile.getVirtualFile();

    if (virtualFile != null) {
      int startOffset = psiElement.getTextOffset();
      if (descriptor instanceof ProblemDescriptorBase) {
        final TextRange textRange =
            ((ProblemDescriptorBase) descriptor).getTextRangeForNavigation();
        if (textRange != null) {
          if (virtualFile instanceof VirtualFileWindow) {
            virtualFile = ((VirtualFileWindow) virtualFile).getDelegate();
          }
          startOffset = textRange.getStartOffset();
        }
      }
      return new OpenFileDescriptor(myProject, virtualFile, startOffset);
    }
    return null;
  }
  @NotNull
  private static String findMainClass(VirtualFile gradleHome, VirtualFile script, Project project) {
    final String userDefined = System.getProperty("gradle.launcher.class");
    if (StringUtil.isNotEmpty(userDefined)) {
      return userDefined;
    }

    VirtualFile launcher = gradleHome.findFileByRelativePath("bin/gradle");
    if (launcher == null) {
      launcher = gradleHome.findFileByRelativePath("bin/gradle.bat");
    }
    if (launcher != null) {
      try {
        final String text = StringUtil.convertLineSeparators(VfsUtilCore.loadText(launcher));
        final Matcher matcher = MAIN_CLASS_NAME_PATTERN.matcher(text);
        if (matcher.find()) {
          String candidate = matcher.group(1);
          if (StringUtil.isNotEmpty(candidate)) {
            return candidate;
          }
        }
      } catch (IOException ignored) {
      }
    }

    final PsiFile grFile = PsiManager.getInstance(project).findFile(script);
    if (grFile != null
        && JavaPsiFacade.getInstance(project)
                .findClass("org.gradle.BootstrapMain", grFile.getResolveScope())
            != null) {
      return "org.gradle.BootstrapMain";
    }

    return "org.gradle.launcher.GradleMain";
  }
  public static boolean isValidName(
      final Project project, final PsiElement psiElement, final String newName) {
    if (newName == null || newName.length() == 0) {
      return false;
    }
    final Condition<String> inputValidator =
        RenameInputValidatorRegistry.getInputValidator(psiElement);
    if (inputValidator != null) {
      return inputValidator.value(newName);
    }
    if (psiElement instanceof PsiFile || psiElement instanceof PsiDirectory) {
      return newName.indexOf('\\') < 0 && newName.indexOf('/') < 0;
    }
    if (psiElement instanceof PomTargetPsiElement) {
      return !StringUtil.isEmptyOrSpaces(newName);
    }

    final PsiFile file = psiElement.getContainingFile();
    final Language elementLanguage = psiElement.getLanguage();

    final Language fileLanguage = file == null ? null : file.getLanguage();
    Language language =
        fileLanguage == null
            ? elementLanguage
            : fileLanguage.isKindOf(elementLanguage) ? fileLanguage : elementLanguage;

    return LanguageNamesValidation.INSTANCE
        .forLanguage(language)
        .isIdentifier(newName.trim(), project);
  }
 private static void reportInconsistentLength(
     PsiFile file, CharSequence newFileText, ASTNode node, int start, int end) {
   String message =
       "Index out of bounds: type="
           + node.getElementType()
           + "; file="
           + file
           + "; file.class="
           + file.getClass()
           + "; start="
           + start
           + "; end="
           + end
           + "; length="
           + node.getTextLength();
   String newTextBefore = newFileText.subSequence(0, start).toString();
   String oldTextBefore = file.getText().subSequence(0, start).toString();
   if (oldTextBefore.equals(newTextBefore)) {
     message += "; oldTextBefore==newTextBefore";
   }
   LOG.error(
       message,
       new Attachment(file.getName() + "_oldNodeText.txt", node.getText()),
       new Attachment(file.getName() + "_oldFileText.txt", file.getText()),
       new Attachment(file.getName() + "_newFileText.txt", newFileText.toString()));
 }
  public void update(final AnActionEvent event) {
    super.update(event);

    final Presentation presentation = event.getPresentation();
    final DataContext context = event.getDataContext();
    Module module = (Module) context.getData(LangDataKeys.MODULE.getName());
    PsiFile currentFile = (PsiFile) context.getData(LangDataKeys.PSI_FILE.getName());
    Editor editor = (Editor) context.getData(PlatformDataKeys.EDITOR.getName());
    // VirtualFile currentFile = (VirtualFile)
    // context.getData(PlatformDataKeys.VIRTUAL_FILE.getName());
    if (currentFile != null && editor != null) {
      boolean isSSFile =
          currentFile
              .getFileType()
              .getDefaultExtension()
              .equals(SilverStripeFileType.DEFAULT_EXTENSION);
      SelectionModel selectionModel = editor.getSelectionModel();
      String selectedText = selectionModel.getSelectedText();
      this.selectedText = selectedText;
      this.selectonModel = selectionModel;
      this.editor = editor;
      this.currentFile = currentFile;
      if (selectedText == null) {
        presentation.setEnabled(false);
      }
      if (!isSSFile) {
        presentation.setEnabled(false);
        presentation.setVisible(false);
      }
    } else {
      presentation.setEnabled(false);
      presentation.setVisible(false);
    }
  }