1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
10 #include <stdint.h> // for uint8_t, uint32_t
11 #include "nsCoord.h" // for NSToIntRound
12 #include "nsStringFwd.h"
14 // A color is a 32 bit unsigned integer with four components: R, G, B
16 typedef uint32_t nscolor
;
18 // Make a color out of r,g,b values. This assumes that the r,g,b values are
19 // properly constrained to 0-255. This also assumes that a is 255.
20 #define NS_RGB(_r, _g, _b) \
21 ((nscolor)((255 << 24) | ((_b) << 16) | ((_g) << 8) | (_r)))
23 // Make a color out of r,g,b,a values. This assumes that the r,g,b,a
24 // values are properly constrained to 0-255.
25 #define NS_RGBA(_r, _g, _b, _a) \
26 ((nscolor)(((_a) << 24) | ((_b) << 16) | ((_g) << 8) | (_r)))
28 // Extract color components from nscolor
29 #define NS_GET_R(_rgba) ((uint8_t)((_rgba) & 0xff))
30 #define NS_GET_G(_rgba) ((uint8_t)(((_rgba) >> 8) & 0xff))
31 #define NS_GET_B(_rgba) ((uint8_t)(((_rgba) >> 16) & 0xff))
32 #define NS_GET_A(_rgba) ((uint8_t)(((_rgba) >> 24) & 0xff))
37 inline uint8_t ClampColor(T aColor
) {
44 return NSToIntRound(aColor
);
47 } // namespace mozilla
49 enum class nsHexColorType
: uint8_t {
50 NoAlpha
, // 3 or 6 digit hex colors only
51 AllowAlpha
, // 3, 4, 6, or 8 digit hex colors
54 // Translate a hex string to a color. Return true if it parses ok,
55 // otherwise return false.
56 // This accepts the number of digits specified by aType.
57 bool NS_HexToRGBA(const nsAString
& aBuf
, nsHexColorType aType
,
60 // Compose one NS_RGB color onto another. The result is what
61 // you get if you draw aFG on top of aBG with operator OVER.
62 nscolor
NS_ComposeColors(nscolor aBG
, nscolor aFG
);
66 inline uint32_t RoundingDivideBy255(uint32_t n
) {
67 // There is an approximate alternative: ((n << 8) + n + 32896) >> 16
68 // But that is actually slower than this simple expression on a modern
69 // machine with a modern compiler.
70 return (n
+ 127) / 255;
73 } // namespace mozilla
75 // Translate a hex string to a color. Return true if it parses ok,
76 // otherwise return false.
77 // This version accepts 1 to 9 digits (missing digits are 0)
78 bool NS_LooseHexToRGB(const nsString
& aBuf
, nscolor
* aResult
);
80 // There is no function to translate a color to a hex string, because
81 // the hex-string syntax does not support transparency.
83 #endif /* nsColor_h___ */