Java Code Examples for com.intellij.psi.PsiManager

The following are top voted examples for showing how to use com.intellij.psi.PsiManager. 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: intellij-spring-assistant   File: PropertiesDocumentationProvider.java   Source Code and License 6 votes vote down vote up
@Override
public PsiElement getDocumentationElementForLookupItem(PsiManager psiManager, Object object,
    @Nullable PsiElement element) {
  if (object instanceof Suggestion) {
    Suggestion suggestion = Suggestion.class.cast(object);
    MetadataNode target = suggestion.getRef();
    boolean requestedForTargetValue = suggestion.isReferringToValue();
    String text = null;
    if (element != null) {
      text = element.getText();
    }
    return new DocumentationProxyElement(psiManager, JavaLanguage.INSTANCE, target,
        requestedForTargetValue, text);
  }
  return super.getDocumentationElementForLookupItem(psiManager, object, element);
}
 
Example 2
Project: TS-IJ   File: TSGlobalCachedListGenerator.java   Source Code and License 6 votes vote down vote up
@Override
public Set<TSVarExpr> generate(Project project) {
    Set<TSVarExpr> items = new HashSet<>();
    //Search every file in the project
    Collection<VirtualFile> virtualFiles = FileBasedIndex.getInstance().getContainingFiles(FileTypeIndex.NAME, TSFileType.INSTANCE, GlobalSearchScope.projectScope(project));
    for (VirtualFile virtualFile : virtualFiles) {
        TSFile tsFile = (TSFile) PsiManager.getInstance(project).findFile(virtualFile);
        if (tsFile != null) {
            Collection<TSAssignExpr> assignments = PsiTreeUtil.findChildrenOfType(tsFile, TSAssignExpr.class);
            for (TSAssignExpr assignment : assignments) {
                PsiElement first = assignment.getFirstChild();
                if (!(first instanceof TSVarExpr))
                    continue;

                if (((TSVarExpr)first).isLocal())
                    continue;

                items.add((TSVarExpr) first);

            }
        }
        ProgressManager.progress("Loading Symbols");
    }
    return items;
}
 
Example 3
Project: AppleScript-IDEA   File: SDEF_Parser.java   Source Code and License 6 votes vote down vote up
@Nullable
private static XmlFile getDictionaryFileFromInclude(@NotNull Project project, IncludedXmlTag xmlIncludeTag) {
  XmlFile xmlFile = null;
  XmlElement origXmlElement = xmlIncludeTag.getOriginal();
  PsiFile origPsiFile = origXmlElement != null ? origXmlElement.getContainingFile() : null;
  if (origPsiFile instanceof XmlFile) {
    xmlFile = (XmlFile) origPsiFile;
    AppleScriptSystemDictionaryRegistryService dictionaryService = ServiceManager.getService(AppleScriptSystemDictionaryRegistryService
        .class);
    VirtualFile vFile = origPsiFile.getVirtualFile();
    DictionaryInfo dInfo = dictionaryService.getDictionaryInfoByApplicationPath(vFile.getPath());
    if (dInfo != null) {
      File ioFile = dInfo.getDictionaryFile();
      if (ioFile.exists()) {
        vFile = LocalFileSystem.getInstance().findFileByIoFile(ioFile);
        if (vFile == null || !vFile.isValid()) return null;

        PsiFile psiFile = PsiManager.getInstance(project).findFile(vFile);
        xmlFile = (XmlFile) psiFile;
      }
    }
  }
  return xmlFile;
}
 
Example 4
Project: AppleScript-IDEA   File: AppleScriptProjectDictionaryService.java   Source Code and License 6 votes vote down vote up
@Nullable
private ApplicationDictionary createDictionaryFromInfo(final @NotNull DictionaryInfo dInfo) {
  if (!dInfo.isInitialized()) {
    //dictionary terms must be ridden from the dictionary file before creating a PSI for it
    LOG.error("Attempt to create dictionary for not initialized Dictionary Info for application" + dInfo.getApplicationName());
    return null;
  }
  String applicationName = dInfo.getApplicationName();
  VirtualFile vFile = LocalFileSystem.getInstance().findFileByIoFile(dInfo.getDictionaryFile());
  if (vFile != null && vFile.isValid()) {
    PsiFile psiFile = PsiManager.getInstance(project).findFile(vFile);
    XmlFile xmlFile = (XmlFile) psiFile;
    if (xmlFile != null) {
      ApplicationDictionary dictionary = new ApplicationDictionaryImpl(project, xmlFile, applicationName, dInfo.getApplicationFile());
      dictionaryMap.put(applicationName, dictionary);
      return dictionary;
    }
  }
  LOG.warn("Failed to create dictionary from info for application: " + applicationName + ". Reason: file is null");
  return null;
}
 
