Java Code Examples for com.intellij.psi.PsiFile

The following are top voted examples for showing how to use com.intellij.psi.PsiFile. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: OpenInExplorer-idea   File: RightAction.java   Source Code and License 7 votes vote down vote up
@Override
public void actionPerformed(AnActionEvent event) {
    // TODO: insert action logic here
    Project project = event.getData(PlatformDataKeys.PROJECT);
    Object nav = event.getData(CommonDataKeys.NAVIGATABLE);
    String path;
    try {
        if (nav instanceof PsiDirectory) {
            PsiDirectory directory = (PsiDirectory) nav;
            path = directory.getVirtualFile().getPath();
        } else {
            PsiFile file = (PsiFile) nav;
            path = file.getVirtualFile().getPath();
        }
        Toast.make(project, MessageType.INFO, "Open: " + path);
        Runtime.getRuntime().exec("cmd /c start " + path);
    } catch (Exception e) {
        e.printStackTrace();
        if (nav instanceof PsiClass) {
            Toast.make(project, MessageType.ERROR, "Could not open the java file, double-click to open.");
            return;
        }

        Toast.make(project, MessageType.ERROR, e.getMessage());
    }
}
 
Example 2
Project: yii2support   File: RenameViewProcessor.java   Source Code and License 6 votes vote down vote up
@Override
public void prepareRenaming(PsiElement psiElement, String s, Map<PsiElement, String> map) {
    renders.clear();
    for (PsiReference reference : findReferences(psiElement)) {
        final PsiElement element = reference.getElement();
        if (element instanceof StringLiteralExpression) {
            String fileName = ((StringLiteralExpression) element).getContents();
            if (fileName.contains("/")) {
                element.getParent().putUserData(RELATIVE_PATH, fileName.substring(0, fileName.lastIndexOf('/') + 1));
                fileName = fileName.substring(fileName.lastIndexOf('/') + 1);
            }
            element.getParent().putUserData(WITH_EXT, fileName.contains("."));

            String realFile = ((PsiFile) psiElement).getName();
            if (realFile.contains(".")) {
                element.getParent().putUserData(OLD_EXT, realFile.substring(realFile.lastIndexOf('.')));
            }

            renders.add(element.getParent());
        }
    }
}
 
Example 3
Project: idea-php-typo3-plugin   File: FunctionCallMatcherInspection.java   Source Code and License 6 votes vote down vote up
private Set<String> getRemovedGlobalFuntions(PhpPsiElement element) {
    Set<PsiElement> elements = new HashSet<>();
    PsiFile[] constantMatcherFiles = FilenameIndex.getFilesByName(element.getProject(), "FunctionCallMatcher.php", GlobalSearchScope.allScope(element.getProject()));
    for (PsiFile file : constantMatcherFiles) {

        Collections.addAll(
                elements,
                PsiTreeUtil.collectElements(file, el -> PlatformPatterns
                        .psiElement(StringLiteralExpression.class)
                        .withParent(
                                PlatformPatterns.psiElement(PhpElementTypes.ARRAY_KEY)
                                        .withAncestor(
                                                4,
                                                PlatformPatterns.psiElement(PhpElementTypes.RETURN)
                                        )
                        )
                        .accepts(el)
                )
        );
    }

    return elements.stream()
            .map(stringLiteral -> "\\" + ((StringLiteralExpression) stringLiteral).getContents())
            .collect(Collectors.toSet());
}
 
Example 4
Project: idea-php-typo3-plugin   File: ClassConstantMatcherInspection.java   Source Code and License 6 votes vote down vote up
private Set<String> getDeprecatedClassConstants(PhpPsiElement element) {
    Set<PsiElement> elements = new HashSet<>();
    PsiFile[] classConstantMatcherFiles = FilenameIndex.getFilesByName(element.getProject(), "ClassConstantMatcher.php", GlobalSearchScope.allScope(element.getProject()));
    for (PsiFile file : classConstantMatcherFiles) {

        Collections.addAll(
                elements,
                PsiTreeUtil.collectElements(file, el -> PlatformPatterns
                        .psiElement(StringLiteralExpression.class)
                        .withParent(
                                PlatformPatterns.psiElement(PhpElementTypes.ARRAY_KEY)
                                        .withAncestor(
                                                4,
                                                PlatformPatterns.psiElement(PhpElementTypes.RETURN)
                                        )
                        )
                        .accepts(el)
                )
        );
    }

    return elements.stream().map(stringLiteral -> ((StringLiteralExpression)stringLiteral).getContents()).collect(Collectors.toSet());
}
 
Example 5
Project: CodeGenerate   File: FieldsDialog.java   Source Code and License 6 votes vote down vote up
public FieldsDialog(ConvertBridge.Operator operator, ClassEntity classEntity,
                    PsiElementFactory factory, PsiClass psiClass, PsiClass aClass, PsiFile file, Project project
        , String generateClassStr) {
    this.operator = operator;
    this.factory = factory;
    this.aClass = aClass;
    this.file = file;
    this.project = project;
    this.psiClass = psiClass;
    this.generateClassStr = generateClassStr;
    setContentPane(contentPane);
    setTitle("Virgo Model");
    getRootPane().setDefaultButton(buttonOK);
    this.setAlwaysOnTop(true);
    initListener(classEntity, generateClassStr);
}
 
Example 6
Project: chocolate-cakephp   File: ControllerMethodLineMarker.java   Source Code and License 6 votes vote down vote up
@Nullable
private LineMarkerInfo getRelatedFiles(@NotNull PsiFile file, @NotNull String controllerName, @NotNull PsiElement element) {
    if (!(element instanceof Method)) {
        return null;
    }
    Method method = (Method)element;
    if (!method.getAccess().isPublic()) {
        return null;
    }
    String methodName = method.getName();
    PsiDirectory appDir = PsiUtil.getAppDirectoryFromFile(file);
    String templatePath = String.format("View/%s/%s.ctp", controllerName, methodName);
    VirtualFile relativeFile = VfsUtil.findRelativeFile(appDir, templatePath);
    if (relativeFile == null) {
        return null;
    }

    PsiFile targetFile = PsiUtil.convertVirtualFileToPsiFile(method.getProject(), relativeFile);
    if (targetFile == null) {
        return null;
    }
    PsiElement targetElement = targetFile.getFirstChild();
    NavigationGutterIconBuilder<PsiElement> builder = NavigationGutterIconBuilder.create(CakeIcons.LOGO).setTarget(targetElement);
    return builder.createLineMarkerInfo(method);
}
 
