public PsiDirectory[] getSelectedDirectories() { final PsiElement[] elements = getSelectedPSIElements(); if (elements.length == 1) { final PsiElement element = elements[0]; if (element instanceof PsiDirectory) { return new PsiDirectory[] {(PsiDirectory) element}; } else if (element instanceof PsiDirectoryContainer) { return ((PsiDirectoryContainer) element).getDirectories(); } else { final PsiFile containingFile = element.getContainingFile(); if (containingFile != null) { final PsiDirectory psiDirectory = containingFile.getContainingDirectory(); if (psiDirectory != null) { return new PsiDirectory[] {psiDirectory}; } final VirtualFile file = containingFile.getVirtualFile(); if (file instanceof VirtualFileWindow) { final VirtualFile delegate = ((VirtualFileWindow) file).getDelegate(); final PsiFile delegatePsiFile = containingFile.getManager().findFile(delegate); if (delegatePsiFile != null && delegatePsiFile.getContainingDirectory() != null) { return new PsiDirectory[] {delegatePsiFile.getContainingDirectory()}; } } return PsiDirectory.EMPTY_ARRAY; } } } else { final DefaultMutableTreeNode selectedNode = getSelectedNode(); if (selectedNode != null) { return getSelectedDirectoriesInAmbiguousCase(selectedNode); } } return PsiDirectory.EMPTY_ARRAY; }
@Override public final void actionPerformed(final AnActionEvent event) { final DataContext dataContext = event.getDataContext(); final HierarchyBrowserBaseEx browser = (HierarchyBrowserBaseEx) dataContext.getData(myBrowserDataKey); if (browser == null) return; final PsiElement selectedElement = browser.getSelectedElement(); if (selectedElement == null || !browser.isApplicableElement(selectedElement)) return; final String currentViewType = browser.myCurrentViewType; Disposer.dispose(browser); final HierarchyProvider provider = BrowseHierarchyActionBase.findProvider( myProviderLanguageExtension, selectedElement, selectedElement.getContainingFile(), event.getDataContext()); final HierarchyBrowser newBrowser = BrowseHierarchyActionBase.createAndAddToPanel( selectedElement.getProject(), provider, selectedElement); ApplicationManager.getApplication() .invokeLater( () -> ((HierarchyBrowserBaseEx) newBrowser) .changeView(correctViewType(browser, currentViewType))); }
public MoveClassesOrPackagesDialog( Project project, boolean searchTextOccurences, PsiElement[] elementsToMove, final PsiElement initialTargetElement, MoveCallback moveCallback) { super(project, true); myElementsToMove = elementsToMove; myMoveCallback = moveCallback; myManager = PsiManager.getInstance(myProject); setTitle(MoveHandler.REFACTORING_NAME); mySearchTextOccurencesEnabled = searchTextOccurences; selectInitialCard(); init(); if (initialTargetElement instanceof PsiClass) { myMakeInnerClassOfRadioButton.setSelected(true); myInnerClassChooser.setText(((PsiClass) initialTargetElement).getQualifiedName()); ApplicationManager.getApplication() .invokeLater( () -> myInnerClassChooser.requestFocus(), ModalityState.stateForComponent(myMainPanel)); } else if (initialTargetElement instanceof PsiPackage) { myClassPackageChooser.setText(((PsiPackage) initialTargetElement).getQualifiedName()); } updateControlsEnabled(); myToPackageRadioButton.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { updateControlsEnabled(); myClassPackageChooser.requestFocus(); } }); myMakeInnerClassOfRadioButton.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { updateControlsEnabled(); myInnerClassChooser.requestFocus(); } }); for (PsiElement element : elementsToMove) { if (element.getContainingFile() != null) { myOpenInEditorPanel.add(initOpenInEditorCb(), BorderLayout.EAST); break; } } }
@Nullable private static String verifyDestinationForElement( final PsiElement element, final MoveDestination moveDestination) { final String message; if (element instanceof PsiDirectory) { message = moveDestination.verify((PsiDirectory) element); } else if (element instanceof PsiPackage) { message = moveDestination.verify((PsiPackage) element); } else { message = moveDestination.verify(element.getContainingFile()); } return message; }
private void doWriteAction(final ImportCandidateHolder item) { PsiElement src = item.getImportable(); new WriteCommandAction( src.getProject(), PyBundle.message("ACT.CMD.use.import"), myTarget.getContainingFile()) { @Override protected void run(@NotNull Result result) throws Throwable { doIt(item); } }.execute(); if (myOnDoneCallback != null) { myOnDoneCallback.run(); } }
@Nullable private static String getQuickNavigateInfo(PsiElement element) { final String name = ElementDescriptionUtil.getElementDescription(element, UsageViewShortNameLocation.INSTANCE); if (StringUtil.isEmpty(name)) return null; final String typeName = ElementDescriptionUtil.getElementDescription(element, UsageViewTypeLocation.INSTANCE); final PsiFile file = element.getContainingFile(); final StringBuilder sb = new StringBuilder(); if (StringUtil.isNotEmpty(typeName)) sb.append(typeName).append(" "); sb.append("\"").append(name).append("\""); if (file != null && file.isPhysical()) { sb.append(" [").append(file.getName()).append("]"); } return sb.toString(); }
private void invokeMoveToPackage() { final MoveDestination destination = selectDestination(); if (destination == null) return; saveRefactoringSettings(); for (final PsiElement element : myElementsToMove) { String message = verifyDestinationForElement(element, destination); if (message != null) { String helpId = HelpID.getMoveHelpID(myElementsToMove[0]); CommonRefactoringUtil.showErrorMessage( RefactoringBundle.message("error.title"), message, helpId, getProject()); return; } } try { for (PsiElement element : myElementsToMove) { if (element instanceof PsiClass) { final PsiClass aClass = (PsiClass) element; LOG.assertTrue(aClass.isPhysical(), aClass); /*PsiElement toAdd; if (aClass.getContainingFile() instanceof PsiJavaFile && ((PsiJavaFile)aClass.getContainingFile()).getClasses().length > 1) { toAdd = aClass; } else { toAdd = aClass.getContainingFile(); }*/ final PsiDirectory targetDirectory = destination.getTargetIfExists(element.getContainingFile()); if (targetDirectory != null) { MoveFilesOrDirectoriesUtil.checkMove(aClass, targetDirectory); } } } MoveClassesOrPackagesProcessor processor = createMoveToPackageProcessor(destination, myElementsToMove, myMoveCallback); if (processor.verifyValidPackageName()) { processor.setOpenInEditor(isOpenInEditor()); invokeRefactoring(processor); } } catch (IncorrectOperationException e) { String helpId = HelpID.getMoveHelpID(myElementsToMove[0]); CommonRefactoringUtil.showErrorMessage( RefactoringBundle.message("error.title"), e.getMessage(), helpId, getProject()); } }
private void addImportStatement(ImportCandidateHolder item) { final Project project = myTarget.getProject(); final PyElementGenerator gen = PyElementGenerator.getInstance(project); AddImportHelper.ImportPriority priority = AddImportHelper.getImportPriority(myTarget, item.getFile()); PsiFile file = myTarget.getContainingFile(); InjectedLanguageManager manager = InjectedLanguageManager.getInstance(project); if (manager.isInjectedFragment(file)) { file = manager.getTopLevelFile(myTarget); } // We are trying to import top-level module or package which thus cannot be qualified if (isRoot(item.getFile())) { if (myImportLocally) { AddImportHelper.addLocalImportStatement(myTarget, myName); } else { AddImportHelper.addImportStatement(file, myName, item.getAsName(), priority, null); } } else { final QualifiedName path = item.getPath(); final String qualifiedName = path != null ? path.toString() : ""; if (myUseQualifiedImport) { String nameToImport = qualifiedName; if (item.getImportable() instanceof PsiFileSystemItem) { nameToImport += "." + myName; } if (myImportLocally) { AddImportHelper.addLocalImportStatement(myTarget, nameToImport); } else { AddImportHelper.addImportStatement(file, nameToImport, item.getAsName(), priority, null); } myTarget.replace( gen.createExpressionFromText( LanguageLevel.forElement(myTarget), qualifiedName + "." + myName)); } else { if (myImportLocally) { AddImportHelper.addLocalFromImportStatement(myTarget, qualifiedName, myName); } else { AddImportHelper.addFromImportStatement( file, qualifiedName, myName, item.getAsName(), priority, null); } } } }
@Override @NotNull public AnnotationPlace chooseAnnotationsPlace(@NotNull final PsiElement element) { if (!element.isPhysical()) return AnnotationPlace.IN_CODE; // element just created if (!element.getManager().isInProject(element)) return AnnotationPlace.EXTERNAL; final Project project = myPsiManager.getProject(); final PsiFile containingFile = element.getContainingFile(); final VirtualFile virtualFile = containingFile.getVirtualFile(); LOG.assertTrue(virtualFile != null); final List<OrderEntry> entries = ProjectRootManager.getInstance(project).getFileIndex().getOrderEntriesForFile(virtualFile); if (!entries.isEmpty()) { for (OrderEntry entry : entries) { if (!(entry instanceof ModuleOrderEntry)) { if (AnnotationOrderRootType.getUrls(entry).length > 0) { return AnnotationPlace.EXTERNAL; } break; } } } final MyExternalPromptDialog dialog = ApplicationManager.getApplication().isUnitTestMode() || ApplicationManager.getApplication().isHeadlessEnvironment() ? null : new MyExternalPromptDialog(project); if (dialog != null && dialog.isToBeShown()) { final PsiElement highlightElement = element instanceof PsiNameIdentifierOwner ? ((PsiNameIdentifierOwner) element).getNameIdentifier() : element.getNavigationElement(); LOG.assertTrue(highlightElement != null); final Editor editor = FileEditorManager.getInstance(project).getSelectedTextEditor(); final List<RangeHighlighter> highlighters = new ArrayList<RangeHighlighter>(); final boolean highlight = editor != null && editor.getDocument() == PsiDocumentManager.getInstance(project).getDocument(containingFile); try { if (highlight) { // do not highlight for batch inspections final EditorColorsManager colorsManager = EditorColorsManager.getInstance(); final TextAttributes attributes = colorsManager.getGlobalScheme().getAttributes(EditorColors.SEARCH_RESULT_ATTRIBUTES); final TextRange textRange = highlightElement.getTextRange(); HighlightManager.getInstance(project) .addRangeHighlight( editor, textRange.getStartOffset(), textRange.getEndOffset(), attributes, true, highlighters); final LogicalPosition logicalPosition = editor.offsetToLogicalPosition(textRange.getStartOffset()); editor.getScrollingModel().scrollTo(logicalPosition, ScrollType.CENTER); } dialog.show(); if (dialog.getExitCode() == 2) { return AnnotationPlace.EXTERNAL; } else if (dialog.getExitCode() == 1) { return AnnotationPlace.NOWHERE; } } finally { if (highlight) { HighlightManager.getInstance(project) .removeSegmentHighlighter(editor, highlighters.get(0)); } } } else if (dialog != null) { dialog.close(DialogWrapper.OK_EXIT_CODE); } return AnnotationPlace.IN_CODE; }
private static PsiFile getContainingFile(final PsiElement elt) { PsiFile psiFile = elt.getContainingFile(); if (psiFile == null) return null; return psiFile.getOriginalFile(); }
@Override public void annotate(@NotNull final PsiElement element, @NotNull AnnotationHolder holder) { final PsiFile containingFile = element.getContainingFile(); if (!JavaFxFileTypeFactory.isFxml(containingFile)) return; if (element instanceof XmlAttributeValue) { final String value = ((XmlAttributeValue) element).getValue(); if (!JavaFxPsiUtil.isExpressionBinding(value) && !JavaFxPsiUtil.isIncorrectExpressionBinding(value)) { final PsiReference[] references = element.getReferences(); for (PsiReference reference : references) { if (reference instanceof JavaFxColorReference) { attachColorIcon(element, holder, StringUtil.unquoteString(element.getText())); continue; } final PsiElement resolve = reference.resolve(); if (resolve instanceof PsiMember) { if (!JavaFxPsiUtil.isVisibleInFxml((PsiMember) resolve)) { final String symbolPresentation = "'" + SymbolPresentationUtil.getSymbolPresentableText(resolve) + "'"; final Annotation annotation = holder.createErrorAnnotation( element, symbolPresentation + (resolve instanceof PsiClass ? " should be public" : " should be public or annotated with @FXML")); if (!(resolve instanceof PsiClass)) { annotation.registerUniversalFix( new AddAnnotationFix( JavaFxCommonNames.JAVAFX_FXML_ANNOTATION, (PsiMember) resolve, ArrayUtil.EMPTY_STRING_ARRAY), null, null); } } } } } } else if (element instanceof XmlAttribute) { final XmlAttribute attribute = (XmlAttribute) element; final String attributeName = attribute.getName(); if (!FxmlConstants.FX_BUILT_IN_ATTRIBUTES.contains(attributeName) && !attribute.isNamespaceDeclaration() && JavaFxPsiUtil.isReadOnly(attributeName, attribute.getParent())) { holder.createErrorAnnotation( element.getNavigationElement(), "Property '" + attributeName + "' is read-only"); } if (FxmlConstants.SOURCE.equals(attributeName)) { final XmlAttributeValue valueElement = attribute.getValueElement(); if (valueElement != null) { final XmlTag xmlTag = attribute.getParent(); if (xmlTag != null) { final XmlTag referencedTag = JavaFxBuiltInTagDescriptor.getReferencedTag(xmlTag); if (referencedTag != null) { if (referencedTag.getTextOffset() > xmlTag.getTextOffset()) { holder.createErrorAnnotation( valueElement.getValueTextRange(), valueElement.getValue() + " not found"); } else if (xmlTag.getParentTag() == referencedTag.getParentTag()) { final Annotation annotation = holder.createErrorAnnotation( valueElement.getValueTextRange(), "Duplicate child added"); annotation.registerFix( new JavaFxWrapWithDefineIntention(referencedTag, valueElement.getValue())); } } } } } } else if (element instanceof XmlTag) { if (FxmlConstants.FX_SCRIPT.equals(((XmlTag) element).getName())) { final XmlTagValue tagValue = ((XmlTag) element).getValue(); if (!StringUtil.isEmptyOrSpaces(tagValue.getText())) { final List<String> langs = JavaFxPsiUtil.parseInjectedLanguages((XmlFile) element.getContainingFile()); if (langs.isEmpty()) { final ASTNode openTag = element.getNode().findChildByType(XmlTokenType.XML_NAME); final Annotation annotation = holder.createErrorAnnotation( openTag != null ? openTag.getPsi() : element, "Page language not specified."); annotation.registerFix(new JavaFxInjectPageLanguageIntention()); } } } } }