Example 5
Project: manifold-ij   File: TypeUtil.java   Source Code and License 6 votes vote down vote up
private static PsiType makeDefaultParameterizedTypeForCompoundType( PsiIntersectionType type, PsiManager mgr )
{
  PsiType[] types = type.getConjuncts();
  PsiType[] defCompTypes = new PsiType[types.length];
  int i = 0;
  boolean bDifferent = false;
  for( PsiType compType : types )
  {
    defCompTypes[i++] = getDefaultParameterizedType( compType, mgr );
    bDifferent = bDifferent || !defCompTypes[i].equals( compType );
  }
  if( bDifferent )
  {
    return PsiIntersectionType.createIntersection( defCompTypes );
  }
  return type;
}
 
Example 6
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 7
Project: idea-php-typo3-plugin   File: ResourcePathIndex.java   Source Code and License 6 votes vote down vote up
public static PsiElement[] findElementsForKey(@NotNull Project project, @NotNull String identifier) {
    Set<String> keys = new HashSet<>();
    keys.add(identifier);
    Set<PsiElement> elements = new HashSet<>();

    FileBasedIndex.getInstance().getFilesWithKey(ResourcePathIndex.KEY, keys, virtualFile -> {
        elements.add(PsiManager.getInstance(project).findFile(virtualFile));

        return true;
    }, GlobalSearchScope.allScope(project));

    return elements
            .stream()
            .filter(Objects::nonNull)
            .toArray(PsiElement[]::new);
}
 
Example 8
Project: idea-php-typo3-plugin   File: IconIndex.java   Source Code and License 6 votes vote down vote up
@NotNull
public static PsiElement[] getIconDefinitionElements(@NotNull Project project, @NotNull String identifier) {
    Map<VirtualFile, IconStub> iconDefinitionByIdentifier = getIconDefinitionByIdentifier(project, identifier);
    if (iconDefinitionByIdentifier.size() > 0) {
        return iconDefinitionByIdentifier
                .keySet()
                .stream()
                .map(virtualFile -> {
                    IconStub iconStub = iconDefinitionByIdentifier.get(virtualFile);
                    PsiFile file = PsiManager.getInstance(project).findFile(virtualFile);
                    return file != null ? file.findElementAt(iconStub.getTextRange().getStartOffset()) : null;
                })
                .filter(Objects::nonNull)
                .toArray(PsiElement[]::new);
    }

    return new PsiElement[0];
}
 
Example 9
Project: idea-php-typo3-plugin   File: TranslationUtil.java   Source Code and License 6 votes vote down vote up
public static PsiElement[] findDefinitionElements(@NotNull Project project, @NotNull String translationId) {
    Set<String> keys = new HashSet<>();
    keys.add(translationId);

    List<PsiElement> elements = new ArrayList<>();
    FileBasedIndex.getInstance().getFilesWithKey(TranslationIndex.KEY, keys, virtualFile -> {
        FileBasedIndex.getInstance().processValues(TranslationIndex.KEY, translationId, virtualFile, (file, value) -> {
            PsiFile file1 = PsiManager.getInstance(project).findFile(file);
            if (file1 != null) {
                PsiElement elementAt = file1.findElementAt(value.getTextRange().getStartOffset());
                if (elementAt != null) {
                    elements.add(elementAt.getParent());
                }
            }

            return true;
        }, GlobalSearchScope.allScope(project));

        return true;
    }, GlobalSearchScope.allScope(project));

    return elements.toArray(new PsiElement[elements.size()]);
}
 
Example 10
Project: idea-php-typo3-plugin   File: TableUtil.java   Source Code and License 6 votes vote down vote up
public static PsiElement[] getTableDefinitionElements(@NotNull String tableName, @NotNull Project project) {

        PsiFile[] extTablesSqlFilesInProjectContainingTable = getExtTablesSqlFilesInProjectContainingTable(tableName, project);
        Set<PsiElement> elements = new HashSet<>();

        PsiManager psiManager = PsiManager.getInstance(project);

        for (PsiFile virtualFile : extTablesSqlFilesInProjectContainingTable) {
            FileBasedIndex.getInstance().processValues(TablenameFileIndex.KEY, tableName, virtualFile.getVirtualFile(), (file, value) -> {

                PsiFile file1 = psiManager.findFile(file);
                if (file1 != null) {
                    PsiElement elementAt = file1.findElementAt(value.getEndOffset() - 2);
                    if (elementAt != null) {
                        elements.add(elementAt);
                    }
                }

                return true;
            }, GlobalSearchScope.allScope(project));
        }

        return elements.toArray(new PsiElement[elements.size()]);
    }
 