Example 7
Project: manifold-ij   File: ExtensionClassAnnotator.java   Source Code and License 6 votes vote down vote up
private PsiClass findExtensionClass( PsiElement element )
{
  PsiFile containingFile = element.getContainingFile();
  if( !(containingFile instanceof PsiJavaFileImpl) )
  {
    return null;
  }

  PsiJavaFileImpl file = (PsiJavaFileImpl)containingFile;
  for( PsiClass psiClass : file.getClasses() )
  {
    if( psiClass.getModifierList().findAnnotation( Extension.class.getName() ) != null )
    {
      return psiClass;
    }
  }

  return null;
}
 
Example 8
Project: educational-plugin   File: PyStudyInspectionExtension.java   Source Code and License 6 votes vote down vote up
@Override
public boolean ignoreUnresolvedReference(@NotNull PyElement element, @NotNull PsiReference reference) {
  final PsiFile file = element.getContainingFile();
  final Project project = file.getProject();

  if (StudyTaskManager.getInstance(project).getCourse() == null) {
    return false;
  }
  TaskFile taskFile = StudyUtils.getTaskFile(project, file.getVirtualFile());
  if (taskFile == null || taskFile.isUserCreated() || taskFile.isHighlightErrors()) {
    return false;
  }
  if (PsiTreeUtil.getParentOfType(element, PyImportStatementBase.class) != null) {
    return false;
  }
  return true;
}
 
Example 9
Project: bamboo-soy   File: ClosingTagHandler.java   Source Code and License 6 votes vote down vote up
public void execute(@NotNull Editor editor, char charTyped, @NotNull DataContext dataContext) {
  myOriginalHandler.execute(editor, charTyped, dataContext);
  if (isMatchForClosingTag(editor, charTyped)) {
    int offset = editor.getCaretModel().getOffset();
    PsiFile file = dataContext.getData(LangDataKeys.PSI_FILE);
    if (file == null) {
      return;
    }
    PsiElement el = file.findElementAt(offset - 1);
    TagBlockElement block = (TagBlockElement) PsiTreeUtil
        .findFirstParent(el,
            parent -> parent instanceof TagBlockElement && !(parent instanceof SoyChoiceClause));
    if (block == null) {
      return;
    }
    String closingTag = block.getOpeningTag().generateClosingTag();
    insertClosingTag(editor, offset, closingTag);
    if (editor.getProject() != null) {
      PsiDocumentManager.getInstance(editor.getProject()).commitDocument(editor.getDocument());
      CodeStyleManager.getInstance(editor.getProject()).reformat(block);
    }
  }
}
 
Example 10
Project: idea-php-typo3-plugin   File: ClassNameMatcherInspection.java   Source Code and License 6 votes vote down vote up
private Set<String> getDeprecatedClasses(PhpPsiElement element) {
    Set<PsiElement> elements = new HashSet<>();
    PsiFile[] classNameMatcherFiles = FilenameIndex.getFilesByName(element.getProject(), "ClassNameMatcher.php", GlobalSearchScope.allScope(element.getProject()));
    for (PsiFile file : classNameMatcherFiles) {

        Collections.addAll(
                elements,
                PsiTreeUtil.collectElements(file, el -> PlatformPatterns
                        .psiElement(StringLiteralExpression.class)
                        .withParent(
                                PlatformPatterns.psiElement(PhpElementTypes.ARRAY_KEY)
                                        .withAncestor(
                                                4,
                                                PlatformPatterns.psiElement(PhpElementTypes.RETURN)
                                        )
                        )
                        .accepts(el)
                )
        );
    }

    return elements.stream()
            .map(stringLiteral -> "\\" + ((StringLiteralExpression)stringLiteral).getContents())
            .collect(Collectors.toSet());
}
 
Example 11
Project: educational-plugin   File: StudyShowHintAction.java   Source Code and License 6 votes vote down vote up
public void showHint(Project project) {
  Course course = StudyTaskManager.getInstance(project).getCourse();
  if (course == null) {
    return;
  }
  StudyState studyState = new StudyState(StudyUtils.getSelectedStudyEditor(project));
  if (!studyState.isValid()) {
    return;
  }
  PsiFile file = PsiManager.getInstance(project).findFile(studyState.getVirtualFile());
  final Editor editor = studyState.getEditor();
  int offset = editor.getCaretModel().getOffset();
  AnswerPlaceholder answerPlaceholder = studyState.getTaskFile().getAnswerPlaceholder(offset);
  if (file == null) {
    return;
  }
  EduUsagesCollector.hintShown();

  final StudyToolWindow hintComponent = getHint(project, answerPlaceholder).getStudyToolWindow();
  hintComponent.setPreferredSize(new Dimension(400, 150));
  showHintPopUp(project, studyState, editor, hintComponent);
}
 
Example 12
Project: intellij-plugin   File: AnnotatedInterfaceNode.java   Source Code and License 6 votes vote down vote up
@Override
protected MultiMap<PsiFile, T> computeChildren(@Nullable PsiFile psiFile) {
    MultiMap<PsiFile, T> children = new MultiMap<>();
    Project project = getProject();
    if (project != null) {
        JavaPsiFacade javaPsiFacade = JavaPsiFacade.getInstance(project);
        PsiClass serviceAnnotation = javaPsiFacade.findClass(getAnnotationQName(), GlobalSearchScope.allScope(project));
        if (serviceAnnotation != null) {
            AnnotatedElementsSearch.searchPsiClasses(serviceAnnotation, GlobalSearchScope.allScope(project)).forEach(psiClass -> {
                if (psiClass.isInterface() && isSatisfying(psiClass)) {
                    children.putValue(psiClass.getContainingFile(), createChild(psiClass));
                }
                return true;
            });
        }
    }
    return children;
}
 
