1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
|
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "CrossProcessPaint.h"
#include "mozilla/dom/ContentProcessManager.h"
#include "mozilla/dom/ImageBitmap.h"
#include "mozilla/dom/BrowserParent.h"
#include "mozilla/dom/PWindowGlobalParent.h"
#include "mozilla/dom/Promise.h"
#include "mozilla/dom/WindowGlobalParent.h"
#include "mozilla/dom/WindowGlobalChild.h"
#include "mozilla/dom/WindowGlobalActorsBinding.h"
#include "mozilla/gfx/DrawEventRecorder.h"
#include "mozilla/gfx/InlineTranslator.h"
#include "mozilla/Logging.h"
#include "mozilla/PresShell.h"
#include "gfxPlatform.h"
#include "nsContentUtils.h"
#include "nsGlobalWindowInner.h"
#include "nsIDocShell.h"
#include "nsPresContext.h"
static mozilla::LazyLogModule gCrossProcessPaintLog("CrossProcessPaint");
static mozilla::LazyLogModule gPaintFragmentLog("PaintFragment");
#define CPP_LOG(msg, ...) \
MOZ_LOG(gCrossProcessPaintLog, LogLevel::Debug, (msg, ##__VA_ARGS__))
#define PF_LOG(msg, ...) \
MOZ_LOG(gPaintFragmentLog, LogLevel::Debug, (msg, ##__VA_ARGS__))
namespace mozilla {
namespace gfx {
using namespace mozilla::ipc;
/// The minimum scale we allow tabs to be rasterized at.
static const float kMinPaintScale = 0.05f;
/* static */
PaintFragment PaintFragment::Record(dom::BrowsingContext* aBc,
const Maybe<IntRect>& aRect, float aScale,
nscolor aBackgroundColor,
CrossProcessPaintFlags aFlags) {
nsIDocShell* ds = aBc->GetDocShell();
if (!ds) {
PF_LOG("Couldn't find docshell.\n");
return PaintFragment{};
}
RefPtr<nsPresContext> presContext = ds->GetPresContext();
if (!presContext) {
PF_LOG("Couldn't find PresContext.\n");
return PaintFragment{};
}
IntRect rect;
if (!aRect) {
nsCOMPtr<nsIWidget> widget =
nsContentUtils::WidgetForDocument(presContext->Document());
// TODO: Apply some sort of clipping to visible bounds here (Bug 1562720)
LayoutDeviceIntRect boundsDevice = widget->GetBounds();
boundsDevice.MoveTo(0, 0);
nsRect boundsAu = LayoutDevicePixel::ToAppUnits(
boundsDevice, presContext->AppUnitsPerDevPixel());
rect = gfx::RoundedOut(CSSPixel::FromAppUnits(boundsAu).ToUnknownRect());
} else {
rect = *aRect;
}
if (rect.IsEmpty()) {
// TODO: Should we return an empty surface here?
PF_LOG("Empty rect to paint.\n");
return PaintFragment{};
}
IntSize surfaceSize = rect.Size();
surfaceSize.width *= aScale;
surfaceSize.height *= aScale;
CPP_LOG(
"Recording "
"[browsingContext=%p, "
"rect=(%d, %d) x (%d, %d), "
"scale=%f, "
"color=(%u, %u, %u, %u)]\n",
aBc, rect.x, rect.y, rect.width, rect.height, aScale,
NS_GET_R(aBackgroundColor), NS_GET_G(aBackgroundColor),
NS_GET_B(aBackgroundColor), NS_GET_A(aBackgroundColor));
// Check for invalid sizes
if (surfaceSize.width <= 0 || surfaceSize.height <= 0 ||
!Factory::CheckSurfaceSize(surfaceSize)) {
PF_LOG("Invalid surface size of (%d x %d).\n", surfaceSize.width,
surfaceSize.height);
return PaintFragment{};
}
// Flush any pending notifications
nsContentUtils::FlushLayoutForTree(ds->GetWindow());
// Initialize the recorder
SurfaceFormat format = SurfaceFormat::B8G8R8A8;
RefPtr<DrawTarget> referenceDt = Factory::CreateDrawTarget(
gfxPlatform::GetPlatform()->GetSoftwareBackend(), IntSize(1, 1), format);
// TODO: This may OOM crash if the content is complex enough
RefPtr<DrawEventRecorderMemory> recorder =
MakeAndAddRef<DrawEventRecorderMemory>(nullptr);
RefPtr<DrawTarget> dt = Factory::CreateRecordingDrawTarget(
recorder, referenceDt, IntRect(IntPoint(0, 0), surfaceSize));
RenderDocumentFlags renderDocFlags = RenderDocumentFlags::None;
if (!(aFlags & CrossProcessPaintFlags::DrawView)) {
renderDocFlags = (RenderDocumentFlags::IgnoreViewportScrolling |
RenderDocumentFlags::DocumentRelative);
}
// Perform the actual rendering
{
nsRect r(nsPresContext::CSSPixelsToAppUnits(rect.x),
nsPresContext::CSSPixelsToAppUnits(rect.y),
nsPresContext::CSSPixelsToAppUnits(rect.width),
nsPresContext::CSSPixelsToAppUnits(rect.height));
RefPtr<gfxContext> thebes = gfxContext::CreateOrNull(dt);
thebes->SetMatrix(Matrix::Scaling(aScale, aScale));
RefPtr<PresShell> presShell = presContext->PresShell();
Unused << presShell->RenderDocument(r, renderDocFlags, aBackgroundColor,
thebes);
}
if (!recorder->mOutputStream.mValid) {
return PaintFragment{};
}
ByteBuf recording = ByteBuf((uint8_t*)recorder->mOutputStream.mData,
recorder->mOutputStream.mLength,
recorder->mOutputStream.mCapacity);
recorder->mOutputStream.mData = nullptr;
recorder->mOutputStream.mLength = 0;
recorder->mOutputStream.mCapacity = 0;
return PaintFragment{
surfaceSize,
std::move(recording),
std::move(recorder->TakeDependentSurfaces()),
};
}
bool PaintFragment::IsEmpty() const {
return !mRecording.mData || mRecording.mLen == 0 || mSize == IntSize(0, 0);
}
PaintFragment::PaintFragment(IntSize aSize, ByteBuf&& aRecording,
nsTHashtable<nsUint64HashKey>&& aDependencies)
: mSize(aSize),
mRecording(std::move(aRecording)),
mDependencies(std::move(aDependencies)) {}
static dom::TabId GetTabId(dom::WindowGlobalParent* aWGP) {
// There is no unique TabId for a given WindowGlobalParent, as multiple
// WindowGlobalParents share the same PBrowser actor. However, we only
// ever queue one paint per PBrowser by just using the current
// WindowGlobalParent for a PBrowser. So we can interchange TabId and
// WindowGlobalParent when dealing with resolving surfaces.
RefPtr<dom::BrowserParent> browserParent = aWGP->GetBrowserParent();
return browserParent ? browserParent->GetTabId() : dom::TabId(0);
}
/* static */
bool CrossProcessPaint::Start(dom::WindowGlobalParent* aRoot,
const dom::DOMRect* aRect, float aScale,
nscolor aBackgroundColor,
CrossProcessPaintFlags aFlags,
dom::Promise* aPromise) {
MOZ_RELEASE_ASSERT(XRE_IsParentProcess());
aScale = std::max(aScale, kMinPaintScale);
CPP_LOG(
"Starting paint. "
"[wgp=%p, "
"scale=%f, "
"color=(%u, %u, %u, %u)]\n",
aRoot, aScale, NS_GET_R(aBackgroundColor), NS_GET_G(aBackgroundColor),
NS_GET_B(aBackgroundColor), NS_GET_A(aBackgroundColor));
Maybe<IntRect> rect;
if (aRect) {
rect =
Some(IntRect::RoundOut((float)aRect->X(), (float)aRect->Y(),
(float)aRect->Width(), (float)aRect->Height()));
}
if (rect && rect->IsEmpty()) {
return false;
}
dom::TabId rootId = GetTabId(aRoot);
RefPtr<CrossProcessPaint> resolver = new CrossProcessPaint(aScale, rootId);
RefPtr<CrossProcessPaint::ResolvePromise> promise;
if (aRoot->IsInProcess()) {
RefPtr<dom::WindowGlobalChild> childActor = aRoot->GetChildActor();
if (!childActor) {
return false;
}
// `BrowsingContext()` cannot be nullptr.
RefPtr<dom::BrowsingContext> bc = childActor->BrowsingContext();
promise = resolver->Init();
resolver->mPendingFragments += 1;
resolver->ReceiveFragment(
aRoot,
PaintFragment::Record(bc, rect, aScale, aBackgroundColor, aFlags));
} else {
promise = resolver->Init();
resolver->QueuePaint(aRoot, rect, aBackgroundColor, aFlags);
}
promise->Then(
GetCurrentSerialEventTarget(), __func__,
[promise = RefPtr{aPromise}, rootId](ResolvedFragmentMap&& aFragments) {
RefPtr<RecordedDependentSurface> root = aFragments.Get(rootId);
CPP_LOG("Resolved all fragments.\n");
// Create the destination draw target
RefPtr<DrawTarget> drawTarget =
gfxPlatform::GetPlatform()->CreateOffscreenContentDrawTarget(
root->mSize, SurfaceFormat::B8G8R8A8);
if (!drawTarget || !drawTarget->IsValid()) {
CPP_LOG("Couldn't create (%d x %d) surface for fragment %" PRIu64
".\n",
root->mSize.width, root->mSize.height, (uint64_t)rootId);
promise->MaybeReject(NS_ERROR_FAILURE);
return;
}
// Translate the recording using our child tabs
{
InlineTranslator translator(drawTarget, nullptr);
translator.SetDependentSurfaces(&aFragments);
if (!translator.TranslateRecording((char*)root->mRecording.mData,
root->mRecording.mLen)) {
CPP_LOG("Couldn't translate recording for fragment %" PRIu64 ".\n",
(uint64_t)rootId);
promise->MaybeReject(NS_ERROR_FAILURE);
return;
}
}
RefPtr<SourceSurface> snapshot = drawTarget->Snapshot();
if (!snapshot) {
promise->MaybeReject(NS_ERROR_FAILURE);
return;
}
ErrorResult rv;
RefPtr<dom::ImageBitmap> bitmap =
dom::ImageBitmap::CreateFromSourceSurface(
promise->GetParentObject(), snapshot, rv);
if (!rv.Failed()) {
CPP_LOG("Success, fulfilling promise.\n");
promise->MaybeResolve(bitmap);
} else {
CPP_LOG("Couldn't create ImageBitmap for SourceSurface.\n");
promise->MaybeReject(std::move(rv));
}
},
[promise = RefPtr{aPromise}](const nsresult& aRv) {
promise->MaybeReject(aRv);
});
return true;
}
/* static */
RefPtr<CrossProcessPaint::ResolvePromise> CrossProcessPaint::Start(
nsTHashtable<nsUint64HashKey>&& aDependencies) {
MOZ_ASSERT(!aDependencies.IsEmpty());
RefPtr<CrossProcessPaint> resolver =
new CrossProcessPaint(1.0, dom::TabId(0));
RefPtr<CrossProcessPaint::ResolvePromise> promise = resolver->Init();
PaintFragment rootFragment;
rootFragment.mDependencies = std::move(aDependencies);
resolver->QueueDependencies(rootFragment.mDependencies);
resolver->mReceivedFragments.Put(dom::TabId(0), std::move(rootFragment));
return promise;
}
CrossProcessPaint::CrossProcessPaint(float aScale, dom::TabId aRoot)
: mRoot{aRoot}, mScale{aScale}, mPendingFragments{0} {}
CrossProcessPaint::~CrossProcessPaint() = default;
void CrossProcessPaint::ReceiveFragment(dom::WindowGlobalParent* aWGP,
PaintFragment&& aFragment) {
if (IsCleared()) {
CPP_LOG("Ignoring fragment from %p.\n", aWGP);
return;
}
dom::TabId surfaceId = GetTabId(aWGP);
MOZ_ASSERT(mPendingFragments > 0);
MOZ_ASSERT(!mReceivedFragments.GetValue(surfaceId));
// Double check our invariants to protect against a compromised content
// process
if (mPendingFragments == 0 || mReceivedFragments.GetValue(surfaceId) ||
aFragment.IsEmpty()) {
CPP_LOG("Dropping invalid fragment from %p.\n", aWGP);
LostFragment(aWGP);
return;
}
CPP_LOG("Receiving fragment from %p(%" PRIu64 ").\n", aWGP,
(uint64_t)surfaceId);
// Queue paints for child tabs
QueueDependencies(aFragment.mDependencies);
mReceivedFragments.Put(surfaceId, std::move(aFragment));
mPendingFragments -= 1;
// Resolve this paint if we have received all pending fragments
MaybeResolve();
}
void CrossProcessPaint::LostFragment(dom::WindowGlobalParent* aWGP) {
if (IsCleared()) {
CPP_LOG("Ignoring lost fragment from %p.\n", aWGP);
return;
}
Clear(NS_ERROR_LOSS_OF_SIGNIFICANT_DATA);
}
void CrossProcessPaint::QueueDependencies(
const nsTHashtable<nsUint64HashKey>& aDependencies) {
for (auto iter = aDependencies.ConstIter(); !iter.Done(); iter.Next()) {
auto dependency = dom::TabId(iter.Get()->GetKey());
// Get the current WindowGlobalParent of the remote browser that was marked
// as a dependency
dom::ContentProcessManager* cpm =
dom::ContentProcessManager::GetSingleton();
dom::ContentParentId cpId = cpm->GetTabProcessId(dependency);
RefPtr<dom::BrowserParent> browser =
cpm->GetBrowserParentByProcessAndTabId(cpId, dependency);
RefPtr<dom::WindowGlobalParent> wgp =
browser->GetBrowsingContext()->GetCurrentWindowGlobal();
if (!wgp) {
CPP_LOG("Skipping dependency %" PRIu64 "with no current WGP.\n",
(uint64_t)dependency);
continue;
}
// TODO: Apply some sort of clipping to visible bounds here (Bug 1562720)
QueuePaint(wgp, Nothing());
}
}
void CrossProcessPaint::QueuePaint(dom::WindowGlobalParent* aWGP,
const Maybe<IntRect>& aRect,
nscolor aBackgroundColor,
CrossProcessPaintFlags aFlags) {
MOZ_ASSERT(!mReceivedFragments.GetValue(GetTabId(aWGP)));
CPP_LOG("Queueing paint for %p.\n", aWGP);
aWGP->DrawSnapshotInternal(this, aRect, mScale, aBackgroundColor,
(uint32_t)aFlags);
mPendingFragments += 1;
}
void CrossProcessPaint::Clear(nsresult aStatus) {
mPendingFragments = 0;
mReceivedFragments.Clear();
mPromise.RejectIfExists(aStatus, __func__);
}
bool CrossProcessPaint::IsCleared() const { return mPromise.IsEmpty(); }
void CrossProcessPaint::MaybeResolve() {
// Don't do anything if we aren't ready, experienced an error, or already
// resolved this paint
if (IsCleared() || mPendingFragments > 0) {
CPP_LOG("Not ready to resolve yet, have %u fragments left.\n",
mPendingFragments);
return;
}
CPP_LOG("Starting to resolve fragments.\n");
// Resolve the paint fragments from the bottom up
ResolvedFragmentMap resolved;
{
nsresult rv = ResolveInternal(mRoot, &resolved);
if (NS_FAILED(rv)) {
CPP_LOG("Couldn't resolve.\n");
Clear(rv);
return;
}
}
CPP_LOG("Resolved all fragments.\n");
mPromise.ResolveIfExists(std::move(resolved), __func__);
Clear(NS_OK);
}
nsresult CrossProcessPaint::ResolveInternal(dom::TabId aTabId,
ResolvedFragmentMap* aResolved) {
// We should not have resolved this paint already
MOZ_ASSERT(!aResolved->GetWeak(aTabId));
CPP_LOG("Resolving fragment %" PRIu64 ".\n", (uint64_t)aTabId);
Maybe<PaintFragment> fragment = mReceivedFragments.GetAndRemove(aTabId);
if (!fragment) {
return NS_ERROR_LOSS_OF_SIGNIFICANT_DATA;
}
// Rasterize all the dependencies first so that we can resolve this fragment
for (auto iter = fragment->mDependencies.Iter(); !iter.Done(); iter.Next()) {
auto dependency = dom::TabId(iter.Get()->GetKey());
nsresult rv = ResolveInternal(dependency, aResolved);
if (NS_FAILED(rv)) {
return rv;
}
}
RefPtr<RecordedDependentSurface> surface = new RecordedDependentSurface{
fragment->mSize, std::move(fragment->mRecording)};
aResolved->Put(aTabId, std::move(surface));
return NS_OK;
}
} // namespace gfx
} // namespace mozilla
|