Line data Source code
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/. */
6 :
7 : #include "mozilla/StyleComplexColor.h"
8 :
9 : #include "mozilla/ComputedStyle.h"
10 : #include "mozilla/ComputedStyleInlines.h"
11 : #include "nsIFrame.h"
12 : #include "nsStyleStruct.h"
13 :
14 : using namespace mozilla;
15 :
16 : // Blend one RGBA color with another based on a given ratios.
17 : // It is a linear combination of each channel with alpha premultipled.
18 : static nscolor
19 0 : LinearBlendColors(nscolor aBg, float aBgRatio, nscolor aFg, float aFgRatio)
20 : {
21 0 : constexpr float kFactor = 1.0f / 255.0f;
22 :
23 0 : float p1 = aBgRatio;
24 0 : float a1 = kFactor * NS_GET_A(aBg);
25 0 : float r1 = a1 * NS_GET_R(aBg);
26 0 : float g1 = a1 * NS_GET_G(aBg);
27 0 : float b1 = a1 * NS_GET_B(aBg);
28 :
29 0 : float p2 = aFgRatio;
30 0 : float a2 = kFactor * NS_GET_A(aFg);
31 0 : float r2 = a2 * NS_GET_R(aFg);
32 0 : float g2 = a2 * NS_GET_G(aFg);
33 0 : float b2 = a2 * NS_GET_B(aFg);
34 :
35 0 : float a = p1 * a1 + p2 * a2;
36 0 : if (a <= 0.f) {
37 : return NS_RGBA(0, 0, 0, 0);
38 : }
39 :
40 0 : if (a > 1.f) {
41 0 : a = 1.f;
42 : }
43 :
44 0 : auto r = ClampColor((p1 * r1 + p2 * r2) / a);
45 0 : auto g = ClampColor((p1 * g1 + p2 * g2) / a);
46 0 : auto b = ClampColor((p1 * b1 + p2 * b2) / a);
47 0 : return NS_RGBA(r, g, b, NSToIntRound(a * 255));
48 : }
49 :
50 : bool
51 0 : StyleComplexColor::MaybeTransparent() const {
52 : // We know that the color is opaque when it's a numeric color with
53 : // alpha == 255.
54 : // TODO(djg): Should we extend this to check Complex with bgRatio =
55 : // 0, and fgRatio * alpha >= 255?
56 0 : return mTag != eNumeric || NS_GET_A(mColor) != 255;
57 : }
58 :
59 : nscolor
60 799 : StyleComplexColor::CalcColor(mozilla::ComputedStyle* aStyle) const {
61 : // Common case that is numeric color, which is pure background, we
62 : // can skip resolving StyleColor().
63 0 : if (mTag == eNumeric) {
64 0 : return mColor;
65 : }
66 :
67 31 : MOZ_ASSERT(aStyle);
68 0 : auto fgColor = aStyle->StyleColor()->mColor;
69 :
70 0 : if (mTag == eComplex) {
71 0 : return LinearBlendColors(mColor, mBgRatio, fgColor, mFgRatio);
72 : }
73 :
74 : // eForeground and eAuto return the currentcolor.
75 : return fgColor;
76 : }
77 :
78 : nscolor
79 : StyleComplexColor::CalcColor(const nsIFrame* aFrame) const {
80 : return CalcColor(aFrame->Style());
81 : }
|