Example 13
Project: AppleScript-IDEA   File: AbstractParsingFixtureTestCase.java   Source Code and License 6 votes vote down vote up
protected void doParseAllInPackageTest() {
  LOG.info("Parsing files in the package: " + getMyTargetDirectoryPath());
  System.out.println("Parsing files in the package: " + getMyTargetDirectoryPath());
  for (PsiFile psiFile : myPsiFiles) {
    LOG.info("File: " + psiFile.getName());
    System.out.print("File: " + psiFile.getName());
    try {
      ParsingTestCase.doCheckResult(myTargetTestDataDir, psiFile, checkAllPsiRoots(),
              psiFile.getVirtualFile().getNameWithoutExtension(), skipSpaces(), printRanges());
      System.out.println(": Ok");
    } catch (IOException e) {
      System.out.println(": Parsing failed" + psiFile.getName());
      e.printStackTrace();
    }
  }
}
 
Example 14
Project: bamboo-soy   File: EnterHandler.java   Source Code and License 6 votes vote down vote up
private static void handleEnterInComment(
    PsiElement element, @NotNull PsiFile file, @NotNull Editor editor) {
  if (element.getText().startsWith("/*")) {
    Document document = editor.getDocument();

    int caretOffset = editor.getCaretModel().getOffset();
    int lineNumber = document.getLineNumber(caretOffset);

    String lineTextBeforeCaret =
        document.getText(new TextRange(document.getLineStartOffset(lineNumber), caretOffset));
    String lineTextAfterCaret =
        document.getText(new TextRange(caretOffset, document.getLineEndOffset(lineNumber)));

    if (lineTextAfterCaret.equals("*/")) {
      return;
    }

    String toInsert = lineTextBeforeCaret.equals("") ? " * " : "* ";
    insertText(file, editor, toInsert, toInsert.length());
  }
}
 
Example 15
Project: chocolate-cakephp   File: ElementGotoDeclarationHandler.java   Source Code and License 6 votes vote down vote up
@Nullable
@Override
public PsiElement[] getGotoDeclarationTargets(@Nullable PsiElement psiElement, int i, Editor editor) {
    if (psiElement == null) {
        return PsiElement.EMPTY_ARRAY;
    }
    Project project = psiElement.getProject();
    if (!PlatformPatterns
            .psiElement(StringLiteralExpression.class)
            .withLanguage(PhpLanguage.INSTANCE)
            .accepts(psiElement.getContext())
    ) {
        return PsiElement.EMPTY_ARRAY;
    }
    PsiFile containingFile = psiElement.getContainingFile();
    PsiDirectory appDir = PsiUtil.getAppDirectoryFromFile(containingFile);
    String elementFilename = String.format("View/Elements/%s.ctp", psiElement.getText());
    VirtualFile relativeFile = VfsUtil.findRelativeFile(appDir, elementFilename);
    if (relativeFile != null) {
        Collection<VirtualFile> files = new HashSet<>();
        files.add(relativeFile);
        return PsiUtil.convertVirtualFilesToPsiFiles(project, files).toArray(new PsiElement[files.size()]);
    }
    return PsiElement.EMPTY_ARRAY;
}
 
Example 16
Project: MultiHighlight   File: MultiHighlightHandler.java   Source Code and License 6 votes vote down vote up
private static PsiElement findTargetElement(@NotNull Editor editor, @NotNull PsiFile file) {
    PsiElement targetElement = TargetElementUtil.findTargetElement(editor,
            TargetElementUtil.getInstance().getReferenceSearchFlags());
    
    if (targetElement != null && targetElement != file) {
        if (targetElement instanceof NavigationItem) {
            targetElement = (targetElement).getNavigationElement();
        }
        
        if (targetElement instanceof NavigationItem) {
            return targetElement;
        }
    }
    
    return null;
}
 
Example 17
Project: reasonml-idea-plugin   File: RmlPsiUtil.java   Source Code and License 6 votes vote down vote up
@NotNull
public static List<PsiModule> findModules(@NotNull Project project, @NotNull String name) {
    ArrayList<PsiModule> result = new ArrayList<>();

    Collection<VirtualFile> virtualFiles = FilenameIndex.getAllFilesByExt(project, RmlFileType.INSTANCE.getDefaultExtension());
    for (VirtualFile virtualFile : virtualFiles) {
        PsiFile file = PsiManager.getInstance(project).findFile(virtualFile);
        PsiModule[] modules = PsiTreeUtil.getChildrenOfType(file, PsiModule.class);
        if (modules != null) {
            for (PsiModule module : modules) {
                if (name.equals(module.getName())) {
                    result.add(module);
                }
            }
        }
    }

    return result;
}
 
Example 18
Project: educational-plugin   File: PyStudyImportResolver.java   Source Code and License 6 votes vote down vote up
@Nullable
public PsiElement resolveImportReference(QualifiedName name, PyQualifiedNameResolveContext context, boolean withRoots) {
  if (StudyTaskManager.getInstance(context.getProject()).getCourse() == null) {
    return null;
  }
  final String nameString = name.toString();
  PsiFile containingFile = context.getFootholdFile();
  if (containingFile == null) return null;

  final PsiDirectory directory = containingFile.getContainingDirectory();
  if (directory == null) return null;
  final PsiFile file = directory.findFile(nameString + ".py");
  if (file != null) {
    return file;
  }

  return null;
}
 
