com.intellij.psi.PsiManager Java Examples

The following examples show how to use com.intellij.psi.PsiManager. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: FindUsagesImpl171.java    From Android-Resource-Usage-Count with MIT 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 #2
Source File: BuckBuildUtil.java    From buck with Apache License 2.0 6 votes vote down vote up
/**
 * Get the buck target from a buck file. TODO(#7908675): We should use Buck's own classes for it.
 */
public static String extractBuckTarget(Project project, VirtualFile file) {
  BuckFile buckFile = (BuckFile) PsiManager.getInstance(project).findFile(file);
  if (buckFile == null) {
    return null;
  }

  PsiElement[] children = buckFile.getChildren();
  for (PsiElement child : children) {
    if (child.getNode().getElementType() == BuckTypes.STATEMENT) {
      BuckFunctionTrailer functionTrailer =
          PsiTreeUtil.findChildOfType(child, BuckFunctionTrailer.class);
      // Find rule "project_config"
      if (functionTrailer != null) {
        return getPropertyStringValue(functionTrailer, SRC_TARGET_PROPERTY_NAME);
      }
    }
  }
  return null;
}
 
Example #3
Source File: GUI.java    From svgtoandroid with MIT License 6 votes vote down vote up
private void showSVGChooser() {
    FileChooserDescriptor descriptor = FileChooserDescriptorFactory.createSingleFolderDescriptor();
    if (!batch.isSelected()) {
        descriptor = FileChooserDescriptorFactory.createSingleFileDescriptor("svg");
    }
    VirtualFile virtualFile = FileChooser.chooseFile(descriptor, project, null);
    if (virtualFile != null) {
        if (!virtualFile.isDirectory() && virtualFile.getName().toLowerCase().endsWith("svg")) {
            svg = (XmlFile) PsiManager.getInstance(project).findFile(virtualFile);
            //got *.svg file as xml
            svgPath.setText(virtualFile.getPath());
            xmlName.setEditable(true);
            xmlName.setEnabled(true);
            xmlName.setText(CommonUtil.getValidName(svg.getName().split("\\.")[0]) + ".xml");
        } else if (virtualFile.isDirectory()) {
            svgDir = PsiManager.getInstance(project).findDirectory(virtualFile);
            svgPath.setText(virtualFile.getPath());
            xmlName.setEditable(false);
            xmlName.setEnabled(false);
            xmlName.setText("keep origin name");
        }
    }
    frame.setAlwaysOnTop(true);
}
 
Example #4
Source File: AbstractUploadCloudActionTest.java    From markdown-image-kit with MIT License 6 votes vote down vote up
/**
 * 获取 document 的几种方式
 *
 * @param e the e
 */
private void getDocument(AnActionEvent e) {
    // 从当前编辑器中获取
    Document documentFromEditor = Objects.requireNonNull(e.getData(PlatformDataKeys.EDITOR)).getDocument();
    // 从 VirtualFile 获取 (如果之前未加载文档内容,则此调用会强制从磁盘加载文档内容)
    VirtualFile virtualFile = e.getData(PlatformDataKeys.VIRTUAL_FILE);
    if (virtualFile != null) {
        Document documentFromVirtualFile = FileDocumentManager.getInstance().getDocument(virtualFile);
        // 从缓存中获取
        Document documentFromVirtualFileCache = FileDocumentManager.getInstance().getCachedDocument(virtualFile);

        // 从 PSI 中获取
        Project project = e.getProject();
        if (project != null) {
            // 获取 PSI (一)
            PsiFile psiFile = PsiManager.getInstance(project).findFile(virtualFile);
            // 获取 PSI (二)
            psiFile = e.getData(CommonDataKeys.PSI_FILE);
            if (psiFile != null) {
                Document documentFromPsi = PsiDocumentManager.getInstance(project).getDocument(psiFile);
                // 从缓存中获取
                Document documentFromPsiCache = PsiDocumentManager.getInstance(project).getCachedDocument(psiFile);
            }
        }
    }
}
 
