Search in sources :

Example 26 with ResourceResolver

use of com.android.ide.common.resources.ResourceResolver in project android by JetBrains.

the class ColorRendererEditor method updateComponent.

@Override
protected void updateComponent(@NotNull ThemeEditorContext context, @NotNull ResourceComponent component, @NotNull EditedStyleItem item) {
    ResourceResolver resourceResolver = context.getResourceResolver();
    assert resourceResolver != null;
    final List<Color> colors = ResourceHelper.resolveMultipleColors(resourceResolver, item.getSelectedValue(), context.getProject());
    SwatchComponent.SwatchIcon icon;
    if (colors.isEmpty()) {
        icon = SwatchComponent.WARNING_ICON;
    } else {
        icon = new SwatchComponent.ColorIcon(Iterables.getLast(colors));
        icon.setIsStack(colors.size() > 1);
    }
    component.setSwatchIcon(icon);
    component.setNameText(item.getQualifiedName());
    component.setValueText(item.getValue());
    if (!colors.isEmpty()) {
        Color color = Iterables.getLast(colors);
        String attributeName = item.getName();
        ImmutableMap<String, Color> contrastColorsWithDescription = ColorUtils.getContrastColorsWithDescription(context, attributeName);
        component.setWarning(ColorUtils.getContrastWarningMessage(contrastColorsWithDescription, color, ColorUtils.isBackgroundAttribute(attributeName)));
    } else {
        component.setWarning(null);
    }
}
Also used : ResourceResolver(com.android.ide.common.resources.ResourceResolver) SwatchComponent(com.android.tools.swing.ui.SwatchComponent)

Example 27 with ResourceResolver

use of com.android.ide.common.resources.ResourceResolver in project android by JetBrains.

the class StyleListPaletteCellRenderer method customizeCellRenderer.

@Override
protected void customizeCellRenderer(JList list, Object value, int index, boolean selected, boolean hasFocus) {
    super.customizeCellRenderer(list, value, index, selected, hasFocus);
    if (!(value instanceof String) || ThemesListModel.isSpecialOption((String) value)) {
        myColorPaletteComponent.reset();
        return;
    }
    ThemeResolver themeResolver = myContext.getThemeResolver();
    final ConfiguredThemeEditorStyle theme = themeResolver.getTheme((String) value);
    if (theme == null) {
        myColorPaletteComponent.reset();
        setIcon(null);
        return;
    }
    final boolean isFrameworkAttr = !ThemeEditorUtils.isAppCompatTheme(theme);
    ItemResourceValue primaryResourceValue = ThemeEditorUtils.resolveItemFromParents(theme, PRIMARY_MATERIAL, isFrameworkAttr);
    ItemResourceValue primaryDarkResourceValue = ThemeEditorUtils.resolveItemFromParents(theme, PRIMARY_DARK_MATERIAL, isFrameworkAttr);
    ItemResourceValue accentResourceValue = ThemeEditorUtils.resolveItemFromParents(theme, ACCENT_MATERIAL, isFrameworkAttr);
    //Check needed in case the xml files are inconsistent and have an item, but not a value
    if (primaryResourceValue != null && primaryDarkResourceValue != null && accentResourceValue != null) {
        Configuration configuration = theme.getConfiguration();
        ResourceResolver resourceResolver = configuration.getConfigurationManager().getResolverCache().getResourceResolver(configuration.getRealTarget(), theme.getStyleResourceUrl(), configuration.getFullConfig());
        Color primaryColor = ResourceHelper.resolveColor(resourceResolver, primaryResourceValue, myContext.getProject());
        Color primaryDarkColor = ResourceHelper.resolveColor(resourceResolver, primaryDarkResourceValue, myContext.getProject());
        Color accentColor = ResourceHelper.resolveColor(resourceResolver, accentResourceValue, myContext.getProject());
        if (primaryColor != null && primaryDarkColor != null && accentColor != null) {
            myColorPaletteComponent.setValues(primaryColor, primaryDarkColor, accentColor);
        }
        setIcon(myColorPaletteComponent);
    } else {
        myColorPaletteComponent.reset();
        setIcon(null);
    }
    if (selected) {
        myThemeChangedListener.themeChanged(theme.getQualifiedName());
    }
}
Also used : ItemResourceValue(com.android.ide.common.rendering.api.ItemResourceValue) Configuration(com.android.tools.idea.configurations.Configuration) ThemeResolver(com.android.tools.idea.editors.theme.ThemeResolver) ResourceResolver(com.android.ide.common.resources.ResourceResolver) ConfiguredThemeEditorStyle(com.android.tools.idea.editors.theme.datamodels.ConfiguredThemeEditorStyle)