Example 11
Project: idea-php-typo3-plugin   File: ControllerActionUtil.java   Source Code and License 6 votes vote down vote up
public static PsiElement[] getDefinitionElements(@NotNull Project project, @NotNull String actionName) {
    Set<String> keys = new HashSet<>();
    keys.add(actionName);

    List<PsiElement> elements = new ArrayList<>();
    FileBasedIndex.getInstance().getFilesWithKey(ControllerActionIndex.KEY, keys, virtualFile -> {
        FileBasedIndex.getInstance().processValues(ControllerActionIndex.KEY, actionName, virtualFile, (file, value) -> {
            PsiFile file1 = PsiManager.getInstance(project).findFile(file);
            if (file1 != null) {
                PsiElement elementAt = file1.findElementAt(value.getTextRange().getStartOffset());
                if (elementAt != null) {
                    elements.add(elementAt.getParent().getParent());
                }
            }

            return true;
        }, GlobalSearchScope.allScope(project));

        return true;
    }, GlobalSearchScope.allScope(project));

    return elements.toArray(new PsiElement[elements.size()]);
}
 
Example 12
Project: idea-php-typo3-plugin   File: CoreServiceParser.java   Source Code and License 6 votes vote down vote up
private void collectServices(Project project) {
    FileBasedIndex index = FileBasedIndex.getInstance();
    Collection<VirtualFile> containingFiles = index.getContainingFiles(
            FileTypeIndex.NAME,
            PhpFileType.INSTANCE,
            GlobalSearchScope.allScope(project)
    );
    containingFiles.removeIf(virtualFile -> !(virtualFile.getName().contains("ext_localconf.php")));

    for (VirtualFile projectFile : containingFiles) {
        PsiFile psiFile = PsiManager.getInstance(project).findFile(projectFile);
        if (psiFile != null) {
            psiFile.accept(new CoreServiceDefinitionParserVisitor(serviceMap));
        }
    }
}
 
Example 13
Project: greycat-idea-plugin   File: GCMUtil.java   Source Code and License 6 votes vote down vote up
public static List<GCMTypeDeclaration> findProperties(Project project) {
    final List<GCMTypeDeclaration> result = new ArrayList<GCMTypeDeclaration>();
    Collection<VirtualFile> virtualFiles = FileBasedIndex.getInstance().getContainingFiles(FileTypeIndex.NAME, GCMLanguageType.INSTANCE,
            GlobalSearchScope.allScope(project));
    for (VirtualFile virtualFile : virtualFiles) {
        GCMFile simpleFile = (GCMFile) PsiManager.getInstance(project).findFile(virtualFile);
        if (simpleFile != null) {
            simpleFile.acceptChildren(new PsiElementVisitor() {
                @Override
                public void visitElement(PsiElement element) {
                    if (element instanceof GCMDeclaration) {
                        GCMDeclaration declaration = (GCMDeclaration) element;
                        if (declaration.getClassDeclaration() != null) {
                            result.add(declaration.getClassDeclaration().getTypeDeclaration());
                        }
                        if (declaration.getCustomTypeDeclaration() != null) {
                            //result.add(declaration.getCustomTypeDeclaration().getTypeDeclaration());
                        }
                    }
                    super.visitElement(element);
                }
            });
        }
    }
    return result;
}
 
Example 14
Project: magento2-phpstorm-plugin   File: DiIndex.java   Source Code and License 6 votes vote down vote up
public Collection<PsiElement> getVirtualTypeElements(final String name, final GlobalSearchScope scope) {
    Collection<PsiElement> result = new ArrayList<>();

    Collection<VirtualFile> virtualFiles =
            FileBasedIndex.getInstance().getContainingFiles(VirtualTypeIndex.KEY, name, scope);

    for (VirtualFile virtualFile : virtualFiles) {
        XmlFile xmlFile = (XmlFile) PsiManager.getInstance(project).findFile(virtualFile);
        if (xmlFile != null) {
            Collection<XmlAttributeValue> valueElements = XmlPsiTreeUtil
                    .findAttributeValueElements(xmlFile, "virtualType", "name", name);
            result.addAll(valueElements);
        }
    }
    return result;
}
 
Example 15
Project: magento2-phpstorm-plugin   File: LayoutIndex.java   Source Code and License 6 votes vote down vote up
private static List<XmlTag> getComponentDeclarations(String componentValue, String componentType, ID<String, Void> id, Project project, ComponentMatcher componentMatcher) {
    List<XmlTag> results = new ArrayList<XmlTag>();
    Collection<VirtualFile> containingFiles = FileBasedIndex.getInstance()
        .getContainingFiles(
            id,
            componentValue,
            GlobalSearchScope.allScope(project)
        );
    PsiManager psiManager = PsiManager.getInstance(project);

    for (VirtualFile virtualFile: containingFiles) {
        XmlFile xmlFile = (XmlFile)psiManager.findFile(virtualFile);
        if (xmlFile == null) {
            continue;
        }

        XmlTag rootTag = xmlFile.getRootTag();
        if (rootTag == null) {
            continue;
        }
        collectComponentDeclarations(rootTag, results, componentValue, componentType, componentMatcher);
    }

    return results;
}
 
