Example #1
0
void TThread::Executor::Imp::Worker::run() {
  try {
    while (true) {
      // check if thread has been canceled
      Thread::milestone();

      // get the next task
      RunnableP task = 0;

      {
        ScopedLock sl(m_owner->m_mutex);
        if (m_owner->m_tasks.empty()) {
          // la lista di task e' stata esaurita
          if (m_owner->m_suspend) {
            // il thread deve sospendersi
            m_owner->m_taskQueueNotEmpty.wait(sl);

            // a questo punto il thread e' stato risvegliato
            if (m_owner->m_threadHasToDie) {
              doCleanup();
              return;
            }
          } else {
            // il thread sta per morire -> bisogna eliminarlo dalla lista dei
            // worker thread
            doCleanup();
            return;
          }
        }

        if (!m_owner->m_tasks.empty()) {
          task = m_owner->m_tasks.front();
          m_owner->m_tasks.pop();
        }
      }

      if (task) task->run();

      // check if thread has been canceled
      Thread::milestone();
    }
  } catch (TThread::Interrupt &) {
    // m_owner->m_cond.notifyOne();
  } catch (...) {
    // eccezione non prevista --> bisogna eliminare il thread
    // dalla lista dei worker thread

    ScopedLock sl(m_owner->m_mutex);
    doCleanup();
  }
}
Example #2
0
/*!
 *  Unload the plugin registry.  This will unload the DLLs and free
 *  the nodes in the data structure containing them.
 *
 *  \param reg  The registry
 *  \param error An error to populate on failure
 *  \return 1 on success, 0 on failure
 *
 */
NITFPRIV(NITF_BOOL) unloadDSO(nitf_DLL* dll, nitf_Error * error)
{

    NITF_BOOL ok = NITF_SUCCESS;


    if (nitf_DLL_isValid(dll))
    {
	doCleanup(dll, error);

	/* destroy the lib */
        ok &= nitf_DLL_unload(dll, error);
	if ( dll->libname )
	{

#ifdef NITF_DEBUG_PLUGIN_REG
            printf("Unloaded dll with name [%s]\n", dll->libname);
#endif

	    NITF_FREE( dll->libname );
	    dll->libname = NULL;
	}

        nitf_DLL_destruct(&dll);


    }
    return ok;
}
Example #3
0
void Cplm::showdown()
{
  if (0)//DEBUG & DEBUG_PLM_SHOWDOWN)
  {
    printf("Doing SHOWDOWN Function: ");
    
    if ((currentInstr_.operand & iSHOWDOWN_HI) &&
      (currentInstr_.operand & iSHOWDOWN_LO))
    {
      printf("Pot Will Be Split Between Hi and Lo Hands");
    } else if (currentInstr_.operand & iSHOWDOWN_HI) {
      printf("Pot Will Be Awarded To Hi Hand");
    } else if (currentInstr_.operand & iSHOWDOWN_LO) {
      printf("Pot Will Be Awarded To Lo Hand");
    }
    
    if (currentInstr_.operand & iSHOWDOWN_GUTS)
    {
      printf(", This is a Guts Game\n");
    }
    else
    {
      printf("\n");
    }
  }
  
  doShowdown();
  table_->advanceButton();
  doCleanup();
}
Example #4
0
// Destructor
PsButtonTask::~PsButtonTask()
{
   OsWriteLock lock(mMutex);       // acquire a write lock

   doCleanup();
   delete mpKeybdDev;
   spInstance = NULL;
}
void LargeObjectCache::
    cleanupCacheIfNeededOnRange(uintptr_t range, uintptr_t currTime)
{
    if (range >= cacheCleanupFreq
        || currTime+range < currTime-1 // overflow, 0 is power of 2, do cleanup
        // (prev;prev+range] contains n*cacheCleanupFreq
        || alignUp(currTime, cacheCleanupFreq)<=currTime+range)
        doCleanup(currTime, /*doThreshDecr=*/false);
}
Example #6
0
int main(int argc, char *argv[])
/* Process command line. */
{
optionInit(&argc, argv, options);
if (argc != 2)
    usage();
cacheDir = optionVal("cacheDir", udcDefaultDir());
testOnly = optionExists("test");
doCleanup(argv[1]);
return 0;
}
Example #7
0
void SQLTransactionBackend::notifyDatabaseThreadIsShuttingDown()
{
    ASSERT(currentThread() == database()->databaseContext()->databaseThread()->getThreadID());

    // If the transaction is in progress, we should roll it back here, since this
    // is our last opportunity to do something related to this transaction on the
    // DB thread. Amongst other work, doCleanup() will clear m_sqliteTransaction
    // which invokes SQLiteTransaction's destructor, which will do the roll back
    // if necessary.
    doCleanup();
}
Example #8
0
SQLTransactionState SQLTransactionBackend::cleanupAndTerminate()
{
    ASSERT(m_lockAcquired);

    // Spec 4.3.2.9: End transaction steps. There is no next step.
    LOG(StorageAPI, "Transaction %p is complete\n", this);
    ASSERT(!m_database->sqliteDatabase().transactionInProgress());

    // Phase 5 cleanup. See comment on the SQLTransaction life-cycle above.
    doCleanup();
    m_database->inProgressTransactionCompleted();
    return SQLTransactionState::End;
}
Example #9
0
 void Service::main()
 {
   mStatusHandle = RegisterServiceCtrlHandlerW( mName.c_str(),
     _serviceControlHandler );
   if ( !mStatusHandle )
     EXCEPT_WINAPI( L"Couldn't register service control handler" );
   setState( SERVICE_START_PENDING, 0 );
   doInitialize();
   setState( SERVICE_START_PENDING, 1 );
   doStart();
   WaitForSingleObject( mRunEvent, INFINITE );
   setState( SERVICE_RUNNING, 0 );
   WaitForSingleObject( mStopEvent, INFINITE );
   doCleanup();
 }
