void VideoFrameContainer::InvalidateWithFlags(uint32_t aFlags) { NS_ASSERTION(NS_IsMainThread(), "Must call on main thread"); if (!mElement) { // Element has been destroyed return; } nsIFrame* frame = mElement->GetPrimaryFrame(); bool invalidateFrame = false; { Maybe<AutoTimer<Telemetry::VFC_INVALIDATE_LOCK_WAIT_MS>> lockWait; lockWait.emplace(); MutexAutoLock lock(mMutex); lockWait.reset(); AutoTimer<Telemetry::VFC_INVALIDATE_LOCK_HOLD_MS> lockHold; // Get mImageContainerSizeChanged while holding the lock. invalidateFrame = mImageSizeChanged; mImageSizeChanged = false; if (mIntrinsicSizeChanged) { mElement->UpdateMediaSize(mIntrinsicSize); mIntrinsicSizeChanged = false; if (frame) { nsPresContext* presContext = frame->PresContext(); nsIPresShell *presShell = presContext->PresShell(); presShell->FrameNeedsReflow(frame, nsIPresShell::eStyleChange, NS_FRAME_IS_DIRTY); } } } bool asyncInvalidate = mImageContainer && mImageContainer->IsAsync() && !(aFlags & INVALIDATE_FORCE); if (frame) { if (invalidateFrame) { frame->InvalidateFrame(); } else { frame->InvalidateLayer(nsDisplayItem::TYPE_VIDEO, nullptr, nullptr, asyncInvalidate ? nsIFrame::UPDATE_IS_ASYNC : 0); } } nsSVGEffects::InvalidateDirectRenderingObservers(mElement); }
nsresult MP4TrackDemuxer::GetNextRandomAccessPoint(media::TimeUnit* aTime) { if (mNextKeyframeTime.isNothing()) { // There's no next key frame. *aTime = media::TimeUnit::FromMicroseconds(std::numeric_limits<int64_t>::max()); } else { *aTime = mNextKeyframeTime.value(); } return NS_OK; }
void Compositor::DrawGeometry(const gfx::Rect& aRect, const gfx::IntRect& aClipRect, const EffectChain& aEffectChain, gfx::Float aOpacity, const gfx::Matrix4x4& aTransform, const gfx::Rect& aVisibleRect, const Maybe<gfx::Polygon3D>& aGeometry) { if (!aGeometry) { DrawQuad(aRect, aClipRect, aEffectChain, aOpacity, aTransform, aVisibleRect); return; } // Cull invisible polygons. if (aRect.Intersect(aGeometry->BoundingBox()).IsEmpty()) { return; } gfx::Polygon3D clipped = aGeometry->ClipPolygon(aRect); nsTArray<gfx::Triangle> triangles = clipped.ToTriangles(); for (gfx::Triangle& geometry : triangles) { const gfx::Rect intersection = aRect.Intersect(geometry.BoundingBox()); // Cull invisible triangles. if (intersection.IsEmpty()) { continue; } MOZ_ASSERT(aRect.width > 0.0f && aRect.height > 0.0f); MOZ_ASSERT(intersection.width > 0.0f && intersection.height > 0.0f); gfx::TexturedTriangle triangle(Move(geometry)); triangle.width = aRect.width; triangle.height = aRect.height; // Since the texture was created for non-split geometry, we need to // update the texture coordinates to account for the split. if (aEffectChain.mPrimaryEffect->mType == EffectTypes::RGB) { TexturedEffect* texturedEffect = static_cast<TexturedEffect*>(aEffectChain.mPrimaryEffect.get()); UpdateTextureCoordinates(triangle, aRect, intersection, texturedEffect->mTextureCoords); } DrawTriangle(triangle, aClipRect, aEffectChain, aOpacity, aTransform, aVisibleRect); } }
nsresult SourceBuffer::Compact() { mMutex.AssertCurrentThreadOwns(); MOZ_ASSERT(mConsumerCount == 0, "Should have no consumers here"); MOZ_ASSERT(mWaitingConsumers.Length() == 0, "Shouldn't have waiters"); MOZ_ASSERT(mStatus, "Should be complete here"); // Compact our waiting consumers list, since we're complete and no future // consumer will ever have to wait. mWaitingConsumers.Compact(); // If we have no chunks, then there's nothing to compact. if (mChunks.Length() < 1) { return NS_OK; } // If we have one chunk, then we can compact if it has excess capacity. if (mChunks.Length() == 1 && mChunks[0].Length() == mChunks[0].Capacity()) { return NS_OK; } // We can compact our buffer. Determine the total length. size_t length = 0; for (uint32_t i = 0 ; i < mChunks.Length() ; ++i) { length += mChunks[i].Length(); } Maybe<Chunk> newChunk = CreateChunk(length, /* aRoundUp = */ false); if (MOZ_UNLIKELY(!newChunk || newChunk->AllocationFailed())) { NS_WARNING("Failed to allocate chunk for SourceBuffer compacting - OOM?"); return NS_OK; } // Copy our old chunks into the new chunk. for (uint32_t i = 0 ; i < mChunks.Length() ; ++i) { size_t offset = newChunk->Length(); MOZ_ASSERT(offset < newChunk->Capacity()); MOZ_ASSERT(offset + mChunks[i].Length() <= newChunk->Capacity()); memcpy(newChunk->Data() + offset, mChunks[i].Data(), mChunks[i].Length()); newChunk->AddLength(mChunks[i].Length()); } MOZ_ASSERT(newChunk->Length() == newChunk->Capacity(), "Compacted chunk has slack space"); // Replace the old chunks with the new, compact chunk. mChunks.Clear(); if (MOZ_UNLIKELY(NS_FAILED(AppendChunk(Move(newChunk))))) { return HandleError(NS_ERROR_OUT_OF_MEMORY); } mChunks.Compact(); return NS_OK; }
Maybe<gfx::IntSize> GLContextGLX::GetTargetSize() { unsigned int width = 0, height = 0; Window root; int x, y; unsigned int border, depth; XGetGeometry(mDisplay, mDrawable, &root, &x, &y, &width, &height, &border, &depth); Maybe<gfx::IntSize> size; size.emplace(width, height); return size; }
void CacheOpChild::HandleResponse(const Maybe<CacheResponse>& aMaybeResponse) { if (aMaybeResponse.isNothing()) { mPromise->MaybeResolveWithUndefined(); return; } const CacheResponse& cacheResponse = aMaybeResponse.ref(); AddWorkerHolderToStreamChild(cacheResponse, GetWorkerHolder()); RefPtr<Response> response = ToResponse(cacheResponse); mPromise->MaybeResolve(response); }
TEST(ContainerParser, MIMETypes) { const char* containerTypes[] = {"video/webm", "audio/webm", "video/mp4", "audio/mp4", "audio/aac"}; nsAutoPtr<ContainerParser> parser; for (size_t i = 0; i < ArrayLength(containerTypes); ++i) { Maybe<MediaContainerType> containerType = MakeMediaContainerType(containerTypes[i]); ASSERT_TRUE(containerType.isSome()); parser = ContainerParser::CreateForMIMEType(*containerType); ASSERT_NE(parser, nullptr); } }
void IDBRequest::SetResultCallback(ResultCallback* aCallback) { AssertIsOnOwningThread(); MOZ_ASSERT(aCallback); MOZ_ASSERT(!mHaveResultOrErrorCode); MOZ_ASSERT(mResultVal.isUndefined()); MOZ_ASSERT(!mError); // See if our window is still valid. if (NS_WARN_IF(NS_FAILED(CheckInnerWindowCorrectness()))) { IDB_REPORT_INTERNAL_ERR(); SetError(NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR); return; } AutoJSAPI autoJS; Maybe<JSAutoCompartment> ac; if (GetScriptOwner()) { // If we have a script owner we want the SafeJSContext and then to enter the // script owner's compartment. autoJS.Init(); ac.emplace(autoJS.cx(), GetScriptOwner()); } else { // Otherwise our owner is a window and we use that to initialize. MOZ_ASSERT(GetOwner()); if (!autoJS.InitWithLegacyErrorReporting(GetOwner())) { IDB_WARNING("Failed to initialize AutoJSAPI!"); SetError(NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR); return; } } JSContext* cx = autoJS.cx(); AssertIsRooted(); JS::Rooted<JS::Value> result(cx); nsresult rv = aCallback->GetResult(cx, &result); if (NS_WARN_IF(NS_FAILED(rv))) { SetError(rv); mResultVal.setUndefined(); } else { mError = nullptr; mResultVal = result; } mHaveResultOrErrorCode = true; }
dom::Nullable<uint64_t> DominatorTree::GetImmediateDominator(uint64_t aNodeId) const { JS::ubi::Node::Id id(aNodeId); Maybe<JS::ubi::Node> node = mHeapSnapshot->getNodeById(id); if (node.isNothing()) return dom::Nullable<uint64_t>(); JS::ubi::Node dominator = mDominatorTree.getImmediateDominator(*node); if (!dominator || dominator == *node) return dom::Nullable<uint64_t>(); return dom::Nullable<uint64_t>(dominator.identifier()); }
void nsHTMLButtonControlFrame::BuildDisplayList(nsDisplayListBuilder* aBuilder, const nsRect& aDirtyRect, const nsDisplayListSet& aLists) { // Clip to our border area for event hit testing. Maybe<DisplayListClipState::AutoSaveRestore> eventClipState; const bool isForEventDelivery = aBuilder->IsForEventDelivery(); if (isForEventDelivery) { eventClipState.emplace(aBuilder); nsRect rect(aBuilder->ToReferenceFrame(this), GetSize()); nscoord radii[8]; bool hasRadii = GetBorderRadii(radii); eventClipState->ClipContainingBlockDescendants(rect, hasRadii ? radii : nullptr); } nsDisplayList onTop; if (IsVisibleForPainting(aBuilder)) { mRenderer.DisplayButton(aBuilder, aLists.BorderBackground(), &onTop); } nsDisplayListCollection set; // Do not allow the child subtree to receive events. if (!isForEventDelivery) { DisplayListClipState::AutoSaveRestore clipState(aBuilder); if (IsInput() || StyleDisplay()->mOverflowX != NS_STYLE_OVERFLOW_VISIBLE) { nsMargin border = StyleBorder()->GetComputedBorder(); nsRect rect(aBuilder->ToReferenceFrame(this), GetSize()); rect.Deflate(border); nscoord radii[8]; bool hasRadii = GetPaddingBoxBorderRadii(radii); clipState.ClipContainingBlockDescendants(rect, hasRadii ? radii : nullptr); } BuildDisplayListForChild(aBuilder, mFrames.FirstChild(), aDirtyRect, set, DISPLAY_CHILD_FORCE_PSEUDO_STACKING_CONTEXT); // That should put the display items in set.Content() } // Put the foreground outline and focus rects on top of the children set.Content()->AppendToTop(&onTop); set.MoveTo(aLists); DisplayOutline(aBuilder, aLists); // to draw border when selected in editor DisplaySelectionOverlay(aBuilder, aLists.Content()); }
JSContext * js_ContextIterator(JSRuntime *rt, JSBool unlocked, JSContext **iterp) { JSContext *cx = *iterp; Maybe<AutoLockGC> lockIf; if (unlocked) lockIf.construct(rt); cx = JSContext::fromLinkField(cx ? cx->link.next : rt->contextList.next); if (&cx->link == &rt->contextList) cx = NULL; *iterp = cx; return cx; }
std::pair<T, int> findLocalMin(const Shrinkable<T> &shrinkable, Predicate pred) { std::pair<T, int> result(shrinkable.value(), 0); Seq<Shrinkable<T>> shrinks = shrinkable.shrinks(); Maybe<Shrinkable<T>> shrink; while ((shrink = shrinks.next())) { T value = shrink->value(); if (pred(value)) { result.first = std::move(value); shrinks = shrink->shrinks(); result.second++; } } return result; }
void GMPVideoDecoder::InitTags(nsTArray<nsCString>& aTags) { if (MP4Decoder::IsH264(mConfig.mMimeType)) { aTags.AppendElement(NS_LITERAL_CSTRING("h264")); const Maybe<nsCString> gmp( GMPDecoderModule::PreferredGMP(NS_LITERAL_CSTRING("video/avc"))); if (gmp.isSome()) { aTags.AppendElement(gmp.value()); } } else if (VPXDecoder::IsVP8(mConfig.mMimeType)) { aTags.AppendElement(NS_LITERAL_CSTRING("vp8")); } else if (VPXDecoder::IsVP9(mConfig.mMimeType)) { aTags.AppendElement(NS_LITERAL_CSTRING("vp9")); } }
void FrameBuilder::ProcessChildList(ContainerLayer* aContainer, RenderViewMLGPU* aView, const RenderTargetIntRect& aParentClipRect, const Maybe<gfx::Polygon>& aParentGeometry) { nsTArray<LayerPolygon> polygons = aContainer->SortChildrenBy3DZOrder(ContainerLayer::SortMode::WITH_GEOMETRY); // Visit layers in front-to-back order. for (auto iter = polygons.rbegin(); iter != polygons.rend(); iter++) { LayerPolygon& entry = *iter; Layer* child = entry.layer; if (child->IsBackfaceHidden() || !child->IsVisible()) { continue; } RenderTargetIntRect clip = child->CalculateScissorRect(aParentClipRect); if (clip.IsEmpty()) { continue; } Maybe<gfx::Polygon> geometry; if (aParentGeometry && entry.geometry) { // Both parent and child are split. geometry = Some(aParentGeometry->ClipPolygon(*entry.geometry)); } else if (aParentGeometry) { geometry = aParentGeometry; } else if (entry.geometry) { geometry = Move(entry.geometry); } AssignLayer(child, aView, clip, Move(geometry)); } }
/* * CreateImageFromRawData(), CreateSurfaceFromRawData() and * CreateImageFromRawDataInMainThreadSyncTask are helpers for * create-from-ImageData case */ static already_AddRefed<SourceSurface> CreateSurfaceFromRawData(const gfx::IntSize& aSize, uint32_t aStride, gfx::SurfaceFormat aFormat, uint8_t* aBuffer, uint32_t aBufferLength, const Maybe<IntRect>& aCropRect) { MOZ_ASSERT(!aSize.IsEmpty()); MOZ_ASSERT(aBuffer); // Wrap the source buffer into a SourceSurface. RefPtr<DataSourceSurface> dataSurface = Factory::CreateWrappingDataSourceSurface(aBuffer, aStride, aSize, aFormat); if (NS_WARN_IF(!dataSurface)) { return nullptr; } // The temporary cropRect variable is equal to the size of source buffer if we // do not need to crop, or it equals to the given cropping size. const IntRect cropRect = aCropRect.valueOr(IntRect(0, 0, aSize.width, aSize.height)); // Copy the source buffer in the _cropRect_ area into a new SourceSurface. RefPtr<DataSourceSurface> result = CropAndCopyDataSourceSurface(dataSurface, cropRect); if (NS_WARN_IF(!result)) { return nullptr; } return result.forget(); }
size_t read (unsigned char *buffer, size_t size) { if (seek_to.present) { off_t sampleoff = seek_to.value.offset * rate; int whence = seek_to.value.mode == seek_command::absolute? SEEK_SET : SEEK_CUR; mpg123_seek(mh, sampleoff, whence); seek_to.reset(); time_samples = mpg123_tell(mh); } if (eof) return 0; else if (paused) return size; else { const int bytes_per_sample = 4; size_t bytes_read; int code = mpg123_read(mh, buffer, size, &bytes_read); size_t samples_read = bytes_read / bytes_per_sample; switch (code) { case MPG123_DONE: eof = true; time_samples += samples_read; return bytes_read; case MPG123_OK: time_samples += samples_read; return bytes_read; default: //cout << mpg123_strerror(mh) << endl; eof = true; return 0; } } }
nsresult PushNotifier::NotifyPush(const nsACString& aScope, nsIPrincipal* aPrincipal, const nsAString& aMessageId, const Maybe<nsTArray<uint8_t>>& aData) { // Notify XPCOM observers in the current process. nsresult rv = NotifyPushObservers(aScope, aData); Unused << NS_WARN_IF(NS_FAILED(rv)); if (XRE_IsContentProcess()) { // If we're in the content process, forward the notification to the parent. // We don't need to do anything if we're already in the parent; // `ContentChild::RecvPush` will notify content process observers. ContentChild* parentActor = ContentChild::GetSingleton(); if (!NS_WARN_IF(!parentActor)) { if (aData) { Unused << NS_WARN_IF( !parentActor->SendNotifyPushObserversWithData( PromiseFlatCString(aScope), PromiseFlatString(aMessageId), aData.ref())); } else { Unused << NS_WARN_IF( !parentActor->SendNotifyPushObservers( PromiseFlatCString(aScope), PromiseFlatString(aMessageId))); } } } rv = NotifyPushWorkers(aScope, aPrincipal, aMessageId, aData); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } return NS_OK; }
static gboolean gum_v8_module_handle_export_match (const GumExportDetails * details, gpointer user_data) { GumV8ExportsContext * ctx = static_cast<GumV8ExportsContext *> (user_data); Isolate * isolate = ctx->isolate; Local<Context> jc = isolate->GetCurrentContext (); PropertyAttribute attrs = static_cast<PropertyAttribute> (ReadOnly | DontDelete); Local<Object> exp (ctx->exp->Clone ()); if (details->type != GUM_EXPORT_FUNCTION) { Maybe<bool> success = exp->ForceSet (jc, ctx->type, ctx->variable, attrs); g_assert (success.IsJust ()); } Maybe<bool> success = exp->ForceSet (jc, ctx->name, String::NewFromOneByte (isolate, reinterpret_cast<const uint8_t *> (details->name)), attrs); g_assert (success.IsJust ()); success = exp->ForceSet (jc, ctx->address, _gum_v8_native_pointer_new (GSIZE_TO_POINTER (details->address), ctx->self->core), attrs); g_assert (success.IsJust ()); Handle<Value> argv[] = { exp }; Local<Value> result = ctx->on_match->Call (ctx->receiver, 1, argv); gboolean proceed = TRUE; if (!result.IsEmpty () && result->IsString ()) { String::Utf8Value str (result); proceed = (strcmp (*str, "stop") != 0); } return proceed; }
STDMETHODIMP ia2Accessible::get_relationTargetsOfType(BSTR aType, long aMaxTargets, IUnknown*** aTargets, long* aNTargets) { if (!aTargets || !aNTargets || aMaxTargets < 0) return E_INVALIDARG; *aNTargets = 0; Maybe<RelationType> relationType; for (uint32_t idx = 0; idx < ArrayLength(sRelationTypePairs); idx++) { if (wcscmp(aType, sRelationTypePairs[idx].second) == 0) { relationType.emplace(sRelationTypePairs[idx].first); break; } } if (!relationType) return E_INVALIDARG; AccessibleWrap* acc = static_cast<AccessibleWrap*>(this); if (acc->IsDefunct()) return CO_E_OBJNOTCONNECTED; nsTArray<Accessible*> targets; MOZ_ASSERT(!acc->IsProxy()); Relation rel = acc->RelationByType(*relationType); Accessible* target = nullptr; while ((target = rel.Next()) && static_cast<long>(targets.Length()) <= aMaxTargets) { targets.AppendElement(target); } *aNTargets = targets.Length(); *aTargets = static_cast<IUnknown**>( ::CoTaskMemAlloc(sizeof(IUnknown*) * *aNTargets)); if (!*aTargets) return E_OUTOFMEMORY; for (int32_t i = 0; i < *aNTargets; i++) { AccessibleWrap* target= static_cast<AccessibleWrap*>(targets[i]); (*aTargets)[i] = static_cast<IAccessible2*>(target); (*aTargets)[i]->AddRef(); } return S_OK; }
/* static */ bool GMPDecoderModule::SupportsMimeType(const nsACString& aMimeType, const Maybe<nsCString>& aGMP) { StaticMutexAutoLock lock(sGMPCodecsMutex); for (GMPCodecs& gmp : sGMPCodecs) { if (((aMimeType.EqualsLiteral("audio/mp4a-latm") && gmp.mHasAAC) || (MP4Decoder::IsH264(aMimeType) && gmp.mHasH264) || (VPXDecoder::IsVP8(aMimeType) && gmp.mHasVP8) || (VPXDecoder::IsVP9(aMimeType) && gmp.mHasVP9)) && (aGMP.isNothing() || aGMP.value().Equals(gmp.mKeySystem))) { return true; } } return false; }
mozilla::ipc::IPCResult RDDParent::RecvInit( const Maybe<FileDescriptor>& aBrokerFd) { Unused << SendInitComplete(); #if defined(MOZ_SANDBOX) # if defined(XP_MACOSX) StartRDDMacSandbox(); # elif defined(XP_LINUX) int fd = -1; if (aBrokerFd.isSome()) { fd = aBrokerFd.value().ClonePlatformHandle().release(); } SetRemoteDataDecoderSandbox(fd); # endif // XP_MACOSX/XP_LINUX #endif // MOZ_SANDBOX return IPC_OK(); }
RefPtr<MP4TrackDemuxer::SamplesPromise> MP4TrackDemuxer::GetSamples(int32_t aNumSamples) { EnsureUpToDateIndex(); RefPtr<SamplesHolder> samples = new SamplesHolder; if (!aNumSamples) { return SamplesPromise::CreateAndReject(NS_ERROR_DOM_MEDIA_DEMUXER_ERR, __func__); } if (mQueuedSample) { MOZ_ASSERT(mQueuedSample->mKeyframe, "mQueuedSample must be a keyframe"); samples->mSamples.AppendElement(mQueuedSample); mQueuedSample = nullptr; aNumSamples--; } RefPtr<MediaRawData> sample; while (aNumSamples && (sample = GetNextSample())) { if (!sample->Size()) { continue; } samples->mSamples.AppendElement(sample); aNumSamples--; } if (samples->mSamples.IsEmpty()) { return SamplesPromise::CreateAndReject(NS_ERROR_DOM_MEDIA_END_OF_STREAM, __func__); } for (const auto& sample : samples->mSamples) { // Collect telemetry from h264 Annex B SPS. if (mNeedSPSForTelemetry && mp4_demuxer::AnnexB::HasSPS(sample)) { RefPtr<MediaByteBuffer> extradata = mp4_demuxer::AnnexB::ExtractExtraData(sample); mNeedSPSForTelemetry = AccumulateSPSTelemetry(extradata); } } if (mNextKeyframeTime.isNothing() || samples->mSamples.LastElement()->mTime >= mNextKeyframeTime.value()) { SetNextKeyFrameTime(); } return SamplesPromise::CreateAndResolve(samples, __func__); }
void CommandLineOptions::add_option(Maybe<std::string> long_form, Maybe<std::string> short_form, std::function<void(Maybe<std::string>)> action, bool needs_value) { if (long_form) { longest_long_form_ = std::max(long_form->size(), longest_long_form_); } if (short_form) { longest_short_form_ = std::max(short_form->size(), longest_short_form_); } options_.emplace_back((Option){ std::move(long_form), std::move(short_form), std::move(next_option_description_), std::move(action), needs_value }); }
void V8RuntimeAgentImpl::runScript(ErrorString* errorString, const String16& scriptId, int executionContextId, const Maybe<String16>& objectGroup, const Maybe<bool>& doNotPauseOnExceptionsAndMuteConsole, const Maybe<bool>& includeCommandLineAPI, std::unique_ptr<RemoteObject>* result, Maybe<ExceptionDetails>* exceptionDetails) { if (!m_enabled) { *errorString = "Runtime agent is not enabled"; return; } auto it = m_compiledScripts.find(scriptId); if (it == m_compiledScripts.end()) { *errorString = "Script execution failed"; return; } InjectedScript::ContextScope scope(errorString, m_debugger, m_session->contextGroupId(), executionContextId); if (!scope.initialize()) return; if (doNotPauseOnExceptionsAndMuteConsole.fromMaybe(false)) scope.ignoreExceptionsAndMuteConsole(); std::unique_ptr<v8::Global<v8::Script>> scriptWrapper = std::move(it->second); m_compiledScripts.erase(it); v8::Local<v8::Script> script = scriptWrapper->Get(m_debugger->isolate()); if (script.IsEmpty()) { *errorString = "Script execution failed"; return; } if (includeCommandLineAPI.fromMaybe(false) && !scope.installCommandLineAPI()) return; v8::MaybeLocal<v8::Value> maybeResultValue = m_debugger->runCompiledScript(scope.context(), script); // Re-initialize after running client's code, as it could have destroyed context or session. if (!scope.initialize()) return; scope.injectedScript()->wrapEvaluateResult(errorString, maybeResultValue, scope.tryCatch(), objectGroup.fromMaybe(""), false, false, result, nullptr, exceptionDetails); }
void DominatorTree::GetImmediatelyDominated(uint64_t aNodeId, dom::Nullable<nsTArray<uint64_t>>& aOutResult, ErrorResult& aRv) { MOZ_ASSERT(aOutResult.IsNull()); JS::ubi::Node::Id id(aNodeId); Maybe<JS::ubi::Node> node = mHeapSnapshot->getNodeById(id); if (node.isNothing()) return; // Get all immediately dominated nodes and their retained sizes. MallocSizeOf mallocSizeOf = getCurrentThreadDebuggerMallocSizeOf(); Maybe<JS::ubi::DominatorTree::DominatedSetRange> range = mDominatorTree.getDominatedSet(*node); MOZ_ASSERT(range.isSome(), "The node should be known, since we got it from the heap snapshot."); size_t length = range->length(); nsTArray<NodeAndRetainedSize> dominatedNodes(length); for (const JS::ubi::Node& dominatedNode : *range) { JS::ubi::Node::Size retainedSize = 0; if (NS_WARN_IF(!mDominatorTree.getRetainedSize(dominatedNode, mallocSizeOf, retainedSize))) { aRv.Throw(NS_ERROR_OUT_OF_MEMORY); return; } MOZ_ASSERT(retainedSize != 0, "retainedSize should not be zero since we know the node is in the dominator tree."); dominatedNodes.AppendElement(NodeAndRetainedSize(dominatedNode, retainedSize)); } // Sort them by retained size. NodeAndRetainedSize::Comparator comparator; dominatedNodes.Sort(comparator); // Fill the result with the nodes' ids. JS::ubi::Node root = mDominatorTree.root(); aOutResult.SetValue(nsTArray<uint64_t>(length)); for (const NodeAndRetainedSize& entry : dominatedNodes) { // The root dominates itself, but we don't want to expose that to JS. if (entry.mNode == root) continue; aOutResult.Value().AppendElement(entry.mNode.identifier()); } }
/** * Starts the seccomp sandbox for a content process. Should be called * only once, and before any potentially harmful content is loaded. * * Will normally make the process exit on failure. */ void SetContentProcessSandbox(int aBrokerFd) { if (!SandboxInfo::Get().Test(SandboxInfo::kEnabledForContent)) { if (aBrokerFd >= 0) { close(aBrokerFd); } return; } // This needs to live until the process exits. static Maybe<SandboxBrokerClient> sBroker; if (aBrokerFd >= 0) { sBroker.emplace(aBrokerFd); } SetCurrentProcessSandbox(GetContentSandboxPolicy(sBroker.ptrOr(nullptr))); }
SVGDrawingParameters(gfxContext* aContext, const nsIntSize& aSize, const ImageRegion& aRegion, GraphicsFilter aFilter, const Maybe<SVGImageContext>& aSVGContext, float aAnimationTime, uint32_t aFlags) : context(aContext) , size(aSize.width, aSize.height) , imageRect(0, 0, aSize.width, aSize.height) , region(aRegion) , filter(aFilter) , svgContext(aSVGContext) , viewportSize(aSVGContext ? aSVGContext->GetViewportSize() : aSize) , animationTime(aAnimationTime) , flags(aFlags) , opacity(aSVGContext ? aSVGContext->GetGlobalOpacity() : 1.0) { }
T overrideDefault(const char* param, T dflt) { char* str = getenv(param); if (!str) return dflt; if (IsBool<T>::value) { if (strcmp(str, "true") == 0 || strcmp(str, "yes") == 0) return true; if (strcmp(str, "false") == 0 || strcmp(str, "no") == 0) return false; Warn(param, str); } else { Maybe<int> value = ParseInt(str); if (value.isSome()) return value.ref(); Warn(param, str); } return dflt; }
void FreqWindow::Recalc() { if (!mData || mDataLen < mWindowSize) { DrawPlot(); return; } SpectrumAnalyst::Algorithm alg = SpectrumAnalyst::Algorithm(mAlgChoice->GetSelection()); int windowFunc = mFuncChoice->GetSelection(); wxWindow *hadFocus = FindFocus(); // In wxMac, the skipped window MUST be a top level window. I'd originally made it // just the mProgress window with the idea of preventing user interaction with the // controls while the plot was being recalculated. This doesn't appear to be necessary // so just use the the top level window instead. { Maybe<wxWindowDisabler> blocker; if (IsShown()) blocker.create(this); wxYieldIfNeeded(); mAnalyst->Calculate(alg, windowFunc, mWindowSize, mRate, mData.get(), mDataLen, &mYMin, &mYMax, mProgress); } if (hadFocus) { hadFocus->SetFocus(); } if (alg == SpectrumAnalyst::Spectrum) { if(mYMin < -dBRange) mYMin = -dBRange; if(mYMax <= -dBRange) mYMax = -dBRange + 10.; // it's all out of range, but show a scale. else mYMax += .5; } // Prime the scrollbar mPanScroller->SetScrollbar(0, (mYMax - mYMin) * 100, (mYMax - mYMin) * 100, 1); DrawPlot(); }
/* static */ already_AddRefed<ImageBitmap> ImageBitmap::CreateInternal(nsIGlobalObject* aGlobal, HTMLVideoElement& aVideoEl, const Maybe<IntRect>& aCropRect, ErrorResult& aRv) { // Check network state. if (aVideoEl.NetworkState() == HTMLMediaElement::NETWORK_EMPTY) { aRv.Throw(NS_ERROR_DOM_INVALID_STATE_ERR); return nullptr; } // Check ready state. // Cannot be HTMLMediaElement::HAVE_NOTHING or HTMLMediaElement::HAVE_METADATA. if (aVideoEl.ReadyState() <= HTMLMediaElement::HAVE_METADATA) { aRv.Throw(NS_ERROR_DOM_INVALID_STATE_ERR); return nullptr; } // Check security. nsCOMPtr<nsIPrincipal> principal = aVideoEl.GetCurrentPrincipal(); bool CORSUsed = aVideoEl.GetCORSMode() != CORS_NONE; if (!CheckSecurityForHTMLElements(false, CORSUsed, principal)) { aRv.Throw(NS_ERROR_DOM_SECURITY_ERR); return nullptr; } // Create ImageBitmap. ImageContainer *container = aVideoEl.GetImageContainer(); if (!container) { aRv.Throw(NS_ERROR_NOT_AVAILABLE); return nullptr; } AutoLockImage lockImage(container); layers::Image* data = lockImage.GetImage(); RefPtr<ImageBitmap> ret = new ImageBitmap(aGlobal, data); // Set the picture rectangle. if (ret && aCropRect.isSome()) { ret->SetPictureRect(aCropRect.ref(), aRv); } return ret.forget(); }