Example 16
Project: magento2-phpstorm-plugin   File: LayoutIndex.java   Source Code and License 6 votes vote down vote up
public static List<XmlFile> getLayoutFiles(Project project, @Nullable String fileName) {
    List<XmlFile> results = new ArrayList<XmlFile>();
    Collection<VirtualFile> xmlFiles = FilenameIndex.getAllFilesByExt(project, "xml");

    PsiManager psiManager = PsiManager.getInstance(project);
    for (VirtualFile xmlFile: xmlFiles) {
        if (isLayoutFile(xmlFile)) {
            if (fileName != null && !xmlFile.getNameWithoutExtension().equals(fileName)) {
                continue;
            }

            PsiFile file = psiManager.findFile(xmlFile);
            if (file != null) {
                results.add((XmlFile)file);
            }
        }
    }

    return results;
}
 
Example 17
Project: magento2-phpstorm-plugin   File: TypeConfigurationIndex.java   Source Code and License 6 votes vote down vote up
public static List<XmlTag> getClassConfigurations(PhpClass phpClass) {
    String classFqn = phpClass.getPresentableFQN();

    Collection<VirtualFile> containingFiles = FileBasedIndex.getInstance()
        .getContainingFiles(KEY, classFqn, GlobalSearchScope.allScope(phpClass.getProject())
    );

    PsiManager psiManager = PsiManager.getInstance(phpClass.getProject());

    List<XmlTag> tags = new ArrayList<XmlTag>();

    for (VirtualFile virtualFile: containingFiles) {
        XmlFile file = (XmlFile)psiManager.findFile(virtualFile);

        if (file == null) {
            continue;
        }

        XmlTag rootTag = file.getRootTag();
        fillRelatedTags(classFqn, rootTag, tags);
    }

    return tags;
}
 
Example 18
Project: magento2-phpstorm-plugin   File: WebApiTypeIndex.java   Source Code and License 6 votes vote down vote up
/**
 * Get list of Web API routes associated with the provided method.
 *
 * Parent classes are not taken into account.
 */
public static List<XmlTag> getWebApiRoutes(Method method) {
    List<XmlTag> tags = new ArrayList<>();
    if (!method.getAccess().isPublic()) {
        return tags;
    }
    PhpClass phpClass = method.getContainingClass();
    String methodFqn = method.getName();
    if (phpClass == null) {
        return tags;
    }
    String classFqn = phpClass.getPresentableFQN();
    Collection<VirtualFile> containingFiles = FileBasedIndex
        .getInstance().getContainingFiles(KEY, classFqn, GlobalSearchScope.allScope(phpClass.getProject()));

    PsiManager psiManager = PsiManager.getInstance(phpClass.getProject());
    for (VirtualFile virtualFile : containingFiles) {
        XmlFile file = (XmlFile) psiManager.findFile(virtualFile);
        if (file == null) {
            continue;
        }
        XmlTag rootTag = file.getRootTag();
        fillRelatedTags(classFqn, methodFqn, rootTag, tags);
    }
    return tags;
}
 
Example 19
Project: magento2-phpstorm-plugin   File: EventNameReferenceProvider.java   Source Code and License 6 votes vote down vote up
@NotNull
@Override
public PsiReference[] getReferencesByElement(@NotNull PsiElement element, @NotNull ProcessingContext context) {
    String value = StringUtil.unquoteString(element.getText());
    Collection<VirtualFile> containingFiles = FileBasedIndex.getInstance()
        .getContainingFiles(EventNameIndex.KEY, value,
                GlobalSearchScope.getScopeRestrictedByFileTypes(
                        GlobalSearchScope.allScope(element.getProject()),
                        PhpFileType.INSTANCE
                )
        );

    PsiManager psiManager = PsiManager.getInstance(element.getProject());
    for (VirtualFile virtualFile: containingFiles) {
        PhpFile phpFile = (PhpFile) psiManager.findFile(virtualFile);
        if (phpFile != null) {
            List<PsiElement> psiElements = new ArrayList<>();
            recursiveFill(psiElements, phpFile, value);
            if (psiElements.size() > 0) {
                return new PsiReference[] {new PolyVariantReferenceBase(element, psiElements)};
            }
        }
    }
    return PsiReference.EMPTY_ARRAY;
}
 
Example 20
Project: idea-php-dotenv-plugin   File: EnvironmentVariablesApi.java   Source Code and License 6 votes vote down vote up
/**
 *
 * @param project project
 * @param key environment variable key
 * @return All key declarations, in .env files, Dockerfile, docker-compose.yml, etc
 */
