1 /* -*- Mode: C++; tab-width: 20; 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/. */
5
6 #define PANGO_ENABLE_BACKEND
7 #define PANGO_ENABLE_ENGINE
8
9 #include "gfxPlatformGtk.h"
10
11 #include <gtk/gtk.h>
12 #include <fontconfig/fontconfig.h>
13
14 #include "base/task.h"
15 #include "base/thread.h"
16 #include "base/message_loop.h"
17 #include "cairo.h"
18 #include "gfx2DGlue.h"
19 #include "gfxFcPlatformFontList.h"
20 #include "gfxConfig.h"
21 #include "gfxContext.h"
22 #include "gfxImageSurface.h"
23 #include "gfxUserFontSet.h"
24 #include "gfxUtils.h"
25 #include "gfxFT2FontBase.h"
26 #include "gfxTextRun.h"
27 #include "GLContextProvider.h"
28 #include "mozilla/Atomics.h"
29 #include "mozilla/Components.h"
30 #include "mozilla/dom/ContentChild.h"
31 #include "mozilla/FontPropertyTypes.h"
32 #include "mozilla/gfx/2D.h"
33 #include "mozilla/gfx/Logging.h"
34 #include "mozilla/gfx/XlibDisplay.h"
35 #include "mozilla/Monitor.h"
36 #include "mozilla/Preferences.h"
37 #include "mozilla/StaticPrefs_gfx.h"
38 #include "mozilla/StaticPrefs_layers.h"
39 #include "nsAppRunner.h"
40 #include "nsIGfxInfo.h"
41 #include "nsMathUtils.h"
42 #include "nsUnicharUtils.h"
43 #include "nsUnicodeProperties.h"
44 #include "VsyncSource.h"
45
46 #ifdef MOZ_X11
47 # include <gdk/gdkx.h>
48 # include "cairo-xlib.h"
49 # include "gfxXlibSurface.h"
50 # include "GLContextGLX.h"
51 # include "GLXLibrary.h"
52 # include "mozilla/X11Util.h"
53
54 /* Undefine the Status from Xlib since it will conflict with system headers on
55 * OSX */
56 # if defined(__APPLE__) && defined(Status)
57 # undef Status
58 # endif
59 #endif /* MOZ_X11 */
60
61 #ifdef MOZ_WAYLAND
62 # include <gdk/gdkwayland.h>
63 # include "mozilla/widget/nsWaylandDisplay.h"
64 # include "mozilla/widget/DMABufLibWrapper.h"
65 # include "mozilla/StaticPrefs_widget.h"
66 #endif
67
68 #define GDK_PIXMAP_SIZE_MAX 32767
69
70 #define GFX_PREF_MAX_GENERIC_SUBSTITUTIONS \
71 "gfx.font_rendering.fontconfig.max_generic_substitutions"
72
73 using namespace mozilla;
74 using namespace mozilla::gfx;
75 using namespace mozilla::unicode;
76 using namespace mozilla::widget;
77
78 static FT_Library gPlatformFTLibrary = nullptr;
79 static int32_t sDPI;
80
screen_resolution_changed(GdkScreen * aScreen,GParamSpec * aPspec,gpointer aClosure)81 static void screen_resolution_changed(GdkScreen* aScreen, GParamSpec* aPspec,
82 gpointer aClosure) {
83 sDPI = 0;
84 }
85
86 #if defined(MOZ_X11)
87 // TODO(aosmond): The envvar is deprecated. We should remove it once EGL is the
88 // default in release.
IsX11EGLEnvvarEnabled()89 static bool IsX11EGLEnvvarEnabled() {
90 const char* eglPref = PR_GetEnv("MOZ_X11_EGL");
91 return (eglPref && *eglPref);
92 }
93 #endif
94
gfxPlatformGtk()95 gfxPlatformGtk::gfxPlatformGtk() {
96 if (!gfxPlatform::IsHeadless()) {
97 gtk_init(nullptr, nullptr);
98 }
99
100 mMaxGenericSubstitutions = UNINITIALIZED_VALUE;
101 mIsX11Display = gfxPlatform::IsHeadless() ? false : GdkIsX11Display();
102 if (XRE_IsParentProcess()) {
103 #ifdef MOZ_X11
104 if (mIsX11Display && mozilla::Preferences::GetBool("gfx.xrender.enabled")) {
105 gfxVars::SetUseXRender(true);
106 }
107 #endif
108
109 InitX11EGLConfig();
110 if (IsWaylandDisplay() || gfxConfig::IsEnabled(Feature::X11_EGL)) {
111 gfxVars::SetUseEGL(true);
112 }
113
114 InitDmabufConfig();
115 if (gfxConfig::IsEnabled(Feature::DMABUF)) {
116 gfxVars::SetUseDMABuf(true);
117 }
118 }
119
120 #ifdef MOZ_WAYLAND
121 mUseWebGLDmabufBackend = true;
122 #endif
123
124 InitBackendPrefs(GetBackendPrefs());
125
126 gPlatformFTLibrary = Factory::NewFTLibrary();
127 MOZ_RELEASE_ASSERT(gPlatformFTLibrary);
128 Factory::SetFTLibrary(gPlatformFTLibrary);
129
130 GdkScreen* gdkScreen = gdk_screen_get_default();
131 if (gdkScreen) {
132 g_signal_connect(gdkScreen, "notify::resolution",
133 G_CALLBACK(screen_resolution_changed), nullptr);
134 }
135
136 // Bug 1714483: Force disable FXAA Antialiasing on NV drivers. This is a
137 // temporary workaround for a driver bug.
138 PR_SetEnv("__GL_ALLOW_FXAA_USAGE=0");
139 }
140
~gfxPlatformGtk()141 gfxPlatformGtk::~gfxPlatformGtk() {
142 Factory::ReleaseFTLibrary(gPlatformFTLibrary);
143 gPlatformFTLibrary = nullptr;
144 }
145
InitX11EGLConfig()146 void gfxPlatformGtk::InitX11EGLConfig() {
147 FeatureState& feature = gfxConfig::GetFeature(Feature::X11_EGL);
148 #ifdef MOZ_X11
149 feature.EnableByDefault();
150
151 if (StaticPrefs::gfx_x11_egl_force_enabled_AtStartup()) {
152 feature.UserForceEnable("Force enabled by pref");
153 } else if (IsX11EGLEnvvarEnabled()) {
154 feature.UserForceEnable("Force enabled by envvar");
155 } else if (StaticPrefs::gfx_x11_egl_force_disabled_AtStartup()) {
156 feature.UserDisable("Force disabled by pref",
157 "FEATURE_FAILURE_USER_FORCE_DISABLED"_ns);
158 }
159
160 nsCString failureId;
161 int32_t status;
162 nsCOMPtr<nsIGfxInfo> gfxInfo = components::GfxInfo::Service();
163 if (NS_FAILED(gfxInfo->GetFeatureStatus(nsIGfxInfo::FEATURE_X11_EGL,
164 failureId, &status))) {
165 feature.Disable(FeatureStatus::BlockedNoGfxInfo, "gfxInfo is broken",
166 "FEATURE_FAILURE_NO_GFX_INFO"_ns);
167 } else if (status != nsIGfxInfo::FEATURE_STATUS_OK) {
168 feature.Disable(FeatureStatus::Blocklisted, "Blocklisted by gfxInfo",
169 failureId);
170 }
171
172 nsAutoString testType;
173 gfxInfo->GetTestType(testType);
174 // We can only use X11/EGL if we actually found the EGL library and
175 // successfully use it to determine system information in glxtest.
176 if (testType != u"EGL") {
177 feature.ForceDisable(FeatureStatus::Broken, "glxtest could not use EGL",
178 "FEATURE_FAILURE_GLXTEST_NO_EGL"_ns);
179 }
180 #else
181 feature.DisableByDefault(FeatureStatus::Unavailable, "X11 support missing",
182 "FEATURE_FAILURE_NO_X11"_ns);
183 #endif
184 }
185
InitDmabufConfig()186 void gfxPlatformGtk::InitDmabufConfig() {
187 FeatureState& feature = gfxConfig::GetFeature(Feature::DMABUF);
188 #ifdef MOZ_WAYLAND
189 feature.EnableByDefault();
190
191 if (StaticPrefs::widget_dmabuf_force_enabled_AtStartup()) {
192 feature.UserForceEnable("Force enabled by pref");
193 }
194
195 nsCString failureId;
196 int32_t status;
197 nsCOMPtr<nsIGfxInfo> gfxInfo = components::GfxInfo::Service();
198 if (NS_FAILED(gfxInfo->GetFeatureStatus(nsIGfxInfo::FEATURE_DMABUF, failureId,
199 &status))) {
200 feature.Disable(FeatureStatus::BlockedNoGfxInfo, "gfxInfo is broken",
201 "FEATURE_FAILURE_NO_GFX_INFO"_ns);
202 } else if (status != nsIGfxInfo::FEATURE_STATUS_OK) {
203 feature.Disable(FeatureStatus::Blocklisted, "Blocklisted by gfxInfo",
204 failureId);
205 }
206
207 if (!gfxVars::UseEGL()) {
208 feature.ForceDisable(FeatureStatus::Unavailable, "Requires EGL",
209 "FEATURE_FAILURE_REQUIRES_EGL"_ns);
210 }
211
212 if (feature.IsEnabled()) {
213 nsAutoCString drmRenderDevice;
214 gfxInfo->GetDrmRenderDevice(drmRenderDevice);
215 gfxVars::SetDrmRenderDevice(drmRenderDevice);
216
217 if (!GetDMABufDevice()->Configure(failureId)) {
218 feature.ForceDisable(FeatureStatus::Failed, "Failed to configure",
219 failureId);
220 }
221 }
222 #else
223 feature.DisableByDefault(FeatureStatus::Unavailable,
224 "Wayland support missing",
225 "FEATURE_FAILURE_NO_WAYLAND"_ns);
226 #endif
227 }
228
InitWebRenderConfig()229 void gfxPlatformGtk::InitWebRenderConfig() {
230 gfxPlatform::InitWebRenderConfig();
231
232 if (!XRE_IsParentProcess()) {
233 return;
234 }
235
236 FeatureState& feature = gfxConfig::GetFeature(Feature::WEBRENDER_COMPOSITOR);
237 if (feature.IsEnabled()) {
238 if (!(gfxConfig::IsEnabled(Feature::WEBRENDER) ||
239 gfxConfig::IsEnabled(Feature::WEBRENDER_SOFTWARE))) {
240 feature.ForceDisable(FeatureStatus::Unavailable, "WebRender disabled",
241 "FEATURE_FAILURE_WR_DISABLED"_ns);
242 } else if (!IsWaylandDisplay()) {
243 feature.ForceDisable(FeatureStatus::Unavailable,
244 "Wayland support missing",
245 "FEATURE_FAILURE_NO_WAYLAND"_ns);
246 }
247 #ifdef MOZ_WAYLAND
248 else if (!widget::WaylandDisplayGet()->GetViewporter()) {
249 feature.ForceDisable(FeatureStatus::Unavailable,
250 "Requires wp_viewporter protocol support",
251 "FEATURE_FAILURE_REQUIRES_WPVIEWPORTER"_ns);
252 }
253 #endif
254 }
255 gfxVars::SetUseWebRenderCompositor(feature.IsEnabled());
256 }
257
InitPlatformGPUProcessPrefs()258 void gfxPlatformGtk::InitPlatformGPUProcessPrefs() {
259 #ifdef MOZ_WAYLAND
260 if (IsWaylandDisplay()) {
261 FeatureState& gpuProc = gfxConfig::GetFeature(Feature::GPU_PROCESS);
262 gpuProc.ForceDisable(FeatureStatus::Blocked,
263 "Wayland does not work in the GPU process",
264 "FEATURE_FAILURE_WAYLAND"_ns);
265 }
266 #endif
267 }
268
CreateOffscreenSurface(const IntSize & aSize,gfxImageFormat aFormat)269 already_AddRefed<gfxASurface> gfxPlatformGtk::CreateOffscreenSurface(
270 const IntSize& aSize, gfxImageFormat aFormat) {
271 if (!Factory::AllowedSurfaceSize(aSize)) {
272 return nullptr;
273 }
274
275 RefPtr<gfxASurface> newSurface;
276 bool needsClear = true;
277 #ifdef MOZ_X11
278 // XXX we really need a different interface here, something that passes
279 // in more context, including the display and/or target surface type that
280 // we should try to match
281 GdkScreen* gdkScreen = gdk_screen_get_default();
282 if (gdkScreen) {
283 // When forcing PaintedLayers to use image surfaces for content,
284 // force creation of gfxImageSurface surfaces.
285 if (gfxVars::UseXRender() && !UseImageOffscreenSurfaces()) {
286 Screen* screen = gdk_x11_screen_get_xscreen(gdkScreen);
287 XRenderPictFormat* xrenderFormat =
288 gfxXlibSurface::FindRenderFormat(DisplayOfScreen(screen), aFormat);
289
290 if (xrenderFormat) {
291 newSurface = gfxXlibSurface::Create(screen, xrenderFormat, aSize);
292 }
293 } else {
294 // We're not going to use XRender, so we don't need to
295 // search for a render format
296 newSurface = new gfxImageSurface(aSize, aFormat);
297 // The gfxImageSurface ctor zeroes this for us, no need to
298 // waste time clearing again
299 needsClear = false;
300 }
301 }
302 #endif
303
304 if (!newSurface) {
305 // We couldn't create a native surface for whatever reason;
306 // e.g., no display, no RENDER, bad size, etc.
307 // Fall back to image surface for the data.
308 newSurface = new gfxImageSurface(aSize, aFormat);
309 }
310
311 if (newSurface->CairoStatus()) {
312 newSurface = nullptr; // surface isn't valid for some reason
313 }
314
315 if (newSurface && needsClear) {
316 gfxUtils::ClearThebesSurface(newSurface);
317 }
318
319 return newSurface.forget();
320 }
321
GetFontList(nsAtom * aLangGroup,const nsACString & aGenericFamily,nsTArray<nsString> & aListOfFonts)322 nsresult gfxPlatformGtk::GetFontList(nsAtom* aLangGroup,
323 const nsACString& aGenericFamily,
324 nsTArray<nsString>& aListOfFonts) {
325 gfxPlatformFontList::PlatformFontList()->GetFontList(
326 aLangGroup, aGenericFamily, aListOfFonts);
327 return NS_OK;
328 }
329
330 // xxx - this is ubuntu centric, need to go through other distros and flesh
331 // out a more general list
332 static const char kFontDejaVuSans[] = "DejaVu Sans";
333 static const char kFontDejaVuSerif[] = "DejaVu Serif";
334 static const char kFontFreeSans[] = "FreeSans";
335 static const char kFontFreeSerif[] = "FreeSerif";
336 static const char kFontTakaoPGothic[] = "TakaoPGothic";
337 static const char kFontTwemojiMozilla[] = "Twemoji Mozilla";
338 static const char kFontDroidSansFallback[] = "Droid Sans Fallback";
339 static const char kFontWenQuanYiMicroHei[] = "WenQuanYi Micro Hei";
340 static const char kFontNanumGothic[] = "NanumGothic";
341 static const char kFontSymbola[] = "Symbola";
342 static const char kFontNotoSansSymbols[] = "Noto Sans Symbols";
343 static const char kFontNotoSansSymbols2[] = "Noto Sans Symbols2";
344
GetCommonFallbackFonts(uint32_t aCh,Script aRunScript,eFontPresentation aPresentation,nsTArray<const char * > & aFontList)345 void gfxPlatformGtk::GetCommonFallbackFonts(uint32_t aCh, Script aRunScript,
346 eFontPresentation aPresentation,
347 nsTArray<const char*>& aFontList) {
348 if (PrefersColor(aPresentation)) {
349 aFontList.AppendElement(kFontTwemojiMozilla);
350 }
351
352 aFontList.AppendElement(kFontDejaVuSerif);
353 aFontList.AppendElement(kFontFreeSerif);
354 aFontList.AppendElement(kFontDejaVuSans);
355 aFontList.AppendElement(kFontFreeSans);
356 aFontList.AppendElement(kFontSymbola);
357 aFontList.AppendElement(kFontNotoSansSymbols);
358 aFontList.AppendElement(kFontNotoSansSymbols2);
359
360 // add fonts for CJK ranges
361 // xxx - this isn't really correct, should use the same CJK font ordering
362 // as the pref font code
363 if (aCh >= 0x3000 && ((aCh < 0xe000) || (aCh >= 0xf900 && aCh < 0xfff0) ||
364 ((aCh >> 16) == 2))) {
365 aFontList.AppendElement(kFontTakaoPGothic);
366 aFontList.AppendElement(kFontDroidSansFallback);
367 aFontList.AppendElement(kFontWenQuanYiMicroHei);
368 aFontList.AppendElement(kFontNanumGothic);
369 }
370 }
371
ReadSystemFontList(mozilla::dom::SystemFontList * retValue)372 void gfxPlatformGtk::ReadSystemFontList(
373 mozilla::dom::SystemFontList* retValue) {
374 gfxFcPlatformFontList::PlatformFontList()->ReadSystemFontList(retValue);
375 }
376
CreatePlatformFontList()377 bool gfxPlatformGtk::CreatePlatformFontList() {
378 return gfxPlatformFontList::Initialize(new gfxFcPlatformFontList);
379 }
380
GetFontScaleDPI()381 int32_t gfxPlatformGtk::GetFontScaleDPI() {
382 MOZ_ASSERT(XRE_IsParentProcess(),
383 "You can access this via LookAndFeel if you need it in child "
384 "processes");
385 if (MOZ_LIKELY(sDPI != 0)) {
386 return sDPI;
387 }
388 GdkScreen* screen = gdk_screen_get_default();
389 // Ensure settings in config files are processed.
390 gtk_settings_get_for_screen(screen);
391 int32_t dpi = int32_t(round(gdk_screen_get_resolution(screen)));
392 if (dpi <= 0) {
393 // Fall back to something sane
394 dpi = 96;
395 }
396 sDPI = dpi;
397 return dpi;
398 }
399
GetFontScaleFactor()400 double gfxPlatformGtk::GetFontScaleFactor() {
401 // Integer scale factors work well with GTK window scaling, image scaling, and
402 // pixel alignment, but there is a range where 1 is too small and 2 is too
403 // big.
404 //
405 // An additional step of 1.5 is added because this is common scale on WINNT
406 // and at this ratio the advantages of larger rendering outweigh the
407 // disadvantages from scaling and pixel mis-alignment.
408 //
409 // A similar step for 1.25 is added as well, because this is the scale that
410 // "Large text" settings use in gnome, and it seems worth to allow, especially
411 // on already-hidpi environments.
412 int32_t dpi = GetFontScaleDPI();
413 if (dpi < 120) {
414 return 1.0;
415 }
416 if (dpi < 132) {
417 return 1.25;
418 }
419 if (dpi < 168) {
420 return 1.5;
421 }
422 return round(dpi / 96.0);
423 }
424
UseImageOffscreenSurfaces()425 bool gfxPlatformGtk::UseImageOffscreenSurfaces() {
426 return GetDefaultContentBackend() != mozilla::gfx::BackendType::CAIRO ||
427 StaticPrefs::layers_use_image_offscreen_surfaces_AtStartup();
428 }
429
GetOffscreenFormat()430 gfxImageFormat gfxPlatformGtk::GetOffscreenFormat() {
431 // Make sure there is a screen
432 GdkScreen* screen = gdk_screen_get_default();
433 if (screen && gdk_visual_get_depth(gdk_visual_get_system()) == 16) {
434 return SurfaceFormat::R5G6B5_UINT16;
435 }
436
437 return SurfaceFormat::X8R8G8B8_UINT32;
438 }
439
FontsPrefsChanged(const char * aPref)440 void gfxPlatformGtk::FontsPrefsChanged(const char* aPref) {
441 // only checking for generic substitions, pass other changes up
442 if (strcmp(GFX_PREF_MAX_GENERIC_SUBSTITUTIONS, aPref) != 0) {
443 gfxPlatform::FontsPrefsChanged(aPref);
444 return;
445 }
446
447 mMaxGenericSubstitutions = UNINITIALIZED_VALUE;
448 gfxFcPlatformFontList* pfl = gfxFcPlatformFontList::PlatformFontList();
449 pfl->ClearGenericMappings();
450 FlushFontAndWordCaches();
451 }
452
MaxGenericSubstitions()453 uint32_t gfxPlatformGtk::MaxGenericSubstitions() {
454 if (mMaxGenericSubstitutions == UNINITIALIZED_VALUE) {
455 mMaxGenericSubstitutions =
456 Preferences::GetInt(GFX_PREF_MAX_GENERIC_SUBSTITUTIONS, 3);
457 if (mMaxGenericSubstitutions < 0) {
458 mMaxGenericSubstitutions = 3;
459 }
460 }
461
462 return uint32_t(mMaxGenericSubstitutions);
463 }
464
AccelerateLayersByDefault()465 bool gfxPlatformGtk::AccelerateLayersByDefault() { return true; }
466
467 #ifdef MOZ_WAYLAND
UseDMABufWebGL()468 bool gfxPlatformGtk::UseDMABufWebGL() {
469 static bool dmabufAvailable = []() {
470 return gfxVars::UseDMABuf() && GetDMABufDevice()->IsDMABufWebGLEnabled();
471 }();
472 return dmabufAvailable && mUseWebGLDmabufBackend;
473 }
474 #endif
475
476 #if defined(MOZ_X11)
477
GetDisplayICCProfile(Display * dpy,Window & root)478 static nsTArray<uint8_t> GetDisplayICCProfile(Display* dpy, Window& root) {
479 const char kIccProfileAtomName[] = "_ICC_PROFILE";
480 Atom iccAtom = XInternAtom(dpy, kIccProfileAtomName, TRUE);
481 if (!iccAtom) {
482 return nsTArray<uint8_t>();
483 }
484
485 Atom retAtom;
486 int retFormat;
487 unsigned long retLength, retAfter;
488 unsigned char* retProperty;
489
490 if (XGetWindowProperty(dpy, root, iccAtom, 0, INT_MAX /* length */, X11False,
491 AnyPropertyType, &retAtom, &retFormat, &retLength,
492 &retAfter, &retProperty) != Success) {
493 return nsTArray<uint8_t>();
494 }
495
496 nsTArray<uint8_t> result;
497
498 if (retLength > 0) {
499 result.AppendElements(static_cast<uint8_t*>(retProperty), retLength);
500 }
501
502 XFree(retProperty);
503
504 return result;
505 }
506
GetPlatformCMSOutputProfileData()507 nsTArray<uint8_t> gfxPlatformGtk::GetPlatformCMSOutputProfileData() {
508 nsTArray<uint8_t> prefProfileData = GetPrefCMSOutputProfileData();
509 if (!prefProfileData.IsEmpty()) {
510 return prefProfileData;
511 }
512
513 if (XRE_IsContentProcess()) {
514 MOZ_ASSERT(NS_IsMainThread());
515 // This will be passed in during InitChild so we can avoid sending a
516 // sync message back to the parent during init.
517 const mozilla::gfx::ContentDeviceData* contentDeviceData =
518 GetInitContentDeviceData();
519 if (contentDeviceData) {
520 // On Windows, we assert that the profile isn't empty, but on
521 // Linux it can legitimately be empty if the display isn't
522 // calibrated. Thus, no assertion here.
523 return contentDeviceData->cmsOutputProfileData().Clone();
524 }
525
526 // Otherwise we need to ask the parent for the updated color profile
527 mozilla::dom::ContentChild* cc = mozilla::dom::ContentChild::GetSingleton();
528 nsTArray<uint8_t> result;
529 Unused << cc->SendGetOutputColorProfileData(&result);
530 return result;
531 }
532
533 if (!mIsX11Display) {
534 return nsTArray<uint8_t>();
535 }
536
537 GdkDisplay* display = gdk_display_get_default();
538 Display* dpy = GDK_DISPLAY_XDISPLAY(display);
539 // In xpcshell tests, we never initialize X and hence don't have a Display.
540 // In this case, there's no output colour management to be done, so we just
541 // return with nullptr.
542 if (!dpy) {
543 return nsTArray<uint8_t>();
544 }
545
546 Window root = gdk_x11_get_default_root_xwindow();
547
548 // First try ICC Profile
549 nsTArray<uint8_t> iccResult = GetDisplayICCProfile(dpy, root);
550 if (!iccResult.IsEmpty()) {
551 return iccResult;
552 }
553
554 // If ICC doesn't work, then try EDID
555 const char kEdid1AtomName[] = "XFree86_DDC_EDID1_RAWDATA";
556 Atom edidAtom = XInternAtom(dpy, kEdid1AtomName, TRUE);
557 if (!edidAtom) {
558 return nsTArray<uint8_t>();
559 }
560
561 Atom retAtom;
562 int retFormat;
563 unsigned long retLength, retAfter;
564 unsigned char* retProperty;
565
566 if (XGetWindowProperty(dpy, root, edidAtom, 0, 32, X11False, AnyPropertyType,
567 &retAtom, &retFormat, &retLength, &retAfter,
568 &retProperty) != Success) {
569 return nsTArray<uint8_t>();
570 }
571
572 if (retLength != 128) {
573 return nsTArray<uint8_t>();
574 }
575
576 // Format documented in "VESA E-EDID Implementation Guide"
577 float gamma = (100 + (float)retProperty[0x17]) / 100.0f;
578
579 qcms_CIE_xyY whitePoint;
580 whitePoint.x =
581 ((retProperty[0x21] << 2) | (retProperty[0x1a] >> 2 & 3)) / 1024.0;
582 whitePoint.y =
583 ((retProperty[0x22] << 2) | (retProperty[0x1a] >> 0 & 3)) / 1024.0;
584 whitePoint.Y = 1.0;
585
586 qcms_CIE_xyYTRIPLE primaries;
587 primaries.red.x =
588 ((retProperty[0x1b] << 2) | (retProperty[0x19] >> 6 & 3)) / 1024.0;
589 primaries.red.y =
590 ((retProperty[0x1c] << 2) | (retProperty[0x19] >> 4 & 3)) / 1024.0;
591 primaries.red.Y = 1.0;
592
593 primaries.green.x =
594 ((retProperty[0x1d] << 2) | (retProperty[0x19] >> 2 & 3)) / 1024.0;
595 primaries.green.y =
596 ((retProperty[0x1e] << 2) | (retProperty[0x19] >> 0 & 3)) / 1024.0;
597 primaries.green.Y = 1.0;
598
599 primaries.blue.x =
600 ((retProperty[0x1f] << 2) | (retProperty[0x1a] >> 6 & 3)) / 1024.0;
601 primaries.blue.y =
602 ((retProperty[0x20] << 2) | (retProperty[0x1a] >> 4 & 3)) / 1024.0;
603 primaries.blue.Y = 1.0;
604
605 XFree(retProperty);
606
607 void* mem = nullptr;
608 size_t size = 0;
609 qcms_data_create_rgb_with_gamma(whitePoint, primaries, gamma, &mem, &size);
610 if (!mem) {
611 return nsTArray<uint8_t>();
612 }
613
614 nsTArray<uint8_t> result;
615 result.AppendElements(static_cast<uint8_t*>(mem), size);
616 free(mem);
617
618 // XXX: It seems like we get wrong colors when using this constructed profile:
619 // See bug 1696819. For now just forget that we made it.
620 return nsTArray<uint8_t>();
621 }
622
623 #else // defined(MOZ_X11)
624
GetPlatformCMSOutputProfileData()625 nsTArray<uint8_t> gfxPlatformGtk::GetPlatformCMSOutputProfileData() {
626 return nsTArray<uint8_t>();
627 }
628
629 #endif
630
CheckVariationFontSupport()631 bool gfxPlatformGtk::CheckVariationFontSupport() {
632 // Although there was some variation/multiple-master support in FreeType
633 // in older versions, it seems too incomplete/unstable for us to use
634 // until at least 2.7.1.
635 FT_Int major, minor, patch;
636 FT_Library_Version(Factory::GetFTLibrary(), &major, &minor, &patch);
637 return major * 1000000 + minor * 1000 + patch >= 2007001;
638 }
639
640 #ifdef MOZ_X11
641
642 class GtkVsyncSource final : public VsyncSource {
643 public:
GtkVsyncSource()644 GtkVsyncSource() {
645 MOZ_ASSERT(NS_IsMainThread());
646 mGlobalDisplay = new GLXDisplay();
647 }
648
~GtkVsyncSource()649 virtual ~GtkVsyncSource() { MOZ_ASSERT(NS_IsMainThread()); }
650
GetGlobalDisplay()651 virtual Display& GetGlobalDisplay() override { return *mGlobalDisplay; }
652
653 class GLXDisplay final : public VsyncSource::Display {
654 public:
GLXDisplay()655 GLXDisplay()
656 : mGLContext(nullptr),
657 mXDisplay(nullptr),
658 mSetupLock("GLXVsyncSetupLock"),
659 mVsyncThread("GLXVsyncThread"),
660 mVsyncTask(nullptr),
661 mVsyncEnabledLock("GLXVsyncEnabledLock"),
662 mVsyncEnabled(false) {}
663
664 // Sets up the display's GL context on a worker thread.
665 // Required as GLContexts may only be used by the creating thread.
666 // Returns true if setup was a success.
Setup()667 bool Setup() {
668 MonitorAutoLock lock(mSetupLock);
669 MOZ_ASSERT(NS_IsMainThread());
670 if (!mVsyncThread.Start()) return false;
671
672 RefPtr<Runnable> vsyncSetup =
673 NewRunnableMethod("GtkVsyncSource::GLXDisplay::SetupGLContext", this,
674 &GLXDisplay::SetupGLContext);
675 mVsyncThread.message_loop()->PostTask(vsyncSetup.forget());
676 // Wait until the setup has completed.
677 lock.Wait();
678 return mGLContext != nullptr;
679 }
680
681 // Called on the Vsync thread to setup the GL context.
SetupGLContext()682 void SetupGLContext() {
683 MonitorAutoLock lock(mSetupLock);
684 MOZ_ASSERT(!NS_IsMainThread());
685 MOZ_ASSERT(!mGLContext, "GLContext already setup!");
686
687 // Create video sync timer on a separate Display to prevent locking the
688 // main thread X display.
689 mXDisplay = XOpenDisplay(nullptr);
690 if (!mXDisplay) {
691 lock.NotifyAll();
692 return;
693 }
694
695 // Most compositors wait for vsync events on the root window.
696 Window root = DefaultRootWindow(mXDisplay);
697 int screen = DefaultScreen(mXDisplay);
698
699 ScopedXFree<GLXFBConfig> cfgs;
700 GLXFBConfig config;
701 int visid;
702 bool forWebRender = false;
703 if (!gl::GLContextGLX::FindFBConfigForWindow(
704 mXDisplay, screen, root, &cfgs, &config, &visid, forWebRender)) {
705 lock.NotifyAll();
706 return;
707 }
708
709 mGLContext = gl::GLContextGLX::CreateGLContext(
710 {}, gfx::XlibDisplay::Borrow(mXDisplay), root, config, false,
711 nullptr);
712
713 if (!mGLContext) {
714 lock.NotifyAll();
715 return;
716 }
717
718 mGLContext->MakeCurrent();
719
720 // Test that SGI_video_sync lets us get the counter.
721 unsigned int syncCounter = 0;
722 if (gl::sGLXLibrary.fGetVideoSync(&syncCounter) != 0) {
723 mGLContext = nullptr;
724 }
725
726 lock.NotifyAll();
727 }
728
EnableVsync()729 virtual void EnableVsync() override {
730 MOZ_ASSERT(NS_IsMainThread());
731 MOZ_ASSERT(mGLContext, "GLContext not setup!");
732
733 MonitorAutoLock lock(mVsyncEnabledLock);
734 if (mVsyncEnabled) {
735 return;
736 }
737 mVsyncEnabled = true;
738
739 // If the task has not nulled itself out, it hasn't yet realized
740 // that vsync was disabled earlier, so continue its execution.
741 if (!mVsyncTask) {
742 mVsyncTask = NewRunnableMethod("GtkVsyncSource::GLXDisplay::RunVsync",
743 this, &GLXDisplay::RunVsync);
744 RefPtr<Runnable> addrefedTask = mVsyncTask;
745 mVsyncThread.message_loop()->PostTask(addrefedTask.forget());
746 }
747 }
748
DisableVsync()749 virtual void DisableVsync() override {
750 MonitorAutoLock lock(mVsyncEnabledLock);
751 mVsyncEnabled = false;
752 }
753
IsVsyncEnabled()754 virtual bool IsVsyncEnabled() override {
755 MonitorAutoLock lock(mVsyncEnabledLock);
756 return mVsyncEnabled;
757 }
758
Shutdown()759 virtual void Shutdown() override {
760 MOZ_ASSERT(NS_IsMainThread());
761 DisableVsync();
762
763 // Cleanup thread-specific resources before shutting down.
764 RefPtr<Runnable> shutdownTask = NewRunnableMethod(
765 "GtkVsyncSource::GLXDisplay::Cleanup", this, &GLXDisplay::Cleanup);
766 mVsyncThread.message_loop()->PostTask(shutdownTask.forget());
767
768 // Stop, waiting for the cleanup task to finish execution.
769 mVsyncThread.Stop();
770 }
771
772 private:
773 virtual ~GLXDisplay() = default;
774
RunVsync()775 void RunVsync() {
776 MOZ_ASSERT(!NS_IsMainThread());
777
778 mGLContext->MakeCurrent();
779
780 unsigned int syncCounter = 0;
781 gl::sGLXLibrary.fGetVideoSync(&syncCounter);
782 for (;;) {
783 {
784 MonitorAutoLock lock(mVsyncEnabledLock);
785 if (!mVsyncEnabled) {
786 mVsyncTask = nullptr;
787 return;
788 }
789 }
790
791 TimeStamp lastVsync = TimeStamp::Now();
792 bool useSoftware = false;
793
794 // Wait until the video sync counter reaches the next value by waiting
795 // until the parity of the counter value changes.
796 unsigned int nextSync = syncCounter + 1;
797 int status;
798 if ((status = gl::sGLXLibrary.fWaitVideoSync(2, (int)nextSync % 2,
799 &syncCounter)) != 0) {
800 gfxWarningOnce() << "glXWaitVideoSync returned " << status;
801 useSoftware = true;
802 }
803
804 if (syncCounter == (nextSync - 1)) {
805 gfxWarningOnce()
806 << "glXWaitVideoSync failed to increment the sync counter.";
807 useSoftware = true;
808 }
809
810 if (useSoftware) {
811 double remaining =
812 (1000.f / 60.f) - (TimeStamp::Now() - lastVsync).ToMilliseconds();
813 if (remaining > 0) {
814 PlatformThread::Sleep((int)remaining);
815 }
816 }
817
818 lastVsync = TimeStamp::Now();
819 TimeStamp outputTime = lastVsync + GetVsyncRate();
820 NotifyVsync(lastVsync, outputTime);
821 }
822 }
823
Cleanup()824 void Cleanup() {
825 MOZ_ASSERT(!NS_IsMainThread());
826
827 mGLContext = nullptr;
828 if (mXDisplay) XCloseDisplay(mXDisplay);
829 }
830
831 // Owned by the vsync thread.
832 RefPtr<gl::GLContextGLX> mGLContext;
833 _XDisplay* mXDisplay;
834 Monitor mSetupLock;
835 base::Thread mVsyncThread;
836 RefPtr<Runnable> mVsyncTask;
837 Monitor mVsyncEnabledLock;
838 bool mVsyncEnabled;
839 };
840
841 private:
842 // We need a refcounted VsyncSource::Display to use chromium IPC runnables.
843 RefPtr<GLXDisplay> mGlobalDisplay;
844 };
845
CreateHardwareVsyncSource()846 already_AddRefed<gfx::VsyncSource> gfxPlatformGtk::CreateHardwareVsyncSource() {
847 # ifdef MOZ_WAYLAND
848 if (IsWaylandDisplay()) {
849 // For wayland, we simply return the standard software vsync for now.
850 // This powers refresh drivers and the likes.
851 return gfxPlatform::CreateHardwareVsyncSource();
852 }
853 # endif
854
855 // Only use GLX vsync when the OpenGL compositor / WebRender is being used.
856 // The extra cost of initializing a GLX context while blocking the main
857 // thread is not worth it when using basic composition.
858 //
859 // Don't call gl::sGLXLibrary.SupportsVideoSync() when EGL is used.
860 // NVIDIA drivers refuse to use EGL GL context when GLX was initialized first
861 // and fail silently.
862 if (gfxConfig::IsEnabled(Feature::HW_COMPOSITING)) {
863 bool useGlxVsync = false;
864
865 nsCOMPtr<nsIGfxInfo> gfxInfo = components::GfxInfo::Service();
866 nsString adapterDriverVendor;
867 gfxInfo->GetAdapterDriverVendor(adapterDriverVendor);
868
869 // Nvidia doesn't support GLX at the same time as EGL but Mesa does.
870 if (!gfxVars::UseEGL() || (adapterDriverVendor.Find("mesa") != -1)) {
871 useGlxVsync = gl::sGLXLibrary.SupportsVideoSync(DefaultXDisplay());
872 }
873 if (useGlxVsync) {
874 RefPtr<VsyncSource> vsyncSource = new GtkVsyncSource();
875 VsyncSource::Display& display = vsyncSource->GetGlobalDisplay();
876 if (!static_cast<GtkVsyncSource::GLXDisplay&>(display).Setup()) {
877 NS_WARNING(
878 "Failed to setup GLContext, falling back to software vsync.");
879 return gfxPlatform::CreateHardwareVsyncSource();
880 }
881 return vsyncSource.forget();
882 }
883 NS_WARNING("SGI_video_sync unsupported. Falling back to software vsync.");
884 }
885 return gfxPlatform::CreateHardwareVsyncSource();
886 }
887
888 #endif
889
BuildContentDeviceData(ContentDeviceData * aOut)890 void gfxPlatformGtk::BuildContentDeviceData(ContentDeviceData* aOut) {
891 gfxPlatform::BuildContentDeviceData(aOut);
892
893 aOut->cmsOutputProfileData() = GetPlatformCMSOutputProfileData();
894 }
895