Example 19
Project: bamboo-soy   File: EnterHandler.java   Source Code and License 6 votes vote down vote up
@Override
public Result postProcessEnter(
    @NotNull PsiFile file, @NotNull Editor editor, @NotNull DataContext dataContext) {
  if (file.getFileType() != SoyFileType.INSTANCE) {
    return Result.Continue;
  }

  int caretOffset = editor.getCaretModel().getOffset();
  PsiElement element = file.findElementAt(caretOffset);
  Document document = editor.getDocument();

  int lineNumber = document.getLineNumber(caretOffset) - 1;
  int lineStartOffset = document.getLineStartOffset(lineNumber);
  String lineTextBeforeCaret = document.getText(new TextRange(lineStartOffset, caretOffset));

  if (element instanceof PsiComment && element.getTextOffset() < caretOffset) {
    handleEnterInComment(element, file, editor);
  } else if (lineTextBeforeCaret.startsWith("/*")) {
    insertText(file, editor, " * \n ", 3);
  }

  return Result.Continue;
}
 
Example 20
Project: processing-idea   File: PdeConverter.java   Source Code and License 6 votes vote down vote up
public Collection<PsiFile> parseAll(Project project, @NotNull Collection<VirtualFile> pdeFiles) throws InterruptedException {
    Collection<PsiFile> parsed = new ArrayList<>(pdeFiles.size());

    Collection<Callable<PsiFile>> parsingTasks = new ArrayList<>(pdeFiles.size());

    for (VirtualFile pdeFile : pdeFiles) {
        parsingTasks.add(() -> parse(project, pdeFile));
    }

    ExecutorService parsingExecutor = Executors.newWorkStealingPool(Runtime.getRuntime().availableProcessors());

    List<Future<PsiFile>> parsingResults = parsingExecutor.invokeAll(parsingTasks);

    for (Future<PsiFile> futureParsedClass : parsingResults) {
        try {
            parsed.add(futureParsedClass.get());
        } catch (ExecutionException ee) {
            logger.error(ee);
        }
    }

    parsingExecutor.shutdown();

    return parsed;
}
 
Example 21
Project: intellij-postfix-templates   File: CptPsiImplUtil.java   Source Code and License 6 votes vote down vote up
public static ItemPresentation getPresentation(final CptMapping element) {
	return new ItemPresentation() {
		@Nullable
		@Override
		public String getPresentableText() {
			return element.getMatchingClass();
		}

		@Nullable
		@Override
		public String getLocationString() {
			PsiFile containingFile = element.getContainingFile();
			return containingFile == null ? null : containingFile.getName();
		}

		@Nullable
		@Override
		public Icon getIcon(boolean unused) {
			return CptIcons.FILE;
		}
	};
}
 
Example 22
Project: ReactPropTypes-Plugin   File: PropTypeAction.java   Source Code and License 6 votes vote down vote up
@Override
void actionPerformed(Project project,
                     Editor editor,
                     PsiFile file,
                     String selectedText,
                     List<PropTypeBean> propNameList,
                     Component component) {
    PropTypesDialog dialog = new PropTypesDialog(propNameList , component);
    dialog.pack();
    dialog.setLocationRelativeTo(WindowManager.getInstance().getFrame(project));
    dialog.setOnSubmitListener((beans, importMode, esVersion) -> {
        Document document = editor.getDocument();
        runCommand(project, () -> {
            //insert PropTypes Object
            insertPropTypesCodeString(document,file,selectedText,beans,esVersion);
            //insert import statement
            autoInsertImportPropTypes(document,file,importMode);
        });
    });
    dialog.setVisible(true);
}
 
Example 23
Project: laravel-insight   File: FluentUtilTest.java   Source Code and License 5 votes vote down vote up
public void testIsUsingDirectly() {
    Assert.assertFalse(FluentUtil.isUsingDirectly(null));

    final PsiFile    fileSample     = getResourceFile("laravelInsight/fluent/FluentUtil.samples.php");
    final PsiElement emptyReference = getElementByName(fileSample, "reference");

    Assert.assertFalse(FluentUtil.isUsingDirectly(emptyReference));
}
 
Example 24
Project: ReactPropTypes-Plugin   File: CommonAction.java   Source Code and License 5 votes vote down vote up
@Nullable
private PsiElement getDefaultPropsElementByName(PsiFile file, String componentName){
  PsiElement es7Element = getES7FieldElementByName(file, componentName, "defaultProps");
  if(es7Element == null) {
    PsiElement es6Element = getES6FieldByName(file,componentName , "defaultProps");
    if(es6Element == null){
      return getES5PropTypeElementByName(file,componentName);
    }else {
      return es6Element;
    }
  }else {
    return es7Element;
  }
}
 
Example 25
Project: GravSupport   File: GravFileTemplateUtil.java   Source Code and License 5 votes vote down vote up
/**
 * Return the current theme which is set in the system/config/system.yaml file
 *
 * @param project the project
 * @return theme name or null
 */
public static String getDefaultTheme(Project project) {
    VirtualFile vfile = VfsUtil.findRelativeFile(project.getBaseDir(), "system", "config", "system.yaml");
    if (vfile == null) return null;
    PsiFile psiFile = PsiManager.getInstance(project).findFile(vfile);
    if (psiFile == null) return null;

    YAMLKeyValue yamlKeyValue = GravYAMLUtils.getKeyValue((YAMLFile) psiFile, Arrays.asList(new String[]{"pages", "theme"}));
    if (yamlKeyValue == null) return null;

    return yamlKeyValue.getValueText();
}
 
Example 26
Project: TearDownGenerator   File: TearDownInspectionQuickFix.java   Source Code and License 5 votes vote down vote up
@Override
public void invoke(@NotNull Project project, @NotNull PsiFile file, @NotNull PsiElement element, @NotNull PsiElement element1) {
  elementFactory = SwiftPsiElementFactory.getInstance(getClassDeclaration());
  List<String> writableNames = TearDownUtil.getWritableVariableNames(getClassDeclaration());
  SwiftFunctionDeclaration tearDownMethod = TearDownUtil.getTearDownMethod(getClassDeclaration());
  if (tearDownMethod != null) {
    replaceTearDownMethod(tearDownMethod, writableNames);
  } else {
    createTearDown(writableNames);
  }
}
 