@NotNull
public static PsiElement[] getKeyDeclarations(Project project, String key) {
    List<PsiElement> targets = new ArrayList<>();

    FileBasedIndex.getInstance().getFilesWithKey(DotEnvKeysIndex.KEY, new HashSet<>(Collections.singletonList(key)), virtualFile -> {
        PsiFile psiFileTarget = PsiManager.getInstance(project).findFile(virtualFile);
        if(psiFileTarget == null) {
            return true;
        }

        for(EnvironmentVariablesProvider provider : EnvironmentVariablesProviderUtil.PROVIDERS) {
            if(provider.acceptFile(virtualFile)) {
                targets.addAll(EnvironmentVariablesUtil.getElementsByKey(key, provider.getElements(psiFileTarget)));
            }
        }

        return true;
    }, GlobalSearchScope.allScope(project));

    return targets.toArray(new PsiElement[0]);
}
 
Example 21
Project: EmojiPrefix   File: EmojiCheckinHandler.java   Source Code and License 6 votes vote down vote up
public EmojiCheckinHandler(CheckinProjectPanel checkinProjectPanel) {
	JPanel emojiPanel = new JPanel();
	emojiPanel.setLayout(new VerticalFlowLayout());
	VirtualFile emojirc = checkinProjectPanel.getProject().getBaseDir().findChild(".emojirc");
	if (emojirc == null) return;
	PsiFile psiFile = PsiManager.getInstance(checkinProjectPanel.getProject()).findFile(emojirc);
	if (psiFile == null) return;
	for (PsiElement psiElement : psiFile.getChildren()) {
		if (!(psiElement instanceof EmojiResourceProperty)) continue;
		emojiPanel.add(createEmojiButton(psiElement.getFirstChild().getText(), psiElement.getLastChild().getText(), false, buttonGroup));
	}
	emojiPanel.add(createEmojiButton(null, NO_EMOJI, true, buttonGroup));
	Splitter splitter = (Splitter) checkinProjectPanel.getComponent();
	CommitMessage commitMessage = (CommitMessage) splitter.getSecondComponent();
	JComponent component = (JComponent) commitMessage.getComponent(1);
	JBScrollPane scrollPane = new JBScrollPane(emojiPanel);
	scrollPane.setBorder(null);
	Splitter commitSplitter = new Splitter();
	commitSplitter.setFirstComponent(scrollPane);
	commitSplitter.setSecondComponent((JComponent) commitMessage.getComponent(0));
	commitMessage.add(commitSplitter, 0);
	for (EmojiPanelFactory factory : factories) {
		factory.createPanel(commitMessage);
	}
	this.checkinProjectPanel = checkinProjectPanel;
}
 
Example 22
Project: manifold-ij   File: TypeUtil.java   Source Code and License 6 votes vote down vote up
public static PsiType getDefaultParameterizedType( PsiType type, PsiManager mgr )
{
  if( type.getArrayDimensions() > 0 )
  {
    PsiType defType = getDefaultParameterizedType( ((PsiArrayType)type).getComponentType(), mgr );
    if( !defType.equals( type ) )
    {
      return new PsiArrayType( defType );
    }
    return type;
  }
  if( type instanceof PsiIntersectionType )
  {
    return makeDefaultParameterizedTypeForCompoundType( (PsiIntersectionType)type, mgr );
  }
  if( type instanceof PsiDisjunctionType )
  {
    return getDefaultParameterizedType( PsiTypesUtil.getLowestUpperBoundClassType( (PsiDisjunctionType)type ), mgr );
  }
  if( !isGenericType( type ) && !isParameterizedType( type ) )
  {
    return type;
  }
  type = ((PsiClassType)type).rawType();
  return makeDefaultParameterizedType( type );
}
 
Example 23
Project: intellij-postfix-templates   File: CptUtil.java   Source Code and License 6 votes vote down vote up
public static List<CptMapping> findMappings(Project project) {
	List<CptMapping> result = new ArrayList<>();

	Collection<VirtualFile> virtualFiles =
		FileBasedIndex.getInstance().getContainingFiles(FileTypeIndex.NAME, CptFileType.INSTANCE,
			GlobalSearchScope.allScope(project));

	for (VirtualFile virtualFile : virtualFiles) {
		CptFile cptFile = (CptFile) PsiManager.getInstance(project).findFile(virtualFile);
		if (cptFile != null) {
			CptMapping[] mappings = PsiTreeUtil.getChildrenOfType(cptFile, CptMapping.class);
			if (mappings != null) {
				Collections.addAll(result, mappings);
			}
		}
	}
	return result;
}
 
