Debian Codegraph @

mozglue/misc/PreXULSkeletonUI.cpp

raw
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6
7 #include "PreXULSkeletonUI.h"
8
9 #include <algorithm>
10 #include <dwmapi.h>
11 #include <math.h>
12 #include <limits.h>
13 #include <cmath>
14 #include <locale>
15 #include <string>
16 #include <objbase.h>
17 #include <shlobj.h>
18
19 #include "mozilla/Assertions.h"
20 #include "mozilla/Attributes.h"
21 #include "mozilla/BaseProfilerMarkers.h"
22 #include "mozilla/CacheNtDllThunk.h"
23 #include "mozilla/FStream.h"
24 #include "mozilla/GetKnownFolderPath.h"
25 #include "mozilla/HashFunctions.h"
26 #include "mozilla/HelperMacros.h"
27 #include "mozilla/glue/Debug.h"
28 #include "mozilla/Maybe.h"
29 #include "mozilla/mscom/ProcessRuntime.h"
30 #include "mozilla/ResultVariant.h"
31 #include "mozilla/ScopeExit.h"
32 #include "mozilla/Try.h"
33 #include "mozilla/UniquePtr.h"
34 #include "mozilla/UniquePtrExtensions.h"
35 #include "mozilla/Unused.h"
36 #include "mozilla/WindowsDpiAwareness.h"
37 #include "mozilla/WindowsProcessMitigations.h"
38
39 namespace mozilla {
40
41 // ColorRect defines an optionally-rounded, optionally-bordered rectangle of a
42 // particular color that we will draw.
43 struct ColorRect {
44 uint32_t color;
45 uint32_t borderColor;
46 int x;
47 int y;
48 int width;
49 int height;
50 int borderWidth;
51 int borderRadius;
52 bool flipIfRTL;
53 };
54
55 // DrawRect is mostly the same as ColorRect, but exists as an implementation
56 // detail to simplify drawing borders. We draw borders as a strokeOnly rect
57 // underneath an inner rect of a particular color. We also need to keep
58 // track of the backgroundColor for rounding rects, in order to correctly
59 // anti-alias.
60 struct DrawRect {
61 uint32_t color;
62 uint32_t backgroundColor;
63 int x;
64 int y;
65 int width;
66 int height;
67 int borderRadius;
68 int borderWidth;
69 bool strokeOnly;
70 };
71
72 struct NormalizedRGB {
73 double r;
74 double g;
75 double b;
76 };
77
78 NormalizedRGB UintToRGB(uint32_t color) {
79 double r = static_cast<double>(color >> 16 & 0xff) / 255.0;
80 double g = static_cast<double>(color >> 8 & 0xff) / 255.0;
81 double b = static_cast<double>(color >> 0 & 0xff) / 255.0;
82 return NormalizedRGB{r, g, b};
83 }
84
85 uint32_t RGBToUint(const NormalizedRGB& rgb) {
86 return (static_cast<uint32_t>(rgb.r * 255.0) << 16) |
87 (static_cast<uint32_t>(rgb.g * 255.0) << 8) |
88 (static_cast<uint32_t>(rgb.b * 255.0) << 0);
89 }
90
91 double Lerp(double a, double b, double x) { return a + x * (b - a); }
92
93 NormalizedRGB Lerp(const NormalizedRGB& a, const NormalizedRGB& b, double x) {
94 return NormalizedRGB{Lerp(a.r, b.r, x), Lerp(a.g, b.g, x), Lerp(a.b, b.b, x)};
95 }
96
97 // Produces a smooth curve in [0,1] based on a linear input in [0,1]
98 double SmoothStep3(double x) { return x * x * (3.0 - 2.0 * x); }
99
100 struct Margin {
101 int top = 0;
102 int right = 0;
103 int bottom = 0;
104 int left = 0;
105 };
106
107 static const wchar_t kPreXULSkeletonUIKeyPath[] =
108 L"SOFTWARE"
109 L"\\" MOZ_APP_VENDOR L"\\" MOZ_APP_BASENAME L"\\PreXULSkeletonUISettings";
110
111 static bool sPreXULSkeletonUIShown = false;
112 static bool sPreXULSkeletonUIEnabled = false;
113 static HWND sPreXULSkeletonUIWindow;
114 static LPWSTR const gStockApplicationIcon = MAKEINTRESOURCEW(32512);
115 static LPWSTR const gIDCWait = MAKEINTRESOURCEW(32514);
116 static HANDLE sPreXULSKeletonUIAnimationThread;
117 static HANDLE sPreXULSKeletonUILockFile = INVALID_HANDLE_VALUE;
118
119 static mozilla::mscom::ProcessRuntime* sProcessRuntime;
120 static uint32_t* sPixelBuffer = nullptr;
121 static Vector<ColorRect>* sAnimatedRects = nullptr;
122 static int sTotalChromeHeight = 0;
123 static volatile LONG sAnimationControlFlag = 0;
124 static bool sMaximized = false;
125 static uint32_t sDpi = 0;
126 // See nsWindow::mNonClientOffset
127 static Margin sNonClientOffset;
128 static int sCaptionHeight = 0;
129 static int sHorizontalResizeMargin = 0;
130 static int sVerticalResizeMargin = 0;
131
132 // See nsWindow::NonClientSizeMargin()
133 static Margin NonClientSizeMargin() {
134 return Margin{sCaptionHeight + sVerticalResizeMargin - sNonClientOffset.top,
135 sHorizontalResizeMargin - sNonClientOffset.right,
136 sVerticalResizeMargin - sNonClientOffset.bottom,
137 sHorizontalResizeMargin - sNonClientOffset.left};
138 }
139
140 // Color values needed by the animation loop
141 static uint32_t sAnimationColor;
142 static uint32_t sToolbarForegroundColor;
143
144 static ThemeMode sTheme = ThemeMode::Invalid;
145
146 #define MOZ_DECL_IMPORTED_WIN32_FN(name) \
147 static decltype(&::name) s##name = nullptr
148 MOZ_DECL_IMPORTED_WIN32_FN(EnableNonClientDpiScaling);
149 MOZ_DECL_IMPORTED_WIN32_FN(GetSystemMetricsForDpi);
150 MOZ_DECL_IMPORTED_WIN32_FN(GetDpiForWindow);
151 MOZ_DECL_IMPORTED_WIN32_FN(RegisterClassW);
152 MOZ_DECL_IMPORTED_WIN32_FN(LoadIconW);
153 MOZ_DECL_IMPORTED_WIN32_FN(LoadCursorW);
154 MOZ_DECL_IMPORTED_WIN32_FN(CreateWindowExW);
155 MOZ_DECL_IMPORTED_WIN32_FN(ShowWindow);
156 MOZ_DECL_IMPORTED_WIN32_FN(SetWindowPos);
157 MOZ_DECL_IMPORTED_WIN32_FN(GetWindowDC);
158 MOZ_DECL_IMPORTED_WIN32_FN(GetWindowRect);
159 MOZ_DECL_IMPORTED_WIN32_FN(MapWindowPoints);
160 MOZ_DECL_IMPORTED_WIN32_FN(FillRect);
161 MOZ_DECL_IMPORTED_WIN32_FN(DeleteObject);
162 MOZ_DECL_IMPORTED_WIN32_FN(ReleaseDC);
163 MOZ_DECL_IMPORTED_WIN32_FN(MonitorFromWindow);
164 MOZ_DECL_IMPORTED_WIN32_FN(GetMonitorInfoW);
165 MOZ_DECL_IMPORTED_WIN32_FN(SetWindowLongPtrW);
166 MOZ_DECL_IMPORTED_WIN32_FN(StretchDIBits);
167 MOZ_DECL_IMPORTED_WIN32_FN(CreateSolidBrush);
168 MOZ_DECL_IMPORTED_WIN32_FN(DwmGetWindowAttribute);
169 MOZ_DECL_IMPORTED_WIN32_FN(DwmSetWindowAttribute);
170 #undef MOZ_DECL_IMPORTED_WIN32_FN
171
172 static int sWindowWidth;
173 static int sWindowHeight;
174 static double sCSSToDevPixelScaling;
175
176 static Maybe<PreXULSkeletonUIError> sErrorReason;
177
178 static const int kAnimationCSSPixelsPerFrame = 11;
179 static const int kAnimationCSSExtraWindowSize = 300;
180
181 // NOTE: these values were pulled out of thin air as round numbers that are
182 // likely to be too big to be seen in practice. If we legitimately see windows
183 // this big, we probably don't want to be drawing them on the CPU anyway.
184 static const uint32_t kMaxWindowWidth = 1 << 16;
185 static const uint32_t kMaxWindowHeight = 1 << 16;
186
187 static const wchar_t* sEnabledRegSuffix = L"|Enabled";
188 static const wchar_t* sScreenXRegSuffix = L"|ScreenX";
189 static const wchar_t* sScreenYRegSuffix = L"|ScreenY";
190 static const wchar_t* sWidthRegSuffix = L"|Width";
191 static const wchar_t* sHeightRegSuffix = L"|Height";
192 static const wchar_t* sMaximizedRegSuffix = L"|Maximized";
193 static const wchar_t* sUrlbarCSSRegSuffix = L"|UrlbarCSSSpan";
194 static const wchar_t* sCssToDevPixelScalingRegSuffix = L"|CssToDevPixelScaling";
195 static const wchar_t* sSearchbarRegSuffix = L"|SearchbarCSSSpan";
196 static const wchar_t* sSpringsCSSRegSuffix = L"|SpringsCSSSpan";
197 static const wchar_t* sThemeRegSuffix = L"|Theme";
198 static const wchar_t* sFlagsRegSuffix = L"|Flags";
199 static const wchar_t* sProgressSuffix = L"|Progress";
200
201 std::wstring GetRegValueName(const wchar_t* prefix, const wchar_t* suffix) {
202 std::wstring result(prefix);
203 result.append(suffix);
204 return result;
205 }
206
207 // This is paraphrased from WinHeaderOnlyUtils.h. The fact that this file is
208 // included in standalone SpiderMonkey builds prohibits us from including that
209 // file directly, and it hardly warrants its own header. Bug 1674920 tracks
210 // only including this file for gecko-related builds.
211 Result<UniquePtr<wchar_t[]>, PreXULSkeletonUIError> GetBinaryPath() {
212 DWORD bufLen = MAX_PATH;
213 UniquePtr<wchar_t[]> buf;
214 while (true) {
215 buf = MakeUnique<wchar_t[]>(bufLen);
216 DWORD retLen = ::GetModuleFileNameW(nullptr, buf.get(), bufLen);
217 if (!retLen) {
218 return Err(PreXULSkeletonUIError::FilesystemFailure);
219 }
220
221 if (retLen == bufLen && ::GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
222 bufLen *= 2;
223 continue;
224 }
225
226 break;
227 }
228
229 return buf;
230 }
231
232 // PreXULSkeletonUIDisallowed means that we don't even have the capacity to
233 // enable the skeleton UI, whether because we're on a platform that doesn't
234 // support it or because we launched with command line arguments that we don't
235 // support. Some of these situations are transient, so we want to make sure we
236 // don't mess with registry values in these scenarios that we may use in
237 // other scenarios in which the skeleton UI is actually enabled.
238 static bool PreXULSkeletonUIDisallowed() {
239 return sErrorReason.isSome() &&
240 (*sErrorReason == PreXULSkeletonUIError::Cmdline ||
241 *sErrorReason == PreXULSkeletonUIError::EnvVars);
242 }
243
244 // Note: this is specifically *not* a robust, multi-locale lowercasing
245 // operation. It is not intended to be such. It is simply intended to match the
246 // way in which we look for other instances of firefox to remote into.
247 // See
248 // https://searchfox.org/mozilla-central/rev/71621bfa47a371f2b1ccfd33c704913124afb933/toolkit/components/remote/nsRemoteService.cpp#56
249 static void MutateStringToLowercase(wchar_t* ptr) {
250 while (*ptr) {
251 wchar_t ch = *ptr;
252 if (ch >= L'A' && ch <= L'Z') {
253 *ptr = ch + (L'a' - L'A');
254 }
255 ++ptr;
256 }
257 }
258
259 static Result<Ok, PreXULSkeletonUIError> GetSkeletonUILock() {
260 auto localAppDataPath = GetKnownFolderPath(FOLDERID_LocalAppData);
261 if (!localAppDataPath) {
262 return Err(PreXULSkeletonUIError::FilesystemFailure);
263 }
264
265 if (sPreXULSKeletonUILockFile != INVALID_HANDLE_VALUE) {
266 return Ok();
267 }
268
269 // Note: because we're in mozglue, we cannot easily access things from
270 // toolkit, like `GetInstallHash`. We could move `GetInstallHash` into
271 // mozglue, and rip out all of its usage of types defined in toolkit headers.
272 // However, it seems cleaner to just hash the bin path ourselves. We don't
273 // get quite the same robustness that `GetInstallHash` might provide, but
274 // we already don't have that with how we key our registry values, so it
275 // probably makes sense to just match those.
276 UniquePtr<wchar_t[]> binPath;
277 MOZ_TRY_VAR(binPath, GetBinaryPath());
278
279 // Lowercase the binpath to match how we look for remote instances.
280 MutateStringToLowercase(binPath.get());
281
282 // The number of bytes * 2 characters per byte + 1 for the null terminator
283 uint32_t hexHashSize = sizeof(uint32_t) * 2 + 1;
284 UniquePtr<wchar_t[]> installHash = MakeUnique<wchar_t[]>(hexHashSize);
285 // This isn't perfect - it's a 32-bit hash of the path to our executable. It
286 // could reasonably collide, or casing could potentially affect things, but
287 // the theory is that that should be uncommon enough and the failure case
288 // mild enough that this is fine.
289 uint32_t binPathHash = HashString(binPath.get());
290 swprintf(installHash.get(), hexHashSize, L"%08x", binPathHash);
291
292 std::wstring lockFilePath;
293 lockFilePath.append(localAppDataPath.get());
294 lockFilePath.append(
295 L"\\" MOZ_APP_VENDOR L"\\" MOZ_APP_BASENAME L"\\SkeletonUILock-");
296 lockFilePath.append(installHash.get());
297
298 // We intentionally leak this file - that is okay, and (kind of) the point.
299 // We want to hold onto this handle until the application exits, and hold
300 // onto it with exclusive rights. If this check fails, then we assume that
301 // another instance of the executable is holding it, and thus return false.
302 sPreXULSKeletonUILockFile =
303 ::CreateFileW(lockFilePath.c_str(), GENERIC_READ | GENERIC_WRITE,
304 0, // No sharing - this is how the lock works
305 nullptr, CREATE_ALWAYS,
306 FILE_FLAG_DELETE_ON_CLOSE, // Don't leave this lying around
307 nullptr);
308 if (sPreXULSKeletonUILockFile == INVALID_HANDLE_VALUE) {
309 return Err(PreXULSkeletonUIError::FailedGettingLock);
310 }
311
312 return Ok();
313 }
314
315 const char kGeneralSection[] = "[General]";
316 const char kStartWithLastProfile[] = "StartWithLastProfile=";
317
318 static bool ProfileDbHasStartWithLastProfile(IFStream& iniContents) {
319 bool inGeneral = false;
320 std::string line;
321 while (std::getline(iniContents, line)) {
322 size_t whitespace = 0;
323 while (line.length() > whitespace &&
324 (line[whitespace] == ' ' || line[whitespace] == '\t')) {
325 whitespace++;
326 }
327 line.erase(0, whitespace);
328
329 if (line.compare(kGeneralSection) == 0) {
330 inGeneral = true;
331 } else if (inGeneral) {
332 if (line[0] == '[') {
333 inGeneral = false;
334 } else {
335 if (line.find(kStartWithLastProfile) == 0) {
336 char val = line.c_str()[sizeof(kStartWithLastProfile) - 1];
337 if (val == '0') {
338 return false;
339 } else if (val == '1') {
340 return true;
341 }
342 }
343 }
344 }
345 }
346
347 // If we don't find it in the .ini file, we interpret that as true
348 return true;
349 }
350
351 static Result<Ok, PreXULSkeletonUIError> CheckForStartWithLastProfile() {
352 auto roamingAppData = GetKnownFolderPath(FOLDERID_RoamingAppData);
353 if (!roamingAppData) {
354 return Err(PreXULSkeletonUIError::FilesystemFailure);
355 }
356 std::wstring profileDbPath(roamingAppData.get());
357 profileDbPath.append(
358 L"\\" MOZ_APP_VENDOR L"\\" MOZ_APP_BASENAME L"\\profiles.ini");
359 IFStream profileDb(profileDbPath.c_str());
360 if (profileDb.fail()) {
361 return Err(PreXULSkeletonUIError::FilesystemFailure);
362 }
363
364 if (!ProfileDbHasStartWithLastProfile(profileDb)) {
365 return Err(PreXULSkeletonUIError::NoStartWithLastProfile);
366 }
367
368 return Ok();
369 }
370
371 // We could use nsAutoRegKey, but including nsWindowsHelpers.h causes build
372 // failures in random places because we're in mozglue. Overall it should be
373 // simpler and cleaner to just step around that issue with this class:
374 class MOZ_RAII AutoCloseRegKey {
375 public:
376 explicit AutoCloseRegKey(HKEY key) : mKey(key) {}
377 ~AutoCloseRegKey() { ::RegCloseKey(mKey); }
378
379 private:
380 HKEY mKey;
381 };
382
383 int CSSToDevPixels(double cssPixels, double scaling) {
384 return floor(cssPixels * scaling + 0.5);
385 }
386
387 int CSSToDevPixels(int cssPixels, double scaling) {
388 return CSSToDevPixels((double)cssPixels, scaling);
389 }
390
391 int CSSToDevPixelsFloor(double cssPixels, double scaling) {
392 return floor(cssPixels * scaling);
393 }
394
395 // Some things appear to floor to device pixels rather than rounding. A good
396 // example of this is border widths.
397 int CSSToDevPixelsFloor(int cssPixels, double scaling) {
398 return CSSToDevPixelsFloor((double)cssPixels, scaling);
399 }
400
401 double SignedDistanceToCircle(double x, double y, double radius) {
402 return sqrt(x * x + y * y) - radius;
403 }
404
405 // For more details, see
406 // https://searchfox.org/mozilla-central/rev/a5d9abfda1e26b1207db9549549ab0bdd73f735d/gfx/wr/webrender/res/shared.glsl#141-187
407 // which was a reference for this function.
408 double DistanceAntiAlias(double signedDistance) {
409 // Distance assumed to be in device pixels. We use an aa range of 0.5 for
410 // reasons detailed in the linked code above.
411 const double aaRange = 0.5;
412 double dist = 0.5 * signedDistance / aaRange;
413 if (dist <= -0.5 + std::numeric_limits<double>::epsilon()) return 1.0;
414 if (dist >= 0.5 - std::numeric_limits<double>::epsilon()) return 0.0;
415 return 0.5 + dist * (0.8431027 * dist * dist - 1.14453603);
416 }
417
418 void RasterizeRoundedRectTopAndBottom(const DrawRect& rect) {
419 if (rect.height <= 2 * rect.borderRadius) {
420 MOZ_ASSERT(false, "Skeleton UI rect height too small for border radius.");
421 return;
422 }
423 if (rect.width <= 2 * rect.borderRadius) {
424 MOZ_ASSERT(false, "Skeleton UI rect width too small for border radius.");
425 return;
426 }
427
428 NormalizedRGB rgbBase = UintToRGB(rect.backgroundColor);
429 NormalizedRGB rgbBlend = UintToRGB(rect.color);
430
431 for (int rowIndex = 0; rowIndex < rect.borderRadius; ++rowIndex) {
432 int yTop = rect.y + rect.borderRadius - 1 - rowIndex;
433 int yBottom = rect.y + rect.height - rect.borderRadius + rowIndex;
434
435 uint32_t* lineStartTop = &sPixelBuffer[yTop * sWindowWidth];
436 uint32_t* innermostPixelTopLeft =
437 lineStartTop + rect.x + rect.borderRadius - 1;
438 uint32_t* innermostPixelTopRight =
439 lineStartTop + rect.x + rect.width - rect.borderRadius;
440 uint32_t* lineStartBottom = &sPixelBuffer[yBottom * sWindowWidth];
441 uint32_t* innermostPixelBottomLeft =
442 lineStartBottom + rect.x + rect.borderRadius - 1;
443 uint32_t* innermostPixelBottomRight =
444 lineStartBottom + rect.x + rect.width - rect.borderRadius;
445
446 // Add 0.5 to x and y to get the pixel center.
447 double pixelY = (double)rowIndex + 0.5;
448 for (int columnIndex = 0; columnIndex < rect.borderRadius; ++columnIndex) {
449 double pixelX = (double)columnIndex + 0.5;
450 double distance =
451 SignedDistanceToCircle(pixelX, pixelY, (double)rect.borderRadius);
452 double alpha = DistanceAntiAlias(distance);
453 NormalizedRGB rgb = Lerp(rgbBase, rgbBlend, alpha);
454 uint32_t color = RGBToUint(rgb);
455
456 innermostPixelTopLeft[-columnIndex] = color;
457 innermostPixelTopRight[columnIndex] = color;
458 innermostPixelBottomLeft[-columnIndex] = color;
459 innermostPixelBottomRight[columnIndex] = color;
460 }
461
462 std::fill(innermostPixelTopLeft + 1, innermostPixelTopRight, rect.color);
463 std::fill(innermostPixelBottomLeft + 1, innermostPixelBottomRight,
464 rect.color);
465 }
466 }
467
468 void RasterizeAnimatedRoundedRectTopAndBottom(
469 const ColorRect& colorRect, const uint32_t* animationLookup,
470 int priorUpdateAreaMin, int priorUpdateAreaMax, int currentUpdateAreaMin,
471 int currentUpdateAreaMax, int animationMin) {
472 // We iterate through logical pixel rows here, from inside to outside, which
473 // for the top of the rounded rect means from bottom to top, and for the
474 // bottom of the rect means top to bottom. We paint pixels from left to
475 // right on the top and bottom rows at the same time for the entire animation
476 // window. (If the animation window does not overlap any rounded corners,
477 // however, we won't be called at all)
478 for (int rowIndex = 0; rowIndex < colorRect.borderRadius; ++rowIndex) {
479 int yTop = colorRect.y + colorRect.borderRadius - 1 - rowIndex;
480 int yBottom =
481 colorRect.y + colorRect.height - colorRect.borderRadius + rowIndex;
482
483 uint32_t* lineStartTop = &sPixelBuffer[yTop * sWindowWidth];
484 uint32_t* lineStartBottom = &sPixelBuffer[yBottom * sWindowWidth];
485
486 // Add 0.5 to x and y to get the pixel center.
487 double pixelY = (double)rowIndex + 0.5;
488 for (int x = priorUpdateAreaMin; x < currentUpdateAreaMax; ++x) {
489 // The column index is the distance from the innermost pixel, which
490 // is different depending on whether we're on the left or right
491 // side of the rect. It will always be the max here, and if it's
492 // negative that just means we're outside the rounded area.
493 int columnIndex =
494 std::max((int)colorRect.x + (int)colorRect.borderRadius - x - 1,
495 x - ((int)colorRect.x + (int)colorRect.width -
496 (int)colorRect.borderRadius));
497
498 double alpha = 1.0;
499 if (columnIndex >= 0) {
500 double pixelX = (double)columnIndex + 0.5;
501 double distance = SignedDistanceToCircle(
502 pixelX, pixelY, (double)colorRect.borderRadius);
503 alpha = DistanceAntiAlias(distance);
504 }
505 // We don't do alpha blending for the antialiased pixels at the
506 // shape's border. It is not noticeable in the animation.
507 if (alpha > 1.0 - std::numeric_limits<double>::epsilon()) {
508 // Overwrite the tail end of last frame's animation with the
509 // rect's normal, unanimated color.
510 uint32_t color = x < priorUpdateAreaMax
511 ? colorRect.color
512 : animationLookup[x - animationMin];
513 lineStartTop[x] = color;
514 lineStartBottom[x] = color;
515 }
516 }
517 }
518 }
519
520 void RasterizeColorRect(const ColorRect& colorRect) {
521 // We sometimes split our rect into two, to simplify drawing borders. If we
522 // have a border, we draw a stroke-only rect first, and then draw the smaller
523 // inner rect on top of it.
524 Vector<DrawRect, 2> drawRects;
525 Unused << drawRects.reserve(2);
526 if (colorRect.borderWidth == 0) {
527 DrawRect rect = {};
528 rect.color = colorRect.color;
529 rect.backgroundColor =
530 sPixelBuffer[colorRect.y * sWindowWidth + colorRect.x];
531 rect.x = colorRect.x;
532 rect.y = colorRect.y;
533 rect.width = colorRect.width;
534 rect.height = colorRect.height;
535 rect.borderRadius = colorRect.borderRadius;
536 rect.strokeOnly = false;
537 drawRects.infallibleAppend(rect);
538 } else {
539 DrawRect borderRect = {};
540 borderRect.color = colorRect.borderColor;
541 borderRect.backgroundColor =
542 sPixelBuffer[colorRect.y * sWindowWidth + colorRect.x];
543 borderRect.x = colorRect.x;
544 borderRect.y = colorRect.y;
545 borderRect.width = colorRect.width;
546 borderRect.height = colorRect.height;
547 borderRect.borderRadius = colorRect.borderRadius;
548 borderRect.borderWidth = colorRect.borderWidth;
549 borderRect.strokeOnly = true;
550 drawRects.infallibleAppend(borderRect);
551
552 DrawRect baseRect = {};
553 baseRect.color = colorRect.color;
554 baseRect.backgroundColor = borderRect.color;
555 baseRect.x = colorRect.x + colorRect.borderWidth;
556 baseRect.y = colorRect.y + colorRect.borderWidth;
557 baseRect.width = colorRect.width - 2 * colorRect.borderWidth;
558 baseRect.height = colorRect.height - 2 * colorRect.borderWidth;
559 baseRect.borderRadius =
560 std::max(0, (int)colorRect.borderRadius - (int)colorRect.borderWidth);
561 baseRect.borderWidth = 0;
562 baseRect.strokeOnly = false;
563 drawRects.infallibleAppend(baseRect);
564 }
565
566 for (const DrawRect& rect : drawRects) {
567 if (rect.height <= 0 || rect.width <= 0) {
568 continue;
569 }
570
571 // For rounded rectangles, the first thing we do is draw the top and
572 // bottom of the rectangle, with the more complicated logic below. After
573 // that we can just draw the vertically centered part of the rect like
574 // normal.
575 RasterizeRoundedRectTopAndBottom(rect);
576
577 // We then draw the flat, central portion of the rect (which in the case of
578 // non-rounded rects, is just the entire thing.)
579 int solidRectStartY =
580 std::clamp(rect.y + rect.borderRadius, 0, sTotalChromeHeight);
581 int solidRectEndY = std::clamp(rect.y + rect.height - rect.borderRadius, 0,
582 sTotalChromeHeight);
583 for (int y = solidRectStartY; y < solidRectEndY; ++y) {
584 // For strokeOnly rects (used to draw borders), we just draw the left
585 // and right side here. Looping down a column of pixels is not the most
586 // cache-friendly thing, but it shouldn't be a big deal given the height
587 // of the urlbar.
588 // Also, if borderRadius is less than borderWidth, we need to ensure
589 // that we fully draw the top and bottom lines, so we make sure to check
590 // that we're inside the middle range range before excluding pixels.
591 if (rect.strokeOnly && y - rect.y > rect.borderWidth &&
592 rect.y + rect.height - y > rect.borderWidth) {
593 int startXLeft = std::clamp(rect.x, 0, sWindowWidth);
594 int endXLeft = std::clamp(rect.x + rect.borderWidth, 0, sWindowWidth);
595 int startXRight =
596 std::clamp(rect.x + rect.width - rect.borderWidth, 0, sWindowWidth);
597 int endXRight = std::clamp(rect.x + rect.width, 0, sWindowWidth);
598
599 uint32_t* lineStart = &sPixelBuffer[y * sWindowWidth];
600 uint32_t* dataStartLeft = lineStart + startXLeft;
601 uint32_t* dataEndLeft = lineStart + endXLeft;
602 uint32_t* dataStartRight = lineStart + startXRight;
603 uint32_t* dataEndRight = lineStart + endXRight;
604 std::fill(dataStartLeft, dataEndLeft, rect.color);
605 std::fill(dataStartRight, dataEndRight, rect.color);
606 } else {
607 int startX = std::clamp(rect.x, 0, sWindowWidth);
608 int endX = std::clamp(rect.x + rect.width, 0, sWindowWidth);
609 uint32_t* lineStart = &sPixelBuffer[y * sWindowWidth];
610 uint32_t* dataStart = lineStart + startX;
611 uint32_t* dataEnd = lineStart + endX;
612 std::fill(dataStart, dataEnd, rect.color);
613 }
614 }
615 }
616 }
617
618 // Paints the pixels to sPixelBuffer for the skeleton UI animation (a light
619 // gradient which moves from left to right across the grey placeholder rects).
620 // Takes in the rect to draw, together with a lookup table for the gradient,
621 // and the bounds of the previous and current frame of the animation.
622 bool RasterizeAnimatedRect(const ColorRect& colorRect,
623 const uint32_t* animationLookup,
624 int priorAnimationMin, int animationMin,
625 int animationMax) {
626 int rectMin = colorRect.x;
627 int rectMax = colorRect.x + colorRect.width;
628 bool animationWindowOverlaps =
629 rectMax >= priorAnimationMin && rectMin < animationMax;
630
631 int priorUpdateAreaMin = std::max(rectMin, priorAnimationMin);
632 int priorUpdateAreaMax = std::min(rectMax, animationMin);
633 int currentUpdateAreaMin = std::max(rectMin, animationMin);
634 int currentUpdateAreaMax = std::min(rectMax, animationMax);
635
636 if (!animationWindowOverlaps) {
637 return false;
638 }
639
640 bool animationWindowOverlapsBorderRadius =
641 rectMin + colorRect.borderRadius > priorAnimationMin ||
642 rectMax - colorRect.borderRadius <= animationMax;
643
644 // If we don't overlap the left or right side of the rounded rectangle,
645 // just pretend it's not rounded. This is a small optimization but
646 // there's no point in doing all of this rounded rectangle checking if
647 // we aren't even overlapping
648 int borderRadius =
649 animationWindowOverlapsBorderRadius ? colorRect.borderRadius : 0;
650
651 if (borderRadius > 0) {
652 // Similarly to how we draw the rounded rects in DrawSkeletonUI, we
653 // first draw the rounded top and bottom, and then we draw the center
654 // rect.
655 RasterizeAnimatedRoundedRectTopAndBottom(
656 colorRect, animationLookup, priorUpdateAreaMin, priorUpdateAreaMax,
657 currentUpdateAreaMin, currentUpdateAreaMax, animationMin);
658 }
659
660 for (int y = colorRect.y + borderRadius;
661 y < colorRect.y + colorRect.height - borderRadius; ++y) {
662 uint32_t* lineStart = &sPixelBuffer[y * sWindowWidth];
663 // Overwrite the tail end of last frame's animation with the rect's
664 // normal, unanimated color.
665 for (int x = priorUpdateAreaMin; x < priorUpdateAreaMax; ++x) {
666 lineStart[x] = colorRect.color;
667 }
668 // Then apply the animated color
669 for (int x = currentUpdateAreaMin; x < currentUpdateAreaMax; ++x) {
670 lineStart[x] = animationLookup[x - animationMin];
671 }
672 }
673
674 return true;
675 }
676
677 bool FillRectWithColor(HDC hdc, LPCRECT rect, uint32_t mozColor) {
678 HBRUSH brush = sCreateSolidBrush(RGB((mozColor & 0xff0000) >> 16,
679 (mozColor & 0x00ff00) >> 8,
680 (mozColor & 0x0000ff) >> 0));
681 int fillRectResult = sFillRect(hdc, rect, brush);
682
683 sDeleteObject(brush);
684
685 return !!fillRectResult;
686 }
687
688 Result<Ok, PreXULSkeletonUIError> DrawSkeletonUI(
689 HWND hWnd, CSSPixelSpan urlbarCSSSpan, CSSPixelSpan searchbarCSSSpan,
690 Vector<CSSPixelSpan>& springs, const ThemeColors& currentTheme,
691 const EnumSet<SkeletonUIFlag, uint32_t>& flags) {
692 // NOTE: we opt here to paint a pixel buffer for the application chrome by
693 // hand, without using native UI library methods. Why do we do this?
694 //
695 // 1) It gives us a little bit more control, especially if we want to animate
696 // any of this.
697 // 2) It's actually more portable. We can do this on any platform where we
698 // can blit a pixel buffer to the screen, and it only has to change
699 // insofar as the UI is different on those platforms (and thus would have
700 // to change anyway.)
701 //
702 // The performance impact of this ought to be negligible. As far as has been
703 // observed, on slow reference hardware this might take up to a millisecond,
704 // for a startup which otherwise takes 30 seconds.
705 //
706 // The readability and maintainability are a greater concern. When the
707 // silhouette of Firefox's core UI changes, this code will likely need to
708 // change. However, for the foreseeable future, our skeleton UI will be mostly
709 // axis-aligned geometric shapes, and the thought is that any code which is
710 // manipulating raw pixels should not be *too* hard to maintain and
711 // understand so long as it is only painting such simple shapes.
712
713 sAnimationColor = currentTheme.animationColor;
714 sToolbarForegroundColor = currentTheme.toolbarForegroundColor;
715
716 bool menubarShown = flags.contains(SkeletonUIFlag::MenubarShown);
717 bool verticalTabs = flags.contains(SkeletonUIFlag::VerticalTabs);
718 bool bookmarksToolbarShown =
719 flags.contains(SkeletonUIFlag::BookmarksToolbarShown);
720 bool rtlEnabled = flags.contains(SkeletonUIFlag::RtlEnabled);
721
722 int chromeHorMargin = CSSToDevPixels(2, sCSSToDevPixelScaling);
723 int verticalOffset = sMaximized ? sVerticalResizeMargin : 0;
724 int horizontalOffset =
725 sHorizontalResizeMargin - (sMaximized ? 0 : chromeHorMargin);
726
727 // found in tabs.inc.css, "--tab-min-height" + 2 * "--tab-block-margin"
728 int tabBarHeight =
729 verticalTabs ? 0 : CSSToDevPixels(44, sCSSToDevPixelScaling);
730 int selectedTabBorderWidth = CSSToDevPixels(2, sCSSToDevPixelScaling);
731 // found in tabs.inc.css, "--tab-block-margin"
732 int titlebarSpacerWidth = horizontalOffset +
733 CSSToDevPixels(2, sCSSToDevPixelScaling) -
734 selectedTabBorderWidth;
735 if (!sMaximized && !menubarShown) {
736 // found in tabs.inc.css, ".titlebar-spacer"
737 titlebarSpacerWidth += CSSToDevPixels(40, sCSSToDevPixelScaling);
738 }
739 // found in tabs.inc.css, "--tab-block-margin"
740 int selectedTabMarginTop =
741 CSSToDevPixels(4, sCSSToDevPixelScaling) - selectedTabBorderWidth;
742 int selectedTabMarginBottom =
743 CSSToDevPixels(4, sCSSToDevPixelScaling) - selectedTabBorderWidth;
744 int selectedTabBorderRadius = CSSToDevPixels(4, sCSSToDevPixelScaling);
745 int selectedTabWidth =
746 CSSToDevPixels(221, sCSSToDevPixelScaling) + 2 * selectedTabBorderWidth;
747 int toolbarHeight = CSSToDevPixels(40, sCSSToDevPixelScaling);
748 // found in browser.css, "#PersonalToolbar"
749 int bookmarkToolbarHeight = CSSToDevPixels(28, sCSSToDevPixelScaling);
750 if (bookmarksToolbarShown) {
751 toolbarHeight += bookmarkToolbarHeight;
752 }
753 // found in urlbar-searchbar.inc.css, "#urlbar[breakout]"
754 int urlbarTopOffset = CSSToDevPixels(4, sCSSToDevPixelScaling);
755 int urlbarHeight = CSSToDevPixels(32, sCSSToDevPixelScaling);
756 // found in browser-aero.css, "#navigator-toolbox::after" border-bottom
757 int chromeContentDividerHeight = CSSToDevPixels(1, sCSSToDevPixelScaling);
758
759 int tabPlaceholderBarMarginTop = CSSToDevPixels(14, sCSSToDevPixelScaling);
760 int tabPlaceholderBarMarginLeft = CSSToDevPixels(10, sCSSToDevPixelScaling);
761 int tabPlaceholderBarHeight = CSSToDevPixels(10, sCSSToDevPixelScaling);
762 int tabPlaceholderBarWidth = CSSToDevPixels(120, sCSSToDevPixelScaling);
763
764 int toolbarPlaceholderHeight = CSSToDevPixels(10, sCSSToDevPixelScaling);
765 int toolbarPlaceholderMarginRight =
766 rtlEnabled ? CSSToDevPixels(11, sCSSToDevPixelScaling)
767 : CSSToDevPixels(9, sCSSToDevPixelScaling);
768 int toolbarPlaceholderMarginLeft =
769 rtlEnabled ? CSSToDevPixels(9, sCSSToDevPixelScaling)
770 : CSSToDevPixels(11, sCSSToDevPixelScaling);
771 int placeholderMargin = CSSToDevPixels(8, sCSSToDevPixelScaling);
772
773 int menubarHeightDevPixels =
774 menubarShown ? CSSToDevPixels(28, sCSSToDevPixelScaling) : 0;
775
776 // defined in urlbar-searchbar.inc.css as --urlbar-margin-inline: 5px
777 int urlbarMargin =
778 CSSToDevPixels(5, sCSSToDevPixelScaling) + horizontalOffset;
779
780 int urlbarTextPlaceholderMarginTop =
781 CSSToDevPixels(12, sCSSToDevPixelScaling);
782 int urlbarTextPlaceholderMarginLeft =
783 CSSToDevPixels(12, sCSSToDevPixelScaling);
784 int urlbarTextPlaceHolderWidth = CSSToDevPixels(
785 std::clamp(urlbarCSSSpan.end - urlbarCSSSpan.start - 10.0, 0.0, 260.0),
786 sCSSToDevPixelScaling);
787 int urlbarTextPlaceholderHeight = CSSToDevPixels(10, sCSSToDevPixelScaling);
788
789 int searchbarTextPlaceholderWidth = CSSToDevPixels(62, sCSSToDevPixelScaling);
790
791 auto scopeExit = MakeScopeExit([&] {
792 delete sAnimatedRects;
793 sAnimatedRects = nullptr;
794 });
795
796 Vector<ColorRect> rects;
797
798 ColorRect menubar = {};
799 menubar.color = currentTheme.titlebarColor;
800 menubar.x = 0;
801 menubar.y = verticalOffset;
802 menubar.width = sWindowWidth;
803 menubar.height = menubarHeightDevPixels;
804 menubar.flipIfRTL = false;
805 if (!rects.append(menubar)) {
806 return Err(PreXULSkeletonUIError::OOM);
807 }
808
809 int placeholderBorderRadius = CSSToDevPixels(4, sCSSToDevPixelScaling);
810 // found in browser.css "--toolbarbutton-border-radius"
811 int urlbarBorderRadius = CSSToDevPixels(4, sCSSToDevPixelScaling);
812
813 // The (traditionally dark blue on Windows) background of the tab bar.
814 ColorRect tabBar = {};
815 tabBar.color = currentTheme.titlebarColor;
816 tabBar.x = 0;
817 tabBar.y = menubar.y + menubar.height;
818 tabBar.width = sWindowWidth;
819 tabBar.height = tabBarHeight;
820 tabBar.flipIfRTL = false;
821 if (!rects.append(tabBar)) {
822 return Err(PreXULSkeletonUIError::OOM);
823 }
824
825 if (!verticalTabs) {
826 // The initial selected tab
827 ColorRect selectedTab = {};
828 selectedTab.color = currentTheme.tabColor;
829 selectedTab.x = titlebarSpacerWidth;
830 selectedTab.y = menubar.y + menubar.height + selectedTabMarginTop;
831 selectedTab.width = selectedTabWidth;
832 selectedTab.height =
833 tabBar.y + tabBar.height - selectedTab.y - selectedTabMarginBottom;
834 selectedTab.borderColor = currentTheme.tabOutlineColor;
835 selectedTab.borderWidth = selectedTabBorderWidth;
836 selectedTab.borderRadius = selectedTabBorderRadius;
837 selectedTab.flipIfRTL = true;
838 if (!rects.append(selectedTab)) {
839 return Err(PreXULSkeletonUIError::OOM);
840 }
841
842 // A placeholder rect representing text that will fill the selected tab
843 // title
844 ColorRect tabTextPlaceholder = {};
845 tabTextPlaceholder.color = currentTheme.toolbarForegroundColor;
846 tabTextPlaceholder.x = selectedTab.x + tabPlaceholderBarMarginLeft;
847 tabTextPlaceholder.y = selectedTab.y + tabPlaceholderBarMarginTop;
848 tabTextPlaceholder.width = tabPlaceholderBarWidth;
849 tabTextPlaceholder.height = tabPlaceholderBarHeight;
850 tabTextPlaceholder.borderRadius = placeholderBorderRadius;
851 tabTextPlaceholder.flipIfRTL = true;
852 if (!rects.append(tabTextPlaceholder)) {
853 return Err(PreXULSkeletonUIError::OOM);
854 }
855
856 if (!sAnimatedRects->append(tabTextPlaceholder)) {
857 return Err(PreXULSkeletonUIError::OOM);
858 }
859 }
860
861 // The toolbar background
862 ColorRect toolbar = {};
863 // In the vertical tabs case the main toolbar is in the titlebar:
864 toolbar.color =
865 verticalTabs ? currentTheme.titlebarColor : currentTheme.backgroundColor;
866 toolbar.x = 0;
867 toolbar.y = tabBar.y + tabBarHeight;
868 toolbar.width = sWindowWidth;
869 toolbar.height = toolbarHeight;
870 toolbar.flipIfRTL = false;
871 if (!rects.append(toolbar)) {
872 return Err(PreXULSkeletonUIError::OOM);
873 }
874
875 // The single-pixel divider line below the toolbar
876 ColorRect chromeContentDivider = {};
877 chromeContentDivider.color = currentTheme.chromeContentDividerColor;
878 chromeContentDivider.x = 0;
879 chromeContentDivider.y = toolbar.y + toolbar.height;
880 chromeContentDivider.width = sWindowWidth;
881 chromeContentDivider.height = chromeContentDividerHeight;
882 chromeContentDivider.flipIfRTL = false;
883 if (!rects.append(chromeContentDivider)) {
884 return Err(PreXULSkeletonUIError::OOM);
885 }
886
887 // The urlbar
888 ColorRect urlbar = {};
889 urlbar.color = currentTheme.urlbarColor;
890 urlbar.x = CSSToDevPixels(urlbarCSSSpan.start, sCSSToDevPixelScaling) +
891 horizontalOffset;
892 urlbar.y = tabBar.y + tabBarHeight + urlbarTopOffset;
893 urlbar.width = CSSToDevPixels((urlbarCSSSpan.end - urlbarCSSSpan.start),
894 sCSSToDevPixelScaling);
895 urlbar.height = urlbarHeight;
896 urlbar.borderColor = currentTheme.urlbarBorderColor;
897 urlbar.borderWidth = CSSToDevPixels(1, sCSSToDevPixelScaling);
898 urlbar.borderRadius = urlbarBorderRadius;
899 urlbar.flipIfRTL = false;
900 if (!rects.append(urlbar)) {
901 return Err(PreXULSkeletonUIError::OOM);
902 }
903
904 // The urlbar placeholder rect representating text that will fill the urlbar
905 // If rtl is enabled, it is flipped relative to the the urlbar rectangle, not
906 // sWindowWidth.
907 ColorRect urlbarTextPlaceholder = {};
908 urlbarTextPlaceholder.color = currentTheme.toolbarForegroundColor;
909 urlbarTextPlaceholder.x =
910 rtlEnabled
911 ? ((urlbar.x + urlbar.width) - urlbarTextPlaceholderMarginLeft -
912 urlbarTextPlaceHolderWidth)
913 : (urlbar.x + urlbarTextPlaceholderMarginLeft);
914 urlbarTextPlaceholder.y = urlbar.y + urlbarTextPlaceholderMarginTop;
915 urlbarTextPlaceholder.width = urlbarTextPlaceHolderWidth;
916 urlbarTextPlaceholder.height = urlbarTextPlaceholderHeight;
917 urlbarTextPlaceholder.borderRadius = placeholderBorderRadius;
918 urlbarTextPlaceholder.flipIfRTL = false;
919 if (!rects.append(urlbarTextPlaceholder)) {
920 return Err(PreXULSkeletonUIError::OOM);
921 }
922
923 // The searchbar and placeholder text, if present
924 // This is y-aligned with the urlbar
925 bool hasSearchbar = searchbarCSSSpan.start != 0 && searchbarCSSSpan.end != 0;
926 ColorRect searchbarRect = {};
927 if (hasSearchbar == true) {
928 searchbarRect.color = currentTheme.urlbarColor;
929 searchbarRect.x =
930 CSSToDevPixels(searchbarCSSSpan.start, sCSSToDevPixelScaling) +
931 horizontalOffset;
932 searchbarRect.y = urlbar.y;
933 searchbarRect.width = CSSToDevPixels(
934 searchbarCSSSpan.end - searchbarCSSSpan.start, sCSSToDevPixelScaling);
935 searchbarRect.height = urlbarHeight;
936 searchbarRect.borderRadius = urlbarBorderRadius;
937 searchbarRect.borderColor = currentTheme.urlbarBorderColor;
938 searchbarRect.borderWidth = CSSToDevPixels(1, sCSSToDevPixelScaling);
939 searchbarRect.flipIfRTL = false;
940 if (!rects.append(searchbarRect)) {
941 return Err(PreXULSkeletonUIError::OOM);
942 }
943
944 // The placeholder rect representating text that will fill the searchbar
945 // This uses the same margins as the urlbarTextPlaceholder
946 // If rtl is enabled, it is flipped relative to the the searchbar rectangle,
947 // not sWindowWidth.
948 ColorRect searchbarTextPlaceholder = {};
949 searchbarTextPlaceholder.color = currentTheme.toolbarForegroundColor;
950 searchbarTextPlaceholder.x =
951 rtlEnabled
952 ? ((searchbarRect.x + searchbarRect.width) -
953 urlbarTextPlaceholderMarginLeft - searchbarTextPlaceholderWidth)
954 : (searchbarRect.x + urlbarTextPlaceholderMarginLeft);
955 searchbarTextPlaceholder.y =
956 searchbarRect.y + urlbarTextPlaceholderMarginTop;
957 searchbarTextPlaceholder.width = searchbarTextPlaceholderWidth;
958 searchbarTextPlaceholder.height = urlbarTextPlaceholderHeight;
959 searchbarTextPlaceholder.flipIfRTL = false;
960 if (!rects.append(searchbarTextPlaceholder) ||
961 !sAnimatedRects->append(searchbarTextPlaceholder)) {
962 return Err(PreXULSkeletonUIError::OOM);
963 }
964 }
965
966 // Determine where the placeholder rectangles should not go. This is
967 // anywhere occupied by a spring, urlbar, or searchbar
968 Vector<DevPixelSpan> noPlaceholderSpans;
969
970 DevPixelSpan urlbarSpan;
971 urlbarSpan.start = urlbar.x - urlbarMargin;
972 urlbarSpan.end = urlbar.width + urlbar.x + urlbarMargin;
973
974 DevPixelSpan searchbarSpan;
975 if (hasSearchbar) {
976 searchbarSpan.start = searchbarRect.x - urlbarMargin;
977 searchbarSpan.end = searchbarRect.width + searchbarRect.x + urlbarMargin;
978 }
979
980 DevPixelSpan marginLeftPlaceholder;
981 marginLeftPlaceholder.start = toolbarPlaceholderMarginLeft;
982 marginLeftPlaceholder.end = toolbarPlaceholderMarginLeft;
983 if (!noPlaceholderSpans.append(marginLeftPlaceholder)) {
984 return Err(PreXULSkeletonUIError::OOM);
985 }
986
987 if (rtlEnabled) {
988 // If we're RTL, then the springs as ordered in the DOM will be from right
989 // to left, which will break our comparison logic below
990 springs.reverse();
991 }
992
993 for (auto spring : springs) {
994 DevPixelSpan springDevPixels;
995 springDevPixels.start =
996 CSSToDevPixels(spring.start, sCSSToDevPixelScaling) + horizontalOffset;
997 springDevPixels.end =
998 CSSToDevPixels(spring.end, sCSSToDevPixelScaling) + horizontalOffset;
999 if (!noPlaceholderSpans.append(springDevPixels)) {
1000 return Err(PreXULSkeletonUIError::OOM);
1001 }
1002 }
1003
1004 DevPixelSpan marginRightPlaceholder;
1005 marginRightPlaceholder.start = sWindowWidth - toolbarPlaceholderMarginRight;
1006 marginRightPlaceholder.end = sWindowWidth - toolbarPlaceholderMarginRight;
1007 if (!noPlaceholderSpans.append(marginRightPlaceholder)) {
1008 return Err(PreXULSkeletonUIError::OOM);
1009 }
1010
1011 Vector<DevPixelSpan, 2> spansToAdd;
1012 Unused << spansToAdd.reserve(2);
1013 spansToAdd.infallibleAppend(urlbarSpan);
1014 if (hasSearchbar) {
1015 spansToAdd.infallibleAppend(searchbarSpan);
1016 }
1017
1018 for (auto& toAdd : spansToAdd) {
1019 for (auto& span : noPlaceholderSpans) {
1020 if (span.start > toAdd.start) {
1021 if (!noPlaceholderSpans.insert(&span, toAdd)) {
1022 return Err(PreXULSkeletonUIError::OOM);
1023 }
1024 break;
1025 }
1026 }
1027 }
1028
1029 for (size_t i = 1; i < noPlaceholderSpans.length(); i++) {
1030 int start = noPlaceholderSpans[i - 1].end + placeholderMargin;
1031 int end = noPlaceholderSpans[i].start - placeholderMargin;
1032 if (start + 2 * placeholderBorderRadius >= end) {
1033 continue;
1034 }
1035
1036 // The placeholder rects should all be y-aligned.
1037 ColorRect placeholderRect = {};
1038 placeholderRect.color = currentTheme.toolbarForegroundColor;
1039 placeholderRect.x = start;
1040 placeholderRect.y = urlbarTextPlaceholder.y;
1041 placeholderRect.width = end - start;
1042 placeholderRect.height = toolbarPlaceholderHeight;
1043 placeholderRect.borderRadius = placeholderBorderRadius;
1044 placeholderRect.flipIfRTL = false;
1045 if (!rects.append(placeholderRect) ||
1046 !sAnimatedRects->append(placeholderRect)) {
1047 return Err(PreXULSkeletonUIError::OOM);
1048 }
1049 }
1050
1051 sTotalChromeHeight = chromeContentDivider.y + chromeContentDivider.height;
1052 if (sTotalChromeHeight > sWindowHeight) {
1053 return Err(PreXULSkeletonUIError::BadWindowDimensions);
1054 }
1055
1056 if (!sAnimatedRects->append(urlbarTextPlaceholder)) {
1057 return Err(PreXULSkeletonUIError::OOM);
1058 }
1059
1060 sPixelBuffer =
1061 (uint32_t*)calloc(sWindowWidth * sTotalChromeHeight, sizeof(uint32_t));
1062
1063 for (auto& rect : *sAnimatedRects) {
1064 if (rtlEnabled && rect.flipIfRTL) {
1065 rect.x = sWindowWidth - rect.x - rect.width;
1066 }
1067 rect.x = std::clamp(rect.x, 0, sWindowWidth);
1068 rect.width = std::clamp(rect.width, 0, sWindowWidth - rect.x);
1069 rect.y = std::clamp(rect.y, 0, sTotalChromeHeight);
1070 rect.height = std::clamp(rect.height, 0, sTotalChromeHeight - rect.y);
1071 }
1072
1073 for (auto& rect : rects) {
1074 if (rtlEnabled && rect.flipIfRTL) {
1075 rect.x = sWindowWidth - rect.x - rect.width;
1076 }
1077 rect.x = std::clamp(rect.x, 0, sWindowWidth);
1078 rect.width = std::clamp(rect.width, 0, sWindowWidth - rect.x);
1079 rect.y = std::clamp(rect.y, 0, sTotalChromeHeight);
1080 rect.height = std::clamp(rect.height, 0, sTotalChromeHeight - rect.y);
1081 RasterizeColorRect(rect);
1082 }
1083
1084 HDC hdc = sGetWindowDC(hWnd);
1085 if (!hdc) {
1086 return Err(PreXULSkeletonUIError::FailedGettingDC);
1087 }
1088 auto cleanupDC = MakeScopeExit([=] { sReleaseDC(hWnd, hdc); });
1089
1090 BITMAPINFO chromeBMI = {};
1091 chromeBMI.bmiHeader.biSize = sizeof(chromeBMI.bmiHeader);
1092 chromeBMI.bmiHeader.biWidth = sWindowWidth;
1093 chromeBMI.bmiHeader.biHeight = -sTotalChromeHeight;
1094 chromeBMI.bmiHeader.biPlanes = 1;
1095 chromeBMI.bmiHeader.biBitCount = 32;
1096 chromeBMI.bmiHeader.biCompression = BI_RGB;
1097
1098 // First, we just paint the chrome area with our pixel buffer
1099 int scanLinesCopied = sStretchDIBits(
1100 hdc, 0, 0, sWindowWidth, sTotalChromeHeight, 0, 0, sWindowWidth,
1101 sTotalChromeHeight, sPixelBuffer, &chromeBMI, DIB_RGB_COLORS, SRCCOPY);
1102 if (scanLinesCopied == 0) {
1103 return Err(PreXULSkeletonUIError::FailedBlitting);
1104 }
1105
1106 // Then, we just fill the rest with FillRect
1107 RECT rect = {0, sTotalChromeHeight, sWindowWidth, sWindowHeight};
1108 bool const fillRectOk =
1109 FillRectWithColor(hdc, &rect, currentTheme.backgroundColor);
1110
1111 if (!fillRectOk) {
1112 return Err(PreXULSkeletonUIError::FailedFillingBottomRect);
1113 }
1114
1115 scopeExit.release();
1116 return Ok();
1117 }
1118
1119 DWORD WINAPI AnimateSkeletonUI(void* aUnused) {
1120 if (!sPixelBuffer || sAnimatedRects->empty()) {
1121 return 0;
1122 }
1123
1124 // See the comments above the InterlockedIncrement calls below here - we
1125 // atomically flip this up and down around sleep so the main thread doesn't
1126 // have to wait for us if we're just sleeping.
1127 if (InterlockedIncrement(&sAnimationControlFlag) != 1) {
1128 return 0;
1129 }
1130 // Sleep for two seconds - startups faster than this don't really benefit
1131 // from an animation, and we don't want to take away cycles from them.
1132 // Startups longer than this, however, are more likely to be blocked on IO,
1133 // and thus animating does not substantially impact startup times for them.
1134 ::Sleep(2000);
1135 if (InterlockedDecrement(&sAnimationControlFlag) != 0) {
1136 return 0;
1137 }
1138
1139 // On each of the animated rects (which happen to all be placeholder UI
1140 // rects sharing the same color), we want to animate a gradient moving across
1141 // the screen from left to right. The gradient starts as the rect's color on,
1142 // the left side, changes to the background color of the window by the middle
1143 // of the gradient, and then goes back down to the rect's color. To make this
1144 // faster than interpolating between the two colors for each pixel for each
1145 // frame, we simply create a lookup buffer in which we can look up the color
1146 // for a particular offset into the gradient.
1147 //
1148 // To do this we just interpolate between the two values, and to give the
1149 // gradient a smoother transition between colors, we transform the linear
1150 // blend amount via the cubic smooth step function (SmoothStep3) to produce
1151 // a smooth start and stop for the gradient. We do this for the first half
1152 // of the gradient, and then simply copy that backwards for the second half.
1153 //
1154 // The CSS width of 80 chosen here is effectively is just to match the size
1155 // of the animation provided in the design mockup. We define it in CSS pixels
1156 // simply because the rest of our UI is based off of CSS scalings.
1157 int animationWidth = CSSToDevPixels(80, sCSSToDevPixelScaling);
1158 UniquePtr<uint32_t[]> animationLookup =
1159 MakeUnique<uint32_t[]>(animationWidth);
1160 uint32_t animationColor = sAnimationColor;
1161 NormalizedRGB rgbBlend = UintToRGB(animationColor);
1162
1163 // Build the first half of the lookup table
1164 for (int i = 0; i < animationWidth / 2; ++i) {
1165 uint32_t baseColor = sToolbarForegroundColor;
1166 double blendAmountLinear =
1167 static_cast<double>(i) / (static_cast<double>(animationWidth / 2));
1168 double blendAmount = SmoothStep3(blendAmountLinear);
1169
1170 NormalizedRGB rgbBase = UintToRGB(baseColor);
1171 NormalizedRGB rgb = Lerp(rgbBase, rgbBlend, blendAmount);
1172 animationLookup[i] = RGBToUint(rgb);
1173 }
1174
1175 // Copy the first half of the lookup table into the second half backwards
1176 for (int i = animationWidth / 2; i < animationWidth; ++i) {
1177 int j = animationWidth - 1 - i;
1178 if (j == animationWidth / 2) {
1179 // If animationWidth is odd, we'll be left with one pixel at the center.
1180 // Just color that as the animation color.
1181 animationLookup[i] = animationColor;
1182 } else {
1183 animationLookup[i] = animationLookup[j];
1184 }
1185 }
1186
1187 // The bitmap info remains unchanged throughout the animation - this just
1188 // effectively describes the contents of sPixelBuffer
1189 BITMAPINFO chromeBMI = {};
1190 chromeBMI.bmiHeader.biSize = sizeof(chromeBMI.bmiHeader);
1191 chromeBMI.bmiHeader.biWidth = sWindowWidth;
1192 chromeBMI.bmiHeader.biHeight = -sTotalChromeHeight;
1193 chromeBMI.bmiHeader.biPlanes = 1;
1194 chromeBMI.bmiHeader.biBitCount = 32;
1195 chromeBMI.bmiHeader.biCompression = BI_RGB;
1196
1197 uint32_t animationIteration = 0;
1198
1199 int devPixelsPerFrame =
1200 CSSToDevPixels(kAnimationCSSPixelsPerFrame, sCSSToDevPixelScaling);
1201 int devPixelsExtraWindowSize =
1202 CSSToDevPixels(kAnimationCSSExtraWindowSize, sCSSToDevPixelScaling);
1203
1204 if (::InterlockedCompareExchange(&sAnimationControlFlag, 0, 0)) {
1205 // The window got consumed before we were able to draw anything.
1206 return 0;
1207 }
1208
1209 while (true) {
1210 // The gradient will move across the screen at devPixelsPerFrame at
1211 // 60fps, and then loop back to the beginning. However, we add a buffer of
1212 // devPixelsExtraWindowSize around the edges so it doesn't immediately
1213 // jump back, giving it a more pulsing feel.
1214 int animationMin = ((animationIteration * devPixelsPerFrame) %
1215 (sWindowWidth + devPixelsExtraWindowSize)) -
1216 devPixelsExtraWindowSize / 2;
1217 int animationMax = animationMin + animationWidth;
1218 // The priorAnimationMin is the beginning of the previous frame's animation.
1219 // Since we only want to draw the bits of the image that we updated, we need
1220 // to overwrite the left bit of the animation we drew last frame with the
1221 // default color.
1222 int priorAnimationMin = animationMin - devPixelsPerFrame;
1223 animationMin = std::max(0, animationMin);
1224 priorAnimationMin = std::max(0, priorAnimationMin);
1225 animationMax = std::min((int)sWindowWidth, animationMax);
1226
1227 // The gradient only affects the specific rects that we put into
1228 // sAnimatedRects. So we simply update those rects, and maintain a flag
1229 // to avoid drawing when we don't need to.
1230 bool updatedAnything = false;
1231 for (ColorRect rect : *sAnimatedRects) {
1232 bool hadUpdates =
1233 RasterizeAnimatedRect(rect, animationLookup.get(), priorAnimationMin,
1234 animationMin, animationMax);
1235 updatedAnything = updatedAnything || hadUpdates;
1236 }
1237
1238 if (updatedAnything) {
1239 HDC hdc = sGetWindowDC(sPreXULSkeletonUIWindow);
1240 if (!hdc) {
1241 return 0;
1242 }
1243
1244 sStretchDIBits(hdc, priorAnimationMin, 0,
1245 animationMax - priorAnimationMin, sTotalChromeHeight,
1246 priorAnimationMin, 0, animationMax - priorAnimationMin,
1247 sTotalChromeHeight, sPixelBuffer, &chromeBMI,
1248 DIB_RGB_COLORS, SRCCOPY);
1249
1250 sReleaseDC(sPreXULSkeletonUIWindow, hdc);
1251 }
1252
1253 animationIteration++;
1254
1255 // We coordinate around our sleep here to ensure that the main thread does
1256 // not wait on us if we're sleeping. If we don't get 1 here, it means the
1257 // window has been consumed and we don't need to sleep. If in
1258 // ConsumePreXULSkeletonUIHandle we get a value other than 1 after
1259 // incrementing, it means we're sleeping, and that function can assume that
1260 // we will safely exit after the sleep because of the observed value of
1261 // sAnimationControlFlag.
1262 if (InterlockedIncrement(&sAnimationControlFlag) != 1) {
1263 return 0;
1264 }
1265
1266 // Note: Sleep does not guarantee an exact time interval. If the system is
1267 // busy, for instance, we could easily end up taking several frames longer,
1268 // and really we could be left unscheduled for an arbitrarily long time.
1269 // This is fine, and we don't really care. We could track how much time this
1270 // actually took and jump the animation forward the appropriate amount, but
1271 // its not even clear that that's a better user experience. So we leave this
1272 // as simple as we can.
1273 ::Sleep(16);
1274
1275 // Here we bring sAnimationControlFlag back down - again, if we don't get a
1276 // 0 here it means we consumed the skeleton UI window in the mean time, so
1277 // we can simply exit.
1278 if (InterlockedDecrement(&sAnimationControlFlag) != 0) {
1279 return 0;
1280 }
1281 }
1282 }
1283
1284 LRESULT WINAPI PreXULSkeletonUIProc(HWND hWnd, UINT msg, WPARAM wParam,
1285 LPARAM lParam) {
1286 // Exposing a generic oleacc proxy for the skeleton isn't useful and may cause
1287 // screen readers to report spurious information when the skeleton appears.
1288 if (msg == WM_GETOBJECT && sPreXULSkeletonUIWindow) {
1289 return E_FAIL;
1290 }
1291
1292 // NOTE: this block was copied from WinUtils.cpp, and needs to be kept in
1293 // sync.
1294 if (msg == WM_NCCREATE && sEnableNonClientDpiScaling) {
1295 sEnableNonClientDpiScaling(hWnd);
1296 }
1297
1298 // NOTE: this block was paraphrased from the WM_NCCALCSIZE handler in
1299 // nsWindow.cpp, and will need to be kept in sync.
1300 if (msg == WM_NCCALCSIZE) {
1301 RECT* clientRect =
1302 wParam ? &(reinterpret_cast<NCCALCSIZE_PARAMS*>(lParam))->rgrc[0]
1303 : (reinterpret_cast<RECT*>(lParam));
1304
1305 Margin margin = NonClientSizeMargin();
1306 clientRect->top += margin.top;
1307 clientRect->left += margin.left;
1308 clientRect->right -= margin.right;
1309 clientRect->bottom -= margin.bottom;
1310
1311 return 0;
1312 }
1313
1314 return ::DefWindowProcW(hWnd, msg, wParam, lParam);
1315 }
1316
1317 bool IsSystemDarkThemeEnabled() {
1318 DWORD result;
1319 HKEY themeKey;
1320 DWORD dataLen = sizeof(uint32_t);
1321 LPCWSTR keyName =
1322 L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize";
1323
1324 result = ::RegOpenKeyExW(HKEY_CURRENT_USER, keyName, 0, KEY_READ, &themeKey);
1325 if (result != ERROR_SUCCESS) {
1326 return false;
1327 }
1328 AutoCloseRegKey closeKey(themeKey);
1329
1330 uint32_t lightThemeEnabled;
1331 result = ::RegGetValueW(
1332 themeKey, nullptr, L"AppsUseLightTheme", RRF_RT_REG_DWORD, nullptr,
1333 reinterpret_cast<PBYTE>(&lightThemeEnabled), &dataLen);
1334 if (result != ERROR_SUCCESS) {
1335 return false;
1336 }
1337 return !lightThemeEnabled;
1338 }
1339
1340 ThemeColors GetTheme(ThemeMode themeId) {
1341 ThemeColors theme = {};
1342 switch (themeId) {
1343 case ThemeMode::Dark:
1344 // Dark theme or default theme when in dark mode
1345
1346 // controlled by css variable --toolbar-bgcolor
1347 theme.backgroundColor = 0x2b2a33;
1348 theme.tabColor = 0x42414d;
1349 theme.toolbarForegroundColor = 0x6a6a6d;
1350 theme.tabOutlineColor = 0x1c1b22;
1351 // controlled by css variable --lwt-accent-color
1352 theme.titlebarColor = 0x1c1b22;
1353 // controlled by --toolbar-color in browser.css
1354 theme.chromeContentDividerColor = 0x0c0c0d;
1355 // controlled by css variable --toolbar-field-background-color
1356 theme.urlbarColor = 0x42414d;
1357 theme.urlbarBorderColor = 0x42414d;
1358 theme.animationColor = theme.urlbarColor;
1359 return theme;
1360 case ThemeMode::Light:
1361 case ThemeMode::Default:
1362 default:
1363 // --toolbar-bgcolor in browser.css
1364 theme.backgroundColor = 0xf9f9fb;
1365 theme.tabColor = 0xf9f9fb;
1366 theme.toolbarForegroundColor = 0xdddde1;
1367 theme.tabOutlineColor = 0xdddde1;
1368 theme.titlebarColor = 0xeaeaed;
1369 // --chrome-content-separator-color in browser.css
1370 theme.chromeContentDividerColor = 0xe1e1e2;
1371 // controlled by css variable --toolbar-color
1372 theme.urlbarColor = 0xffffff;
1373 theme.urlbarBorderColor = 0xdddde1;
1374 theme.animationColor = theme.backgroundColor;
1375 return theme;
1376 }
1377 }
1378
1379 Result<HKEY, PreXULSkeletonUIError> OpenPreXULSkeletonUIRegKey() {
1380 HKEY key;
1381 DWORD disposition;
1382 LSTATUS result =
1383 ::RegCreateKeyExW(HKEY_CURRENT_USER, kPreXULSkeletonUIKeyPath, 0, nullptr,
1384 0, KEY_ALL_ACCESS, nullptr, &key, &disposition);
1385
1386 if (result != ERROR_SUCCESS) {
1387 return Err(PreXULSkeletonUIError::FailedToOpenRegistryKey);
1388 }
1389
1390 if (disposition == REG_CREATED_NEW_KEY ||
1391 disposition == REG_OPENED_EXISTING_KEY) {
1392 return key;
1393 }
1394
1395 ::RegCloseKey(key);
1396 return Err(PreXULSkeletonUIError::FailedToOpenRegistryKey);
1397 }
1398
1399 Result<Ok, PreXULSkeletonUIError> LoadGdi32AndUser32Procedures() {
1400 HMODULE user32Dll = ::LoadLibraryW(L"user32");
1401 HMODULE gdi32Dll = ::LoadLibraryW(L"gdi32");
1402 HMODULE dwmapiDll = ::LoadLibraryW(L"dwmapi.dll");
1403
1404 if (!user32Dll || !gdi32Dll || !dwmapiDll) {
1405 return Err(PreXULSkeletonUIError::FailedLoadingDynamicProcs);
1406 }
1407
1408 #define MOZ_LOAD_OR_FAIL(dll_handle, name) \
1409 do { \
1410 s##name = (decltype(&::name))::GetProcAddress(dll_handle, #name); \
1411 if (!s##name) { \
1412 return Err(PreXULSkeletonUIError::FailedLoadingDynamicProcs); \
1413 } \
1414 } while (0)
1415
1416 auto getThreadDpiAwarenessContext =
1417 (decltype(GetThreadDpiAwarenessContext)*)::GetProcAddress(
1418 user32Dll, "GetThreadDpiAwarenessContext");
1419 auto areDpiAwarenessContextsEqual =
1420 (decltype(AreDpiAwarenessContextsEqual)*)::GetProcAddress(
1421 user32Dll, "AreDpiAwarenessContextsEqual");
1422 if (getThreadDpiAwarenessContext && areDpiAwarenessContextsEqual &&
1423 areDpiAwarenessContextsEqual(getThreadDpiAwarenessContext(),
1424 DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE)) {
1425 // EnableNonClientDpiScaling is first available in Win10 Build 1607, but
1426 // it's optional - we can handle not having it.
1427 Unused << [&]() -> Result<Ok, PreXULSkeletonUIError> {
1428 MOZ_LOAD_OR_FAIL(user32Dll, EnableNonClientDpiScaling);
1429 return Ok{};
1430 }();
1431 }
1432
1433 MOZ_LOAD_OR_FAIL(user32Dll, GetSystemMetricsForDpi);
1434 MOZ_LOAD_OR_FAIL(user32Dll, GetDpiForWindow);
1435 MOZ_LOAD_OR_FAIL(user32Dll, RegisterClassW);
1436 MOZ_LOAD_OR_FAIL(user32Dll, CreateWindowExW);
1437 MOZ_LOAD_OR_FAIL(user32Dll, ShowWindow);
1438 MOZ_LOAD_OR_FAIL(user32Dll, SetWindowPos);
1439 MOZ_LOAD_OR_FAIL(user32Dll, GetWindowDC);
1440 MOZ_LOAD_OR_FAIL(user32Dll, GetWindowRect);
1441 MOZ_LOAD_OR_FAIL(user32Dll, MapWindowPoints);
1442 MOZ_LOAD_OR_FAIL(user32Dll, FillRect);
1443 MOZ_LOAD_OR_FAIL(user32Dll, ReleaseDC);
1444 MOZ_LOAD_OR_FAIL(user32Dll, LoadIconW);
1445 MOZ_LOAD_OR_FAIL(user32Dll, LoadCursorW);
1446 MOZ_LOAD_OR_FAIL(user32Dll, MonitorFromWindow);
1447 MOZ_LOAD_OR_FAIL(user32Dll, GetMonitorInfoW);
1448 MOZ_LOAD_OR_FAIL(user32Dll, SetWindowLongPtrW);
1449 MOZ_LOAD_OR_FAIL(gdi32Dll, StretchDIBits);
1450 MOZ_LOAD_OR_FAIL(gdi32Dll, CreateSolidBrush);
1451 MOZ_LOAD_OR_FAIL(gdi32Dll, DeleteObject);
1452 MOZ_LOAD_OR_FAIL(dwmapiDll, DwmGetWindowAttribute);
1453 MOZ_LOAD_OR_FAIL(dwmapiDll, DwmSetWindowAttribute);
1454
1455 #undef MOZ_LOAD_OR_FAIL
1456
1457 return Ok();
1458 }
1459
1460 // Strips "--", "-", and "/" from the front of the arg if one of those exists,
1461 // returning `arg + 2`, `arg + 1`, and `arg + 1` respectively. If none of these
1462 // prefixes are found, the argument is not a flag, and nullptr is returned.
1463 const char* NormalizeFlag(const char* arg) {
1464 if (strstr(arg, "--") == arg) {
1465 return arg + 2;
1466 }
1467
1468 if (arg[0] == '-') {
1469 return arg + 1;
1470 }
1471
1472 if (arg[0] == '/') {
1473 return arg + 1;
1474 }
1475
1476 return nullptr;
1477 }
1478
1479 static bool EnvHasValue(const char* name) {
1480 const char* val = getenv(name);
1481 return (val && *val);
1482 }
1483
1484 // Ensures that we only see arguments in the command line which are acceptable.
1485 // This is based on manual inspection of the list of arguments listed in the MDN
1486 // page for Gecko/Firefox commandline options:
1487 // https://developer.mozilla.org/en-US/docs/Mozilla/Command_Line_Options
1488 // Broadly speaking, we want to reject any argument which causes us to show
1489 // something other than the default window at its normal size. Here is a non-
1490 // exhaustive list of command line options we want to *exclude*:
1491 //
1492 // -ProfileManager : This will display the profile manager window, which does
1493 // not match the skeleton UI at all.
1494 //
1495 // -CreateProfile : This will display a firefox window with the default
1496 // screen position and size, and not the position and size
1497 // which we have recorded in the registry.
1498 //
1499 // -P <profile> : This could cause us to display firefox with a position
1500 // and size of a different profile than that in which we
1501 // were previously running.
1502 //
1503 // -width, -height : This will cause the width and height values in the
1504 // registry to be incorrect.
1505 //
1506 // -kiosk : See above.
1507 //
1508 // -headless : This one should be rather obvious.
1509 //
1510 // -migration : This will start with the import wizard, which of course
1511 // does not match the skeleton UI.
1512 //
1513 // -private-window : This is tricky, but the colors of the main content area
1514 // make this not feel great with the white content of the
1515 // default skeleton UI.
1516 //
1517 // NOTE: we generally want to skew towards erroneous rejections of the command
1518 // line rather than erroneous approvals. The consequence of a bad rejection
1519 // is that we don't show the skeleton UI, which is business as usual. The
1520 // consequence of a bad approval is that we show it when we're not supposed to,
1521 // which is visually jarring and can also be unpredictable - there's no
1522 // guarantee that the code which handles the non-default window is set up to
1523 // properly handle the transition from the skeleton UI window.
1524 static Result<Ok, PreXULSkeletonUIError> ValidateCmdlineArguments(
1525 int argc, char** argv, bool* explicitProfile) {
1526 const char* approvedArgumentsArray[] = {
1527 // These won't cause the browser to be visualy different in any way
1528 "new-instance", "no-remote", "browser", "foreground", "setDefaultBrowser",
1529 "attach-console", "wait-for-browser", "osint",
1530
1531 // These will cause the chrome to be a bit different or extra windows to
1532 // be created, but overall the skeleton UI should still be broadly
1533 // correct enough.
1534 "new-tab", "new-window",
1535
1536 // To the extent possible, we want to ensure that existing tests cover
1537 // the skeleton UI, so we need to allow marionette
1538 "marionette",
1539
1540 // These will cause the content area to appear different, but won't
1541 // meaningfully affect the chrome
1542 "preferences", "search", "url",
1543
1544 #ifndef MOZILLA_OFFICIAL
1545 // On local builds, we want to allow -profile, because it's how `mach run`
1546 // operates, and excluding that would create an unnecessary blind spot for
1547 // Firefox devs.
1548 "profile"
1549 #endif
1550
1551 // There are other arguments which are likely okay. However, they are
1552 // not included here because this list is not intended to be
1553 // exhaustive - it only intends to green-light some somewhat commonly
1554 // used arguments. We want to err on the side of an unnecessary
1555 // rejection of the command line.
1556 };
1557
1558 int approvedArgumentsArraySize =
1559 sizeof(approvedArgumentsArray) / sizeof(approvedArgumentsArray[0]);
1560 Vector<const char*> approvedArguments;
1561 if (!approvedArguments.reserve(approvedArgumentsArraySize)) {
1562 return Err(PreXULSkeletonUIError::OOM);
1563 }
1564
1565 for (int i = 0; i < approvedArgumentsArraySize; ++i) {
1566 approvedArguments.infallibleAppend(approvedArgumentsArray[i]);
1567 }
1568
1569 #ifdef MOZILLA_OFFICIAL
1570 int profileArgIndex = -1;
1571 // If we're running mochitests or direct marionette tests, those specify a
1572 // temporary profile, and we want to ensure that we get the added coverage
1573 // from those.
1574 for (int i = 1; i < argc; ++i) {
1575 const char* flag = NormalizeFlag(argv[i]);
1576 if (flag && !strcmp(flag, "marionette")) {
1577 if (!approvedArguments.append("profile")) {
1578 return Err(PreXULSkeletonUIError::OOM);
1579 }
1580 profileArgIndex = approvedArguments.length() - 1;
1581
1582 break;
1583 }
1584 }
1585 #else
1586 int profileArgIndex = approvedArguments.length() - 1;
1587 #endif
1588
1589 for (int i = 1; i < argc; ++i) {
1590 const char* flag = NormalizeFlag(argv[i]);
1591 if (!flag) {
1592 // If this is not a flag, then we interpret it as a URL, similar to
1593 // BrowserContentHandler.sys.mjs. Some command line options take
1594 // additional arguments, which may or may not be URLs. We don't need to
1595 // know this, because we don't need to parse them out; we just rely on the
1596 // assumption that if arg X is actually a parameter for the preceding
1597 // arg Y, then X must not look like a flag (starting with "--", "-",
1598 // or "/").
1599 //
1600 // The most important thing here is the assumption that if something is
1601 // going to meaningfully alter the appearance of the window itself, it
1602 // must be a flag.
1603 continue;
1604 }
1605
1606 bool approved = false;
1607 for (const char* approvedArg : approvedArguments) {
1608 // We do a case-insensitive compare here with _stricmp. Even though some
1609 // of these arguments are *not* read as case-insensitive, others *are*.
1610 // Similar to the flag logic above, we don't really care about this
1611 // distinction, because we don't need to parse the arguments - we just
1612 // rely on the assumption that none of the listed flags in our
1613 // approvedArguments are overloaded in such a way that a different
1614 // casing would visually alter the firefox window.
1615 if (!_stricmp(flag, approvedArg)) {
1616 approved = true;
1617
1618 if (i == profileArgIndex) {
1619 *explicitProfile = true;
1620 }
1621 break;
1622 }
1623 }
1624
1625 if (!approved) {
1626 return Err(PreXULSkeletonUIError::Cmdline);
1627 }
1628 }
1629
1630 return Ok();
1631 }
1632
1633 static Result<Ok, PreXULSkeletonUIError> ValidateEnvVars() {
1634 if (EnvHasValue("MOZ_SAFE_MODE_RESTART") ||
1635 EnvHasValue("MOZ_APP_SILENT_START") ||
1636 EnvHasValue("MOZ_RESET_PROFILE_RESTART") || EnvHasValue("MOZ_HEADLESS") ||
1637 (EnvHasValue("XRE_PROFILE_PATH") &&
1638 !EnvHasValue("MOZ_SKELETON_UI_RESTARTING"))) {
1639 return Err(PreXULSkeletonUIError::EnvVars);
1640 }
1641
1642 return Ok();
1643 }
1644
1645 static bool VerifyWindowDimensions(uint32_t windowWidth,
1646 uint32_t windowHeight) {
1647 return windowWidth <= kMaxWindowWidth && windowHeight <= kMaxWindowHeight;
1648 }
1649
1650 static Result<Vector<CSSPixelSpan>, PreXULSkeletonUIError> ReadRegCSSPixelSpans(
1651 HKEY regKey, const std::wstring& valueName) {
1652 DWORD dataLen = 0;
1653 LSTATUS result = ::RegQueryValueExW(regKey, valueName.c_str(), nullptr,
1654 nullptr, nullptr, &dataLen);
1655 if (result != ERROR_SUCCESS) {
1656 return Err(PreXULSkeletonUIError::RegistryError);
1657 }
1658
1659 if (dataLen % (2 * sizeof(double)) != 0) {
1660 return Err(PreXULSkeletonUIError::CorruptData);
1661 }
1662
1663 auto buffer = MakeUniqueFallible<wchar_t[]>(dataLen);
1664 if (!buffer) {
1665 return Err(PreXULSkeletonUIError::OOM);
1666 }
1667 result =
1668 ::RegGetValueW(regKey, nullptr, valueName.c_str(), RRF_RT_REG_BINARY,
1669 nullptr, reinterpret_cast<PBYTE>(buffer.get()), &dataLen);
1670 if (result != ERROR_SUCCESS) {
1671 return Err(PreXULSkeletonUIError::RegistryError);
1672 }
1673
1674 Vector<CSSPixelSpan> resultVector;
1675 double* asDoubles = reinterpret_cast<double*>(buffer.get());
1676 for (size_t i = 0; i < dataLen / (2 * sizeof(double)); i++) {
1677 CSSPixelSpan span = {};
1678 span.start = *(asDoubles++);
1679 span.end = *(asDoubles++);
1680 if (!resultVector.append(span)) {
1681 return Err(PreXULSkeletonUIError::OOM);
1682 }
1683 }
1684
1685 return resultVector;
1686 }
1687
1688 static Result<double, PreXULSkeletonUIError> ReadRegDouble(
1689 HKEY regKey, const std::wstring& valueName) {
1690 double value = 0;
1691 DWORD dataLen = sizeof(double);
1692 LSTATUS result =
1693 ::RegGetValueW(regKey, nullptr, valueName.c_str(), RRF_RT_REG_BINARY,
1694 nullptr, reinterpret_cast<PBYTE>(&value), &dataLen);
1695 if (result != ERROR_SUCCESS || dataLen != sizeof(double)) {
1696 return Err(PreXULSkeletonUIError::RegistryError);
1697 }
1698
1699 return value;
1700 }
1701
1702 static Result<uint32_t, PreXULSkeletonUIError> ReadRegUint(
1703 HKEY regKey, const std::wstring& valueName) {
1704 DWORD value = 0;
1705 DWORD dataLen = sizeof(uint32_t);
1706 LSTATUS result =
1707 ::RegGetValueW(regKey, nullptr, valueName.c_str(), RRF_RT_REG_DWORD,
1708 nullptr, reinterpret_cast<PBYTE>(&value), &dataLen);
1709 if (result != ERROR_SUCCESS) {
1710 return Err(PreXULSkeletonUIError::RegistryError);
1711 }
1712
1713 return value;
1714 }
1715
1716 static Result<bool, PreXULSkeletonUIError> ReadRegBool(
1717 HKEY regKey, const std::wstring& valueName) {
1718 uint32_t value;
1719 MOZ_TRY_VAR(value, ReadRegUint(regKey, valueName));
1720 return !!value;
1721 }
1722
1723 static Result<Ok, PreXULSkeletonUIError> WriteRegCSSPixelSpans(
1724 HKEY regKey, const std::wstring& valueName, const CSSPixelSpan* spans,
1725 int spansLength) {
1726 // No guarantee on the packing of CSSPixelSpan. We could #pragma it, but it's
1727 // also trivial to just copy them into a buffer of doubles.
1728 auto doubles = MakeUnique<double[]>(spansLength * 2);
1729 for (int i = 0; i < spansLength; ++i) {
1730 doubles[i * 2] = spans[i].start;
1731 doubles[i * 2 + 1] = spans[i].end;
1732 }
1733
1734 LSTATUS result =
1735 ::RegSetValueExW(regKey, valueName.c_str(), 0, REG_BINARY,
1736 reinterpret_cast<const BYTE*>(doubles.get()),
1737 spansLength * sizeof(double) * 2);
1738 if (result != ERROR_SUCCESS) {
1739 return Err(PreXULSkeletonUIError::RegistryError);
1740 }
1741 return Ok();
1742 }
1743
1744 static Result<Ok, PreXULSkeletonUIError> WriteRegDouble(
1745 HKEY regKey, const std::wstring& valueName, double value) {
1746 LSTATUS result =
1747 ::RegSetValueExW(regKey, valueName.c_str(), 0, REG_BINARY,
1748 reinterpret_cast<const BYTE*>(&value), sizeof(value));
1749 if (result != ERROR_SUCCESS) {
1750 return Err(PreXULSkeletonUIError::RegistryError);
1751 }
1752
1753 return Ok();
1754 }
1755
1756 static Result<Ok, PreXULSkeletonUIError> WriteRegUint(
1757 HKEY regKey, const std::wstring& valueName, uint32_t value) {
1758 LSTATUS result =
1759 ::RegSetValueExW(regKey, valueName.c_str(), 0, REG_DWORD,
1760 reinterpret_cast<PBYTE>(&value), sizeof(value));
1761 if (result != ERROR_SUCCESS) {
1762 return Err(PreXULSkeletonUIError::RegistryError);
1763 }
1764
1765 return Ok();
1766 }
1767
1768 static Result<Ok, PreXULSkeletonUIError> WriteRegBool(
1769 HKEY regKey, const std::wstring& valueName, bool value) {
1770 return WriteRegUint(regKey, valueName, value ? 1 : 0);
1771 }
1772
1773 static Result<Ok, PreXULSkeletonUIError> CreateAndStorePreXULSkeletonUIImpl(
1774 HINSTANCE hInstance, int argc, char** argv) {
1775 // Initializing COM below may load modules via SetWindowHookEx, some of
1776 // which may modify the executable's IAT for ntdll.dll. If that happens,
1777 // this browser process fails to launch sandbox processes because we cannot
1778 // copy a modified IAT into a remote process (See SandboxBroker::LaunchApp).
1779 // To prevent that, we cache the intact IAT before COM initialization.
1780 // If EAF+ is enabled, CacheNtDllThunk() causes a crash, but EAF+ will
1781 // also prevent an injected module from parsing the PE headers and modifying
1782 // the IAT. Therefore, we can skip CacheNtDllThunk().
1783 if (!mozilla::IsEafPlusEnabled()) {
1784 CacheNtDllThunk();
1785 }
1786
1787 // NOTE: it's important that we initialize sProcessRuntime before showing a
1788 // window. Historically we ran into issues where showing the window would
1789 // cause an accessibility win event to fire, which could cause in-process
1790 // system or third party components to initialize COM and prevent us from
1791 // initializing it with important settings we need.
1792
1793 // Some COM settings are global to the process and must be set before any non-
1794 // trivial COM is run in the application. Since these settings may affect
1795 // stability, we should instantiate COM ASAP so that we can ensure that these
1796 // global settings are configured before anything can interfere.
1797 sProcessRuntime = new mscom::ProcessRuntime(
1798 mscom::ProcessRuntime::ProcessCategory::GeckoBrowserParent);
1799
1800 const TimeStamp skeletonStart = TimeStamp::Now();
1801
1802 HKEY regKey;
1803 MOZ_TRY_VAR(regKey, OpenPreXULSkeletonUIRegKey());
1804 AutoCloseRegKey closeKey(regKey);
1805
1806 UniquePtr<wchar_t[]> binPath;
1807 MOZ_TRY_VAR(binPath, GetBinaryPath());
1808
1809 std::wstring regProgressName =
1810 GetRegValueName(binPath.get(), sProgressSuffix);
1811 auto progressResult = ReadRegUint(regKey, regProgressName);
1812 if (!progressResult.isErr() &&
1813 progressResult.unwrap() !=
1814 static_cast<uint32_t>(PreXULSkeletonUIProgress::Completed)) {
1815 return Err(PreXULSkeletonUIError::CrashedOnce);
1816 }
1817
1818 MOZ_TRY(
1819 WriteRegUint(regKey, regProgressName,
1820 static_cast<uint32_t>(PreXULSkeletonUIProgress::Started)));
1821 auto writeCompletion = MakeScopeExit([&] {
1822 Unused << WriteRegUint(
1823 regKey, regProgressName,
1824 static_cast<uint32_t>(PreXULSkeletonUIProgress::Completed));
1825 });
1826
1827 MOZ_TRY(GetSkeletonUILock());
1828
1829 bool explicitProfile = false;
1830 MOZ_TRY(ValidateCmdlineArguments(argc, argv, &explicitProfile));
1831 MOZ_TRY(ValidateEnvVars());
1832
1833 auto enabledResult =
1834 ReadRegBool(regKey, GetRegValueName(binPath.get(), sEnabledRegSuffix));
1835 if (enabledResult.isErr()) {
1836 return Err(PreXULSkeletonUIError::EnabledKeyDoesNotExist);
1837 }
1838 if (!enabledResult.unwrap()) {
1839 return Err(PreXULSkeletonUIError::Disabled);
1840 }
1841 sPreXULSkeletonUIEnabled = true;
1842
1843 MOZ_ASSERT(!sAnimatedRects);
1844 sAnimatedRects = new Vector<ColorRect>();
1845
1846 MOZ_TRY(LoadGdi32AndUser32Procedures());
1847
1848 if (!explicitProfile) {
1849 MOZ_TRY(CheckForStartWithLastProfile());
1850 }
1851
1852 WNDCLASSW wc;
1853 wc.style = CS_DBLCLKS;
1854 wc.lpfnWndProc = PreXULSkeletonUIProc;
1855 wc.cbClsExtra = 0;
1856 wc.cbWndExtra = 0;
1857 wc.hInstance = hInstance;
1858 wc.hIcon = sLoadIconW(::GetModuleHandleW(nullptr), gStockApplicationIcon);
1859 wc.hCursor = sLoadCursorW(hInstance, gIDCWait);
1860 wc.hbrBackground = nullptr;
1861 wc.lpszMenuName = nullptr;
1862
1863 // TODO: just ensure we disable this if we've overridden the window class
1864 wc.lpszClassName = L"MozillaWindowClass";
1865
1866 if (!sRegisterClassW(&wc)) {
1867 return Err(PreXULSkeletonUIError::FailedRegisteringWindowClass);
1868 }
1869
1870 uint32_t screenX;
1871 MOZ_TRY_VAR(screenX, ReadRegUint(regKey, GetRegValueName(binPath.get(),
1872 sScreenXRegSuffix)));
1873 uint32_t screenY;
1874 MOZ_TRY_VAR(screenY, ReadRegUint(regKey, GetRegValueName(binPath.get(),
1875 sScreenYRegSuffix)));
1876 uint32_t windowWidth;
1877 MOZ_TRY_VAR(
1878 windowWidth,
1879 ReadRegUint(regKey, GetRegValueName(binPath.get(), sWidthRegSuffix)));
1880 uint32_t windowHeight;
1881 MOZ_TRY_VAR(
1882 windowHeight,
1883 ReadRegUint(regKey, GetRegValueName(binPath.get(), sHeightRegSuffix)));
1884 MOZ_TRY_VAR(
1885 sMaximized,
1886 ReadRegBool(regKey, GetRegValueName(binPath.get(), sMaximizedRegSuffix)));
1887 MOZ_TRY_VAR(
1888 sCSSToDevPixelScaling,
1889 ReadRegDouble(regKey, GetRegValueName(binPath.get(),
1890 sCssToDevPixelScalingRegSuffix)));
1891 Vector<CSSPixelSpan> urlbar;
1892 MOZ_TRY_VAR(urlbar,
1893 ReadRegCSSPixelSpans(
1894 regKey, GetRegValueName(binPath.get(), sUrlbarCSSRegSuffix)));
1895 Vector<CSSPixelSpan> searchbar;
1896 MOZ_TRY_VAR(searchbar,
1897 ReadRegCSSPixelSpans(
1898 regKey, GetRegValueName(binPath.get(), sSearchbarRegSuffix)));
1899 Vector<CSSPixelSpan> springs;
1900 MOZ_TRY_VAR(springs, ReadRegCSSPixelSpans(
1901 regKey, GetRegValueName(binPath.get(),
1902 sSpringsCSSRegSuffix)));
1903
1904 if (urlbar.empty() || searchbar.empty()) {
1905 return Err(PreXULSkeletonUIError::CorruptData);
1906 }
1907
1908 EnumSet<SkeletonUIFlag, uint32_t> flags;
1909 uint32_t flagsUint;
1910 MOZ_TRY_VAR(flagsUint, ReadRegUint(regKey, GetRegValueName(binPath.get(),
1911 sFlagsRegSuffix)));
1912 flags.deserialize(flagsUint);
1913
1914 if (flags.contains(SkeletonUIFlag::TouchDensity) ||
1915 flags.contains(SkeletonUIFlag::CompactDensity)) {
1916 return Err(PreXULSkeletonUIError::BadUIDensity);
1917 }
1918
1919 uint32_t theme;
1920 MOZ_TRY_VAR(theme, ReadRegUint(regKey, GetRegValueName(binPath.get(),
1921 sThemeRegSuffix)));
1922 ThemeMode themeMode = static_cast<ThemeMode>(theme);
1923 if (themeMode == ThemeMode::Default) {
1924 if (IsSystemDarkThemeEnabled()) {
1925 themeMode = ThemeMode::Dark;
1926 }
1927 }
1928 ThemeColors currentTheme = GetTheme(themeMode);
1929
1930 if (!VerifyWindowDimensions(windowWidth, windowHeight)) {
1931 return Err(PreXULSkeletonUIError::BadWindowDimensions);
1932 }
1933
1934 int showCmd = SW_SHOWNORMAL;
1935 DWORD windowStyle = kPreXULSkeletonUIWindowStyle;
1936 if (sMaximized) {
1937 showCmd = SW_SHOWMAXIMIZED;
1938 windowStyle |= WS_MAXIMIZE;
1939 }
1940
1941 sPreXULSkeletonUIWindow =
1942 sCreateWindowExW(kPreXULSkeletonUIWindowStyleEx, L"MozillaWindowClass",
1943 L"", windowStyle, screenX, screenY, windowWidth,
1944 windowHeight, nullptr, nullptr, hInstance, nullptr);
1945 if (!sPreXULSkeletonUIWindow) {
1946 return Err(PreXULSkeletonUIError::CreateWindowFailed);
1947 }
1948
1949 // DWM displays garbage immediately on Show(), and that garbage is usually
1950 // mostly #FFFFFF. To avoid a bright flash when the window is first created,
1951 // cloak the window while showing it, and fill it with the appropriate
1952 // background color before uncloaking it.
1953 {
1954 constexpr static auto const CloakWindow = [](HWND hwnd, BOOL state) {
1955 sDwmSetWindowAttribute(sPreXULSkeletonUIWindow, DWMWA_CLOAK, &state,
1956 sizeof(state));
1957 };
1958 // Equivalent to ::OffsetRect, with no dynamic-symbol resolution needed.
1959 constexpr static auto const OffsetRect = [](LPRECT rect, int dx, int dy) {
1960 rect->left += dx;
1961 rect->top += dy;
1962 rect->right += dx;
1963 rect->bottom += dy;
1964 };
1965
1966 CloakWindow(sPreXULSkeletonUIWindow, TRUE);
1967 auto const _uncloak =
1968 MakeScopeExit([&]() { CloakWindow(sPreXULSkeletonUIWindow, FALSE); });
1969 sShowWindow(sPreXULSkeletonUIWindow, showCmd);
1970
1971 HDC hdc = sGetWindowDC(sPreXULSkeletonUIWindow);
1972 if (!hdc) {
1973 return Err(PreXULSkeletonUIError::FailedGettingDC);
1974 }
1975 auto const _cleanupDC =
1976 MakeScopeExit([&] { sReleaseDC(sPreXULSkeletonUIWindow, hdc); });
1977
1978 // This should match the related code in nsWindow::Show.
1979 RECT rect;
1980 sGetWindowRect(sPreXULSkeletonUIWindow, &rect); // includes non-client area
1981 // screen-to-client (handling RTL if necessary)
1982 sMapWindowPoints(HWND_DESKTOP, sPreXULSkeletonUIWindow, (LPPOINT)&rect, 2);
1983 // client-to-window (no RTL handling needed)
1984 OffsetRect(&rect, -rect.left, -rect.top);
1985 FillRectWithColor(hdc, &rect, currentTheme.backgroundColor);
1986 }
1987
1988 sDpi = sGetDpiForWindow(sPreXULSkeletonUIWindow);
1989 sHorizontalResizeMargin = sGetSystemMetricsForDpi(SM_CXFRAME, sDpi) +
1990 sGetSystemMetricsForDpi(SM_CXPADDEDBORDER, sDpi);
1991 sVerticalResizeMargin = sGetSystemMetricsForDpi(SM_CYFRAME, sDpi) +
1992 sGetSystemMetricsForDpi(SM_CXPADDEDBORDER, sDpi);
1993 sCaptionHeight = sGetSystemMetricsForDpi(SM_CYCAPTION, sDpi);
1994
1995 // These match the offsets that we get with default prefs. We don't use the
1996 // skeleton ui if tabsInTitlebar is disabled, see bug 1673092.
1997 if (sMaximized) {
1998 sNonClientOffset = Margin{sCaptionHeight, 0, 0, 0};
1999 } else {
2000 // See nsWindow::NormalWindowNonClientOffset()
2001 sNonClientOffset = Margin{sCaptionHeight + sVerticalResizeMargin, 0, 0, 0};
2002 }
2003
2004 if (sMaximized) {
2005 HMONITOR monitor =
2006 sMonitorFromWindow(sPreXULSkeletonUIWindow, MONITOR_DEFAULTTONULL);
2007 if (!monitor) {
2008 // NOTE: we specifically don't clean up the window here. If we're unable
2009 // to finish setting up the window how we want it, we still need to keep
2010 // it around and consume it with the first real toplevel window we
2011 // create, to avoid flickering.
2012 return Err(PreXULSkeletonUIError::FailedGettingMonitorInfo);
2013 }
2014 MONITORINFO mi = {sizeof(MONITORINFO)};
2015 if (!sGetMonitorInfoW(monitor, &mi)) {
2016 return Err(PreXULSkeletonUIError::FailedGettingMonitorInfo);
2017 }
2018
2019 sWindowWidth =
2020 mi.rcWork.right - mi.rcWork.left + sHorizontalResizeMargin * 2;
2021 sWindowHeight =
2022 mi.rcWork.bottom - mi.rcWork.top + sVerticalResizeMargin * 2;
2023 } else {
2024 sWindowWidth = static_cast<int>(windowWidth);
2025 sWindowHeight = static_cast<int>(windowHeight);
2026 }
2027
2028 sSetWindowPos(sPreXULSkeletonUIWindow, 0, 0, 0, 0, 0,
2029 SWP_FRAMECHANGED | SWP_NOACTIVATE | SWP_NOMOVE |
2030 SWP_NOOWNERZORDER | SWP_NOSIZE | SWP_NOZORDER);
2031 MOZ_TRY(DrawSkeletonUI(sPreXULSkeletonUIWindow, urlbar[0], searchbar[0],
2032 springs, currentTheme, flags));
2033 if (sAnimatedRects) {
2034 sPreXULSKeletonUIAnimationThread = ::CreateThread(
2035 nullptr, 256 * 1024, AnimateSkeletonUI, nullptr, 0, nullptr);
2036 }
2037
2038 BASE_PROFILER_MARKER_UNTYPED(
2039 "CreatePreXULSkeletonUI", OTHER,
2040 MarkerTiming::IntervalUntilNowFrom(skeletonStart));
2041
2042 return Ok();
2043 }
2044
2045 void CreateAndStorePreXULSkeletonUI(HINSTANCE hInstance, int argc,
2046 char** argv) {
2047 auto result = CreateAndStorePreXULSkeletonUIImpl(hInstance, argc, argv);
2048
2049 if (result.isErr()) {
2050 sErrorReason.emplace(result.unwrapErr());
2051 }
2052 }
2053
2054 void CleanupProcessRuntime() {
2055 delete sProcessRuntime;
2056 sProcessRuntime = nullptr;
2057 }
2058
2059 bool WasPreXULSkeletonUIMaximized() { return sMaximized; }
2060
2061 bool GetPreXULSkeletonUIWasShown() {
2062 return sPreXULSkeletonUIShown || !!sPreXULSkeletonUIWindow;
2063 }
2064
2065 HWND ConsumePreXULSkeletonUIHandle() {
2066 // NOTE: we need to make sure that everything that runs here is a no-op if
2067 // it failed to be set, which is a possibility. If anything fails to be set
2068 // we don't want to clean everything up right away, because if we have a
2069 // blank window up, we want that to stick around and get consumed by nsWindow
2070 // as normal, otherwise the window will flicker in and out, which we imagine
2071 // is unpleasant.
2072
2073 // If we don't get 1 here, it means the thread is actually just sleeping, so
2074 // we don't need to worry about giving out ownership of the window, because
2075 // the thread will simply exit after its sleep. However, if it is 1, we need
2076 // to wait for the thread to exit to be safe, as it could be doing anything.
2077 if (InterlockedIncrement(&sAnimationControlFlag) == 1) {
2078 ::WaitForSingleObject(sPreXULSKeletonUIAnimationThread, INFINITE);
2079 }
2080 ::CloseHandle(sPreXULSKeletonUIAnimationThread);
2081 sPreXULSKeletonUIAnimationThread = nullptr;
2082 HWND result = sPreXULSkeletonUIWindow;
2083 sPreXULSkeletonUIWindow = nullptr;
2084 free(sPixelBuffer);
2085 sPixelBuffer = nullptr;
2086 delete sAnimatedRects;
2087 sAnimatedRects = nullptr;
2088
2089 return result;
2090 }
2091
2092 Result<Ok, PreXULSkeletonUIError> PersistPreXULSkeletonUIValues(
2093 const SkeletonUISettings& settings) {
2094 if (!sPreXULSkeletonUIEnabled) {
2095 return Err(PreXULSkeletonUIError::Disabled);
2096 }
2097
2098 HKEY regKey;
2099 MOZ_TRY_VAR(regKey, OpenPreXULSkeletonUIRegKey());
2100 AutoCloseRegKey closeKey(regKey);
2101
2102 UniquePtr<wchar_t[]> binPath;
2103 MOZ_TRY_VAR(binPath, GetBinaryPath());
2104
2105 MOZ_TRY(WriteRegUint(regKey,
2106 GetRegValueName(binPath.get(), sScreenXRegSuffix),
2107 settings.screenX));
2108 MOZ_TRY(WriteRegUint(regKey,
2109 GetRegValueName(binPath.get(), sScreenYRegSuffix),
2110 settings.screenY));
2111 MOZ_TRY(WriteRegUint(regKey, GetRegValueName(binPath.get(), sWidthRegSuffix),
2112 settings.width));
2113 MOZ_TRY(WriteRegUint(regKey, GetRegValueName(binPath.get(), sHeightRegSuffix),
2114 settings.height));
2115
2116 MOZ_TRY(WriteRegBool(regKey,
2117 GetRegValueName(binPath.get(), sMaximizedRegSuffix),
2118 settings.maximized));
2119
2120 EnumSet<SkeletonUIFlag, uint32_t> flags;
2121 if (settings.menubarShown) {
2122 flags += SkeletonUIFlag::MenubarShown;
2123 }
2124 if (settings.bookmarksToolbarShown) {
2125 flags += SkeletonUIFlag::BookmarksToolbarShown;
2126 }
2127 if (settings.rtlEnabled) {
2128 flags += SkeletonUIFlag::RtlEnabled;
2129 }
2130 if (settings.uiDensity == SkeletonUIDensity::Touch) {
2131 flags += SkeletonUIFlag::TouchDensity;
2132 }
2133 if (settings.uiDensity == SkeletonUIDensity::Compact) {
2134 flags += SkeletonUIFlag::CompactDensity;
2135 }
2136 if (settings.verticalTabs) {
2137 flags += SkeletonUIFlag::VerticalTabs;
2138 }
2139
2140 uint32_t flagsUint = flags.serialize();
2141 MOZ_TRY(WriteRegUint(regKey, GetRegValueName(binPath.get(), sFlagsRegSuffix),
2142 flagsUint));
2143
2144 MOZ_TRY(WriteRegDouble(
2145 regKey, GetRegValueName(binPath.get(), sCssToDevPixelScalingRegSuffix),
2146 settings.cssToDevPixelScaling));
2147 MOZ_TRY(WriteRegCSSPixelSpans(
2148 regKey, GetRegValueName(binPath.get(), sUrlbarCSSRegSuffix),
2149 &settings.urlbarSpan, 1));
2150 MOZ_TRY(WriteRegCSSPixelSpans(
2151 regKey, GetRegValueName(binPath.get(), sSearchbarRegSuffix),
2152 &settings.searchbarSpan, 1));
2153 MOZ_TRY(WriteRegCSSPixelSpans(
2154 regKey, GetRegValueName(binPath.get(), sSpringsCSSRegSuffix),
2155 settings.springs.begin(), settings.springs.length()));
2156
2157 return Ok();
2158 }
2159
2160 MFBT_API bool GetPreXULSkeletonUIEnabled() { return sPreXULSkeletonUIEnabled; }
2161
2162 MFBT_API Result<Ok, PreXULSkeletonUIError> SetPreXULSkeletonUIEnabledIfAllowed(
2163 bool value) {
2164 // If the pre-XUL skeleton UI was disallowed for some reason, we just want to
2165 // ignore changes to the registry. An example of how things could be bad if
2166 // we didn't: someone running firefox with the -profile argument could
2167 // turn the skeleton UI on or off for the default profile. Turning it off
2168 // maybe isn't so bad (though it's likely still incorrect), but turning it
2169 // on could be bad if the user had specifically disabled it for a profile for
2170 // some reason. Ultimately there's no correct decision here, and the
2171 // messiness of this is just a consequence of sharing the registry values
2172 // across profiles. However, whatever ill effects we observe should be
2173 // correct themselves after one session.
2174 if (PreXULSkeletonUIDisallowed()) {
2175 return Err(PreXULSkeletonUIError::Disabled);
2176 }
2177
2178 HKEY regKey;
2179 MOZ_TRY_VAR(regKey, OpenPreXULSkeletonUIRegKey());
2180 AutoCloseRegKey closeKey(regKey);
2181
2182 UniquePtr<wchar_t[]> binPath;
2183 MOZ_TRY_VAR(binPath, GetBinaryPath());
2184 MOZ_TRY(WriteRegBool(
2185 regKey, GetRegValueName(binPath.get(), sEnabledRegSuffix), value));
2186
2187 if (!sPreXULSkeletonUIEnabled && value) {
2188 // We specifically don't care if we fail to get this lock. We just want to
2189 // do our best effort to lock it so that future instances don't create
2190 // skeleton UIs while we're still running, since they will immediately exit
2191 // and tell us to open a new window.
2192 Unused << GetSkeletonUILock();
2193 }
2194
2195 sPreXULSkeletonUIEnabled = value;
2196
2197 return Ok();
2198 }
2199
2200 MFBT_API Result<Ok, PreXULSkeletonUIError> SetPreXULSkeletonUIThemeId(
2201 ThemeMode theme) {
2202 if (theme == sTheme) {
2203 return Ok();
2204 }
2205 sTheme = theme;
2206
2207 // If we fail below, invalidate sTheme
2208 auto invalidateTheme = MakeScopeExit([] { sTheme = ThemeMode::Invalid; });
2209
2210 HKEY regKey;
2211 MOZ_TRY_VAR(regKey, OpenPreXULSkeletonUIRegKey());
2212 AutoCloseRegKey closeKey(regKey);
2213
2214 UniquePtr<wchar_t[]> binPath;
2215 MOZ_TRY_VAR(binPath, GetBinaryPath());
2216 MOZ_TRY(WriteRegUint(regKey, GetRegValueName(binPath.get(), sThemeRegSuffix),
2217 static_cast<uint32_t>(theme)));
2218
2219 invalidateTheme.release();
2220 return Ok();
2221 }
2222
2223 MFBT_API void PollPreXULSkeletonUIEvents() {
2224 if (sPreXULSkeletonUIEnabled && sPreXULSkeletonUIWindow) {
2225 MSG outMsg = {};
2226 PeekMessageW(&outMsg, sPreXULSkeletonUIWindow, 0, 0, 0);
2227 }
2228 }
2229
2230 Result<Ok, PreXULSkeletonUIError> NotePreXULSkeletonUIRestarting() {
2231 if (!sPreXULSkeletonUIEnabled) {
2232 return Err(PreXULSkeletonUIError::Disabled);
2233 }
2234
2235 ::SetEnvironmentVariableW(L"MOZ_SKELETON_UI_RESTARTING", L"1");
2236
2237 // We assume that we are going to exit the application very shortly after
2238 // this. It should thus be fine to release this lock, and we'll need to,
2239 // since during a restart we launch the new instance before closing this
2240 // one.
2241 if (sPreXULSKeletonUILockFile != INVALID_HANDLE_VALUE) {
2242 ::CloseHandle(sPreXULSKeletonUILockFile);
2243 }
2244 return Ok();
2245 }
2246
2247 } // namespace mozilla