summaryrefslogtreecommitdiffstats
path: root/toolkit/modules/LightweightThemeConsumer.sys.mjs
blob: 4e825b14e592ac7cbeed82f1b7833e3e1a62f17d (plain)
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
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

import { XPCOMUtils } from "resource://gre/modules/XPCOMUtils.sys.mjs";

import { AppConstants } from "resource://gre/modules/AppConstants.sys.mjs";

const lazy = {};
// Get the theme variables from the app resource directory.
// This allows per-app variables.
ChromeUtils.defineESModuleGetters(lazy, {
  NimbusFeatures: "resource://nimbus/ExperimentAPI.sys.mjs",
  PrivateBrowsingUtils: "resource://gre/modules/PrivateBrowsingUtils.sys.mjs",
  ThemeContentPropertyList: "resource:///modules/ThemeVariableMap.sys.mjs",
  ThemeVariableMap: "resource:///modules/ThemeVariableMap.sys.mjs",
});

// Whether the content and chrome areas should always use the same color
// scheme (unless user-overridden). Thunderbird uses this.
XPCOMUtils.defineLazyPreferenceGetter(
  lazy,
  "BROWSER_THEME_UNIFIED_COLOR_SCHEME",
  "browser.theme.unified-color-scheme",
  false
);

const DEFAULT_THEME_ID = "default-theme@mozilla.org";

// On Linux, the default theme picks up the right colors from dark GTK themes.
const DEFAULT_THEME_RESPECTS_SYSTEM_COLOR_SCHEME =
  AppConstants.platform == "linux";

const toolkitVariableMap = [
  [
    "--lwt-accent-color",
    {
      lwtProperty: "accentcolor",
      processColor(rgbaChannels, element) {
        if (!rgbaChannels || rgbaChannels.a == 0) {
          return "white";
        }
        // Remove the alpha channel
        const { r, g, b } = rgbaChannels;
        return `rgb(${r}, ${g}, ${b})`;
      },
    },
  ],
  [
    "--lwt-text-color",
    {
      lwtProperty: "textcolor",
      processColor(rgbaChannels, element) {
        if (!rgbaChannels) {
          rgbaChannels = { r: 0, g: 0, b: 0 };
        }
        // Remove the alpha channel
        const { r, g, b } = rgbaChannels;
        return `rgba(${r}, ${g}, ${b})`;
      },
    },
  ],
  [
    "--arrowpanel-background",
    {
      lwtProperty: "popup",
    },
  ],
  [
    "--arrowpanel-color",
    {
      lwtProperty: "popup_text",
    },
  ],
  [
    "--arrowpanel-border-color",
    {
      lwtProperty: "popup_border",
    },
  ],
  [
    "--toolbar-field-background-color",
    {
      lwtProperty: "toolbar_field",
    },
  ],
  [
    "--toolbar-field-color",
    {
      lwtProperty: "toolbar_field_text",
    },
  ],
  [
    "--toolbar-field-border-color",
    {
      lwtProperty: "toolbar_field_border",
    },
  ],
  [
    "--toolbar-field-focus-background-color",
    {
      lwtProperty: "toolbar_field_focus",
      fallbackProperty: "toolbar_field",
      processColor(rgbaChannels, element, propertyOverrides) {
        if (!rgbaChannels) {
          return null;
        }
        // Ensure minimum opacity as this is used behind address bar results.
        const min_opacity = 0.9;
        let { r, g, b, a } = rgbaChannels;
        if (a < min_opacity) {
          propertyOverrides.set(
            "toolbar_field_text_focus",
            _isColorDark(r, g, b) ? "white" : "black"
          );
          return `rgba(${r}, ${g}, ${b}, ${min_opacity})`;
        }
        return `rgba(${r}, ${g}, ${b}, ${a})`;
      },
    },
  ],
  [
    "--toolbar-field-focus-color",
    {
      lwtProperty: "toolbar_field_text_focus",
      fallbackProperty: "toolbar_field_text",
    },
  ],
  [
    "--toolbar-field-focus-border-color",
    {
      lwtProperty: "toolbar_field_border_focus",
    },
  ],
  [
    "--lwt-toolbar-field-highlight",
    {
      lwtProperty: "toolbar_field_highlight",
      processColor(rgbaChannels, element) {
        if (!rgbaChannels) {
          return null;
        }
        const { r, g, b, a } = rgbaChannels;
        return `rgba(${r}, ${g}, ${b}, ${a})`;
      },
    },
  ],
  [
    "--lwt-toolbar-field-highlight-text",
    {
      lwtProperty: "toolbar_field_highlight_text",
    },
  ],
];