Example 24
Project: educational-plugin   File: PyEduPluginConfigurator.java   Source Code and License 6 votes vote down vote up
@Override
public void createTestsForNewSubtask(@NotNull Project project, @NotNull TaskWithSubtasks task) {
  VirtualFile taskDir = task.getTaskDir(project);
  if (taskDir == null) {
    return;
  }
  int nextSubtaskIndex = task.getLastSubtaskIndex() + 1;
  String nextSubtaskTestsFileName = getSubtaskTestsFileName(nextSubtaskIndex);
  ApplicationManager.getApplication().runWriteAction(() -> {
    try {
      PsiDirectory taskPsiDir = PsiManager.getInstance(project).findDirectory(taskDir);
      FileTemplate testsTemplate = FileTemplateManager.getInstance(project).getInternalTemplate(TESTS_PY);
      if (taskPsiDir == null || testsTemplate == null) {
        return;
      }
      FileTemplateUtil.createFromTemplate(testsTemplate, nextSubtaskTestsFileName, null, taskPsiDir);
    }
    catch (Exception e) {
      LOG.error(e);
    }
  });
}
 
Example 25
Project: educational-plugin   File: PyEduPluginConfigurator.java   Source Code and License 6 votes vote down vote up
@Override
public void configureModule(@NotNull Module module) {
  final Project project = module.getProject();
  StartupManager.getInstance(project).runWhenProjectIsInitialized(() -> {
    final VirtualFile baseDir = project.getBaseDir();
    final String testHelper = EduNames.TEST_HELPER;
    if (baseDir.findChild(testHelper) != null) return;
    final FileTemplate template = FileTemplateManager.getInstance(project).getInternalTemplate("test_helper");
    final PsiDirectory projectDir = PsiManager.getInstance(project).findDirectory(baseDir);
    if (projectDir == null) return;
    try {
      FileTemplateUtil.createFromTemplate(template, testHelper, null, projectDir);
    }
    catch (Exception exception) {
      LOG.error("Can't copy test_helper.py " + exception.getMessage());
    }
  });
}
 
Example 26
Project: educational-plugin   File: PyCCProjectGenerator.java   Source Code and License 6 votes vote down vote up
@Override
public void configureProject(@NotNull final Project project, @NotNull final VirtualFile baseDir,
                             @NotNull PyNewProjectSettings settings,
                             @NotNull Module module,
                             @Nullable final PyProjectSynchronizer synchronizer) {
  final Course course = getCourse(project, mySettingsPanel);
  EduUsagesCollector.projectTypeCreated(CCUtils.COURSE_MODE);
  final CCProjectComponent component = project.getComponent(CCProjectComponent.class);
  component.registerListener();
  final PsiDirectory projectDir = PsiManager.getInstance(project).findDirectory(baseDir);
  if (projectDir == null) return;
  new WriteCommandAction.Simple(project) {
    @Override
    protected void run() throws Throwable {

      createTestHelper(project, projectDir);

      PsiDirectory lessonDir = new CCCreateLesson().createItem(null, project, projectDir, course);
      if (lessonDir == null) {
        LOG.error("Failed to create lesson");
        return;
      }
      new CCCreateTask().createItem(null, project, lessonDir, course);
    }
  }.execute();
}
 
Example 27
Project: educational-plugin   File: EduAdaptiveStepicConnector.java   Source Code and License 6 votes vote down vote up
private static void createFilesForNewTask(@NotNull Project project,
                                          @NotNull Task task,
                                          @NotNull String lessonName,
                                          @NotNull Language language) {
  final VirtualFile lessonDir = project.getBaseDir().findChild(lessonName);
  if (lessonDir == null) {
    return;
  }

  ApplicationManager.getApplication().invokeLater(() -> ApplicationManager.getApplication().runWriteAction(() -> {
    PsiDirectory directory = PsiManager.getInstance(project).findDirectory(lessonDir);
    if (directory == null) {
      return;
    }

    EduPluginConfigurator.INSTANCE.forLanguage(language).createTaskContent(project, task, null, directory, task.getLesson().getCourse());
  }));
}
 
Example 28
Project: educational-plugin   File: EduAdaptiveStepicConnector.java   Source Code and License 6 votes vote down vote up
private static void updateProjectFiles(@NotNull Project project, @NotNull Task task, @NotNull String lessonName, Language language) {
  final VirtualFile lessonDir = project.getBaseDir().findChild(lessonName);
  if (lessonDir == null) {
    return;
  }

  ApplicationManager.getApplication().invokeLater(() -> ApplicationManager.getApplication().runWriteAction(() -> {
    try {
      PsiDirectory directory = PsiManager.getInstance(project).findDirectory(lessonDir);
      if (directory == null) {
        return;
      }

      removeOldProjectFiles(lessonDir, task.getIndex());
      EduPluginConfigurator.INSTANCE.forLanguage(language).createTaskContent(project, task, null, directory, task.getLesson().getCourse());
    }
    catch (IOException e) {
      LOG.warn(e.getMessage());
    }
  }));
}
 