Example #5
Source File: HaxeComponentIndex.java    From intellij-haxe with Apache License 2.0 6 votes vote down vote up
public static List<HaxeComponent> getItemsByName(String name, Project project, GlobalSearchScope searchScope) {
  HaxeIndexUtil.warnIfDumbMode(project);
  Collection<VirtualFile> files =
    FileBasedIndex.getInstance().getContainingFiles(HAXE_COMPONENT_INDEX, name, searchScope);
  final List<HaxeComponent> result = new ArrayList<HaxeComponent>();
  for (VirtualFile vFile : files) {
    PsiFile file = PsiManager.getInstance(project).findFile(vFile);
    if (file == null || file.getFileType() != HaxeFileType.HAXE_FILE_TYPE) {
      continue;
    }
    final HaxeComponent component = HaxeResolveUtil.findComponentDeclaration(file, name);
    if (component != null) {
      result.add(component);
    }
  }
  return result;
}
 
Example #6
Source File: IdeaUtils.java    From camel-idea-plugin with Apache License 2.0 6 votes vote down vote up
public void iterateXmlDocumentRoots(Module module, Consumer<XmlTag> rootTag) {
    final GlobalSearchScope moduleScope = module.getModuleContentScope();
    final GlobalSearchScope xmlFiles = GlobalSearchScope.getScopeRestrictedByFileTypes(moduleScope, XmlFileType.INSTANCE);

    ModuleFileIndex fileIndex = ModuleRootManager.getInstance(module).getFileIndex();
    fileIndex.iterateContent(f -> {
        if (xmlFiles.contains(f)) {
            PsiFile file = PsiManager.getInstance(module.getProject()).findFile(f);
            if (file instanceof XmlFile) {
                XmlFile xmlFile = (XmlFile) file;
                XmlTag root = xmlFile.getRootTag();
                if (root != null) {
                    rootTag.accept(xmlFile.getRootTag());
                }
            }
        }
        return true;
    });
}
 
Example #7
Source File: JSGraphQLEndpointCompletionContributor.java    From js-graphql-intellij-plugin with MIT License 6 votes vote down vote up
private boolean completeImportFile(@NotNull CompletionResultSet result, PsiFile file, PsiElement parent) {
	if ((parent instanceof JSGraphQLEndpointQuotedString || parent instanceof JSGraphQLEndpointString) && PsiTreeUtil.getParentOfType(parent, JSGraphQLEndpointImportFileReference.class) != null) {

		final Project project = file.getProject();
		final VirtualFile entryFile = JSGraphQLConfigurationProvider.getService(project).getEndpointEntryFile(file);
		final GlobalSearchScope scope = JSGraphQLEndpointPsiUtil.getImportScopeFromEntryFile(project, entryFile, file);
		final Collection<VirtualFile> files = FileTypeIndex.getFiles(JSGraphQLEndpointFileType.INSTANCE, scope);
		for (VirtualFile virtualFile : files) {
			if(virtualFile.equals(entryFile)) {
				// entry file should never be imported
				continue;
			}
			final PsiFile psiFile = PsiManager.getInstance(project).findFile(virtualFile);
			if (psiFile != null) {
				if(psiFile.equals(file)) {
					// don't suggest the current file
					continue;
				}
				String name = JSGraphQLEndpointImportUtil.getImportName(project, psiFile);
				result.addElement(LookupElementBuilder.create(name).withIcon(psiFile.getIcon(0)));
			}
		}
		return true;
	}
	return false;
}
 
Example #8
Source File: GraphQLTreeNodeNavigationUtil.java    From js-graphql-intellij-plugin with MIT License 6 votes vote down vote up
public static void openSourceLocation(Project myProject, SourceLocation location, boolean resolveSDLFromJSON) {
    VirtualFile sourceFile = StandardFileSystems.local().findFileByPath(location.getSourceName());
    if (sourceFile != null) {
        PsiFile file = PsiManager.getInstance(myProject).findFile(sourceFile);
        if (file != null) {
            if (file instanceof JsonFile && resolveSDLFromJSON) {
                GraphQLFile graphQLFile = file.getUserData(GraphQLSchemaKeys.GRAPHQL_INTROSPECTION_JSON_TO_SDL);
                if (graphQLFile != null) {
                    // open the SDL file and not the JSON introspection file it was based on
                    file = graphQLFile;
                    sourceFile = file.getVirtualFile();
                }
            }
            new OpenFileDescriptor(myProject, sourceFile, location.getLine() - 1, location.getColumn() - 1).navigate(true);
        }
    }
}
 
