void IApp::GameLoop(void) { SLOG(App_GameLoop, SeverityInfo) << std::endl; // Is this a Console Only game loop? bool anConsoleOnly = mProperties.Get<bool>("bWindowConsole"); // Clock used in restricting Update loop to a fixed rate sf::Clock anUpdateClock; #if (SFML_VERSION_MAJOR < 2) // Restart/Reset our Update clock anUpdateClock.Reset(); // When do we need to update next (in seconds)? float anUpdateNext = anUpdateClock.GetElapsedTime(); #else // Clock used in calculating the time elapsed since the last frame sf::Clock anFrameClock; // Restart/Reset our Update clock anUpdateClock.restart(); // When do we need to update next (in milliseconds)? sf::Int32 anUpdateNext = anUpdateClock.getElapsedTime().asMilliseconds(); #endif // Make sure we have at least one state active if(mStateManager.IsEmpty()) { // Exit with an error since there isn't an active state Quit(StatusAppInitFailed); } // Loop while IsRunning returns true #if (SFML_VERSION_MAJOR < 2) while(IsRunning() && !mStateManager.IsEmpty() && (mWindow.IsOpened() || anConsoleOnly)) #else while(IsRunning() && !mStateManager.IsEmpty() && (mWindow.isOpen() || anConsoleOnly)) #endif { // Get the currently active state IState& anState = mStateManager.GetActiveState(); // Count the number of sequential UpdateFixed loop calls Uint32 anUpdates = 0; // Process any available input ProcessInput(anState); // Make note of the current update time #if (SFML_VERSION_MAJOR < 2) float anUpdateTime = anUpdateClock.GetElapsedTime(); #else sf::Int32 anUpdateTime = anUpdateClock.getElapsedTime().asMilliseconds(); #endif // Process our UpdateFixed portion of the game loop while((anUpdateTime - anUpdateNext) >= mUpdateRate && anUpdates++ < mMaxUpdates) { // Let the current active state perform fixed updates next anState.UpdateFixed(); // Let the StatManager perfom its updates mStatManager.UpdateFixed(); //ILOG() << "IApp::UpdateFixed() anUpdates=" << anUpdates // << ", anUpdateTime=" << anUpdateTime << ", anUpdateNext=" << anUpdateNext // << ", mUpdateRate=" << mUpdateRate << ", anUpdateActual=" #if (SFML_VERSION_MAJOR < 2) // << (anUpdateClock.GetElapsedTime() - anUpdateTime) << std::endl; #else // << (anUpdateClock.getElapsedTime().asMilliseconds() - anUpdateTime) << std::endl; #endif // Compute the next appropriate UpdateFixed time anUpdateNext += mUpdateRate; } // while((anUpdateTime - anUpdateNext) >= mUpdateRate && anUpdates <= mMaxUpdates) // Let the current active state perform its variable update #if (SFML_VERSION_MAJOR < 2) anState.UpdateVariable(mWindow.GetFrameTime()); #else // Convert to floating point value of seconds for SFML 2.0 anState.UpdateVariable(anFrameClock.restart().asSeconds()); #endif // Let the current active state draw stuff anState.Draw(); // Let the StatManager perform its drawing mStatManager.Draw(); #if (SFML_VERSION_MAJOR < 2) // Display Render window to the screen mWindow.Display(); #else // Display Render window to the screen mWindow.display(); #endif // Give the state manager a chance to delete any pending states mStateManager.Cleanup(); } // while(IsRunning() && !mStates.empty() && (mWindow.isOpen() || anConsoleOnly)) }
bool AudioOutputDeviceAlsa::IsPlaying() { return IsRunning(); // if Thread is running }
//============================================================================== int COptoTrack::GetOptoState( int * piState ){ *piState = IsRunning(); return 0; }
void MsgHandlerJSON::Run() { std::string msg; syslog(LOG_INFO, "JSON message handler started"); m_closed = false; while(IsRunning()) { // exit if connection was closed if(m_closed) { break; } // wait for string if(!ReceiveString(msg)) { continue; } std::cout << msg << std::endl; // check for http request if(msg.substr(0, 8) == "OPTIONS " && msg.size() > 8) { msg = msg.substr(8); } else if(msg.substr(0, 4) != "GET ") { continue; } std::string::size_type p = msg.rfind("HTTP/"); if(p == std::string::npos) { continue; } msg = msg.substr(0, p); std::cout << "URI: " << msg << std::endl; // extract JSON query string p = msg.find("?"); std::string url; std::string query; if(p > 0) { url = msg.substr(0, p); } if(p < msg.size() - 1) { query = URLDecode(msg.substr(p + 1)); } std::cout << "URL: " << url << std::endl; std::cout << "QUERY: " << query << std::endl; // get message id while((url[0] > '9' || url[0] < '0') && url.size() > 1) { url = url.substr(1); } uint32_t msgid = atoi(url.c_str()); MsgPacket* request = MsgPacketFromJSON(query, msgid); if(m_msgtype != 0) { request->setType(m_msgtype); } std::cout << "MSGID: " << request->getMsgID() << std::endl; std::cout << "MSGTYPE: " << request->getType() << std::endl; request->print(); MsgPacket* response = new MsgPacket(request->getMsgID(), request->getType(), request->getUID()); std::string jsonformat; std::string result; request->rewind(); if(OnMessage(request, response)) { if(OnCustomJSONResponse(response, result)) { SendHTTPResponse(result); } else if(OnResponseFormat(response, jsonformat)) { result = MsgPacketToJSON(response, jsonformat); SendHTTPResponse(result); } } delete response; delete request; } }
LRESULT GameApp::OnSysCommand(WPARAM wParam, LPARAM lParam) { switch (wParam) { case SC_MAXIMIZE : { // If windowed and ready... if ( m_bWindowedMode && IsRunning() ) { // Make maximize into FULLSCREEN toggle OnAltEnter(); } } return 0; case SC_CLOSE : { // The quit dialog confirmation would appear once for // every SC_CLOSE we get - which happens multiple times // if modal dialogs are up. This now uses the QUIT_NO_PROMPT // flag to only prompt when receiving a SC_CLOSE that isn't // generated by us (identified by QUIT_NO_PROMPT). // If closing, prompt to close if this isn't a forced quit if ( lParam != QUIT_NO_PROMPT ) { // ET - 05/21/01 - Bug #1916 - Begin // We were receiving multiple close dialogs // when closing again ALT-F4 while the close // confirmation dialog was up. // Eat if already servicing a close if ( m_bQuitRequested ) return true; // Wait for the application to be restored // before going any further with the new // screen. Flash until the person selects // that they want to restore the game, then // reinit the display if fullscreen. // The reinit is necessary otherwise the game // will switch to windowed mode. // TODO MrMike: Need a message eater, message saver //if (postableMessageBacklog.valid()) //{ // postableMessageBacklog->Add( PostableMessage(WM_SYSCOMMAND, wParam, MAKELPARAM(0, 0) ) ); // return true; //} // Quit requested m_bQuitRequested = true; } m_bQuitting = true; // Reset the quit after any other dialogs have popped up from this close m_bQuitRequested = false; } return 0; default: // return non-zero of we didn't process the SYSCOMMAND message return DefWindowProc(GetHwnd(), WM_SYSCOMMAND, wParam, lParam); } return 0; }
// send an ipmi command and wait for response. SaErrorT cIpmiCon::Cmd( const cIpmiAddr &addr, const cIpmiMsg &msg, cIpmiAddr &rsp_addr, cIpmiMsg &rsp, int retries ) { assert( retries > 0 ); SaErrorT rv; assert( msg.m_data_len <= dIpmiMaxMsgLength ); assert( IsRunning() ); int idx = addr.m_slave_addr; // use 0 for system interface if ( addr.m_type == eIpmiAddrTypeSystemInterface ) idx = 0; cThreadCond cond; // create request cIpmiRequest *r = new cIpmiRequest( addr, msg ); r->m_rsp_addr = &rsp_addr; r->m_rsp = &rsp; r->m_signal = &cond; r->m_error = SA_ERR_HPI_INVALID_CMD; r->m_retries_left = retries; // lock queue cond.Lock(); m_queue_lock.Lock(); if ( m_num_outstanding < m_max_outstanding ) { // send the command within this thread context. rv = SendCmd( r ); if ( rv != SA_OK ) { // error delete r; m_queue_lock.Unlock(); cond.Unlock(); return rv; } } else { stdlog << "send queue full.\n"; m_queue = g_list_append( m_queue, r ); } m_queue_lock.Unlock(); // wait for response cond.Wait(); cond.Unlock(); rv = r->m_error; delete r; if ( rv == SA_OK ) { assert( (tIpmiNetfn)(msg.m_netfn | 1) == rsp.m_netfn ); assert( msg.m_cmd == rsp.m_cmd ); } return rv; }
/** * G0, G1: Coordinated movement of X Y Z E axes */ void GcodeSuite::G0_G1( #if IS_SCARA || defined(G0_FEEDRATE) bool fast_move/*=false*/ #endif ) { if (IsRunning() #if ENABLED(NO_MOTION_BEFORE_HOMING) && !axis_unhomed_error(parser.seen('X'), parser.seen('Y'), parser.seen('Z')) #endif ) { #ifdef G0_FEEDRATE float saved_feedrate_mm_s; #if ENABLED(VARIABLE_G0_FEEDRATE) if (fast_move) { saved_feedrate_mm_s = feedrate_mm_s; // Back up the (old) motion mode feedrate feedrate_mm_s = saved_g0_feedrate_mm_s; // Get G0 feedrate from last usage } #endif #endif get_destination_from_command(); // For X Y Z E F #ifdef G0_FEEDRATE if (fast_move) { #if ENABLED(VARIABLE_G0_FEEDRATE) saved_g0_feedrate_mm_s = feedrate_mm_s; // Save feedrate for the next G0 #else saved_feedrate_mm_s = feedrate_mm_s; // Back up the (new) motion mode feedrate feedrate_mm_s = MMM_TO_MMS(G0_FEEDRATE); // Get the fixed G0 feedrate #endif } #endif #if ENABLED(FWRETRACT) && ENABLED(FWRETRACT_AUTORETRACT) if (MIN_AUTORETRACT <= MAX_AUTORETRACT) { // When M209 Autoretract is enabled, convert E-only moves to firmware retract/recover moves if (fwretract.autoretract_enabled && parser.seen('E') && !(parser.seen('X') || parser.seen('Y') || parser.seen('Z'))) { const float echange = destination[E_AXIS] - current_position[E_AXIS]; // Is this a retract or recover move? if (WITHIN(ABS(echange), MIN_AUTORETRACT, MAX_AUTORETRACT) && fwretract.retracted[active_extruder] == (echange > 0.0)) { current_position[E_AXIS] = destination[E_AXIS]; // Hide a G1-based retract/recover from calculations sync_plan_position_e(); // AND from the planner return fwretract.retract(echange < 0.0); // Firmware-based retract/recover (double-retract ignored) } } } #endif // FWRETRACT #if IS_SCARA fast_move ? prepare_uninterpolated_move_to_destination() : prepare_move_to_destination(); #else prepare_move_to_destination(); #endif #ifdef G0_FEEDRATE // Restore the motion mode feedrate if (fast_move) feedrate_mm_s = saved_feedrate_mm_s; #endif #if ENABLED(NANODLP_Z_SYNC) #if ENABLED(NANODLP_ALL_AXIS) #define _MOVE_SYNC parser.seenval('X') || parser.seenval('Y') || parser.seenval('Z') // For any move wait and output sync message #else #define _MOVE_SYNC parser.seenval('Z') // Only for Z move #endif if (_MOVE_SYNC) { planner.synchronize(); SERIAL_ECHOLNPGM(MSG_Z_MOVE_COMP); } #endif } }
void Track::Draw( ocpnDC& dc, ViewPort &VP, const LLBBox &box ) { std::list< std::list<wxPoint> > pointlists; GetPointLists(pointlists, VP, box); if(!pointlists.size()) return; unsigned short int FromSegNo = 1; // Establish basic colour wxColour basic_colour; if( IsRunning() ) basic_colour = GetGlobalColor( _T ( "URED" ) ); else basic_colour = GetDimColor(g_colourTrackLineColour); wxPenStyle style = wxPENSTYLE_SOLID; int width = g_pRouteMan->GetTrackPen()->GetWidth(); wxColour col; if( m_style != wxPENSTYLE_INVALID ) style = m_style; if( m_width != WIDTH_UNDEFINED ) width = m_width; if( m_Colour == wxEmptyString ) { col = basic_colour; } else { for( unsigned int i = 0; i < sizeof( ::GpxxColorNames ) / sizeof(wxString); i++ ) { if( m_Colour == ::GpxxColorNames[i] ) { col = ::GpxxColors[i]; break; } } } double radius = 0.; if( g_bHighliteTracks ) { double radius_meters = 20; //Current_Ch->GetNativeScale() * .0015; // 1.5 mm at original scale radius = radius_meters * VP.view_scale_ppm; if(radius < 1.0) radius = 0; } if( dc.GetDC() || radius ) { dc.SetPen( *wxThePenList->FindOrCreatePen( col, width, style ) ); dc.SetBrush( *wxTheBrushList->FindOrCreateBrush( col, wxBRUSHSTYLE_SOLID ) ); for(std::list< std::list<wxPoint> >::iterator lines = pointlists.begin(); lines != pointlists.end(); lines++) { // convert from linked list to array wxPoint *points = new wxPoint[lines->size()]; int i = 0; for(std::list<wxPoint>::iterator line = lines->begin(); line != lines->end(); line++) { points[i] = *line; i++; } int hilite_width = radius; if( hilite_width ) { wxPen psave = dc.GetPen(); dc.StrokeLines( i, points ); wxColor trackLine_dim_colour = GetDimColor(g_colourTrackLineColour); wxColour hilt( trackLine_dim_colour.Red(), trackLine_dim_colour.Green(), trackLine_dim_colour.Blue(), 128 ); wxPen HiPen( hilt, hilite_width, wxPENSTYLE_SOLID ); dc.SetPen( HiPen ); dc.StrokeLines( i, points ); dc.SetPen( psave ); } else dc.StrokeLines( i, points ); delete [] points; } } #ifdef ocpnUSE_GL else { // opengl version glColor3ub(col.Red(), col.Green(), col.Blue()); glLineWidth( wxMax( g_GLMinSymbolLineWidth, width ) ); if( g_GLOptions.m_GLLineSmoothing ) glEnable( GL_LINE_SMOOTH ); glEnable( GL_BLEND ); int size = 0; // convert from linked list to array, allocate array just once for(std::list< std::list<wxPoint> >::iterator lines = pointlists.begin(); lines != pointlists.end(); lines++) size = wxMax(size, lines->size()); int *points = new int[2*size]; glVertexPointer(2, GL_INT, 0, points); glEnableClientState(GL_VERTEX_ARRAY); for(std::list< std::list<wxPoint> >::iterator lines = pointlists.begin(); lines != pointlists.end(); lines++) { // convert from linked list to array int i = 0; for(std::list<wxPoint>::iterator line = lines->begin(); line != lines->end(); line++) { points[i+0] = line->x; points[i+1] = line->y; i+=2; } glDrawArrays(GL_LINE_STRIP, 0, i >> 1); } glDisableClientState(GL_VERTEX_ARRAY); delete [] points; glDisable( GL_LINE_SMOOTH ); glDisable( GL_BLEND ); } #endif if(m_HighlightedTrackPoint >= 0) TrackPoints[m_HighlightedTrackPoint]->Draw(dc); }
bool Shooter::IsReady() { return (IsRunning() && !IsShooting() && (motor_timer.Get() > MOTOR_START) && pid_bottom.OnTarget() && pid_top.OnTarget()); }
int wxEventLoopManual::Run() { // event loops are not recursive, you need to create another loop! wxCHECK_MSG( !IsRunning(), -1, _T("can't reenter a message loop") ); // ProcessIdle() and Dispatch() below may throw so the code here should // be exception-safe, hence we must use local objects for all actions we // should undo wxEventLoopActivator activate(wx_static_cast(wxEventLoop *, this)); #if defined(__WXMSW__) && wxUSE_THREADS wxRunningEventLoopCounter evtLoopCounter; #endif // __WXMSW__ // we must ensure that OnExit() is called even if an exception is thrown // from inside Dispatch() but we must call it from Exit() in normal // situations because it is supposed to be called synchronously, // wxModalEventLoop depends on this (so we can't just use ON_BLOCK_EXIT or // something similar here) #if wxUSE_EXCEPTIONS for ( ;; ) { try { #endif // wxUSE_EXCEPTIONS // this is the event loop itself for ( ;; ) { // give them the possibility to do whatever they want OnNextIteration(); // generate and process idle events for as long as we don't // have anything else to do while ( !Pending() && (wxTheApp && wxTheApp->ProcessIdle()) ) ; // if the "should exit" flag is set, the loop should terminate // but not before processing any remaining messages so while // Pending() returns true, do process them if ( m_shouldExit ) { while ( Pending() ) Dispatch(); break; } // a message came or no more idle processing to do, sit in // Dispatch() waiting for the next message if ( !Dispatch() ) { // we got WM_QUIT break; } } #if wxUSE_EXCEPTIONS // exit the outer loop as well break; } catch ( ... ) { try { if ( !wxTheApp || !wxTheApp->OnExceptionInMainLoop() ) { OnExit(); break; } //else: continue running the event loop } catch ( ... ) { // OnException() throwed, possibly rethrowing the same // exception again: very good, but we still need OnExit() to // be called OnExit(); throw; } } } #endif // wxUSE_EXCEPTIONS return m_exitcode; }
TEST_F(CoreContextTest, InitiateMultipleChildren) { AutoCurrentContext testCtxt; testCtxt->Initiate(); // Initiate all children { auto outerCtxt = testCtxt->Create<void>(); auto child1 = outerCtxt->Create<void>(); auto child2 = outerCtxt->Create<void>(); auto child3 = outerCtxt->Create<void>(); child1->Initiate(); child2->Initiate(); child3->Initiate(); outerCtxt->Initiate(); ASSERT_TRUE(child1->IsRunning()); ASSERT_TRUE(child2->IsRunning()); ASSERT_TRUE(child3->IsRunning()); outerCtxt->SignalShutdown(true); } // Don't initiate middle child { auto outerCtxt = testCtxt->Create<void>(); auto child1 = outerCtxt->Create<void>(); auto child2 = outerCtxt->Create<void>(); auto child3 = outerCtxt->Create<void>(); child1->Initiate(); child3->Initiate(); outerCtxt->Initiate(); ASSERT_TRUE(child1->IsRunning()); ASSERT_FALSE(child2->IsInitiated()); ASSERT_TRUE(child3->IsRunning()); outerCtxt->SignalShutdown(true); } // Don't initiate middle child and initiate parent first { auto outerCtxt = testCtxt->Create<void>(); auto child1 = outerCtxt->Create<void>(); auto child2 = outerCtxt->Create<void>(); auto child3 = outerCtxt->Create<void>(); outerCtxt->Initiate(); child1->Initiate(); child3->Initiate(); ASSERT_TRUE(child1->IsRunning()); ASSERT_FALSE(child2->IsInitiated()); ASSERT_TRUE(child3->IsRunning()); outerCtxt->SignalShutdown(true); } }
int main(int args[]) { srand(time(0)); //auto window = Window::CreateSDLWindow(); auto application = new FWApplication(); if (!application->GetWindow()) { LOG("Couldn't create window..."); return EXIT_FAILURE; } application->SetTargetFPS(60); application->SetColor(Color(255, 10, 40, 255)); Game* game = new Game(application); //while (true){} while (application->IsRunning()) { application->StartTick(); SDL_Event event; while (SDL_PollEvent(&event)) { switch (event.type) { case SDL_QUIT: application->Quit(); break; case SDL_KEYDOWN: switch (event.key.keysym.scancode){ case SDL_SCANCODE_SPACE: game->Pause(); break; default: break; } } } application->UpdateGameObjects(); if (!game->IsPause()){ game->Update(application->GetDeltaTime()); } application->RenderGameObjects(); application->SetColor(Color(0, 0, 0, 255));// For the letter colour application->DrawTextWithWhiteBorder("[Round] " + std::to_string(game->GetRoundNumber()), SCREEN_WIDTH / 2, 20); application->DrawTextWithWhiteBorder("[Seconds Remaining] " + std::to_string(game->GetTimeRemaining()), SCREEN_WIDTH / 2, 40); if (game->IsPause()){ application->DrawTextWithWhiteBorder("[PAUSE]", SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2); application->SetColor(Color(238, 233, 233, 255));// For the background } else{ application->SetColor(Color(255, 255, 255, 255));// For the background } if (game->GameOver()){ application->Quit(); } application->EndTick(); } return EXIT_SUCCESS; }
/*! * \brief Scan a list of directories recursively for music and albumart. * Inserts, updates and removes any files any files found in the * database. * * \param dirList List of directories to scan * * \returns Nothing. */ void MusicFileScanner::SearchDirs(const QStringList &dirList) { QString host = gCoreContext->GetHostName(); if (IsRunning()) { // check how long the scanner has been running // if it's more than 60 minutes assume something went wrong QString lastRun = gCoreContext->GetSetting("MusicScannerLastRunStart", ""); if (!lastRun.isEmpty()) { QDateTime dtLastRun = QDateTime::fromString(lastRun, Qt::ISODate); if (dtLastRun.isValid()) { if (MythDate::current() > dtLastRun.addSecs(60*60)) { LOG(VB_GENERAL, LOG_INFO, "Music file scanner has been running for more than 60 minutes. Lets reset and try again"); gCoreContext->SendMessage(QString("MUSIC_SCANNER_ERROR %1 %2").arg(host).arg("Stalled")); // give the user time to read the notification before restarting the scan sleep(5); } else { LOG(VB_GENERAL, LOG_INFO, "Music file scanner is already running"); gCoreContext->SendMessage(QString("MUSIC_SCANNER_ERROR %1 %2").arg(host).arg("Already_Running")); return; } } } } //TODO: could sanity check the directory exists and is readable here? LOG(VB_GENERAL, LOG_INFO, "Music file scanner started"); gCoreContext->SendMessage(QString("MUSIC_SCANNER_STARTED %1").arg(host)); updateLastRunStart(); QString status = QString("running"); updateLastRunStatus(status); m_tracksTotal = m_tracksAdded = m_tracksUnchanged = m_tracksRemoved = m_tracksUpdated = 0; m_coverartTotal = m_coverartAdded = m_coverartUnchanged = m_coverartRemoved = m_coverartUpdated = 0; MusicLoadedMap music_files; MusicLoadedMap art_files; MusicLoadedMap::Iterator iter; for (int x = 0; x < dirList.count(); x++) { QString startDir = dirList[x]; m_startDirs.append(startDir + '/'); LOG(VB_GENERAL, LOG_INFO, QString("Searching '%1' for music files").arg(startDir)); BuildFileList(startDir, music_files, art_files, 0); } m_tracksTotal = music_files.count(); m_coverartTotal = art_files.count(); ScanMusic(music_files); ScanArtwork(art_files); LOG(VB_GENERAL, LOG_INFO, "Updating database"); /* This can be optimised quite a bit by consolidating all commands via a lot of refactoring. 1) group all files of the same decoder type, and don't create/delete a Decoder pr. AddFileToDB. Or make Decoders be singletons, it should be a fairly simple change. 2) RemoveFileFromDB should group the remove into one big SQL. 3) UpdateFileInDB, same as 1. */ for (iter = music_files.begin(); iter != music_files.end(); iter++) { if ((*iter).location == MusicFileScanner::kFileSystem) AddFileToDB(iter.key(), (*iter).startDir); else if ((*iter).location == MusicFileScanner::kDatabase) RemoveFileFromDB(iter.key(), (*iter).startDir); else if ((*iter).location == MusicFileScanner::kNeedUpdate) { UpdateFileInDB(iter.key(), (*iter).startDir); ++m_tracksUpdated; } } for (iter = art_files.begin(); iter != art_files.end(); iter++) { if ((*iter).location == MusicFileScanner::kFileSystem) AddFileToDB(iter.key(), (*iter).startDir); else if ((*iter).location == MusicFileScanner::kDatabase) RemoveFileFromDB(iter.key(), (*iter).startDir); else if ((*iter).location == MusicFileScanner::kNeedUpdate) { UpdateFileInDB(iter.key(), (*iter).startDir); ++m_coverartUpdated; } } // Cleanup orphaned entries from the database cleanDB(); QString trackStatus = QString("total tracks found: %1 (unchanged: %2, added: %3, removed: %4, updated %5)") .arg(m_tracksTotal).arg(m_tracksUnchanged).arg(m_tracksAdded) .arg(m_tracksRemoved).arg(m_tracksUpdated); QString coverartStatus = QString("total coverart found: %1 (unchanged: %2, added: %3, removed: %4, updated %5)") .arg(m_coverartTotal).arg(m_coverartUnchanged).arg(m_coverartAdded) .arg(m_coverartRemoved).arg(m_coverartUpdated); LOG(VB_GENERAL, LOG_INFO, "Music file scanner finished "); LOG(VB_GENERAL, LOG_INFO, trackStatus); LOG(VB_GENERAL, LOG_INFO, coverartStatus); gCoreContext->SendMessage(QString("MUSIC_SCANNER_FINISHED %1 %2 %3 %4 %5") .arg(host).arg(m_tracksTotal).arg(m_tracksAdded) .arg(m_coverartTotal).arg(m_coverartAdded)); updateLastRunEnd(); status = QString("success - %1 - %2").arg(trackStatus).arg(coverartStatus); updateLastRunStatus(status); }
//-------------------------------------------------------------------------- void VeTickThread::Stop() { m_bNeedTick = false; while(IsRunning()) {} }
void ZoneLaunch::SendStatus() const { m_world->SendStatus(m_zone.c_str(), m_startCount, IsRunning()); }
bool wxEventLoop::Dispatch() { wxCHECK_MSG( IsRunning(), false, _T("can't call Dispatch() if not running") ); MSG msg; BOOL rc = ::GetMessage(&msg, (HWND) NULL, 0, 0); if ( rc == 0 ) { // got WM_QUIT return false; } if ( rc == -1 ) { // should never happen, but let's test for it nevertheless wxLogLastError(wxT("GetMessage")); // still break from the loop return false; } #if wxUSE_THREADS wxASSERT_MSG( wxThread::IsMain(), wxT("only the main thread can process Windows messages") ); static bool s_hadGuiLock = true; static wxMsgList s_aSavedMessages; // if a secondary thread owning the mutex is doing GUI calls, save all // messages for later processing - we can't process them right now because // it will lead to recursive library calls (and we're not reentrant) if ( !wxGuiOwnedByMainThread() ) { s_hadGuiLock = false; // leave out WM_COMMAND messages: too dangerous, sometimes // the message will be processed twice if ( !wxIsWaitingForThread() || msg.message != WM_COMMAND ) { MSG* pMsg = new MSG(msg); s_aSavedMessages.Append(pMsg); } return true; } else { // have we just regained the GUI lock? if so, post all of the saved // messages // // FIXME of course, it's not _exactly_ the same as processing the // messages normally - expect some things to break... if ( !s_hadGuiLock ) { s_hadGuiLock = true; wxMsgList::compatibility_iterator node = s_aSavedMessages.GetFirst(); while (node) { MSG* pMsg = node->GetData(); s_aSavedMessages.Erase(node); ProcessMessage(pMsg); delete pMsg; node = s_aSavedMessages.GetFirst(); } } } #endif // wxUSE_THREADS ProcessMessage(&msg); return true; }
//--------------------------------------------------------------------------- size_t MediaInfoList_Internal::Open(const String &File_Name, const fileoptions_t Options) { //Option FileOption_Close if (Options & FileOption_CloseAll) Close(All); //Option Recursive //TODO //Get all filenames ZtringList List; if ((File_Name.size()>=7 && File_Name[0]==_T('h') && File_Name[1]==_T('t') && File_Name[2]==_T('t') && File_Name[3]==_T('p') && File_Name[4]==_T(':') && File_Name[5]==_T('/') && File_Name[6]==_T('/')) || (File_Name.size()>=6 && File_Name[0]==_T('f') && File_Name[1]==_T('t') && File_Name[2]==_T('p') && File_Name[3]==_T(':') && File_Name[4]==_T('/') && File_Name[5]==_T('/')) || (File_Name.size()>=6 && File_Name[0]==_T('m') && File_Name[1]==_T('m') && File_Name[2]==_T('s') && File_Name[3]==_T(':') && File_Name[4]==_T('/') && File_Name[5]==_T('/')) || (File_Name.size()>=7 && File_Name[0]==_T('m') && File_Name[1]==_T('m') && File_Name[2]==_T('s') && File_Name[3]==_T('h') && File_Name[4]==_T(':') && File_Name[5]==_T('/') && File_Name[6]==_T('/'))) List.push_back(File_Name); else if (File::Exists(File_Name)) List.push_back(File_Name); else List=Dir::GetAllFileNames(File_Name, (Options&FileOption_NoRecursive)?Dir::Nothing:Dir::Parse_SubDirs); #if defined(MEDIAINFO_DIRECTORY_YES) Reader_Directory().Directory_Cleanup(List); #endif //defined(MEDIAINFO_DIRECTORY_YES) //Registering files CS.Enter(); if (ToParse.empty()) CountValid=0; for (ZtringList::iterator L=List.begin(); L!=List.end(); L++) ToParse.push(*L); ToParse_Total+=List.size(); if (ToParse_Total) State=ToParse_AlreadyDone*10000/ToParse_Total; else State=10000; CS.Leave(); //Parsing if (BlockMethod==1) { CS.Enter(); if (!IsRunning()) //If already created, the routine will read the new files { RunAgain(); IsInThread=true; } CS.Leave(); return 0; } else { Entry(); //Normal parsing return Count_Get(); } }
void CVideoReferenceClock::Start() { if(CServiceBroker::GetSettings()->GetBool(CSettings::SETTING_VIDEOPLAYER_USEDISPLAYASCLOCK) && !IsRunning()) Create(); }
MPIComm::~MPIComm() { if(IsRunning()){ EndProcessing(); } }
void BasicEvent::ScheduleAbort() { ASSERT(IsRunning() && "Tried to scheduled the abortion of an event twice!"); m_abortState = AbortState::STATE_ABORT_SCHEDULED; }
// Do reflex avoidance movements if our "feelers" are touched void CCSBot::FeelerReflexAdjustment(Vector *goalPosition) { // if we are in a "precise" area, do not do feeler adjustments if (m_lastKnownArea && (m_lastKnownArea->GetAttributes() & NAV_PRECISE)) return; Vector dir(BotCOS(m_forwardAngle), BotSIN(m_forwardAngle), 0.0f); Vector lat(-dir.y, dir.x, 0.0f); const float feelerOffset = (IsCrouching()) ? 15.0f : 20.0f; const float feelerLengthRun = 50.0f; // 100 - too long for tight hallways (cs_747) const float feelerLengthWalk = 30.0f; const float feelerHeight = StepHeight + 0.1f; // if obstacle is lower than StepHeight, we'll walk right over it float feelerLength = (IsRunning()) ? feelerLengthRun : feelerLengthWalk; feelerLength = (IsCrouching()) ? 20.0f : feelerLength; // Feelers must follow floor slope float ground; Vector normal; //m_eyePos = EyePosition(); m_eyePos.x = pev->origin.x + pev->view_ofs.x; m_eyePos.y = pev->origin.y + pev->view_ofs.y; m_eyePos.z = pev->origin.z + pev->view_ofs.z; if (GetSimpleGroundHeightWithFloor(&m_eyePos, &ground, &normal) == false) return; // get forward vector along floor dir = CrossProduct(lat, normal); // correct the sideways vector lat = CrossProduct(dir, normal); Vector feet(pev->origin.x, pev->origin.y, GetFeetZ()); feet.z += feelerHeight; Vector from = feet + feelerOffset * lat; Vector to = from + feelerLength * dir; bool leftClear = IsWalkableTraceLineClear(from, to, WALK_THRU_EVERYTHING); // avoid ledges, too // use 'from' so it doesn't interfere with legitimate gap jumping (its at our feet) // TODO: Rethink this - it causes lots of wiggling when bots jump down from vents, etc /* float ground; if (GetSimpleGroundHeightWithFloor(&from, &ground)) { if (GetFeetZ() - ground > JumpHeight) leftClear = false; } */ if ((cv_bot_traceview.value == 1.0f && IsLocalPlayerWatchingMe()) || cv_bot_traceview.value == 10.0f) { if (leftClear) UTIL_DrawBeamPoints(from, to, 1, 0, 255, 0); else UTIL_DrawBeamPoints(from, to, 1, 255, 0, 0); } from = feet - feelerOffset * lat; to = from + feelerLength * dir; bool rightClear = IsWalkableTraceLineClear(from, to, WALK_THRU_EVERYTHING); /* // avoid ledges, too if (GetSimpleGroundHeightWithFloor(&from, &ground)) { if (GetFeetZ() - ground > JumpHeight) rightClear = false; } */ if ((cv_bot_traceview.value == 1.0f && IsLocalPlayerWatchingMe()) || cv_bot_traceview.value == 10.0f) { if (rightClear) UTIL_DrawBeamPoints(from, to, 1, 0, 255, 0); else UTIL_DrawBeamPoints(from, to, 1, 255, 0, 0); } const float avoidRange = (IsCrouching()) ? 150.0f : 300.0f; // 50.0f : 300.0f if (!rightClear) { if (leftClear) { // right hit, left clear - veer left *goalPosition = *goalPosition + avoidRange * lat; } } else if (!leftClear) { // right clear, left hit - veer right *goalPosition = *goalPosition - avoidRange * lat; } }
bool PAPlayer::OpenFile(const CFileItem& file, const CPlayerOptions &options) { if (m_currentlyCrossFading) CloseFileInternal(false); //user seems to be in a hurry m_crossFading = g_guiSettings.GetInt("musicplayer.crossfade"); //WASAPI doesn't support multiple streams, no crossfading for cdda, cd-reading goes mad and no crossfading for last.fm doesn't like two connections if (file.IsCDDA() || file.IsLastFM() || g_guiSettings.GetString("audiooutput.audiodevice").find("wasapi:") != CStdString::npos) m_crossFading = 0; if (m_crossFading && IsPlaying()) { //do a short crossfade on trackskip //set to max 2 seconds for these prev/next transitions if (m_crossFading > 2) m_crossFading = 2; //queue for crossfading bool result = QueueNextFile(file, false); if (result) { //crossfading value may be update by QueueNextFile when nr of channels changed if (!m_crossFading) // swap to next track m_decoder[m_currentDecoder].SetStatus(STATUS_ENDED); else //force to fade to next track immediately m_forceFadeToNext = true; } return result; } // normal opening of file, nothing playing or crossfading not enabled // however no need to return to gui audio device CloseFileInternal(false); // always open the file using the current decoder m_currentDecoder = 0; if (!m_decoder[m_currentDecoder].Create(file, (__int64)(options.starttime * 1000), m_crossFading)) return false; m_iSpeed = 1; m_bPaused = false; m_bStopPlaying = false; m_bytesSentOut = 0; CLog::Log(LOGINFO, "PAPlayer: Playing %s", file.GetPath().c_str()); m_timeOffset = (__int64)(options.starttime * 1000); unsigned int channel, sampleRate, bitsPerSample; m_decoder[m_currentDecoder].GetDataFormat(&channel, &sampleRate, &bitsPerSample); if (!CreateStream(m_currentStream, channel, sampleRate, bitsPerSample)) { m_decoder[m_currentDecoder].Destroy(); CLog::Log(LOGERROR, "PAPlayer::Unable to create audio stream"); } *m_currentFile = file; if (!IsRunning()) Create(); m_startEvent.Set(); m_bIsPlaying = true; m_cachingNextFile = false; m_currentlyCrossFading = false; m_forceFadeToNext = false; m_bQueueFailed = false; m_decoder[m_currentDecoder].Start(); // start playback return true; }
void CVideoReferenceClock::Start() { CSingleExit lock(g_graphicsContext); if(CSettings::GetInstance().GetBool(CSettings::SETTING_VIDEOPLAYER_USEDISPLAYASCLOCK) && !IsRunning()) Create(); }
wxThreadError wxThread::Delete(ExitCode *pRc, wxThreadWait WXUNUSED(waitMode)) { ExitCode rc = 0; // Delete() is always safe to call, so consider all possible states // we might need to resume the thread, but we might also not need to cancel // it if it doesn't run yet bool shouldResume = false, shouldCancel = true, isRunning = false; // check if the thread already started to run { wxCriticalSectionLocker lock((wxCriticalSection &)m_critsect); if ( m_internal->GetState() == STATE_NEW ) { // WinThreadStart() will see it and terminate immediately, no need // to cancel the thread - but we still need to resume it to let it // run m_internal->SetState(STATE_EXITED); Resume(); // it knows about STATE_EXITED special case shouldCancel = false; isRunning = true; // shouldResume is correctly set to false here } else { shouldResume = IsPaused(); } } // resume the thread if it is paused if ( shouldResume ) Resume(); TID hThread = m_internal->GetHandle(); if ( isRunning || IsRunning()) { if (IsMain()) { // set flag for wxIsWaitingForThread() gs_bWaitingForThread = true; } // ask the thread to terminate if ( shouldCancel ) { wxCriticalSectionLocker lock(m_critsect); m_internal->Cancel(); } #if 0 // we can't just wait for the thread to terminate because it might be // calling some GUI functions and so it will never terminate before we // process the Windows messages that result from these functions DWORD result = 0; // suppress warnings from broken compilers do { if ( IsMain() ) { // give the thread we're waiting for chance to do the GUI call // it might be in if ( (gs_nWaitingForGui > 0) && wxGuiOwnedByMainThread() ) { wxMutexGuiLeave(); } } result = ::DosWaitThread(&hThread, DCWW_NOWAIT); // FIXME: We ought to have a message processing loop here!! switch ( result ) { case ERROR_INTERRUPT: case ERROR_THREAD_NOT_TERMINATED: break; case ERROR_INVALID_THREADID: case NO_ERROR: // thread we're waiting for just terminated // or even does not exist any more. result = NO_ERROR; break; default: wxFAIL_MSG(wxT("unexpected result of DosWaitThread")); } if ( IsMain() ) { // event processing - needed if we are the main thread // to give other threads a chance to do remaining GUI // processing and terminate cleanly. wxTheApp->HandleSockets(); if (wxTheApp->Pending()) if ( !wxTheApp->DoMessage() ) { // WM_QUIT received: kill the thread Kill(); return wxTHREAD_KILLED; } else wxUsleep(10); } else wxUsleep(10); } while ( result != NO_ERROR ); #else // !wxUSE_GUI // simply wait for the thread to terminate // // OTOH, even console apps create windows (in wxExecute, for WinSock // &c), so may be use MsgWaitForMultipleObject() too here? if ( ::DosWaitThread(&hThread, DCWW_WAIT) != NO_ERROR ) { wxFAIL_MSG(wxT("unexpected result of DosWaitThread")); } #endif // wxUSE_GUI/!wxUSE_GUI if ( IsMain() ) { gs_bWaitingForThread = false; } } #if 0 // although the thread might be already in the EXITED state it might not // have terminated yet and so we are not sure that it has actually // terminated if the "if" above hadn't been taken do { if ( !::GetExitCodeThread(hThread, (LPDWORD)&rc) ) { wxLogLastError(wxT("GetExitCodeThread")); rc = (ExitCode)-1; } } while ( (DWORD)rc == STILL_ACTIVE ); #endif if ( IsDetached() ) { // if the thread exits normally, this is done in WinThreadStart, but in // this case it would have been too early because // MsgWaitForMultipleObject() would fail if the thread handle was // closed while we were waiting on it, so we must do it here delete this; } if ( pRc ) *pRc = rc; return rc == (ExitCode)-1 ? wxTHREAD_MISC_ERROR : wxTHREAD_NO_ERROR; }
void locapi_pi::SetInterval( int interval ) { m_interval = interval; if ( IsRunning() ) // Timer started? Start( m_interval, wxTIMER_CONTINUOUS ); // restart timer with new interval }
bool IsRunningInCurrentThread() { return IsRunning() && IsCPUThread(); }
task<bool> SandboxJSExecutor::ConnectAsync(std::shared_ptr<SandboxEndpoint> endpoint, const std::function<void(std::string)>& errorCallback) { m_errorCallback = std::move(errorCallback); auto t = task_from_result(); return t.then([=]() -> bool { int retryCount = ConnectRetryCount; while (true) { try { cancellation_token_source timer_cts; auto timeoutT = create_delayed_task(std::chrono::milliseconds(ConnectTimeoutMilliseconds), [=]() -> string { throw std::runtime_error("timeout"); }, timer_cts.get_token()); if (!IsConnected()) { try { m_sandboxEndpoint = nullptr; } catch (std::exception& /*e*/) { // Don't care what happens with the old client at this point } // TODO: Pass as param m_sandboxEndpoint = endpoint; m_sandboxEndpoint->RegisterReplyHandler([this](int64_t replyId) { OnReplyMessage(replyId); }); m_sandboxEndpoint->RegisterNativeModuleCallHandler([this](folly::dynamic&& calls) { OnNativeModuleCallMessage(std::move(calls)); }); if (m_sandboxEndpoint->Start(EndpointType::Host)) { SetState(State::Connected); timer_cts.cancel(); } } else { PrepareJavaScriptRuntimeAsync().then([=](bool success) { if (success) { SetState(State::Running); timer_cts.cancel(); } else { SetState(State::Error); } }); } auto status = timeoutT.wait(); if (status != canceled) { throw new std::exception("Timeout"); } if (IsRunning()) { return true; } } catch (std::exception& /*e*/) { retryCount--; if (retryCount == 0) { m_errorCallback(IsConnected() ? "Timeout: preparing JS runtime" : "Timeout: Failed to connect to dev server"); SetState(State::Error); return false; } } } }); }
ZoneLaunch::~ZoneLaunch() { if(IsRunning()) s_running--; }
//============================================================================== int COptoTrack::SetSensors( int nSensorsToSet, tSensorInfo * atSensorInfo ){ int i; int iPortSensor, iPortSensorPrev; int iPort, iPortPrev; int iSensorRead; if( IsRunning() ) { CP_printf("Cannot set sensors. Tracker is active!\n"); return 1; } if( nSensorsToSet < 1 || nSensorsToSet > N_SENSORS_MAX ){ CP_printf("Cannot set sensors. Number of sensors is out of range: %d\n", nSensorsToSet); return 1; } // reset to zero m_nSensorsToRead = 0; m_nSensorsToWrite = 0; ZeroMemory(m_atSensorState, sizeof(m_atSensorState) ); iPortSensorPrev = -1; iPortPrev = -1; for( i = 0; i < nSensorsToSet; i++) { iPort = atSensorInfo[i].iPort; if( iPort < iPortPrev ) { CP_printf("Cannot set sensors. Ports should be ordered.\n"); return 1; } if( iPort > iPortPrev ) { iPortSensorPrev = -1; } iPortSensor = atSensorInfo[i].iSensor; // incoming sensors start from 0 if( iPortSensor <= iPortSensorPrev ) { CP_printf("Cannot set sensors. Sensors should be ordered.\n"); return 1; } // Check sensor for valid range if( iPortSensor < 0 || iPortSensor >= N_SENSORS_AT_PORT_MAX ){ CP_printf("Cannot set sensors. Sensor out of range: %d\n", iPortSensor ); return 1; } iPortSensorPrev = iPortSensor; m_atSensorState[i].iSensor = iPortSensor; m_atSensorState[i].iPort = iPort; } // Optotrak cannot setup sensors individually. If we want say // sensor #3 at port #2 we need to include sensors #1,#2, and #3 // So we mark #3 as useful and ignore the others // Calc N sensors at each port ZeroMemory(m_anSensorsPerPort, sizeof(m_anSensorsPerPort)); // The settings are ordered by port/sensor, // so in the sequence the last sensor for the port // has the largest sensor # for( i = 0; i<nSensorsToSet; i++){ iPort = m_atSensorState[i].iPort; iPortSensor = m_atSensorState[i].iSensor; m_anSensorsPerPort[iPort] = iPortSensor+1; } // Mark sensors that should be saved ZeroMemory(m_aiWriteFlag, sizeof(m_aiWriteFlag)); for( i = 0; i<nSensorsToSet; i++){ // for each sensor to be written // find the port/sensor combination in the read buffer sequence // and set the write flag iSensorRead = 0; for( iPort = 0; iPort<N_PORTS; iPort++){ for(iPortSensor = 0; iPortSensor<m_anSensorsPerPort[iPort]; iPortSensor++){ if( ( iPort == atSensorInfo[i].iPort) && (iPortSensor == atSensorInfo[i].iSensor ) ){ m_aiWriteFlag[iSensorRead] = 1; } iSensorRead++; } } } // Calc total number of sensors to read m_nSensorsToRead = 0; for( iPort = 0; iPort<N_PORTS; iPort++){ m_nSensorsToRead += m_anSensorsPerPort[iPort]; } m_nSensorsToWrite = nSensorsToSet; CP_printf("Sensors set:\n"); for( i = 0; i<nSensorsToSet; i++){ CP_printf("Port: %d, Sensor: %d\n", m_atSensorState[i].iPort+1, m_atSensorState[i].iSensor+1); } CP_printf("Total %d (%d) sensors to acquire.\n", m_nSensorsToWrite, m_nSensorsToRead ); return 0; }
bool WinWindow::Start() { RETURN_FALSE_IF_FALSE(IWindow::Start()); // Main message loop: MSG msg; HACCEL hAccelTable = nullptr; mWatch.Start(); while (1) { if (!PeekMessage(&msg, nullptr, 0, 0, PM_REMOVE)) { if (IsRunning()) { // Get current time tick. //mNow= PerformanceCounter::Ticks(); mWatch.Shot(); float dt = mWatch.ElapsedSeconds(); // If it's the time to draw next frame, draw it, else sleep a while. if (dt >= Application::Instance().FrameIntervalSeconds()) { mWatch.Go(); if (!Application::Instance().UpdateAndDraw(dt)) { break; } } else { Sleep(1); } } else if (IsDone()) { break; //quit } else { Sleep(1); //not active } } else { if (WM_QUIT == msg.message) { // Quit message loop break; } if (hAccelTable == nullptr || !TranslateAccelerator(msg.hwnd, hAccelTable, &msg)) { TranslateMessage(&msg); DispatchMessage(&msg); } } } return (int)msg.wParam >= 0; }