Example 29
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 30
Project: Goal-Intellij-Plugin   File: GoalSettingsEditor.java   Source Code and License 6 votes vote down vote up
@Override
protected void resetEditorFrom(final @NotNull GoalRunConfiguration s) {
    this.fileBox.setText("<no file selected>");
    if (s.getRunFile() != null) {
        final VirtualFile file = LocalFileSystem.getInstance().refreshAndFindFileByPath(s.getRunFile());

        if (file != null) {
            final PsiFile selectedFile = PsiManager.getInstance(this.project).findFile(file);

            if (selectedFile != null) {
                this.fileChooser.selectFile(selectedFile);
                this.fileBox.setText(s.getRunFile());
            }
        }
    }
}
 
Example 31
Project: educational-plugin   File: CCShowPreviewTest.java   Source Code and License 6 votes vote down vote up
private void doTest(String name) {
  VirtualFile file = configureByTaskFile(name + CCTestsUtil.BEFORE_POSTFIX);
  CCShowPreview action = new CCShowPreview();
  TestActionEvent e = getActionEvent(action,PsiManager.getInstance(getProject()).findFile(file));
  action.beforeActionPerformedUpdate(e);
  assertTrue(e.getPresentation().isEnabled() && e.getPresentation().isVisible());
  action.actionPerformed(e);
  Editor editor = EditorFactory.getInstance().getAllEditors()[1];
  try {
    Pair<Document, List<AnswerPlaceholder>> pair = getPlaceholders(name + CCTestsUtil.AFTER_POSTFIX);
    assertEquals("Files don't match", pair.getFirst().getText(), editor.getDocument().getText());
    for (AnswerPlaceholder placeholder : pair.getSecond()) {
      assertNotNull("No highlighter for placeholder:" + CCTestsUtil.getPlaceholderPresentation(placeholder),
                    getHighlighter(editor.getMarkupModel(), placeholder));
    }
  }
  finally {
    EditorFactory.getInstance().releaseEditor(editor);
  }
}
 
Example 32
Project: Android-Resource-Usage-Count   File: FindUsageUtils.java   Source Code and License 6 votes vote down vote up
private static void dropResolveCacheRegularly(ProgressIndicator indicator, final Project project) {
    if (indicator instanceof ProgressIndicatorEx) {
        ((ProgressIndicatorEx)indicator).addStateDelegate(new ProgressIndicatorBase() {
            volatile long lastCleared = System.currentTimeMillis();

            public void setFraction(double fraction) {
                super.setFraction(fraction);
                long current = System.currentTimeMillis();
                if (current - this.lastCleared >= 500L) {
                    this.lastCleared = current;
                    PsiManager.getInstance(project).dropResolveCaches();
                }

            }
        });
    }

}
 
Example 33
Project: intellij-crystal   File: CrystalUtil.java   Source Code and License 6 votes vote down vote up
public static List<CrystalProperty> findProperties(Project project) {
    List<CrystalProperty> result = new ArrayList<CrystalProperty>();
    Collection<VirtualFile> virtualFiles =
            FileBasedIndex.getInstance().getContainingFiles(FileTypeIndex.NAME, CrystalFileType.INSTANCE,
                    GlobalSearchScope.allScope(project));
    for (VirtualFile virtualFile : virtualFiles) {
        CrystalFile simpleFile = (CrystalFile) PsiManager.getInstance(project).findFile(virtualFile);
        if (simpleFile != null) {
            CrystalProperty[] properties = PsiTreeUtil.getChildrenOfType(simpleFile, CrystalProperty.class);
            if (properties != null) {
                Collections.addAll(result, properties);
            }
        }
    }
    return result;
}
 
Example 34
Project: manifold-ij   File: ManifoldPsiClass.java   Source Code and License 6 votes vote down vote up
public void initialize( PsiClass delegate, List<IFile> files, String fqn, DiagnosticCollector issues )
{
  _ifiles = files;
  _fqn = fqn;
  _issues = issues;
  PsiManager manager = PsiManagerImpl.getInstance( delegate.getProject() );
  _files = new ArrayList<>( _ifiles.size() );
  for( IFile ifile : _ifiles )
  {
    VirtualFile vfile = ((IjFile)ifile).getVirtualFile();
    if( vfile != null )
    {
      PsiFile file = manager.findFile( vfile );
      _files.add( file );

      Module module = ModuleUtilCore.findModuleForFile( vfile, delegate.getProject() );
      if( module != null )
      {
        file.putUserData( ModuleUtil.KEY_MODULE, module );
      }
    }
  }
  delegate.getContainingFile().putUserData( KEY_MANIFOLD_PSI_CLASS, this );
}
 