Example 28 with ResourceResolver

use of com.android.ide.common.resources.ResourceResolver in project android by JetBrains.

the class AndroidColorAnnotator method annotateResourceReference.

private static void annotateResourceReference(@NotNull ResourceType type, @NotNull AnnotationHolder holder, @NotNull PsiElement element, @NotNull String name, boolean isFramework) {
    Module module = ModuleUtilCore.findModuleForPsiElement(element);
    if (module == null) {
        return;
    }
    AndroidFacet facet = AndroidFacet.getInstance(module);
    if (facet == null) {
        return;
    }
    PsiFile file = PsiTreeUtil.getParentOfType(element, PsiFile.class);
    if (file == null) {
        return;
    }
    Configuration configuration = pickConfiguration(facet, module, file);
    if (configuration == null) {
        return;
    }
    ResourceValue value = findResourceValue(type, name, isFramework, module, configuration);
    if (value != null) {
        // TODO: Use a *shared* fallback resolver for this?
        ResourceResolver resourceResolver = configuration.getResourceResolver();
        if (resourceResolver != null) {
            annotateResourceValue(type, holder, element, value, resourceResolver, facet);
        }
    }
}
Also used : Configuration(com.android.tools.idea.configurations.Configuration) FolderConfiguration(com.android.ide.common.resources.configuration.FolderConfiguration) ResourceValue(com.android.ide.common.rendering.api.ResourceValue) ResourceResolver(com.android.ide.common.resources.ResourceResolver) PsiFile(com.intellij.psi.PsiFile) Module(com.intellij.openapi.module.Module) AndroidFacet(org.jetbrains.android.facet.AndroidFacet)

Example 29 with ResourceResolver

use of com.android.ide.common.resources.ResourceResolver in project android by JetBrains.

the class GraphicsLayoutRenderer method create.

