2 * Copyright (C) 2017 The Android Open Source Project
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License
17 package com.android.internal.colorextraction.types;
19 import android.annotation.NonNull;
20 import android.annotation.Nullable;
21 import android.app.WallpaperColors;
22 import android.content.Context;
23 import android.graphics.Color;
24 import android.util.Log;
25 import android.util.MathUtils;
26 import android.util.Range;
28 import com.android.internal.R;
29 import com.android.internal.annotations.VisibleForTesting;
30 import com.android.internal.colorextraction.ColorExtractor.GradientColors;
31 import com.android.internal.graphics.ColorUtils;
33 import org.xmlpull.v1.XmlPullParser;
34 import org.xmlpull.v1.XmlPullParserException;
36 import java.io.IOException;
37 import java.util.ArrayList;
38 import java.util.Arrays;
39 import java.util.List;
42 * Implementation of tonal color extraction
44 public class Tonal implements ExtractionType {
45 private static final String TAG = "Tonal";
47 // Used for tonal palette fitting
48 private static final float FIT_WEIGHT_H = 1.0f;
49 private static final float FIT_WEIGHT_S = 1.0f;
50 private static final float FIT_WEIGHT_L = 10.0f;
52 private static final boolean DEBUG = true;
54 public static final int MAIN_COLOR_LIGHT = 0xffe0e0e0;
55 public static final int SECONDARY_COLOR_LIGHT = 0xff9e9e9e;
56 public static final int MAIN_COLOR_DARK = 0xff212121;
57 public static final int SECONDARY_COLOR_DARK = 0xff000000;
59 private final TonalPalette mGreyPalette;
60 private final ArrayList<TonalPalette> mTonalPalettes;
61 private final ArrayList<ColorRange> mBlacklistedColors;
63 // Temporary variable to avoid allocations
64 private float[] mTmpHSL = new float[3];
66 public Tonal(Context context) {
68 ConfigParser parser = new ConfigParser(context);
69 mTonalPalettes = parser.getTonalPalettes();
70 mBlacklistedColors = parser.getBlacklistedColors();
72 mGreyPalette = mTonalPalettes.get(0);
73 mTonalPalettes.remove(0);
77 * Grab colors from WallpaperColors and set them into GradientColors.
78 * Also applies the default gradient in case extraction fails.
80 * @param inWallpaperColors Input.
81 * @param outColorsNormal Colors for normal theme.
82 * @param outColorsDark Colors for dar theme.
83 * @param outColorsExtraDark Colors for extra dark theme.
85 public void extractInto(@Nullable WallpaperColors inWallpaperColors,
86 @NonNull GradientColors outColorsNormal, @NonNull GradientColors outColorsDark,
87 @NonNull GradientColors outColorsExtraDark) {
88 boolean success = runTonalExtraction(inWallpaperColors, outColorsNormal, outColorsDark,
91 applyFallback(inWallpaperColors, outColorsNormal, outColorsDark, outColorsExtraDark);
96 * Grab colors from WallpaperColors and set them into GradientColors.
98 * @param inWallpaperColors Input.
99 * @param outColorsNormal Colors for normal theme.
100 * @param outColorsDark Colors for dar theme.
101 * @param outColorsExtraDark Colors for extra dark theme.
102 * @return True if succeeded or false if failed.
104 private boolean runTonalExtraction(@Nullable WallpaperColors inWallpaperColors,
105 @NonNull GradientColors outColorsNormal, @NonNull GradientColors outColorsDark,
106 @NonNull GradientColors outColorsExtraDark) {
108 if (inWallpaperColors == null) {
112 final List<Color> mainColors = inWallpaperColors.getMainColors();
113 final int mainColorsSize = mainColors.size();
114 final int hints = inWallpaperColors.getColorHints();
115 final boolean supportsDarkText = (hints & WallpaperColors.HINT_SUPPORTS_DARK_TEXT) != 0;
116 final boolean generatedFromBitmap = (hints & WallpaperColors.HINT_FROM_BITMAP) != 0;
118 if (mainColorsSize == 0) {
122 // Decide what's the best color to use.
123 // We have 2 options:
124 // • Just pick the primary color
125 // • Filter out blacklisted colors. This is useful when palette is generated
126 // automatically from a bitmap.
127 Color bestColor = null;
128 final float[] hsl = new float[3];
129 for (int i = 0; i < mainColorsSize; i++) {
130 final Color color = mainColors.get(i);
131 final int colorValue = color.toArgb();
132 ColorUtils.RGBToHSL(Color.red(colorValue), Color.green(colorValue),
133 Color.blue(colorValue), hsl);
135 // Stop when we find a color that meets our criteria
136 if (!generatedFromBitmap || !isBlacklisted(hsl)) {
143 if (bestColor == null) {
147 // Tonal is not really a sort, it takes a color from the extracted
148 // palette and finds a best fit amongst a collection of pre-defined
149 // palettes. The best fit is tweaked to be closer to the source color
150 // and replaces the original palette.
151 int colorValue = bestColor.toArgb();
152 ColorUtils.RGBToHSL(Color.red(colorValue), Color.green(colorValue), Color.blue(colorValue),
155 // The Android HSL definition requires the hue to go from 0 to 360 but
156 // the Material Tonal Palette defines hues from 0 to 1.
159 // Find the palette that contains the closest color
160 TonalPalette palette = findTonalPalette(hsl[0], hsl[1]);
161 if (palette == null) {
162 Log.w(TAG, "Could not find a tonal palette!");
166 // Figure out what's the main color index in the optimal palette
167 int fitIndex = bestFit(palette, hsl[0], hsl[1], hsl[2]);
168 if (fitIndex == -1) {
169 Log.w(TAG, "Could not find best fit!");
173 // Generate the 10 colors palette by offsetting each one of them
174 float[] h = fit(palette.h, hsl[0], fitIndex,
175 Float.NEGATIVE_INFINITY, Float.POSITIVE_INFINITY);
176 float[] s = fit(palette.s, hsl[1], fitIndex, 0.0f, 1.0f);
177 float[] l = fit(palette.l, hsl[2], fitIndex, 0.0f, 1.0f);
180 StringBuilder builder = new StringBuilder("Tonal Palette - index: " + fitIndex +
181 ". Main color: " + Integer.toHexString(getColorInt(fitIndex, h, s, l)) +
184 for (int i=0; i < h.length; i++) {
185 builder.append(Integer.toHexString(getColorInt(i, h, s, l)));
186 if (i < h.length - 1) {
187 builder.append(", ");
190 Log.d(TAG, builder.toString());
193 int primaryIndex = fitIndex;
194 int mainColor = getColorInt(primaryIndex, h, s, l);
196 // We might want use the fallback in case the extracted color is brighter than our
197 // light fallback or darker than our dark fallback.
198 ColorUtils.colorToHSL(mainColor, mTmpHSL);
199 final float mainLuminosity = mTmpHSL[2];
200 ColorUtils.colorToHSL(MAIN_COLOR_LIGHT, mTmpHSL);
201 final float lightLuminosity = mTmpHSL[2];
202 if (mainLuminosity > lightLuminosity) {
205 ColorUtils.colorToHSL(MAIN_COLOR_DARK, mTmpHSL);
206 final float darkLuminosity = mTmpHSL[2];
207 if (mainLuminosity < darkLuminosity) {
212 // best fit + a 2 colors offset
213 outColorsNormal.setMainColor(mainColor);
214 int secondaryIndex = primaryIndex + (primaryIndex >= 2 ? -2 : 2);
215 outColorsNormal.setSecondaryColor(getColorInt(secondaryIndex, h, s, l));
218 // Stops at 4th color, only lighter if dark text is supported
219 if (supportsDarkText) {
220 primaryIndex = h.length - 1;
221 } else if (fitIndex < 2) {
224 primaryIndex = Math.min(fitIndex, 3);
226 secondaryIndex = primaryIndex + (primaryIndex >= 2 ? -2 : 2);
227 outColorsDark.setMainColor(getColorInt(primaryIndex, h, s, l));
228 outColorsDark.setSecondaryColor(getColorInt(secondaryIndex, h, s, l));
231 // Stay close to dark colors until dark text is supported
232 if (supportsDarkText) {
233 primaryIndex = h.length - 1;
234 } else if (fitIndex < 2) {
239 secondaryIndex = primaryIndex + (primaryIndex >= 2 ? -2 : 2);
240 outColorsExtraDark.setMainColor(getColorInt(primaryIndex, h, s, l));
241 outColorsExtraDark.setSecondaryColor(getColorInt(secondaryIndex, h, s, l));
243 outColorsNormal.setSupportsDarkText(supportsDarkText);
244 outColorsDark.setSupportsDarkText(supportsDarkText);
245 outColorsExtraDark.setSupportsDarkText(supportsDarkText);
248 Log.d(TAG, "Gradients: \n\tNormal " + outColorsNormal + "\n\tDark " + outColorsDark
249 + "\n\tExtra dark: " + outColorsExtraDark);
255 private void applyFallback(@Nullable WallpaperColors inWallpaperColors,
256 GradientColors outColorsNormal, GradientColors outColorsDark,
257 GradientColors outColorsExtraDark) {
258 applyFallback(inWallpaperColors, outColorsNormal);
259 applyFallback(inWallpaperColors, outColorsDark);
260 applyFallback(inWallpaperColors, outColorsExtraDark);
264 * Sets the gradient to the light or dark fallbacks based on the current wallpaper colors.
266 * @param inWallpaperColors Colors to read.
267 * @param outGradientColors Destination.
269 public static void applyFallback(@Nullable WallpaperColors inWallpaperColors,
270 @NonNull GradientColors outGradientColors) {
271 boolean light = inWallpaperColors != null
272 && (inWallpaperColors.getColorHints() & WallpaperColors.HINT_SUPPORTS_DARK_TEXT)
274 int innerColor = light ? MAIN_COLOR_LIGHT : MAIN_COLOR_DARK;
275 int outerColor = light ? SECONDARY_COLOR_LIGHT : SECONDARY_COLOR_DARK;
277 outGradientColors.setMainColor(innerColor);
278 outGradientColors.setSecondaryColor(outerColor);
279 outGradientColors.setSupportsDarkText(light);
282 private int getColorInt(int fitIndex, float[] h, float[] s, float[] l) {
283 mTmpHSL[0] = fract(h[fitIndex]) * 360.0f;
284 mTmpHSL[1] = s[fitIndex];
285 mTmpHSL[2] = l[fitIndex];
286 return ColorUtils.HSLToColor(mTmpHSL);
290 * Checks if a given color exists in the blacklist
291 * @param hsl float array with 3 components (H 0..360, S 0..1 and L 0..1)
292 * @return true if color should be avoided
294 private boolean isBlacklisted(float[] hsl) {
295 for (int i = mBlacklistedColors.size() - 1; i >= 0; i--) {
296 ColorRange badRange = mBlacklistedColors.get(i);
297 if (badRange.containsColor(hsl[0], hsl[1], hsl[2])) {
305 * Offsets all colors by a delta, clamping values that go beyond what's
306 * supported on the color space.
307 * @param data what you want to fit
308 * @param v how big should be the offset
309 * @param index which index to calculate the delta against
310 * @param min minimum accepted value (clamp)
311 * @param max maximum accepted value (clamp)
312 * @return new shifted palette
314 private static float[] fit(float[] data, float v, int index, float min, float max) {
315 float[] fitData = new float[data.length];
316 float delta = v - data[index];
318 for (int i = 0; i < data.length; i++) {
319 fitData[i] = MathUtils.constrain(data[i] + delta, min, max);
326 * Finds the closest color in a palette, given another HSL color
328 * @param palette where to search
330 * @param s saturation
332 * @return closest index or -1 if palette is empty.
334 private static int bestFit(@NonNull TonalPalette palette, float h, float s, float l) {
335 int minErrorIndex = -1;
336 float minError = Float.POSITIVE_INFINITY;
338 for (int i = 0; i < palette.h.length; i++) {
340 FIT_WEIGHT_H * Math.abs(h - palette.h[i])
341 + FIT_WEIGHT_S * Math.abs(s - palette.s[i])
342 + FIT_WEIGHT_L * Math.abs(l - palette.l[i]);
343 if (error < minError) {
349 return minErrorIndex;
353 public List<ColorRange> getBlacklistedColors() {
354 return mBlacklistedColors;
358 private TonalPalette findTonalPalette(float h, float s) {
359 // Fallback to a grey palette if the color is too desaturated.
360 // This avoids hue shifts.
365 TonalPalette best = null;
366 float error = Float.POSITIVE_INFINITY;
368 final int tonalPalettesCount = mTonalPalettes.size();
369 for (int i = 0; i < tonalPalettesCount; i++) {
370 final TonalPalette candidate = mTonalPalettes.get(i);
372 if (h >= candidate.minHue && h <= candidate.maxHue) {
377 if (candidate.maxHue > 1.0f && h >= 0.0f && h <= fract(candidate.maxHue)) {
382 if (candidate.minHue < 0.0f && h >= fract(candidate.minHue) && h <= 1.0f) {
387 if (h <= candidate.minHue && candidate.minHue - h < error) {
389 error = candidate.minHue - h;
390 } else if (h >= candidate.maxHue && h - candidate.maxHue < error) {
392 error = h - candidate.maxHue;
393 } else if (candidate.maxHue > 1.0f && h >= fract(candidate.maxHue)
394 && h - fract(candidate.maxHue) < error) {
396 error = h - fract(candidate.maxHue);
397 } else if (candidate.minHue < 0.0f && h <= fract(candidate.minHue)
398 && fract(candidate.minHue) - h < error) {
400 error = fract(candidate.minHue) - h;
407 private static float fract(float v) {
408 return v - (float) Math.floor(v);
411 static class TonalPalette {
418 TonalPalette(float[] h, float[] s, float[] l) {
419 if (h.length != s.length || s.length != l.length) {
420 throw new IllegalArgumentException("All arrays should have the same size. h: "
421 + Arrays.toString(h) + " s: " + Arrays.toString(s) + " l: "
422 + Arrays.toString(l));
428 float minHue = Float.POSITIVE_INFINITY;
429 float maxHue = Float.NEGATIVE_INFINITY;
432 minHue = Math.min(v, minHue);
433 maxHue = Math.max(v, maxHue);
436 this.minHue = minHue;
437 this.maxHue = maxHue;
442 * Representation of an HSL color range.
444 * <li>hsl[0] is Hue [0 .. 360)</li>
445 * <li>hsl[1] is Saturation [0...1]</li>
446 * <li>hsl[2] is Lightness [0...1]</li>
450 public static class ColorRange {
451 private Range<Float> mHue;
452 private Range<Float> mSaturation;
453 private Range<Float> mLightness;
455 public ColorRange(Range<Float> hue, Range<Float> saturation, Range<Float> lightness) {
457 mSaturation = saturation;
458 mLightness = lightness;
461 public boolean containsColor(float h, float s, float l) {
462 if (!mHue.contains(h)) {
464 } else if (!mSaturation.contains(s)) {
466 } else if (!mLightness.contains(l)) {
472 public float[] getCenter() {
474 mHue.getLower() + (mHue.getUpper() - mHue.getLower()) / 2f,
475 mSaturation.getLower() + (mSaturation.getUpper() - mSaturation.getLower()) / 2f,
476 mLightness.getLower() + (mLightness.getUpper() - mLightness.getLower()) / 2f
481 public String toString() {
482 return String.format("H: %s, S: %s, L %s", mHue, mSaturation, mLightness);
487 public static class ConfigParser {
488 private final ArrayList<TonalPalette> mTonalPalettes;
489 private final ArrayList<ColorRange> mBlacklistedColors;
491 public ConfigParser(Context context) {
492 mTonalPalettes = new ArrayList<>();
493 mBlacklistedColors = new ArrayList<>();
495 // Load all palettes and the blacklist from an XML.
497 XmlPullParser parser = context.getResources().getXml(R.xml.color_extraction);
498 int eventType = parser.getEventType();
499 while (eventType != XmlPullParser.END_DOCUMENT) {
500 if (eventType == XmlPullParser.START_DOCUMENT ||
501 eventType == XmlPullParser.END_TAG) {
503 } else if (eventType == XmlPullParser.START_TAG) {
504 String tagName = parser.getName();
505 if (tagName.equals("palettes")) {
506 parsePalettes(parser);
507 } else if (tagName.equals("blacklist")) {
508 parseBlacklist(parser);
511 throw new XmlPullParserException("Invalid XML event " + eventType + " - "
512 + parser.getName(), parser, null);
514 eventType = parser.next();
516 } catch (XmlPullParserException | IOException e) {
517 throw new RuntimeException(e);
521 public ArrayList<TonalPalette> getTonalPalettes() {
522 return mTonalPalettes;
525 public ArrayList<ColorRange> getBlacklistedColors() {
526 return mBlacklistedColors;
529 private void parseBlacklist(XmlPullParser parser)
530 throws XmlPullParserException, IOException {
531 parser.require(XmlPullParser.START_TAG, null, "blacklist");
532 while (parser.next() != XmlPullParser.END_TAG) {
533 if (parser.getEventType() != XmlPullParser.START_TAG) {
536 String name = parser.getName();
537 // Starts by looking for the entry tag
538 if (name.equals("range")) {
539 mBlacklistedColors.add(readRange(parser));
542 throw new XmlPullParserException("Invalid tag: " + name, parser, null);
547 private ColorRange readRange(XmlPullParser parser)
548 throws XmlPullParserException, IOException {
549 parser.require(XmlPullParser.START_TAG, null, "range");
550 float[] h = readFloatArray(parser.getAttributeValue(null, "h"));
551 float[] s = readFloatArray(parser.getAttributeValue(null, "s"));
552 float[] l = readFloatArray(parser.getAttributeValue(null, "l"));
554 if (h == null || s == null || l == null) {
555 throw new XmlPullParserException("Incomplete range tag.", parser, null);
558 return new ColorRange(new Range<>(h[0], h[1]), new Range<>(s[0], s[1]),
559 new Range<>(l[0], l[1]));
562 private void parsePalettes(XmlPullParser parser)
563 throws XmlPullParserException, IOException {
564 parser.require(XmlPullParser.START_TAG, null, "palettes");
565 while (parser.next() != XmlPullParser.END_TAG) {
566 if (parser.getEventType() != XmlPullParser.START_TAG) {
569 String name = parser.getName();
570 // Starts by looking for the entry tag
571 if (name.equals("palette")) {
572 mTonalPalettes.add(readPalette(parser));
575 throw new XmlPullParserException("Invalid tag: " + name);
580 private TonalPalette readPalette(XmlPullParser parser)
581 throws XmlPullParserException, IOException {
582 parser.require(XmlPullParser.START_TAG, null, "palette");
584 float[] h = readFloatArray(parser.getAttributeValue(null, "h"));
585 float[] s = readFloatArray(parser.getAttributeValue(null, "s"));
586 float[] l = readFloatArray(parser.getAttributeValue(null, "l"));
588 if (h == null || s == null || l == null) {
589 throw new XmlPullParserException("Incomplete range tag.", parser, null);
592 return new TonalPalette(h, s, l);
595 private float[] readFloatArray(String attributeValue)
596 throws IOException, XmlPullParserException {
597 String[] tokens = attributeValue.replaceAll(" ", "").replaceAll("\n", "").split(",");
598 float[] numbers = new float[tokens.length];
599 for (int i = 0; i < tokens.length; i++) {
600 numbers[i] = Float.parseFloat(tokens[i]);