Example #9
Source File: LSPQuickDocAction.java    From lsp4intellij with Apache License 2.0 6 votes vote down vote up
@Override
public void actionPerformed(AnActionEvent e) {
    Editor editor = e.getData(CommonDataKeys.EDITOR);
    VirtualFile file = FileDocumentManager.getInstance().getFile(editor.getDocument());
    Language language = PsiManager.getInstance(editor.getProject()).findFile(file).getLanguage();
    //Hack for IntelliJ 2018 TODO proper way
    if (LanguageDocumentation.INSTANCE.allForLanguage(language).isEmpty()
            || (Integer.parseInt(ApplicationInfo.getInstance().getMajorVersion()) > 2017)
            && language == PlainTextLanguage.INSTANCE) {
        EditorEventManager manager = EditorEventManagerBase.forEditor(editor);
        if (manager != null) {
            manager.quickDoc(editor);
        } else {
            super.actionPerformed(e);
        }
    } else
        super.actionPerformed(e);
}
 
Example #10
Source File: IncompatibleDartPluginNotificationProvider.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public EditorNotificationPanel createNotificationPanel(@NotNull VirtualFile file, @NotNull FileEditor fileEditor) {
  if (!FlutterUtils.isFlutteryFile(file)) return null;

  final PsiFile psiFile = PsiManager.getInstance(myProject).findFile(file);
  if (psiFile == null) return null;

  if (psiFile.getLanguage() != DartLanguage.INSTANCE) return null;

  final Module module = ModuleUtilCore.findModuleForPsiElement(psiFile);
  if (module == null) return null;

  if (!FlutterModuleUtils.isFlutterModule(module)) return null;

  final Version minimumVersion = DartPlugin.getInstance().getMinimumVersion();
  final Version dartVersion = DartPlugin.getInstance().getVersion();
  if (dartVersion.minor == 0 && dartVersion.bugfix == 0) {
    return null; // Running from sources.
  }
  return dartVersion.compareTo(minimumVersion) < 0 ? createUpdateDartPanel(myProject, module, dartVersion.toCompactString(),
                                                                           getPrintableRequiredDartVersion()) : null;
}
 
Example #11
Source File: EntityHelper.java    From idea-php-symfony2-plugin with MIT License 6 votes vote down vote up
@Nullable
private static PsiFile getEntityMetadataFile(@NotNull Project project, @NotNull SymfonyBundle symfonyBundleUtil, @NotNull String className, @NotNull String modelShortcut) {

    for(String s: new String[] {"yml", "yaml", "xml"}) {

        String entityFile = "Resources/config/doctrine/" + className + String.format(".%s.%s", modelShortcut, s);
        VirtualFile virtualFile = symfonyBundleUtil.getRelative(entityFile);
        if(virtualFile != null) {
            PsiFile psiFile = PsiManager.getInstance(project).findFile(virtualFile);
            if(psiFile != null) {
                return psiFile;
            }
        }

    }

    return null;
}
 
Example #12
Source File: IconIndex.java    From idea-php-typo3-plugin with MIT 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 #13
Source File: Utils.java    From idea-gitignore with MIT License 6 votes vote down vote up
/**
 * Finds {@link PsiFile} for the given {@link VirtualFile} instance. If file is outside current project,
 * it's required to create new {@link PsiFile} manually.
 *
 * @param project     current project
 * @param virtualFile to handle
 * @return {@link PsiFile} instance
 */
