Search in sources :

Example 1 with HtmlBuilder

use of com.android.utils.HtmlBuilder in project android by JetBrains.

the class LinuxHaxmInfoStep method createUIComponents.

private void createUIComponents() {
    myUrlPane = SwingHelper.createHtmlViewer(true, null, null, null);
    myUrlPane.addHyperlinkListener(BrowserHyperlinkListener.INSTANCE);
    HtmlBuilder description = new HtmlBuilder();
    description.addHtml("Search for install instructions for your particular Linux configuration (");
    description.addLink("Android KVM Linux Installation", KVM_DOCUMENTATION_URL);
    description.addHtml(") that KVM is enabled for faster Android emulator performance.");
    myUrlPane.setText(description.getHtml());
    SwingHelper.setHtml(myUrlPane, description.getHtml(), UIUtil.getLabelForeground());
    myUrlPane.setBackground(UIUtil.getLabelBackground());
}
Also used : HtmlBuilder(com.android.utils.HtmlBuilder)

Example 2 with HtmlBuilder

use of com.android.utils.HtmlBuilder in project android by JetBrains.

the class RenderErrorContributor method reportRelevantCompilationErrors.

private void reportRelevantCompilationErrors(@NotNull RenderLogger logger, @NotNull RenderTask renderTask) {
    Module module = logger.getModule();
    if (module == null) {
        return;
    }
    Project project = module.getProject();
    WolfTheProblemSolver wolfgang = WolfTheProblemSolver.getInstance(project);
    if (!wolfgang.hasProblemFilesBeneath(module)) {
        return;
    }
    HtmlBuilder builder = new HtmlBuilder();
    String summary = null;
    if (logger.seenTagPrefix(TAG_RESOURCES_PREFIX)) {
        // Do we have errors in the res/ files?
        // See if it looks like we have aapt problems
        boolean haveResourceErrors = wolfgang.hasProblemFilesBeneath(virtualFile -> virtualFile.getFileType() == StdFileTypes.XML);
        if (haveResourceErrors) {
            summary = "Resource errors";
            builder.addBold("This project contains resource errors, so aapt did not succeed, " + "which can cause rendering failures. Fix resource problems first.").newline().newline();
        }
    } else if (renderTask.getLayoutlibCallback().isUsed()) {
        boolean hasJavaErrors = wolfgang.hasProblemFilesBeneath(virtualFile -> virtualFile.getFileType() == StdFileTypes.JAVA);
        if (hasJavaErrors) {
            summary = "Compilation errors";
            builder.addBold("This project contains Java compilation errors, " + "which can cause rendering failures for custom views. " + "Fix compilation problems first.").newline().newline();
        }
    }
    if (summary == null) {
        return;
    }
    addIssue().setSeverity(HighlightSeverity.ERROR).setSummary(summary).setHtmlContent(builder).build();
}
Also used : AndroidSdkType(org.jetbrains.android.sdk.AndroidSdkType) ResourceHelper.isViewPackageNeeded(com.android.tools.idea.res.ResourceHelper.isViewPackageNeeded) HyperlinkEvent(javax.swing.event.HyperlinkEvent) ResourceResolver(com.android.ide.common.resources.ResourceResolver) XmlFile(com.intellij.psi.xml.XmlFile) AndroidPlatform(org.jetbrains.android.sdk.AndroidPlatform) HighlightSeverity(com.intellij.lang.annotation.HighlightSeverity) JavaSdk(com.intellij.openapi.projectRoots.JavaSdk) VisibleForTesting(com.android.annotations.VisibleForTesting) Matcher(java.util.regex.Matcher) RenderErrorPanel(com.android.tools.idea.rendering.errors.ui.RenderErrorPanel) Messages(com.intellij.openapi.ui.Messages) AttributeDefinition(org.jetbrains.android.dom.attrs.AttributeDefinition) Logger(com.intellij.openapi.diagnostic.Logger) Module(com.intellij.openapi.module.Module) LintUtils.editDistance(com.android.tools.lint.detector.api.LintUtils.editDistance) XmlTag(com.intellij.psi.xml.XmlTag) JpsJavaCompilerOptions(org.jetbrains.jps.model.java.compiler.JpsJavaCompilerOptions) AndroidModuleInfo(com.android.tools.idea.model.AndroidModuleInfo) AndroidSdks(com.android.tools.idea.sdk.AndroidSdks) IndexNotReadyException(com.intellij.openapi.project.IndexNotReadyException) GlobalSearchScope(com.intellij.psi.search.GlobalSearchScope) Sets(com.google.common.collect.Sets) IAndroidTarget(com.android.sdklib.IAndroidTarget) Nullable(org.jetbrains.annotations.Nullable) HTMLDocument(javax.swing.text.html.HTMLDocument) ModuleRootManager(com.intellij.openapi.roots.ModuleRootManager) ProjectJdkTable(com.intellij.openapi.projectRoots.ProjectJdkTable) LayoutLog(com.android.ide.common.rendering.api.LayoutLog) AttributeFormat(org.jetbrains.android.dom.attrs.AttributeFormat) AndroidSdkAdditionalData(org.jetbrains.android.sdk.AndroidSdkAdditionalData) ApplicationManager(com.intellij.openapi.application.ApplicationManager) ClassInheritorsSearch(com.intellij.psi.search.searches.ClassInheritorsSearch) Pattern(java.util.regex.Pattern) NotNull(org.jetbrains.annotations.NotNull) CompilerManager(com.intellij.openapi.compiler.CompilerManager) CopyPasteManager(com.intellij.openapi.ide.CopyPasteManager) Application(org.jetbrains.android.dom.manifest.Application) java.util(java.util) ShowSettingsUtil(com.intellij.openapi.options.ShowSettingsUtil) DataContext(com.intellij.openapi.actionSystem.DataContext) AndroidManifest(com.android.xml.AndroidManifest) SdkConstants(com.android.SdkConstants) JavaPsiFacade(com.intellij.psi.JavaPsiFacade) Manifest(org.jetbrains.android.dom.manifest.Manifest) TAG_STILL_BUILDING(com.android.tools.idea.rendering.RenderLogger.TAG_STILL_BUILDING) LintUtils.stripIdPrefix(com.android.tools.lint.detector.api.LintUtils.stripIdPrefix) Computable(com.intellij.openapi.util.Computable) JavaSdkVersion(com.intellij.openapi.projectRoots.JavaSdkVersion) EditorDesignSurface(com.android.tools.idea.ui.designer.EditorDesignSurface) JAVA_VERSION(com.intellij.openapi.util.SystemInfo.JAVA_VERSION) PsiClass(com.intellij.psi.PsiClass) Lists(com.google.common.collect.Lists) Density(com.android.resources.Density) RenderSessionImpl(com.android.layoutlib.bridge.impl.RenderSessionImpl) StringSelection(java.awt.datatransfer.StringSelection) Project(com.intellij.openapi.project.Project) PsiFile(com.intellij.psi.PsiFile) RenderErrorModel(com.android.tools.idea.rendering.errors.ui.RenderErrorModel) HyperlinkListener(javax.swing.event.HyperlinkListener) AndroidTargetData(org.jetbrains.android.sdk.AndroidTargetData) StdFileTypes(com.intellij.openapi.fileTypes.StdFileTypes) StringUtil(com.intellij.openapi.util.text.StringUtil) HtmlBuilder(com.android.utils.HtmlBuilder) JavacConfiguration(com.intellij.compiler.impl.javaCompiler.javac.JavacConfiguration) Throwables(com.google.common.base.Throwables) AttributeDefinitions(org.jetbrains.android.dom.attrs.AttributeDefinitions) HTMLFrameHyperlinkEvent(javax.swing.text.html.HTMLFrameHyperlinkEvent) AndroidFacet(org.jetbrains.android.facet.AndroidFacet) IOException(java.io.IOException) ClasspathEditor(com.intellij.openapi.roots.ui.configuration.ClasspathEditor) Sdk(com.intellij.openapi.projectRoots.Sdk) ModulesConfigurator(com.intellij.openapi.roots.ui.configuration.ModulesConfigurator) SystemInfo(com.intellij.openapi.util.SystemInfo) File(java.io.File) ExtensionPointName(com.intellij.openapi.extensions.ExtensionPointName) TAG_RESOURCES_RESOLVE_THEME_ATTR(com.android.ide.common.rendering.api.LayoutLog.TAG_RESOURCES_RESOLVE_THEME_ATTR) WolfTheProblemSolver(com.intellij.problems.WolfTheProblemSolver) ProjectStructureConfigurable(com.intellij.openapi.roots.ui.configuration.ProjectStructureConfigurable) javax.swing(javax.swing) TAG_RESOURCES_PREFIX(com.android.ide.common.rendering.api.LayoutLog.TAG_RESOURCES_PREFIX) Project(com.intellij.openapi.project.Project) HtmlBuilder(com.android.utils.HtmlBuilder) Module(com.intellij.openapi.module.Module) WolfTheProblemSolver(com.intellij.problems.WolfTheProblemSolver)

