Bug 1858509 add thread-safety annotations around MediaSourceDemuxer::mMonitor r=alwu
[gecko.git] / widget / nsXPLookAndFeel.cpp
blob7e33a614b4fc51246fc821a38912f0bb66181d79
1 /* -*- mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* This Source Code Form is subject to the terms of the Mozilla Public
3 * License, v. 2.0. If a copy of the MPL was not distributed with this
4 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6 #include "mozilla/ArrayUtils.h"
8 #include "mozilla/LookAndFeel.h"
9 #include "nscore.h"
11 #include "nsXPLookAndFeel.h"
12 #include "nsLookAndFeel.h"
13 #include "HeadlessLookAndFeel.h"
14 #include "RemoteLookAndFeel.h"
15 #include "nsContentUtils.h"
16 #include "nsCRT.h"
17 #include "nsFont.h"
18 #include "nsIFrame.h"
19 #include "nsIXULRuntime.h"
20 #include "nsLayoutUtils.h"
21 #include "Theme.h"
22 #include "SurfaceCacheUtils.h"
23 #include "mozilla/dom/ContentParent.h"
24 #include "mozilla/dom/ContentChild.h"
25 #include "mozilla/Preferences.h"
26 #include "mozilla/Services.h"
27 #include "mozilla/ServoStyleSet.h"
28 #include "mozilla/ServoCSSParser.h"
29 #include "mozilla/StaticPrefs_browser.h"
30 #include "mozilla/StaticPrefs_editor.h"
31 #include "mozilla/StaticPrefs_layout.h"
32 #include "mozilla/StaticPrefs_ui.h"
33 #include "mozilla/StaticPrefs_widget.h"
34 #include "mozilla/dom/Document.h"
35 #include "mozilla/PreferenceSheet.h"
36 #include "mozilla/gfx/2D.h"
37 #include "mozilla/widget/WidgetMessageUtils.h"
38 #include "mozilla/dom/KeyboardEventBinding.h"
39 #include "mozilla/RelativeLuminanceUtils.h"
40 #include "mozilla/Telemetry.h"
41 #include "mozilla/TelemetryScalarEnums.h"
42 #include "mozilla/Try.h"
44 #include "gfxPlatform.h"
45 #include "gfxFont.h"
47 #include "qcms.h"
49 #include <bitset>
51 using namespace mozilla;
53 using IntID = mozilla::LookAndFeel::IntID;
54 using FloatID = mozilla::LookAndFeel::FloatID;
55 using ColorID = mozilla::LookAndFeel::ColorID;
56 using FontID = mozilla::LookAndFeel::FontID;
58 template <typename Index, typename Value, Index kEnd>
59 class EnumeratedCache {
60 mozilla::EnumeratedArray<Index, kEnd, Value> mEntries;
61 std::bitset<size_t(kEnd)> mValidity;
63 public:
64 constexpr EnumeratedCache() = default;
66 bool IsValid(Index aIndex) const { return mValidity[size_t(aIndex)]; }
68 const Value* Get(Index aIndex) const {
69 return IsValid(aIndex) ? &mEntries[aIndex] : nullptr;
72 void Insert(Index aIndex, Value aValue) {
73 mValidity[size_t(aIndex)] = true;
74 mEntries[aIndex] = aValue;
77 void Remove(Index aIndex) {
78 mValidity[size_t(aIndex)] = false;
79 mEntries[aIndex] = Value();
82 void Clear() {
83 mValidity.reset();
84 for (auto& entry : mEntries) {
85 entry = Value();
90 using ColorCache = EnumeratedCache<ColorID, Maybe<nscolor>, ColorID::End>;
92 struct ColorCaches {
93 using UseStandins = LookAndFeel::UseStandins;
95 ColorCache mCaches[2][2];
97 constexpr ColorCaches() = default;
99 ColorCache& Get(ColorScheme aScheme, UseStandins aUseStandins) {
100 return mCaches[aScheme == ColorScheme::Dark]
101 [aUseStandins == UseStandins::Yes];
104 void Clear() {
105 for (auto& c : mCaches) {
106 for (auto& cache : c) {
107 cache.Clear();
113 static ColorCaches sColorCaches;
115 static EnumeratedCache<FloatID, Maybe<float>, FloatID::End> sFloatCache;
116 static EnumeratedCache<IntID, Maybe<int32_t>, IntID::End> sIntCache;
117 static EnumeratedCache<FontID, widget::LookAndFeelFont, FontID::End> sFontCache;
119 // To make one of these prefs toggleable from a reftest add a user
120 // pref in testing/profiles/reftest/user.js. For example, to make
121 // ui.useAccessibilityTheme toggleable, add:
123 // user_pref("ui.useAccessibilityTheme", 0);
125 // This needs to be of the same length and in the same order as
126 // LookAndFeel::IntID values.
127 static const char sIntPrefs[][45] = {
128 "ui.caretBlinkTime",
129 "ui.caretBlinkCount",
130 "ui.caretWidth",
131 "ui.caretVisibleWithSelection",
132 "ui.selectTextfieldsOnKeyFocus",
133 "ui.submenuDelay",
134 "ui.menusCanOverlapOSBar",
135 "ui.useOverlayScrollbars",
136 "ui.allowOverlayScrollbarsOverlap",
137 "ui.skipNavigatingDisabledMenuItem",
138 "ui.dragThresholdX",
139 "ui.dragThresholdY",
140 "ui.useAccessibilityTheme",
141 "ui.scrollArrowStyle",
142 "ui.scrollButtonLeftMouseButtonAction",
143 "ui.scrollButtonMiddleMouseButtonAction",
144 "ui.scrollButtonRightMouseButtonAction",
145 "ui.treeOpenDelay",
146 "ui.treeCloseDelay",
147 "ui.treeLazyScrollDelay",
148 "ui.treeScrollDelay",
149 "ui.treeScrollLinesMax",
150 "accessibility.tabfocus", // Weird one...
151 "ui.chosenMenuItemsShouldBlink",
152 "ui.windowsAccentColorInTitlebar",
153 "ui.macBigSurTheme",
154 "ui.macRTL",
155 "ui.alertNotificationOrigin",
156 "ui.scrollToClick",
157 "ui.IMERawInputUnderlineStyle",
158 "ui.IMESelectedRawTextUnderlineStyle",
159 "ui.IMEConvertedTextUnderlineStyle",
160 "ui.IMESelectedConvertedTextUnderlineStyle",
161 "ui.SpellCheckerUnderlineStyle",
162 "ui.menuBarDrag",
163 "ui.scrollbarButtonAutoRepeatBehavior",
164 "ui.tooltipDelay",
165 "ui.swipeAnimationEnabled",
166 "ui.scrollbarDisplayOnMouseMove",
167 "ui.scrollbarFadeBeginDelay",
168 "ui.scrollbarFadeDuration",
169 "ui.contextMenuOffsetVertical",
170 "ui.contextMenuOffsetHorizontal",
171 "ui.GtkCSDAvailable",
172 "ui.GtkCSDMinimizeButton",
173 "ui.GtkCSDMaximizeButton",
174 "ui.GtkCSDCloseButton",
175 "ui.GtkCSDMinimizeButtonPosition",
176 "ui.GtkCSDMaximizeButtonPosition",
177 "ui.GtkCSDCloseButtonPosition",
178 "ui.GtkCSDReversedPlacement",
179 "ui.systemUsesDarkTheme",
180 "ui.prefersReducedMotion",
181 "ui.prefersReducedTransparency",
182 "ui.invertedColors",
183 "ui.primaryPointerCapabilities",
184 "ui.allPointerCapabilities",
185 "ui.systemScrollbarSize",
186 "ui.touchDeviceSupportPresent",
187 "ui.titlebarRadius",
188 "ui.dynamicRange",
189 "ui.videoDynamicRange",
190 "ui.panelAnimations",
191 "ui.hideCursorWhileTyping",
194 static_assert(ArrayLength(sIntPrefs) == size_t(LookAndFeel::IntID::End),
195 "Should have a pref for each int value");
197 // This array MUST be kept in the same order as the float id list in
198 // LookAndFeel.h
199 // clang-format off
200 static const char sFloatPrefs[][37] = {
201 "ui.IMEUnderlineRelativeSize",
202 "ui.SpellCheckerUnderlineRelativeSize",
203 "ui.caretAspectRatio",
204 "ui.textScaleFactor",
205 "ui.cursorScale",
207 // clang-format on
209 static_assert(ArrayLength(sFloatPrefs) == size_t(LookAndFeel::FloatID::End),
210 "Should have a pref for each float value");
212 // This array MUST be kept in the same order as the color list in
213 // specified/color.rs
214 static const char sColorPrefs[][41] = {
215 "ui.activeborder",
216 "ui.activecaption",
217 "ui.appworkspace",
218 "ui.background",
219 "ui.buttonface",
220 "ui.buttonhighlight",
221 "ui.buttonshadow",
222 "ui.buttontext",
223 "ui.buttonborder",
224 "ui.captiontext",
225 "ui.-moz-field",
226 "ui.-moz-disabledfield",
227 "ui.-moz-fieldtext",
228 "ui.mark",
229 "ui.marktext",
230 "ui.-moz-comboboxtext",
231 "ui.-moz-combobox",
232 "ui.graytext",
233 "ui.highlight",
234 "ui.highlighttext",
235 "ui.inactiveborder",
236 "ui.inactivecaption",
237 "ui.inactivecaptiontext",
238 "ui.infobackground",
239 "ui.infotext",
240 "ui.menu",
241 "ui.menutext",
242 "ui.scrollbar",
243 "ui.threeddarkshadow",
244 "ui.threedface",
245 "ui.threedhighlight",
246 "ui.threedlightshadow",
247 "ui.threedshadow",
248 "ui.window",
249 "ui.windowframe",
250 "ui.windowtext",
251 "ui.-moz-default-color",
252 "ui.-moz-default-background-color",
253 "ui.-moz-dialog",
254 "ui.-moz-dialogtext",
255 "ui.-moz-cellhighlight",
256 "ui.-moz_cellhighlighttext",
257 "ui.selecteditem",
258 "ui.selecteditemtext",
259 "ui.-moz-buttonhoverface",
260 "ui.-moz_buttonhovertext",
261 "ui.-moz_menuhover",
262 "ui.-moz_menuhoverdisabled",
263 "ui.-moz_menuhovertext",
264 "ui.-moz_menubarhovertext",
265 "ui.-moz_eventreerow",
266 "ui.-moz_oddtreerow",
267 "ui.-moz-buttonactivetext",
268 "ui.-moz-buttonactiveface",
269 "ui.-moz-buttondisabledface",
270 "ui.-moz-headerbar",
271 "ui.-moz-headerbartext",
272 "ui.-moz-headerbarinactive",
273 "ui.-moz-headerbarinactivetext",
274 "ui.-moz-mac-defaultbuttontext",
275 "ui.-moz-mac-focusring",
276 "ui.-moz_mac_disabledtoolbartext",
277 "ui.accentcolor",
278 "ui.accentcolortext",
279 "ui.-moz-autofill-background",
280 "ui.-moz-nativehyperlinktext",
281 "ui.-moz-nativevisitedhyperlinktext",
282 "ui.-moz-hyperlinktext",
283 "ui.-moz-activehyperlinktext",
284 "ui.-moz-visitedhyperlinktext",
285 "ui.-moz-colheadertext",
286 "ui.-moz-colheaderhovertext",
287 "ui.textSelectDisabledBackground",
288 "ui.textSelectAttentionBackground",
289 "ui.textSelectAttentionForeground",
290 "ui.textHighlightBackground",
291 "ui.textHighlightForeground",
292 "ui.IMERawInputBackground",
293 "ui.IMERawInputForeground",
294 "ui.IMERawInputUnderline",
295 "ui.IMESelectedRawTextBackground",
296 "ui.IMESelectedRawTextForeground",
297 "ui.IMESelectedRawTextUnderline",
298 "ui.IMEConvertedTextBackground",
299 "ui.IMEConvertedTextForeground",
300 "ui.IMEConvertedTextUnderline",
301 "ui.IMESelectedConvertedTextBackground",
302 "ui.IMESelectedConvertedTextForeground",
303 "ui.IMESelectedConvertedTextUnderline",
304 "ui.SpellCheckerUnderline",
305 "ui.themedScrollbar",
306 "ui.themedScrollbarInactive",
307 "ui.themedScrollbarThumb",
308 "ui.themedScrollbarThumbHover",
309 "ui.themedScrollbarThumbActive",
310 "ui.themedScrollbarThumbInactive",
313 static_assert(ArrayLength(sColorPrefs) == size_t(LookAndFeel::ColorID::End),
314 "Should have a pref for each color value");
316 // This array MUST be kept in the same order as the SystemFont enum.
317 static const char sFontPrefs[][41] = {
318 "ui.font.caption",
319 "ui.font.icon",
320 "ui.font.menu",
321 "ui.font.message-box",
322 "ui.font.small-caption",
323 "ui.font.status-bar",
324 "ui.font.-moz-pull-down-menu",
325 "ui.font.-moz-button",
326 "ui.font.-moz-list",
327 "ui.font.-moz-field",
330 static_assert(ArrayLength(sFontPrefs) == size_t(LookAndFeel::FontID::End),
331 "Should have a pref for each font value");
333 const char* nsXPLookAndFeel::GetColorPrefName(ColorID aId) {
334 return sColorPrefs[size_t(aId)];
337 bool nsXPLookAndFeel::sInitialized = false;
339 nsXPLookAndFeel* nsXPLookAndFeel::sInstance = nullptr;
340 bool nsXPLookAndFeel::sShutdown = false;
342 auto LookAndFeel::SystemZoomSettings() -> ZoomSettings {
343 ZoomSettings settings;
344 switch (StaticPrefs::browser_display_os_zoom_behavior()) {
345 case 0:
346 default:
347 break;
348 case 1:
349 settings.mFullZoom = GetTextScaleFactor();
350 break;
351 case 2:
352 settings.mTextZoom = GetTextScaleFactor();
353 break;
355 return settings;
358 // static
359 nsXPLookAndFeel* nsXPLookAndFeel::GetInstance() {
360 if (sInstance) {
361 return sInstance;
364 NS_ENSURE_TRUE(!sShutdown, nullptr);
366 // If we're in a content process, then the parent process will have supplied
367 // us with an initial FullLookAndFeel object.
368 // We grab this data from the ContentChild,
369 // where it's been temporarily stashed, and initialize our new LookAndFeel
370 // object with it.
372 FullLookAndFeel* lnf = nullptr;
374 if (auto* cc = mozilla::dom::ContentChild::GetSingleton()) {
375 lnf = &cc->BorrowLookAndFeelData();
378 if (lnf) {
379 sInstance = new widget::RemoteLookAndFeel(std::move(*lnf));
380 } else if (gfxPlatform::IsHeadless()) {
381 sInstance = new widget::HeadlessLookAndFeel();
382 } else {
383 sInstance = new nsLookAndFeel();
386 // This is only ever used once during initialization, and can be cleared now.
387 if (lnf) {
388 *lnf = {};
391 widget::Theme::Init();
392 return sInstance;
395 // static
396 void nsXPLookAndFeel::Shutdown() {
397 if (sShutdown) {
398 return;
401 sShutdown = true;
402 delete sInstance;
403 sInstance = nullptr;
405 // This keeps strings alive, so need to clear to make leak checking happy.
406 sFontCache.Clear();
408 widget::Theme::Shutdown();
411 static void IntPrefChanged(const nsACString& aPref) {
412 // Most Int prefs can't change our system colors or fonts, but
413 // ui.systemUsesDarkTheme can, since it affects the effective color-scheme
414 // (affecting system colors).
415 auto changeKind = aPref.EqualsLiteral("ui.systemUsesDarkTheme")
416 ? widget::ThemeChangeKind::Style
417 : widget::ThemeChangeKind::MediaQueriesOnly;
418 LookAndFeel::NotifyChangedAllWindows(changeKind);
421 static void FloatPrefChanged(const nsACString& aPref) {
422 // Most float prefs can't change our system colors or fonts, but
423 // textScaleFactor affects layout.
424 auto changeKind = aPref.EqualsLiteral("ui.textScaleFactor")
425 ? widget::ThemeChangeKind::StyleAndLayout
426 : widget::ThemeChangeKind::MediaQueriesOnly;
427 LookAndFeel::NotifyChangedAllWindows(changeKind);
430 static void ColorPrefChanged() {
431 // Color prefs affect style, because they by definition change system colors.
432 LookAndFeel::NotifyChangedAllWindows(widget::ThemeChangeKind::Style);
435 static void FontPrefChanged() {
436 // Color prefs affect style, because they by definition change system fonts.
437 LookAndFeel::NotifyChangedAllWindows(widget::ThemeChangeKind::Style);
440 // static
441 void nsXPLookAndFeel::OnPrefChanged(const char* aPref, void* aClosure) {
442 nsDependentCString prefName(aPref);
443 for (const char* pref : sIntPrefs) {
444 if (prefName.Equals(pref)) {
445 IntPrefChanged(prefName);
446 return;
450 for (const char* pref : sFloatPrefs) {
451 if (prefName.Equals(pref)) {
452 FloatPrefChanged(prefName);
453 return;
457 for (const char* pref : sColorPrefs) {
458 // We use StringBeginsWith to handle .dark prefs too.
459 if (StringBeginsWith(prefName, nsDependentCString(pref))) {
460 ColorPrefChanged();
461 return;
465 for (const char* pref : sFontPrefs) {
466 if (StringBeginsWith(prefName, nsDependentCString(pref))) {
467 FontPrefChanged();
468 return;
473 static constexpr struct {
474 nsLiteralCString mName;
475 widget::ThemeChangeKind mChangeKind =
476 widget::ThemeChangeKind::MediaQueriesOnly;
477 } kMediaQueryPrefs[] = {
478 // Affects whether standins are used for the accent color.
479 {"widget.non-native-theme.use-theme-accent"_ns,
480 widget::ThemeChangeKind::Style},
481 // These three affect system colors on Windows.
482 {"widget.windows.uwp-system-colors.enabled"_ns,
483 widget::ThemeChangeKind::Style},
484 {"widget.windows.uwp-system-colors.highlight-accent"_ns,
485 widget::ThemeChangeKind::Style},
486 // Affects env().
487 {"layout.css.prefers-color-scheme.content-override"_ns,
488 widget::ThemeChangeKind::Style},
489 // Affects media queries and scrollbar sizes, so gotta relayout.
490 {"widget.gtk.overlay-scrollbars.enabled"_ns,
491 widget::ThemeChangeKind::StyleAndLayout},
492 // Affects zoom settings which includes text and full zoom.
493 {"browser.display.os-zoom-behavior"_ns,
494 widget::ThemeChangeKind::StyleAndLayout},
495 // This affects not only the media query, but also the native theme, so we
496 // need to re-layout.
497 {"browser.theme.toolbar-theme"_ns, widget::ThemeChangeKind::AllBits},
498 {"browser.theme.content-theme"_ns},
501 // Read values from the user's preferences.
502 // This is done once at startup, but since the user's preferences
503 // haven't actually been read yet at that time, we also have to
504 // set a callback to inform us of changes to each pref.
505 void nsXPLookAndFeel::Init() {
506 MOZ_RELEASE_ASSERT(NS_IsMainThread());
508 // Say we're already initialized, and take the chance that it might fail;
509 // protects against some other process writing to our static variables.
510 sInitialized = true;
512 if (XRE_IsParentProcess()) {
513 nsLayoutUtils::RecomputeSmoothScrollDefault();
516 // XXX If we could reorganize the pref names, we should separate the branch
517 // for each types. Then, we could reduce the unnecessary loop from
518 // nsXPLookAndFeel::OnPrefChanged().
519 Preferences::RegisterPrefixCallback(OnPrefChanged, "ui.");
520 // We really do just want the accessibility.tabfocus pref, not other prefs
521 // that start with that string.
522 Preferences::RegisterCallback(OnPrefChanged, "accessibility.tabfocus");
524 for (const auto& pref : kMediaQueryPrefs) {
525 Preferences::RegisterCallback(
526 [](const char*, void* aChangeKind) {
527 auto changeKind =
528 widget::ThemeChangeKind(reinterpret_cast<uintptr_t>(aChangeKind));
529 LookAndFeel::NotifyChangedAllWindows(changeKind);
531 pref.mName, reinterpret_cast<void*>(uintptr_t(pref.mChangeKind)));
535 nsXPLookAndFeel::~nsXPLookAndFeel() {
536 NS_ASSERTION(sInstance == this,
537 "This destroying instance isn't the singleton instance");
538 sInstance = nullptr;
541 static bool IsSpecialColor(LookAndFeel::ColorID aID, nscolor aColor) {
542 using ColorID = LookAndFeel::ColorID;
544 if (aColor == NS_SAME_AS_FOREGROUND_COLOR) {
545 return true;
548 switch (aID) {
549 case ColorID::IMESelectedRawTextBackground:
550 case ColorID::IMESelectedConvertedTextBackground:
551 case ColorID::IMERawInputBackground:
552 case ColorID::IMEConvertedTextBackground:
553 case ColorID::IMESelectedRawTextForeground:
554 case ColorID::IMESelectedConvertedTextForeground:
555 case ColorID::IMERawInputForeground:
556 case ColorID::IMEConvertedTextForeground:
557 case ColorID::IMERawInputUnderline:
558 case ColorID::IMEConvertedTextUnderline:
559 case ColorID::IMESelectedRawTextUnderline:
560 case ColorID::IMESelectedConvertedTextUnderline:
561 case ColorID::SpellCheckerUnderline:
562 return NS_IS_SELECTION_SPECIAL_COLOR(aColor);
563 default:
564 break;
567 * In GetColor(), every color that is not a special color is color
568 * corrected. Use false to make other colors color corrected.
570 return false;
573 nscolor nsXPLookAndFeel::GetStandinForNativeColor(ColorID aID,
574 ColorScheme aScheme) {
575 if (aScheme == ColorScheme::Dark) {
576 if (auto color = GenericDarkColor(aID)) {
577 return *color;
581 // The stand-in colors are taken from what the non-native theme needs (for
582 // field/button colors), the Windows 7 Aero theme except Mac-specific colors
583 // which are taken from Mac OS 10.7.
585 #define COLOR(name_, r, g, b) \
586 case ColorID::name_: \
587 return NS_RGB(r, g, b);
589 #define COLORA(name_, r, g, b, a) \
590 case ColorID::name_: \
591 return NS_RGBA(r, g, b, a);
593 switch (aID) {
594 // These are here for the purposes of headless mode.
595 case ColorID::IMESelectedRawTextBackground:
596 case ColorID::IMESelectedConvertedTextBackground:
597 case ColorID::IMERawInputBackground:
598 case ColorID::IMEConvertedTextBackground:
599 return NS_TRANSPARENT;
600 case ColorID::IMESelectedRawTextForeground:
601 case ColorID::IMESelectedConvertedTextForeground:
602 case ColorID::IMERawInputForeground:
603 case ColorID::IMEConvertedTextForeground:
604 return NS_SAME_AS_FOREGROUND_COLOR;
605 case ColorID::IMERawInputUnderline:
606 case ColorID::IMEConvertedTextUnderline:
607 return NS_40PERCENT_FOREGROUND_COLOR;
608 case ColorID::Accentcolor:
609 return widget::sDefaultAccent.ToABGR();
610 case ColorID::Accentcolortext:
611 return widget::sDefaultAccentText.ToABGR();
612 COLOR(SpellCheckerUnderline, 0xff, 0x00, 0x00)
613 COLOR(TextSelectDisabledBackground, 0xaa, 0xaa, 0xaa)
615 // Titlebar colors
616 COLOR(Activeborder, 0xB4, 0xB4, 0xB4)
617 COLOR(Inactiveborder, 0xB4, 0xB4, 0xB4)
618 COLOR(Activecaption, 0xF0, 0xF0, 0xF4)
619 COLOR(Inactivecaption, 0xF0, 0xF0, 0xF4)
620 COLOR(Captiontext, 0x00, 0x00, 0x00)
621 COLOR(Inactivecaptiontext, 0x00, 0x00, 0x00)
623 // CSS 2 colors:
624 COLOR(Appworkspace, 0xAB, 0xAB, 0xAB)
625 COLOR(Background, 0x00, 0x00, 0x00)
626 COLOR(Buttonhighlight, 0xFF, 0xFF, 0xFF)
627 COLOR(Buttonshadow, 0xA0, 0xA0, 0xA0)
629 // Buttons and comboboxes should be kept in sync since they are drawn with
630 // the same colors by the non-native theme.
631 COLOR(Buttonface, 0xe9, 0xe9, 0xed)
632 COLORA(MozButtondisabledface, 0xe9, 0xe9, 0xed, 128)
634 COLOR(MozCombobox, 0xe9, 0xe9, 0xed)
636 COLOR(Buttontext, 0x00, 0x00, 0x00)
637 COLOR(MozComboboxtext, 0x00, 0x00, 0x00)
639 COLOR(Graytext, 0x6D, 0x6D, 0x6D)
640 COLOR(Highlight, 0x33, 0x99, 0xFF)
641 COLOR(Highlighttext, 0xFF, 0xFF, 0xFF)
642 COLOR(Infobackground, 0xFF, 0xFF, 0xE1)
643 COLOR(Infotext, 0x00, 0x00, 0x00)
644 COLOR(Menu, 0xF0, 0xF0, 0xF0)
645 COLOR(Menutext, 0x00, 0x00, 0x00)
646 COLOR(Scrollbar, 0xC8, 0xC8, 0xC8)
647 COLOR(Threeddarkshadow, 0x69, 0x69, 0x69)
648 COLOR(Threedface, 0xF0, 0xF0, 0xF0)
649 COLOR(Threedhighlight, 0xFF, 0xFF, 0xFF)
650 COLOR(Threedlightshadow, 0xE3, 0xE3, 0xE3)
651 COLOR(Threedshadow, 0xA0, 0xA0, 0xA0)
652 COLOR(Buttonborder, 0xE3, 0xE3, 0xE3)
653 COLOR(Mark, 0xFF, 0xFF, 0x00)
654 COLOR(Marktext, 0x00, 0x00, 0x00)
655 COLOR(Window, 0xFF, 0xFF, 0xFF)
656 COLOR(Windowframe, 0x64, 0x64, 0x64)
657 COLOR(Windowtext, 0x00, 0x00, 0x00)
658 COLOR(Field, 0xFF, 0xFF, 0xFF)
659 COLORA(MozDisabledfield, 0xFF, 0xFF, 0xFF, 128)
660 COLOR(Fieldtext, 0x00, 0x00, 0x00)
661 COLOR(MozDialog, 0xF0, 0xF0, 0xF0)
662 COLOR(MozDialogtext, 0x00, 0x00, 0x00)
663 COLOR(MozColheadertext, 0x00, 0x00, 0x00)
664 COLOR(MozColheaderhovertext, 0x00, 0x00, 0x00)
665 COLOR(MozCellhighlight, 0xF0, 0xF0, 0xF0)
666 COLOR(MozCellhighlighttext, 0x00, 0x00, 0x00)
667 COLOR(Selecteditem, 0x33, 0x99, 0xFF)
668 COLOR(Selecteditemtext, 0xFF, 0xFF, 0xFF)
669 COLOR(MozButtonhoverface, 0xd0, 0xd0, 0xd7)
670 COLOR(MozButtonhovertext, 0x00, 0x00, 0x00)
671 COLOR(MozButtonactiveface, 0xb1, 0xb1, 0xb9)
672 COLOR(MozButtonactivetext, 0x00, 0x00, 0x00)
673 COLOR(MozMenuhover, 0x33, 0x99, 0xFF)
674 COLOR(MozMenuhovertext, 0x00, 0x00, 0x00)
675 COLOR(MozMenubarhovertext, 0x00, 0x00, 0x00)
676 COLOR(MozMenuhoverdisabled, 0xF0, 0xF0, 0xF0)
677 COLOR(MozEventreerow, 0xFF, 0xFF, 0xFF)
678 COLOR(MozOddtreerow, 0xFF, 0xFF, 0xFF)
679 COLOR(MozMacFocusring, 0x60, 0x9D, 0xD7)
680 COLOR(MozMacDisabledtoolbartext, 0x3F, 0x3F, 0x3F)
681 // Seems to be the default color (hardcoded because of bug 1065998)
682 COLOR(MozNativehyperlinktext, 0x00, 0x66, 0xCC)
683 COLOR(MozNativevisitedhyperlinktext, 0x55, 0x1A, 0x8B)
684 default:
685 break;
687 return NS_RGB(0xFF, 0xFF, 0xFF);
690 #undef COLOR
691 #undef COLORA
693 // Taken from in-content/common.inc.css's dark theme.
694 Maybe<nscolor> nsXPLookAndFeel::GenericDarkColor(ColorID aID) {
695 nscolor color = NS_RGB(0, 0, 0);
696 static constexpr nscolor kWindowBackground = NS_RGB(28, 27, 34);
697 static constexpr nscolor kWindowText = NS_RGB(251, 251, 254);
698 switch (aID) {
699 case ColorID::Window: // --in-content-page-background
700 case ColorID::Background:
701 color = kWindowBackground;
702 break;
704 case ColorID::Menu:
705 color = NS_RGB(0x2b, 0x2a, 0x33);
706 break;
708 case ColorID::MozMenuhovertext:
709 case ColorID::MozMenubarhovertext:
710 case ColorID::Menutext:
711 color = NS_RGB(0xfb, 0xfb, 0xfe);
712 break;
714 case ColorID::MozMenuhover:
715 color = NS_RGB(0x52, 0x52, 0x5e);
716 break;
718 case ColorID::MozMenuhoverdisabled:
719 color = NS_RGB(0x3a, 0x39, 0x44);
720 break;
722 case ColorID::MozOddtreerow:
723 case ColorID::MozDialog: // --in-content-box-background
724 color = NS_RGB(35, 34, 43);
725 break;
726 case ColorID::Windowtext: // --in-content-page-color
727 case ColorID::MozDialogtext:
728 case ColorID::Fieldtext:
729 case ColorID::Buttontext: // --in-content-button-text-color (via
730 // --in-content-page-color)
731 case ColorID::MozComboboxtext:
732 case ColorID::MozButtonhovertext:
733 case ColorID::MozButtonactivetext:
734 case ColorID::MozHeaderbartext:
735 case ColorID::MozHeaderbarinactivetext:
736 case ColorID::Captiontext:
737 case ColorID::Inactivecaptiontext: // TODO(emilio): Maybe make
738 // Inactivecaptiontext Graytext?
739 color = kWindowText;
740 break;
741 case ColorID::Buttonshadow:
742 case ColorID::Threedshadow:
743 case ColorID::Threedlightshadow:
744 case ColorID::Buttonborder: // --in-content-box-border-color computed
745 // with kWindowText above
746 // kWindowBackground.
747 case ColorID::Graytext: // opacity: 0.4 of kWindowText blended over the
748 // "Window" background color, which happens to be
749 // the same :-)
750 color = NS_ComposeColors(kWindowBackground, NS_RGBA(251, 251, 254, 102));
751 break;
752 case ColorID::MozCellhighlight:
753 case ColorID::Selecteditem: // --in-content-primary-button-background /
754 // --in-content-item-selected
755 color = NS_RGB(0, 221, 255);
756 break;
757 case ColorID::Field:
758 case ColorID::Buttonface: // --in-content-button-background
759 case ColorID::Threedface:
760 case ColorID::MozCombobox:
761 case ColorID::MozCellhighlighttext:
762 case ColorID::Selecteditemtext: // --in-content-primary-button-text-color /
763 // --in-content-item-selected-text
764 color = NS_RGB(43, 42, 51);
765 break;
766 case ColorID::Threeddarkshadow: // Same as Threedlightshadow but with the
767 // background.
768 case ColorID::MozDisabledfield: // opacity: 0.4 of the face above blended
769 // over the "Window" background color.
770 case ColorID::MozButtondisabledface:
771 color = NS_ComposeColors(kWindowBackground, NS_RGBA(43, 42, 51, 102));
772 break;
773 case ColorID::MozButtonhoverface: // --in-content-button-background-hover
774 color = NS_RGB(82, 82, 94);
775 break;
776 case ColorID::MozButtonactiveface: // --in-content-button-background-active
777 color = NS_RGB(91, 91, 102);
778 break;
779 case ColorID::Highlight:
780 color = NS_RGBA(0, 221, 255, 78);
781 break;
782 case ColorID::Highlighttext:
783 color = NS_SAME_AS_FOREGROUND_COLOR;
784 break;
785 case ColorID::MozNativehyperlinktext:
786 // If you change this color, you probably also want to change the default
787 // value of browser.anchor_color.dark.
788 color = NS_RGB(0x8c, 0x8c, 0xff);
789 break;
790 case ColorID::MozNativevisitedhyperlinktext:
791 // If you change this color, you probably also want to change the default
792 // value of browser.visited_color.dark.
793 color = NS_RGB(0xff, 0xad, 0xff);
794 break;
795 case ColorID::SpellCheckerUnderline:
796 // This is the default for active links in dark mode as well
797 // (browser.active_color.dark). See bug 1755564 for some analysis and
798 // other options too.
799 color = NS_RGB(0xff, 0x66, 0x66);
800 break;
801 case ColorID::Activeborder:
802 case ColorID::Inactiveborder:
803 color = NS_RGB(57, 57, 57);
804 break;
805 case ColorID::MozHeaderbar:
806 case ColorID::MozHeaderbarinactive:
807 case ColorID::Activecaption:
808 case ColorID::Inactivecaption:
809 color = NS_RGB(28, 27, 34);
810 break;
811 default:
812 return Nothing();
814 return Some(color);
817 // Uncomment the #define below if you want to debug system color use in a skin
818 // that uses them. When set, it will make all system color pairs that are
819 // appropriate for foreground/background pairing the same. This means if the
820 // skin is using system colors correctly you will not be able to see *any* text.
822 // #define DEBUG_SYSTEM_COLOR_USE
824 #ifdef DEBUG_SYSTEM_COLOR_USE
825 static nsresult SystemColorUseDebuggingColor(LookAndFeel::ColorID aID,
826 nscolor& aResult) {
827 using ColorID = LookAndFeel::ColorID;
829 switch (aID) {
830 // css2 http://www.w3.org/TR/REC-CSS2/ui.html#system-colors
831 case ColorID::Activecaption:
832 // active window caption background
833 case ColorID::Captiontext:
834 // text in active window caption
835 aResult = NS_RGB(0xff, 0x00, 0x00);
836 break;
838 case ColorID::Highlight:
839 // background of selected item
840 case ColorID::Highlighttext:
841 // text of selected item
842 aResult = NS_RGB(0xff, 0xff, 0x00);
843 break;
845 case ColorID::Inactivecaption:
846 // inactive window caption
847 case ColorID::Inactivecaptiontext:
848 // text in inactive window caption
849 aResult = NS_RGB(0x66, 0x66, 0x00);
850 break;
852 case ColorID::Infobackground:
853 // tooltip background color
854 case ColorID::Infotext:
855 // tooltip text color
856 aResult = NS_RGB(0x00, 0xff, 0x00);
857 break;
859 case ColorID::Menu:
860 // menu background
861 case ColorID::Menutext:
862 // menu text
863 aResult = NS_RGB(0x00, 0xff, 0xff);
864 break;
866 case ColorID::Threedface:
867 case ColorID::Buttonface:
868 // 3-D face color
869 case ColorID::Buttontext:
870 // text on push buttons
871 aResult = NS_RGB(0x00, 0x66, 0x66);
872 break;
874 case ColorID::Window:
875 case ColorID::Windowtext:
876 aResult = NS_RGB(0x00, 0x00, 0xff);
877 break;
879 // from the CSS3 working draft (not yet finalized)
880 // http://www.w3.org/tr/2000/wd-css3-userint-20000216.html#color
882 case ColorID::Field:
883 case ColorID::Fieldtext:
884 aResult = NS_RGB(0xff, 0x00, 0xff);
885 break;
887 case ColorID::MozDialog:
888 case ColorID::MozDialogtext:
889 aResult = NS_RGB(0x66, 0x00, 0x66);
890 break;
892 default:
893 return NS_ERROR_NOT_AVAILABLE;
896 return NS_OK;
898 #endif
900 static nsresult GetPrefColor(const char* aPref, nscolor& aResult) {
901 nsAutoCString colorStr;
902 MOZ_TRY(Preferences::GetCString(aPref, colorStr));
903 if (!ServoCSSParser::ComputeColor(nullptr, NS_RGB(0, 0, 0), colorStr,
904 &aResult)) {
905 return NS_ERROR_FAILURE;
907 return NS_OK;
910 static nsresult GetColorFromPref(LookAndFeel::ColorID aID, ColorScheme aScheme,
911 nscolor& aResult) {
912 const char* prefName = sColorPrefs[size_t(aID)];
913 if (aScheme == ColorScheme::Dark) {
914 nsAutoCString darkPrefName(prefName);
915 darkPrefName.Append(".dark");
916 if (NS_SUCCEEDED(GetPrefColor(darkPrefName.get(), aResult))) {
917 return NS_OK;
920 return GetPrefColor(prefName, aResult);
923 // All these routines will return NS_OK if they have a value,
924 // in which case the nsLookAndFeel should use that value;
925 // otherwise we'll return NS_ERROR_NOT_AVAILABLE, in which case, the
926 // platform-specific nsLookAndFeel should use its own values instead.
927 nsresult nsXPLookAndFeel::GetColorValue(ColorID aID, ColorScheme aScheme,
928 UseStandins aUseStandins,
929 nscolor& aResult) {
930 if (!sInitialized) {
931 Init();
934 #ifdef DEBUG_SYSTEM_COLOR_USE
935 if (NS_SUCCEEDED(SystemColorUseDebuggingColor(aID, aResult))) {
936 return NS_OK;
938 #endif
940 auto& cache = sColorCaches.Get(aScheme, aUseStandins);
941 if (const auto* cached = cache.Get(aID)) {
942 if (cached->isNothing()) {
943 return NS_ERROR_FAILURE;
945 aResult = cached->value();
946 return NS_OK;
949 // NOTE: Servo holds a lock and the main thread is paused, so writing to the
950 // global cache here is fine.
951 auto result = GetUncachedColor(aID, aScheme, aUseStandins);
952 cache.Insert(aID, result);
953 if (!result) {
954 return NS_ERROR_FAILURE;
956 aResult = *result;
957 return NS_OK;
960 Maybe<nscolor> nsXPLookAndFeel::GetUncachedColor(ColorID aID,
961 ColorScheme aScheme,
962 UseStandins aUseStandins) {
963 if (aUseStandins == UseStandins::Yes) {
964 return Some(GetStandinForNativeColor(aID, aScheme));
966 nscolor r;
967 if (NS_SUCCEEDED(GetColorFromPref(aID, aScheme, r))) {
968 return Some(r);
970 if (NS_SUCCEEDED(NativeGetColor(aID, aScheme, r))) {
971 if (gfxPlatform::GetCMSMode() == CMSMode::All && !IsSpecialColor(aID, r)) {
972 qcms_transform* transform = gfxPlatform::GetCMSInverseRGBTransform();
973 if (transform) {
974 uint8_t color[4];
975 color[0] = NS_GET_R(r);
976 color[1] = NS_GET_G(r);
977 color[2] = NS_GET_B(r);
978 color[3] = NS_GET_A(r);
979 qcms_transform_data(transform, color, color, 1);
980 r = NS_RGBA(color[0], color[1], color[2], color[3]);
984 return Some(r);
986 return Nothing();
989 nsresult nsXPLookAndFeel::GetIntValue(IntID aID, int32_t& aResult) {
990 if (!sInitialized) {
991 Init();
994 if (const auto* cached = sIntCache.Get(aID)) {
995 if (cached->isNothing()) {
996 return NS_ERROR_FAILURE;
998 aResult = cached->value();
999 return NS_OK;
1002 if (NS_SUCCEEDED(Preferences::GetInt(sIntPrefs[size_t(aID)], &aResult))) {
1003 sIntCache.Insert(aID, Some(aResult));
1004 return NS_OK;
1007 if (NS_FAILED(NativeGetInt(aID, aResult))) {
1008 sIntCache.Insert(aID, Nothing());
1009 return NS_ERROR_FAILURE;
1012 sIntCache.Insert(aID, Some(aResult));
1013 return NS_OK;
1016 nsresult nsXPLookAndFeel::GetFloatValue(FloatID aID, float& aResult) {
1017 if (!sInitialized) {
1018 Init();
1021 if (const auto* cached = sFloatCache.Get(aID)) {
1022 if (cached->isNothing()) {
1023 return NS_ERROR_FAILURE;
1025 aResult = cached->value();
1026 return NS_OK;
1029 int32_t pref = 0;
1030 if (NS_SUCCEEDED(Preferences::GetInt(sFloatPrefs[size_t(aID)], &pref))) {
1031 aResult = float(pref) / 100.0f;
1032 sFloatCache.Insert(aID, Some(aResult));
1033 return NS_OK;
1036 if (NS_FAILED(NativeGetFloat(aID, aResult))) {
1037 sFloatCache.Insert(aID, Nothing());
1038 return NS_ERROR_FAILURE;
1041 sFloatCache.Insert(aID, Some(aResult));
1042 return NS_OK;
1045 bool nsXPLookAndFeel::LookAndFeelFontToStyle(const LookAndFeelFont& aFont,
1046 nsString& aName,
1047 gfxFontStyle& aStyle) {
1048 if (!aFont.haveFont()) {
1049 return false;
1051 aName = aFont.name();
1052 aStyle = gfxFontStyle();
1053 aStyle.size = aFont.size();
1054 aStyle.weight = FontWeight::FromInt(aFont.weight());
1055 aStyle.style =
1056 aFont.italic() ? FontSlantStyle::ITALIC : FontSlantStyle::NORMAL;
1057 aStyle.systemFont = true;
1058 return true;
1061 widget::LookAndFeelFont nsXPLookAndFeel::StyleToLookAndFeelFont(
1062 const nsAString& aName, const gfxFontStyle& aStyle) {
1063 LookAndFeelFont font;
1064 font.haveFont() = true;
1065 font.name() = aName;
1066 font.size() = aStyle.size;
1067 font.weight() = aStyle.weight.ToFloat();
1068 font.italic() = aStyle.style.IsItalic();
1069 MOZ_ASSERT(aStyle.style.IsNormal() || aStyle.style.IsItalic(),
1070 "Cannot handle oblique font style");
1071 #ifdef DEBUG
1073 // Assert that all the remaining font style properties have their
1074 // default values.
1075 gfxFontStyle candidate = aStyle;
1076 gfxFontStyle defaults{};
1077 candidate.size = defaults.size;
1078 candidate.weight = defaults.weight;
1079 candidate.style = defaults.style;
1080 MOZ_ASSERT(candidate.Equals(defaults),
1081 "Some font style properties not supported");
1083 #endif
1084 return font;
1087 bool nsXPLookAndFeel::GetFontValue(FontID aID, nsString& aName,
1088 gfxFontStyle& aStyle) {
1089 if (const LookAndFeelFont* cached = sFontCache.Get(aID)) {
1090 return LookAndFeelFontToStyle(*cached, aName, aStyle);
1093 LookAndFeelFont font;
1094 auto GetFontsFromPrefs = [&]() -> bool {
1095 nsDependentCString pref(sFontPrefs[size_t(aID)]);
1096 if (NS_FAILED(Preferences::GetString(pref.get(), aName))) {
1097 return false;
1099 font.haveFont() = true;
1100 font.name() = aName;
1101 font.size() = Preferences::GetFloat(nsAutoCString(pref + ".size"_ns).get());
1102 // This is written this way rather than using the fallback so that an empty
1103 // pref (such like the one about:config creates) doesn't cause system fonts
1104 // to have zero-size.
1105 if (font.size() < 1.0f) {
1106 font.size() = StyleFONT_MEDIUM_PX;
1108 font.weight() = Preferences::GetFloat(
1109 nsAutoCString(pref + ".weight"_ns).get(), FontWeight::NORMAL.ToFloat());
1110 font.italic() =
1111 Preferences::GetBool(nsAutoCString(pref + ".italic"_ns).get());
1112 return true;
1115 if (GetFontsFromPrefs()) {
1116 LookAndFeelFontToStyle(font, aName, aStyle);
1117 } else if (NativeGetFont(aID, aName, aStyle)) {
1118 font = StyleToLookAndFeelFont(aName, aStyle);
1119 } else {
1120 MOZ_ASSERT(!font.haveFont());
1122 bool success = font.haveFont();
1123 sFontCache.Insert(aID, std::move(font));
1124 return success;
1127 void nsXPLookAndFeel::RefreshImpl() {
1128 // Wipe out our caches.
1129 sColorCaches.Clear();
1130 sFontCache.Clear();
1131 sFloatCache.Clear();
1132 sIntCache.Clear();
1134 if (XRE_IsParentProcess()) {
1135 nsLayoutUtils::RecomputeSmoothScrollDefault();
1136 // Clear any cached FullLookAndFeel data, which is now invalid.
1137 widget::RemoteLookAndFeel::ClearCachedData();
1141 static bool sRecordedLookAndFeelTelemetry = false;
1143 void nsXPLookAndFeel::RecordTelemetry() {
1144 if (!XRE_IsParentProcess()) {
1145 return;
1148 if (sRecordedLookAndFeelTelemetry) {
1149 return;
1152 sRecordedLookAndFeelTelemetry = true;
1154 int32_t i;
1155 Telemetry::ScalarSet(
1156 Telemetry::ScalarID::WIDGET_DARK_MODE,
1157 NS_SUCCEEDED(GetIntValue(IntID::SystemUsesDarkTheme, i)) && i != 0);
1159 RecordLookAndFeelSpecificTelemetry();
1162 namespace mozilla {
1164 bool LookAndFeel::sGlobalThemeChanged;
1165 static widget::ThemeChangeKind sGlobalThemeChangeKind{0};
1167 void LookAndFeel::NotifyChangedAllWindows(widget::ThemeChangeKind aKind) {
1168 sGlobalThemeChanged = true;
1169 sGlobalThemeChangeKind |= aKind;
1171 if (nsCOMPtr<nsIObserverService> obs = services::GetObserverService()) {
1172 const char16_t kind[] = {char16_t(aKind), 0};
1173 obs->NotifyObservers(nullptr, "internal-look-and-feel-changed", kind);
1177 void LookAndFeel::DoHandleGlobalThemeChange() {
1178 MOZ_ASSERT(sGlobalThemeChanged);
1179 sGlobalThemeChanged = false;
1180 auto kind = std::exchange(sGlobalThemeChangeKind, widget::ThemeChangeKind(0));
1182 // Tell the theme that it changed, so it can flush any handles to stale theme
1183 // data.
1185 // We can use the *DoNotUseDirectly functions directly here, because we want
1186 // to notify all possible themes in a given process (but just once).
1187 if (XRE_IsParentProcess() ||
1188 !StaticPrefs::widget_non_native_theme_enabled()) {
1189 if (nsCOMPtr<nsITheme> theme = do_GetNativeThemeDoNotUseDirectly()) {
1190 theme->ThemeChanged();
1193 if (nsCOMPtr<nsITheme> theme = do_GetBasicNativeThemeDoNotUseDirectly()) {
1194 theme->ThemeChanged();
1197 // Clear all cached LookAndFeel colors.
1198 LookAndFeel::Refresh();
1200 // Reset default background and foreground colors for the document since they
1201 // may be using system colors, color scheme, etc.
1202 PreferenceSheet::Refresh();
1204 // Vector images (SVG) may be using theme colors so we discard all cached
1205 // surfaces. (We could add a vector image only version of DiscardAll, but
1206 // in bug 940625 we decided theme changes are rare enough not to bother.)
1207 image::SurfaceCacheUtils::DiscardAll();
1209 if (XRE_IsParentProcess()) {
1210 dom::ContentParent::BroadcastThemeUpdate(kind);
1213 nsContentUtils::AddScriptRunner(
1214 NS_NewRunnableFunction("HandleGlobalThemeChange", [] {
1215 if (nsCOMPtr<nsIObserverService> obs = services::GetObserverService()) {
1216 obs->NotifyObservers(nullptr, "look-and-feel-changed", nullptr);
1218 }));
1221 #define BIT_FOR(_c) (1ull << size_t(ColorID::_c))
1223 // We want to use a non-native color scheme for the non-native theme (except in
1224 // high-contrast mode), so spoof some of the colors with stand-ins to prevent
1225 // lack of contrast.
1226 static constexpr std::bitset<size_t(ColorID::End)> sNonNativeThemeStandinColors{
1227 // Used by default button styles.
1228 BIT_FOR(Buttonface) | BIT_FOR(Buttontext) | BIT_FOR(MozButtonhoverface) |
1229 BIT_FOR(MozButtonhovertext) | BIT_FOR(MozButtonactiveface) |
1230 BIT_FOR(MozButtonactivetext) | BIT_FOR(MozButtondisabledface) |
1231 BIT_FOR(Buttonborder) |
1232 // Used by select elements.
1233 BIT_FOR(MozCombobox) | BIT_FOR(MozComboboxtext) |
1234 BIT_FOR(Threedlightshadow) |
1235 // For symmetry with the above.
1236 BIT_FOR(Threeddarkshadow) |
1237 // Used by fieldset borders.
1238 BIT_FOR(Threedface) |
1239 // Used by input / textarea.
1240 BIT_FOR(Field) | BIT_FOR(Fieldtext) |
1241 // Used by disabled form controls.
1242 BIT_FOR(MozDisabledfield) | BIT_FOR(Graytext) |
1243 // Some pages expect these to return windows-like colors, see bug 1773795.
1244 // Also, per spec these should match Canvas/CanvasText, see
1245 // https://drafts.csswg.org/css-color-4/#window
1246 BIT_FOR(Window) | BIT_FOR(Windowtext)};
1247 #undef BIT_FOR
1249 static bool ShouldUseStandinsForNativeColorForNonNativeTheme(
1250 const dom::Document& aDoc, LookAndFeel::ColorID aColor,
1251 const PreferenceSheet::Prefs& aPrefs) {
1252 const bool shouldUseStandinsForColor = [&] {
1253 if (sNonNativeThemeStandinColors[size_t(aColor)]) {
1254 return true;
1256 // There are platforms where we want the content-exposed accent color to be
1257 // the windows blue rather than the system accent color, for now.
1258 return !StaticPrefs::widget_non_native_theme_use_theme_accent() &&
1259 (aColor == LookAndFeel::ColorID::Accentcolor ||
1260 aColor == LookAndFeel::ColorID::Accentcolortext);
1261 }();
1263 return shouldUseStandinsForColor && aDoc.ShouldAvoidNativeTheme() &&
1264 !aPrefs.NonNativeThemeShouldBeHighContrast();
1267 bool LookAndFeel::IsDarkColor(nscolor aColor) {
1268 // Given https://www.w3.org/TR/WCAG20/#contrast-ratiodef, this is the
1269 // threshold that tells us whether contrast is better against white or black.
1271 // Contrast ratio against black is: (L + 0.05) / 0.05
1272 // Contrast ratio against white is: 1.05 / (L + 0.05)
1274 // So the intersection is:
1276 // (L + 0.05) / 0.05 = 1.05 / (L + 0.05)
1278 // And the solution to that equation is:
1280 // sqrt(1.05 * 0.05) - 0.05
1282 // So we consider a color dark if the contrast is below this threshold, and
1283 // it's at least half-opaque.
1284 constexpr float kThreshold = 0.179129;
1285 return NS_GET_A(aColor) > 127 &&
1286 RelativeLuminanceUtils::Compute(aColor) < kThreshold;
1289 ColorScheme LookAndFeel::ColorSchemeForStyle(
1290 const dom::Document& aDoc, const StyleColorSchemeFlags& aFlags,
1291 ColorSchemeMode aMode) {
1292 const auto& prefs = PreferenceSheet::PrefsFor(aDoc);
1293 StyleColorSchemeFlags style(aFlags);
1294 if (!style) {
1295 style._0 = aDoc.GetColorSchemeBits();
1297 const bool supportsDark = bool(style & StyleColorSchemeFlags::DARK);
1298 const bool supportsLight = bool(style & StyleColorSchemeFlags::LIGHT);
1299 if (supportsLight && supportsDark) {
1300 // Both color-schemes are explicitly supported, use the preferred one.
1301 return aDoc.PreferredColorScheme();
1303 if (supportsDark || supportsLight) {
1304 // One color-scheme is explicitly supported and one isn't, so use the one
1305 // the content supports.
1306 return supportsDark ? ColorScheme::Dark : ColorScheme::Light;
1308 // No value specified. Chrome docs, and forced-colors mode always supports
1309 // both, so use the preferred color-scheme.
1310 if (aMode == ColorSchemeMode::Preferred || aDoc.ChromeRulesEnabled() ||
1311 !prefs.mUseDocumentColors) {
1312 return aDoc.PreferredColorScheme();
1314 // Otherwise default content to light.
1315 return ColorScheme::Light;
1318 LookAndFeel::ColorScheme LookAndFeel::ColorSchemeForFrame(
1319 const nsIFrame* aFrame, ColorSchemeMode aMode) {
1320 return ColorSchemeForStyle(*aFrame->PresContext()->Document(),
1321 aFrame->StyleUI()->mColorScheme.bits, aMode);
1324 // static
1325 Maybe<nscolor> LookAndFeel::GetColor(ColorID aId, ColorScheme aScheme,
1326 UseStandins aUseStandins) {
1327 nscolor result;
1328 nsresult rv = nsLookAndFeel::GetInstance()->GetColorValue(
1329 aId, aScheme, aUseStandins, result);
1330 if (NS_FAILED(rv)) {
1331 return Nothing();
1333 return Some(result);
1336 // Returns whether there is a CSS color name for this color.
1337 static bool ColorIsCSSAccessible(LookAndFeel::ColorID aId) {
1338 using ColorID = LookAndFeel::ColorID;
1340 switch (aId) {
1341 case ColorID::TextSelectDisabledBackground:
1342 case ColorID::TextSelectAttentionBackground:
1343 case ColorID::TextSelectAttentionForeground:
1344 case ColorID::TextHighlightBackground:
1345 case ColorID::TextHighlightForeground:
1346 case ColorID::ThemedScrollbar:
1347 case ColorID::ThemedScrollbarInactive:
1348 case ColorID::ThemedScrollbarThumb:
1349 case ColorID::ThemedScrollbarThumbActive:
1350 case ColorID::ThemedScrollbarThumbInactive:
1351 case ColorID::ThemedScrollbarThumbHover:
1352 case ColorID::IMERawInputBackground:
1353 case ColorID::IMERawInputForeground:
1354 case ColorID::IMERawInputUnderline:
1355 case ColorID::IMESelectedRawTextBackground:
1356 case ColorID::IMESelectedRawTextForeground:
1357 case ColorID::IMESelectedRawTextUnderline:
1358 case ColorID::IMEConvertedTextBackground:
1359 case ColorID::IMEConvertedTextForeground:
1360 case ColorID::IMEConvertedTextUnderline:
1361 case ColorID::IMESelectedConvertedTextBackground:
1362 case ColorID::IMESelectedConvertedTextForeground:
1363 case ColorID::IMESelectedConvertedTextUnderline:
1364 case ColorID::SpellCheckerUnderline:
1365 return false;
1366 default:
1367 break;
1370 return true;
1373 LookAndFeel::UseStandins LookAndFeel::ShouldUseStandins(
1374 const dom::Document& aDoc, ColorID aId) {
1375 const auto& prefs = PreferenceSheet::PrefsFor(aDoc);
1376 if (ShouldUseStandinsForNativeColorForNonNativeTheme(aDoc, aId, prefs)) {
1377 return UseStandins::Yes;
1379 if (prefs.mUseStandins && ColorIsCSSAccessible(aId)) {
1380 return UseStandins::Yes;
1382 return UseStandins::No;
1385 Maybe<nscolor> LookAndFeel::GetColor(ColorID aId, const nsIFrame* aFrame) {
1386 const auto* doc = aFrame->PresContext()->Document();
1387 return GetColor(aId, ColorSchemeForFrame(aFrame),
1388 ShouldUseStandins(*doc, aId));
1391 // static
1392 nsresult LookAndFeel::GetInt(IntID aID, int32_t* aResult) {
1393 return nsLookAndFeel::GetInstance()->GetIntValue(aID, *aResult);
1396 // static
1397 nsresult LookAndFeel::GetFloat(FloatID aID, float* aResult) {
1398 return nsLookAndFeel::GetInstance()->GetFloatValue(aID, *aResult);
1401 // static
1402 bool LookAndFeel::GetFont(FontID aID, nsString& aName, gfxFontStyle& aStyle) {
1403 return nsLookAndFeel::GetInstance()->GetFontValue(aID, aName, aStyle);
1406 // static
1407 char16_t LookAndFeel::GetPasswordCharacter() {
1408 return nsLookAndFeel::GetInstance()->GetPasswordCharacterImpl();
1411 // static
1412 bool LookAndFeel::GetEchoPassword() {
1413 if (StaticPrefs::editor_password_mask_delay() >= 0) {
1414 return StaticPrefs::editor_password_mask_delay() > 0;
1416 return nsLookAndFeel::GetInstance()->GetEchoPasswordImpl();
1419 // static
1420 uint32_t LookAndFeel::GetPasswordMaskDelay() {
1421 int32_t delay = StaticPrefs::editor_password_mask_delay();
1422 if (delay < 0) {
1423 return nsLookAndFeel::GetInstance()->GetPasswordMaskDelayImpl();
1425 return delay;
1428 bool LookAndFeel::DrawInTitlebar() {
1429 switch (StaticPrefs::browser_tabs_inTitlebar()) {
1430 case 0:
1431 return false;
1432 case 1:
1433 return true;
1434 default:
1435 break;
1437 return nsLookAndFeel::GetInstance()->GetDefaultDrawInTitlebar();
1440 void LookAndFeel::GetThemeInfo(nsACString& aOut) {
1441 nsLookAndFeel::GetInstance()->GetThemeInfo(aOut);
1444 uint32_t LookAndFeel::GetMenuAccessKey() {
1445 return StaticPrefs::ui_key_menuAccessKey();
1448 Modifiers LookAndFeel::GetMenuAccessKeyModifiers() {
1449 switch (GetMenuAccessKey()) {
1450 case dom::KeyboardEvent_Binding::DOM_VK_SHIFT:
1451 return MODIFIER_SHIFT;
1452 case dom::KeyboardEvent_Binding::DOM_VK_CONTROL:
1453 return MODIFIER_CONTROL;
1454 case dom::KeyboardEvent_Binding::DOM_VK_ALT:
1455 return MODIFIER_ALT;
1456 case dom::KeyboardEvent_Binding::DOM_VK_META:
1457 case dom::KeyboardEvent_Binding::DOM_VK_WIN:
1458 return MODIFIER_META;
1459 default:
1460 return 0;
1464 // static
1465 void LookAndFeel::Refresh() {
1466 nsLookAndFeel::GetInstance()->RefreshImpl();
1467 widget::Theme::LookAndFeelChanged();
1470 // static
1471 void LookAndFeel::NativeInit() { nsLookAndFeel::GetInstance()->NativeInit(); }
1473 // static
1474 void LookAndFeel::SetData(widget::FullLookAndFeel&& aTables) {
1475 nsLookAndFeel::GetInstance()->SetDataImpl(std::move(aTables));
1478 } // namespace mozilla