This repository was archived by the owner on Feb 23, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 63
Expand file tree
/
Copy pathGssFunctions.java
More file actions
1697 lines (1480 loc) · 59.8 KB
/
GssFunctions.java
File metadata and controls
1697 lines (1480 loc) · 59.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.css.compiler.gssfunctions;
import static com.google.common.css.compiler.gssfunctions.ColorUtil.formatColor;
import static com.google.common.css.compiler.gssfunctions.ColorUtil.hsbToColor;
import static com.google.common.css.compiler.gssfunctions.ColorUtil.hslToColor;
import static com.google.common.css.compiler.gssfunctions.ColorUtil.testContrast;
import static com.google.common.css.compiler.gssfunctions.ColorUtil.toHsb;
import static com.google.common.css.compiler.gssfunctions.ColorUtil.toHsl;
import com.google.common.base.CharMatcher;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.common.css.SourceCodeLocation;
import com.google.common.css.compiler.ast.CssCompositeValueNode;
import com.google.common.css.compiler.ast.CssFunctionArgumentsNode;
import com.google.common.css.compiler.ast.CssFunctionNode;
import com.google.common.css.compiler.ast.CssHexColorNode;
import com.google.common.css.compiler.ast.CssLiteralNode;
import com.google.common.css.compiler.ast.CssNumericNode;
import com.google.common.css.compiler.ast.CssStringNode;
import com.google.common.css.compiler.ast.CssValueNode;
import com.google.common.css.compiler.ast.ErrorManager;
import com.google.common.css.compiler.ast.GssError;
import com.google.common.css.compiler.ast.GssFunction;
import com.google.common.css.compiler.ast.GssFunctionException;
import java.awt.Color;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import javax.annotation.Nullable;
/**
* Container for common GSS functions.
*
* @author oana@google.com (Oana Florescu)
* @author dgajda@google.com (Damian Gajda)
*/
public class GssFunctions {
/**
* @return a map from each GSS function name to the function
*/
public static Map<String, GssFunction> getFunctionMap() {
// TODO(dgajda): Add getName() to the function interface.
return ImmutableMap.<String, GssFunction>builder()
// Arithmetic functions.
.put("add", new GssFunctions.AddToNumericValue())
.put("sub", new GssFunctions.SubtractFromNumericValue())
.put("mult", new GssFunctions.Mult())
// Not named "div" so it will not be confused with the HTML element.
.put("divide", new GssFunctions.Div())
.put("minimum", new GssFunctions.MinValue())
.put("maximum", new GssFunctions.MaxValue())
// Color functions.
.put("blendColorsHsb", new BlendColorsHsb())
.put("blendColorsRgb", new BlendColorsRgb())
.put("makeMutedColor", new MakeMutedColor())
.put("addHsbToCssColor", new AddHsbToCssColor())
.put("makeContrastingColor", new MakeContrastingColor())
.put("adjustBrightness", new AdjustBrightness())
.put("makeTranslucent", new MakeTranslucent())
.put("saturateColor", new SaturateColor())
.put("desaturateColor", new DesaturateColor())
.put("greyscale", new Greyscale())
.put("lighten", new Lighten())
.put("darken", new Darken())
.put("spin", new Spin())
// Logic functions.
.put("selectFrom", new SelectFrom())
// String functions.
.put("concat", new Concat())
.build();
}
/**
* Round decimals to the eight places, which appears to be the smallest
* precision that works well across all browsers. (Yes, this is crazy.)
*/
private static final String DECIMAL_FORMAT = "#.########";
/**
* US decimal format symbols.
*/
private static final DecimalFormatSymbols US_SYMBOLS =
DecimalFormatSymbols.getInstance(Locale.US);
/**
* This class encapsulates results of background definition calculation and
* is used to build either a list of {@link CssValueNode} instances or a string that
* represents the background CSS property.
*/
static class ImageBackground {
private static final String NO_REPEAT = "no-repeat";
private final String url;
private final String positionH;
private final String positionHUnit;
private final String positionV;
private final String positionVUnit;
/**
* @param url The URL to be used as the background image URL
* @param cornerId The corner id which tells how the image is positioned
* @param imgSize The size of the image
* @param units The units of the image size
*/
public ImageBackground(
String url, String cornerId, String imgSize, String units) {
this.url = url;
boolean isZero = Float.parseFloat(imgSize) == 0;
boolean isLeft = isZero || cornerId.endsWith("l");
positionH = isLeft ? "0" : "-" + imgSize;
positionHUnit = isLeft ? CssNumericNode.NO_UNITS : units;
boolean isTop = isZero || cornerId.startsWith("t");
positionV = isTop ? "0" : "-" + imgSize;
positionVUnit = isTop ? CssNumericNode.NO_UNITS : units;
}
@Override
public String toString() {
return createUrl(url) + " " + NO_REPEAT + " " +
positionH + positionHUnit + " " + positionV + positionVUnit;
}
public List<CssValueNode> toNodes(SourceCodeLocation location) {
return ImmutableList.of(
createUrlNode(url, location),
new CssLiteralNode(NO_REPEAT, location),
new CssNumericNode(positionH, positionHUnit, location),
new CssNumericNode(positionV, positionVUnit, location));
}
}
/**
* Base implementation of the color blending GSS function. Returns a color
* half way between the two colors supplied as arguments.
*/
public abstract static class BaseBlendColors implements GssFunction {
/**
* Returns the number of expected arguments of this GSS function.
*
* @return Number of expected arguments
*/
@Override
public Integer getNumExpectedArguments() {
return 2;
}
/**
* Returns the string representation in hex format for a color half way in
* between the two supplied colors.
*
* @param args The list of arguments
* @return The computed color
*/
@Override
public List<CssValueNode> getCallResultNodes(List<CssValueNode> args,
ErrorManager errorManager) {
CssValueNode arg1 = args.get(0);
CssValueNode arg2 = args.get(1);
String startColorStr = arg1.getValue();
String endColorStr = arg2.getValue();
String resultString = blend(startColorStr, endColorStr);
CssHexColorNode result = new CssHexColorNode(resultString,
arg1.getSourceCodeLocation());
return ImmutableList.of((CssValueNode) result);
}
@Override
public String getCallResultString(List<String> args)
throws GssFunctionException {
try {
return blend(args.get(0), args.get(1));
} catch (IllegalArgumentException e) {
throw new GssFunctionException("Colors could not be parsed", e);
}
}
// TODO(dgajda): Hide it, this function is only visible because
public abstract String blend(String startColor, String endColor);
}
/**
* Implementation of the blendColorsHsb GSS function. Returns a color half way
* between the two colors supplied as arguments.
*/
public static class BlendColorsHsb extends BaseBlendColors {
@Override
// TODO(dgajda): Hide it, this function is only visible because
public String blend(String startColorStr, String endColorStr) {
Color midColor = blendHsb(
ColorParser.parseAny(startColorStr),
ColorParser.parseAny(endColorStr));
return formatColor(midColor);
}
}
private static Color blendHsb(Color startColor, Color endColor) {
float[] startColorHsb = toHsb(startColor);
float[] endColorHsb = toHsb(endColor);
float diffHue = Math.abs(startColorHsb[0] - endColorHsb[0]);
float sumHue = startColorHsb[0] + endColorHsb[0];
float midHue = (diffHue <= 0.5)
? sumHue / 2
: (sumHue + 1) / 2; // Hue values range 0 to 1 and wrap (i.e. 0 == 1)
if (midHue > 1) {
midHue -= 1;
}
return Color.getHSBColor(
midHue,
(startColorHsb[1] + endColorHsb[1]) / 2,
(startColorHsb[2] + endColorHsb[2]) / 2);
}
/**
* Implementation of the blendColorsRgb GSS function. Returns a color half way
* between the two colors by averaging each of red, green & blue.
*/
public static class BlendColorsRgb extends BaseBlendColors {
/**
* Returns the string representation in hex format for a color half way in
* between the two supplied colors by averaging each of red, green & blue.
*
* @param startColorStr The start color in string form
* @param endColorStr The endcolor in string form
* @return The computed color
*/
@Override
// TODO(dgajda): Hide it, this function is only visible because
public String blend(String startColorStr, String endColorStr) {
Color startColor = ColorParser.parseAny(startColorStr);
Color endColor = ColorParser.parseAny(endColorStr);
Color midColor = new Color(
(startColor.getRed() + endColor.getRed()) / 2,
(startColor.getGreen() + endColor.getGreen()) / 2,
(startColor.getBlue() + endColor.getBlue()) / 2);
return formatColor(midColor);
}
}
/**
* Helper method to convert a numeric value of "0" or "1" into a boolean.
*
* @param numericPart The string containing the value
* @return The corresponding boolean value
*/
public static boolean parseBoolean(String numericPart) {
return Integer.parseInt(numericPart) == 1;
}
/**
* Helper method for implementors of GssFunction to allow the creation of
* a url entry node in a GSS file.
*
* @param imageUrl The url of the image to add.
* @param location The location in the GSS file to place the node.
* @return The node containing the url entry.
*/
public static CssFunctionNode createUrlNode(
String imageUrl, SourceCodeLocation location) {
CssFunctionNode url =
new CssFunctionNode(CssFunctionNode.Function.byName("url"), location);
if (!imageUrl.equals("")) {
CssLiteralNode argument = new CssLiteralNode(imageUrl, location);
List<CssValueNode> argList = ImmutableList.of((CssValueNode) argument);
CssFunctionArgumentsNode arguments =
new CssFunctionArgumentsNode(argList);
url.setArguments(arguments);
}
return url;
}
/**
* Implementation of the addHsbToCssColor GSS function.
*/
public static class AddHsbToCssColor implements GssFunction {
@Override
public Integer getNumExpectedArguments() {
return 4;
}
@Override
public List<CssValueNode> getCallResultNodes(List<CssValueNode> args,
ErrorManager errorManager) throws GssFunctionException {
CssValueNode arg1 = args.get(0);
CssValueNode arg2 = args.get(1);
CssValueNode arg3 = args.get(2);
CssValueNode arg4 = args.get(3);
assertArgumentLooksLikeAColor(1, arg1, errorManager);
CssNumericNode numeric2, numeric3, numeric4;
if (arg2 instanceof CssNumericNode && arg3 instanceof CssNumericNode
&& arg4 instanceof CssNumericNode) {
numeric2 = (CssNumericNode)arg2;
numeric3 = (CssNumericNode)arg3;
numeric4 = (CssNumericNode)arg4;
} else {
String message = "Arguments number 2, 3 and 4 must be CssNumericNodes";
errorManager.report(
new GssError(message, arg2.getSourceCodeLocation()));
throw new GssFunctionException(message);
}
try {
String resultString =
addHsbToCssColor(args.get(0).getValue(),
numeric2.getNumericPart(),
numeric3.getNumericPart(),
numeric4.getNumericPart());
CssHexColorNode result = new CssHexColorNode(resultString,
arg1.getSourceCodeLocation());
return ImmutableList.of((CssValueNode)result);
} catch (GssFunctionException e) {
errorManager.report(
new GssError(e.getMessage(), arg2.getSourceCodeLocation()));
throw e;
}
}
@Override
public String getCallResultString(List<String> args)
throws GssFunctionException {
String baseColorString = args.get(0);
return addHsbToCssColor(
baseColorString, args.get(1), args.get(2), args.get(3));
}
protected String addHsbToCssColor(
String baseColorString, String hueToAdd, String saturationToAdd,
String brightnessToAdd) throws GssFunctionException {
try {
return addHsbToCssColor(
baseColorString,
Integer.parseInt(hueToAdd),
Integer.parseInt(saturationToAdd),
Integer.parseInt(brightnessToAdd));
} catch (IllegalArgumentException e) {
String message = String.format("Could not parse the "
+ (e instanceof NumberFormatException ? "integer arguments" : "color argument")
+ " for the function 'addHsbToCssColor'. The list of arguments was:"
+ " %s, %s, %s, %s. ",
baseColorString, hueToAdd, saturationToAdd, brightnessToAdd);
throw new GssFunctionException(message);
}
}
/**
* Takes a CSS color string, and adds the specified amount of hue,
* saturation and brightness to it.
*
* @param baseColorString The string representing the color to change
* @param hueToAdd The amount of hue to add (can be negative)
* @param saturationToAdd The amount of saturation to add (can be negative)
* @param brightnessToAdd The amount of brightness to add (can be negative)
* @return A CSS String representing the new color
*/
public String addHsbToCssColor(String baseColorString,
int hueToAdd,
int saturationToAdd,
int brightnessToAdd) {
// Skip transformation for the transparent color.
if ("transparent".equals(baseColorString)) {
return baseColorString;
}
Color baseColor = ColorParser.parseAny(baseColorString);
Color newColor = addValuesToHsbComponents(baseColor,
hueToAdd,
saturationToAdd,
brightnessToAdd);
return formatColor(newColor);
}
/**
* Adds the specified amount to the specified HSB (Hue, Saturation,
* Brightness) parameter of the given color. The amount can be negative.
*
* @param baseColor The color to modify
* @param hueToAdd The amount of hue to add
* @param saturationToAdd The amount of saturation to add
* @param brightnessToAdd The amount of brightness to add
* @return The modified color
*/
public Color addValuesToHsbComponents(Color baseColor,
int hueToAdd,
int saturationToAdd,
int brightnessToAdd) {
float[] hsbValues = toHsb(baseColor);
// In HSB color space, Hue goes from 0 to 360, Saturation and Brightness
// from 0 to 100. However, in Java all three parameters vary from 0.0 to
// 1.0, so we need some basic conversion.
hsbValues[0] = (float) (hsbValues[0] + hueToAdd / 360.0);
// The hue needs to wrap around, so just keep hue - floor(hue).
hsbValues[0] -= (float) Math.floor(hsbValues[0]);
// For saturation and brightness, no wrapping around, we just make sure
// we don't go over 1.0 or under 0.0
hsbValues[1] = (float) Math.min(1.0, Math.max(0,
hsbValues[1] + saturationToAdd / 100.0));
hsbValues[2] = (float) Math.min(1.0, Math.max(0,
hsbValues[2] + brightnessToAdd / 100.0));
return Color.getHSBColor(hsbValues[0], hsbValues[1], hsbValues[2]);
}
}
/** Verify a function argument looks like a color node. */
public static void assertArgumentLooksLikeAColor(
int argOrdinal, CssValueNode argValue, ErrorManager errorManager)
throws GssFunctionException {
if (!(argValue instanceof CssHexColorNode
|| argValue instanceof CssLiteralNode
|| argValue instanceof CssFunctionNode)) {
String message =
String.format(
"Argument %d must be a CssHexColorNode. a CssLiteralNode, or a "
+ "CssFunctionNode, was %s",
argOrdinal, argValue.getClass().getSimpleName());
errorManager.report(new GssError(message, argValue.getSourceCodeLocation()));
throw new GssFunctionException(message);
}
if (argValue instanceof CssFunctionNode) {
CssFunctionNode functionNode = (CssFunctionNode) argValue;
if (!functionNode.getFunctionName().equals("rgb")
&& !functionNode.getFunctionName().equals("rgba")) {
String message =
String.format(
"Could not interpret argument %d as a color. Function must be 'rgb' or"
+ " 'rgba', was %s",
argOrdinal, functionNode.getFunctionName());
errorManager.report(new GssError(message, argValue.getSourceCodeLocation()));
throw new GssFunctionException(message);
}
}
}
/**
* Abstract base class providing HSL color space manipulation functions.
*/
public abstract static class BaseHslColorManipulation {
protected String addHslToCssColor(
String baseColorString, String hueToAdd, String saturationToAdd,
String lightnessToAdd) throws GssFunctionException {
try {
return addHslToCssColor(
baseColorString,
Integer.parseInt(hueToAdd),
Integer.parseInt(saturationToAdd),
Integer.parseInt(lightnessToAdd));
} catch (IllegalArgumentException e) {
String message = String.format("Could not parse the "
+ (e instanceof NumberFormatException ? "integer arguments" : "color argument")
+ " for the function 'addHslToCssColor'. The list of arguments was:"
+ " %s, %s, %s, %s. ",
baseColorString, hueToAdd, saturationToAdd, lightnessToAdd);
throw new GssFunctionException(message);
}
}
/**
* Takes a CSS color string, and adds the specified amount of hue,
* saturation and lightness to it in HSL color space
*
* @param baseColorString The string representing the color to change
* @param hueToAdd The amount of hue to add (can be negative)
* @param saturationToAdd The amount of saturation to add (can be negative)
* @param lightnessToAdd The amount of lightness to add (can be negative)
* @return A CSS String representing the new color
*/
protected String addHslToCssColor(String baseColorString,
int hueToAdd,
int saturationToAdd,
int lightnessToAdd) {
// Skip transformation for the transparent color.
if ("transparent".equals(baseColorString)) {
return baseColorString;
}
Color baseColor = ColorParser.parseAny(baseColorString);
Color newColor = addValuesToHslComponents(baseColor,
hueToAdd,
saturationToAdd,
lightnessToAdd);
return formatColor(newColor);
}
/**
* Adds the specified amount to the specified HSL (Hue, Saturation,
* Lightness) parameter of the given color. The amount can be negative.
*
* @param baseColor The color to modify
* @param hueToAdd The amount of hue to add
* @param saturationToAdd The amount of saturation to add
* @param lightnessToAdd The amount of lightness to add
* @return The modified color
*/
private Color addValuesToHslComponents(Color baseColor,
int hueToAdd,
int saturationToAdd,
int lightnessToAdd) {
float[] hslValues = toHsl(baseColor);
// In HSL color space, Hue goes from 0 to 360, Saturation and Lightness
// from 0 to 100. However, in Java all three parameters vary from 0.0 to
// 1.0, so we need some basic conversion.
hslValues[0] = (float) (hslValues[0] + hueToAdd / 360.0);
// The hue needs to wrap around, so just keep hue - floor(hue).
hslValues[0] -= (float) Math.floor(hslValues[0]);
// For saturation and lightness, no wrapping around, we just make sure
// we don't go over 1.0 or under 0.0
hslValues[1] = (float) Math.min(1.0, Math.max(0,
hslValues[1] + saturationToAdd / 100.0));
hslValues[2] = (float) Math.min(1.0, Math.max(0,
hslValues[2] + lightnessToAdd / 100.0));
return hslToColor(hslValues);
}
}
/**
* Increase the saturation of the specified color. First argument is the
* color, second is the absolute amount of saturation in HSL color space
* to add (from 0 to 100).
*/
public static class SaturateColor extends BaseHslColorManipulation implements GssFunction {
@Override
public Integer getNumExpectedArguments() {
return 2;
}
@Override
public List<CssValueNode> getCallResultNodes(List<CssValueNode> args,
ErrorManager errorManager) throws GssFunctionException {
CssValueNode arg1 = args.get(0);
CssValueNode arg2 = args.get(1);
assertArgumentLooksLikeAColor(1, arg1, errorManager);
CssNumericNode numeric2;
if (arg2 instanceof CssNumericNode) {
numeric2 = (CssNumericNode) arg2;
} else {
String message = "The second argument must be a CssNumericNode";
errorManager.report(
new GssError(message, arg2.getSourceCodeLocation()));
throw new GssFunctionException(message);
}
try {
String resultString =
addHslToCssColor(arg1.getValue(),
"0",
numeric2.getNumericPart(),
"0");
CssHexColorNode result = new CssHexColorNode(resultString,
arg1.getSourceCodeLocation());
return ImmutableList.of((CssValueNode) result);
} catch (GssFunctionException e) {
errorManager.report(
new GssError(e.getMessage(), arg2.getSourceCodeLocation()));
throw e;
}
}
@Override
public String getCallResultString(List<String> args)
throws GssFunctionException {
String baseColorString = args.get(0);
return addHslToCssColor(
baseColorString, "0", args.get(1), "0");
}
}
/**
* Decrease the saturation of the specified color. First argument is the
* color, second is the absolute amount of saturation in HSL color space
* to substract (from 0 to 100).
*/
public static class DesaturateColor extends BaseHslColorManipulation implements GssFunction {
@Override
public Integer getNumExpectedArguments() {
return 2;
}
@Override
public List<CssValueNode> getCallResultNodes(List<CssValueNode> args,
ErrorManager errorManager) throws GssFunctionException {
CssValueNode arg1 = args.get(0);
CssValueNode arg2 = args.get(1);
assertArgumentLooksLikeAColor(1, arg1, errorManager);
CssNumericNode numeric2;
if (arg2 instanceof CssNumericNode) {
numeric2 = (CssNumericNode) arg2;
} else {
String message = "The second argument must be a CssNumericNode";
errorManager.report(new GssError(message, arg2
.getSourceCodeLocation()));
throw new GssFunctionException(message);
}
try {
String resultString = addHslToCssColor(arg1.getValue(), "0",
"-" + numeric2.getNumericPart(), "0");
CssHexColorNode result = new CssHexColorNode(resultString,
arg1.getSourceCodeLocation());
return ImmutableList.of((CssValueNode) result);
} catch (GssFunctionException e) {
errorManager.report(new GssError(e.getMessage(), arg2
.getSourceCodeLocation()));
throw e;
}
}
@Override
public String getCallResultString(List<String> args)
throws GssFunctionException {
String baseColorString = args.get(0);
return addHslToCssColor(baseColorString, "0", "-"
+ args.get(1), "0");
}
}
/**
* Convert the color to a grayscale (desaturation with amount of 100).
*/
public static class Greyscale extends BaseHslColorManipulation implements GssFunction {
@Override
public Integer getNumExpectedArguments() {
return 1;
}
@Override
public List<CssValueNode> getCallResultNodes(List<CssValueNode> args,
ErrorManager errorManager) throws GssFunctionException {
CssValueNode arg1 = args.get(0);
if (!(arg1 instanceof CssHexColorNode
|| arg1 instanceof CssLiteralNode)) {
String message =
"The argument must be a CssHexColorNode or a CssLiteralNode.";
errorManager.report(
new GssError(message, arg1.getSourceCodeLocation()));
throw new GssFunctionException(message);
}
try {
String resultString =
addHslToCssColor(arg1.getValue(),
"0",
"-100",
"0");
CssHexColorNode result = new CssHexColorNode(resultString,
arg1.getSourceCodeLocation());
return ImmutableList.of((CssValueNode) result);
} catch (GssFunctionException e) {
errorManager.report(
new GssError(e.getMessage(), arg1.getSourceCodeLocation()));
throw e;
}
}
@Override
public String getCallResultString(List<String> args)
throws GssFunctionException {
String baseColorString = args.get(0);
return addHslToCssColor(
baseColorString, "0", "-100", "0");
}
}
/**
* Increase the lightness of a color. First argument is the color, second
* is the lighten to add, between 0 and 100.
*/
public static class Lighten extends BaseHslColorManipulation implements GssFunction {
@Override
public Integer getNumExpectedArguments() {
return 2;
}
@Override
public List<CssValueNode> getCallResultNodes(List<CssValueNode> args,
ErrorManager errorManager) throws GssFunctionException {
CssValueNode arg1 = args.get(0);
CssValueNode arg2 = args.get(1);
assertArgumentLooksLikeAColor(1, arg1, errorManager);
CssNumericNode numeric2;
if (arg2 instanceof CssNumericNode) {
numeric2 = (CssNumericNode) arg2;
} else {
String message = "The second argument must be a CssNumericNode";
errorManager.report(
new GssError(message, arg2.getSourceCodeLocation()));
throw new GssFunctionException(message);
}
try {
String resultString =
addHslToCssColor(arg1.getValue(),
"0",
"0",
numeric2.getNumericPart());
CssHexColorNode result = new CssHexColorNode(resultString,
arg1.getSourceCodeLocation());
return ImmutableList.of((CssValueNode) result);
} catch (GssFunctionException e) {
errorManager.report(
new GssError(e.getMessage(), arg2.getSourceCodeLocation()));
throw e;
}
}
@Override
public String getCallResultString(List<String> args)
throws GssFunctionException {
String baseColorString = args.get(0);
return addHslToCssColor(
baseColorString, "0", "0", args.get(1));
}
}
/**
* Decrease the lightness of a color. First argument is the color, second
* is the lighten to remove, between 0 and 100.
*/
public static class Darken extends BaseHslColorManipulation implements GssFunction {
@Override
public Integer getNumExpectedArguments() {
return 2;
}
@Override
public List<CssValueNode> getCallResultNodes(List<CssValueNode> args,
ErrorManager errorManager) throws GssFunctionException {
CssValueNode arg1 = args.get(0);
CssValueNode arg2 = args.get(1);
assertArgumentLooksLikeAColor(1, arg1, errorManager);
CssNumericNode numeric2;
if (arg2 instanceof CssNumericNode) {
numeric2 = (CssNumericNode) arg2;
} else {
String message = "The second argument must be a CssNumericNode";
errorManager.report(
new GssError(message, arg2.getSourceCodeLocation()));
throw new GssFunctionException(message);
}
try {
String resultString =
addHslToCssColor(arg1.getValue(),
"0",
"0",
"-" + numeric2.getNumericPart());
CssHexColorNode result = new CssHexColorNode(resultString,
arg1.getSourceCodeLocation());
return ImmutableList.of((CssValueNode) result);
} catch (GssFunctionException e) {
errorManager.report(
new GssError(e.getMessage(), arg2.getSourceCodeLocation()));
throw e;
}
}
@Override
public String getCallResultString(List<String> args)
throws GssFunctionException {
String baseColorString = args.get(0);
return addHslToCssColor(
baseColorString, "0", "0", "-" + args.get(1));
}
}
/**
* Increase or decrease the hue of a color. First argument is the color, second
* is the hue to add or remove, between 0 and 360.
* It's like rotating the color on a color wheel and hue is the angle to apply.
*/
public static class Spin extends BaseHslColorManipulation implements GssFunction {
@Override
public Integer getNumExpectedArguments() {
return 2;
}
@Override
public List<CssValueNode> getCallResultNodes(List<CssValueNode> args,
ErrorManager errorManager) throws GssFunctionException {
CssValueNode arg1 = args.get(0);
CssValueNode arg2 = args.get(1);
assertArgumentLooksLikeAColor(1, arg1, errorManager);
CssNumericNode numeric2;
if (arg2 instanceof CssNumericNode) {
numeric2 = (CssNumericNode) arg2;
} else {
String message = "The second argument must be a CssNumericNode";
errorManager.report(
new GssError(message, arg2.getSourceCodeLocation()));
throw new GssFunctionException(message);
}
try {
String resultString =
addHslToCssColor(arg1.getValue(),
numeric2.getNumericPart(),
"0",
"0");
CssHexColorNode result = new CssHexColorNode(resultString,
arg1.getSourceCodeLocation());
return ImmutableList.of((CssValueNode) result);
} catch (GssFunctionException e) {
errorManager.report(
new GssError(e.getMessage(), arg2.getSourceCodeLocation()));
throw e;
}
}
@Override
public String getCallResultString(List<String> args)
throws GssFunctionException {
String baseColorString = args.get(0);
return addHslToCssColor(
baseColorString, args.get(1), "0", "0");
}
}
/**
* Implementation of the makeMutedColor GSS function. This is intended to
* generate a muted flavor of a text or link color. Takes three arguments: the
* background color over which this text or link will appear, and the text or
* link color this should be a muted version of and optionally the loss of
* saturation for muted tone (0 <= loss <= 1).
*/
public static class MakeMutedColor implements GssFunction {
private final float LOSS_OF_SATURATION_FOR_MUTED_TONE = 0.2f;
private final String ARGUMENT_COUNT_ERROR_MESSAGE = "makeMutedColor " +
"expected arguments: backgroundColorStr, foregroundColorStr and an " +
"optional loss of saturation value (0 <= loss <= 1).";
/**
* Returns the number of expected arguments of this GSS function.
*
* @return Number of expected arguments
*/
@Override
public Integer getNumExpectedArguments() {
return null;
}
/**
* Returns the muted color corresponding to the arguments
* documented in {@link MakeMutedColor}.
*
* @param args The list of arguments.
* @return The generated muted color.
*/
@Override
public List<CssValueNode> getCallResultNodes(List<CssValueNode> args,
ErrorManager errorManager) throws GssFunctionException {
if (args.size() != 2 && args.size() != 3) {
throw new GssFunctionException(ARGUMENT_COUNT_ERROR_MESSAGE);
}
CssValueNode backgroundColorNode = args.get(0);
CssValueNode foregroundColorNode = args.get(1);
String lossOfSaturationForMutedTone =
String.valueOf(LOSS_OF_SATURATION_FOR_MUTED_TONE);
if (args.size() == 3) {
lossOfSaturationForMutedTone = args.get(2).getValue();
}
String backgroundColorStr = backgroundColorNode.getValue();
String foregroundColorStr = foregroundColorNode.getValue();
String resultStr = makeMutedColor(backgroundColorStr, foregroundColorStr,
lossOfSaturationForMutedTone);
CssHexColorNode result = new CssHexColorNode(resultStr,
backgroundColorNode.getSourceCodeLocation());
return ImmutableList.of((CssValueNode) result);
}
protected String makeMutedColor(
String backgroundColorStr, String foregroundColorStr, String lossStr) {
// If the background is transparent, or if the foreground is transparent,
// there's really no way we can know how to pick a muted color. We thus
// return the foreground color unchanged.
if ("transparent".equalsIgnoreCase(backgroundColorStr)
|| "transparent".equalsIgnoreCase(foregroundColorStr)) {
return foregroundColorStr;
}
Color backgroundColor = ColorParser.parseAny(backgroundColorStr);
Color foregroundColor = ColorParser.parseAny(foregroundColorStr);
float[] backgroundColorHsb = toHsb(backgroundColor);
float[] foregroundColorHsb = toHsb(foregroundColor);
float lossOfSaturationForMutedTone = Float.valueOf(lossStr);
// Make sure that 0 <= lossOfSaturationForMutedTone <= 1
if (lossOfSaturationForMutedTone < 0) {
lossOfSaturationForMutedTone = 0;
} else if (lossOfSaturationForMutedTone > 1) {
lossOfSaturationForMutedTone = 1;
}
// We take the hue from the foreground color, we desaturate it a little
// bit, and choose a brightness halfway between foreground and background.
// For example, if the background has a brightness of 50, and 100 for the
// foreground, the muted color will have 75. If we have a dark background,
// it should be the reverse.
float mutedHue = foregroundColorHsb[0];
float mutedSaturation = Math.max(
foregroundColorHsb[1] - lossOfSaturationForMutedTone, 0);
float mutedBrightness = (foregroundColorHsb[2] + backgroundColorHsb[2]) /
2;
Color mutedColor
= Color.getHSBColor(mutedHue, mutedSaturation, mutedBrightness);
return formatColor(mutedColor);
}
protected String makeMutedColor(
String backgroundColorStr, String foregroundColorStr) {
return makeMutedColor(backgroundColorStr, foregroundColorStr,
String.valueOf(LOSS_OF_SATURATION_FOR_MUTED_TONE));
}
@Override
public String getCallResultString(List<String> args) throws
GssFunctionException {
if (args.size() == 2) {
return makeMutedColor(args.get(0), args.get(1));
} else if (args.size() == 3) {