Java Code Examples for com.intellij.psi.PsiManager

The following examples show how to use com.intellij.psi.PsiManager. These examples are extracted from open source projects. 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
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 2
Source Project: lsp4intellij   Source File: LSPQuickDocAction.java    License: 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 3
Source Project: markdown-image-kit   Source File: AbstractUploadCloudActionTest.java    License: 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 4
Source Project: intellij-haxe   Source File: HaxeComponentIndex.java    License: 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 5
Source Project: camel-idea-plugin   Source File: IdeaUtils.java    License: 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 6
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 7
Source Project: buck   Source File: BuckBuildUtil.java    License: 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 8
Source Project: svgtoandroid   Source File: GUI.java    License: 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 9
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 10
Source Project: consulo   Source File: FileContentUtil.java    License: 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 11
Source Project: idea-php-typo3-plugin   Source File: ResourcePathIndex.java    License: 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 12
Source Project: idea-php-typo3-plugin   Source File: IconIndex.java    License: 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 Project: idea-gitignore   Source File: Utils.java    License: 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 Project: JHelper   Source File: ProcessAction.java    License: 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 15
Source Project: consulo-csharp   Source File: CSharpFragmentFactory.java    License: 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 16
Source Project: Android-Resource-Usage-Count   Source File: FindUsagesImpl171.java    License: 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 17
@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 18
Source Project: consulo   Source File: ChangeUtil.java    License: 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 19
Source Project: idea-php-shopware-plugin   Source File: SnippetUtil.java    License: 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 20
Source Project: idea-php-symfony2-plugin   Source File: EntityHelper.java    License: 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 21
@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 22
Source Project: consulo   Source File: DependenciesPanel.java    License: 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 23
Source Project: idea-php-laravel-plugin   Source File: TemplateLineMarker.java    License: 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 24
Source Project: IntelliJDeodorant   Source File: ScopeChooserCombo.java    License: 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;
}
 
Example 25
Source Project: yiistorm   Source File: FileReference.java    License: MIT License 5 votes vote down vote up
@Nullable
public PsiElement resolve() {
    Project project = element.getProject();
    if (this.virtualFile != null) {
        return PsiManager.getInstance(project).findFile(virtualFile);
    }
    return null;
}
 
Example 26
Source Project: consulo   Source File: GistManagerImpl.java    License: Apache License 2.0 5 votes vote down vote up
private static void invalidateDependentCaches() {
  GuiUtils.invokeLaterIfNeeded(() -> {
    for (Project project : ProjectManager.getInstance().getOpenProjects()) {
      PsiManager.getInstance(project).dropPsiCaches();
    }
  }, ModalityState.NON_MODAL);
}
 
Example 27
Source Project: yiistorm   Source File: I18nFileReference.java    License: MIT License 5 votes vote down vote up
@Nullable
public PsiElement resolve() {
    Project project = element.getProject();
    if (this.virtualFile != null) {
        return PsiManager.getInstance(project).findFile(virtualFile);
    }
    return null;
}
 
Example 28
Source Project: consulo   Source File: UsageSerializable.java    License: Apache License 2.0 5 votes vote down vote up
public UsageInfo execute(final Project project) {
  final GenericElementSignatureProvider provider = new GenericElementSignatureProvider();

  final String path = readNext(false);
  if (path == null) return null;
  final VirtualFile file = LocalFileSystem.getInstance().findFileByIoFile(new File(path));
  if (file == null) return null;
  PsiFile psiFile = PsiManager.getInstance(project).findFile(file);
  if (psiFile == null) return null;
  final String signature = readNext(false);
  final PsiElement element = provider.restoreBySignature(psiFile, signature, new StringBuilder());
  if (element == null) return null;
  final String startStr = readNext(false);
  if (startStr == null) return null;
  final int start = Integer.parseInt(startStr);
  final String endStr = readNext(false);
  if (endStr == null) return null;
  final int end = Integer.parseInt(endStr);
  final String nonCodeUsageStr = readNext(false);
  if (nonCodeUsageStr == null) return null;
  final boolean nonCodeUsage = Boolean.parseBoolean(nonCodeUsageStr);
  final String dynamicUsageStr = readNext(false);
  if (dynamicUsageStr == null) return null;
  final boolean dynamicUsage = Boolean.parseBoolean(dynamicUsageStr);

  final String text = readNext(true);
  if (text == null) return null;

  final UsageInfo info = new UsageInfo(element, start, end, nonCodeUsage);
  info.setDynamicUsage(dynamicUsage);

  return info;
  /*final String newText = new UsageInfo2UsageAdapter(info).getPlainText();
  if (! Comparing.equal(newText, text)) {
    LOG.info("Usage not restored, oldText:\n'" + text + "'\nnew text: '\n" + newText + "'");
    return null;
  }*/
}
 
Example 29
Source Project: Intellij-Plugin   Source File: FileManager.java    License: Apache License 2.0 5 votes vote down vote up
public static List<PsiFile> getAllJavaFiles(Module module) {
    Collection<VirtualFile> javaVirtualFiles = FileTypeIndex.getFiles(JavaFileType.INSTANCE, moduleScope(module));
    List<PsiFile> javaFiles = new ArrayList<>();

    for (VirtualFile javaVFile : javaVirtualFiles) {
        PsiFile file = PsiManager.getInstance(module.getProject()).findFile(javaVFile);
        if (file != null && PsiTreeUtil.findChildrenOfType(file, PsiClass.class).size() > 0) {
            javaFiles.add(file);
        }
    }
    Collections.sort(javaFiles, (o1, o2) -> FileManager.getJavaFileName(o1).compareToIgnoreCase(FileManager.getJavaFileName(o2)));
    return javaFiles;
}
 
Example 30
@Override
public String renderBuildCode(@NotNull PsiVariable psiVariable, @NotNull String fieldName, @NotNull String builderVariable) {
  final PsiManager psiManager = psiVariable.getManager();
  final PsiType psiFieldType = psiVariable.getType();

  final PsiType elementType = PsiTypeUtil.extractOneElementType(psiFieldType, psiManager);
  return MessageFormat.format(
    "{2}<{1}> {0} = " +
      "{4}.{0} == null ? " +
      "{3}.<{1}>of() : " +
      "{4}.{0}.build();\n",
    fieldName, elementType.getCanonicalText(false), collectionQualifiedName, typeCollectionQualifiedName, builderVariable);
}