void KeymapWrapper::InitBySystemSettings() { PR_LOG(gKeymapWrapperLog, PR_LOG_ALWAYS, ("KeymapWrapper(%p): InitBySystemSettings, mGdkKeymap=%p", this, mGdkKeymap)); Display* display = gdk_x11_display_get_xdisplay(gdk_display_get_default()); int min_keycode = 0; int max_keycode = 0; XDisplayKeycodes(display, &min_keycode, &max_keycode); int keysyms_per_keycode = 0; KeySym* xkeymap = XGetKeyboardMapping(display, min_keycode, max_keycode - min_keycode + 1, &keysyms_per_keycode); if (!xkeymap) { PR_LOG(gKeymapWrapperLog, PR_LOG_ALWAYS, ("KeymapWrapper(%p): InitBySystemSettings, " "Failed due to null xkeymap", this)); return; } XModifierKeymap* xmodmap = XGetModifierMapping(display); if (!xmodmap) { PR_LOG(gKeymapWrapperLog, PR_LOG_ALWAYS, ("KeymapWrapper(%p): InitBySystemSettings, " "Failed due to null xmodmap", this)); XFree(xkeymap); return; } PR_LOG(gKeymapWrapperLog, PR_LOG_ALWAYS, ("KeymapWrapper(%p): InitBySystemSettings, min_keycode=%d, " "max_keycode=%d, keysyms_per_keycode=%d, max_keypermod=%d", this, min_keycode, max_keycode, keysyms_per_keycode, xmodmap->max_keypermod)); // The modifiermap member of the XModifierKeymap structure contains 8 sets // of max_keypermod KeyCodes, one for each modifier in the order Shift, // Lock, Control, Mod1, Mod2, Mod3, Mod4, and Mod5. // Only nonzero KeyCodes have meaning in each set, and zero KeyCodes are // ignored. // Note that two or more modifiers may use one modifier flag. E.g., // on Ubuntu 10.10, Alt and Meta share the Mod1 in default settings. // And also Super and Hyper share the Mod4. In such cases, we need to // decide which modifier flag means one of DOM modifiers. // mod[0] is Modifier introduced by Mod1. Modifier mod[5]; int32_t foundLevel[5]; for (uint32_t i = 0; i < ArrayLength(mod); i++) { mod[i] = NOT_MODIFIER; foundLevel[i] = INT32_MAX; } const uint32_t map_size = 8 * xmodmap->max_keypermod; for (uint32_t i = 0; i < map_size; i++) { KeyCode keycode = xmodmap->modifiermap[i]; PR_LOG(gKeymapWrapperLog, PR_LOG_ALWAYS, ("KeymapWrapper(%p): InitBySystemSettings, " " i=%d, keycode=0x%08X", this, i, keycode)); if (!keycode || keycode < min_keycode || keycode > max_keycode) { continue; } ModifierKey* modifierKey = GetModifierKey(keycode); if (!modifierKey) { modifierKey = mModifierKeys.AppendElement(ModifierKey(keycode)); } const KeySym* syms = xkeymap + (keycode - min_keycode) * keysyms_per_keycode; const uint32_t bit = i / xmodmap->max_keypermod; modifierKey->mMask |= 1 << bit; // We need to know the meaning of Mod1, Mod2, Mod3, Mod4 and Mod5. // Let's skip if current map is for others. if (bit < 3) { continue; } const int32_t modIndex = bit - 3; for (int32_t j = 0; j < keysyms_per_keycode; j++) { Modifier modifier = GetModifierForGDKKeyval(syms[j]); PR_LOG(gKeymapWrapperLog, PR_LOG_ALWAYS, ("KeymapWrapper(%p): InitBySystemSettings, " " Mod%d, j=%d, syms[j]=%s(0x%X), modifier=%s", this, modIndex + 1, j, gdk_keyval_name(syms[j]), syms[j], GetModifierName(modifier))); switch (modifier) { case NOT_MODIFIER: // Don't overwrite the stored information with // NOT_MODIFIER. break; case CAPS_LOCK: case SHIFT: case CTRL: // Ignore the modifiers defined in GDK spec. They shouldn't // be mapped to Mod1-5 because they must not work on native // GTK applications. break; default: // If new modifier is found in higher level than stored // value, we don't need to overwrite it. if (j > foundLevel[modIndex]) { break; } // If new modifier is more important than stored value, // we should overwrite it with new modifier. if (j == foundLevel[modIndex]) { mod[modIndex] = NS_MIN(modifier, mod[modIndex]); break; } foundLevel[modIndex] = j; mod[modIndex] = modifier; break; } } } for (uint32_t i = 0; i < COUNT_OF_MODIFIER_INDEX; i++) { Modifier modifier; switch (i) { case INDEX_NUM_LOCK: modifier = NUM_LOCK; break; case INDEX_SCROLL_LOCK: modifier = SCROLL_LOCK; break; case INDEX_ALT: modifier = ALT; break; case INDEX_META: modifier = META; break; case INDEX_SUPER: modifier = SUPER; break; case INDEX_HYPER: modifier = HYPER; break; case INDEX_LEVEL3: modifier = LEVEL3; break; case INDEX_LEVEL5: modifier = LEVEL5; break; default: MOZ_NOT_REACHED("All indexes must be handled here"); break; } for (uint32_t j = 0; j < ArrayLength(mod); j++) { if (modifier == mod[j]) { mModifierMasks[i] |= 1 << (j + 3); } } } XFreeModifiermap(xmodmap); XFree(xkeymap); }
PetscErrorCode FiberField_UnpackFromRecvbufs( FiberField f ) { int i; int e; int b; int lv; // local vert index int le; // local edge index int len; // length of recvbuf int total_recv_verts; int total_recv_edges; Array *recvbufs = f->recvbufs; Vertex v_local; Edge e_local; VertexEdgeMPI *buf; FiberType *ftype = ArrayGetData( f->fibertypesDB ); PetscErrorCode ierr; PetscFunctionBegin; // sum up total number of verts and edges received total_recv_verts = 0; total_recv_edges = 0; for (b = 0; b < NUMNEI; b++) { len = ArrayLength( recvbufs[b] ); buf = ArrayGetData( recvbufs[b] ); for (i = 0; i < len; i++) { if ( ftype[ buf[i].type ].isEdge ) { total_recv_edges++; } else { total_recv_verts++; } } } ierr = PetscInfo1(0, "total_recv_verts = %d\n", total_recv_verts ); CHKERRQ(ierr); ierr = PetscInfo1(0, "total_recv_edges = %d\n", total_recv_edges ); CHKERRQ(ierr); // set local vert/edge array length to sum of total received ierr = ArraySetSize( f->verts, total_recv_verts); CHKERRQ(ierr); ierr = ArraySetSize( f->edges, total_recv_edges); CHKERRQ(ierr); v_local = ArrayGetData( f->verts ); e_local = ArrayGetData( f->edges ); // copy from bufs to local vert list // for each buf // for each elem in buf // if edge // e_local = buf // else // v_local = buf lv = 0; le = 0; for (b = 0; b < NUMNEI; b++) { len = ArrayLength( recvbufs[b] ); buf = ArrayGetData( recvbufs[b] ); for (i = 0; i < len; i++) { if ( ftype[ buf[i].type ].isEdge ) { e_local[le].eID = buf[i].xID; e_local[le].type = buf[i].type; e_local[le].l0 = buf[i].X.x; e_local[le].vID[0] = buf[i].yIDs[0]; e_local[le].vID[1] = buf[i].yIDs[1]; le++; } else { v_local[lv].vID = buf[i].xID; v_local[lv].type= buf[i].type; v_local[lv].X = buf[i].X; v_local[lv].V = buf[i].V; for (e = 0; e < MAXEDGES; e++) { v_local[lv].eID[e] = buf[i].yIDs[e]; } lv++; } // if vertex or edge } // for i in recvbuf } // for b in NUMNEI PetscFunctionReturn(0); }
nsSVGElement::StringAttributesInfo SVGMPathElement::GetStringInfo() { return StringAttributesInfo(mStringAttributes, sStringInfo, ArrayLength(sStringInfo)); }
bool PluginHangUIParent::Init(const nsString& aPluginName) { if (mHangUIProcessHandle) { return false; } nsresult rv; rv = mMiniShm.Init(this, ::IsDebuggerPresent() ? INFINITE : mIPCTimeoutMs); NS_ENSURE_SUCCESS(rv, false); nsCOMPtr<nsIProperties> directoryService(do_GetService(NS_DIRECTORY_SERVICE_CONTRACTID)); if (!directoryService) { return false; } nsCOMPtr<nsIFile> greDir; rv = directoryService->Get(NS_GRE_DIR, NS_GET_IID(nsIFile), getter_AddRefs(greDir)); if (NS_FAILED(rv)) { return false; } nsAutoString path; greDir->GetPath(path); FilePath exePath(path.get()); exePath = exePath.AppendASCII(MOZ_HANGUI_PROCESS_NAME); CommandLine commandLine(exePath.value()); nsXPIDLString localizedStr; const PRUnichar* formatParams[] = { aPluginName.get() }; rv = nsContentUtils::FormatLocalizedString(nsContentUtils::eDOM_PROPERTIES, "PluginHangUIMessage", formatParams, localizedStr); if (NS_FAILED(rv)) { return false; } commandLine.AppendLooseValue(localizedStr.get()); const char* keys[] = { "PluginHangUITitle", "PluginHangUIWaitButton", "PluginHangUIStopButton", "DontAskAgain" }; for (unsigned int i = 0; i < ArrayLength(keys); ++i) { rv = nsContentUtils::GetLocalizedString(nsContentUtils::eDOM_PROPERTIES, keys[i], localizedStr); if (NS_FAILED(rv)) { return false; } commandLine.AppendLooseValue(localizedStr.get()); } rv = GetHangUIOwnerWindowHandle(mMainWindowHandle); if (NS_FAILED(rv)) { return false; } nsAutoString hwndStr; hwndStr.AppendPrintf("%p", mMainWindowHandle); commandLine.AppendLooseValue(hwndStr.get()); ScopedHandle procHandle(::OpenProcess(SYNCHRONIZE, TRUE, GetCurrentProcessId())); if (!procHandle.IsValid()) { return false; } nsAutoString procHandleStr; procHandleStr.AppendPrintf("%p", procHandle.Get()); commandLine.AppendLooseValue(procHandleStr.get()); // On Win7+, pass the application user model to the child, so it can // register with it. This insures windows created by the Hang UI // properly group with the parent app on the Win7 taskbar. nsCOMPtr<nsIWinTaskbar> taskbarInfo = do_GetService(NS_TASKBAR_CONTRACTID); if (taskbarInfo) { bool isSupported = false; taskbarInfo->GetAvailable(&isSupported); nsAutoString appId; if (isSupported && NS_SUCCEEDED(taskbarInfo->GetDefaultGroupId(appId))) { commandLine.AppendLooseValue(appId.get()); } else { commandLine.AppendLooseValue(L"-"); } } else { commandLine.AppendLooseValue(L"-"); } nsAutoString ipcTimeoutStr; ipcTimeoutStr.AppendInt(mIPCTimeoutMs); commandLine.AppendLooseValue(ipcTimeoutStr.get()); std::wstring ipcCookie; rv = mMiniShm.GetCookie(ipcCookie); if (NS_FAILED(rv)) { return false; } commandLine.AppendLooseValue(ipcCookie); ScopedHandle showEvent(::CreateEvent(nullptr, FALSE, FALSE, nullptr)); if (!showEvent.IsValid()) { return false; } mShowEvent = showEvent.Get(); MutexAutoLock lock(mMutex); STARTUPINFO startupInfo = { sizeof(STARTUPINFO) }; PROCESS_INFORMATION processInfo = { nullptr }; BOOL isProcessCreated = ::CreateProcess(exePath.value().c_str(), const_cast<wchar_t*>(commandLine.command_line_string().c_str()), nullptr, nullptr, TRUE, DETACHED_PROCESS, nullptr, nullptr, &startupInfo, &processInfo); if (isProcessCreated) { ::CloseHandle(processInfo.hThread); mHangUIProcessHandle = processInfo.hProcess; ::RegisterWaitForSingleObject(&mRegWait, processInfo.hProcess, &SOnHangUIProcessExit, this, INFINITE, WT_EXECUTEDEFAULT | WT_EXECUTEONLYONCE); ::WaitForSingleObject(mShowEvent, ::IsDebuggerPresent() ? INFINITE : mIPCTimeoutMs); // Setting this to true even if we time out on mShowEvent. This timeout // typically occurs when the machine is thrashing so badly that // plugin-hang-ui.exe is taking a while to start. If we didn't set // this to true, Firefox would keep spawning additional plugin-hang-ui // processes, which is not what we want. mIsShowing = true; } mShowEvent = nullptr; return !(!isProcessCreated); }
bool WebGLContext::InitWebGL2() { MOZ_ASSERT(IsWebGL2(), "WebGLContext is not a WebGL 2 context!"); // check OpenGL features if (!gl->IsSupported(gl::GLFeature::occlusion_query) && !gl->IsSupported(gl::GLFeature::occlusion_query_boolean)) { // On desktop, we fake occlusion_query_boolean with occlusion_query if // necessary. (See WebGL2ContextQueries.cpp) GenerateWarning("WebGL 2 unavailable. Requires occlusion queries."); return false; } std::vector<gl::GLFeature> missingList; for (size_t i = 0; i < ArrayLength(kRequiredFeatures); i++) { if (!gl->IsSupported(kRequiredFeatures[i])) missingList.push_back(kRequiredFeatures[i]); } #ifdef XP_MACOSX // On OSX, GL core profile is used. This requires texture swizzle // support to emulate legacy texture formats: ALPHA, LUMINANCE, // and LUMINANCE_ALPHA. if (!gl->IsSupported(gl::GLFeature::texture_swizzle)) missingList.push_back(gl::GLFeature::texture_swizzle); #endif if (missingList.size()) { nsAutoCString exts; for (auto itr = missingList.begin(); itr != missingList.end(); ++itr) { exts.AppendLiteral("\n "); exts.Append(gl::GLContext::GetFeatureName(*itr)); } GenerateWarning("WebGL 2 unavailable. The following required features are" " unavailible: %s", exts.BeginReading()); return false; } // ok WebGL 2 is compatible, we can enable natively supported extensions. for (size_t i = 0; i < ArrayLength(kNativelySupportedExtensions); i++) { EnableExtension(kNativelySupportedExtensions[i]); MOZ_ASSERT(IsExtensionEnabled(kNativelySupportedExtensions[i])); } // we initialise WebGL 2 related stuff. gl->GetUIntegerv(LOCAL_GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS, &mGLMaxTransformFeedbackSeparateAttribs); gl->GetUIntegerv(LOCAL_GL_MAX_UNIFORM_BUFFER_BINDINGS, &mGLMaxUniformBufferBindings); mBoundTransformFeedbackBuffers.SetLength(mGLMaxTransformFeedbackSeparateAttribs); mBoundUniformBuffers.SetLength(mGLMaxUniformBufferBindings); mDefaultTransformFeedback = new WebGLTransformFeedback(this, 0); mBoundTransformFeedback = mDefaultTransformFeedback; mBypassShaderValidation = true; return true; }
nsSVGElement::NumberAttributesInfo SVGFEDisplacementMapElement::GetNumberInfo() { return NumberAttributesInfo(mNumberAttributes, sNumberInfo, ArrayLength(sNumberInfo)); }
nsSVGElement::StringAttributesInfo SVGFEDisplacementMapElement::GetStringInfo() { return StringAttributesInfo(mStringAttributes, sStringInfo, ArrayLength(sStringInfo)); }
nsSVGElement::IntegerPairAttributesInfo SVGFEConvolveMatrixElement::GetIntegerPairInfo() { return IntegerPairAttributesInfo(mIntegerPairAttributes, sIntegerPairInfo, ArrayLength(sIntegerPairInfo)); }
nsSVGElement::BooleanAttributesInfo SVGFEConvolveMatrixElement::GetBooleanInfo() { return BooleanAttributesInfo(mBooleanAttributes, sBooleanInfo, ArrayLength(sBooleanInfo)); }
//////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// // When a peer has accepted a GT2Connection the UDP layer needs to let // higher level app or message handler know that it accepted the request to // to message a peer. void gsUdpConnectedRoutingCB(GT2Connection theConnection, GT2Result theResult, GT2Byte *theMessage, int theMessageLen) { GSUdpEngineObject *aUdp = gsUdpEngineGetEngine(); int aIndex, len; GSUdpErrorCode aCode; char anAddr[GS_IP_ADDR_AND_PORT]; switch(theResult) { case GT2NegotiationError: aCode = GS_UDP_REMOTE_ERROR; break; case GT2Rejected: aCode = GS_UDP_REJECTED; break; case GT2TimedOut: aCode = GS_UDP_TIMED_OUT; break; case GT2Success: aCode = GS_UDP_NO_ERROR; break; default: aCode = GS_UDP_UNKNOWN_ERROR; break; } if (theResult == GT2Rejected) { int aRemotePeerIdx; GSUdpRemotePeer aRemotePeer; aRemotePeer.mAddr = gt2GetRemoteIP(theConnection); aRemotePeer.mPort = gt2GetRemotePort(theConnection); aRemotePeerIdx = ArraySearch(aUdp->mRemotePeers, &aRemotePeer, gsUdpRemotePeerCompare, 0, 0); if (aRemotePeerIdx != NOT_FOUND) { gsDebugFormat(GSIDebugCat_Common, GSIDebugType_Network, GSIDebugLevel_Comment, "[Udp Engine] Connect rejected by %s\n", gt2AddressToString(gt2GetRemoteIP(theConnection), gt2GetRemotePort(theConnection), anAddr)); ArrayDeleteAt(aUdp->mRemotePeers, aRemotePeerIdx); } } len = ArrayLength(aUdp->mMsgHandlers); for (aIndex = 0; aIndex < len; aIndex++) { int aRemotePeerIdx; GSUdpRemotePeer aRemotePeer; GSUdpMsgHandler *aTempHandler = (GSUdpMsgHandler *)ArrayNth(aUdp->mMsgHandlers, aIndex); aRemotePeer.mAddr = gt2GetRemoteIP(theConnection); aRemotePeer.mPort = gt2GetRemotePort(theConnection); aRemotePeerIdx = ArraySearch(aTempHandler->mPendingConnections, &aRemotePeer, gsUdpRemotePeerCompare, 0, 0); if (aRemotePeerIdx != NOT_FOUND) { if (aTempHandler->mConnected) { gsDebugFormat(GSIDebugCat_Common, GSIDebugType_Network, GSIDebugLevel_Comment, "[Udp Engine] Passing connect result to message handler\n"); aTempHandler->mConnected(gt2GetRemoteIP(theConnection), gt2GetRemotePort(theConnection), aCode, theResult == GT2Rejected ? gsi_true : gsi_false, aTempHandler->mUserData); } ArrayDeleteAt(aTempHandler->mPendingConnections, aRemotePeerIdx); return; } } if (aUdp->mAppPendingConnections > 0) { if (aUdp->mAppConnected) { gsDebugFormat(GSIDebugCat_Common, GSIDebugType_Network, GSIDebugLevel_Comment, "[Udp Engine] Passing connect result to app\n"); aUdp->mAppConnected(gt2GetRemoteIP(theConnection),gt2GetRemotePort(theConnection), aCode, theResult == GT2Rejected ? gsi_true : gsi_false, aUdp->mAppUserData); } aUdp->mAppPendingConnections--; } GSI_UNUSED(theMessage); GSI_UNUSED(theMessageLen); GSI_UNUSED(anAddr); }
//////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// // UDP Layer must be initialized // theIp and thePort cannot be 0 (Zero) // Starts a request to open a communication channel with another peer based on // IP and port. GSUdpErrorCode gsUdpEngineStartTalkingToPeer(unsigned int theIp, unsigned short thePort, char theInitMsg[GS_UDP_MSG_HEADER_LEN], int timeOut) { char anAddr[GS_IP_ADDR_AND_PORT]; GSUdpRemotePeer aRemotePeer; GSUdpMsgHandler aHandler; GSUdpEngineObject *aUdp = gsUdpEngineGetEngine(); GT2ConnectionCallbacks aCallbacks; int index; GS_ASSERT(aUdp->mInitialized); GS_ASSERT(theIp); GS_ASSERT(thePort); if (!aUdp->mInitialized) { gsDebugFormat(GSIDebugCat_Common, GSIDebugType_Network, GSIDebugLevel_Debug, "[Udp Engine] Engine not initialized\n"); return GS_UDP_NETWORK_ERROR; } if (theIp == 0 || thePort == 0) { gsDebugFormat(GSIDebugCat_Common, GSIDebugType_Network, GSIDebugLevel_Debug, "[Udp Engine] Invalid parameter(s), check ip, port"); return GS_UDP_PARAMETER_ERROR; } aRemotePeer.mAddr = theIp; // In Network Byte Order for GT2 aRemotePeer.mPort = thePort; // In Host Byte Order for GT2 index = ArraySearch(aUdp->mRemotePeers, &aRemotePeer, gsUdpRemotePeerCompare, 0, 0); if (index != NOT_FOUND) { GSUdpRemotePeer *aPeerFound = (GSUdpRemotePeer *)ArrayNth(aUdp->mRemotePeers, index); GT2ConnectionState aState = gt2GetConnectionState(aPeerFound->mConnection); if (aState == GT2Connected) { gsDebugFormat(GSIDebugCat_Common, GSIDebugType_Network, GSIDebugLevel_Debug, "[Udp Engine] Engine is already talking to remote address\n"); return GS_UDP_ADDRESS_ALREADY_IN_USE; } else if (aState == GT2Connecting) { memcpy(aHandler.mInitialMsg, theInitMsg, GS_UDP_MSG_HEADER_LEN); index = ArraySearch(aUdp->mMsgHandlers, &aHandler, gsUdpMsgHandlerCompare, 0, 0); if (index != NOT_FOUND) { GSUdpMsgHandler *aHandlerFound = (GSUdpMsgHandler *)ArrayNth(aUdp->mMsgHandlers, index); ArrayAppend(aHandlerFound->mPendingConnections, aPeerFound); } } } else { gt2AddressToString(theIp, thePort, anAddr); aCallbacks.closed = gsUdpClosedRoutingCB; aCallbacks.connected = gsUdpConnectedRoutingCB; aCallbacks.ping = gsUdpPingRoutingCB; aCallbacks.received = gsUdpReceivedRoutingCB; // start the connect without blocking since we want the engine to be as asynchronous as possible gt2Connect(aUdp->mSocket, &aRemotePeer.mConnection, anAddr, (unsigned char *)theInitMsg, GS_UDP_MSG_HEADER_LEN, timeOut, &aCallbacks, GT2False); ArrayAppend(aUdp->mRemotePeers, &aRemotePeer); memcpy(aHandler.mInitialMsg, theInitMsg, GS_UDP_MSG_HEADER_LEN); index = ArraySearch(aUdp->mMsgHandlers, &aHandler, gsUdpMsgHandlerCompare, 0, 0); if (index != NOT_FOUND) { GSUdpRemotePeer *aRemotePeerPtr = (GSUdpRemotePeer *)ArrayNth(aUdp->mRemotePeers, ArrayLength(aUdp->mRemotePeers) - 1); GSUdpMsgHandler *aHandlerFound = (GSUdpMsgHandler *)ArrayNth(aUdp->mMsgHandlers, index); ArrayAppend(aHandlerFound->mPendingConnections, &aRemotePeerPtr); } else { aUdp->mAppPendingConnections++; } } return GS_UDP_NO_ERROR; }
ThebesLayerBuffer::PaintState ContentClientIncremental::BeginPaintBuffer(ThebesLayer* aLayer, ThebesLayerBuffer::ContentType aContentType, uint32_t aFlags) { mTextureInfo.mDeprecatedTextureHostFlags = 0; PaintState result; // We need to disable rotation if we're going to be resampled when // drawing, because we might sample across the rotation boundary. bool canHaveRotation = !(aFlags & ThebesLayerBuffer::PAINT_WILL_RESAMPLE); nsIntRegion validRegion = aLayer->GetValidRegion(); Layer::SurfaceMode mode; ContentType contentType; nsIntRegion neededRegion; bool canReuseBuffer; nsIntRect destBufferRect; while (true) { mode = aLayer->GetSurfaceMode(); contentType = aContentType; neededRegion = aLayer->GetVisibleRegion(); // If we're going to resample, we need a buffer that's in clamp mode. canReuseBuffer = neededRegion.GetBounds().Size() <= mBufferRect.Size() && mHasBuffer && (!(aFlags & ThebesLayerBuffer::PAINT_WILL_RESAMPLE) || !(mTextureInfo.mTextureFlags & TEXTURE_ALLOW_REPEAT)); if (canReuseBuffer) { if (mBufferRect.Contains(neededRegion.GetBounds())) { // We don't need to adjust mBufferRect. destBufferRect = mBufferRect; } else { // The buffer's big enough but doesn't contain everything that's // going to be visible. We'll move it. destBufferRect = nsIntRect(neededRegion.GetBounds().TopLeft(), mBufferRect.Size()); } } else { destBufferRect = neededRegion.GetBounds(); } if (mode == Layer::SURFACE_COMPONENT_ALPHA) { if (!gfxPlatform::ComponentAlphaEnabled() || !aLayer->GetParent() || !aLayer->GetParent()->SupportsComponentAlphaChildren()) { mode = Layer::SURFACE_SINGLE_CHANNEL_ALPHA; } else { contentType = gfxASurface::CONTENT_COLOR; } } if ((aFlags & ThebesLayerBuffer::PAINT_WILL_RESAMPLE) && (!neededRegion.GetBounds().IsEqualInterior(destBufferRect) || neededRegion.GetNumRects() > 1)) { // The area we add to neededRegion might not be painted opaquely if (mode == Layer::SURFACE_OPAQUE) { contentType = gfxASurface::CONTENT_COLOR_ALPHA; mode = Layer::SURFACE_SINGLE_CHANNEL_ALPHA; } // For component alpha layers, we leave contentType as CONTENT_COLOR. // We need to validate the entire buffer, to make sure that only valid // pixels are sampled neededRegion = destBufferRect; } if (mHasBuffer && (mContentType != contentType || (mode == Layer::SURFACE_COMPONENT_ALPHA) != mHasBufferOnWhite)) { // We're effectively clearing the valid region, so we need to draw // the entire needed region now. result.mRegionToInvalidate = aLayer->GetValidRegion(); validRegion.SetEmpty(); mHasBuffer = false; mHasBufferOnWhite = false; mBufferRect.SetRect(0, 0, 0, 0); mBufferRotation.MoveTo(0, 0); // Restart decision process with the cleared buffer. We can only go // around the loop one more iteration, since mTexImage is null now. continue; } break; } result.mRegionToDraw.Sub(neededRegion, validRegion); if (result.mRegionToDraw.IsEmpty()) return result; if (destBufferRect.width > mForwarder->GetMaxTextureSize() || destBufferRect.height > mForwarder->GetMaxTextureSize()) { return result; } // BlitTextureImage depends on the FBO texture target being // TEXTURE_2D. This isn't the case on some older X1600-era Radeons. if (!mForwarder->SupportsTextureBlitting() || !mForwarder->SupportsPartialUploads()) { result.mRegionToDraw = neededRegion; validRegion.SetEmpty(); mHasBuffer = false; mHasBufferOnWhite = false; mBufferRect.SetRect(0, 0, 0, 0); mBufferRotation.MoveTo(0, 0); canReuseBuffer = false; } nsIntRect drawBounds = result.mRegionToDraw.GetBounds(); bool createdBuffer = false; uint32_t bufferFlags = canHaveRotation ? TEXTURE_ALLOW_REPEAT : 0; if (mode == Layer::SURFACE_COMPONENT_ALPHA) { bufferFlags |= TEXTURE_COMPONENT_ALPHA; } if (canReuseBuffer) { nsIntRect keepArea; if (keepArea.IntersectRect(destBufferRect, mBufferRect)) { // Set mBufferRotation so that the pixels currently in mBuffer // will still be rendered in the right place when mBufferRect // changes to destBufferRect. nsIntPoint newRotation = mBufferRotation + (destBufferRect.TopLeft() - mBufferRect.TopLeft()); WrapRotationAxis(&newRotation.x, mBufferRect.width); WrapRotationAxis(&newRotation.y, mBufferRect.height); NS_ASSERTION(nsIntRect(nsIntPoint(0,0), mBufferRect.Size()).Contains(newRotation), "newRotation out of bounds"); int32_t xBoundary = destBufferRect.XMost() - newRotation.x; int32_t yBoundary = destBufferRect.YMost() - newRotation.y; if ((drawBounds.x < xBoundary && xBoundary < drawBounds.XMost()) || (drawBounds.y < yBoundary && yBoundary < drawBounds.YMost()) || (newRotation != nsIntPoint(0,0) && !canHaveRotation)) { // The stuff we need to redraw will wrap around an edge of the // buffer, so we will need to do a self-copy // If mBufferRotation == nsIntPoint(0,0) we could do a real // self-copy but we're not going to do that in GL yet. // We can't do a real self-copy because the buffer is rotated. // So allocate a new buffer for the destination. destBufferRect = neededRegion.GetBounds(); createdBuffer = true; } else { mBufferRect = destBufferRect; mBufferRotation = newRotation; } } else { // No pixels are going to be kept. The whole visible region // will be redrawn, so we don't need to copy anything, so we don't // set destBuffer. mBufferRect = destBufferRect; mBufferRotation = nsIntPoint(0,0); } } else { // The buffer's not big enough, so allocate a new one createdBuffer = true; } NS_ASSERTION(!(aFlags & ThebesLayerBuffer::PAINT_WILL_RESAMPLE) || destBufferRect == neededRegion.GetBounds(), "If we're resampling, we need to validate the entire buffer"); if (!createdBuffer && !mHasBuffer) { return result; } if (createdBuffer) { if (mHasBuffer && (mode != Layer::SURFACE_COMPONENT_ALPHA || mHasBufferOnWhite)) { mTextureInfo.mDeprecatedTextureHostFlags = TEXTURE_HOST_COPY_PREVIOUS; } mHasBuffer = true; if (mode == Layer::SURFACE_COMPONENT_ALPHA) { mHasBufferOnWhite = true; } mBufferRect = destBufferRect; mBufferRotation = nsIntPoint(0,0); NotifyBufferCreated(contentType, bufferFlags); } NS_ASSERTION(canHaveRotation || mBufferRotation == nsIntPoint(0,0), "Rotation disabled, but we have nonzero rotation?"); nsIntRegion invalidate; invalidate.Sub(aLayer->GetValidRegion(), destBufferRect); result.mRegionToInvalidate.Or(result.mRegionToInvalidate, invalidate); // BeginUpdate is allowed to modify the given region, // if it wants more to be repainted than we request. if (mode == Layer::SURFACE_COMPONENT_ALPHA) { nsIntRegion drawRegionCopy = result.mRegionToDraw; nsRefPtr<gfxASurface> onBlack = GetUpdateSurface(BUFFER_BLACK, drawRegionCopy); nsRefPtr<gfxASurface> onWhite = GetUpdateSurface(BUFFER_WHITE, result.mRegionToDraw); if (onBlack && onWhite) { NS_ASSERTION(result.mRegionToDraw == drawRegionCopy, "BeginUpdate should always modify the draw region in the same way!"); FillSurface(onBlack, result.mRegionToDraw, nsIntPoint(drawBounds.x, drawBounds.y), gfxRGBA(0.0, 0.0, 0.0, 1.0)); FillSurface(onWhite, result.mRegionToDraw, nsIntPoint(drawBounds.x, drawBounds.y), gfxRGBA(1.0, 1.0, 1.0, 1.0)); if (RefPtr<DrawTarget> onBlackDT = gfxPlatform::GetPlatform()->CreateDrawTargetForUpdateSurface(onBlack, onBlack->GetSize())) { RefPtr<DrawTarget> onWhiteDT = gfxPlatform::GetPlatform()->CreateDrawTargetForUpdateSurface(onWhite, onWhite->GetSize()); RefPtr<DrawTarget> dt = Factory::CreateDualDrawTarget(onBlackDT, onWhiteDT); result.mContext = new gfxContext(dt); } else { gfxASurface* surfaces[2] = { onBlack.get(), onWhite.get() }; nsRefPtr<gfxTeeSurface> surf = new gfxTeeSurface(surfaces, ArrayLength(surfaces)); // XXX If the device offset is set on the individual surfaces instead of on // the tee surface, we render in the wrong place. Why? gfxPoint deviceOffset = onBlack->GetDeviceOffset(); onBlack->SetDeviceOffset(gfxPoint(0, 0)); onWhite->SetDeviceOffset(gfxPoint(0, 0)); surf->SetDeviceOffset(deviceOffset); // Using this surface as a source will likely go horribly wrong, since // only the onBlack surface will really be used, so alpha information will // be incorrect. surf->SetAllowUseAsSource(false); result.mContext = new gfxContext(surf); } } else { result.mContext = nullptr; } } else { nsRefPtr<gfxASurface> surf = GetUpdateSurface(BUFFER_BLACK, result.mRegionToDraw); if (RefPtr<DrawTarget> dt = gfxPlatform::GetPlatform()->CreateDrawTargetForUpdateSurface(surf, surf->GetSize())) { result.mContext = new gfxContext(dt); } else { result.mContext = new gfxContext(surf); } } if (!result.mContext) { NS_WARNING("unable to get context for update"); return result; } result.mContext->Translate(-gfxPoint(drawBounds.x, drawBounds.y)); // If we do partial updates, we have to clip drawing to the regionToDraw. // If we don't clip, background images will be fillrect'd to the region correctly, // while text or lines will paint outside of the regionToDraw. This becomes apparent // with concave regions. Right now the scrollbars invalidate a narrow strip of the bar // although they never cover it. This leads to two draw rects, the narow strip and the actually // newly exposed area. It would be wise to fix this glitch in any way to have simpler // clip and draw regions. gfxUtils::ClipToRegion(result.mContext, result.mRegionToDraw); if (mContentType == gfxASurface::CONTENT_COLOR_ALPHA) { result.mContext->SetOperator(gfxContext::OPERATOR_CLEAR); result.mContext->Paint(); result.mContext->SetOperator(gfxContext::OPERATOR_OVER); } return result; }
void TextTrackManager::PerformTrackSelection(TextTrackKind aTextTrackKind) { TextTrackKind ttKinds[] = { aTextTrackKind }; PerformTrackSelection(ttKinds, ArrayLength(ttKinds)); }
/* static */ guint KeymapWrapper::GuessGDKKeyval(uint32_t aDOMKeyCode) { // First, try to handle alphanumeric input, not listed in nsKeycodes: // most likely, more letters will be getting typed in than things in // the key list, so we will look through these first. if (aDOMKeyCode >= NS_VK_A && aDOMKeyCode <= NS_VK_Z) { // gdk and DOM both use the ASCII codes for these keys. return aDOMKeyCode; } // numbers if (aDOMKeyCode >= NS_VK_0 && aDOMKeyCode <= NS_VK_9) { // gdk and DOM both use the ASCII codes for these keys. return aDOMKeyCode - NS_VK_0 + GDK_0; } switch (aDOMKeyCode) { // keys in numpad case NS_VK_MULTIPLY: return GDK_KP_Multiply; case NS_VK_ADD: return GDK_KP_Add; case NS_VK_SEPARATOR: return GDK_KP_Separator; case NS_VK_SUBTRACT: return GDK_KP_Subtract; case NS_VK_DECIMAL: return GDK_KP_Decimal; case NS_VK_DIVIDE: return GDK_KP_Divide; case NS_VK_NUMPAD0: return GDK_KP_0; case NS_VK_NUMPAD1: return GDK_KP_1; case NS_VK_NUMPAD2: return GDK_KP_2; case NS_VK_NUMPAD3: return GDK_KP_3; case NS_VK_NUMPAD4: return GDK_KP_4; case NS_VK_NUMPAD5: return GDK_KP_5; case NS_VK_NUMPAD6: return GDK_KP_6; case NS_VK_NUMPAD7: return GDK_KP_7; case NS_VK_NUMPAD8: return GDK_KP_8; case NS_VK_NUMPAD9: return GDK_KP_9; // other prinable keys case NS_VK_SPACE: return GDK_space; case NS_VK_COLON: return GDK_colon; case NS_VK_SEMICOLON: return GDK_semicolon; case NS_VK_LESS_THAN: return GDK_less; case NS_VK_EQUALS: return GDK_equal; case NS_VK_GREATER_THAN: return GDK_greater; case NS_VK_QUESTION_MARK: return GDK_question; case NS_VK_AT: return GDK_at; case NS_VK_CIRCUMFLEX: return GDK_asciicircum; case NS_VK_EXCLAMATION: return GDK_exclam; case NS_VK_DOUBLE_QUOTE: return GDK_quotedbl; case NS_VK_HASH: return GDK_numbersign; case NS_VK_DOLLAR: return GDK_dollar; case NS_VK_PERCENT: return GDK_percent; case NS_VK_AMPERSAND: return GDK_ampersand; case NS_VK_UNDERSCORE: return GDK_underscore; case NS_VK_OPEN_PAREN: return GDK_parenleft; case NS_VK_CLOSE_PAREN: return GDK_parenright; case NS_VK_ASTERISK: return GDK_asterisk; case NS_VK_PLUS: return GDK_plus; case NS_VK_PIPE: return GDK_bar; case NS_VK_HYPHEN_MINUS: return GDK_minus; case NS_VK_OPEN_CURLY_BRACKET: return GDK_braceleft; case NS_VK_CLOSE_CURLY_BRACKET: return GDK_braceright; case NS_VK_TILDE: return GDK_asciitilde; case NS_VK_COMMA: return GDK_comma; case NS_VK_PERIOD: return GDK_period; case NS_VK_SLASH: return GDK_slash; case NS_VK_BACK_QUOTE: return GDK_grave; case NS_VK_OPEN_BRACKET: return GDK_bracketleft; case NS_VK_BACK_SLASH: return GDK_backslash; case NS_VK_CLOSE_BRACKET: return GDK_bracketright; case NS_VK_QUOTE: return GDK_apostrophe; } // misc other things for (uint32_t i = 0; i < ArrayLength(kKeyPairs); ++i) { if (kKeyPairs[i].DOMKeyCode == aDOMKeyCode) { return kKeyPairs[i].GDKKeyval; } } return 0; }
nsSVGElement::AngleAttributesInfo SVGMarkerElement::GetAngleInfo() { return AngleAttributesInfo(mAngleAttributes, sAngleInfo, ArrayLength(sAngleInfo)); }
nsSVGElement::EnumAttributesInfo SVGFEConvolveMatrixElement::GetEnumInfo() { return EnumAttributesInfo(mEnumAttributes, sEnumInfo, ArrayLength(sEnumInfo)); }
nsSVGElement::EnumAttributesInfo SVGMarkerElement::GetEnumInfo() { return EnumAttributesInfo(mEnumAttributes, sEnumInfo, ArrayLength(sEnumInfo)); }
nsSVGElement::StringAttributesInfo SVGFEConvolveMatrixElement::GetStringInfo() { return StringAttributesInfo(mStringAttributes, sStringInfo, ArrayLength(sStringInfo)); }
nsSVGElement::EnumAttributesInfo SVGFEDisplacementMapElement::GetEnumInfo() { return EnumAttributesInfo(mEnumAttributes, sEnumInfo, ArrayLength(sEnumInfo)); }
nsSVGElement::NumberListAttributesInfo SVGFEConvolveMatrixElement::GetNumberListInfo() { return NumberListAttributesInfo(mNumberListAttributes, sNumberListInfo, ArrayLength(sNumberListInfo)); }
nsresult AppleVDADecoder::SubmitFrame(mp4_demuxer::MP4Sample* aSample) { AutoCFRelease<CFDataRef> block = CFDataCreate(kCFAllocatorDefault, aSample->data, aSample->size); if (!block) { NS_ERROR("Couldn't create CFData"); return NS_ERROR_FAILURE; } AutoCFRelease<CFNumberRef> pts = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt64Type, &aSample->composition_timestamp); AutoCFRelease<CFNumberRef> dts = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt64Type, &aSample->decode_timestamp); AutoCFRelease<CFNumberRef> duration = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt64Type, &aSample->duration); AutoCFRelease<CFNumberRef> byte_offset = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt64Type, &aSample->byte_offset); char keyframe = aSample->is_sync_point ? 1 : 0; AutoCFRelease<CFNumberRef> cfkeyframe = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt8Type, &keyframe); const void* keys[] = { CFSTR("FRAME_PTS"), CFSTR("FRAME_DTS"), CFSTR("FRAME_DURATION"), CFSTR("FRAME_OFFSET"), CFSTR("FRAME_KEYFRAME") }; const void* values[] = { pts, dts, duration, byte_offset, cfkeyframe }; static_assert(ArrayLength(keys) == ArrayLength(values), "Non matching keys/values array size"); AutoCFRelease<CFDictionaryRef> frameInfo = CFDictionaryCreate(kCFAllocatorDefault, keys, values, ArrayLength(keys), &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); OSStatus rv = VDADecoderDecode(mDecoder, 0, block, frameInfo); if (rv != noErr) { NS_WARNING("AppleVDADecoder: Couldn't pass frame to decoder"); return NS_ERROR_FAILURE; } if (mIs106) { // TN2267: // frameInfo: A CFDictionaryRef containing information to be returned in // the output callback for this frame. // This dictionary can contain client provided information associated with // the frame being decoded, for example presentation time. // The CFDictionaryRef will be retained by the framework. // In 10.6, it is released one too many. So retain it. CFRetain(frameInfo); } // Ask for more data. if (mTaskQueue->IsEmpty()) { LOG("AppleVDADecoder task queue empty; requesting more data"); mCallback->InputExhausted(); } return NS_OK; }
NS_IMETHODIMP PostMessageEvent::Run() { MOZ_ASSERT(mTargetWindow->IsOuterWindow(), "should have been passed an outer window!"); MOZ_ASSERT(!mSource || mSource->IsOuterWindow(), "should have been passed an outer window!"); AutoJSAPI jsapi; jsapi.Init(); JSContext* cx = jsapi.cx(); // The document is just used for the principal mismatch error message below. // Use a stack variable so mSourceDocument is not held onto after this method // finishes, regardless of the method outcome. nsCOMPtr<nsIDocument> sourceDocument; sourceDocument.swap(mSourceDocument); // If we bailed before this point we're going to leak mMessage, but // that's probably better than crashing. RefPtr<nsGlobalWindow> targetWindow; if (mTargetWindow->IsClosedOrClosing() || !(targetWindow = mTargetWindow->GetCurrentInnerWindowInternal()) || targetWindow->IsClosedOrClosing()) return NS_OK; MOZ_ASSERT(targetWindow->IsInnerWindow(), "we ordered an inner window!"); JSAutoCompartment ac(cx, targetWindow->GetWrapperPreserveColor()); // Ensure that any origin which might have been provided is the origin of this // window's document. Note that we do this *now* instead of when postMessage // is called because the target window might have been navigated to a // different location between then and now. If this check happened when // postMessage was called, it would be fairly easy for a malicious webpage to // intercept messages intended for another site by carefully timing navigation // of the target window so it changed location after postMessage but before // now. if (mProvidedPrincipal) { // Get the target's origin either from its principal or, in the case the // principal doesn't carry a URI (e.g. the system principal), the target's // document. nsIPrincipal* targetPrin = targetWindow->GetPrincipal(); if (NS_WARN_IF(!targetPrin)) return NS_OK; // Note: This is contrary to the spec with respect to file: URLs, which // the spec groups into a single origin, but given we intentionally // don't do that in other places it seems better to hold the line for // now. Long-term, we want HTML5 to address this so that we can // be compliant while being safer. if (!targetPrin->Equals(mProvidedPrincipal)) { nsAutoString providedOrigin, targetOrigin; nsresult rv = nsContentUtils::GetUTFOrigin(targetPrin, targetOrigin); NS_ENSURE_SUCCESS(rv, rv); rv = nsContentUtils::GetUTFOrigin(mProvidedPrincipal, providedOrigin); NS_ENSURE_SUCCESS(rv, rv); const char16_t* params[] = { providedOrigin.get(), targetOrigin.get() }; nsContentUtils::ReportToConsole(nsIScriptError::errorFlag, NS_LITERAL_CSTRING("DOM Window"), sourceDocument, nsContentUtils::eDOM_PROPERTIES, "TargetPrincipalDoesNotMatch", params, ArrayLength(params)); return NS_OK; } } ErrorResult rv; JS::Rooted<JS::Value> messageData(cx); nsCOMPtr<nsPIDOMWindowInner> window = targetWindow->AsInner(); Read(window, cx, &messageData, rv); if (NS_WARN_IF(rv.Failed())) { return rv.StealNSResult(); } // Create the event nsCOMPtr<mozilla::dom::EventTarget> eventTarget = do_QueryObject(targetWindow); RefPtr<MessageEvent> event = new MessageEvent(eventTarget, nullptr, nullptr); Nullable<WindowProxyOrMessagePort> source; source.SetValue().SetAsWindowProxy() = mSource ? mSource->AsOuter() : nullptr; event->InitMessageEvent(nullptr, NS_LITERAL_STRING("message"), false /*non-bubbling */, false /*cancelable */, messageData, mCallerOrigin, EmptyString(), source, nullptr); nsTArray<RefPtr<MessagePort>> ports = TakeTransferredPorts(); event->SetPorts(new MessagePortList(static_cast<dom::Event*>(event.get()), ports)); // We can't simply call dispatchEvent on the window because doing so ends // up flipping the trusted bit on the event, and we don't want that to // happen because then untrusted content can call postMessage on a chrome // window if it can get a reference to it. nsIPresShell *shell = targetWindow->GetExtantDoc()->GetShell(); RefPtr<nsPresContext> presContext; if (shell) presContext = shell->GetPresContext(); event->SetTrusted(mTrustedCaller); WidgetEvent* internalEvent = event->WidgetEventPtr(); nsEventStatus status = nsEventStatus_eIgnore; EventDispatcher::Dispatch(window, presContext, internalEvent, static_cast<dom::Event*>(event.get()), &status); return NS_OK; }
nsSVGElement::LengthAttributesInfo SVGForeignObjectElement::GetLengthInfo() { return LengthAttributesInfo(mLengthAttributes, sLengthInfo, ArrayLength(sLengthInfo)); }
already_AddRefed<nsITransferable> DataTransfer::GetTransferable(uint32_t aIndex, nsILoadContext* aLoadContext) { if (aIndex >= MozItemCount()) { return nullptr; } const nsTArray<RefPtr<DataTransferItem>>& item = *mItems->MozItemsAt(aIndex); uint32_t count = item.Length(); if (!count) { return nullptr; } nsCOMPtr<nsITransferable> transferable = do_CreateInstance("@mozilla.org/widget/transferable;1"); if (!transferable) { return nullptr; } transferable->Init(aLoadContext); nsCOMPtr<nsIStorageStream> storageStream; nsCOMPtr<nsIBinaryOutputStream> stream; bool added = false; bool handlingCustomFormats = true; // When writing the custom data, we need to ensure that there is sufficient // space for a (uint32_t) data ending type, and the null byte character at // the end of the nsCString. We claim that space upfront and store it in // baseLength. This value will be set to zero if a write error occurs // indicating that the data and length are no longer valid. const uint32_t baseLength = sizeof(uint32_t) + 1; uint32_t totalCustomLength = baseLength; const char* knownFormats[] = { kTextMime, kHTMLMime, kNativeHTMLMime, kRTFMime, kURLMime, kURLDataMime, kURLDescriptionMime, kURLPrivateMime, kPNGImageMime, kJPEGImageMime, kGIFImageMime, kNativeImageMime, kFileMime, kFilePromiseMime, kFilePromiseURLMime, kFilePromiseDestFilename, kFilePromiseDirectoryMime, kMozTextInternal, kHTMLContext, kHTMLInfo }; /* * Two passes are made here to iterate over all of the types. First, look for * any types that are not in the list of known types. For this pass, * handlingCustomFormats will be true. Data that corresponds to unknown types * will be pulled out and inserted into a single type (kCustomTypesMime) by * writing the data into a stream. * * The second pass will iterate over the formats looking for known types. * These are added as is. The unknown types are all then inserted as a single * type (kCustomTypesMime) in the same position of the first custom type. This * model is used to maintain the format order as best as possible. * * The format of the kCustomTypesMime type is one or more of the following * stored sequentially: * <32-bit> type (only none or string is supported) * <32-bit> length of format * <wide string> format * <32-bit> length of data * <wide string> data * A type of eCustomClipboardTypeId_None ends the list, without any following * data. */ do { for (uint32_t f = 0; f < count; f++) { RefPtr<DataTransferItem> formatitem = item[f]; nsCOMPtr<nsIVariant> variant = formatitem->DataNoSecurityCheck(); if (!variant) { // skip empty items continue; } nsAutoString type; formatitem->GetInternalType(type); // If the data is of one of the well-known formats, use it directly. bool isCustomFormat = true; for (uint32_t f = 0; f < ArrayLength(knownFormats); f++) { if (type.EqualsASCII(knownFormats[f])) { isCustomFormat = false; break; } } uint32_t lengthInBytes; nsCOMPtr<nsISupports> convertedData; if (handlingCustomFormats) { if (!ConvertFromVariant(variant, getter_AddRefs(convertedData), &lengthInBytes)) { continue; } // When handling custom types, add the data to the stream if this is a // custom type. If totalCustomLength is 0, then a write error occurred // on a previous item, so ignore any others. if (isCustomFormat && totalCustomLength > 0) { // If it isn't a string, just ignore it. The dataTransfer is cached in // the drag sesion during drag-and-drop, so non-strings will be // available when dragging locally. nsCOMPtr<nsISupportsString> str(do_QueryInterface(convertedData)); if (str) { nsAutoString data; str->GetData(data); if (!stream) { // Create a storage stream to write to. NS_NewStorageStream(1024, UINT32_MAX, getter_AddRefs(storageStream)); nsCOMPtr<nsIOutputStream> outputStream; storageStream->GetOutputStream(0, getter_AddRefs(outputStream)); stream = do_CreateInstance("@mozilla.org/binaryoutputstream;1"); stream->SetOutputStream(outputStream); } CheckedInt<uint32_t> formatLength = CheckedInt<uint32_t>(type.Length()) * sizeof(nsString::char_type); // The total size of the stream is the format length, the data // length, two integers to hold the lengths and one integer for // the string flag. Guard against large data by ignoring any that // don't fit. CheckedInt<uint32_t> newSize = formatLength + totalCustomLength + lengthInBytes + (sizeof(uint32_t) * 3); if (newSize.isValid()) { // If a write error occurs, set totalCustomLength to 0 so that // further processing gets ignored. nsresult rv = stream->Write32(eCustomClipboardTypeId_String); if (NS_WARN_IF(NS_FAILED(rv))) { totalCustomLength = 0; continue; } rv = stream->Write32(formatLength.value()); if (NS_WARN_IF(NS_FAILED(rv))) { totalCustomLength = 0; continue; } rv = stream->WriteBytes((const char *)type.get(), formatLength.value()); if (NS_WARN_IF(NS_FAILED(rv))) { totalCustomLength = 0; continue; } rv = stream->Write32(lengthInBytes); if (NS_WARN_IF(NS_FAILED(rv))) { totalCustomLength = 0; continue; } rv = stream->WriteBytes((const char *)data.get(), lengthInBytes); if (NS_WARN_IF(NS_FAILED(rv))) { totalCustomLength = 0; continue; } totalCustomLength = newSize.value(); } } } } else if (isCustomFormat && stream) { // This is the second pass of the loop (handlingCustomFormats is false). // When encountering the first custom format, append all of the stream // at this position. If totalCustomLength is 0 indicating a write error // occurred, or no data has been added to it, don't output anything, if (totalCustomLength > baseLength) { // Write out an end of data terminator. nsresult rv = stream->Write32(eCustomClipboardTypeId_None); if (NS_SUCCEEDED(rv)) { nsCOMPtr<nsIInputStream> inputStream; storageStream->NewInputStream(0, getter_AddRefs(inputStream)); RefPtr<nsStringBuffer> stringBuffer = nsStringBuffer::Alloc(totalCustomLength); // Subtract off the null terminator when reading. totalCustomLength--; // Read the data from the stream and add a null-terminator as // ToString needs it. uint32_t amountRead; rv = inputStream->Read(static_cast<char*>(stringBuffer->Data()), totalCustomLength, &amountRead); if (NS_SUCCEEDED(rv)) { static_cast<char*>(stringBuffer->Data())[amountRead] = 0; nsCString str; stringBuffer->ToString(totalCustomLength, str); nsCOMPtr<nsISupportsCString> strSupports(do_CreateInstance(NS_SUPPORTS_CSTRING_CONTRACTID)); strSupports->SetData(str); nsresult rv = transferable->SetTransferData(kCustomTypesMime, strSupports, totalCustomLength); if (NS_FAILED(rv)) { return nullptr; } added = true; } } } // Clear the stream so it doesn't get used again. stream = nullptr; } else { // This is the second pass of the loop and a known type is encountered. // Add it as is. if (!ConvertFromVariant(variant, getter_AddRefs(convertedData), &lengthInBytes)) { continue; } // The underlying drag code uses text/unicode, so use that instead of // text/plain const char* format; NS_ConvertUTF16toUTF8 utf8format(type); if (utf8format.EqualsLiteral(kTextMime)) { format = kUnicodeMime; } else { format = utf8format.get(); } // If a converter is set for a format, set the converter for the // transferable and don't add the item nsCOMPtr<nsIFormatConverter> converter = do_QueryInterface(convertedData); if (converter) { transferable->AddDataFlavor(format); transferable->SetConverter(converter); continue; } nsresult rv = transferable->SetTransferData(format, convertedData, lengthInBytes); if (NS_FAILED(rv)) { return nullptr; } added = true; } } handlingCustomFormats = !handlingCustomFormats; } while (!handlingCustomFormats); // only return the transferable if data was successfully added to it if (added) { return transferable.forget(); } return nullptr; }
PetscErrorCode FiberField_Nei_Alltoall( FiberField f ) { int i; int neiIdx; // index where nei[] == src int count; // probing count num elements received const int tag = 128456826; // TODO: should tag # be something unique for each call to this routine? const int NUMRECV = f->NUMRECV; Array *sendbufs = f->sendbufs; Array *recvbufs = f->recvbufs; MPI_Request reqSend[NUMNEI]; MPI_Request reqRecv[NUMNEI]; MPI_Status status; MPI_Comm comm = f->comm; const PetscMPIInt *neiRanks; PetscErrorCode ierr; PetscFunctionBegin; //TODO: why is this barrier necessary if all Isend/Irecv matched with WaitAll? //BUG: without barrier, sources from other iterations caught in probe ierr = PetscBarrier(0); CHKERRQ(ierr); ierr = DMDAGetNeighbors(f->da, &neiRanks); CHKERRQ(ierr); // send verts to neighbors for (i = 0; i < NUMNEI; i++) { count = ArrayLength(sendbufs[i]); ierr = MPI_Isend(ArrayGetData(sendbufs[i]), count, f->vertmpitype, neiRanks[i], tag, comm, &reqSend[i] ); CHKERRQ(ierr); /*ierr = MPI_Send(ArrayGetData(sendbufs[i]), count, f->vertmpitype, neiRanks[i], tag, comm ); CHKERRQ(ierr);*/ #ifdef DEBUG_ALLTOALL ierr = PetscInfo1(0, "i = %d\n", i ); CHKERRQ(ierr); ierr = PetscInfo1(0, "dst = %d\n", neiRanks[i] ); CHKERRQ(ierr); ierr = PetscInfo1(0, "count = %d\n", ArrayLength(sendbufs[i]) ); CHKERRQ(ierr); #endif } // receive verts from neighbors for (i = 0; i < NUMRECV; i++) { // probe for count verts sent ierr = MPI_Probe(MPI_ANY_SOURCE, tag, comm, &status); CHKERRQ(ierr); ierr = MPI_Get_count( &status, f->vertmpitype, &count); CHKERRQ(ierr); // convert source rank into nei index (for recvbufs array) for (neiIdx = 0; neiIdx < NUMNEI; neiIdx++) { if( neiRanks[neiIdx] == status.MPI_SOURCE ) break; } #ifdef DEBUG_ALLTOALL ierr = PetscInfo1(0, "i = %d\n", i ); CHKERRQ(ierr); ierr = PetscInfo1(0, "src = %d\n", status.MPI_SOURCE ); CHKERRQ(ierr); ierr = PetscInfo1(0, "count = %d\n", count ); CHKERRQ(ierr); #endif ierr = ArraySetSize( recvbufs[neiIdx], count); CHKERRQ(ierr); ierr = MPI_Irecv( ArrayGetData(recvbufs[neiIdx]), count, f->vertmpitype, status.MPI_SOURCE, tag, comm, &reqRecv[i]); CHKERRQ(ierr); /*ierr = MPI_Recv( ArrayGetData(recvbufs[neiIdx]), count, f->vertmpitype, status.MPI_SOURCE, tag, comm, &status ); CHKERRQ(ierr);*/ } ierr = MPI_Waitall( NUMRECV, reqRecv, MPI_STATUSES_IGNORE ); CHKERRQ(ierr); ierr = MPI_Waitall( NUMNEI, reqSend, MPI_STATUSES_IGNORE ); CHKERRQ(ierr); PetscFunctionReturn(0); }
Expression *ForeachStatement::interpret(InterState *istate) { #if LOG printf("ForeachStatement::interpret()\n"); #endif if (istate->start == this) istate->start = NULL; if (istate->start) return NULL; Expression *e = NULL; Expression *eaggr; if (value->isOut() || value->isRef()) return EXP_CANT_INTERPRET; eaggr = aggr->interpret(istate); if (eaggr == EXP_CANT_INTERPRET) return EXP_CANT_INTERPRET; Expression *dim = ArrayLength(Type::tsize_t, eaggr); if (dim == EXP_CANT_INTERPRET) return EXP_CANT_INTERPRET; Expression *keysave = key ? key->value : NULL; Expression *valuesave = value->value; uinteger_t d = dim->toUInteger(); uinteger_t index; if (op == TOKforeach) { for (index = 0; index < d; index++) { Expression *ekey = new IntegerExp(loc, index, Type::tsize_t); if (key) key->value = ekey; e = Index(value->type, eaggr, ekey); if (e == EXP_CANT_INTERPRET) break; value->value = e; e = body ? body->interpret(istate) : NULL; if (e == EXP_CANT_INTERPRET) break; if (e == EXP_BREAK_INTERPRET) { e = NULL; break; } if (e == EXP_CONTINUE_INTERPRET) e = NULL; else if (e) break; } } else // TOKforeach_reverse { for (index = d; index-- != 0;) { Expression *ekey = new IntegerExp(loc, index, Type::tsize_t); if (key) key->value = ekey; e = Index(value->type, eaggr, ekey); if (e == EXP_CANT_INTERPRET) break; value->value = e; e = body ? body->interpret(istate) : NULL; if (e == EXP_CANT_INTERPRET) break; if (e == EXP_BREAK_INTERPRET) { e = NULL; break; } if (e == EXP_CONTINUE_INTERPRET) e = NULL; else if (e) break; } } value->value = valuesave; if (key) key->value = keysave; return e; }
PetscErrorCode FiberField_AddToSendbufs( FiberField field ) { int i; int e; const int vlen = ArrayLength(field->verts); const int elen = ArrayLength(field->edges); const BoundingBox lbbox = field->localBounds; int neiIdx; VertexEdgeMPI *evmpi; iCoor n; // index in 3x3x3 array nei Vertex v; PetscMPIInt sendRank; const PetscMPIInt *neiRanks; PetscErrorCode ierr; PetscFunctionBegin; ierr = DMDAGetNeighbors(field->da, &neiRanks); CHKERRQ(ierr); // clear send arrays // for each vert // if outside nei, err // else add vert to send list for (i = 0; i < NUMNEI; i++) { ArraySetSize( field->sendbufs[i], 0); } for (i = 0; i < vlen; i++) { ierr = ArrayGet( field->verts, i, &v ); CHKERRQ(ierr); PositionToNeiIdx( &lbbox, &v->X, &n, &neiIdx); // if vertex outside 3x3x3 nei, something went terribly wrong if (n.x < 0 || n.x > 2 || n.y < 0 || n.y > 2 || n.z < 0 || n.z > 2 ) { ierr = PetscInfo(0, "ERROR: Vertex outside 3x3x3 neighbor region\n"); CHKERRQ(ierr); ierr = PetscInfo1(0, "i = %d\n",i); CHKERRQ(ierr); ierr = PetscInfo3(0, "X = {%f, %f, %f}\n",v->X.x,v->X.y,v->X.z); CHKERRQ(ierr); ierr = PetscInfo3(0, "n = {%d, %d, %d}\n",n.x,n.y,n.z); CHKERRQ(ierr); ierr = PetscInfo(0, "ERROR: END MESSAGE\n"); CHKERRQ(ierr); SETERRQ(field->comm, 0, "Vertex outside 3x3x3 neighbor region"); } else { // convert nei index to mpi rank sendRank = neiRanks[neiIdx]; // in the edge case where a vertex leaves the global bounding box, abort // handle this case in the physics, not in the communication routine if ( sendRank == MPI_PROC_NULL) { ierr = PetscInfo(0, "ERROR: Vertex outside global bbox\n"); CHKERRQ(ierr); ierr = PetscInfo1(0, "i = %d\n",i); CHKERRQ(ierr); ierr = PetscInfo3(0, "X = {%f, %f, %f}\n",v->X.x,v->X.y,v->X.z); CHKERRQ(ierr); ierr = PetscInfo3(0, "n = {%d, %d, %d}\n",n.x,n.y,n.z); CHKERRQ(ierr); ierr = PetscInfo1(0, "neiIdx = %d\n",neiIdx); CHKERRQ(ierr); ierr = PetscInfo(0, "ERROR: END MESSAGE\n"); CHKERRQ(ierr); SETERRQ(field->comm, 0, "Vertex outside global bbox\n"); } // add vertex to send list[rank] ierr = ArrayAppend( field->sendbufs[neiIdx], &evmpi); CHKERRQ(ierr); evmpi->xID = v->vID; evmpi->type= v->type; evmpi->X = v->X; evmpi->V = v->V; for (e = 0; e < MAXEDGES; e++) { evmpi->yIDs[e] = v->eID[e]; } } } int min; int vPO; struct _Edge *edges = ArrayGetData(field->edges); struct _Vertex *vertsPO; ierr = FiberFieldGetVertexArrayPO( field, &vertsPO ); CHKERRQ(ierr); for (e = 0; e < elen; e++) { // the edge is 'owned' by the vertex with the smallest ID min = edges[e].vID[0] < edges[e].vID[1] ? 0 : 1; vPO = edges[e].vPO[min]; v = &vertsPO[vPO]; PositionToNeiIdx( &lbbox, &v->X, &n, &neiIdx); if (v->vID != edges[e].vID[min] ) { ierr = PetscInfo1(0, "v->vID = %d\n", v->vID); CHKERRQ(ierr); ierr = PetscInfo1(0, "edges[e].vID[min] = %d\n", edges[e].vID[min]); CHKERRQ(ierr); SETERRQ(PETSC_COMM_SELF, 0, "Bad vertex"); } ierr = ArrayAppend( field->sendbufs[neiIdx], &evmpi); CHKERRQ(ierr); evmpi->xID = edges[e].eID; evmpi->type = edges[e].type; evmpi->yIDs[0] = edges[e].vID[0]; evmpi->yIDs[1] = edges[e].vID[1]; evmpi->X.x = edges[e].l0; } PetscFunctionReturn(0); }
nsSVGElement::LengthAttributesInfo SVGMarkerElement::GetLengthInfo() { return LengthAttributesInfo(mLengthAttributes, sLengthInfo, ArrayLength(sLengthInfo)); }
int main(int argc, char** argv) { ScopedXPCOM xpcom("TestColorNames"); if (xpcom.failed()) return 1; nscolor rgb; int rv = 0; // First make sure we can find all of the tags that are supposed to // be in the table. Futz with the case to make sure any case will // work for (uint32_t index = 0 ; index < ArrayLength(kColorNames); index++) { // Lookup color by name and make sure it has the right id nsCString tagName(kColorNames[index]); // Check that color lookup by name gets the right rgb value if (!NS_ColorNameToRGB(NS_ConvertASCIItoUTF16(tagName), &rgb)) { fail("can't find '%s'", tagName.get()); rv = 1; } if (rgb != kColors[index]) { fail("name='%s' ColorNameToRGB=%x kColors[%d]=%08x", tagName.get(), rgb, index, kColors[index]); rv = 1; } // fiddle with the case to make sure we can still find it tagName.SetCharAt(tagName.CharAt(0) - 32, 0); if (!NS_ColorNameToRGB(NS_ConvertASCIItoUTF16(tagName), &rgb)) { fail("can't find '%s'", tagName.get()); rv = 1; } if (rgb != kColors[index]) { fail("name='%s' ColorNameToRGB=%x kColors[%d]=%08x", tagName.get(), rgb, index, kColors[index]); rv = 1; } // Check that parsing an RGB value in hex gets the right values uint8_t r = NS_GET_R(rgb); uint8_t g = NS_GET_G(rgb); uint8_t b = NS_GET_B(rgb); uint8_t a = NS_GET_A(rgb); if (a != UINT8_MAX) { // NS_HexToRGB() can not handle a color with alpha channel rgb = NS_RGB(r, g, b); } char cbuf[50]; PR_snprintf(cbuf, sizeof(cbuf), "%02x%02x%02x", r, g, b); nscolor hexrgb; if (!NS_HexToRGB(NS_ConvertASCIItoUTF16(cbuf), &hexrgb)) { fail("hex conversion to color of '%s'", cbuf); rv = 1; } if (hexrgb != rgb) { fail("rgb=%x hexrgb=%x", rgb, hexrgb); rv = 1; } } // Now make sure we don't find some garbage for (uint32_t i = 0; i < ArrayLength(kJunkNames); i++) { nsCString tag(kJunkNames[i]); if (NS_ColorNameToRGB(NS_ConvertASCIItoUTF16(tag), &rgb)) { fail("found '%s'", kJunkNames[i] ? kJunkNames[i] : "(null)"); rv = 1; } } if (rv == 0) passed("TestColorNames"); return rv; }
struct chanNode * AddChannel(const char *name, time_t time_, const char *modes, char *banlist, char *exemptlist) { struct chanNode *cNode; char new_modes[MAXLEN], *argv[MAXNUMPARAMS]; unsigned int nn; if (!IsChannelName(name)) { log_module(MAIN_LOG, LOG_ERROR, "Somebody asked to add channel '%s', which isn't a channel name!", name); return NULL; } if (!modes) modes = ""; safestrncpy(new_modes, modes, sizeof(new_modes)); nn = split_line(new_modes, 0, ArrayLength(argv), argv); if (!(cNode = GetChannel(name))) { cNode = calloc(1, sizeof(*cNode) + strlen(name)); strcpy(cNode->name, name); banList_init(&cNode->banlist); exemptList_init(&cNode->exemptlist); modeList_init(&cNode->members); mod_chanmode(NULL, cNode, argv, nn, MCP_FROM_SERVER); dict_insert(channels, cNode->name, cNode); cNode->timestamp = time_; rel_age = 1; } else if (cNode->timestamp > time_) { wipeout_channel(cNode, time_, argv, nn); rel_age = 1; } else if (cNode->timestamp == time_) { mod_chanmode(NULL, cNode, argv, nn, MCP_FROM_SERVER); rel_age = 0; } else { rel_age = -1; } /* rel_age is the relative ages of our channel data versus what is * in a BURST command. 1 means ours is younger, 0 means both are * the same age, -1 means ours is older. */ /* if it's a new or updated channel, make callbacks */ if (rel_age > 0) for (nn=0; nn<ncf_used; nn++) ncf_list[nn](cNode, ncf_list_extra[nn]); /* go through list of bans and add each one */ if (banlist && (rel_age >= 0)) { for (nn=0; banlist[nn];) { char *ban = banlist + nn; struct banNode *bn; while (banlist[nn] != ' ' && banlist[nn]) nn++; while (banlist[nn] == ' ') banlist[nn++] = 0; bn = calloc(1, sizeof(*bn)); safestrncpy(bn->ban, ban, sizeof(bn->ban)); safestrncpy(bn->who, "<unknown>", sizeof(bn->who)); bn->set = now; banList_append(&cNode->banlist, bn); } } /* go through list of exempts and add each one */ if (exemptlist && (rel_age >= 0)) { for (nn=0; exemptlist[nn];) { char *exempt = exemptlist + nn; struct exemptNode *en; while (exemptlist[nn] != ' ' && exemptlist[nn]) nn++; while (exemptlist[nn] == ' ') exemptlist[nn++] = 0; en = calloc(1, sizeof(*en)); safestrncpy(en->exempt, exempt, sizeof(en->exempt)); safestrncpy(en->who, "<unknown>", sizeof(en->who)); en->set = now; exemptList_append(&cNode->exemptlist, en); } } return cNode; }