export function LightweightThemeConsumer(aDocument) {
  this._doc = aDocument;
  this._win = aDocument.defaultView;
  this._winId = this._win.docShell.outerWindowID;

  Services.obs.addObserver(this, "lightweight-theme-styling-update");

  this.darkThemeMediaQuery = this._win.matchMedia("(-moz-system-dark-theme)");
  this.darkThemeMediaQuery.addListener(this);

  const { LightweightThemeManager } = ChromeUtils.importESModule(
    "resource://gre/modules/LightweightThemeManager.sys.mjs"
  );
  this._update(LightweightThemeManager.themeData);

  this._win.addEventListener("unload", this, { once: true });
}

LightweightThemeConsumer.prototype = {
  _lastData: null,

  observe(aSubject, aTopic, aData) {
    if (aTopic != "lightweight-theme-styling-update") {
      return;
    }

    let data = aSubject.wrappedJSObject;
    if (data.window && data.window !== this._winId) {
      return;
    }

    this._update(data);
  },

  handleEvent(aEvent) {
    if (aEvent.target == this.darkThemeMediaQuery) {
      this._update(this._lastData);
      return;
    }

    switch (aEvent.type) {
      case "unload":
        Services.obs.removeObserver(this, "lightweight-theme-styling-update");
        Services.ppmm.sharedData.delete(`theme/${this._winId}`);
        this._win = this._doc = null;
        if (this.darkThemeMediaQuery) {
          this.darkThemeMediaQuery.removeListener(this);
          this.darkThemeMediaQuery = null;
        }
        break;
    }
  },

  _update(themeData) {
    this._lastData = themeData;

    const hasDarkTheme = !!themeData.darkTheme;
    let updateGlobalThemeData = true;
    let useDarkTheme = (() => {
      if (!hasDarkTheme) {
        return false;
      }
      if (this.darkThemeMediaQuery?.matches) {
        return (
          themeData.darkTheme.id != DEFAULT_THEME_ID ||
          !DEFAULT_THEME_RESPECTS_SYSTEM_COLOR_SCHEME
        );
      }

      // If enabled, apply the dark theme variant to private browsing windows.
      if (
        !lazy.NimbusFeatures.majorRelease2022.getVariable(
          "feltPrivacyPBMDarkTheme"
        ) ||
        !lazy.PrivateBrowsingUtils.isWindowPrivate(this._win) ||
        lazy.PrivateBrowsingUtils.permanentPrivateBrowsing
      ) {
        return false;
      }
      // When applying the dark theme for a PBM window we need to skip calling
      // _determineToolbarAndContentTheme, because it applies the color scheme
      // globally for all windows. Skipping this method also means we don't
      // switch the content theme to dark.
      updateGlobalThemeData = false;
      return true;
    })();

    // If this is a per-window dark theme, set the color scheme override so
    // child BrowsingContexts, such as embedded prompts, get themed
    // appropriately.
    // If not, reset the color scheme override field. This is required to reset
    // the color scheme on theme switch.
    if (this._win.browsingContext == this._win.browsingContext.top) {
      if (useDarkTheme && !updateGlobalThemeData) {
        this._win.browsingContext.prefersColorSchemeOverride = "dark";
      } else {
        this._win.browsingContext.prefersColorSchemeOverride = "none";
      }
    }

    let theme = useDarkTheme ? themeData.darkTheme : themeData.theme;
    if (!theme) {
      theme = { id: DEFAULT_THEME_ID };
    }

    let active = (this._active = Object.keys(theme).length);

    let root = this._doc.documentElement;

    if (active && theme.headerURL) {
      root.setAttribute("lwtheme-image", "true");
    } else {
      root.removeAttribute("lwtheme-image");
    }

    this._setExperiment(active, themeData.experiment, theme.experimental);
    _setImage(this._win, root, active, "--lwt-header-image", theme.headerURL);
    _setImage(
      this._win,
      root,
      active,
      "--lwt-additional-images",
      theme.additionalBackgrounds
    );
    _setProperties(root, active, theme);

    if (theme.id != DEFAULT_THEME_ID || useDarkTheme) {
      if (updateGlobalThemeData) {
        _determineToolbarAndContentTheme(
          this._doc,
          theme,
          hasDarkTheme,
          useDarkTheme
        );
      }
      root.setAttribute("lwtheme", "true");
    } else {
      _determineToolbarAndContentTheme(this._doc, null);
      root.removeAttribute("lwtheme");
    }
    if (theme.id == DEFAULT_THEME_ID && useDarkTheme) {
      root.setAttribute("lwt-default-theme-in-dark-mode", "true");
    } else {
      root.removeAttribute("lwt-default-theme-in-dark-mode");
    }

    _setDarkModeAttributes(this._doc, root, theme._processedColors);

    let contentThemeData = _getContentProperties(this._doc, active, theme);
    Services.ppmm.sharedData.set(`theme/${this._winId}`, contentThemeData);
    // We flush sharedData because contentThemeData can be responsible for
    // painting large background surfaces. If this data isn't delivered to the
    // content process before about:home is painted, we will paint a default
    // background and then replace it when sharedData syncs, causing flashing.
    Services.ppmm.sharedData.flush();

    this._win.dispatchEvent(new CustomEvent("windowlwthemeupdate"));
  },

  _setExperiment(active, experiment, properties) {
    const root = this._doc.documentElement;
    if (this._lastExperimentData) {
      const { stylesheet, usedVariables } = this._lastExperimentData;
      if (stylesheet) {
        stylesheet.remove();
      }
      if (usedVariables) {
        for (const [variable] of usedVariables) {
          _setProperty(root, false, variable);
        }
      }
    }

    this._lastExperimentData = {};

    if (!active || !experiment) {
      return;
    }

    let usedVariables = [];
    if (properties.colors) {
      for (const property in properties.colors) {
        const cssVariable = experiment.colors[property];
        const value = _rgbaToString(
          _cssColorToRGBA(root.ownerDocument, properties.colors[property])
        );
        usedVariables.push([cssVariable, value]);
      }
    }

    if (properties.images) {
      for (const property in properties.images) {
        const cssVariable = experiment.images[property];
        usedVariables.push([
          cssVariable,
          `url(${properties.images[property]})`,
        ]);
      }
    }
    if (properties.properties) {
      for (const property in properties.properties) {
        const cssVariable = experiment.properties[property];
        usedVariables.push([cssVariable, properties.properties[property]]);
      }
    }
    for (const [variable, value] of usedVariables) {
      _setProperty(root, true, variable, value);
    }
    this._lastExperimentData.usedVariables = usedVariables;

    if (experiment.stylesheet) {
      /* Stylesheet URLs are validated using WebExtension schemas */
      let stylesheetAttr = `href="${experiment.stylesheet}" type="text/css"`;
      let stylesheet = this._doc.createProcessingInstruction(
        "xml-stylesheet",
        stylesheetAttr
      );
      this._doc.insertBefore(stylesheet, root);
      this._lastExperimentData.stylesheet = stylesheet;
    }
  },
};