Example 27
Project: intellij-plugin   File: NavigatorUtil.java   Source Code and License 5 votes vote down vote up
@Nullable
public static Navigatable createNavigatableForFile(final Project project, final VirtualFile file) {
    if (file != null && file.isValid()) {
        final PsiFile result = PsiManager.getInstance(project).findFile(file);
        return result == null ? null : new NavigatableAdapter() {
            public void navigate(boolean requestFocus) {
                navigate(project, file, 0, requestFocus);
            }
        };
    } else {
        return null;
    }
}
 
Example 28
Project: yii2support   File: Util.java   Source Code and License 5 votes vote down vote up
@NotNull
static ArrayHashElement[] getMessages(PhpPsiElement element, String category) {
    ArrayList<ArrayHashElement> messages = new ArrayList<>();

    PsiDirectory directory = getDirectory(element);
    if (directory != null) {
        PsiFile file = directory.findFile(category.concat(".php"));
        if (file != null) {
            messages.addAll(loadMessagesFromFile(file));
        }
    }

    return messages.toArray(new ArrayHashElement[messages.size()]);
}
 
Example 29
Project: patcher   File: ClassesExportAction.java   Source Code and License 5 votes vote down vote up
@Override
public void actionPerformed(AnActionEvent e) {
    try {
        com.intellij.openapi.actionSystem.DataContext dataContext = e.getDataContext();
        PsiJavaFile javaFile = (PsiJavaFile) ((PsiFile) DataKeys.PSI_FILE.getData(dataContext)).getContainingFile();
        String sourceName = javaFile.getName();
        Module module = (Module) DataKeys.MODULE.getData(dataContext);
        String compileRoot = CompilerModuleExtension.getInstance(module).getCompilerOutputPath().getPath();
        getVirtualFile(sourceName, CompilerModuleExtension.getInstance(module).getCompilerOutputPath().getChildren(), compileRoot);
        VirtualFileManager.getInstance().syncRefresh();
    } catch (Exception ex) {
        ex.printStackTrace();
        Messages.showErrorDialog("Please build your module or project!!!", "error");
    }
}
 
Example 30
Project: ReactPropTypes-Plugin   File: CommonAction.java   Source Code and License 5 votes vote down vote up
@Nullable
boolean hasImportPropTypes(PsiFile file){
  boolean hasNew = PsiTreeUtil.findChildrenOfType(file, ES6FromClause.class)
          .stream()
          .filter(o -> o.getText().contains("\'prop-types\'"))
          .map(Objects::nonNull)
          .reduce(false,(a,b) -> a||b);
  boolean hasOld = PsiTreeUtil.findChildrenOfType(file, ES6FromClause.class)
          .stream()
          .filter(o -> o.getText().contains("\'react\'"))
          .filter(o -> o.getParent().getText().contains("PropTypes"))
          .map(Objects::nonNull)
          .reduce(false,(a,b) -> a||b);
  return hasNew||hasOld;
}
 
Example 31
Project: intellij-plugin   File: SeedStackGroupNodeTest.java   Source Code and License 5 votes vote down vote up
@Test
public void psiFileAdded() throws Exception {
    underTest.refresh(null);
    PsiFile psiFile2 = Mockito.mock(PsiFile.class);
    TestNode test0 = new TestNode(underTest, "test0");
    someChildren.putValue(psiFile2, test0);
    underTest.refresh(null);
    assertThat(underTest.doGetChildren()).containsExactly(test0, test1, test2, test3, test4, test5);
}
 
Example 32
Project: MultiHighlight   File: MultiHighlightHandler.java   Source Code and License 5 votes vote down vote up
/**
 * {@link com.intellij.codeInsight.highlighting.HighlightUsagesHandler#invoke(Project, Editor,
 * PsiFile)}
 *
 * {@link com.intellij.codeInsight.daemon.impl.IdentifierHighlighterPass#doCollectInformation(ProgressIndicator)}
 */
public static void invoke(@NotNull Project project, @NotNull Editor editor,
        @NotNull PsiFile file) {
    PsiDocumentManager.getInstance(project).commitAllDocuments();
    
    if (handleCustomUsage(editor, file)) {
        return;
    }
    
    DumbService.getInstance(project).withAlternativeResolveEnabled(() -> {
        if (!findTarget(project, editor, file)) {
            handleNoUsageTargets(file, editor, project);
        }
    });
}
 
Example 33
Project: manifold-ij   File: JsonUsagesTest.java   Source Code and License 5 votes vote down vote up
public void testFindUsages_Class_FromFile() throws Exception
{
  myFixture.copyFileToProject( "json/sample/Person.json" );
  myFixture.copyFileToProject( "json/usages/TestJsonUsages_Class_FromUseSite.java" );
  PsiClass psiClass = myFixture.findClass( "json.sample.Person" );
  assertNotNull( psiClass );
  PsiFile containingFile = psiClass.getContainingFile();
  assertNotNull( containingFile );
  Collection<UsageInfo> usageInfos = myFixture.findUsages( containingFile );
  assertEquals( 3, usageInfos.size() );
}
 
Example 34
Project: magento2-phpstorm-plugin   File: WebApiTypeIndex.java   Source Code and License 5 votes vote down vote up
@NotNull
@Override
public DataIndexer<String, Void, FileContent> getIndexer() {
    return inputData -> {
        Map<String, Void> map = new HashMap<>();

        PsiFile psiFile = inputData.getPsiFile();
        if (!Settings.isEnabled(psiFile.getProject())) {
            return map;
        }

        if (!(psiFile instanceof XmlFile)) {
            return map;
        }

        XmlDocument document = ((XmlFile) psiFile).getDocument();
        if (document == null) {
            return map;
        }

        XmlTag xmlTags[] = PsiTreeUtil.getChildrenOfType(psiFile.getFirstChild(), XmlTag.class);
        if (xmlTags == null) {
            return map;
        }

        for (XmlTag xmlTag : xmlTags) {
            if (xmlTag.getName().equals("routes")) {
                for (XmlTag routeNode : xmlTag.findSubTags("route")) {
                    for (XmlTag serviceNode : routeNode.findSubTags("service")) {
                        String typeName = serviceNode.getAttributeValue("class");
                        if (typeName != null) {
                            map.put(PhpLangUtil.toPresentableFQN(typeName), null);
                        }
                    }
                }
            }
        }
        return map;
    };
}
 