Example 3 with HtmlBuilder

use of com.android.utils.HtmlBuilder in project android by JetBrains.

the class RenderErrorContributor method reportUnknownFragments.

private void reportUnknownFragments(@NotNull final RenderLogger logger) {
    List<String> fragmentNames = logger.getMissingFragments();
    if (fragmentNames == null || fragmentNames.isEmpty()) {
        return;
    }
    HtmlBuilder builder = new HtmlBuilder();
    builder.add("A ").addHtml("<code>").add("<fragment>").addHtml("</code>").add(" tag allows a layout file to dynamically include " + "different layouts at runtime. ").add("At layout editing time the specific layout to be used is not known. You can choose which layout you would " + "like previewed while editing the layout.");
    builder.beginList();
    for (final String className : fragmentNames) {
        builder.listItem();
        boolean isIdentified = className != null && !className.isEmpty();
        boolean isActivityKnown = isIdentified && !className.startsWith(PREFIX_RESOURCE_REF);
        if (isIdentified) {
            builder.add("<fragment ").addBold(className).add(" ...>");
        } else {
            builder.add("<fragment>");
        }
        builder.add(" (");
        if (isActivityKnown) {
            final Module module = logger.getModule();
            ApplicationManager.getApplication().runReadAction(() -> {
                // Look for R references in the layout
                assert module != null;
                Project project = module.getProject();
                GlobalSearchScope scope = GlobalSearchScope.allScope(project);
                PsiClass clz = JavaPsiFacade.getInstance(project).findClass(className, scope);
                String layoutName = myResult.getFile().getName();
                boolean separate = false;
                if (clz != null) {
                    // TODO: Should instead find all R.layout elements
                    // HACK AHEAD!
                    String matchText = clz.getText();
                    final Pattern LAYOUT_FIELD_PATTERN = Pattern.compile("R\\.layout\\.([a-z0-9_]+)");
                    Matcher matcher = LAYOUT_FIELD_PATTERN.matcher(matchText);
                    Set<String> layouts = Sets.newTreeSet();
                    int index = 0;
                    while (true) {
                        if (matcher.find(index)) {
                            layouts.add(matcher.group(1));
                            index = matcher.end();
                        } else {
                            break;
                        }
                    }
                    for (String layout : layouts) {
                        if (layout.equals(layoutName)) {
                            // Don't include self
                            continue;
                        }
                        if (separate) {
                            builder.add(", ");
                        }
                        builder.addLink("Use @layout/" + layout, myLinkManager.createAssignLayoutUrl(className, layout));
                        separate = true;
                    }
                }
                if (separate) {
                    builder.add(", ");
                }
                builder.addLink("Pick Layout...", myLinkManager.createPickLayoutUrl(className));
            });
        } else {
            builder.addLink("Choose Fragment Class...", myLinkManager.createAssignFragmentUrl(className));
        }
        builder.add(")");
    }
    builder.endList().newline().addLink("Do not warn about <fragment> tags in this session", myLinkManager.createIgnoreFragmentsUrl()).newline();
    addIssue().setSeverity(HighlightSeverity.ERROR).setSummary("Unknown fragments").setHtmlContent(builder).build();
}
Also used : Project(com.intellij.openapi.project.Project) Pattern(java.util.regex.Pattern) GlobalSearchScope(com.intellij.psi.search.GlobalSearchScope) Matcher(java.util.regex.Matcher) HtmlBuilder(com.android.utils.HtmlBuilder) PsiClass(com.intellij.psi.PsiClass) Module(com.intellij.openapi.module.Module)

