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: GravSupport   File: GravLangFileEditor.java   Source Code and License 7 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 2
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 3
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 4
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 5
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 6
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 7
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 8
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 9
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 10
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 11
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 12
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 13
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 14
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 15
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 16
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 17
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 18
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 19
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 20
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 21
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 22
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 23
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 24
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 25
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 26
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 27
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 28
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 29
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 30
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 31
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 32
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 33
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 34
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 35
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 36
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 37
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 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;
}
 
Example 41
Project: TS-IJ   File: TSObjectCachedListGenerator.java   Source Code and License 5 votes vote down vote up
@Override
public Set<TSObjectExpr> generate(Project project) {
    Set<TSObjectExpr> 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) {
            items.addAll(PsiTreeUtil.findChildrenOfType(tsFile, TSObjectExpr.class));
            items.addAll(PsiTreeUtil.findChildrenOfType(tsFile, TSDatablockDecl.class));
        }
        ProgressManager.progress("Loading Symbols");
    }
    return items;
}
 
Example 42
Project: AppleScript-IDEA   File: SDEF_Parser.java   Source Code and License 5 votes vote down vote up
private static void processIncludes(@NotNull ApplicationDictionary parsedDictionary, @Nullable XmlTag[] includes) {
    if (includes == null) return;
    for (XmlTag include : includes) {
      String hrefIncl = include.getAttributeValue("href");
      if (!StringUtil.isEmpty(hrefIncl)) {
        hrefIncl = hrefIncl.replace("file://localhost", "");
        File includedFile = new File(hrefIncl);
//        ((IncludedXmlTag) suiteTag).getOriginal().getContainingFile();
        //as there is assertion error (java.lang.AssertionError: File accessed outside allowed roots),
        // we are trying to find if the dictionary file for this included dictionary was already generated
        AppleScriptSystemDictionaryRegistryService dictionarySystemRegistry = ServiceManager
            .getService(AppleScriptSystemDictionaryRegistryService.class);
        VirtualFile vFile;
        File ioFile = null;
        DictionaryInfo dInfo = dictionarySystemRegistry.getDictionaryInfoByApplicationPath(includedFile.getPath());
        if (dInfo != null) {
          ioFile = dInfo.getDictionaryFile();
        } else if (includedFile.isFile()) {
          String fName = includedFile.getName();
          int index = fName.lastIndexOf('.');
          fName = index < 0 ? fName : fName.substring(0, index);
          ioFile = dictionarySystemRegistry.getDictionaryFile(fName);
        }
        if (ioFile == null || !ioFile.exists()) ioFile = includedFile;
        if (ioFile.exists()) {
          vFile = LocalFileSystem.getInstance().findFileByIoFile(ioFile);
          if (vFile == null || !vFile.isValid()) continue;

          PsiFile psiFile = PsiManager.getInstance(parsedDictionary.getProject()).findFile(vFile);
          XmlFile xmlFile = (XmlFile) psiFile;
          if (xmlFile != null) {
            parsedDictionary.processInclude(xmlFile);
          }
        }
      }
    }
  }
 
Example 43
Project: jgiven-intellij-plugin   File: ScenarioStateReferenceProvider.java   Source Code and License 5 votes vote down vote up
public List<PsiReference> findReferences(PsiField field, int maxNumberOfResults) {
    PsiClass fieldClass = PsiTypesUtil.getPsiClass(field.getType());
    if (fieldClass == null) {
        return Collections.emptyList();
    }
    Project project = field.getProject();
    PsiManager manager = PsiManager.getInstance(project);
    JGivenUsageProvider usageProvider = new JGivenUsageProvider(scenarioStateProvider, resolutionHandler, new ReferenceFactory(manager));
    StateReferenceProcessor processor = new StateReferenceProcessor(field, maxNumberOfResults, usageProvider);

    SearchScope scope = GlobalSearchScope.everythingScope(project).intersectWith(javaFilesScope(project));

    findPsiFields(project, (GlobalSearchScope) scope, processor);
    return processor.getResults();
}
 
Example 44
Project: reasonml-idea-plugin   File: RmlPsiUtil.java   Source Code and License 5 votes vote down vote up
@NotNull
public static List<PsiModule> findModules(@NotNull Project project) {
    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) {
            result.addAll(Arrays.asList(modules));
        }
    }

    return result;
}
 