@VisibleForTesting
@NotNull
static GraphicsLayoutRenderer create(@NotNull AndroidFacet facet, @NotNull AndroidPlatform platform, @NotNull Project project, @NotNull Configuration configuration, @NotNull ILayoutPullParser parser, @Nullable Color backgroundColor, @NotNull SessionParams.RenderingMode renderingMode, boolean useSecurityManager) throws InitializationException {
    AndroidModuleInfo moduleInfo = AndroidModuleInfo.get(facet);
    LayoutLibrary layoutLib;
    try {
        IAndroidTarget latestTarget = configuration.getConfigurationManager().getHighestApiTarget();
        if (latestTarget == null) {
            throw new UnsupportedLayoutlibException("GraphicsLayoutRenderer requires at least layoutlib version " + MIN_LAYOUTLIB_API_VERSION);
        }
        layoutLib = platform.getSdkData().getTargetData(latestTarget).getLayoutLibrary(project);
        if (layoutLib == null) {
            throw new InitializationException("getLayoutLibrary() returned null");
        }
    } catch (RenderingException e) {
        throw new InitializationException(e);
    } catch (IOException e) {
        throw new InitializationException(e);
    }
    if (layoutLib.getApiLevel() < MIN_LAYOUTLIB_API_VERSION) {
        throw new UnsupportedLayoutlibException("GraphicsLayoutRenderer requires at least layoutlib version " + MIN_LAYOUTLIB_API_VERSION);
    }
    AppResourceRepository appResources = AppResourceRepository.getAppResources(facet, true);
    final Module module = facet.getModule();
    // Security token used to disable the security manager. Only objects that have a reference to it are allowed to disable it.
    Object credential = new Object();
    RenderLogger logger = new RenderLogger("theme_editor", module, credential);
    final ActionBarCallback actionBarCallback = new ActionBarCallback();
    // TODO: Remove LayoutlibCallback dependency.
    //noinspection ConstantConditions
    final LayoutlibCallbackImpl layoutlibCallback = new LayoutlibCallbackImpl(null, layoutLib, appResources, module, facet, logger, credential, null) {

        @Override
        public ActionBarCallback getActionBarCallback() {
            return actionBarCallback;
        }
    };
    // Load the local project R identifiers.
    boolean loadRResult = ApplicationManager.getApplication().runReadAction(new Computable<Boolean>() {

        @Override
        public Boolean compute() {
            // half way.
            if (module.isDisposed()) {
                return false;
            }
            layoutlibCallback.loadAndParseRClass();
            return true;
        }
    });
    if (!loadRResult) {
        throw new AlreadyDisposedException("Module was already disposed");
    }
    IAndroidTarget target = configuration.getTarget();
    if (target == null) {
        throw new InitializationException("Unable to get IAndroidTarget");
    }
    Device device = configuration.getDevice();
    assert device != null;
    HardwareConfigHelper hardwareConfigHelper = new HardwareConfigHelper(device);
    DynamicHardwareConfig hardwareConfig = new DynamicHardwareConfig(hardwareConfigHelper.getConfig());
    List<ResourceValue> resourceLookupChain = new ArrayList<ResourceValue>();
    ResourceResolver resourceResolver = ResourceResolver.copy(configuration.getResourceResolver());
    assert resourceResolver != null;
    // Create a resource resolver that will save the lookups on the passed List<>
    ResourceResolver recordingResourceResolver = resourceResolver.createRecorder(resourceLookupChain);
    final SessionParams params = new SessionParams(parser, renderingMode, module, hardwareConfig, recordingResourceResolver, layoutlibCallback, moduleInfo.getMinSdkVersion().getApiLevel(), moduleInfo.getTargetSdkVersion().getApiLevel(), logger, target instanceof CompatibilityRenderTarget ? target.getVersion().getApiLevel() : 0);
    params.setForceNoDecor();
    params.setAssetRepository(new AssetRepositoryImpl(facet));
    // The App Label needs to be not null
    params.setAppLabel("");
    if (backgroundColor != null) {
        params.setOverrideBgColor(backgroundColor.getRGB());
    }
    RenderSecurityManager mySecurityManager = useSecurityManager ? RenderSecurityManagerFactory.create(module, platform) : null;
    return new GraphicsLayoutRenderer(layoutLib, params, mySecurityManager, hardwareConfig, resourceLookupChain, credential);
}
Also used : LayoutLibrary(com.android.ide.common.rendering.LayoutLibrary) AppResourceRepository(com.android.tools.idea.res.AppResourceRepository) AssetRepositoryImpl(com.android.tools.idea.res.AssetRepositoryImpl) AndroidModuleInfo(com.android.tools.idea.model.AndroidModuleInfo) HardwareConfigHelper(com.android.ide.common.rendering.HardwareConfigHelper) Device(com.android.sdklib.devices.Device) RenderingException(com.android.tools.idea.layoutlib.RenderingException) IAndroidTarget(com.android.sdklib.IAndroidTarget) IOException(java.io.IOException) CompatibilityRenderTarget(com.android.tools.idea.rendering.multi.CompatibilityRenderTarget) ResourceResolver(com.android.ide.common.resources.ResourceResolver) Module(com.intellij.openapi.module.Module) VisibleForTesting(com.google.common.annotations.VisibleForTesting) NotNull(org.jetbrains.annotations.NotNull)