function _getContentProperties(doc, active, data) {
  if (!active) {
    return {};
  }
  let properties = {};
  for (let property in data) {
    if (lazy.ThemeContentPropertyList.includes(property)) {
      properties[property] = _cssColorToRGBA(doc, data[property]);
    }
  }
  if (data.experimental) {
    for (const property in data.experimental.colors) {
      if (lazy.ThemeContentPropertyList.includes(property)) {
        properties[property] = _cssColorToRGBA(
          doc,
          data.experimental.colors[property]
        );
      }
    }
    for (const property in data.experimental.images) {
      if (lazy.ThemeContentPropertyList.includes(property)) {
        properties[property] = `url(${data.experimental.images[property]})`;
      }
    }
    for (const property in data.experimental.properties) {
      if (lazy.ThemeContentPropertyList.includes(property)) {
        properties[property] = data.experimental.properties[property];
      }
    }
  }
  return properties;
}

function _setImage(aWin, aRoot, aActive, aVariableName, aURLs) {
  if (aURLs && !Array.isArray(aURLs)) {
    aURLs = [aURLs];
  }
  _setProperty(
    aRoot,
    aActive,
    aVariableName,
    aURLs && aURLs.map(v => `url(${aWin.CSS.escape(v)})`).join(", ")
  );
}