Example 35
Project: greycat-idea-plugin   File: GCMTemplatesFactory.java   Source Code and License 5 votes vote down vote up
public static PsiElement createFromTemplate(PsiDirectory directory, String fileName, Template template, String text2) {
    final PsiFileFactory factory = PsiFileFactory.getInstance(directory.getProject());
    if ((new File(fileName)).exists()) {
        throw new RuntimeException("File already exists");
    }
    final PsiFile file = factory.createFileFromText(fileName, GCMLanguageType.INSTANCE, text2);
    return directory.add(file);
}
 
Example 36
Project: chocolate-cakephp   File: PsiUtil.java   Source Code and License 5 votes vote down vote up
@NotNull
public static Collection<PsiFile> convertVirtualFilesToPsiFiles(@NotNull Project project, @NotNull Collection<VirtualFile> files) {

    Collection<PsiFile> psiFiles = new HashSet<>();
    PsiManager psiManager = PsiManager.getInstance(project);

    for (VirtualFile file : files) {
        PsiFile psiFile = psiManager.findFile(file);
        if(psiFile != null) {
            psiFiles.add(psiFile);
        }
    }

    return psiFiles;
}
 
Example 37
Project: chocolate-cakephp   File: TemplateGotoDeclarationHandler.java   Source Code and License 5 votes vote down vote up
@Nullable
@Override
public PsiElement[] getGotoDeclarationTargets(@Nullable PsiElement psiElement, int i, Editor editor) {
    if (psiElement == null) {
        return PsiElement.EMPTY_ARRAY;
    }
    Project project = psiElement.getProject();
    if (!PlatformPatterns
            .psiElement(StringLiteralExpression.class)
            .withLanguage(PhpLanguage.INSTANCE)
            .accepts(psiElement.getContext())
    ) {
        return PsiElement.EMPTY_ARRAY;
    }
    PsiFile containingFile = psiElement.getContainingFile();
    VirtualFile virtualFile = containingFile.getVirtualFile();
    String filename = virtualFile.getNameWithoutExtension();
    String controllerName = CakeUtil.controllerBaseNameFromControllerFileName(filename);
    if (controllerName == null) {
        return PsiElement.EMPTY_ARRAY;
    }

    PsiDirectory appDir = PsiUtil.getAppDirectoryFromFile(containingFile);
    String templatePath = String.format("View/%s/%s.ctp", controllerName, psiElement.getText());
    VirtualFile relativeFile = VfsUtil.findRelativeFile(appDir, templatePath);
    if (relativeFile != null) {
        Collection<VirtualFile> files = new HashSet<>();
        files.add(relativeFile);
        return PsiUtil.convertVirtualFilesToPsiFiles(project, files).toArray(new PsiElement[files.size()]);
    }
    return PsiElement.EMPTY_ARRAY;
}
 
Example 38
Project: idea-php-typo3-plugin   File: ExtensionUtility.java   Source Code and License 5 votes vote down vote up
private static VirtualFile findExtEmConf(@NotNull PsiDirectory extensionRootDirectory) {
    PsiFile file = extensionRootDirectory.findFile("ext_emconf.php");
    if (file == null) {
        return null;
    }

    return file.getVirtualFile();
}
 
Example 39
Project: CodeGenerate   File: DBConn.java   Source Code and License 5 votes vote down vote up
public DBConn(PsiClass cls, PsiFile file, Project project) throws HeadlessException {
    this.cls = cls;
    this.file = file;
    this.project = project;
    setContentPane(mainPanel);
    setTitle("MySQlConnext");
    getRootPane().setDefaultButton(connectButton);
    this.setAlwaysOnTop(true);
    initGeneratePanel();
    initListener(this);
    setSize(300,200);
    setVisible(true);
}
 
Example 40
Project: intellij-postfix-templates   File: CustomPostfixTemplateProvider.java   Source Code and License 5 votes vote down vote up
@NotNull
@Override
public PsiFile preCheck(@NotNull PsiFile copyFile, @NotNull Editor realEditor, int currentOffset) {
	Document document = copyFile.getViewProvider().getDocument();
	assert document != null;
	CharSequence sequence = document.getCharsSequence();
	StringBuilder fileContentWithSemicolon = new StringBuilder(sequence);
	if (isSemicolonNeeded(copyFile, realEditor)) {
		fileContentWithSemicolon.insert(currentOffset, ';');
		return PostfixLiveTemplate.copyFile(copyFile, fileContentWithSemicolon);
	}

	return copyFile;
}
 
Example 41
Project: bamboo-soy   File: FileStub.java   Source Code and License 5 votes vote down vote up
@Override
public StubBuilder getBuilder() {
  return new DefaultStubBuilder() {
    @Override
    protected StubElement createStubForFile(@NotNull PsiFile file) {
      return new FileStub((SoyFile) file);
    }
  };
}
 
Example 42
Project: manifold-ij   File: FakeTargetElement.java   Source Code and License 5 votes vote down vote up
FakeTargetElement( PsiFile file, int iOffset, int iLength, String name )
{
  _file = file;
  _iOffset = iOffset;
  _iLength = iLength;
  _name = name;
}
 