Example 4 with HtmlBuilder

use of com.android.utils.HtmlBuilder in project android by JetBrains.

the class RenderErrorContributor method reportMissingClasses.

private void reportMissingClasses(@NotNull RenderLogger logger) {
    Set<String> missingClasses = logger.getMissingClasses();
    if (missingClasses == null || missingClasses.isEmpty()) {
        return;
    }
    HtmlBuilder builder = new HtmlBuilder();
    if (missingClasses.contains("CalendarView")) {
        builder.add("The ").addBold("CalendarView").add(" widget does not work correctly with this render target. " + "As a workaround, try using the API 15 (Android 4.0.3) render target library by selecting it from the " + "toolbar menu above.");
        if (missingClasses.size() == 1) {
            addIssue().setSeverity(HighlightSeverity.WARNING).setSummary("CalendarView does not work correctly with this render target").setHtmlContent(builder).build();
            return;
        }
    }
    boolean missingResourceClass = logger.isMissingResourceClass() && logger.getResourceClass() != null && logger.hasLoadedClasses();
    builder.add("The following classes could not be found:");
    builder.beginList();
    Collection<String> customViews = null;
    Collection<String> androidViewClassNames = null;
    Module module = logger.getModule();
    if (module != null) {
        Collection<String> views = getAllViews(module);
        if (!views.isEmpty()) {
            // most will be framework views
            customViews = Lists.newArrayListWithExpectedSize(Math.max(10, views.size() - 80));
            androidViewClassNames = Lists.newArrayListWithExpectedSize(views.size());
            for (String fqcn : views) {
                if (fqcn.startsWith("android.") && !isViewPackageNeeded(fqcn, -1)) {
                    androidViewClassNames.add(fqcn);
                } else {
                    customViews.add(fqcn);
                }
            }
        }
    }
    if (missingResourceClass) {
        builder.listItem();
        builder.add(logger.getResourceClass());
    }
    boolean foundCustomView = false;
    for (String className : missingClasses) {
        builder.listItem();
        builder.add(className);
        builder.add(" (");
        foundCustomView |= addTypoSuggestions(builder, className, customViews, false);
        addTypoSuggestions(builder, className, customViews, true);
        addTypoSuggestions(builder, className, androidViewClassNames, false);
        if (myLinkManager == null) {
            return;
        }
        if (CLASS_CONSTRAINT_LAYOUT.equals(className)) {
            builder.newline().addNbsps(3);
            builder.addLink("Add constraint-layout library dependency to the project", myLinkManager.createAddDependencyUrl(CONSTRAINT_LAYOUT_LIB_ARTIFACT));
            builder.add(", ");
        }
        builder.addLink("Fix Build Path", myLinkManager.createEditClassPathUrl());
        //DesignSurface surface = renderTask.getDesignSurface();
        //if (surface != null && surface.getType() == LAYOUT_EDITOR) {
        builder.add(", ");
        builder.addLink("Edit XML", myLinkManager.createShowTagUrl(className));
        // user didn't realize a FQN is required here
        if (className.indexOf('.') != -1) {
            builder.add(", ");
            builder.addLink("Create Class", myLinkManager.createNewClassUrl(className));
        }
        builder.add(")");
    }
    builder.endList();
    builder.addIcon(HtmlBuilderHelper.getTipIconPath());
    builder.addLink("Tip: Try to ", "build", " the project.", myLinkManager.createBuildProjectUrl());
    addRefreshAction(builder);
    if (foundCustomView) {
        builder.newline().add("One or more missing custom views were found in the project, but does not appear to have been compiled yet.");
    }
    builder.newline().newline();
    addIssue().setSeverity(HighlightSeverity.ERROR).setSummary("Missing classes").setHtmlContent(builder).build();
}
Also used : HtmlBuilder(com.android.utils.HtmlBuilder) Module(com.intellij.openapi.module.Module)