@Nullable
public static PsiFile getPsiFile(@NotNull Project project, @NotNull VirtualFile virtualFile) {
    PsiFile psiFile = PsiManager.getInstance(project).findFile(virtualFile);

    if (psiFile == null) {
        FileViewProvider viewProvider = PsiManager.getInstance(project).findViewProvider(virtualFile);
        if (viewProvider != null) {
            IgnoreLanguage language = IgnoreBundle.obtainLanguage(virtualFile);
            if (language != null) {
                psiFile = language.createFile(viewProvider);
            }
        }
    }

    return psiFile;
}
 
Example #14
Source File: ShowUsagesTableCellRenderer.java    From dagger-intellij-plugin with Apache License 2.0 6 votes vote down vote up
private Color getBackgroundColor(boolean isSelected, Usage usage) {
  Color fileBgColor = null;
  if (isSelected) {
    fileBgColor = UIUtil.getListSelectionBackground();
  } else {
    VirtualFile virtualFile =
        usage instanceof UsageInFile ? ((UsageInFile) usage).getFile() : null;
    if (virtualFile != null) {
      Project project = myUsageView.getProject();
      PsiFile psiFile = PsiManager.getInstance(project).findFile(virtualFile);
      if (psiFile != null && psiFile.isValid()) {
        final Color color = FileColorManager.getInstance(project).getRendererBackground(psiFile);
        if (color != null) fileBgColor = color;
      }
    }
  }
  return fileBgColor;
}
 
Example #15
Source File: SnippetUtil.java    From idea-php-shopware-plugin with MIT License 6 votes vote down vote up
/**
 * Snippet target, only use ini files
 */
