blob: dbc086c2130443fba45248eb7082bbfd1938b2ab [file] [log] [blame]
Lucas Dupin65f56582017-04-27 10:21:41 -07001/*
2 * Copyright (C) 2017 The Android Open Source Project
3 *
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
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
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
15 */
16
Lucas Dupine2292a92017-07-06 14:35:30 -070017package com.android.internal.colorextraction.types;
Lucas Dupin65f56582017-04-27 10:21:41 -070018
Lucas Dupine2292a92017-07-06 14:35:30 -070019import android.annotation.NonNull;
20import android.annotation.Nullable;
Lucas Dupin65f56582017-04-27 10:21:41 -070021import android.app.WallpaperColors;
Lucas Dupin6e69c852017-07-06 16:09:24 -070022import android.content.Context;
Lucas Dupin65f56582017-04-27 10:21:41 -070023import android.graphics.Color;
Lucas Dupin65f56582017-04-27 10:21:41 -070024import android.util.Log;
25import android.util.MathUtils;
Lucas Dupin98ce4582017-05-22 19:43:45 -070026import android.util.Range;
Lucas Dupin65f56582017-04-27 10:21:41 -070027
Lucas Dupin6e69c852017-07-06 16:09:24 -070028import com.android.internal.R;
Lucas Dupine2292a92017-07-06 14:35:30 -070029import com.android.internal.annotations.VisibleForTesting;
30import com.android.internal.colorextraction.ColorExtractor.GradientColors;
31import com.android.internal.graphics.ColorUtils;
Lucas Dupin65f56582017-04-27 10:21:41 -070032
Lucas Dupin6e69c852017-07-06 16:09:24 -070033import org.xmlpull.v1.XmlPullParser;
34import org.xmlpull.v1.XmlPullParserException;
35
36import java.io.IOException;
37import java.util.ArrayList;
Lucas Dupin96a14c32017-06-22 15:35:15 -070038import java.util.Arrays;
Lucas Dupin84b89d92017-05-09 12:16:19 -070039import java.util.List;
40
Lucas Dupin65f56582017-04-27 10:21:41 -070041/**
42 * Implementation of tonal color extraction
43 */
44public class Tonal implements ExtractionType {
45 private static final String TAG = "Tonal";
46
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;
51
Lucas Dupin7aaa3532017-05-28 08:51:07 -070052 private static final boolean DEBUG = true;
Lucas Dupin65f56582017-04-27 10:21:41 -070053
Lucas Dupinc77b71d2017-07-05 17:34:41 -070054 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;
58
Lucas Dupin6e69c852017-07-06 16:09:24 -070059 private final TonalPalette mGreyPalette;
60 private final ArrayList<TonalPalette> mTonalPalettes;
61 private final ArrayList<ColorRange> mBlacklistedColors;
62
Lucas Dupin7aaa3532017-05-28 08:51:07 -070063 // Temporary variable to avoid allocations
64 private float[] mTmpHSL = new float[3];
Lucas Dupinccec5b62017-05-08 18:35:34 -070065
Lucas Dupin6e69c852017-07-06 16:09:24 -070066 public Tonal(Context context) {
67
68 ConfigParser parser = new ConfigParser(context);
69 mTonalPalettes = parser.getTonalPalettes();
70 mBlacklistedColors = parser.getBlacklistedColors();
71
72 mGreyPalette = mTonalPalettes.get(0);
73 mTonalPalettes.remove(0);
74 }
75
Lucas Dupinccec5b62017-05-08 18:35:34 -070076 /**
Lucas Dupinc77b71d2017-07-05 17:34:41 -070077 * Grab colors from WallpaperColors and set them into GradientColors.
78 * Also applies the default gradient in case extraction fails.
Lucas Dupinccec5b62017-05-08 18:35:34 -070079 *
Lucas Dupinc77b71d2017-07-05 17:34:41 -070080 * @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.
Lucas Dupinccec5b62017-05-08 18:35:34 -070084 */
Lucas Dupinc77b71d2017-07-05 17:34:41 -070085 public void extractInto(@Nullable WallpaperColors inWallpaperColors,
86 @NonNull GradientColors outColorsNormal, @NonNull GradientColors outColorsDark,
87 @NonNull GradientColors outColorsExtraDark) {
88 boolean success = runTonalExtraction(inWallpaperColors, outColorsNormal, outColorsDark,
89 outColorsExtraDark);
90 if (!success) {
91 applyFallback(inWallpaperColors, outColorsNormal, outColorsDark, outColorsExtraDark);
92 }
93 }
94
95 /**
96 * Grab colors from WallpaperColors and set them into GradientColors.
97 *
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.
103 */
104 private boolean runTonalExtraction(@Nullable WallpaperColors inWallpaperColors,
Lucas Dupin7aaa3532017-05-28 08:51:07 -0700105 @NonNull GradientColors outColorsNormal, @NonNull GradientColors outColorsDark,
106 @NonNull GradientColors outColorsExtraDark) {
Lucas Dupin65f56582017-04-27 10:21:41 -0700107
Lucas Dupinc77b71d2017-07-05 17:34:41 -0700108 if (inWallpaperColors == null) {
109 return false;
110 }
111
Lucas Dupin84b89d92017-05-09 12:16:19 -0700112 final List<Color> mainColors = inWallpaperColors.getMainColors();
113 final int mainColorsSize = mainColors.size();
Lucas Dupinc77b71d2017-07-05 17:34:41 -0700114 final boolean supportsDarkText = (inWallpaperColors.getColorHints() &
115 WallpaperColors.HINT_SUPPORTS_DARK_TEXT) != 0;
Lucas Dupin84b89d92017-05-09 12:16:19 -0700116
117 if (mainColorsSize == 0) {
Lucas Dupinccec5b62017-05-08 18:35:34 -0700118 return false;
Lucas Dupin65f56582017-04-27 10:21:41 -0700119 }
120 // Tonal is not really a sort, it takes a color from the extracted
121 // palette and finds a best fit amongst a collection of pre-defined
122 // palettes. The best fit is tweaked to be closer to the source color
123 // and replaces the original palette
124
Lucas Dupin84b89d92017-05-09 12:16:19 -0700125 // Get the most preeminent, non-blacklisted color.
126 Color bestColor = null;
127 final float[] hsl = new float[3];
128 for (int i = 0; i < mainColorsSize; i++) {
129 final Color color = mainColors.get(i);
130 final int colorValue = color.toArgb();
Lucas Dupin65f56582017-04-27 10:21:41 -0700131 ColorUtils.RGBToHSL(Color.red(colorValue), Color.green(colorValue),
132 Color.blue(colorValue), hsl);
Lucas Dupin98ce4582017-05-22 19:43:45 -0700133
134 // Stop when we find a color that meets our criteria
135 if (!isBlacklisted(hsl)) {
Lucas Dupin84b89d92017-05-09 12:16:19 -0700136 bestColor = color;
Lucas Dupinccec5b62017-05-08 18:35:34 -0700137 break;
Lucas Dupin65f56582017-04-27 10:21:41 -0700138 }
139 }
140
Lucas Dupin7aaa3532017-05-28 08:51:07 -0700141 // Fail if not found
Lucas Dupin65f56582017-04-27 10:21:41 -0700142 if (bestColor == null) {
Lucas Dupin98ce4582017-05-22 19:43:45 -0700143 return false;
Lucas Dupin65f56582017-04-27 10:21:41 -0700144 }
145
Lucas Dupin84b89d92017-05-09 12:16:19 -0700146 int colorValue = bestColor.toArgb();
Lucas Dupin65f56582017-04-27 10:21:41 -0700147 ColorUtils.RGBToHSL(Color.red(colorValue), Color.green(colorValue), Color.blue(colorValue),
148 hsl);
Lucas Dupin98ce4582017-05-22 19:43:45 -0700149
150 // The Android HSL definition requires the hue to go from 0 to 360 but
Lucas Dupin7aaa3532017-05-28 08:51:07 -0700151 // the Material Tonal Palette defines hues from 0 to 1.
152 hsl[0] /= 360f;
Lucas Dupin65f56582017-04-27 10:21:41 -0700153
Lucas Dupinccec5b62017-05-08 18:35:34 -0700154 // Find the palette that contains the closest color
Lucas Dupin5266ad12017-06-17 20:57:28 -0700155 TonalPalette palette = findTonalPalette(hsl[0], hsl[1]);
Lucas Dupin65f56582017-04-27 10:21:41 -0700156 if (palette == null) {
157 Log.w(TAG, "Could not find a tonal palette!");
Lucas Dupinccec5b62017-05-08 18:35:34 -0700158 return false;
Lucas Dupin65f56582017-04-27 10:21:41 -0700159 }
160
Lucas Dupin7aaa3532017-05-28 08:51:07 -0700161 // Figure out what's the main color index in the optimal palette
Lucas Dupin65f56582017-04-27 10:21:41 -0700162 int fitIndex = bestFit(palette, hsl[0], hsl[1], hsl[2]);
163 if (fitIndex == -1) {
164 Log.w(TAG, "Could not find best fit!");
Lucas Dupinccec5b62017-05-08 18:35:34 -0700165 return false;
Lucas Dupin65f56582017-04-27 10:21:41 -0700166 }
Lucas Dupin7aaa3532017-05-28 08:51:07 -0700167
168 // Generate the 10 colors palette by offsetting each one of them
Lucas Dupin65f56582017-04-27 10:21:41 -0700169 float[] h = fit(palette.h, hsl[0], fitIndex,
170 Float.NEGATIVE_INFINITY, Float.POSITIVE_INFINITY);
171 float[] s = fit(palette.s, hsl[1], fitIndex, 0.0f, 1.0f);
172 float[] l = fit(palette.l, hsl[2], fitIndex, 0.0f, 1.0f);
173
Lucas Dupin7aaa3532017-05-28 08:51:07 -0700174 if (DEBUG) {
175 StringBuilder builder = new StringBuilder("Tonal Palette - index: " + fitIndex +
176 ". Main color: " + Integer.toHexString(getColorInt(fitIndex, h, s, l)) +
177 "\nColors: ");
Lucas Dupin65f56582017-04-27 10:21:41 -0700178
Lucas Dupin7aaa3532017-05-28 08:51:07 -0700179 for (int i=0; i < h.length; i++) {
180 builder.append(Integer.toHexString(getColorInt(i, h, s, l)));
181 if (i < h.length - 1) {
182 builder.append(", ");
Lucas Dupinccec5b62017-05-08 18:35:34 -0700183 }
Lucas Dupinccec5b62017-05-08 18:35:34 -0700184 }
Lucas Dupin7aaa3532017-05-28 08:51:07 -0700185 Log.d(TAG, builder.toString());
Lucas Dupinccec5b62017-05-08 18:35:34 -0700186 }
187
Lucas Dupinc77b71d2017-07-05 17:34:41 -0700188 int primaryIndex = fitIndex;
189 int mainColor = getColorInt(primaryIndex, h, s, l);
190
191 // We might want use the fallback in case the extracted color is brighter than our
192 // light fallback or darker than our dark fallback.
193 ColorUtils.colorToHSL(mainColor, mTmpHSL);
194 final float mainLuminosity = mTmpHSL[2];
195 ColorUtils.colorToHSL(MAIN_COLOR_LIGHT, mTmpHSL);
196 final float lightLuminosity = mTmpHSL[2];
197 if (mainLuminosity > lightLuminosity) {
198 return false;
199 }
200 ColorUtils.colorToHSL(MAIN_COLOR_DARK, mTmpHSL);
201 final float darkLuminosity = mTmpHSL[2];
202 if (mainLuminosity < darkLuminosity) {
203 return false;
204 }
205
Lucas Dupin7aaa3532017-05-28 08:51:07 -0700206 // Normal colors:
207 // best fit + a 2 colors offset
Lucas Dupinc77b71d2017-07-05 17:34:41 -0700208 outColorsNormal.setMainColor(mainColor);
Lucas Dupin7aaa3532017-05-28 08:51:07 -0700209 int secondaryIndex = primaryIndex + (primaryIndex >= 2 ? -2 : 2);
Lucas Dupin7aaa3532017-05-28 08:51:07 -0700210 outColorsNormal.setSecondaryColor(getColorInt(secondaryIndex, h, s, l));
211
212 // Dark colors:
213 // Stops at 4th color, only lighter if dark text is supported
Lucas Dupinc77b71d2017-07-05 17:34:41 -0700214 if (supportsDarkText) {
Lucas Dupin7aaa3532017-05-28 08:51:07 -0700215 primaryIndex = h.length - 1;
Lucas Dupinc77b71d2017-07-05 17:34:41 -0700216 } else if (fitIndex < 2) {
217 primaryIndex = 0;
218 } else {
219 primaryIndex = Math.min(fitIndex, 3);
Lucas Dupin7aaa3532017-05-28 08:51:07 -0700220 }
221 secondaryIndex = primaryIndex + (primaryIndex >= 2 ? -2 : 2);
222 outColorsDark.setMainColor(getColorInt(primaryIndex, h, s, l));
223 outColorsDark.setSecondaryColor(getColorInt(secondaryIndex, h, s, l));
224
225 // Extra Dark:
226 // Stay close to dark colors until dark text is supported
Lucas Dupinc77b71d2017-07-05 17:34:41 -0700227 if (supportsDarkText) {
Lucas Dupin7aaa3532017-05-28 08:51:07 -0700228 primaryIndex = h.length - 1;
Lucas Dupinc77b71d2017-07-05 17:34:41 -0700229 } else if (fitIndex < 2) {
230 primaryIndex = 0;
231 } else {
232 primaryIndex = 2;
Lucas Dupin7aaa3532017-05-28 08:51:07 -0700233 }
234 secondaryIndex = primaryIndex + (primaryIndex >= 2 ? -2 : 2);
235 outColorsExtraDark.setMainColor(getColorInt(primaryIndex, h, s, l));
236 outColorsExtraDark.setSecondaryColor(getColorInt(secondaryIndex, h, s, l));
237
Lucas Dupin7aaa3532017-05-28 08:51:07 -0700238 outColorsNormal.setSupportsDarkText(supportsDarkText);
239 outColorsDark.setSupportsDarkText(supportsDarkText);
240 outColorsExtraDark.setSupportsDarkText(supportsDarkText);
241
242 if (DEBUG) {
243 Log.d(TAG, "Gradients: \n\tNormal " + outColorsNormal + "\n\tDark " + outColorsDark
Lucas Dupin6e69c852017-07-06 16:09:24 -0700244 + "\n\tExtra dark: " + outColorsExtraDark);
Lucas Dupin7aaa3532017-05-28 08:51:07 -0700245 }
Lucas Dupinccec5b62017-05-08 18:35:34 -0700246
247 return true;
Lucas Dupin65f56582017-04-27 10:21:41 -0700248 }
249
Lucas Dupinc77b71d2017-07-05 17:34:41 -0700250 private void applyFallback(@Nullable WallpaperColors inWallpaperColors,
251 GradientColors outColorsNormal, GradientColors outColorsDark,
252 GradientColors outColorsExtraDark) {
253 applyFallback(inWallpaperColors, outColorsNormal);
254 applyFallback(inWallpaperColors, outColorsDark);
255 applyFallback(inWallpaperColors, outColorsExtraDark);
256 }
257
258 /**
259 * Sets the gradient to the light or dark fallbacks based on the current wallpaper colors.
260 *
261 * @param inWallpaperColors Colors to read.
262 * @param outGradientColors Destination.
263 */
264 public static void applyFallback(@Nullable WallpaperColors inWallpaperColors,
265 @NonNull GradientColors outGradientColors) {
266 boolean light = inWallpaperColors != null
267 && (inWallpaperColors.getColorHints() & WallpaperColors.HINT_SUPPORTS_DARK_TEXT)
268 != 0;
269 int innerColor = light ? MAIN_COLOR_LIGHT : MAIN_COLOR_DARK;
270 int outerColor = light ? SECONDARY_COLOR_LIGHT : SECONDARY_COLOR_DARK;
271
272 outGradientColors.setMainColor(innerColor);
273 outGradientColors.setSecondaryColor(outerColor);
274 outGradientColors.setSupportsDarkText(light);
275 }
276
Lucas Dupin7aaa3532017-05-28 08:51:07 -0700277 private int getColorInt(int fitIndex, float[] h, float[] s, float[] l) {
278 mTmpHSL[0] = fract(h[fitIndex]) * 360.0f;
279 mTmpHSL[1] = s[fitIndex];
280 mTmpHSL[2] = l[fitIndex];
281 return ColorUtils.HSLToColor(mTmpHSL);
282 }
283
Lucas Dupin98ce4582017-05-22 19:43:45 -0700284 /**
285 * Checks if a given color exists in the blacklist
286 * @param hsl float array with 3 components (H 0..360, S 0..1 and L 0..1)
287 * @return true if color should be avoided
288 */
289 private boolean isBlacklisted(float[] hsl) {
Lucas Dupin6e69c852017-07-06 16:09:24 -0700290 for (int i = mBlacklistedColors.size() - 1; i >= 0; i--) {
291 ColorRange badRange = mBlacklistedColors.get(i);
Lucas Dupin98ce4582017-05-22 19:43:45 -0700292 if (badRange.containsColor(hsl[0], hsl[1], hsl[2])) {
293 return true;
294 }
295 }
296 return false;
297 }
298
Lucas Dupin65f56582017-04-27 10:21:41 -0700299 /**
300 * Offsets all colors by a delta, clamping values that go beyond what's
301 * supported on the color space.
302 * @param data what you want to fit
303 * @param v how big should be the offset
304 * @param index which index to calculate the delta against
305 * @param min minimum accepted value (clamp)
306 * @param max maximum accepted value (clamp)
Lucas Dupinccec5b62017-05-08 18:35:34 -0700307 * @return new shifted palette
Lucas Dupin65f56582017-04-27 10:21:41 -0700308 */
309 private static float[] fit(float[] data, float v, int index, float min, float max) {
310 float[] fitData = new float[data.length];
311 float delta = v - data[index];
312
313 for (int i = 0; i < data.length; i++) {
314 fitData[i] = MathUtils.constrain(data[i] + delta, min, max);
315 }
316
317 return fitData;
318 }
319
Lucas Dupin65f56582017-04-27 10:21:41 -0700320 /**
321 * Finds the closest color in a palette, given another HSL color
322 *
323 * @param palette where to search
324 * @param h hue
325 * @param s saturation
326 * @param l lightness
327 * @return closest index or -1 if palette is empty.
328 */
329 private static int bestFit(@NonNull TonalPalette palette, float h, float s, float l) {
330 int minErrorIndex = -1;
331 float minError = Float.POSITIVE_INFINITY;
332
333 for (int i = 0; i < palette.h.length; i++) {
334 float error =
335 FIT_WEIGHT_H * Math.abs(h - palette.h[i])
336 + FIT_WEIGHT_S * Math.abs(s - palette.s[i])
337 + FIT_WEIGHT_L * Math.abs(l - palette.l[i]);
338 if (error < minError) {
339 minError = error;
340 minErrorIndex = i;
341 }
342 }
343
344 return minErrorIndex;
345 }
346
Lucas Dupin6e69c852017-07-06 16:09:24 -0700347 @VisibleForTesting
348 public List<ColorRange> getBlacklistedColors() {
349 return mBlacklistedColors;
350 }
351
Lucas Dupin65f56582017-04-27 10:21:41 -0700352 @Nullable
Lucas Dupin6e69c852017-07-06 16:09:24 -0700353 private TonalPalette findTonalPalette(float h, float s) {
Lucas Dupin5266ad12017-06-17 20:57:28 -0700354 // Fallback to a grey palette if the color is too desaturated.
355 // This avoids hue shifts.
356 if (s < 0.05f) {
Lucas Dupin6e69c852017-07-06 16:09:24 -0700357 return mGreyPalette;
Lucas Dupin5266ad12017-06-17 20:57:28 -0700358 }
359
Lucas Dupin65f56582017-04-27 10:21:41 -0700360 TonalPalette best = null;
361 float error = Float.POSITIVE_INFINITY;
362
Lucas Dupin6e69c852017-07-06 16:09:24 -0700363 final int tonalPalettesCount = mTonalPalettes.size();
364 for (int i = 0; i < tonalPalettesCount; i++) {
365 final TonalPalette candidate = mTonalPalettes.get(i);
Lucas Dupin84b89d92017-05-09 12:16:19 -0700366
Lucas Dupin65f56582017-04-27 10:21:41 -0700367 if (h >= candidate.minHue && h <= candidate.maxHue) {
368 best = candidate;
369 break;
370 }
371
372 if (candidate.maxHue > 1.0f && h >= 0.0f && h <= fract(candidate.maxHue)) {
373 best = candidate;
374 break;
375 }
376
377 if (candidate.minHue < 0.0f && h >= fract(candidate.minHue) && h <= 1.0f) {
378 best = candidate;
379 break;
380 }
381
382 if (h <= candidate.minHue && candidate.minHue - h < error) {
383 best = candidate;
384 error = candidate.minHue - h;
385 } else if (h >= candidate.maxHue && h - candidate.maxHue < error) {
386 best = candidate;
387 error = h - candidate.maxHue;
388 } else if (candidate.maxHue > 1.0f && h >= fract(candidate.maxHue)
389 && h - fract(candidate.maxHue) < error) {
390 best = candidate;
391 error = h - fract(candidate.maxHue);
392 } else if (candidate.minHue < 0.0f && h <= fract(candidate.minHue)
393 && fract(candidate.minHue) - h < error) {
394 best = candidate;
395 error = fract(candidate.minHue) - h;
396 }
397 }
398
399 return best;
400 }
401
402 private static float fract(float v) {
403 return v - (float) Math.floor(v);
404 }
405
406 static class TonalPalette {
407 final float[] h;
408 final float[] s;
409 final float[] l;
410 final float minHue;
411 final float maxHue;
412
413 TonalPalette(float[] h, float[] s, float[] l) {
Lucas Dupin96a14c32017-06-22 15:35:15 -0700414 if (h.length != s.length || s.length != l.length) {
415 throw new IllegalArgumentException("All arrays should have the same size. h: "
416 + Arrays.toString(h) + " s: " + Arrays.toString(s) + " l: "
417 + Arrays.toString(l));
418 }
Lucas Dupin65f56582017-04-27 10:21:41 -0700419 this.h = h;
420 this.s = s;
421 this.l = l;
422
423 float minHue = Float.POSITIVE_INFINITY;
424 float maxHue = Float.NEGATIVE_INFINITY;
425
426 for (float v : h) {
427 minHue = Math.min(v, minHue);
428 maxHue = Math.max(v, maxHue);
429 }
430
431 this.minHue = minHue;
432 this.maxHue = maxHue;
433 }
434 }
435
Lucas Dupin98ce4582017-05-22 19:43:45 -0700436 /**
437 * Representation of an HSL color range.
438 * <ul>
439 * <li>hsl[0] is Hue [0 .. 360)</li>
440 * <li>hsl[1] is Saturation [0...1]</li>
441 * <li>hsl[2] is Lightness [0...1]</li>
442 * </ul>
443 */
444 @VisibleForTesting
Lucas Dupine2292a92017-07-06 14:35:30 -0700445 public static class ColorRange {
Lucas Dupin98ce4582017-05-22 19:43:45 -0700446 private Range<Float> mHue;
447 private Range<Float> mSaturation;
448 private Range<Float> mLightness;
449
Lucas Dupine2292a92017-07-06 14:35:30 -0700450 public ColorRange(Range<Float> hue, Range<Float> saturation, Range<Float> lightness) {
Lucas Dupin98ce4582017-05-22 19:43:45 -0700451 mHue = hue;
452 mSaturation = saturation;
453 mLightness = lightness;
454 }
455
Lucas Dupine2292a92017-07-06 14:35:30 -0700456 public boolean containsColor(float h, float s, float l) {
Lucas Dupin98ce4582017-05-22 19:43:45 -0700457 if (!mHue.contains(h)) {
458 return false;
459 } else if (!mSaturation.contains(s)) {
460 return false;
461 } else if (!mLightness.contains(l)) {
462 return false;
463 }
464 return true;
465 }
466
Lucas Dupine2292a92017-07-06 14:35:30 -0700467 public float[] getCenter() {
Lucas Dupin98ce4582017-05-22 19:43:45 -0700468 return new float[] {
469 mHue.getLower() + (mHue.getUpper() - mHue.getLower()) / 2f,
470 mSaturation.getLower() + (mSaturation.getUpper() - mSaturation.getLower()) / 2f,
471 mLightness.getLower() + (mLightness.getUpper() - mLightness.getLower()) / 2f
472 };
473 }
474
475 @Override
476 public String toString() {
477 return String.format("H: %s, S: %s, L %s", mHue, mSaturation, mLightness);
478 }
479 }
Lucas Dupin6e69c852017-07-06 16:09:24 -0700480
481 @VisibleForTesting
482 public static class ConfigParser {
483 private final ArrayList<TonalPalette> mTonalPalettes;
484 private final ArrayList<ColorRange> mBlacklistedColors;
485
486 public ConfigParser(Context context) {
487 mTonalPalettes = new ArrayList<>();
488 mBlacklistedColors = new ArrayList<>();
489
490 // Load all palettes and the blacklist from an XML.
491 try {
492 XmlPullParser parser = context.getResources().getXml(R.xml.color_extraction);
493 int eventType = parser.getEventType();
494 while (eventType != XmlPullParser.END_DOCUMENT) {
495 if (eventType == XmlPullParser.START_DOCUMENT ||
496 eventType == XmlPullParser.END_TAG) {
497 // just skip
498 } else if (eventType == XmlPullParser.START_TAG) {
499 String tagName = parser.getName();
500 if (tagName.equals("palettes")) {
501 parsePalettes(parser);
502 } else if (tagName.equals("blacklist")) {
503 parseBlacklist(parser);
504 }
505 } else {
506 throw new XmlPullParserException("Invalid XML event " + eventType + " - "
507 + parser.getName(), parser, null);
508 }
509 eventType = parser.next();
510 }
511 } catch (XmlPullParserException | IOException e) {
512 throw new RuntimeException(e);
513 }
514 }
515
516 public ArrayList<TonalPalette> getTonalPalettes() {
517 return mTonalPalettes;
518 }
519
520 public ArrayList<ColorRange> getBlacklistedColors() {
521 return mBlacklistedColors;
522 }
523
524 private void parseBlacklist(XmlPullParser parser)
525 throws XmlPullParserException, IOException {
526 parser.require(XmlPullParser.START_TAG, null, "blacklist");
527 while (parser.next() != XmlPullParser.END_TAG) {
528 if (parser.getEventType() != XmlPullParser.START_TAG) {
529 continue;
530 }
531 String name = parser.getName();
532 // Starts by looking for the entry tag
533 if (name.equals("range")) {
534 mBlacklistedColors.add(readRange(parser));
535 parser.next();
536 } else {
537 throw new XmlPullParserException("Invalid tag: " + name, parser, null);
538 }
539 }
540 }
541
542 private ColorRange readRange(XmlPullParser parser)
543 throws XmlPullParserException, IOException {
544 parser.require(XmlPullParser.START_TAG, null, "range");
545 float[] h = readFloatArray(parser.getAttributeValue(null, "h"));
546 float[] s = readFloatArray(parser.getAttributeValue(null, "s"));
547 float[] l = readFloatArray(parser.getAttributeValue(null, "l"));
548
549 if (h == null || s == null || l == null) {
550 throw new XmlPullParserException("Incomplete range tag.", parser, null);
551 }
552
553 return new ColorRange(new Range<>(h[0], h[1]), new Range<>(s[0], s[1]),
554 new Range<>(l[0], l[1]));
555 }
556
557 private void parsePalettes(XmlPullParser parser)
558 throws XmlPullParserException, IOException {
559 parser.require(XmlPullParser.START_TAG, null, "palettes");
560 while (parser.next() != XmlPullParser.END_TAG) {
561 if (parser.getEventType() != XmlPullParser.START_TAG) {
562 continue;
563 }
564 String name = parser.getName();
565 // Starts by looking for the entry tag
566 if (name.equals("palette")) {
567 mTonalPalettes.add(readPalette(parser));
568 parser.next();
569 } else {
570 throw new XmlPullParserException("Invalid tag: " + name);
571 }
572 }
573 }
574
575 private TonalPalette readPalette(XmlPullParser parser)
576 throws XmlPullParserException, IOException {
577 parser.require(XmlPullParser.START_TAG, null, "palette");
578
579 float[] h = readFloatArray(parser.getAttributeValue(null, "h"));
580 float[] s = readFloatArray(parser.getAttributeValue(null, "s"));
581 float[] l = readFloatArray(parser.getAttributeValue(null, "l"));
582
583 if (h == null || s == null || l == null) {
584 throw new XmlPullParserException("Incomplete range tag.", parser, null);
585 }
586
587 return new TonalPalette(h, s, l);
588 }
589
590 private float[] readFloatArray(String attributeValue)
591 throws IOException, XmlPullParserException {
592 String[] tokens = attributeValue.replaceAll(" ", "").replaceAll("\n", "").split(",");
593 float[] numbers = new float[tokens.length];
594 for (int i = 0; i < tokens.length; i++) {
595 numbers[i] = Float.parseFloat(tokens[i]);
596 }
597 return numbers;
598 }
599 }
600}