Example 35
Project: manifold-ij   File: ManTypeFinder.java   Source Code and License 6 votes vote down vote up
@Override
public PsiPackage findPackage( String fqn )
{
  //System.out.println( "findPackage() : " + fqn );

  List<ManModule> modules = ManProject.manProjectFrom( _project ).getModules();
  PsiManager manager = PsiManagerImpl.getInstance( _project );
  for( ManModule mm : modules )
  {
    for( ITypeManifold sp : mm.getTypeManifolds() )
    {
      if( sp.getProducerKind() != Supplemental && sp.isPackage( fqn ) )
      {
        return new NonDirectoryPackage( manager, fqn );
      }
    }
  }
  return null;
}
 
Example 36
Project: GravSupport   File: LanguageFileStrategy.java   Source Code and License 6 votes vote down vote up
@Override
public TranslationTableModel createTableModel() {
    detactLanguages();
    Collection<String> availableKeys = new LinkedHashSet<>();//preserve order, no dups
    ConcurrentHashMap<String, Collection<YAMLKeyValue>> dataMap = new ConcurrentHashMap<>();
    VirtualFile virtualFile = fileMap.elements().nextElement();
    YAMLFileImpl yamlFile = (YAMLFileImpl) PsiManager.getInstance(project).findFile(virtualFile);
    if (yamlFile != null) {
        Collection<YAMLKeyValue> topLevelKeys = YAMLUtil.getTopLevelKeys(yamlFile);
        for (String eachLanguage : languages) {
            dataMap.put(eachLanguage, new HashSet<>());
            Collection<YAMLKeyValue> topLevelValuesLang = findChildValues(topLevelKeys, eachLanguage);
            for (YAMLKeyValue keyValue : topLevelValuesLang) {
                if (keyValue.getValue() instanceof YAMLCompoundValue) {
                    List<String> keysBuffer = new ArrayList<>();
                    getCompoundKeys0(keyValue, keyValue.getKeyText(), keysBuffer, dataMap, eachLanguage);
                    availableKeys.addAll(keysBuffer);
                } else {
                    availableKeys.add(keyValue.getKeyText());
                    dataMap.get(eachLanguage).add(keyValue);
                }
            }
        }
    }
    return new TranslationTableModel(availableKeys, dataMap).setPrefixKey(true);
}
 
Example 37
Project: GravSupport   File: GravLangFileEditor.java   Source Code and License 6 votes vote down vote up
/**
     * TableModel listener
     *
     * @param e
     */
    @Override
    public void tableChanged(TableModelEvent e) {
//        TODO Do something with the data...
        System.out.println(e.getType());
        if (e.getType() == TableModelEvent.INSERT) {
            //TODO update all files
//            TranslationTableModel model = (TranslationTableModel) editor.getTable1().getModel();
            String lang = editor.getCurrentLang();
            VirtualFile file = getFileMap().get(lang);
            if (file.exists()) {
                YAMLFileImpl yamlFile = (YAMLFileImpl) PsiManager.getInstance(project).findFile(file);
                if (yamlFile != null) {
                    System.out.println(yamlFile);
                }
            }
        }
    }
 
Example 38
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 39
Project: intellij-spring-assistant   File: PropertiesDocumentationProvider.java   Source Code and License 5 votes vote down vote up
DocumentationProxyElement(@NotNull final PsiManager manager, @NotNull final Language language,
    @NotNull final MetadataNode target, boolean requestedForTargetValue,
    @Nullable String value) {
  super(manager, language);
  this.target = target;
  this.requestedForTargetValue = requestedForTargetValue;
  this.value = value;
}
 
Example 40
Project: TS-IJ   File: TSFunctionCachedListGenerator.java   Source Code and License 5 votes vote down vote up
@Override
public Set<TSFnDeclStmt> generate(Project project) {
    Set<TSFnDeclStmt> items = new HashSet<>();
    //Search every file in the project
    Collection<VirtualFile> virtualFiles = FileBasedIndex.getInstance().getContainingFiles(FileTypeIndex.NAME, TSFileType.INSTANCE, GlobalSearchScope.projectScope(project));
    for (VirtualFile virtualFile : virtualFiles) {
        TSFile tsFile = (TSFile) PsiManager.getInstance(project).findFile(virtualFile);
        if (tsFile != null) {
            TSFnDeclStmt[] functions = PsiTreeUtil.getChildrenOfType(tsFile, TSFnDeclStmt.class);
            if (functions != null) {
                Collections.addAll(items, functions);
            }

            TSPackageDecl[] packages = PsiTreeUtil.getChildrenOfType(tsFile, TSPackageDecl.class);
            if (packages != null) {
                for (TSPackageDecl pack : packages) {
                    functions = PsiTreeUtil.getChildrenOfType(pack, TSFnDeclStmt.class);
                    if (functions != null) {
                        Collections.addAll(items, functions);
                    }
                }
            }
            ProgressManager.progress("Loading Symbols");
        }
    }
    return items;
}