bool CGPSController::IsKnownPosition() { Lock(); bool ret = m_knownPosition; Unlock(); return ret; }
AppInstance::~AppInstance() { try { Unlock(); } catch (AppInstException e) {} }
HGLOBAL MGlobal::Detach() { Unlock(); HGLOBAL p = (HGLOBAL)InterlockedExchangePointer((PVOID*)&mh_Global, NULL); return p; }
void OHCI::_FinishTransfers() { while (!fStopFinishThread) { if (acquire_sem(fFinishTransfersSem) < B_OK) continue; // eat up sems that have been released by multiple interrupts int32 semCount = 0; get_sem_count(fFinishTransfersSem, &semCount); if (semCount > 0) acquire_sem_etc(fFinishTransfersSem, semCount, B_RELATIVE_TIMEOUT, 0); if (!Lock()) continue; TRACE("finishing transfers (first transfer: %p; last" " transfer: %p)\n", fFirstTransfer, fLastTransfer); transfer_data *lastTransfer = NULL; transfer_data *transfer = fFirstTransfer; Unlock(); while (transfer) { bool transferDone = false; ohci_general_td *descriptor = transfer->first_descriptor; ohci_endpoint_descriptor *endpoint = transfer->endpoint; status_t callbackStatus = B_OK; MutexLocker endpointLocker(endpoint->lock); if ((endpoint->head_physical_descriptor & OHCI_ENDPOINT_HEAD_MASK) != endpoint->tail_physical_descriptor) { // there are still active transfers on this endpoint, we need // to wait for all of them to complete, otherwise we'd read // a potentially bogus data toggle value below TRACE("endpoint %p still has active tds\n", endpoint); lastTransfer = transfer; transfer = transfer->link; continue; } endpointLocker.Unlock(); while (descriptor && !transfer->canceled) { uint32 status = OHCI_TD_GET_CONDITION_CODE(descriptor->flags); if (status == OHCI_TD_CONDITION_NOT_ACCESSED) { // td is still active TRACE("td %p still active\n", descriptor); break; } if (status != OHCI_TD_CONDITION_NO_ERROR) { // an error occured, but we must ensure that the td // was actually done if (endpoint->head_physical_descriptor & OHCI_ENDPOINT_HALTED) { // the endpoint is halted, this guaratees us that this // descriptor has passed (we don't know if the endpoint // was halted because of this td, but we do not need // to know, as when it was halted by another td this // still ensures that this td was handled before). TRACE_ERROR("td error: 0x%08lx\n", status); switch (status) { case OHCI_TD_CONDITION_CRC_ERROR: case OHCI_TD_CONDITION_BIT_STUFFING: case OHCI_TD_CONDITION_TOGGLE_MISMATCH: callbackStatus = B_DEV_CRC_ERROR; break; case OHCI_TD_CONDITION_STALL: callbackStatus = B_DEV_STALLED; break; case OHCI_TD_CONDITION_NO_RESPONSE: callbackStatus = B_TIMED_OUT; break; case OHCI_TD_CONDITION_PID_CHECK_FAILURE: callbackStatus = B_DEV_BAD_PID; break; case OHCI_TD_CONDITION_UNEXPECTED_PID: callbackStatus = B_DEV_UNEXPECTED_PID; break; case OHCI_TD_CONDITION_DATA_OVERRUN: callbackStatus = B_DEV_DATA_OVERRUN; break; case OHCI_TD_CONDITION_DATA_UNDERRUN: callbackStatus = B_DEV_DATA_UNDERRUN; break; case OHCI_TD_CONDITION_BUFFER_OVERRUN: callbackStatus = B_DEV_FIFO_OVERRUN; break; case OHCI_TD_CONDITION_BUFFER_UNDERRUN: callbackStatus = B_DEV_FIFO_UNDERRUN; break; default: callbackStatus = B_ERROR; break; } transferDone = true; break; } else { // an error occured but the endpoint is not halted so // the td is in fact still active TRACE("td %p active with error\n", descriptor); break; } } // the td has completed without an error TRACE("td %p done\n", descriptor); if (descriptor == transfer->last_descriptor || descriptor->buffer_physical != 0) { // this is the last td of the transfer or a short packet callbackStatus = B_OK; transferDone = true; break; } descriptor = (ohci_general_td *)descriptor->next_logical_descriptor; } if (transfer->canceled) { // when a transfer is canceled, all transfers to that endpoint // are canceled by setting the head pointer to the tail pointer // which causes all of the tds to become "free" (as they are // inaccessible and not accessed anymore (as setting the head // pointer required disabling the endpoint)) callbackStatus = B_OK; transferDone = true; } if (!transferDone) { lastTransfer = transfer; transfer = transfer->link; continue; } // remove the transfer from the list first so we are sure // it doesn't get canceled while we still process it transfer_data *next = transfer->link; if (Lock()) { if (lastTransfer) lastTransfer->link = transfer->link; if (transfer == fFirstTransfer) fFirstTransfer = transfer->link; if (transfer == fLastTransfer) fLastTransfer = lastTransfer; // store the currently processing pipe here so we can wait // in cancel if we are processing something on the target pipe if (!transfer->canceled) fProcessingPipe = transfer->transfer->TransferPipe(); transfer->link = NULL; Unlock(); } // break the descriptor chain on the last descriptor transfer->last_descriptor->next_logical_descriptor = NULL; TRACE("transfer %p done with status 0x%08lx\n", transfer, callbackStatus); // if canceled the callback has already been called if (!transfer->canceled) { size_t actualLength = 0; if (callbackStatus == B_OK) { if (transfer->data_descriptor && transfer->incoming) { // data to read out iovec *vector = transfer->transfer->Vector(); size_t vectorCount = transfer->transfer->VectorCount(); transfer->transfer->PrepareKernelAccess(); actualLength = _ReadDescriptorChain( transfer->data_descriptor, vector, vectorCount); } else if (transfer->data_descriptor) { // read the actual length that was sent actualLength = _ReadActualLength( transfer->data_descriptor); } // get the last data toggle and store it for next time transfer->transfer->TransferPipe()->SetDataToggle( (endpoint->head_physical_descriptor & OHCI_ENDPOINT_TOGGLE_CARRY) != 0); if (transfer->transfer->IsFragmented()) { // this transfer may still have data left TRACE("advancing fragmented transfer\n"); transfer->transfer->AdvanceByFragment(actualLength); if (transfer->transfer->VectorLength() > 0) { TRACE("still %ld bytes left on transfer\n", transfer->transfer->VectorLength()); // TODO actually resubmit the transfer } // the transfer is done, but we already set the // actualLength with AdvanceByFragment() actualLength = 0; } } transfer->transfer->Finished(callbackStatus, actualLength); fProcessingPipe = NULL; } if (callbackStatus != B_OK) { // remove the transfer and make the head pointer valid again // (including clearing the halt state) _RemoveTransferFromEndpoint(transfer); } // free the descriptors _FreeDescriptorChain(transfer->first_descriptor); delete transfer->transfer; delete transfer; transfer = next; } } }
~MessengerAutoLocker() { Unlock(); }
STDMETHODIMP CGfxTitanII::CreateSurfaces() { HRESULT hr; int i; DWORD height,width,buffers,hpad,wpad; if(m_dwWidth==0 || m_dwHeight==0 /*|| m_hwnd==0*/) return E_FAIL; if(m_pVr && m_dwWidth==m_dwOldWidth && m_dwHeight==m_dwOldHeight && m_hwnd==m_Oldhwnd) return S_OK; if(m_bBSMMode == TRUE) { m_BSM_Init(m_pVr); } m_dwOldWidth = m_dwWidth; m_dwOldHeight = m_dwHeight; m_Oldhwnd = m_hwnd; //VR_LAYER_OVERLAY:VR_LAYER_PRIMARY #if defined(SIRF_NOTEBOOK ) || defined(RTK_TITAN_II) hr = m_CVR_SetRenderLayer(m_pVr, VR_LAYER_PRIMARY,0.0f); #else hr = m_CVR_SetRenderLayer(m_pVr, VR_LAYER_OVERLAY,0.0f); #endif //[optional] it will change settings in renderer. //TITAN_BITMAP_ORDER: this is the set the bitmap data order //inputted. //pInBuf: the pointer of input data block //data_size: the size of input data block //pOutBuf: the pointer of output data block. //CVR_EscapeCtrl(m_pVr, TITAN_BITMAP_ORDER, pInBuf, data_size, pOutBuf); //[optional] it will set the display mode //mode: the display mode to be set hr = m_CVR_SetDisplayMode(m_pVr, m_dispmode); //if(m_dwHeight<480) // m_sy = 2; // double the height! //else m_sy = 1; //if(m_bUseDSP) //{ // DSP renderer // alignx = 16; // 16 is required (spec doesn't specify) // aligny = 4; // hr = CVR_EscapeCtrl(m_pVr,TITAN_DSP_RENDERER,0,0,0); // if(hr!=VR_OK) // { // // do something here. // } //} //else { // alignx = 2; /* actually 2, but we prefer this for our averaging ops */ // aligny = 2; } buffers = m_dwMaxBuffers+1; wpad = ~(m_dwWidth-1) & (ALIGNX-1); width = m_dwWidth+wpad; height = m_dwHeight*m_sy; hpad = ~(height-1) & (ALIGNY-1); height = height+hpad; //width = width + (width&0xf); //height = height + (height&0xf); //SetDisplayMode(1); m_iYPitch = width; m_iUVPitch = m_iYPitch>>1; //hr = CVR_SetVideoFormat(m_pVr, 0, width, height, 0, &m_iYPitch, &m_iUVPitch); //Set the Video parameters. //VR_FORMAT_I420: set the input data format as I420 //width: width of source frame //height: height of source frame //rect: the source rect //LumPitch: pitch of lum //ChromPitch: pitch of chrom width = ROOF(m_dwWidth, ALIGNX); if(m_bBSMMode == TRUE) height = ROOF(m_dwHeight, ALIGNY); else height = m_dwHeight; VR_SRCRECT rect; rect.left= 0; rect.right = m_dwWidth; rect.top = 0; rect.bottom= m_dwHeight; hr = m_CVR_SetVideoFormat(m_pVr, VR_FORMAT_I420, width, height, &rect, &m_iYPitch, &m_iUVPitch); SetDeinterlaceMode(m_deinterlace_mode); if(!m_bBSMMode) { m_pBackBuffer = new LPVR_FRAME_SURFACE[buffers]; ZeroMemory(m_pBackBuffer,sizeof(m_pBackBuffer[0])*buffers); for(i=0;i<(signed)buffers;i++) { hr = m_CVR_CreateSurface(m_pVr,&m_pBackBuffer[i],1); if(hr!=VR_OK) break; } if(i==0) { delete[] m_pBackBuffer; m_pBackBuffer = 0; //CVR_DeleteVideoRender(m_pVr); //m_pVr = 0; return E_FAIL; } if(i>1) { // make sure we have at least one surface available for background scratch, otherwise hang. m_CVR_DestroySurface(m_pVr,m_pBackBuffer[--i]); ZeroMemory(&m_pBackBuffer[i],sizeof(m_pBackBuffer[i])); } m_dwBackBuffers = i; // clear out buffers unsigned char *pb; LONG lstride; int xl,xr,yt,yb,ht; yt = hpad>>1&~1; yb = hpad - yt; xl = 0; // (wpad>>1)&~3; xr = wpad -xl; ht = m_dwHeight*m_sy; for(i=0;i<(signed)m_dwBackBuffers;i++) { if(SUCCEEDED(Lock(i, (LPVOID *)&pb, &lstride, 0))) { clearoutsiderect(pb,m_dwWidth,ht,lstride,0,xl,xr,yt,yb); clearoutsiderect(pb+height*width,m_dwWidth>>1,ht>>1,lstride>>1,128,xl>>1,xr>>1,yt>>1,yb>>1); clearoutsiderect(pb+height*width+(height*width>>2),m_dwWidth>>1,ht>>1,lstride>>1,128,xl>>1,xr>>1,yt>>1,yb>>1); Unlock(i); } }
void CDVDPerformanceCounter::DeInitialize() { Lock(); Unlock(); }
bool NzRenderTexture::AttachBuffer(nzAttachmentPoint attachmentPoint, nzUInt8 index, nzPixelFormat format) { #if NAZARA_RENDERER_SAFE if (!m_impl) { NazaraError("Render texture not created"); return false; } if (attachmentPoint != nzAttachmentPoint_Color && index > 0) { NazaraError("Index must be 0 for non-color attachments"); return false; } unsigned int depthStencilIndex = attachmentIndex[nzAttachmentPoint_DepthStencil]; if (attachmentPoint == nzAttachmentPoint_Stencil && m_impl->attachements.size() > depthStencilIndex && m_impl->attachements[depthStencilIndex].isUsed) { NazaraError("Stencil target already attached by DepthStencil attachment"); return false; } if (formatTypeToAttachment[NzPixelFormat::GetType(format)] != attachmentPoint) { NazaraError("Pixel format type does not match attachment point type"); return false; } #endif NzOpenGL::Format openglFormat; if (!NzOpenGL::TranslateFormat(format, &openglFormat, NzOpenGL::FormatType_RenderBuffer)) { NazaraError("Failed to translate pixel format into OpenGL format"); return false; } if (!Lock()) { NazaraError("Failed to lock render texture"); return false; } // Détachement de l'attache précédente (Si il y a) Detach(attachmentPoint, index); GLuint renderBuffer = 0; glGenRenderbuffers(1, &renderBuffer); if (!renderBuffer) { NazaraError("Failed to create renderbuffer"); return false; } GLint previous; glGetIntegerv(GL_RENDERBUFFER_BINDING, &previous); glBindRenderbuffer(GL_RENDERBUFFER, renderBuffer); glRenderbufferStorage(GL_RENDERBUFFER, openglFormat.internalFormat, m_impl->width, m_impl->height); if (previous != 0) glBindRenderbuffer(GL_RENDERBUFFER, previous); glFramebufferRenderbuffer(GL_DRAW_FRAMEBUFFER, NzOpenGL::Attachment[attachmentPoint]+index, GL_RENDERBUFFER, renderBuffer); Unlock(); unsigned int minSize = attachmentIndex[attachmentPoint]+index+1; if (m_impl->attachements.size() < minSize) m_impl->attachements.resize(minSize); Attachment& attachment = m_impl->attachements[minSize-1]; attachment.isBuffer = true; attachment.isUsed = true; attachment.buffer = renderBuffer; m_impl->checked = false; m_impl->drawBuffersUpdated = false; return true; }
// Add a local-bridge void AddLocalBridge(CEDAR *c, char *hubname, char *devicename, bool local, bool monitor, bool tapmode, char *tapaddr, bool limit_broadcast) { UINT i; HUB *h = NULL; LOCALBRIDGE *br = NULL; // Validate arguments if (c == NULL || hubname == NULL || devicename == NULL) { return; } if (OS_IS_UNIX(GetOsInfo()->OsType) == false) { tapmode = false; } LockList(c->HubList); { LockList(c->LocalBridgeList); { bool exists = false; // Ensure that the same configuration local-bridge doesn't exist already for (i = 0;i < LIST_NUM(c->LocalBridgeList);i++) { LOCALBRIDGE *br = LIST_DATA(c->LocalBridgeList, i); if (StrCmpi(br->DeviceName, devicename) == 0) { if (StrCmpi(br->HubName, hubname) == 0) { if (br->TapMode == tapmode) { exists = true; } } } } if (exists == false) { // Add configuration br = ZeroMalloc(sizeof(LOCALBRIDGE)); StrCpy(br->HubName, sizeof(br->HubName), hubname); StrCpy(br->DeviceName, sizeof(br->DeviceName), devicename); br->Bridge = NULL; br->Local = local; br->TapMode = tapmode; br->LimitBroadcast = limit_broadcast; br->Monitor = monitor; if (br->TapMode) { if (tapaddr != NULL && IsZero(tapaddr, 6) == false) { Copy(br->TapMacAddress, tapaddr, 6); } else { GenMacAddress(br->TapMacAddress); } } Add(c->LocalBridgeList, br); // Find the hub for (i = 0;i < LIST_NUM(c->HubList);i++) { HUB *hub = LIST_DATA(c->HubList, i); if (StrCmpi(hub->Name, br->HubName) == 0) { h = hub; AddRef(h->ref); break; } } } } UnlockList(c->LocalBridgeList); } UnlockList(c->HubList); // Start the local-bridge immediately if (h != NULL && br != NULL && h->Type != HUB_TYPE_FARM_DYNAMIC) { Lock(h->lock_online); { if (h->Offline == false) { LockList(c->LocalBridgeList); { if (IsInList(c->LocalBridgeList, br)) { if (br->Bridge == NULL) { br->Bridge = BrNewBridge(h, br->DeviceName, NULL, br->Local, br->Monitor, br->TapMode, br->TapMacAddress, br->LimitBroadcast, br); } } } UnlockList(c->LocalBridgeList); } } Unlock(h->lock_online); } ReleaseHub(h); }
bool NzRenderTexture::AttachTexture(nzAttachmentPoint attachmentPoint, nzUInt8 index, NzTexture* texture, unsigned int z) { #if NAZARA_RENDERER_SAFE if (!m_impl) { NazaraError("Render texture not created"); return false; } if (attachmentPoint != nzAttachmentPoint_Color && index > 0) { NazaraError("Index must be 0 for non-color attachments"); return false; } if (attachmentPoint == nzAttachmentPoint_Stencil) { NazaraError("Targeting stencil-only textures is not supported"); return false; } unsigned int depthStencilIndex = attachmentIndex[nzAttachmentPoint_DepthStencil]; if (attachmentPoint == nzAttachmentPoint_Stencil && m_impl->attachements.size() > depthStencilIndex && m_impl->attachements[depthStencilIndex].isUsed) { NazaraError("Stencil target already attached by DepthStencil attachment"); return false; } if (!texture || !texture->IsValid()) { NazaraError("Invalid texture"); return false; } if (texture->GetWidth() < m_impl->width || texture->GetHeight() < m_impl->height) { NazaraError("Texture cannot be smaller than render texture"); return false; } unsigned int depth = (texture->GetType() == nzImageType_Cubemap) ? 6 : texture->GetDepth(); if (z >= depth) { NazaraError("Z value exceeds depth (" + NzString::Number(z) + " >= (" + NzString::Number(depth) + ')'); return false; } if (texture->GetRenderTexture() != nullptr) { NazaraError("Texture already used by another render texture"); return false; } if (formatTypeToAttachment[NzPixelFormat::GetType(texture->GetFormat())] != attachmentPoint) { NazaraError("Pixel format type does not match attachment point type"); return false; } #endif if (!Lock()) { NazaraError("Failed to lock render texture"); return false; } // Détachement de l'attache précédente (Si il y a) Detach(attachmentPoint, index); switch (texture->GetType()) { case nzImageType_1D: glFramebufferTexture1D(GL_DRAW_FRAMEBUFFER, NzOpenGL::Attachment[attachmentPoint]+index, GL_TEXTURE_1D, texture->GetOpenGLID(), 0); break; case nzImageType_1D_Array: case nzImageType_2D_Array: glFramebufferTextureLayer(GL_DRAW_FRAMEBUFFER, NzOpenGL::Attachment[attachmentPoint]+index, texture->GetOpenGLID(), 0, z); break; case nzImageType_2D: glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, NzOpenGL::Attachment[attachmentPoint]+index, NzOpenGL::TextureTarget[texture->GetType()], texture->GetOpenGLID(), 0); break; case nzImageType_3D: glFramebufferTexture3D(GL_DRAW_FRAMEBUFFER, NzOpenGL::Attachment[attachmentPoint]+index, GL_TEXTURE_3D, texture->GetOpenGLID(), 0, z); break; case nzImageType_Cubemap: glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, NzOpenGL::Attachment[attachmentPoint]+index, NzOpenGL::CubemapFace[z], texture->GetOpenGLID(), 0); break; } Unlock(); unsigned int minSize = attachmentIndex[attachmentPoint]+index+1; if (m_impl->attachements.size() < minSize) m_impl->attachements.resize(minSize); Attachment& attachment = m_impl->attachements[minSize-1]; attachment.isBuffer = false; attachment.isUsed = true; attachment.texture = texture; texture->AddResourceListener(this); texture->SetRenderTexture(this); m_impl->checked = false; m_impl->drawBuffersUpdated = false; return true; }
bool NzRenderTexture::IsComplete() const { #if NAZARA_RENDERER_SAFE if (!m_impl) { NazaraError("Render texture not created"); return false; } #endif if (!m_impl->checked) { if (!Lock()) { NazaraError("Failed to lock render texture"); return false; } GLenum status = glCheckFramebufferStatus(GL_DRAW_FRAMEBUFFER); Unlock(); m_impl->complete = false; switch (status) { case GL_FRAMEBUFFER_COMPLETE: m_impl->complete = true; break; case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT: NazaraError("Incomplete attachment"); break; case GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER: NazaraInternalError("Incomplete draw buffer"); break; case GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER: NazaraInternalError("Incomplete read buffer"); break; case GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT: NazaraError("Incomplete missing attachment"); break; case GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE: NazaraError("Incomplete multisample"); break; case GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS: NazaraError("Incomplete layer targets"); break; case GL_FRAMEBUFFER_UNSUPPORTED: NazaraError("Render texture has unsupported attachments"); break; default: NazaraInternalError("Unknown error"); } m_impl->checked = true; } return m_impl->complete; }
ShellDelete::ShellDelete(Panel *SrcPanel,bool Wipe): ReadOnlyDeleteMode(-1), m_SkipMode(-1), SkipWipeMode(-1), SkipFoldersMode(-1), ProcessedItems(0) { SCOPED_ACTION(ChangePriority)(Global->Opt->DelThreadPriority); SCOPED_ACTION(TPreRedrawFuncGuard)(std::make_unique<DelPreRedrawItem>()); os::FAR_FIND_DATA FindData; string strDeleteFilesMsg; string strSelName; string strSelShortName; string strDizName; DWORD FileAttr; size_t SelCount; int UpdateDiz; int DizPresent; int Ret; BOOL NeedUpdate=TRUE, NeedSetUpADir=FALSE; bool Opt_DeleteToRecycleBin=Global->Opt->DeleteToRecycleBin; /*& 31.05.2001 OT Запретить перерисовку текущего окна*/ auto WindowFromLaunched = Global->WindowManager->GetCurrentWindow(); WindowFromLaunched->Lock(); bool DeleteAllFolders=!Global->Opt->Confirm.DeleteFolder; UpdateDiz=(Global->Opt->Diz.UpdateMode==DIZ_UPDATE_ALWAYS || (SrcPanel->IsDizDisplayed() && Global->Opt->Diz.UpdateMode==DIZ_UPDATE_IF_DISPLAYED)); SCOPE_EXIT { Global->Opt->DeleteToRecycleBin=Opt_DeleteToRecycleBin; // Разрешить перерисовку окна WindowFromLaunched->Unlock(); if (NeedUpdate) { ShellUpdatePanels(SrcPanel,NeedSetUpADir); } }; if (!(SelCount=SrcPanel->GetSelCount())) return; // Удаление в корзину только для FIXED-дисков { string strRoot; SrcPanel->GetSelName(nullptr,FileAttr); SrcPanel->GetSelName(&strSelName,FileAttr); ConvertNameToFull(strSelName, strRoot); GetPathRoot(strRoot,strRoot); if (Global->Opt->DeleteToRecycleBin && FAR_GetDriveType(strRoot) != DRIVE_FIXED) Global->Opt->DeleteToRecycleBin=0; } if (SelCount==1) { SrcPanel->GetSelName(nullptr,FileAttr); SrcPanel->GetSelName(&strSelName,FileAttr); if (TestParentFolderName(strSelName) || strSelName.empty()) { NeedUpdate=FALSE; return; } strDeleteFilesMsg = strSelName; QuoteLeadingSpace(strDeleteFilesMsg); } else { // в зависимости от числа ставим нужное окончание const wchar_t *Ends; FormatString StrItems; StrItems << SelCount; Ends=MSG(MAskDeleteItemsA); size_t LenItems = StrItems.size(); if (LenItems > 0) { if ((LenItems >= 2 && StrItems[LenItems-2] == L'1') || StrItems[LenItems-1] >= L'5' || StrItems[LenItems-1] == L'0') Ends=MSG(MAskDeleteItemsS); else if (StrItems[LenItems-1] == L'1') Ends=MSG(MAskDeleteItems0); } strDeleteFilesMsg = LangString(MAskDeleteItems) << SelCount << Ends; } Ret=1; // Обработка "удаления" линков if ((FileAttr & FILE_ATTRIBUTE_REPARSE_POINT) && SelCount==1) { string strJuncName; ConvertNameToFull(strSelName,strJuncName); if (GetReparsePointInfo(strJuncName, strJuncName)) // ? SelName ? { NormalizeSymlinkName(strJuncName); string strAskDeleteLink=MSG(MAskDeleteLink); os::fs::file_status Status(strJuncName); if (os::fs::exists(Status)) { strAskDeleteLink+=L" "; strAskDeleteLink += MSG(is_directory(Status)? MAskDeleteLinkFolder : MAskDeleteLinkFile); } Ret=Message(0,2,MSG(MDeleteLinkTitle), strDeleteFilesMsg.data(), strAskDeleteLink.data(), strJuncName.data(), MSG(MDeleteLinkDelete), MSG(MCancel)); if (Ret) return; } } if (Ret && Global->Opt->Confirm.Delete) { LNGID mTitle = Wipe ? MDeleteWipeTitle : MDeleteTitle; LNGID mDText; string tText; LNGID mDBttn = Wipe ? MDeleteWipe : Global->Opt->DeleteToRecycleBin ? MDeleteRecycle : MDelete; bool bHilite = Global->Opt->DelOpt.HighlightSelected; int mshow = std::min(std::max((int)Global->Opt->DelOpt.ShowSelected, 1), ScrY/2); std::vector<string> items; items.push_back(strDeleteFilesMsg); if (SelCount == 1) { bool folder = (FileAttr & FILE_ATTRIBUTE_DIRECTORY) != 0; if (Wipe && !(FileAttr & FILE_ATTRIBUTE_REPARSE_POINT)) mDText = folder ? MAskWipeFolder : MAskWipeFile; else { if (Global->Opt->DeleteToRecycleBin) mDText = folder ? MAskDeleteRecycleFolder : MAskDeleteRecycleFile; else mDText = folder ? MAskDeleteFolder : MAskDeleteFile; } if (bHilite) { string name, sname; SrcPanel->GetCurName(name, sname); QuoteLeadingSpace(name); bHilite = strDeleteFilesMsg != name; } } else { if (Wipe) { mDText = MAskWipe; mTitle = MDeleteWipeTitle; } else mDText = Global->Opt->DeleteToRecycleBin ? MAskDeleteRecycle : MAskDelete; if (mshow > 1) { tText = MSG(mDText) + string(L" ") + strDeleteFilesMsg; items.clear(); DWORD attr; string name; SrcPanel->GetSelName(nullptr, attr); for (size_t i = 0; i < SelCount; ++i) { if (i == (size_t)mshow-1 && i+1 < SelCount) { items.push_back(L"..."); break; } SrcPanel->GetSelName(&name, attr); QuoteLeadingSpace(name); items.push_back(name); } } } intptr_t start_hilite = 0, end_hilite = 0; DialogBuilder Builder(mTitle, nullptr, [&](Dialog* Dlg, intptr_t Msg, intptr_t Param1, void* Param2) -> intptr_t { if (bHilite && Msg == DN_CTLCOLORDLGITEM && Param1 >= start_hilite && Param1 <= end_hilite) { auto Colors = static_cast<FarDialogItemColors*>(Param2); Colors->Colors[0] = Colors->Colors[1]; } return Dlg->DefProc(Msg, Param1, Param2); }); if (tText.empty()) tText = MSG(mDText); Builder.AddText(tText.data())->Flags = DIF_CENTERTEXT; if (bHilite || (mshow > 1 && SelCount > 1)) Builder.AddSeparator(); std::for_each(RANGE(items, i) { TruncStrFromCenter(i, ScrX+1-6*2); auto dx = Builder.AddText(i.data()); dx->Flags = (SelCount <= 1 || mshow <= 1 ? DIF_CENTERTEXT : 0) | DIF_SHOWAMPERSAND; size_t index = Builder.GetLastID(); end_hilite = index; if (!start_hilite) start_hilite = index; });
PThreadMutex::Locker::~Locker() { Unlock(); }
double CGPSController::GetLongitude() { Lock(); double ret = m_longitude; Unlock(); return ret; }
void LogUnixServer::Log(const LogType Type, const std::string &str) { char *msg = NULL; time_t current = time(NULL); struct tm timeinfo; char buf[128]; localtime_r(¤t, &timeinfo); strftime(buf, sizeof(buf), "%F %T", &timeinfo); if (asprintf(&msg, "%s - %s [PID: %d] - %s\n", buf, LogTypeToStr(Type).c_str(), getpid(), str.c_str()) < 0) { std::stringstream ss; ss << "asprintf failed error:" << strerror(errno); throw(LogException(ss.str())); } else { std::list<int> broken; int len = strlen(msg); Lock(); for(auto fd : m_list) { ssize_t offset = 0; ssize_t ret = 0; do { ret = write(fd, msg + offset, len - offset); if (ret < 0) { switch(errno) { case EINTR: ret = 0; //Fudge this as if we didn't write anything break; default: break; } } else { offset += len; } } while(offset < len); if (ret < len || ret == 0) { broken.push_back(fd); } } //Kick any broken clients for(auto fd : broken) { if (close(fd) < 0) { abort(); } m_list.remove(fd); } Unlock(); } free(msg); }
HRESULT CPyCOMTest::Fire(long nID) { Lock(); HRESULT hr = S_OK; IUnknown** pp = m_vec.begin(); while (pp < m_vec.end() && hr == S_OK) { if (*pp != NULL) { CComQIPtr<IDispatch> pEvent = *pp; DISPID dispid; OLECHAR *names[] = { L"OnFire" }; hr = pEvent->GetIDsOfNames(IID_NULL, names, 1, 0, &dispid); if (SUCCEEDED(hr)) { CComVariant v(nID); DISPPARAMS params = { &v, NULL, 1, 0 }; hr = pEvent->Invoke(dispid, IID_NULL, 0, DISPATCH_METHOD, ¶ms, NULL, NULL, NULL); } if (FAILED(hr)) break; // call FireWithNamedParams a variety of ways. // See http://msdn2.microsoft.com/en-us/library/ms221653.aspx // "Passing Parameters (Component Automation)" for details. OLECHAR *names2[] = { L"OnFireWithNamedParams" }; hr = pEvent->GetIDsOfNames(IID_NULL, names2, 1, 0, &dispid); if (SUCCEEDED(hr)) { // First call without named params - order is reversed // (ie, last in array is first presented to Python.) LONG out_result1 = nID+1; LONG out_result2 = nID+2; CComVariant v[4]; // the "out2" outVal; V_VT(&v[0]) = VT_I4 | VT_BYREF; v[0].plVal = &out_result2; // the "out1" outVal; V_VT(&v[1]) = VT_I4 | VT_BYREF; v[1].plVal = &out_result1; // the bool v[2] = VARIANT_TRUE; // the bool V_VT(&v[2]) = VT_BOOL; // the first param. v[3] = nID; DISPPARAMS params = { v, NULL, 4, 0 }; hr = pEvent->Invoke(dispid, IID_NULL, 0, DISPATCH_METHOD, ¶ms, NULL, NULL, NULL); // all known impls return these values in the out pointer. _ASSERTE(out_result1==nID+3); _ASSERTE(out_result2==nID+4); } // Now with various combinations of named args. Like Python, this // assumes that param DISPIDs start with zero, are sequential and // in the same order as the IDL signature. if (SUCCEEDED(hr)) { // Call again - this time with named params. LONG out_result1 = nID+1; LONG out_result2 = nID+2; CComVariant v[4]; // the "out2" outVal; V_VT(&v[3]) = VT_I4 | VT_BYREF; v[3].plVal = &out_result2; // the "out1" outVal; V_VT(&v[2]) = VT_I4 | VT_BYREF; v[2].plVal = &out_result1; // the bool v[1] = VARIANT_TRUE; // the bool V_VT(&v[1]) = VT_BOOL; // the first param. v[0] = nID; // Build 210 and earlier, this was the only way params *could* be passed, // which happily was the same way MSOffice did it. DISPID namedIDs[4] = {0, 1, 2, 3}; DISPPARAMS params = { v, namedIDs, 4, 4 }; hr = pEvent->Invoke(dispid, IID_NULL, 0, DISPATCH_METHOD, ¶ms, NULL, NULL, NULL); // all known impls return nID+1 in the out pointer. _ASSERTE(out_result1==nID+3); _ASSERTE(out_result2==nID+4); } // Try some other funky combinations to mess with Python :) if (SUCCEEDED(hr)) { // First 2 positional, 2nd 2 by name. LONG out_result1 = nID+1; LONG out_result2 = nID+2; CComVariant v[4]; // the first param. v[3] = nID; // 2nd positional v[2] = VARIANT_TRUE; // the bool V_VT(&v[2]) = VT_BOOL; // named ones up front. // the "out2" outVal (dispid=3) V_VT(&v[1]) = VT_I4 | VT_BYREF; v[1].plVal = &out_result2; // the "out1" outVal (dispid=2) V_VT(&v[0]) = VT_I4 | VT_BYREF; v[0].plVal = &out_result1; DISPID namedIDs[2] = {2, 3}; DISPPARAMS params = { v, namedIDs, 4, 2 }; hr = pEvent->Invoke(dispid, IID_NULL, 0, DISPATCH_METHOD, ¶ms, NULL, NULL, NULL); // all known impls return nID+1 in the out pointer. _ASSERTE(out_result1==nID+3); _ASSERTE(out_result2==nID+4); } if (SUCCEEDED(hr)) { // Only pass the 2 out params - Python must ensure earlier // ones are also passed. LONG out_result1 = nID+1; LONG out_result2 = nID+2; CComVariant v[4]; // the "out2" outVal (dispid=3) V_VT(&v[0]) = VT_I4 | VT_BYREF; v[0].plVal = &out_result2; // the "out1" outVal (dispid=2) V_VT(&v[1]) = VT_I4 | VT_BYREF; v[1].plVal = &out_result1; DISPID namedIDs[2] = {3, 2}; DISPPARAMS params = { v, namedIDs, 2, 2 }; hr = pEvent->Invoke(dispid, IID_NULL, 0, DISPATCH_METHOD, ¶ms, NULL, NULL, NULL); // all known impls return nID+1 in the out pointer. _ASSERTE(out_result1==nID+3); _ASSERTE(out_result2==nID+4); } // IPyCOMTestEvent* pIEvent = (IPyCOMTestEvent*)*pp; // hr = pIEvent->Fire(nID); } pp++; } Unlock(); _ASSERTE(SUCCEEDED(hr)); return hr; }
TInt DPowerManager::PowerDown() { // called by ExecHandler __KTRACE_OPT(KPOWER,Kern::Printf(">PowerManger::PowerDown(0x%x) Enter", iPowerController->iTargetState)); __ASSERT_CRITICAL; Lock(); if (iPowerController->iTargetState == EPwActive) { Unlock(); return KErrNotReady; } __PM_ASSERT(iHandlers); NFastSemaphore shutdownSem(0); NTimer ntimer; TDfc dfc(ShutDownTimeoutFn, &shutdownSem); #ifndef _DEBUG_POWER iPendingShutdownCount = 0; #endif DPowerHandler* ph = iHandlers; //Power down in reverse order of handle registration. do { #ifdef _DEBUG_POWER __PM_ASSERT(!(ph->iStatus & DPowerHandler::EDone)); #endif ph->iSem = &shutdownSem; ph->PowerDown(iPowerController->iTargetState); #ifndef _DEBUG_POWER iPendingShutdownCount++; #else if(iPslShutdownTimeoutMs>0) { // Fire shut down timeout timer ntimer.OneShot(iPslShutdownTimeoutMs, dfc); } NKern::FSWait(&shutdownSem); // power down drivers one after another to simplify debug __e32_atomic_and_ord32(&(ph->iStatus), ~DPowerHandler::EDone); // timeout condition if(iPslShutdownTimeoutMs>0 && ph->iSem) { __e32_atomic_store_ord_ptr(&ph->iSem, 0); } ntimer.Cancel(); #endif ph = ph->iPrev; }while(ph != iHandlers); #ifndef _DEBUG_POWER if(iPslShutdownTimeoutMs>0) { // Fire shut down timeout timer ntimer.OneShot(iPslShutdownTimeoutMs, dfc); } ph = iHandlers; do { NKern::FSWait(&shutdownSem); if(__e32_atomic_load_acq32(&iPendingShutdownCount)==ESHUTDOWN_TIMEOUT) { iPendingShutdownCount = 0; NKern::Lock(); shutdownSem.Reset(); // iPendingShutdownCount could be altered while ShutDownTimeoutFn is running // reset it to make sure shutdownSem is completely clean. NKern::Unlock(); break; } __e32_atomic_add_ord32(&iPendingShutdownCount, (TUint)(~0x0)); // iPendingShutDownCount--; ph = ph->iPrev; }while(ph != iHandlers); ntimer.Cancel(); #endif TTickQ::Wait(); iPowerController->PowerDown(K::SecondQ->WakeupTime()); __PM_ASSERT(iPowerController->iTargetState != EPwOff); iPowerController->iTargetState = EPwActive; K::SecondQ->WakeUp(); TTickQ::Signal(); NFastSemaphore powerupSem(0); ph = iHandlers->iNext; //Power up in same order of handle registration. do { #ifdef _DEBUG_POWER __PM_ASSERT(!(ph->iStatus & DPowerHandler::EDone)); #endif ph->iSem = &powerupSem; ph->PowerUp(); #ifdef _DEBUG_POWER NKern::FSWait(&powerupSem); // power down drivers one after another to simplify debug __PM_ASSERT(!ph->iSem); __PM_ASSERT(ph->iStatus & DPowerHandler::EDone); ph->iStatus &= ~DPowerHandler::EDone; #endif ph = ph->iNext; }while(ph != iHandlers->iNext); #ifndef _DEBUG_POWER ph = iHandlers->iNext; do { NKern::FSWait(&powerupSem); ph = ph->iNext; }while(ph != iHandlers->iNext); #endif // complete wakeup notification request if any NotifyWakeupEvent(KErrNone); Unlock(); __KTRACE_OPT(KPOWER,Kern::Printf("<PowerManger::PowerDown() Leave")); return KErrNone; }
gmCodeTree::~gmCodeTree() { Unlock(); }
ECRESULT ECSessionGroup::AddNotificationTable(ECSESSIONID ulSessionId, unsigned int ulType, unsigned int ulObjType, unsigned int ulTableId, sObjectTableKey* lpsChildRow, sObjectTableKey* lpsPrevRow, struct propValArray *lpRow) { ECRESULT hr = erSuccess; Lock(); struct notification *lpNotify = new struct notification; memset(lpNotify, 0, sizeof(notification)); lpNotify->tab = new notificationTable; memset(lpNotify->tab, 0, sizeof(notificationTable)); lpNotify->ulEventType = fnevTableModified; lpNotify->tab->ulTableEvent = ulType; if(lpsChildRow && (lpsChildRow->ulObjId > 0 || lpsChildRow->ulOrderId > 0)) { lpNotify->tab->propIndex.ulPropTag = PR_INSTANCE_KEY; lpNotify->tab->propIndex.__union = SOAP_UNION_propValData_bin; lpNotify->tab->propIndex.Value.bin = new struct xsd__base64Binary; lpNotify->tab->propIndex.Value.bin->__ptr = new unsigned char[sizeof(ULONG)*2]; lpNotify->tab->propIndex.Value.bin->__size = sizeof(ULONG)*2; memcpy(lpNotify->tab->propIndex.Value.bin->__ptr, &lpsChildRow->ulObjId, sizeof(ULONG)); memcpy(lpNotify->tab->propIndex.Value.bin->__ptr+sizeof(ULONG), &lpsChildRow->ulOrderId, sizeof(ULONG)); }else { lpNotify->tab->propIndex.ulPropTag = PR_NULL; lpNotify->tab->propIndex.__union = SOAP_UNION_propValData_ul; } if(lpsPrevRow && (lpsPrevRow->ulObjId > 0 || lpsPrevRow->ulOrderId > 0)) { lpNotify->tab->propPrior.ulPropTag = PR_INSTANCE_KEY; lpNotify->tab->propPrior.__union = SOAP_UNION_propValData_bin; lpNotify->tab->propPrior.Value.bin = new struct xsd__base64Binary; lpNotify->tab->propPrior.Value.bin->__ptr = new unsigned char[sizeof(ULONG)*2]; lpNotify->tab->propPrior.Value.bin->__size = sizeof(ULONG)*2; memcpy(lpNotify->tab->propPrior.Value.bin->__ptr, &lpsPrevRow->ulObjId, sizeof(ULONG)); memcpy(lpNotify->tab->propPrior.Value.bin->__ptr+sizeof(ULONG), &lpsPrevRow->ulOrderId, sizeof(ULONG)); }else { lpNotify->tab->propPrior.__union = SOAP_UNION_propValData_ul; lpNotify->tab->propPrior.ulPropTag = PR_NULL; } lpNotify->tab->ulObjType = ulObjType; if(lpRow) { lpNotify->tab->pRow = new struct propValArray; lpNotify->tab->pRow->__ptr = lpRow->__ptr; lpNotify->tab->pRow->__size = lpRow->__size; } AddNotification(lpNotify, ulTableId, 0, ulSessionId); //Free by lpRow if(lpNotify->tab->pRow){ lpNotify->tab->pRow->__ptr = NULL; lpNotify->tab->pRow->__size = 0; } //Free struct FreeNotificationStruct(lpNotify); Unlock(); return hr; }
// TCP listener main loop void ListenerTCPMainLoop(LISTENER *r) { SOCK *new_sock; SOCK *s; // Validate arguments if (r == NULL) { return; } Debug("ListenerTCPMainLoop Starts.\n"); r->Status = LISTENER_STATUS_TRYING; while (true) { bool first_failed = true; Debug("Status = LISTENER_STATUS_TRYING\n"); r->Status = LISTENER_STATUS_TRYING; // Try to Listen while (true) { UINT interval; // Stop flag inspection if (r->Halt) { // Stop return; } s = NULL; if (r->Protocol == LISTENER_TCP) { if (r->ShadowIPv6 == false) { s = ListenEx2(r->Port, r->LocalOnly, r->EnableConditionalAccept); } else { s = ListenEx6(r->Port, r->LocalOnly); } } else if (r->Protocol == LISTENER_INPROC) { s = ListenInProc(); } else if (r->Protocol == LISTENER_RUDP) { s = ListenRUDPEx(VPN_RUDP_SVC_NAME, NULL, ListenerRUDPRpcRecvProc, NULL, 0, false, false, r->NatTGlobalUdpPort, r->RandPortId); } else if (r->Protocol == LISTENER_ICMP) { s = ListenRUDP(VPN_RUDP_SVC_NAME, NULL, ListenerRUDPRpcRecvProc, NULL, MAKE_SPECIAL_PORT(IP_PROTO_ICMPV4), true, false); } else if (r->Protocol == LISTENER_DNS) { s = ListenRUDP(VPN_RUDP_SVC_NAME, NULL, ListenerRUDPRpcRecvProc, NULL, 53, true, true); } else if (r->Protocol == LISTENER_REVERSE) { s = ListenReverse(); } if (s != NULL) { // Listen success AddRef(s->ref); Lock(r->lock); { r->Sock = s; } Unlock(r->lock); if (r->ShadowIPv6 == false && r->Protocol == LISTENER_TCP) { SLog(r->Cedar, "LS_LISTENER_START_2", r->Port); } break; } // Listen failure if (first_failed) { first_failed = false; if (r->ShadowIPv6 == false && r->Protocol == LISTENER_TCP) { SLog(r->Cedar, "LS_LISTENER_START_3", r->Port, LISTEN_RETRY_TIME / 1000); } } interval = LISTEN_RETRY_TIME; if (r->ShadowIPv6) { if (IsIPv6Supported() == false) { interval = LISTEN_RETRY_TIME_NOIPV6; Debug("IPv6 is not supported.\n"); } } Wait(r->Event, interval); // Stop flag inspection if (r->Halt) { // Stop Debug("Listener Halt.\n"); return; } } r->Status = LISTENER_STATUS_LISTENING; Debug("Status = LISTENER_STATUS_LISTENING\n"); // Stop flag inspection if (r->Halt) { // Stop goto STOP; } // Accpet loop while (true) { // Accept Debug("Accept()\n"); new_sock = Accept(s); if (new_sock != NULL) { // Accept success Debug("Accepted.\n"); TCPAccepted(r, new_sock); ReleaseSock(new_sock); } else { STOP: Debug("Accept Canceled.\n"); // Failed to accept (socket is destroyed) // Close the listening socket Disconnect(s); ReleaseSock(s); s = NULL; Lock(r->lock); { if (r->Sock != NULL) { s = r->Sock; r->Sock = NULL; } } Unlock(r->lock); if (s != NULL) { ReleaseSock(s); } s = NULL; break; } } // Stop flag inspection if (r->Halt) { // Stop Debug("Listener Halt.\n"); return; } } }
status_t OHCI::CancelQueuedTransfers(Pipe *pipe, bool force) { if (pipe->Type() & USB_OBJECT_ISO_PIPE) return _CancelQueuedIsochronousTransfers(pipe, force); if (!Lock()) return B_ERROR; struct transfer_entry { Transfer * transfer; transfer_entry * next; }; transfer_entry *list = NULL; transfer_data *current = fFirstTransfer; while (current) { if (current->transfer && current->transfer->TransferPipe() == pipe) { // Check if the skip bit is already set if (!(current->endpoint->flags & OHCI_ENDPOINT_SKIP)) { current->endpoint->flags |= OHCI_ENDPOINT_SKIP; // In case the controller is processing // this endpoint, wait for it to finish snooze(1000); } // Clear the endpoint current->endpoint->head_physical_descriptor = current->endpoint->tail_physical_descriptor; if (!force) { // If the transfer is canceled by force, the one causing the // cancel is probably not the one who initiated the transfer // and the callback is likely not safe anymore transfer_entry *entry = (transfer_entry *)malloc(sizeof(transfer_entry)); if (entry != NULL) { entry->transfer = current->transfer; current->transfer = NULL; entry->next = list; list = entry; } } current->canceled = true; } current = current->link; } Unlock(); while (list != NULL) { transfer_entry *next = list->next; list->transfer->Finished(B_CANCELED, 0); delete list->transfer; free(list); list = next; } // wait for any transfers that might have made it before canceling while (fProcessingPipe == pipe) snooze(1000); // notify the finisher so it can clean up the canceled transfers release_sem_etc(fFinishTransfersSem, 1, B_DO_NOT_RESCHEDULE); return B_OK; }
// Shutdown the Listener void StopListener(LISTENER *r) { UINT port; SOCK *s = NULL; // Validate arguments if (r == NULL) { return; } Lock(r->lock); if (r->Halt) { Unlock(r->lock); return; } // Stop flag set r->Halt = true; if (r->Sock != NULL) { s = r->Sock; AddRef(s->ref); } Unlock(r->lock); port = r->Port; if (r->ShadowIPv6 == false && r->Protocol == LISTENER_TCP) { SLog(r->Cedar, "LS_LISTENER_STOP_1", port); } // Close the socket if (s != NULL) { Disconnect(s); ReleaseSock(s); s = NULL; } // Set the event Set(r->Event); // Wait for stopping the thread WaitThread(r->Thread, INFINITE); // Stop the shadow listener if (r->ShadowIPv6 == false) { if (r->ShadowListener != NULL) { StopListener(r->ShadowListener); ReleaseListener(r->ShadowListener); r->ShadowListener = NULL; } } if (r->ShadowIPv6 == false && r->Protocol == LISTENER_TCP) { SLog(r->Cedar, "LS_LISTENER_STOP_2", port); } }
KeymapWindow::KeymapWindow() : BWindow(BRect(80, 50, 880, 380), B_TRANSLATE_SYSTEM_NAME("Keymap"), B_TITLED_WINDOW, B_ASYNCHRONOUS_CONTROLS | B_AUTO_UPDATE_SIZE_LIMITS) { SetLayout(new BGroupLayout(B_VERTICAL)); fKeyboardLayoutView = new KeyboardLayoutView("layout"); fKeyboardLayoutView->SetKeymap(&fCurrentMap); fTextControl = new BTextControl(B_TRANSLATE("Sample and clipboard:"), "", NULL); fSwitchShortcutsButton = new BButton("switch", "", new BMessage(kMsgSwitchShortcuts)); fRevertButton = new BButton("revertButton", B_TRANSLATE("Revert"), new BMessage(kMsgRevertKeymap)); // controls pane AddChild(BGroupLayoutBuilder(B_VERTICAL) .Add(_CreateMenu()) .Add(BGroupLayoutBuilder(B_HORIZONTAL, 10) .Add(_CreateMapLists(), 0.25) .Add(BGroupLayoutBuilder(B_VERTICAL, 10) .Add(fKeyboardLayoutView) //.Add(new BStringView("text label", "Sample and clipboard:")) .Add(BGroupLayoutBuilder(B_HORIZONTAL, 10) .Add(_CreateDeadKeyMenuField(), 0.0) .AddGlue() .Add(fSwitchShortcutsButton)) .Add(fTextControl) .AddGlue(0.0) .Add(BGroupLayoutBuilder(B_HORIZONTAL, 10) .AddGlue(0.0) .Add(fRevertButton))) .SetInsets(10, 10, 10, 10))); fKeyboardLayoutView->SetTarget(fTextControl->TextView()); fTextControl->MakeFocus(); // Make sure the user keymap directory exists BPath path; find_directory(B_USER_SETTINGS_DIRECTORY, &path); path.Append("Keymap"); entry_ref ref; get_ref_for_path(path.Path(), &ref); BDirectory userKeymapsDir(&ref); if (userKeymapsDir.InitCheck() != B_OK) create_directory(path.Path(), S_IRWXU | S_IRWXG | S_IRWXO); BMessenger messenger(this); fOpenPanel = new BFilePanel(B_OPEN_PANEL, &messenger, &ref, B_FILE_NODE, false, NULL); fSavePanel = new BFilePanel(B_SAVE_PANEL, &messenger, &ref, B_FILE_NODE, false, NULL); BRect windowFrame; BString keyboardLayout; _LoadSettings(windowFrame, keyboardLayout); _SetKeyboardLayout(keyboardLayout.String()); ResizeTo(windowFrame.Width(), windowFrame.Height()); MoveTo(windowFrame.LeftTop()); // TODO: this might be a bug in the interface kit, but scrolling to // selection does not correctly work unless the window is shown. Show(); Lock(); // Try and find the current map name in the two list views (if the name // was read at all) _SelectCurrentMap(); KeymapListItem* current = static_cast<KeymapListItem*>(fUserListView->FirstItem()); fCurrentMap.Load(current->EntryRef()); fPreviousMap = fCurrentMap; fAppliedMap = fCurrentMap; fCurrentMap.SetTarget(this, new BMessage(kMsgKeymapUpdated)); _UpdateButtons(); _UpdateDeadKeyMenu(); _UpdateSwitchShortcutButton(); Unlock(); }
BOOLEAN FxEventQueue::QueueToThreadWorker( VOID ) /*++ Routine Description: Generic worker function which encapsulates the logic of whether to enqueue onto a different thread if the thread has not already been queued to. NOTE: this function could have been virtual, or call a virtual worker function once we have determined that we need to queue to a thread. But to save space on vtable storage (why have one unless you really need one?), we rearrange the code so that the derived class calls the worker function and this function indicates in its return value what the caller should do Arguments: None Return Value: TRUE if the caller should queue to a thread to do the work FALSE if the caller shoudl not queue to a thread b/c it has already been queued --*/ { KIRQL irql; BOOLEAN result; Lock(&irql); // // For one reason or another, we couldn't run the state machine on this // thread. So queue a work item to do it. // if (IsEmpty()) { // // There is no work to do. This means that the caller inserted the // event into the queue, dropped the lock, and then another thread came // in and processed the event. // // This check also helps in the rundown case when the queue is closing // and the following happens between 2 thread: // #1 #2 // insert event // drop lock // process event queue // queue goes to empty, so event is set // try to queue work item // result = FALSE; DoTraceLevelMessage( m_PkgPnp->GetDriverGlobals(), TRACE_LEVEL_INFORMATION, TRACINGPNP, "WDFDEVICE 0x%p !devobj 0x%p not queueing work item to process " "event queue", m_PkgPnp->GetDevice()->GetHandle(), m_PkgPnp->GetDevice()->GetDeviceObject()); } else if ((m_QueueFlags & FxEventQueueFlagWorkItemQueued) == 0x00) { m_QueueFlags |= FxEventQueueFlagWorkItemQueued; result = TRUE; } else { // // Somebody is already in the process of enqueuing the work item. // result = FALSE; } Unlock(irql); return result; }
bool ServerSideScripting::EvaluatePage( QTextStream *pOutStream, const QString &sFileName ) { try { bool bFound( false ); ScriptInfo *pInfo = NULL; // ------------------------------------------------------------------ // See if page has already been loaded // ------------------------------------------------------------------ Lock(); if ( (bFound = m_mapScripts.contains( sFileName )) == true ) pInfo = m_mapScripts[ sFileName ]; Unlock(); // ------------------------------------------------------------------ // Load Script File and Create Function // ------------------------------------------------------------------ QFileInfo fileInfo ( sFileName ); QDateTime dtLastModified = fileInfo.lastModified(); if ((pInfo == NULL) || (pInfo->m_dtTimeStamp != dtLastModified )) { QString sCode = CreateMethodFromFile( sFileName ); QScriptValue func = m_engine.evaluate( sCode, sFileName ); if ( m_engine.hasUncaughtException() ) { VERBOSE( VB_IMPORTANT, QString( "Error Loading QSP File: %1 - (%2)%3" ) .arg( sFileName ) .arg( m_engine.uncaughtExceptionLineNumber() ) .arg( m_engine.uncaughtException().toString() )); return false; } if (pInfo != NULL) { pInfo->m_oFunc = func; pInfo->m_dtTimeStamp = dtLastModified; } else { pInfo = new ScriptInfo( func, dtLastModified ); Lock(); m_mapScripts[ sFileName ] = pInfo; Unlock(); } } // ------------------------------------------------------------------ // Execute function to render output // ------------------------------------------------------------------ OutputStream outStream( pOutStream ); QScriptValueList args; args << m_engine.newQObject( &outStream ); pInfo->m_oFunc.call( QScriptValue(), args ); if (m_engine.hasUncaughtException()) { VERBOSE( VB_IMPORTANT, QString( "Error calling QSP File: %1 - %2" ) .arg( sFileName ) .arg( m_engine.uncaughtException().toString() )); return false; } } catch( ... ) { VERBOSE( VB_IMPORTANT, QString( "Exception while evaluating QSP File: %1" ) .arg( sFileName )); return false; } return true; }
VOID FxEventQueue::EventQueueWorker( VOID ) /*++ Routine Description: This is the work item that attempts to run the queue state machine on the special power thread. --*/ { FxPostProcessInfo info; KIRQL irql; FxPkgPnp* pPkgPnp; #if (FX_CORE_MODE==FX_CORE_KERNEL_MODE) FX_TRACK_DRIVER(m_PkgPnp->GetDriverGlobals()); #endif // // Cache away m_PkgPnp while we know we still have a valid object. Once // we Unlock() after the worker routine, the object could be gone until // the worker routine set a flag postponing deletion. // pPkgPnp = m_PkgPnp; Lock(&irql); ASSERT(m_QueueFlags & FxEventQueueFlagWorkItemQueued); // // Clear the queued flag, so that it's clear that the work item can // be safely re-enqueued. // m_QueueFlags &= ~FxEventQueueFlagWorkItemQueued; // // We should only see this count rise to a small number (like 10 or so). // ASSERT(m_WorkItemRunningCount < 0xFF); m_WorkItemRunningCount++; Unlock(irql); // // Call the function that will actually run the state machine. // m_EventWorker(m_PkgPnp, &info, m_EventWorkerContext); Lock(&irql); m_WorkItemRunningCount--; GetFinishedState(&info); Unlock(irql); // // NOTE: There is no need to use a reference count to keep this event queue // (and the containing state machine) alive. Instead, the thread // which wants to delete the state machine must wait for this work // item to exit. If there was a reference to release, we would have // a race between Unlock()ing and releasing the reference if the state // machine moved into the finished state and deletes the device after // we dropped the lock, but before we released the reference. // // This is important in that the device deletion can trigger // DriverUnload to run before the release executes. DriverUnload // frees the IFR buffer. If this potential release logs something to // the IFR, you would bugcheck. Since it is impossible to defensively // prevent all destructors from logging to the IFR, we can't use a // ref count here to keep the queue alive. // // // If Evaluate needs to use pPkgPnp, then the call to the worker routine // above made sure that pPkgPnp has not yet been freed. // info.Evaluate(pPkgPnp); }
MGlobal::operator HGLOBAL() { Unlock(); return mh_Global; }
void MythEventHandler::ImpMythEventHandler::Action(void) { const char* events[]={ "CMYTH_EVENT_UNKNOWN",\ "CMYTH_EVENT_CLOSE",\ "CMYTH_EVENT_RECORDING_LIST_CHANGE",\ "CMYTH_EVENT_RECORDING_LIST_CHANGE_ADD",\ "CMYTH_EVENT_RECORDING_LIST_CHANGE_UPDATE",\ "CMYTH_EVENT_RECORDING_LIST_CHANGE_DELETE",\ "CMYTH_EVENT_SCHEDULE_CHANGE",\ "CMYTH_EVENT_DONE_RECORDING",\ "CMYTH_EVENT_QUIT_LIVETV",\ "CMYTH_EVENT_WATCH_LIVETV",\ "CMYTH_EVENT_LIVETV_CHAIN_UPDATE",\ "CMYTH_EVENT_SIGNAL",\ "CMYTH_EVENT_ASK_RECORDING",\ "CMYTH_EVENT_SYSTEM_EVENT",\ "CMYTH_EVENT_UPDATE_FILE_SIZE",\ "CMYTH_EVENT_GENERATED_PIXMAP",\ "CMYTH_EVENT_CLEAR_SETTINGS_CACHE"}; cmyth_event_t myth_event; char databuf[2049]; databuf[0]=0; timeval timeout; timeout.tv_sec=0; timeout.tv_usec=100000; while(Running()) { if(CMYTH->EventSelect(m_conn_t,&timeout)>0) { myth_event=CMYTH->EventGet(m_conn_t,databuf,2048); XBMC->Log(LOG_DEBUG,"EVENT ID: %s, EVENT databuf: %s",events[myth_event],databuf); if(myth_event==CMYTH_EVENT_LIVETV_CHAIN_UPDATE) { Lock(); if(!m_rec.IsNull()) { bool retval=m_rec.LiveTVChainUpdate(CStdString(databuf)); XBMC->Log(LOG_NOTICE,"%s: CHAIN_UPDATE: %i",__FUNCTION__,retval); } else XBMC->Log(LOG_NOTICE,"%s: CHAIN_UPDATE - No recorder",__FUNCTION__); Unlock(); } if(myth_event==CMYTH_EVENT_SIGNAL) { CStdString signal=databuf; UpdateSignal(signal); } if(myth_event==CMYTH_EVENT_SCHEDULE_CHANGE) { XBMC->Log(LOG_NOTICE,"Schedule change",__FUNCTION__); } databuf[0]=0; } //Restore timeout timeout.tv_sec=0; timeout.tv_usec=100000; } }
int CFileLoaderThread::DoThreadWork() { int i; // Check for shutdown event if ( WAIT_OBJECT_0 == WaitForSingleObject( GetShutdownHandle(), 0 ) ) { return 0; } // No changes to list right now Lock(); // Move new items to work list int newItems = m_FileList.Count(); for ( i = 0; i < newItems; i++ ) { // Move to pending and issue async i/o calls m_Pending.AddToTail( m_FileList[ i ] ); m_nTotalPending++; } m_FileList.RemoveAll(); // Done adding new work items Unlock(); int remaining = m_Pending.Count(); if ( !remaining ) return 1; int workitems = remaining; // min( remaining, 1000 ); CUtlVector< SentenceRequest * > transfer; for ( i = 0; i < workitems; i++ ) { SentenceRequest *r = m_Pending[ 0 ]; m_Pending.Remove( 0 ); transfer.AddToTail( r ); // Do the work m_nTotalProcessed++; r->valid = SceneManager_LoadSentenceFromWavFileUsingIO( r->filename, r->sentence, m_ThreadIO ); } // Now move to completed list Lock(); for ( i = 0; i < workitems; i++ ) { SentenceRequest *r = transfer[ i ]; if ( r->valid ) { m_nTotalCompleted++; m_Completed.AddToTail( r ); } else { delete r; } } Unlock(); return 1; }
void ConditionLock::Unlock(int targetCondition) { Broadcast(targetCondition); Unlock(); }