Example 45
Project: idea-php-typo3-plugin   File: RouteHelper.java   Source Code and License 5 votes vote down vote up
@NotNull
public static PsiElement[] getRouteDefinitionElements(@NotNull Project project, @NotNull String routeName) {
    List<PsiElement> results = new ArrayList<>();

    for (PsiElement psiElement : RouteHelper.getTargetMethods(project, routeName)) {

        if (psiElement instanceof Method) {
            results.add(psiElement);
        }

    }

    // Route definition
    Set<String> keys = new HashSet<>();
    keys.add(routeName);
    FileBasedIndex.getInstance().getFilesWithKey(RouteIndex.KEY, keys, virtualFile -> {
        FileBasedIndex.getInstance().processValues(RouteIndex.KEY, routeName, virtualFile, (file, value) -> {
            PsiFile file1 = PsiManager.getInstance(project).findFile(file);
            if (file1 != null) {
                PsiElement elementAt = file1.findElementAt(value.getTextRange().getStartOffset());
                if (elementAt != null) {
                    results.add(elementAt.getParent());
                }
            }

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

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

    return results.toArray(new PsiElement[results.size()]);
}
 
Example 46
Project: idea-php-typo3-plugin   File: FilesystemUtil.java   Source Code and License 5 votes vote down vote up
@Nullable
public static PsiDirectory findParentExtensionDirectory(@NotNull PsiDirectory directory) {

    VirtualFile extensionRootFolder = findExtensionRootFolder(directory.getVirtualFile());
    if (extensionRootFolder == null) {
        return null;
    }

    return PsiManager.getInstance(directory.getProject()).findDirectory(extensionRootFolder);
}
 
Example 47
Project: intellij-csv-validator   File: CsvStructureViewElement.java   Source Code and License 5 votes vote down vote up
protected PsiElement createEmptyPsiField() {
    final String text = "<undefined>";
    final IElementType type = CsvTypes.FIELD;
    final Project project = this.element.getProject();
    final PsiManager psiManager = PsiManager.getInstance(project);
    final DummyHolder dummyHolder = DummyHolderFactory.createHolder(psiManager, null);
    final FileElement fileElement = dummyHolder.getTreeElement();
    final ParserDefinition parserDefinition = LanguageParserDefinitions.INSTANCE.forLanguage(CsvLanguage.INSTANCE);
    final Lexer lexer = parserDefinition.createLexer(project);
    final PsiBuilder psiBuilder = PsiBuilderFactory.getInstance().createBuilder(project, fileElement, lexer, CsvLanguage.INSTANCE, text);
    final ASTNode node = parserDefinition.createParser(project).parse(type, psiBuilder);
    fileElement.rawAddChildren((com.intellij.psi.impl.source.tree.TreeElement)node);
    return node.getPsi();
}
 
Example 48
Project: magento2-phpstorm-plugin   File: SettingsForm.java   Source Code and License 5 votes vote down vote up
@Nullable
private String buildUrnKeyForFile(@NotNull PsiFile psiFile, @NotNull MagentoComponent magentoComponent) {
    String prefix = null;

    if (magentoComponent instanceof MagentoModule) {
        prefix = MODULE + ((MagentoModule)magentoComponent).getMagentoName() + ":";
    } else {
        ComposerPackageModel composerPackageModel = magentoComponent.getComposerModel();
        if ("magento2-library".equals(composerPackageModel.getType())) {
            prefix = FRAMEWORK;
        }
    }

    if (prefix == null) {
        return null;
    }

    Stack<String> relativePath = new Stack<>();
    relativePath.push(psiFile.getName());

    PsiManager psiManager = magentoComponent.getDirectory().getManager();
    PsiDirectory parentDir = psiFile.getParent();
    while (parentDir != null && !psiManager.areElementsEquivalent(parentDir, magentoComponent.getDirectory())) {
        relativePath.push("/");
        relativePath.push(parentDir.getName());
        parentDir = parentDir.getParentDirectory();
    }

    StringBuilder stringBuilder = new StringBuilder(prefix);
    while (!relativePath.empty()) {
        stringBuilder.append(relativePath.pop());
    }

    return stringBuilder.toString();
}
 
Example 49
Project: magento2-phpstorm-plugin   File: MagentoComponentManager.java   Source Code and License 5 votes vote down vote up
private void loadModules() {
    Collection<String> packages = FileBasedIndex.getInstance().getAllKeys(ModulePackageIndex.KEY, this.project);
    PsiManager psiManager = PsiManager.getInstance(this.project);
    for (String packageName: packages) {
        if (components.containsKey(packageName)) {
            continue;
        }

        Collection<VirtualFile> containingFiles = FileBasedIndex.getInstance()
            .getContainingFiles(ModulePackageIndex.KEY, packageName, GlobalSearchScope.allScope(this.project));

        if (containingFiles.size() > 0) {
            VirtualFile configurationFile = containingFiles.iterator().next();

            PsiFile psiFile = psiManager.findFile(configurationFile);
            if (psiFile != null && psiFile instanceof JsonFile) {
                JsonObject jsonObject = PsiTreeUtil.getChildOfType((JsonFile) psiFile, JsonObject.class);
                if (jsonObject == null) {
                    continue;
                }

                MagentoComponent magentoComponent;
                ComposerPackageModel composerPackageModel = new ComposerPackageModelImpl(jsonObject);
                if ("magento2-module".equals(composerPackageModel.getType())) {
                    magentoComponent = new MagentoModuleImpl(new ComposerPackageModelImpl(jsonObject), psiFile.getContainingDirectory());
                } else {
                    magentoComponent = new MagentoComponentImp(new ComposerPackageModelImpl(jsonObject), psiFile.getContainingDirectory());
                }

                components.put(
                    packageName,
                    magentoComponent
                );
            }
        }
    }
}
 
Example 50
Project: bamboo-soy   File: SoyFileViewProviderFactory.java   Source Code and License 5 votes vote down vote up
@NotNull
@Override
public FileViewProvider createFileViewProvider(
    @NotNull VirtualFile virtualFile,
    Language language,
    @NotNull PsiManager psiManager,
    boolean eventSystemEnabled) {
  assert language.isKindOf(SoyLanguage.INSTANCE);
  return new SoyFileViewProvider(psiManager, virtualFile, eventSystemEnabled);
}
 
Example 51
Project: json2java4idea   File: MethodNamePolicyTest.java   Source Code and License 5 votes vote down vote up
@Before
@Override
public void setUp() throws Exception {
    super.setUp();
    application = getApplication();

    final Project project = getProject();
    final PsiManager psiManager = PsiManager.getInstance(project);
    final PsiTypeConverter converter = new PsiTypeConverter(psiManager);
    underTest = new MethodNamePolicy(project, converter);
}
 
Example 52
Project: json2java4idea   File: PsiTypeConverterTest.java   Source Code and License 5 votes vote down vote up
@Before
@Override
public void setUp() throws Exception {
    super.setUp();
    final Project project = getProject();
    final PsiManager psiManager = PsiManager.getInstance(project);
    underTest = new PsiTypeConverter(psiManager);
}
 
Example 53
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 54
Project: intellij-postfix-templates   File: CustomPostfixTemplateProvider.java   Source Code and License 5 votes vote down vote up
/**
 * Loads the postfix templates from the given virtual file and returns them.
 *
 * @param vFile virtual templates file
 * @return set of postfix templates
 */
@SuppressWarnings("WeakerAccess")
public Set<PostfixTemplate> loadTemplatesFrom(@NotNull VirtualFile vFile) {
	Set<PostfixTemplate> templates = new OrderedSet<>();

	ApplicationManager.getApplication().runReadAction(() -> {
		Project project = ProjectManager.getInstance().getOpenProjects()[0];

		CptFile cptFile = (CptFile) PsiManager.getInstance(project).findFile(vFile);
		if (cptFile != null) {
			CptTemplate[] cptTemplates = PsiTreeUtil.getChildrenOfType(cptFile, CptTemplate.class);
			if (cptTemplates != null) {
				for (CptTemplate cptTemplate : cptTemplates) {
					for (CptMapping mapping : cptTemplate.getMappings().getMappingList()) {
						StringBuilder sb = new StringBuilder();
						for (PsiElement element : mapping.getReplacement().getChildren()) {
							sb.append(element.getText());
						}

						templates.add(createTemplate(mapping.getMatchingClass(), mapping.getConditionClass(), cptTemplate.getTemplateName(), cptTemplate.getTemplateDescription(), sb.toString()));
					}
				}
			}
		}
	});

	return combineTemplatesWithSameName(templates);
}
 
Example 55
Project: intellij-bpmn-editor   File: BPMNFileSchemaProvider.java   Source Code and License 5 votes vote down vote up
private static XmlFile getReference(@NotNull @NonNls String url, @NotNull Module module) {
    if (url.equalsIgnoreCase("http://bpmn.sourceforge.net")) {
        return null;
    }
    final URL resource = BPMNFileSchemaProvider.class.getResource(BPMNModelConstants.BPMN_SCHEMA_BASEURI + BPMNModelConstants.BPMN_SYSTEM_ID);
    final VirtualFile fileByURL = VfsUtil.findFileByURL(resource);
    if (fileByURL == null) {
        return null;
    }

    PsiFile psiFile = PsiManager.getInstance(module.getProject()).findFile(fileByURL);
    return (XmlFile) psiFile.copy();
}
 
Example 56
Project: hybris-integration-intellij-idea-plugin   File: HybrisAntBuildListener.java   Source Code and License 5 votes vote down vote up
private void triggerCleanAll(final Project project) {
    final HybrisProjectSettings yProjectSettings = HybrisProjectSettingsComponent.getInstance(project).getState();
    final File platformDir = new File(project.getBasePath() + "/" +
                                      yProjectSettings.getHybrisDirectory() + PLATFORM_MODULE_PREFIX);
    final VirtualFile vfPlatformDir = VfsUtil.findFileByIoFile(platformDir, true);
    final VirtualFile vfBuildFile = VfsUtil.findRelativeFile(vfPlatformDir, HybrisConstants.ANT_BUILD_XML);

    if (vfBuildFile == null) {
        return;
    }
    final PsiFile psiBuildFile = PsiManager.getInstance(project).findFile(vfBuildFile);

    if (psiBuildFile == null) {
        return;
    }
    final AntConfigurationBase antConfiguration = AntConfigurationBase.getInstance(project);
    final AntBuildFileBase antBuildFile = antConfiguration.getAntBuildFile(psiBuildFile);

    if (antBuildFile != null) {
        ExecutionHandler.runBuild(
            antBuildFile,
            antCleanAll,
            null,
            getDataContext(project),
            Collections.emptyList(),
            AntBuildListener.NULL
        );
    }
}
 
Example 57
Project: educational-plugin   File: PyStudyDirectoryProjectGenerator.java   Source Code and License 5 votes vote down vote up
private static void createTestHelper(@NotNull Project project, @NotNull VirtualFile baseDir) {
  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 58
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 59
Project: educational-plugin   File: EduCCModuleBuilder.java   Source Code and License 5 votes vote down vote up
@NotNull
@Override
public Module createModule(@NotNull ModifiableModuleModel moduleModel)
  throws InvalidDataException, IOException, ModuleWithNameAlreadyExists,
         JDOMException, ConfigurationException {
  Module module = super.createModule(moduleModel);
  Project project = module.getProject();
  final Course course = new Course();
  course.setName(myPanel.getName());
  course.setAuthorsAsString(myPanel.getAuthors());
  course.setDescription(myPanel.getDescription());
  LanguageWrapper wrapper = (LanguageWrapper)myLanguageComboBox.getSelectedItem();
  Language language = wrapper.getLanguage();
  course.setLanguage(language.getID());
  course.setCourseMode(CCUtils.COURSE_MODE);
  StudyTaskManager.getInstance(project).setCourse(course);
  EduPluginConfigurator configurator = EduPluginConfigurator.INSTANCE.forLanguage(language);
  String languageName = language.getDisplayName();
  if (configurator == null) {
    LOG.error("EduPluginConfigurator for language " + languageName + " not found");
    return module;
  }
  configurator.createCourseModuleContent(moduleModel, project, course, getModuleFileDirectory());
  StartupManager.getInstance(project).runWhenProjectIsInitialized(() -> new WriteCommandAction.Simple(project) {
    @Override
    protected void run() throws Throwable {
      PsiDirectory baseDir = PsiManager.getInstance(project).findDirectory(project.getBaseDir());
      if (baseDir == null) {
        return;
      }
      PsiDirectory lessonDir = new CCCreateLesson().createItem(null, project, baseDir, course);
      if (lessonDir == null) {
        LOG.error("Failed to create lesson");
        return;
      }
      new CCCreateTask().createItem(null, project, lessonDir, course);
    }
  }.execute());
  return module;
}
 
Example 60
Project: educational-plugin   File: CCShowPreviewTest.java   Source Code and License 5 votes vote down vote up
public void testPreviewUnavailable() {
  VirtualFile file = configureByTaskFile("noplaceholders.txt");
  CCShowPreview action = new CCShowPreview();
  TestActionEvent e = getActionEvent(action, PsiManager.getInstance(getProject()).findFile(file));
  action.beforeActionPerformedUpdate(e);
  assertTrue(e.getPresentation().isEnabled() && e.getPresentation().isVisible());
  try {
    action.actionPerformed(e);
    assertTrue("No message shown", false);
  } catch (RuntimeException ex) {
    assertEquals(CCShowPreview.NO_PREVIEW_MESSAGE, ex.getMessage());
  }
}