function _setProperty(elem, active, variableName, value) {
  if (active && value) {
    elem.style.setProperty(variableName, value);
  } else {
    elem.style.removeProperty(variableName);
  }
}

function _determineToolbarAndContentTheme(
  aDoc,
  aTheme,
  aHasDarkTheme = false,
  aIsDarkTheme = false
) {
  const kDark = 0;
  const kLight = 1;
  const kSystem = 2;

  const colors = aTheme?._processedColors;
  function prefValue(aColor, aIsForeground = false) {
    if (typeof aColor != "object") {
      aColor = _cssColorToRGBA(aDoc, aColor);
    }
    return _isColorDark(aColor.r, aColor.g, aColor.b) == aIsForeground
      ? kLight
      : kDark;
  }

  function colorSchemeValue(aColorScheme) {
    if (!aColorScheme) {
      return null;
    }
    switch (aColorScheme) {
      case "light":
        return kLight;
      case "dark":
        return kDark;
      case "system":
        return kSystem;
      case "auto":
      default:
        break;
    }
    return null;
  }

  let toolbarTheme = (function () {
    if (!aTheme) {
      if (!DEFAULT_THEME_RESPECTS_SYSTEM_COLOR_SCHEME) {
        return kLight;
      }
      return kSystem;
    }
    let themeValue = colorSchemeValue(aTheme.color_scheme);
    if (themeValue !== null) {
      return themeValue;
    }
    if (aHasDarkTheme) {
      return aIsDarkTheme ? kDark : kLight;
    }
    // We prefer looking at toolbar background first (if it's opaque) because
    // some text colors can be dark enough for our heuristics, but still
    // contrast well enough with a dark background, see bug 1743010.
    if (colors.toolbarColor) {
      let color = _cssColorToRGBA(aDoc, colors.toolbarColor);
      if (color.a == 1) {
        return prefValue(color);
      }
    }
    if (colors.toolbar_text) {
      return prefValue(colors.toolbar_text, /* aIsForeground = */ true);
    }
    // It'd seem sensible to try looking at the "frame" background (accentcolor),
    // but we don't because some themes that use background images leave it to
    // black, see bug 1741931.
    //
    // Fall back to black as per the textcolor processing above.
    return prefValue(colors.textcolor || "black", /* aIsForeground = */ true);
  })();

  let contentTheme = (function () {
    if (lazy.BROWSER_THEME_UNIFIED_COLOR_SCHEME) {
      return toolbarTheme;
    }
    if (!aTheme) {
      if (!DEFAULT_THEME_RESPECTS_SYSTEM_COLOR_SCHEME) {
        return kLight;
      }
      return kSystem;
    }
    let themeValue = colorSchemeValue(
      aTheme.content_color_scheme || aTheme.color_scheme
    );
    if (themeValue !== null) {
      return themeValue;
    }
    return kSystem;
  })();

  Services.prefs.setIntPref("browser.theme.toolbar-theme", toolbarTheme);
  Services.prefs.setIntPref("browser.theme.content-theme", contentTheme);
}

/**
 * Sets dark mode attributes on root, if required. We must do this here,
 * instead of in each color's processColor function, because multiple colors
 * are considered.
 * @param {Document} doc
 * @param {Element} root
 * @param {object} colors
 *   The `_processedColors` object from the object created for our theme.
 */