Example #10
0
// Cause the Button task to (re)initialize itself.
// The task will allocate an array [0..maxButtonIndex] of PsButtonInfo
// objects to hold button state.
OsStatus PsButtonTask::init(const int maxButtonIndex)
{
   int         i;
   OsWriteLock lock(mMutex);      // acquire a write lock

   doCleanup();                   // release old dynamic storage (if any)

   mMaxBtnIdx = maxButtonIndex;
   mpButtonInfo = new PsButtonInfo[maxButtonIndex+1];
   mpRepTimers  = new OsTimer*[maxButtonIndex+1];

   for (i=0; i <= maxButtonIndex; i++)
      mpRepTimers[i] = NULL;

   return OS_SUCCESS;
}
	void UserInputListener::cleanup()
	{
		m_enabled = false;

		doCleanup();

		auto lock = makeUniqueLock( m_mutexHandlers );
		auto it = m_handlers.begin();

		while ( it != m_handlers.end() )
		{
			auto handler = *it;
			doRemoveHandler( handler );
			it = m_handlers.begin();
		}
	}
Example #12
0
void
MemoryContentCache::add(const Data& data)
{
  doCleanup();

  if (data.getMetaInfo().getFreshnessPeriod() >= 0.0) {
    // The content will go stale, so use staleTimeCache_.
    ptr_lib::shared_ptr<const StaleTimeContent> content(new StaleTimeContent(data));
    // Insert into staleTimeCache_, sorted on content->staleTimeMilliseconds_.
    staleTimeCache_.insert
      (std::lower_bound(staleTimeCache_.begin(), staleTimeCache_.end(), content, contentCompare_),
       content);
  }
  else
    // The data does not go stale, so use noStaleTimeCache_.
    noStaleTimeCache_.push_back
      (ptr_lib::make_shared<const Content>(data));

  // Remove timed-out interests and check if the data packet matches any pending
  // interest.
  // Go backwards through the list so we can erase entries.
  MillisecondsSince1970 nowMilliseconds = ndn_getNowMilliseconds();
  for (int i = (int)pendingInterestTable_.size() - 1; i >= 0; --i) {
    if (pendingInterestTable_[i]->isTimedOut(nowMilliseconds)) {
      pendingInterestTable_.erase(pendingInterestTable_.begin() + i);
      continue;
    }

    if (pendingInterestTable_[i]->getInterest()->matchesName(data.getName())) {
      try {
        // Send to the same transport from the original call to onInterest.
        // wireEncode returns the cached encoding if available.
        pendingInterestTable_[i]->getFace().send(*data.wireEncode());
      } catch (std::exception& e) {
        _LOG_DEBUG("Error in send: " << e.what());
        return;
      }

      // The pending interest is satisfied, so remove it.
      pendingInterestTable_.erase(pendingInterestTable_.begin() + i);
    }
  }
}
Example #13
0
/* \internal
   Event handler reimplementation.  Calls doCleanup() when the timer
   fires.
*/
bool QSharedDoubleBufferCleaner::event( QEvent *e )
{
    if ( e->type() != QEvent::Timer )
	return FALSE;

    QTimerEvent *event = (QTimerEvent *) e;
    if ( event->timerId() == timer_id ) {
	doCleanup();
	stop();
    }
#ifdef QT_CHECK_STATE
    else {
	qWarning( "QSharedDoubleBufferCleaner::event: invalid timer event received." );
	return FALSE;
    }
#endif // QT_CHECK_STATE

    return TRUE;
}
Example #14
0
void SQLTransactionBackend::computeNextStateAndCleanupIfNeeded()
{
    // Only honor the requested state transition if we're not supposed to be
    // cleaning up and shutting down:
    if (m_database->opened() && !m_database->isInterrupted()) {
        setStateToRequestedState();
        ASSERT(m_nextState == SQLTransactionState::AcquireLock
            || m_nextState == SQLTransactionState::OpenTransactionAndPreflight
            || m_nextState == SQLTransactionState::RunStatements
            || m_nextState == SQLTransactionState::PostflightAndCommit
            || m_nextState == SQLTransactionState::CleanupAndTerminate
            || m_nextState == SQLTransactionState::CleanupAfterTransactionErrorCallback);

        WTF_LOG(StorageAPI, "State %s\n", nameForSQLTransactionState(m_nextState));
        return;
    }

    // If we get here, then we should be shutting down. Do clean up if needed:
    if (m_nextState == SQLTransactionState::End)
        return;
    m_nextState = SQLTransactionState::End;

    // If the database was stopped, don't do anything and cancel queued work
    WTF_LOG(StorageAPI, "Database was stopped or interrupted - cancelling work for this transaction");

    // The current SQLite transaction should be stopped, as well
    if (m_sqliteTransaction) {
        m_sqliteTransaction->stop();
        m_sqliteTransaction.clear();
    }

    // Terminate the frontend state machine. This also gets the frontend to
    // call computeNextStateAndCleanupIfNeeded() and clear its wrappers
    // if needed.
    m_frontend->requestTransitToState(SQLTransactionState::End);

    // Redirect to the end state to abort, clean up, and end the transaction.
    doCleanup();
}
Example #15
0
int JoltApp::doExecute() {
    
    if(!doInit()) {
        return -1;
    }
    
    SDL_Event evt;
    
    JoltConsole::logInfo("App","Starting game loop.");
    while(running) {
        while(SDL_PollEvent(&evt)) {
            onEvent(&evt);
        }
        
        onLoop();
        onRender();
        //JoltConsole::logInfo("Main","Loop called at %i", SDL_GetTicks());
    }
    
    doCleanup();
    
    return 0;
    
}
Example #16
0
void LargeObjectCache::cleanupCacheIfNeeded(uintptr_t currTime)
{
    if ( 0 == currTime % cacheCleanupFreq )
        doCleanup(currTime, /*doThreshDecr=*/false);
}
// main window procedure
LONG WINAPI MainWndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {
    LONG lRet = 1;
    PAINTSTRUCT ps;
    RECT rect;

    switch (uMsg) {

    case WM_CREATE:
        ghDC = GetDC(hWnd);
        if (!setupPixelFormat(ghDC)) {
            PostQuitMessage(0);
        }

        initializeGL();
        GetClientRect(hWnd, &rect);
        resize(rect.right, rect.bottom); // added in leiu of passing dims to initialize
        g_programs.compilePrograms();

        setupData(rect.right, rect.bottom);

        ::SetTimer(hWnd, DRAW_TIMER_ID, 0, DrawTimerProc);

        break;

    case WM_PAINT:
        BeginPaint(hWnd, &ps);
        EndPaint(hWnd, &ps);
        break;

    case WM_SIZE:
        GetClientRect(hWnd, &rect);
        resize(rect.right, rect.bottom);
        break;

    case WM_CLOSE:
        doCleanup(hWnd);
        DestroyWindow(hWnd);
        break;

    case WM_DESTROY:
        doCleanup(hWnd);
        PostQuitMessage(0);
        break;

    case WM_KEYDOWN:
        switch (wParam) {
        case 'P':
            g_paused = !g_paused;
            break;

        //case 'W':
        //    if (g_shiftPressed) {
        //        g_camera.moveUp(MOVE_AMOUNT);
        //    }
        //    else {
        //        g_camera.moveForward(MOVE_AMOUNT);
        //    }
        //    redoModelViewMatrix();
        //    break;

        //case 'A':
        //    g_camera.moveSide(-MOVE_AMOUNT);
        //    redoModelViewMatrix();
        //    break;

        //case 'S':
        //    if (g_shiftPressed) {
        //        g_camera.moveUp(-MOVE_AMOUNT);
        //    }
        //    else {
        //        g_camera.moveForward(-MOVE_AMOUNT);
        //    }
        //    redoModelViewMatrix();
        //    break;

        //case 'D':
        //    g_camera.moveSide(MOVE_AMOUNT);
        //    redoModelViewMatrix();
        //    break;

        //case 'Q':
        //    g_camera.spinAroundFwd(SPIN_AMOUNT);
        //    redoModelViewMatrix();
        //    break;

        //case 'E':
        //    g_camera.spinAroundFwd(-SPIN_AMOUNT);
        //    redoModelViewMatrix();
        //    break;

        //case VK_UP:
        //    g_camera.spinAroundSide(-SPIN_AMOUNT);
        //    redoModelViewMatrix();
        //    break;

        //case VK_DOWN:
        //    g_camera.spinAroundSide(SPIN_AMOUNT);
        //    redoModelViewMatrix();
        //    break;

        //case VK_LEFT:
        //    //if (g_shiftPressed) {
        //    //    g_camera.spinAroundFwd(SPIN_AMOUNT);
        //    //}
        //    //else {
        //    g_camera.spinAroundUp(SPIN_AMOUNT);
        //    //}
        //    redoModelViewMatrix();
        //    break;

        //case VK_RIGHT:
        //    //if (g_shiftPressed) {
        //    //    g_camera.spinAroundFwd(-SPIN_AMOUNT);
        //    //}
        //    //else {
        //    g_camera.spinAroundUp(-SPIN_AMOUNT);
        //    //}
        //    redoModelViewMatrix();
        //    break;

        case VK_SHIFT:
            g_shiftPressed = true;
            break;
        }
        break;

    case WM_KEYUP:
        switch (wParam) {
        case VK_SHIFT:
            g_shiftPressed = false;
            break;
        }
        break;

    case WM_LBUTTONDOWN:
        g_mouse.l_btn_down = true;
        break;

    case WM_LBUTTONUP:
        g_mouse.l_btn_down = false;
        break;

    case WM_MOUSEMOVE: {
        int x = GET_X_LPARAM(lParam);
        int y = GET_Y_LPARAM(lParam);
        if (g_mouse.l_btn_down) {
            moveCameraByMouseMove(x, y, g_mouse.last_x, g_mouse.last_y);
        }
        g_mouse.last_x = x;
        g_mouse.last_y = y;
        break;
    }

    case WM_MOUSEWHEEL: {
        int delta = GET_WHEEL_DELTA_WPARAM(wParam);
        zoomCameraByMouseWheel(delta);
        break;
    }

    default:
        lRet = DefWindowProc(hWnd, uMsg, wParam, lParam);
        break;
    }

    return lRet;
}
Example #18
0
bool LargeObjectCache::decreasingCleanup()
{
    return doCleanup(FencedLoad((intptr_t&)cacheCurrTime), /*doThreshDecr=*/true);
}
Example #19
0
bool LargeObjectCache::regularCleanup()
{
    return doCleanup(FencedLoad((intptr_t&)cacheCurrTime), /*doThreshDecr=*/false);
}
Example #20
0
//
// Bet mfunctions
//
void Cplm_7Stud::doBettingRound(int cap, const CChips& raise)
{
    bettingRound_++;

    // in 1-on-1 tables, there really is no cap -
    // make it 40!
    if (table_->getMaxPlayers() == 2)
        cap = 40;

    CChips ante = 1, bringin = 2;
    if (table_->getLo() < 10)
    {
        ante = 1;
        bringin = 2;
    }
    else
    {
        ante = 2;
        bringin = 5;
    }


    CPlayer* spotlight = NULL;

    if (isFirstRound_)
    {
        // Automatic bring-in by the player who has the
        // lowest upcard
        spotlight = getPlayerWithLowestUpCard();
        if (!spotlight || spotlight->getChips() < bringin)
        {   
            char s[100];
            sprintf(s, "Not enough players for betting round (1)!\n");
            Sys_LogError(s);
            doCleanup();
            return;
        }

        // Bring-in counts as a raise
        cap--;

        actionRaise(spotlight, bringin, bringin, true);
    }
    else
    {   
        // start by the player who has the highest showing hand
        spotlight = getPlayerWithHighestShowingHand();
    }

    CRingIterator it(table_->getRingNode(spotlight));

    if (isFirstRound_)
    {   // first round, action begins from player
        // next to bring in
        it.next(PLAYER_STATE_PLAYING);
    }
   
    if (!it.restart(PLAYER_STATE_PLAYING))
    {
        char s[100];
        sprintf(s, "Not enough players for betting round (2)!\n");
        Sys_LogError(s);
        doCleanup();
        return;
    }

    do
    {
        CChips toRaise = (cap > 0 ? raise : 0);
        CPlayer* player = it.current()->getPlayer();
        ASSERT(table_->getBet() >= player->getCurrentBet());
        CChips toPay = table_->getBet() - player->getCurrentBet();

        if (player->matchState(PLAYER_STATE_ALLIN_RAISE))
        {   // player raised and went all-in in previous
            // round, only now does he become really inactive
            player->stateChange(PLAYER_STATE_ALLIN);
            continue;
        }

        // Bet completion
        if (!table_->getLivePot()->isComplete())
        {
            if (player == highBetter_)
            {   // high better cannot complete bet and cannot raise again
                toRaise = 0;
            }
            else
            {   // bet not completed, cannot do full bet but must complete this
                toRaise = table_->getLivePot()->getBetComplete();
            }
        }

        CChips promptPay = toPay;
        if (toPay > player->getChips())
        {
            promptPay = player->getChips();
            toRaise = 0;
        }
        
        if (promptPay + toRaise > player->getChips())
        {
            toRaise = player->getChips() - promptPay;
        }

        Plm_Action action = promptAction(player, promptPay, toRaise);

        switch (action)
        {
            case Action_Timeout:
            { 
                // If player logged out in the middle of a hand,
                // he'll fold
                // If player has no chips in pot, he'll fold
                if (player->matchState(PLAYER_STATE_LOGGINGOUT))
                {
                    actionFold(player);
                }
                else 
                {
                    actionTimeout(player, toPay);  // this is the network failure allIn
                }
            }
            break;

            case Action_Fold:
            {
                actionFold(player);
            }
            break;

            case Action_Call:
            {               
                actionCall(player, toPay);
            }
            break;

            case Action_Raise:
            {
                cap--;                
                actionRaise(player, toRaise, raise);

                // When someone raises, the betting will
                // not end until we're back to the same player
                it.restart(it.current());
            }
            break;

            default:
            {
                char buf[128];
                sprintf(buf, "Cplm::doBettingRound: unknown action %d player %s\n",
                        action, player->getUsername());
                Sys_LogError(buf);
            }
            break;
        }

        if (table_->countPlayers(PLAYER_STATE_PLAYING|PLAYER_STATE_ALLIN_RAISE) < 2)
            break;
    }
    while (it.next(PLAYER_STATE_PLAYING|PLAYER_STATE_ALLIN_RAISE));

    // When betting round is finished, turn players in
    // PLAYER_STATE_ALLIN_RAISE state to PLAYER_STATE_ALLIN
    CRingIterator it2(table_->getDealer());
    if (it2.restart(PLAYER_STATE_PLAYING|PLAYER_STATE_ALLIN_RAISE))
    {
        do
        {
            CPlayer* player = it2.current()->getPlayer();
            if (player->matchState(PLAYER_STATE_ALLIN_RAISE))
                player->stateChange(PLAYER_STATE_ALLIN);
        }
        while (it2.next(PLAYER_STATE_PLAYING|PLAYER_STATE_ALLIN_RAISE));
    }

    // When betting round is finished, mark all bets completed
    for (Cpot* p = table_->getMainPot(); p != NULL; p = p->getNext())
    {
        p->complete();
        p->setBetComplete(0);
    }

    isFirstRound_ = false;
}
Example #21
0
void Cplm::mainLoop()
{
    CStrOut message;
    int i = 0;

    // If a player left in the middle of hand, it might
    // happen that the pot still has money - if so, give
    // the chips here to the player

    if (!inGame_ &&
         (table_->countPlayers(PLAYER_STATE_ACTIVE) < 2 ||
          table_->numPlayersSittingIn() < 2 ||
          CTournament::Inst()->pause()))
    {
        doCleanup();
        Sys_Sleep(2000);

        if (!CTournament::Inst()->isTournament())
        {
          // Players are sitting out
          CpduAnnounce pdu(table_);
          pdu.sendAnnounce("Waiting for players to sit in");
          Sys_Sleep(2000);
        }

        return;
    }
    else
    {
        // The game thread function calls this repeatedly.
        // It only gets this far when there's enough players for a game.
        // First off, get the game number, and setLog all of the current players.

        memcpy((void*)&currentInstr_, pgl_->fetchInstr(), sizeof(pgl_instr_t));

        switch (currentInstr_.opcode)
        {
        case (Instr_NOP):
          break;

        case (Instr_Deal):
          deal();
          break;  // Deal Cards To All Active Players

        case (Instr_Ante):                      // Do ANTE
        {
            table_->setGameNumber();
            CpduGameNumber::SendGameNumber(table_);
            for (i = 0; i < 10; i++)
            {
                CPlayer* player = table_->getPlayerFromSlot(i);
                if (player)
                {
                  message << CStrOut::Clear
                          << "Seat " << i << ": "
                          << player->getUsername() 
                          << " (" << player->getChips() 
                          << " in chips)";
                  table_->setLog(message.str());
                }
            }

            ante();
        }
        break;

        case (Instr_Draw):
          draw();
          break;       // Allow Players to Draw Cards

        case (Instr_Bet):
          bet();
          break;       // Do a betting Round

        case (Instr_Showdown):
          showdown();
          break;       // Do Showdown/Announce

        default:
          printf("Unknown operation %d!\n", (int)currentInstr_.opcode);
          break;
        }
    }
}
Example #22
0
void HsQMLCanvasBackEnd::doCleanupKill()
{
    doCleanup();
    delete this;
}
bool DIALOG_CLEANUP_TRACKS_AND_VIAS::TransferDataFromWindow()
{
    doCleanup( false );

    return true;
}
void DIALOG_CLEANUP_TRACKS_AND_VIAS::OnCheckBox( wxCommandEvent& anEvent )
{
    doCleanup( true );
}
Example #25
0
void HsQMLCanvasBackEnd::doRendering()
{
    if (!mGL) {
        mGL = mWindow->openglContext();
        QObject::connect(
            mGL, SIGNAL(aboutToBeDestroyed()), this, SLOT(doCleanup()));
        HsQMLGLCanvasType ctype;
        QSurfaceFormat format = mGL->format();
        switch (format.renderableType()) {
            case QSurfaceFormat::OpenGL: ctype = HSQML_GL_DESKTOP; break;
            case QSurfaceFormat::OpenGLES: ctype = HSQML_GL_ES; break;
            default: setStatus(HsQMLCanvas::BadConfig); return;
        }
        mGLViewportFn = reinterpret_cast<GLViewportFn>(
            mGL->getProcAddress("glViewport"));
        mGLClearColorFn = reinterpret_cast<GLClearColorFn>(
            mGL->getProcAddress("glClearColor"));
        mGLClearFn = reinterpret_cast<GLClearFn>(
            mGL->getProcAddress("glClear"));
        if (!mGLViewportFn || !mGLClearColorFn || !mGLClearFn) {
            setStatus(HsQMLCanvas::BadProcs);
            return;
        }
        mGLCallbacks->mSetupCb(
            ctype, format.majorVersion(), format.minorVersion());
    }

    // Reset OpenGL state before rendering
#if QT_VERSION >= 0x050200
    mWindow->resetOpenGLState();
#else
#warning Resetting OpenGL state requires Qt 5.2 or later
#endif

    // Clear window if painting below the scenegraph
    if (mWinInfo.needsBelowClear()) {
        QColor bg = mWindow->color();
        mGLClearColorFn(bg.redF(), bg.greenF(), bg.blueF(), bg.alphaF());
        mGLClearFn(GL_COLOR_BUFFER_BIT);
    }

    // Setup prior to paint callback
    QMatrix4x4 matrix;
    bool inlineMode = HsQMLCanvas::Inline == mDisplayMode;
    if (inlineMode) {
        if (!mFBO->bind()) {
            setStatus(HsQMLCanvas::BadBind);
            return;
        }
        mGLViewportFn(0, 0, qCeil(mCanvasWidth), qCeil(mCanvasHeight));

        // Clear FBO to transparent
        mGLClearColorFn(0, 0, 0, 0);
        mGLClearFn(GL_COLOR_BUFFER_BIT);
    }
    else {
        // Calculate matrix for non-inline display modes
        QMatrix4x4 smatrix;
        QSGNode* node = mTransformNode;
        while (node) {
            if (QSGNode::TransformNodeType == node->type()) {
                QSGTransformNode* tnode = static_cast<QSGTransformNode*>(node);
                smatrix = tnode->matrix() * smatrix;
            }
            node = node->parent();
        }
        matrix.translate(-1, 1);
        matrix.scale(2.0f/mWindow->width(), -2.0f/mWindow->height());
        matrix *= smatrix;
        matrix.scale(mItemWidth/2.0f, mItemHeight/2.0f);
        matrix.translate(1, 1);

        mGLViewportFn(0, 0, mWindow->width(), mWindow->height());
    }

    setStatus(HsQMLCanvas::Okay);
    mGLCallbacks->mPaintCb(matrix.data(), mItemWidth, mItemHeight);

    if (inlineMode) {
        mFBO->release();
    }
}
Example #26
0
void
MemoryContentCache::operator()
  (const ptr_lib::shared_ptr<const Name>& prefix,
   const ptr_lib::shared_ptr<const Interest>& interest, Face& face,
   boost::uint64_t interestFilterId,
   const ptr_lib::shared_ptr<const InterestFilter>& filter)
{
  doCleanup();

  const Name::Component* selectedComponent = 0;
  Blob selectedEncoding;
  // We need to iterate over both arrays.
  size_t totalSize = staleTimeCache_.size() + noStaleTimeCache_.size();
  for (size_t i = 0; i < totalSize; ++i) {
    const Content* content;
    if (i < staleTimeCache_.size())
      content = staleTimeCache_[i].get();
    else
      // We have iterated over the first array. Get from the second.
      content = noStaleTimeCache_[i - staleTimeCache_.size()].get();

    if (interest->matchesName(content->getName())) {
      if (interest->getChildSelector() < 0) {
        // No child selector, so send the first match that we have found.
        face.send(*content->getDataEncoding());
        return;
      }
      else {
        // Update selectedEncoding based on the child selector.
        const Name::Component* component;
        if (content->getName().size() > interest->getName().size())
          component = &content->getName().get(interest->getName().size());
        else
          component = &emptyComponent_;

        bool gotBetterMatch = false;
        if (!selectedEncoding)
          // Save the first match.
          gotBetterMatch = true;
        else {
          if (interest->getChildSelector() == 0) {
            // Leftmost child.
            if (*component < *selectedComponent)
              gotBetterMatch = true;
          }
          else {
            // Rightmost child.
            if (*component > *selectedComponent)
              gotBetterMatch = true;
          }
        }

        if (gotBetterMatch) {
          selectedComponent = component;
          selectedEncoding = content->getDataEncoding();
        }
      }
    }
  }

  if (selectedEncoding)
    // We found the leftmost or rightmost child.
    face.send(*selectedEncoding);
  else {
    // Call the onDataNotFound callback (if defined).
    map<string, OnInterestCallback>::iterator onDataNotFound =
      onDataNotFoundForPrefix_.find(prefix->toUri());
    if (onDataNotFound != onDataNotFoundForPrefix_.end() &&
        onDataNotFound->second)
      onDataNotFound->second(prefix, interest, face, interestFilterId, filter);
  }
}