Example 5 with HtmlBuilder

use of com.android.utils.HtmlBuilder in project android by JetBrains.

the class RenderErrorContributor method reportInstantiationProblems.

private void reportInstantiationProblems(@NotNull final RenderLogger logger) {
    Map<String, Throwable> classesWithIncorrectFormat = logger.getClassesWithIncorrectFormat();
    if (classesWithIncorrectFormat == null || classesWithIncorrectFormat.isEmpty()) {
        return;
    }
    HtmlBuilder builder = new HtmlBuilder();
    builder.add("Preview might be incorrect: unsupported class version.").newline().addIcon(HtmlBuilderHelper.getTipIconPath()).add("Tip: ");
    builder.add("You need to run the IDE with the highest JDK version that you are compiling custom views with. ");
    int highest = ClassConverter.findHighestMajorVersion(classesWithIncorrectFormat.values());
    if (highest > 0 && highest > ClassConverter.getCurrentClassVersion()) {
        String required = ClassConverter.classVersionToJdk(highest);
        builder.add("One or more views have been compiled with JDK ").add(required).add(", but you are running the IDE on JDK ").add(ClassConverter.getCurrentJdkVersion()).add(". ");
    } else {
        builder.add("For example, if you are compiling with sourceCompatibility 1.7, you must run the IDE with JDK 1.7. ");
    }
    builder.add("Running on a higher JDK is necessary such that these classes can be run in the layout renderer. " + "(Or, extract your custom views into a library which you compile with a lower JDK version.)").newline().newline().addLink("If you have just accidentally built your code with a later JDK, try to ", "build", " the project.", myLinkManager.createBuildProjectUrl()).newline().newline().add("Classes with incompatible format:");
    builder.beginList();
    List<String> names = Lists.newArrayList(classesWithIncorrectFormat.keySet());
    Collections.sort(names);
    for (String className : names) {
        builder.listItem();
        builder.add(className);
        //noinspection ThrowableResultOfMethodCallIgnored
        Throwable throwable = classesWithIncorrectFormat.get(className);
        if (throwable instanceof InconvertibleClassError) {
            InconvertibleClassError error = (InconvertibleClassError) throwable;
            builder.add(" (Compiled with ").add(ClassConverter.classVersionToJdk(error.getMajor())).add(")");
        }
    }
    builder.endList();
    Module module = logger.getModule();
    if (module == null) {
        return;
    }
    final List<Module> problemModules = getProblemModules(module);
    if (!problemModules.isEmpty()) {
        builder.add("The following modules are built with incompatible JDK:").newline();
        for (Iterator<Module> it = problemModules.iterator(); it.hasNext(); ) {
            Module problemModule = it.next();
            builder.add(problemModule.getName());
            if (it.hasNext()) {
                builder.add(", ");
            }
        }
        builder.newline();
    }
    AndroidFacet facet = AndroidFacet.getInstance(logger.getModule());
    if (facet != null && !facet.requiresAndroidModel()) {
        Project project = logger.getModule().getProject();
        builder.addLink("Rebuild project with '-target 1.6'", myLinkManager.createRunnableLink(new RebuildWith16Fix(project))).newline();
        if (!problemModules.isEmpty()) {
            builder.addLink("Change Java SDK to 1.6", myLinkManager.createRunnableLink(new SwitchTo16Fix(project, problemModules))).newline();
        }
    }
    addIssue().setSeverity(HighlightSeverity.WARNING).setSummary("Some classes have an unsupported version").setHtmlContent(builder).build();
}
Also used : HtmlBuilder(com.android.utils.HtmlBuilder) AndroidFacet(org.jetbrains.android.facet.AndroidFacet) Project(com.intellij.openapi.project.Project) Module(com.intellij.openapi.module.Module)