@NotNull
public static Set<PsiElement> getSnippetNamespaceTargets(@NotNull Project project, @NotNull String namespace) {
    Set<VirtualFile> files = new HashSet<>();

    FileBasedIndexImpl.getInstance().getFilesWithKey(SnippetIndex.KEY, new HashSet<>(Collections.singletonList(namespace)), virtualFile -> {
        if("ini".equalsIgnoreCase(virtualFile.getExtension())) {
            files.add(virtualFile);
        }

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

    // we are not allows to resolve inside index process
    PsiManager instance = PsiManager.getInstance(project);

    return files.stream()
        .map(instance::findFile)
        .filter(Objects::nonNull)
        .collect(Collectors.toSet());
}
 
Example #16
Source File: ChangeUtil.java    From consulo with Apache License 2.0 6 votes vote down vote up
public static void prepareAndRunChangeAction(final ChangeAction action, final TreeElement changedElement){
  final FileElement changedFile = TreeUtil.getFileElement(changedElement);
  final PsiManager manager = changedFile.getManager();
  final PomModel model = PomManager.getModel(manager.getProject());
  final TreeAspect treeAspect = model.getModelAspect(TreeAspect.class);
  model.runTransaction(new PomTransactionBase(changedElement.getPsi(), treeAspect) {
    @Override
    public PomModelEvent runInner() {
      final PomModelEvent event = new PomModelEvent(model);
      final TreeChangeEvent destinationTreeChange = new TreeChangeEventImpl(treeAspect, changedFile);
      event.registerChangeSet(treeAspect, destinationTreeChange);
      action.makeChange(destinationTreeChange);

      changedElement.clearCaches();
      if (changedElement instanceof CompositeElement) {
        ((CompositeElement) changedElement).subtreeChanged();
      }
      return event;
    }
  });
}
 
Example #17
Source File: ProcessAction.java    From JHelper with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
protected void performAction(AnActionEvent e) {
	Project project = e.getProject();
	if (project == null) {
		throw new NotificationException("No project found", "Are you in any project?");
	}
	FileEditorManager manager = FileEditorManager.getInstance(project);
	if (manager == null) {
		throw new NotificationException("This is unexpected", "File editor manager is null");
	}
	VirtualFile[] files = manager.getSelectedFiles();
	if (files.length == 0) {
		throw new NotificationException("No file found", "Do you have opened file?");
	}
	PsiFile file = PsiManager.getInstance(project).findFile(files[0]);
	if (file == null) {
		throw new NotificationException("This is unexpected", "No associated PsiFile");
	}
	if (!FileUtils.isCppFile(file)) {
		throw new NotificationException("Not a cpp file", "Only cpp files are currently supported");
	}
	String result = IncludesProcessor.process(file);
	FileUtils.writeToFile(file, result);
}
 
Example #18
Source File: Unity3dSceneCSharpFieldReference.java    From consulo-unity3d with Apache License 2.0 6 votes vote down vote up
@RequiredReadAction
@Nullable
@Override
public PsiElement resolve()
{
	Project project = myKeyValue.getProject();
	PsiFile file = PsiManager.getInstance(project).findFile(myCSharpFile);
	if(!(file instanceof CSharpFile))
	{
		return null;
	}

	CSharpTypeDeclaration type = Unity3dAssetUtil.findPrimaryType(file);
	if(type == null)
	{
		return null;
	}

	return findField(type, getCanonicalText());
}
 
Example #19
Source File: ResourcePathIndex.java    From idea-php-typo3-plugin with MIT 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 #20
Source File: CSharpFragmentFactory.java    From consulo-csharp with Apache License 2.0 6 votes vote down vote up
@Nonnull
public static CSharpFragmentFileImpl createExpressionFragment(Project project, String text, @Nullable final PsiElement context)
{
	LightVirtualFile virtualFile = new LightVirtualFile("dummy.cs", CSharpFileType.INSTANCE, text, System.currentTimeMillis());
	SingleRootFileViewProvider viewProvider = new SingleRootFileViewProvider(PsiManager.getInstance(project), virtualFile, true)
	{
		@Nonnull
		@Override
		public SingleRootFileViewProvider createCopy(@Nonnull final VirtualFile copy)
		{
			SingleRootFileViewProvider provider = new SingleRootFileViewProvider(getManager(), copy, false);
			CSharpFragmentFileImpl psiFile = new CSharpFragmentFileImpl(ourExpressionFileElementType, ourExpressionFileElementType, provider, context);
			provider.forceCachedPsi(psiFile);
			psiFile.getNode();
			return provider;
		}
	};
	CSharpFragmentFileImpl file = new CSharpFragmentFileImpl(ourExpressionFileElementType, ourExpressionFileElementType, viewProvider, context);
	viewProvider.forceCachedPsi(file);
	file.getNode();
	return file;
}
 
Example #21
Source File: FileContentUtil.java    From consulo with Apache License 2.0 6 votes vote down vote up
public static void setFileText(@javax.annotation.Nullable Project project, final VirtualFile virtualFile, final String text) throws IOException {
  if (project == null) {
    project = ProjectUtil.guessProjectForFile(virtualFile);
  }
  if (project != null) {
    final PsiFile psiFile = PsiManager.getInstance(project).findFile(virtualFile);
    final PsiDocumentManager psiDocumentManager = PsiDocumentManager.getInstance(project);
    final Document document = psiFile == null? null : psiDocumentManager.getDocument(psiFile);
    if (document != null) {
      document.setText(text != null ? text : "");
      psiDocumentManager.commitDocument(document);
      FileDocumentManager.getInstance().saveDocument(document);
      return;
    }
  }
  VfsUtil.saveText(virtualFile, text != null ? text : "");
  virtualFile.refresh(false, false);
}
 
Example #22
Source File: TemplateLineMarker.java    From idea-php-laravel-plugin with MIT License 5 votes vote down vote up
/**
 * Like this @section('sidebar')
 */
@NotNull
private Collection<LineMarkerInfo> collectOverwrittenSection(@NotNull LeafPsiElement psiElement, @NotNull String sectionName, @NotNull LazyVirtualFileTemplateResolver resolver) {
    List<GotoRelatedItem> gotoRelatedItems = new ArrayList<>();

    for(PsiElement psiElement1 : psiElement.getContainingFile().getChildren()) {
        PsiElement extendDirective = psiElement1.getFirstChild();
        if(extendDirective != null && extendDirective.getNode().getElementType() == BladeTokenTypes.EXTENDS_DIRECTIVE) {
            PsiElement bladeParameter = extendDirective.getNextSibling();
            if(bladeParameter instanceof BladePsiDirectiveParameter) {
                String extendTemplate = BladePsiUtil.getSection(bladeParameter);
                if(extendTemplate != null) {
                    for(VirtualFile virtualFile: resolver.resolveTemplateName(psiElement.getProject(), extendTemplate)) {
                        PsiFile psiFile = PsiManager.getInstance(psiElement.getProject()).findFile(virtualFile);
                        if(psiFile != null) {
                            visitOverwrittenTemplateFile(psiFile, gotoRelatedItems, sectionName, resolver);
                        }
                    }
                }
            }
        }
    }

    if(gotoRelatedItems.size() == 0) {
        return Collections.emptyList();
    }

    return Collections.singletonList(
        getRelatedPopover("Parent Section", "Blade Section", psiElement, gotoRelatedItems, PhpIcons.OVERRIDES)
    );
}
 
Example #23
Source File: ServiceLineMarkerProvider.java    From idea-php-symfony2-plugin with MIT License 5 votes vote down vote up
private void repositoryClassMarker(PsiElement psiElement, Collection<? super RelatedItemLineMarkerInfo> result) {

        PsiElement phpClassContext = psiElement.getContext();
        if(!(phpClassContext instanceof PhpClass)) {
            return;
        }

        Collection<PsiFile> psiFiles = new ArrayList<>();
        for (VirtualFile virtualFile : DoctrineMetadataUtil.findMetadataForRepositoryClass((PhpClass) phpClassContext)) {
            PsiFile file = PsiManager.getInstance(psiElement.getProject()).findFile(virtualFile);
            if(file == null) {
                continue;
            }

            psiFiles.add(file);
        }

        if(psiFiles.size() == 0) {
            return;
        }

        NavigationGutterIconBuilder<PsiElement> builder = NavigationGutterIconBuilder.create(Symfony2Icons.DOCTRINE_LINE_MARKER).
            setTargets(psiFiles).
            setTooltipText("Navigate to metadata");

        result.add(builder.createLineMarkerInfo(psiElement));
    }
 
Example #24
Source File: LombokLightParameter.java    From lombok-intellij-plugin with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public LombokLightParameter(@NotNull String name, @NotNull PsiType type, PsiElement declarationScope, Language language) {
  super(name, type, declarationScope, language);
  myName = name;
  PsiManager manager = declarationScope.getManager();
  myNameIdentifier = new LombokLightIdentifier(manager, name);
  ReflectionUtil.setFinalFieldPerReflection(LightVariableBuilder.class, this, LightModifierList.class,
    new LombokLightModifierList(manager, language, Collections.emptySet()));
}
 
Example #25
Source File: DependenciesPanel.java    From consulo with Apache License 2.0 5 votes vote down vote up
private void selectElementInLeftTree(PsiElement elt) {
  PsiManager manager = PsiManager.getInstance(myProject);

  PackageDependenciesNode root = (PackageDependenciesNode)myLeftTree.getModel().getRoot();
  Enumeration enumeration = root.breadthFirstEnumeration();
  while (enumeration.hasMoreElements()) {
    PackageDependenciesNode child = (PackageDependenciesNode)enumeration.nextElement();
    if (manager.areElementsEquivalent(child.getPsiElement(), elt)) {
      myLeftTree.setSelectionPath(new TreePath(((DefaultTreeModel)myLeftTree.getModel()).getPathToRoot(child)));
      break;
    }
  }
}
 
Example #26
Source File: TemplatesUtils.java    From JHelper with GNU Lesser General Public License v3.0 5 votes vote down vote up
private static void createTemplateFromDefault(Project project, String name) {
	String filename = name + ".template";
	VirtualFile file = FileUtils.findOrCreateByRelativePath(project.getBaseDir(), filename);
	PsiFile psiFile = PsiManager.getInstance(project).findFile(file);
	String defaultTemplate;
	try {
		defaultTemplate = getResourceContent("/name/admitriev/jhelper/templates/" + filename);
	}
	catch (IOException e) {
		throw new NotificationException("Couldn't open default template " + filename, e);
	}

	FileUtils.writeToFile(psiFile, defaultTemplate);
}
 
Example #27
Source File: BackgroundTaskByVfsChangeProvider.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
@RequiredReadAction
public String[] getGeneratedFiles(@Nonnull Project project, @Nonnull VirtualFile virtualFile) {
  PsiManager psiManager = PsiManager.getInstance(project);
  PsiFile file = psiManager.findFile(virtualFile);
  if (file != null) {
    return getGeneratedFiles(file);
  }
  return ArrayUtil.EMPTY_STRING_ARRAY;
}
 
Example #28
Source File: ConfigCompletionGoto.java    From idea-php-drupal-symfony2-bridge with MIT License 5 votes vote down vote up
@NotNull
@Override
public Collection<PsiElement> getPsiTargets(PsiElement psiElement) {

    PsiElement element = psiElement.getParent();
    if(!(element instanceof StringLiteralExpression)) {
        return Collections.emptyList();
    }

    final String contents = ((StringLiteralExpression) element).getContents();
    if(StringUtils.isBlank(contents)) {
        return Collections.emptyList();
    }

    final Collection<PsiElement> psiElements = new ArrayList<>();
    FileBasedIndex.getInstance().getFilesWithKey(ConfigSchemaIndex.KEY, new HashSet<>(Collections.singletonList(contents)), virtualFile -> {

        PsiFile psiFile = PsiManager.getInstance(getProject()).findFile(virtualFile);
        if(psiFile == null) {
            return true;
        }

        YAMLDocument yamlDocument = PsiTreeUtil.getChildOfType(psiFile, YAMLDocument.class);
        if(yamlDocument == null) {
            return true;
        }

        for(YAMLKeyValue yamlKeyValue: PsiTreeUtil.getChildrenOfTypeAsList(yamlDocument, YAMLKeyValue.class)) {
            String keyText = PsiElementUtils.trimQuote(yamlKeyValue.getKeyText());
            if(StringUtils.isNotBlank(keyText) && keyText.equals(contents)) {
                psiElements.add(yamlKeyValue);
            }
        }

        return true;
    }, GlobalSearchScope.getScopeRestrictedByFileTypes(GlobalSearchScope.allScope(getProject()), YAMLFileType.YML));

    return psiElements;
}
 
Example #29
Source File: FileOverwritesLazyLoader.java    From idea-php-symfony2-plugin with MIT License 5 votes vote down vote up
@NotNull
public Collection<VirtualFile> getFiles(boolean includeSelf, @NotNull Collection<VirtualFile> virtualFiles) {
    Map<VirtualFile, Collection<VirtualFile>> target;

    if(includeSelf) {
        // {{ block("foo") }}
        target = selfScope;
    } else {
        target = fileScope;
    }

    Collection<VirtualFile> virtualFileCollection = new HashSet<>();

    for (VirtualFile virtualFile : virtualFiles) {
        if(!target.containsKey(virtualFile)) {
            PsiFile file = PsiManager.getInstance(project).findFile(virtualFile);
            if(file != null) {
                target.put(virtualFile, TwigFileUtil.collectParentFiles(includeSelf, file));
            } else {
                target.put(virtualFile, Collections.emptySet());
            }
        }

        virtualFileCollection.addAll(target.get(virtualFile));
    }

    return virtualFileCollection;
}
 
Example #30
Source File: ScopeChooserCombo.java    From IntelliJDeodorant with MIT License 5 votes vote down vote up
private AnalysisScope getCurrentFileScope() {
    FileEditor currentEditor = FileEditorManager.getInstance(project).getSelectedEditor();
    if (currentEditor != null) {
        VirtualFile currentFile = currentEditor.getFile();
        PsiFile file = PsiManager.getInstance(project).findFile(currentFile);
        if (file instanceof PsiJavaFile)
            return new AnalysisScope(project, Collections.singletonList(currentFile));
    }
    return null;
}