public AddModuleDependencyFix( Module currentModule, VirtualFile classVFile, PsiClass[] classes, PsiReference reference) { final PsiElement psiElement = reference.getElement(); final Project project = psiElement.getProject(); final JavaPsiFacade facade = JavaPsiFacade.getInstance(project); final ProjectFileIndex fileIndex = ProjectRootManager.getInstance(project).getFileIndex(); for (PsiClass aClass : classes) { if (!facade.getResolveHelper().isAccessible(aClass, psiElement, aClass)) continue; PsiFile psiFile = aClass.getContainingFile(); if (psiFile == null) continue; VirtualFile virtualFile = psiFile.getVirtualFile(); if (virtualFile == null) continue; final Module classModule = fileIndex.getModuleForFile(virtualFile); if (classModule != null && classModule != currentModule && !ModuleRootManager.getInstance(currentModule).isDependsOn(classModule)) { myModules.add(classModule); } } myCurrentModule = currentModule; myClassVFile = classVFile; myClasses = classes; myReference = reference; }
private void updateEditorText() { disposeNonTextEditor(); final PsiElement elt = myElements[myIndex].getNavigationElement(); Project project = elt.getProject(); PsiFile psiFile = getContainingFile(elt); final VirtualFile vFile = psiFile.getVirtualFile(); if (vFile == null) return; final FileEditorProvider[] providers = FileEditorProviderManager.getInstance().getProviders(project, vFile); for (FileEditorProvider provider : providers) { if (provider instanceof TextEditorProvider) { updateTextElement(elt); myBinarySwitch.show(myViewingPanel, TEXT_PAGE_KEY); break; } else if (provider.accept(project, vFile)) { myCurrentNonTextEditorProvider = provider; myNonTextEditor = myCurrentNonTextEditorProvider.createEditor(project, vFile); myBinaryPanel.removeAll(); myBinaryPanel.add(myNonTextEditor.getComponent()); myBinarySwitch.show(myViewingPanel, BINARY_PAGE_KEY); break; } } }
@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))); }
@Nullable public String getInfo() { try { return generateInfo(myTargetElement, myElementAtPointer); } catch (IndexNotReadyException e) { showDumbModeNotification(myTargetElement.getProject()); return null; } }
@NotNull public static GlobalSearchScope getMaximalScope(@NotNull FindUsagesHandler handler) { PsiElement element = handler.getPsiElement(); Project project = element.getProject(); PsiFile file = element.getContainingFile(); if (file != null && ProjectFileIndex.SERVICE .getInstance(project) .isInContent(file.getViewProvider().getVirtualFile())) { return GlobalSearchScope.projectScope(project); } return GlobalSearchScope.allScope(project); }
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(); } }
@Override @NotNull public DocInfo getInfo() { AccessToken token = ReadAction.start(); try { return generateInfo(myTargetElement, myElementAtPointer); } catch (IndexNotReadyException e) { showDumbModeNotification(myTargetElement.getProject()); return DocInfo.EMPTY; } finally { token.finish(); } }
@Override public void actionPerformed(AnActionEvent e) { PsiElement element = myElements[myIndex]; PsiElement navigationElement = element.getNavigationElement(); PsiFile file = getContainingFile(navigationElement); if (file == null) return; VirtualFile virtualFile = file.getVirtualFile(); if (virtualFile == null) return; Project project = element.getProject(); FileEditorManagerEx fileEditorManager = FileEditorManagerEx.getInstanceEx(project); OpenFileDescriptor descriptor = new OpenFileDescriptor(project, virtualFile, navigationElement.getTextOffset()); fileEditorManager.openTextEditor(descriptor, myFocusEditor); }
private void addToExistingImport(PyImportElement src) { final PyElementGenerator gen = PyElementGenerator.getInstance(myTarget.getProject()); // did user choose 'import' or 'from import'? PsiElement parent = src.getParent(); if (parent instanceof PyFromImportStatement) { // add another import element right after the one we got PsiElement newImportElement = gen.createImportElement(LanguageLevel.getDefault(), myName); parent.add(newImportElement); } else { // just 'import' // all we need is to qualify our target myTarget.replace( gen.createExpressionFromText( LanguageLevel.forElement(myTarget), src.getVisibleName() + "." + myName)); } }
@Override public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) { if (!FileModificationService.getInstance() .preparePsiElementForWrite(descriptor.getPsiElement())) return; final PsiElement psiElement = descriptor.getPsiElement(); if (psiElement instanceof PsiInstanceOfExpression) { try { final PsiExpression compareToNull = JavaPsiFacade.getInstance(psiElement.getProject()) .getElementFactory() .createExpressionFromText( ((PsiInstanceOfExpression) psiElement).getOperand().getText() + " != null", psiElement.getParent()); psiElement.replace(compareToNull); } catch (IncorrectOperationException e) { LOG.error(e); } } }
@Override public PsiElement setName(@NonNls @NotNull String name) throws IncorrectOperationException { PsiElement nameElement = getNameIdentifierGroovy(); GroovyPsiElementFactory factory = GroovyPsiElementFactory.getInstance(nameElement.getProject()); PsiElement newNameElement; if (JavaPsiFacade.getInstance(getProject()).getNameHelper().isIdentifier(name)) { try { GrMethod method = factory.createMethod(name, null); newNameElement = method.getNameIdentifierGroovy(); } catch (IncorrectOperationException e) { newNameElement = factory.createLiteralFromValue(name).getFirstChild(); } } else { newNameElement = factory.createLiteralFromValue(name).getFirstChild(); } nameElement.replace(newNameElement); return this; }
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); } } } }
public static String getNewText(PsiElement elt) { Project project = elt.getProject(); PsiFile psiFile = getContainingFile(elt); final Document doc = PsiDocumentManager.getInstance(project).getDocument(psiFile); if (doc == null) return null; final ImplementationTextSelectioner implementationTextSelectioner = LanguageImplementationTextSelectioner.INSTANCE.forLanguage(elt.getLanguage()); int start = implementationTextSelectioner.getTextStartOffset(elt); final int end = implementationTextSelectioner.getTextEndOffset(elt); final int lineStart = doc.getLineStartOffset(doc.getLineNumber(start)); final int lineEnd = end < doc.getTextLength() ? doc.getLineEndOffset(doc.getLineNumber(end)) : doc.getTextLength(); return doc.getCharsSequence().subSequence(lineStart, lineEnd).toString(); }
/** * Alters either target (by qualifying a name) or source (by explicitly importing the name). * * @return true if action succeeded */ public boolean execute() { // check if the tree is sane PsiDocumentManager.getInstance(myTarget.getProject()).commitAllDocuments(); if (!myTarget.isValid()) return false; if ((myTarget instanceof PyQualifiedExpression) && ((((PyQualifiedExpression) myTarget).isQualified()))) return false; // we cannot be qualified for (ImportCandidateHolder item : mySources) { if (!item.getImportable().isValid()) return false; if (!item.getFile().isValid()) return false; if (item.getImportElement() != null && !item.getImportElement().isValid()) return false; } if (mySources.isEmpty()) { return false; } // act if (mySources.size() > 1) { selectSourceAndDo(); } else doWriteAction(mySources.get(0)); return true; }
@NotNull @Override protected InspectionGadgetsFix[] buildFixes(Object... infos) { final PsiElement context = (PsiElement) infos[1]; final SmartTypePointerManager pointerManager = SmartTypePointerManager.getInstance(context.getProject()); final List<PsiType> maskedTypes = (List<PsiType>) infos[0]; final List<InspectionGadgetsFix> fixes = new ArrayList<>(); for (PsiType thrown : maskedTypes) { final String typeText = thrown.getCanonicalText(); if (CommonClassNames.JAVA_LANG_RUNTIME_EXCEPTION.equals(typeText)) { fixes.add(new ReplaceWithRuntimeExceptionFix()); } else { fixes.add(new AddCatchSectionFix(pointerManager.createSmartTypePointer(thrown), typeText)); } } final InspectionGadgetsFix fix = SuppressForTestsScopeFix.build(this, context); if (fix != null) { fixes.add(fix); } return fixes.toArray(new InspectionGadgetsFix[fixes.size()]); }
/** Should be invoked in command and write action */ @SuppressWarnings({"HardCodedStringLiteral"}) public static void generateDataBindingMethods(final WizardData data) throws MyException { if (data.myBindToNewBean) { data.myBeanClass = createBeanClass(data); } else { if (!CommonRefactoringUtil.checkReadOnlyStatus( data.myBeanClass.getProject(), data.myBeanClass)) { return; } } final HashMap<String, String> binding2beanGetter = new HashMap<String, String>(); final HashMap<String, String> binding2beanSetter = new HashMap<String, String>(); final FormProperty2BeanProperty[] bindings = data.myBindings; for (final FormProperty2BeanProperty form2bean : bindings) { if (form2bean == null || form2bean.myBeanProperty == null) { continue; } // check that bean contains the property, and if not, try to add the property to the bean { final String setterName = PropertyUtil.suggestSetterName(form2bean.myBeanProperty.myName); final PsiMethod[] methodsByName = data.myBeanClass.findMethodsByName(setterName, true); if (methodsByName.length < 1) { // bean does not contain this property // try to add... LOG.assertTrue( !data.myBindToNewBean); // just generated bean class should contain all necessary // properties if (!data.myBeanClass.isWritable()) { throw new MyException( "Cannot add property to non writable class " + data.myBeanClass.getQualifiedName()); } final StringBuffer membersBuffer = new StringBuffer(); final StringBuffer methodsBuffer = new StringBuffer(); final Project project = data.myBeanClass.getProject(); final CodeStyleManager formatter = CodeStyleManager.getInstance(project); final JavaCodeStyleManager styler = JavaCodeStyleManager.getInstance(project); generateProperty( styler, form2bean.myBeanProperty.myName, form2bean.myBeanProperty.myType, membersBuffer, methodsBuffer); final PsiClass fakeClass; try { fakeClass = JavaPsiFacade.getInstance(data.myBeanClass.getProject()) .getElementFactory() .createClassFromText(membersBuffer.toString() + methodsBuffer.toString(), null); final PsiField[] fields = fakeClass.getFields(); { final PsiElement result = data.myBeanClass.add(fields[0]); styler.shortenClassReferences(result); formatter.reformat(result); } final PsiMethod[] methods = fakeClass.getMethods(); { final PsiElement result = data.myBeanClass.add(methods[0]); styler.shortenClassReferences(result); formatter.reformat(result); } { final PsiElement result = data.myBeanClass.add(methods[1]); styler.shortenClassReferences(result); formatter.reformat(result); } } catch (IncorrectOperationException e) { throw new MyException(e.getMessage()); } } } final PsiMethod propertySetter = PropertyUtil.findPropertySetter( data.myBeanClass, form2bean.myBeanProperty.myName, false, true); final PsiMethod propertyGetter = PropertyUtil.findPropertyGetter( data.myBeanClass, form2bean.myBeanProperty.myName, false, true); if (propertyGetter == null) { // todo continue; } if (propertySetter == null) { // todo continue; } final String binding = form2bean.myFormProperty.getLwComponent().getBinding(); binding2beanGetter.put(binding, propertyGetter.getName()); binding2beanSetter.put(binding, propertySetter.getName()); } final String dataBeanClassName = data.myBeanClass.getQualifiedName(); final LwRootContainer[] rootContainer = new LwRootContainer[1]; final FormProperty[] formProperties = exposeForm(data.myProject, data.myFormFile, rootContainer); final StringBuffer getDataBody = new StringBuffer(); final StringBuffer setDataBody = new StringBuffer(); final StringBuffer isModifiedBody = new StringBuffer(); // iterate exposed formproperties for (final FormProperty formProperty : formProperties) { final String binding = formProperty.getLwComponent().getBinding(); if (!binding2beanGetter.containsKey(binding)) { continue; } getDataBody.append("data."); getDataBody.append(binding2beanSetter.get(binding)); getDataBody.append("("); getDataBody.append(binding); getDataBody.append("."); getDataBody.append(formProperty.getComponentPropertyGetterName()); getDataBody.append("());\n"); setDataBody.append(binding); setDataBody.append("."); setDataBody.append(formProperty.getComponentPropertySetterName()); setDataBody.append("(data."); setDataBody.append(binding2beanGetter.get(binding)); setDataBody.append("());\n"); final String propertyClassName = formProperty.getComponentPropertyClassName(); if ("boolean".equals(propertyClassName)) { isModifiedBody.append("if ("); // isModifiedBody.append(binding); isModifiedBody.append("."); isModifiedBody.append(formProperty.getComponentPropertyGetterName()); isModifiedBody.append("()"); // isModifiedBody.append("!= "); // isModifiedBody.append("data."); isModifiedBody.append(binding2beanGetter.get(binding)); isModifiedBody.append("()"); // isModifiedBody.append(") return true;\n"); } else { isModifiedBody.append("if ("); // isModifiedBody.append(binding); isModifiedBody.append("."); isModifiedBody.append(formProperty.getComponentPropertyGetterName()); isModifiedBody.append("()"); // isModifiedBody.append("!= null ? "); // isModifiedBody.append("!"); // isModifiedBody.append(binding); isModifiedBody.append("."); isModifiedBody.append(formProperty.getComponentPropertyGetterName()); isModifiedBody.append("()"); // isModifiedBody.append(".equals("); // isModifiedBody.append("data."); isModifiedBody.append(binding2beanGetter.get(binding)); isModifiedBody.append("()"); isModifiedBody.append(") : "); // isModifiedBody.append("data."); isModifiedBody.append(binding2beanGetter.get(binding)); isModifiedBody.append("()"); isModifiedBody.append("!= null"); // isModifiedBody.append(") return true;\n"); } } isModifiedBody.append("return false;\n"); final String textOfMethods = "public void setData(" + dataBeanClassName + " data){\n" + setDataBody.toString() + "}\n" + "\n" + "public void getData(" + dataBeanClassName + " data){\n" + getDataBody.toString() + "}\n" + "\n" + "public boolean isModified(" + dataBeanClassName + " data){\n" + isModifiedBody.toString() + "}\n"; // put them to the bound class final Module module = ModuleUtil.findModuleForFile(data.myFormFile, data.myProject); LOG.assertTrue(module != null); final PsiClass boundClass = FormEditingUtil.findClassToBind(module, rootContainer[0].getClassToBind()); LOG.assertTrue(boundClass != null); if (!CommonRefactoringUtil.checkReadOnlyStatus(module.getProject(), boundClass)) { return; } // todo: check that this method does not exist yet final PsiClass fakeClass; try { fakeClass = JavaPsiFacade.getInstance(data.myProject) .getElementFactory() .createClassFromText(textOfMethods, null); final PsiMethod methodSetData = fakeClass.getMethods()[0]; final PsiMethod methodGetData = fakeClass.getMethods()[1]; final PsiMethod methodIsModified = fakeClass.getMethods()[2]; final PsiMethod existing1 = boundClass.findMethodBySignature(methodSetData, false); final PsiMethod existing2 = boundClass.findMethodBySignature(methodGetData, false); final PsiMethod existing3 = boundClass.findMethodBySignature(methodIsModified, false); // warning already shown if (existing1 != null) { existing1.delete(); } if (existing2 != null) { existing2.delete(); } if (existing3 != null) { existing3.delete(); } final CodeStyleManager formatter = CodeStyleManager.getInstance(module.getProject()); final JavaCodeStyleManager styler = JavaCodeStyleManager.getInstance(module.getProject()); final PsiElement setData = boundClass.add(methodSetData); styler.shortenClassReferences(setData); formatter.reformat(setData); final PsiElement getData = boundClass.add(methodGetData); styler.shortenClassReferences(getData); formatter.reformat(getData); if (data.myGenerateIsModified) { final PsiElement isModified = boundClass.add(methodIsModified); styler.shortenClassReferences(isModified); formatter.reformat(isModified); } final OpenFileDescriptor descriptor = new OpenFileDescriptor( setData.getProject(), setData.getContainingFile().getVirtualFile(), setData.getTextOffset()); FileEditorManager.getInstance(data.myProject).openTextEditor(descriptor, true); } catch (IncorrectOperationException e) { throw new MyException(e.getMessage()); } }
@Override public JComponent getPreviewComponent(@NotNull PsiElement element) { final PsiNewExpression psiNewExpression = PsiTreeUtil.getParentOfType(element, PsiNewExpression.class); if (psiNewExpression != null) { final PsiJavaCodeReferenceElement referenceElement = PsiTreeUtil.getChildOfType(psiNewExpression, PsiJavaCodeReferenceElement.class); if (referenceElement != null) { final PsiReference reference = referenceElement.getReference(); if (reference != null) { final PsiElement psiElement = reference.resolve(); if (psiElement instanceof PsiClass && "java.awt.Color".equals(((PsiClass) psiElement).getQualifiedName())) { final PsiExpressionList argumentList = psiNewExpression.getArgumentList(); if (argumentList != null) { final PsiExpression[] expressions = argumentList.getExpressions(); int[] values = ArrayUtil.newIntArray(expressions.length); float[] values2 = new float[expressions.length]; int i = 0; int j = 0; final PsiConstantEvaluationHelper helper = JavaPsiFacade.getInstance(element.getProject()).getConstantEvaluationHelper(); for (final PsiExpression each : expressions) { final Object o = helper.computeConstantExpression(each); if (o instanceof Integer) { values[i] = ((Integer) o).intValue(); if (expressions.length != 1) { values[i] = values[i] > 255 ? 255 : values[i] < 0 ? 0 : values[i]; } i++; } else if (o instanceof Float) { values2[j] = ((Float) o).floatValue(); values2[j] = values2[j] > 1 ? 1 : values2[j] < 0 ? 0 : values2[j]; j++; } } Color c = null; if (i == expressions.length) { if (i == 1 && values[0] > 255) { c = new Color(values[0]); } else { switch (values.length) { case 1: c = new Color(values[0]); break; case 3: c = new Color(values[0], values[1], values[2]); break; case 4: c = new Color(values[0], values[1], values[2], values[3]); break; default: break; } } } else if (j == expressions.length) { switch (values2.length) { case 3: c = new Color(values2[0], values2[1], values2[2]); break; case 4: c = new Color(values2[0], values2[1], values2[2], values2[3]); break; default: break; } } if (c != null) { return new ColorPreviewComponent(c); } } } } } } if (ColorChooserIntentionAction.isInsideDecodeOrGetColorMethod(element)) { final String color = StringUtil.unquoteString(element.getText()); try { return new ColorPreviewComponent(Color.decode(color)); } catch (NumberFormatException ignore) { } } if (PlatformPatterns.psiElement(PsiIdentifier.class) .withParent(PlatformPatterns.psiElement(PsiReferenceExpression.class)) .accepts(element)) { final PsiReference reference = element.getParent().getReference(); if (reference != null) { final PsiElement psiElement = reference.resolve(); if (psiElement instanceof PsiField) { if ("java.awt.Color" .equals(((PsiField) psiElement).getContainingClass().getQualifiedName())) { final String colorName = ((PsiField) psiElement).getName().toLowerCase().replace("_", ""); final String hex = ColorSampleLookupValue.getHexCodeForColorName(colorName); return new ColorPreviewComponent(Color.decode("0x" + hex.substring(1))); } } } } if (PlatformPatterns.psiElement() .withParent(PlatformPatterns.psiElement(PsiLiteralExpression.class)) .accepts(element)) { final PsiLiteralExpression psiLiteralExpression = (PsiLiteralExpression) element.getParent(); if (psiLiteralExpression != null) { return ImagePreviewComponent.getPreviewComponent(psiLiteralExpression); } } return null; }