Aggregations

HtmlBuilder (com.android.utils.HtmlBuilder)36 NotNull (org.jetbrains.annotations.NotNull)9 XmlFile (com.intellij.psi.xml.XmlFile)8 Module (com.intellij.openapi.module.Module)7 Project (com.intellij.openapi.project.Project)7 File (java.io.File)6 IOException (java.io.IOException)3 AndroidFacet (org.jetbrains.android.facet.AndroidFacet)3 VisibleForTesting (com.android.annotations.VisibleForTesting)2 SourceFile (com.android.ide.common.blame.SourceFile)2 ResourceResolver (com.android.ide.common.resources.ResourceResolver)2 FolderConfiguration (com.android.ide.common.resources.configuration.FolderConfiguration)2 RepositoryPackages (com.android.repository.impl.meta.RepositoryPackages)2 ResourceFolderType (com.android.resources.ResourceFolderType)2 AndroidVersion (com.android.sdklib.AndroidVersion)2 IAndroidTarget (com.android.sdklib.IAndroidTarget)2 GradleBuildFile (com.android.tools.idea.gradle.parser.GradleBuildFile)2 AndroidModuleModel (com.android.tools.idea.gradle.project.model.AndroidModuleModel)2 AndroidModuleInfo (com.android.tools.idea.model.AndroidModuleInfo)2 EditorDesignSurface (com.android.tools.idea.ui.designer.EditorDesignSurface)2