Example 43
Project: bamboo-soy   File: SoyFormattingModelBuilder.java   Source Code and License 5 votes vote down vote up
@NotNull
public FormattingModel createModel(PsiElement element, CodeStyleSettings settings) {
  final PsiFile file = element.getContainingFile();

  if (element.getNode().getElementType() == SoyTypes.OTHER) {
    return new SimpleTemplateLanguageFormattingModelBuilder().createModel(element, settings);
  } else {
    return new DocumentBasedFormattingModel(
        getRootBlock(file, file.getViewProvider(), settings),
        element.getProject(),
        settings,
        file.getFileType(),
        file);
  }
}
 
Example 44
Project: hybris-integration-intellij-idea-plugin   File: HighlightMacrosHandlerFactory.java   Source Code and License 5 votes vote down vote up
@Override
public HighlightUsagesHandlerBase createHighlightUsagesHandler(
    @NotNull final Editor editor,
    @NotNull final PsiFile file,
    @NotNull final PsiElement target
) {

    if (isMacroNameDeclaration(target)
        || isMacroUsage(target)) {
        return new HighlightMacrosHandler(editor, file, target);
    }

    return null;
}
 
Example 45
Project: IntellijMethodHierarchyHighlighter   File: MethodHighlighter.java   Source Code and License 5 votes vote down vote up
private void unfoldMethodsInCurrentFile(Editor editor) {
	Project project = editor.getProject();
	if (project != null) {
		PsiFile psiFile = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument());
		methodFolder.unfoldMethods(editor, methodFinder.findMethodsCalledBy(psiFile));
	}
}
 
Example 46
Project: intellij-plugin   File: ConfigurationNode.java   Source Code and License 5 votes vote down vote up
@Override
public MultiMap<PsiFile, ConfigFileNode> computeChildren(PsiFile psiFile) {
    Project project = getProject();
    MultiMap<PsiFile, ConfigFileNode> children = new MultiMap<>();
    if (project != null) {
        PsiManager psiManager = PsiManager.getInstance(project);
        for (VirtualFile virtualFile : CoffigUtil.findCoffigFiles(getProject())) {
            PsiFile file = psiManager.findFile(virtualFile);
            children.putValue(file, new ConfigFileNode(this, psiManager.findFile(virtualFile)));
        }
    }
    return children;
}
 
Example 47
Project: laravel-insight   File: PhpClassUtilTest.java   Source Code and License 5 votes vote down vote up
public void testGetTraitsDeclared() {
    final PsiFile fileSample = getResourceFile("utils/PhpClassUtil.traitsDeclaration.php");

    final ArrayList<PhpUse> phpUses = Lists.newArrayList(PhpClassUtil.getTraitsDeclared(valueOf(getElementByName(fileSample, "ObjectClass"))));

    Assert.assertSame(3, phpUses.size());

    Assert.assertEquals("\\FirstTrait", valueOf(getElementByName(fileSample, "FirstTrait")).getFQN());
    Assert.assertEquals("\\SecondTrait", valueOf(getElementByName(fileSample, "SecondTrait")).getFQN());
    Assert.assertEquals("\\ThirdTrait", valueOf(getElementByName(fileSample, "ThirdTrait")).getFQN());
}
 
Example 48
Project: nullability-annotations-inspection   File: AddPackageInfoWithNullabilityDefaultsFix.java   Source Code and License 5 votes vote down vote up
@Nullable
private PsiJavaFile createPackageInfoFile(PsiFile file, PsiPackage target) {
    DataManager.getInstance().getDataContextFromFocus().doWhenDone((Consumer<DataContext>) context -> {
        AnActionEvent event =
                new AnActionEvent(null, context, "", new Presentation(), ActionManager.getInstance(), 0);
        new CreatePackageInfoAction().actionPerformed(event);
    });
    return packageInfoFile(target, file.getContainingDirectory());
}
 
Example 49
Project: laravel-insight   File: FluentUtilTest.java   Source Code and License 5 votes vote down vote up
public void testIsUsingIndirectly() {
    Assert.assertFalse(FluentUtil.isUsingIndirectly(null));

    final PsiFile    fileSample     = getResourceFile("laravelInsight/fluent/FluentUtil.samples.php");
    final PsiElement emptyReference = getElementByName(fileSample, "reference");

    Assert.assertFalse(FluentUtil.isUsingIndirectly(emptyReference));
}
 
Example 50
Project: ReactPropTypes-Plugin   File: CommonAction.java   Source Code and License 5 votes vote down vote up
@Nullable
ES6ImportDeclaration getReactImportDeclaration(PsiFile file){
  return PsiTreeUtil.findChildrenOfType(file, ES6FromClause.class)
          .stream()
          .filter(o -> o.getText().contains("\'react\'"))
          .filter(o -> o.getParent() instanceof ES6ImportDeclaration)
          .map(o -> (ES6ImportDeclaration) o.getParent())
          .findFirst()
          .orElse(null);

}
 
Example 51
Project: idea-php-class-templates   File: NewPHPTemplateClass.java   Source Code and License 5 votes vote down vote up
protected PhpCreateFileFromTemplateDataProvider getDataProvider(@NotNull Project project, @NotNull PsiDirectory dir, @Nullable PsiFile file) {
    PhpNewTemplateClassDialog dialog = new PhpNewTemplateClassDialog(project, dir);

    if (!dialog.showAndGet()) {
        return null;
    }

    return dialog;
}
 
Example 52
Project: jgiven-intellij-plugin   File: ScenarioStateUsageProviderIntegrationTest.java   Source Code and License 5 votes vote down vote up
private void configureByFile(String filename) {
    List<String> files = new ArrayList<>();
    files.add(filename);
    files.addAll(getUsageFilesForAllTests());
    String[] asArray = files.toArray(new String[files.size()]);
    PsiFile[] loadedFiles = myFixture.configureByFiles(asArray);
    assertThat(loadedFiles).hasSameSizeAs(files);
}
 