function _setDarkModeAttributes(doc, root, colors) {
  {
    let textColor = _cssColorToRGBA(doc, colors.textcolor);
    if (textColor && !_isColorDark(textColor.r, textColor.g, textColor.b)) {
      root.setAttribute("lwtheme-brighttext", "true");
    } else {
      root.removeAttribute("lwtheme-brighttext");
    }
  }

  if (
    _determineIfColorPairIsDark(
      doc,
      colors,
      "toolbar_field_text",
      "toolbar_field"
    )
  ) {
    root.setAttribute("lwt-toolbar-field-brighttext", "true");
  } else {
    root.removeAttribute("lwt-toolbar-field-brighttext");
  }

  if (
    _determineIfColorPairIsDark(
      doc,
      colors,
      "toolbar_field_text_focus",
      "toolbar_field_focus"
    )
  ) {
    root.setAttribute("lwt-toolbar-field-focus-brighttext", "true");
  } else {
    root.removeAttribute("lwt-toolbar-field-focus-brighttext");
  }

  if (_determineIfColorPairIsDark(doc, colors, "popup_text", "popup")) {
    root.setAttribute("lwt-popup-brighttext", "true");
  } else {
    root.removeAttribute("lwt-popup-brighttext");
  }
}

/**
 * Determines if a themed color pair should be considered to have a dark color
 * scheme. We consider both the background and foreground (i.e. usually text)
 * colors because some text colors can be dark enough for our heuristics, but
 * still contrast well enough with a dark background
 * @param {Document} doc
 * @param {object} colors
 * @param {string} foregroundElementId
 *   The key for the foreground element in `colors`.
 * @param {string} backgroundElementId
 *   The key for the background element in `colors`.
 * @returns {boolean} True if the element should be considered dark, false
 *   otherwise.
 */
function _determineIfColorPairIsDark(
  doc,
  colors,
  textPropertyName,
  backgroundPropertyName
) {
  if (!colors[backgroundPropertyName] && !colors[textPropertyName]) {
    // Handles the system theme.
    return false;
  }

  let color = _cssColorToRGBA(doc, colors[backgroundPropertyName]);
  if (color && color.a == 1) {
    return _isColorDark(color.r, color.g, color.b);
  }

  color = _cssColorToRGBA(doc, colors[textPropertyName]);
  if (!color) {
    // Handles the case where a theme only provides a background color and it is
    // semi-transparent.
    return false;
  }

  return !_isColorDark(color.r, color.g, color.b);
}

function _setProperties(root, active, themeData) {
  let propertyOverrides = new Map();
  let doc = root.ownerDocument;

  // Copy the theme into _processedColors. We'll replace values with processed
  // colors if necessary. We copy because some colors (such as those used in
  // content) are not processed here, but are referenced in places that check
  // _processedColors. Copying means _processedColors will contain irrelevant
  // properties like `id`. There aren't too many, so that's OK.
  themeData._processedColors = { ...themeData };
  for (let map of [toolkitVariableMap, lazy.ThemeVariableMap]) {
    for (let [cssVarName, definition] of map) {
      const {
        lwtProperty,
        fallbackProperty,
        optionalElementID,
        processColor,
        isColor = true,
      } = definition;
      let elem = optionalElementID
        ? doc.getElementById(optionalElementID)
        : root;
      let val = propertyOverrides.get(lwtProperty) || themeData[lwtProperty];
      if (isColor) {
        val = _cssColorToRGBA(doc, val);
        if (!val && fallbackProperty) {
          val = _cssColorToRGBA(doc, themeData[fallbackProperty]);
        }
        if (processColor) {
          val = processColor(val, elem, propertyOverrides);
        } else {
          val = _rgbaToString(val);
        }
      }

      // Add processed color to themeData.
      themeData._processedColors[lwtProperty] = val;

      _setProperty(elem, active, cssVarName, val);
    }
  }
}

const kInvalidColor = { r: 0, g: 0, b: 0, a: 1 };

function _cssColorToRGBA(doc, cssColor) {
  if (!cssColor) {
    return null;
  }
  return (
    doc.defaultView.InspectorUtils.colorToRGBA(cssColor, doc) || kInvalidColor
  );
}

function _rgbaToString(parsedColor) {
  if (!parsedColor) {
    return null;
  }
  let { r, g, b, a } = parsedColor;
  if (a == 1) {
    return `rgb(${r}, ${g}, ${b})`;
  }
  return `rgba(${r}, ${g}, ${b}, ${a})`;
}

function _isColorDark(r, g, b) {
  return 0.2125 * r + 0.7154 * g + 0.0721 * b <= 127;
}