Example 30 with ResourceResolver

use of com.android.ide.common.resources.ResourceResolver in project android by JetBrains.

the class ThemeEditorComponent method loadStyleAttributes.

/**
   * Loads the theme attributes table for the current selected theme or substyle.
   */
private void loadStyleAttributes() {
    ConfiguredThemeEditorStyle selectedTheme = getPreviewTheme();
    ConfiguredThemeEditorStyle selectedStyle = null;
    if (selectedTheme == null) {
        selectedTheme = getSelectedTheme();
        selectedStyle = getCurrentSubStyle();
    }
    // Clean any previous row sorters.
    myAttributesTable.setRowSorter(null);
    myPanel.setSubstyleName(mySubStyleName);
    myPanel.getBackButton().setVisible(mySubStyleName != null);
    AndroidThemePreviewPanel previewPanel = myPreviewComponent.getPreviewPanel();
    if (selectedTheme == null) {
        if (myThemeName != null) {
            previewPanel.setErrorMessage("The theme " + myThemeName + " cannot be rendered in the current configuration");
        } else {
            previewPanel.setErrorMessage("No theme selected");
        }
        myAttributesTable.setModel(EMPTY_TABLE_MODEL);
        return;
    }
    previewPanel.setErrorMessage(null);
    myPanel.setShowThemeNotUsedWarning(false);
    if (selectedTheme.isProjectStyle()) {
        // Check whenever we reload the theme as any external file could have been changed that would affect this.
        // e.g. change to the manifest to use a theme.
        final PsiElement name = selectedTheme.getNamePsiElement();
        mySwingWorker = new SwingWorker<Boolean, Object>() {

            @Override
            protected Boolean doInBackground() throws Exception {
                // it's a project theme, so we should always have a name.
                assert name != null;
                return ReferencesSearch.search(name).findFirst() == null;
            }

            @Override
            protected void done() {
                if (isCancelled()) {
                    return;
                }
                try {
                    myPanel.setShowThemeNotUsedWarning(get());
                } catch (Exception ex) {
                    // should never happen, as we are calling get from done.
                    throw new RuntimeException(ex);
                }
            }
        };
        mySwingWorker.execute();
    }
    myThemeEditorContext.setCurrentTheme(selectedTheme);
    final Configuration configuration = myThemeEditorContext.getConfiguration();
    configuration.setTheme(selectedTheme.getStyleResourceUrl());
    myModel = new AttributesTableModel(selectedStyle != null ? selectedStyle : selectedTheme, getSelectedAttrGroup(), myThemeEditorContext);
    myModel.addThemePropertyChangedListener(new AttributesTableModel.ThemePropertyChangedListener() {

        @Override
        public void attributeChangedOnReadOnlyTheme(final EditedStyleItem attribute, final String newValue) {
            createNewThemeWithAttributeValue(attribute, newValue);
        }
    });
    myAttributesSorter = new TableRowSorter<AttributesTableModel>(myModel);
    // This is only used when the sort keys are set (only set in simple mode).
    myAttributesSorter.setComparator(0, SIMPLE_MODE_COMPARATOR);
    configureFilter();
    int row = myAttributesTable.getEditingRow();
    int column = myAttributesTable.getEditingColumn();
    // If an editor is present, remove it to update the entire table, do nothing otherwise
    myAttributesTable.removeEditor();
    // update the table
    myAttributesTable.setModel(myModel);
    myAttributesTable.setRowSorter(myAttributesSorter);
    myAttributesTable.updateRowHeights();
    // as a refresh can happen at any point, we want to restore the editor if one was present, do nothing otherwise
    myAttributesTable.editCellAt(row, column);
    myPanel.getPalette().setModel(new AttributesModelColorPaletteModel(configuration, myModel));
    myPanel.getPalette().addItemListener(new ItemListener() {

        @Override
        public void itemStateChanged(ItemEvent e) {
            if (e.getStateChange() == ItemEvent.SELECTED) {
                AttributesModelColorPaletteModel model = (AttributesModelColorPaletteModel) myPanel.getPalette().getModel();
                List<EditedStyleItem> references = model.getReferences((Color) e.getItem());
                if (references.isEmpty()) {
                    return;
                }
                HashSet<String> attributeNames = new HashSet<String>(references.size());
                for (EditedStyleItem item : references) {
                    attributeNames.add(item.getQualifiedName());
                }
                myAttributesFilter.setAttributesFilter(attributeNames);
                myAttributesFilter.setFilterEnabled(true);
            } else {
                myAttributesFilter.setFilterEnabled(false);
            }
            if (myAttributesTable.isEditing()) {
                myAttributesTable.getCellEditor().cancelCellEditing();
            }
            ((TableRowSorter) myAttributesTable.getRowSorter()).sort();
            myPanel.getAdvancedFilterCheckBox().getModel().setSelected(!myAttributesFilter.myIsFilterEnabled);
        }
    });
    myAttributesTable.updateRowHeights();
    ResourceResolver resourceResolver = myThemeEditorContext.getResourceResolver();
    assert resourceResolver != null;
    myPreviewComponent.setPreviewBackground(ThemeEditorUtils.getGoodContrastPreviewBackground(selectedTheme, resourceResolver));
    myPreviewComponent.reloadPreviewContents();
    myAttributesTable.repaint();
    myPanel.getThemeCombo().repaint();
}
Also used : AttributesTableModel(com.android.tools.idea.editors.theme.attributes.AttributesTableModel) ItemEvent(java.awt.event.ItemEvent) ConfiguredThemeEditorStyle(com.android.tools.idea.editors.theme.datamodels.ConfiguredThemeEditorStyle) EditedStyleItem(com.android.tools.idea.editors.theme.datamodels.EditedStyleItem) AndroidThemePreviewPanel(com.android.tools.idea.editors.theme.preview.AndroidThemePreviewPanel) AttributesModelColorPaletteModel(com.android.tools.idea.editors.theme.attributes.AttributesModelColorPaletteModel) ResourceResolver(com.android.ide.common.resources.ResourceResolver) ItemListener(java.awt.event.ItemListener) List(java.util.List) PsiElement(com.intellij.psi.PsiElement)