Example 53
Project: GravSupport   File: LanguageFolderStrategy.java   Source Code and License 5 votes vote down vote up
@Override
public void initTab(LanguageFileEditorGUI gui) {
    for (VirtualFile file : fileMap.values()) {
        PsiFile psiFile = PsiManager.getInstance(project).findFile(file);
        if (psiFile != null) {
            Document document = PsiDocumentManager.getInstance(project).getDocument(psiFile);
            if (document != null) {
                Editor editorTextField = gui.createEditor(document, project, psiFile.getFileType());
                editorMap.put(psiFile.getVirtualFile().getNameWithoutExtension(), editorTextField);
                gui.addTab(psiFile.getVirtualFile().getNameWithoutExtension(), editorTextField.getComponent());
            }
        }
    }
}
 
Example 54
Project: idea-php-dotenv-plugin   File: PhpEnvironmentVariablesUsagesProvider.java   Source Code and License 5 votes vote down vote up
@NotNull
@Override
public Collection<KeyUsagePsiElement> getUsages(PsiFile psiFile) {
    if(psiFile instanceof PhpFile) {
        PhpEnvironmentCallsVisitor visitor = new PhpEnvironmentCallsVisitor();
        psiFile.acceptChildren(visitor);

        return visitor.getCollectedItems();
    }

    return Collections.emptyList();
}
 
Example 55
Project: idea-php-dotenv-plugin   File: DockerComposeYamlVariablesProvider.java   Source Code and License 5 votes vote down vote up
@NotNull
@Override
public Collection<KeyValuePsiElement> getElements(PsiFile psiFile) {

    if(psiFile instanceof YAMLFile) {
        DockerComposeYamlPsiElementsVisitor visitor = new DockerComposeYamlPsiElementsVisitor();
        psiFile.acceptChildren(visitor);

        return visitor.getCollectedItems();
    }

    return Collections.emptyList();
}
 
Example 56
Project: hybris-integration-intellij-idea-plugin   File: ImpexStructureViewBuilder.java   Source Code and License 5 votes vote down vote up
@Override
protected StructureViewDescriptor createMainView(
    final FileEditor fileEditor, final PsiFile mainFile
) {
    final Editor editor = fileEditor instanceof TextEditor ? ((TextEditor) fileEditor).getEditor() : null;
    StructureViewModel model = new ImpexStructureViewModel(editor, psiFile);
    StructureView view = new ImpexStructureViewComponent(fileEditor, model, psiFile.getProject());
    StructureViewDescriptor descriptor = new StructureViewDescriptor(psiFile.getName(), view, null);
    return descriptor;
}
 
Example 57
Project: manifold-ij   File: ManGotoDeclarationHandler.java   Source Code and License 5 votes vote down vote up
private static PsiElement findTargetFeature( PsiAnnotation psiAnnotation, ManifoldPsiClass facade )
  {
    PsiAnnotationMemberValue value = psiAnnotation.findAttributeValue( SourcePosition.FEATURE );
    String featureName = StringUtil.unquoteString( value.getText() );
//    value = psiAnnotation.findAttributeValue( SourcePosition.TYPE );
//    if( value != null )
//    {
//      String ownersType = StringUtil.unquoteString( value.getText() );
//      if( ownersType != null )
//      {
//        PsiElement target = findIndirectTarget( ownersType, featureName, facade.getRawFile().getProject() );
//        if( target != null )
//        {
//          return target;
//        }
//      }
//    }

    int iOffset = Integer.parseInt( psiAnnotation.findAttributeValue( SourcePosition.OFFSET ).getText() );
    int iLength = Integer.parseInt( psiAnnotation.findAttributeValue( SourcePosition.LENGTH ).getText() );

    List<PsiFile> sourceFiles = facade.getRawFiles();
    if( iOffset >= 0 )
    {
      //PsiElement target = sourceFile.findElementAt( iOffset );
      //## todo: handle multiple files
      return new FakeTargetElement( sourceFiles.get( 0 ), iOffset, iLength >= 0 ? iLength : 1, featureName );
    }
    return facade;
  }
 
Example 58
Project: reasonml-idea-plugin   File: RmlPsiUtil.java   Source Code and License 5 votes vote down vote up
@Nullable
public static PsiFile findFileModule(Project project, String name) {
    List<PsiFile> rmlModules = findFileModules(project, RmlFileType.INSTANCE.getDefaultExtension(), name, true);
    if (rmlModules.size() == 1) {
        return rmlModules.get(0);
    }

    List<PsiFile> oclModules = findFileModules(project, OclFileType.INSTANCE.getDefaultExtension(), name, true);
    if (oclModules.size() == 1) {
        return oclModules.get(0);
    }

    return null;
}
 
Example 59
Project: idea-php-typo3-plugin   File: ResourceReferenceContributorTest.java   Source Code and License 5 votes vote down vote up
public void testResourceReferenceResolves() {
    PsiFile psiFile = myFixture.addFileToProject("foo/ext_emconf.php", "");
    myFixture.addFileToProject("foo/bar.txt", "");

    myFixture.configureByText(PhpFileType.INSTANCE, "<?php \n" +
            "'EXT:foo/ext_emconf.php<caret>';");

    PsiElement elementAtCaret = myFixture.getFile().findElementAt(myFixture.getCaretOffset()).getParent();

    ResourceReference target = null;
    PsiReference[] references = elementAtCaret.getReferences();
    for (PsiReference ref : references) {
        if (ref instanceof ResourceReference) {
            target = (ResourceReference) ref;
        }
    }

    if (target != null) {
        for (ResolveResult o : target.multiResolve(true)) {
            if (o.getElement().isEquivalentTo(psiFile)) {
                return;
            }
        }
    }

    fail("No resource reference.");
}
 
Example 60
Project: manifold-ij   File: ResourceToManifoldUtil.java   Source Code and License 5 votes vote down vote up
private static boolean isFileOpenInCurrentEditor( PsiFile file )
{
  Editor editor = getActiveEditor( file.getProject() );
  if( editor == null )
  {
    return false;
  }

  VirtualFile editorFile = FileDocumentManager.getInstance().getFile( editor.getDocument() );
  return editorFile != null && editorFile.getPath().equals( file.getVirtualFile().getPath() );

}