Aggregations

ResourceResolver (com.android.ide.common.resources.ResourceResolver)43 Configuration (com.android.tools.idea.configurations.Configuration)16 ResourceValue (com.android.ide.common.rendering.api.ResourceValue)13 NotNull (org.jetbrains.annotations.NotNull)11 FolderConfiguration (com.android.ide.common.resources.configuration.FolderConfiguration)8 ItemResourceValue (com.android.ide.common.rendering.api.ItemResourceValue)6 Nullable (org.jetbrains.annotations.Nullable)6 SessionParams (com.android.ide.common.rendering.api.SessionParams)5 StyleResourceValue (com.android.ide.common.rendering.api.StyleResourceValue)5 ConfiguredThemeEditorStyle (com.android.tools.idea.editors.theme.datamodels.ConfiguredThemeEditorStyle)5 Module (com.intellij.openapi.module.Module)5 VirtualFile (com.intellij.openapi.vfs.VirtualFile)5 IAndroidTarget (com.android.sdklib.IAndroidTarget)4 Project (com.intellij.openapi.project.Project)4 ResourceType (com.android.resources.ResourceType)3 CompatibilityRenderTarget (com.android.tools.idea.rendering.multi.CompatibilityRenderTarget)3 XmlFile (com.intellij.psi.xml.XmlFile)3 ResourceRepository (com.android.ide.common.resources.ResourceRepository)2 Device (com.android.sdklib.devices.Device)2 ConfigurationManager (com.android.tools.idea.configurations.ConfigurationManager)2