bool EventDispatcher::DispatchSDLEvent(const SDL_Event &event) { switch (event.type) { case SDL_KEYDOWN: return Dispatch(KeyboardEvent(KeyboardEvent::KEY_DOWN, KeySym(event.key.keysym.sym, SDL_Keymod(event.key.keysym.mod)), event.key.repeat)); case SDL_KEYUP: return Dispatch(KeyboardEvent(KeyboardEvent::KEY_UP, KeySym(event.key.keysym.sym, SDL_Keymod(event.key.keysym.mod)), event.key.repeat)); case SDL_TEXTINPUT: Uint32 unicode; Text::utf8_decode_char(&unicode, event.text.text); return Dispatch(TextInputEvent(unicode)); case SDL_MOUSEWHEEL: return Dispatch(MouseWheelEvent(event.wheel.y > 0 ? MouseWheelEvent::WHEEL_UP : MouseWheelEvent::WHEEL_DOWN, m_lastMousePosition)); case SDL_MOUSEBUTTONDOWN: return Dispatch(MouseButtonEvent(MouseButtonEvent::BUTTON_DOWN, MouseButtonFromSDLButton(event.button.button), Point(event.button.x,event.button.y))); case SDL_MOUSEBUTTONUP: return Dispatch(MouseButtonEvent(MouseButtonEvent::BUTTON_UP, MouseButtonFromSDLButton(event.button.button), Point(event.button.x,event.button.y))); case SDL_MOUSEMOTION: return Dispatch(MouseMotionEvent(Point(event.motion.x,event.motion.y), Point(event.motion.xrel, event.motion.yrel))); case SDL_JOYAXISMOTION: // SDL joystick axis value is documented to have the range -32768 to 32767 // unfortunately this places the centre at -0.5, not at zero, which is clearly nuts... // so since that doesn't make any sense, we assume the range is *actually* -32767 to +32767, // and scale it accordingly, clamping the output so that if we *do* get -32768, it turns into -1 return Dispatch(JoystickAxisMotionEvent(event.jaxis.which, Clamp(event.jaxis.value * (1.0f / 32767.0f), -1.0f, 1.0f), event.jaxis.axis)); case SDL_JOYHATMOTION: return Dispatch(JoystickHatMotionEvent(event.jhat.which, JoystickHatMotionEvent::JoystickHatDirection(event.jhat.value), event.jhat.hat)); case SDL_JOYBUTTONDOWN: return Dispatch(JoystickButtonEvent(event.jbutton.which, JoystickButtonEvent::BUTTON_DOWN, event.jbutton.button)); case SDL_JOYBUTTONUP: return Dispatch(JoystickButtonEvent(event.jbutton.which, JoystickButtonEvent::BUTTON_UP, event.jbutton.button)); } return false; }
void BenchmarkPlayback::InputExhausted() { RefPtr<Benchmark> ref(mMainThreadState); Dispatch(NS_NewRunnableFunction([this, ref]() { MOZ_ASSERT(OnThread()); if (mFinished || mSampleIndex >= mSamples.Length()) { return; } mDecoder->Input(mSamples[mSampleIndex]); mSampleIndex++; if (mSampleIndex == mSamples.Length()) { if (ref->mParameters.mStopAtFrame) { mSampleIndex = 0; } else { mDecoder->Drain(); } } })); }
void Monitor_Start(RingBuffer *inputBuffer) { dGuard(inputBuffer == NULL); OpenConsole(); PrintLogo(Console); while (1) { uint16_t read = ReadLineInto(inputBuffer); StreamWriter_WriteLine(Console, inputBuffer->Buffer, read); if (!Dispatch(inputBuffer, Console)) break; } StreamWriter_WriteLine(Console, "Bye.", 4); Stream_Close(Console); Console = NULL; }
int Decode(int index, uint8_t bytes[]) { Instruction instruction = DecodeInstruction(bytes[index]); AddressingMode addressingMode = DecodeAddressingMode(bytes[index]); /* * Exceptions: * STX: * ZeroPageX -> ZeroPageY * LDX: * ZeroPageX -> ZeroPageY * AbsoluteX -> AbsoluteY */ if ((instruction == STX || instruction == LDX) && addressingMode == ZeroPageX) addressingMode = ZeroPageY; if (instruction == LDX && addressingMode == AbsoluteX) addressingMode = AbsoluteY; Dispatch(instruction, addressingMode, index, bytes); return FindInstructionLength(addressingMode); }
void BenchmarkPlayback::InitDecoder(TrackInfo&& aInfo) { MOZ_ASSERT(OnThread()); RefPtr<PDMFactory> platform = new PDMFactory(); mDecoder = platform->CreateDecoder(aInfo, mDecoderTaskQueue, this); if (!mDecoder) { MainThreadShutdown(); return; } RefPtr<Benchmark> ref(mMainThreadState); mDecoder->Init()->Then( ref->Thread(), __func__, [this, ref](TrackInfo::TrackType aTrackType) { Dispatch(NS_NewRunnableFunction([this, ref]() { InputExhausted(); })); }, [this, ref](MediaDataDecoder::DecoderFailureReason aReason) { MainThreadShutdown(); }); }
void VSTPlugin::Create(VSTPlugin *plug) { h_dll=plug->h_dll; _pEffect=plug->_pEffect; _pEffect->user=this; Dispatch( effMainsChanged, 0, 1, NULL, 0.0f); // strcpy(_editName,plug->_editName); On current implementation, this replaces the right one. strcpy(_sProductName,plug->_sProductName); strcpy(_sVendorName,plug->_sVendorName); _sDllName = new char[strlen(plug->_sDllName)+1]; strcpy(_sDllName,plug->_sDllName); _isSynth=plug->_isSynth; _version=plug->_version; plug->instantiated=false; // We are "stoling" the plugin from the "plug" object so this // is just a "trick" so that when destructing the "plug", it // doesn't unload the Dll. instantiated=true; }
void CacheStorageService::OnMemoryConsumptionChange(CacheMemoryConsumer* aConsumer, uint32_t aCurrentMemoryConsumption) { LOG(("CacheStorageService::OnMemoryConsumptionChange [consumer=%p, size=%u]", aConsumer, aCurrentMemoryConsumption)); uint32_t savedMemorySize = aConsumer->mReportedMemoryConsumption; if (savedMemorySize == aCurrentMemoryConsumption) return; // Exchange saved size with current one. aConsumer->mReportedMemoryConsumption = aCurrentMemoryConsumption; mMemorySize -= savedMemorySize; mMemorySize += aCurrentMemoryConsumption; LOG((" mMemorySize=%u (+%u,-%u)", uint32_t(mMemorySize), aCurrentMemoryConsumption, savedMemorySize)); // Bypass purging when memory has not grew up significantly if (aCurrentMemoryConsumption <= savedMemorySize) return; if (mPurging) { LOG((" already purging")); return; } if (mMemorySize <= CacheObserver::MemoryLimit()) return; // Throw the oldest data or whole entries away when over certain limits mPurging = true; // Must always dipatch, since this can be called under e.g. a CacheFile's lock. nsCOMPtr<nsIRunnable> event = NS_NewRunnableMethod(this, &CacheStorageService::PurgeOverMemoryLimit); Dispatch(event); }
void BenchmarkPlayback::Output(MediaData* aData) { RefPtr<Benchmark> ref(mMainThreadState); Dispatch(NS_NewRunnableFunction([this, ref]() { mFrameCount++; if (mFrameCount == ref->mParameters.mStartupFrame) { mDecodeStartTime = TimeStamp::Now(); } int32_t frames = mFrameCount - ref->mParameters.mStartupFrame; TimeDuration elapsedTime = TimeStamp::Now() - mDecodeStartTime; if (!mFinished && (frames == ref->mParameters.mFramesToMeasure || elapsedTime >= ref->mParameters.mTimeout)) { uint32_t decodeFps = frames / elapsedTime.ToSeconds(); MainThreadShutdown(); ref->Dispatch(NS_NewRunnableFunction([ref, decodeFps]() { ref->ReturnResult(decodeFps); })); } })); }
bool ProcessEvents() { // process pending wx events first as they correspond to low-level events // which happened before, i.e. typically pending events were queued by a // previous call to Dispatch() and if we didn't process them now the next // call to it might enqueue them again (as happens with e.g. socket events // which would be generated as long as there is input available on socket // and this input is only removed from it when pending event handlers are // executed) if( wxTheApp ) { wxTheApp->ProcessPendingEvents(); // One of the pending event handlers could have decided to exit the // loop so check for the flag before trying to dispatch more events // (which could block indefinitely if no more are coming). if( m_shouldExit ) return false; } return Dispatch(); }
nsresult nsSocketTransportService::DetachSocket(SocketContext *listHead, SocketContext *sock) { SOCKET_LOG(("nsSocketTransportService::DetachSocket [handler=%p]\n", sock->mHandler)); MOZ_ASSERT((listHead == mActiveList) || (listHead == mIdleList), "DetachSocket invalid head"); // inform the handler that this socket is going away sock->mHandler->OnSocketDetached(sock->mFD); mSentBytesCount += sock->mHandler->ByteCountSent(); mReceivedBytesCount += sock->mHandler->ByteCountReceived(); // cleanup sock->mFD = nullptr; NS_RELEASE(sock->mHandler); if (listHead == mActiveList) RemoveFromPollList(sock); else RemoveFromIdleList(sock); // NOTE: sock is now an invalid pointer // // notify the first element on the pending socket queue... // nsCOMPtr<nsIRunnable> event; LinkedRunnableEvent *runnable = mPendingSocketQueue.getFirst(); if (runnable) { event = runnable->TakeEvent(); runnable->remove(); delete runnable; } if (event) { // move event from pending queue to dispatch queue return Dispatch(event, NS_DISPATCH_NORMAL); } return NS_OK; }
void ConnectionHandler::DispatchIfCan() { if (reading_status_ == ReadingStatus::Length && socket_buffer_.used() >= sizeof(UInt32)) { UInt32Bytes length{}; socket_buffer_.read(length.bytes, sizeof(UInt32)); current_message_length = length.number; // set reading status to next reading_status_ = ReadingStatus::OpCode; } if (reading_status_ == ReadingStatus::OpCode && socket_buffer_.used() >= sizeof(UInt32)) { UInt32Bytes opcode{}; socket_buffer_.read(opcode.bytes, sizeof(UInt32)); // initialize current message with the opcode current_message_ = Message{opcode.number}; // set reading status to data reading_status_ = ReadingStatus::Data; } if (reading_status_ == ReadingStatus::Data && socket_buffer_.used() >= current_message_length) { // initialize the vector for the data current_message_.data_vector().clear(); current_message_.data_vector().resize(current_message_length); socket_buffer_.read(current_message_.data(), current_message_length); // dispatch message Dispatch(current_message_); // set reading status back to length reading_status_ = ReadingStatus::Length; // if there is data in the buffer and we read the whole // packet, launch socket readable once more if (socket_buffer_.used() > sizeof(UInt32)) { DispatchIfCan(); } } }
void LazyIdleThread::EnableIdleTimeout() { ASSERT_OWNING_THREAD(); if (mIdleTimeoutEnabled) { return; } mIdleTimeoutEnabled = true; { MutexAutoLock lock(mMutex); MOZ_ASSERT(mPendingEventCount, "Mismatched calls to observer methods!"); --mPendingEventCount; } if (mThread) { nsCOMPtr<nsIRunnable> runnable(new nsRunnable()); if (NS_FAILED(Dispatch(runnable, NS_DISPATCH_NORMAL))) { NS_WARNING("Failed to dispatch!"); } } }
void Shape::Render(const char *path){ if(geom_ == NULL) return; cairo_surface_t *surface = cairo_ps_surface_create(path, width_, height_); if(cairo_surface_status(surface) != CAIRO_STATUS_SUCCESS) { std::cout << cairo_status_to_string(cairo_surface_status(surface)) << std::endl; exit(1); return; } ctx_ = cairo_create(surface); OGREnvelope env; geom_->getEnvelope(&env); cairo_matrix_t mat; matrix_init(&mat, width_, height_, &env); cairo_set_matrix(ctx_, &mat); Dispatch(geom_); cairo_show_page(ctx_); cairo_destroy(ctx_); cairo_surface_destroy(surface); }
//*================================================================================= //*原型: void ProcessRequest(SOCKET hSocket) //*功能: 处理客户机的请求 //*参数: 无 //*返回: 无 //*说明: 先读入包头, 再读包数据, 然后再处理请求 //*================================================================================= void TSmartOutThread::ProcessRequest(SOCKET hSocket, SOCKADDR_IN *psockAddr) { TSmartPacket Packet; try { if( ReadRequestPacket(hSocket, Packet) ) { if( CheckPacket(psockAddr, Packet) ) { Dispatch(hSocket, psockAddr, Packet); } } } catch(TException& e) { WriteLog(e.GetText()); } catch(...) { WriteLog("客户服务线程有未知异常!"); } }
bool wxGUIEventLoop::YieldFor(long eventsToProcess) { #if wxUSE_THREADS // Yielding from a non-gui thread needs to bail out, otherwise we end up // possibly sending events in the thread too. if ( !wxThread::IsMain() ) { return true; } #endif // wxUSE_THREADS m_isInsideYield = true; m_eventsToProcessInsideYield = eventsToProcess; #if wxUSE_LOG // disable log flushing from here because a call to wxYield() shouldn't // normally result in message boxes popping up &c wxLog::Suspend(); #endif // wxUSE_LOG // process all pending events: while ( Pending() ) Dispatch(); // it's necessary to call ProcessIdle() to update the frames sizes which // might have been changed (it also will update other things set from // OnUpdateUI() which is a nice (and desired) side effect) while ( ProcessIdle() ) {} #if wxUSE_LOG wxLog::Resume(); #endif // wxUSE_LOG m_isInsideYield = false; return true; }
bool wxGUIEventLoop::YieldFor(long eventsToProcess) { #if wxUSE_THREADS if ( !wxThread::IsMain() ) return true; // can't process events from other threads #endif // wxUSE_THREADS m_isInsideYield = true; m_eventsToProcessInsideYield = eventsToProcess; #if wxUSE_LOG wxLog::Suspend(); #endif // wxUSE_LOG // TODO: implement event filtering using the eventsToProcess mask // process all pending events: while ( Pending() ) Dispatch(); // handle timers, sockets etc. OnNextIteration(); // it's necessary to call ProcessIdle() to update the frames sizes which // might have been changed (it also will update other things set from // OnUpdateUI() which is a nice (and desired) side effect) while ( ProcessIdle() ) {} #if wxUSE_LOG wxLog::Resume(); #endif // wxUSE_LOG m_isInsideYield = false; return true; }
/* doSchedule() will do a Task Switch to a high priority task * in ready state.It don't care wether OSCurTask are * Preemptable or not,or INVALID_TASK. * Note OSCurTsk also may be the highest priority Task in READY state. * in ready or running state*/ void doSchedule(void) { /* The Situation that when the SEVERAL_TASKS_PER_PRIORITY Policy was adopted, * there may be a task or more with the same xPriority as OSCurTsk in the * ready state*/ if(OSCurTsk == OSHighRdyTsk) { /* higher priority task in ready or running state */ /* Search the table map to find OSHighPriority*/ OS_ENTER_CRITICAL(); #if (cfgOS_TASK_PER_PRIORITY == SEVERAL_TASKS_PER_PRIORITY) if(listTskRdyIsEmpty(OSCurTcb->xPriority)) { /* if OSTskRdyListHead[xPriority] is Empty, */ #endif /* Find out an Runnable Task */ OSHighRdyPrio = tableRdyMapFindHighPriority(); #if (cfgOS_TASK_PER_PRIORITY == SEVERAL_TASKS_PER_PRIORITY) } /* if OSTcbRdyGrpList[xPriority] is not Empty, */ #endif /* make the head task runnable */ /* Get The Tcb with the highest Priority*/ OSHighRdyTsk = listGetRdyTsk(OSHighRdyPrio); OSHighRdyTcb = &OSTcbTable[OSHighRdyTsk]; OS_EXIT_CRITICAL(); } Dispatch(); }
int main(int argc, char *argv[], char *envp[]) #endif { int i; HWEventQueueType alwaysCheckForInput[2]; display = "0"; InitRegions(); CheckUserParameters(argc, argv, envp); CheckUserAuthorization(); InitConnectionLimits(); ProcessCommandLine(argc, argv); alwaysCheckForInput[0] = 0; alwaysCheckForInput[1] = 1; while (1) { serverGeneration++; ScreenSaverTime = defaultScreenSaverTime; ScreenSaverInterval = defaultScreenSaverInterval; ScreenSaverBlanking = defaultScreenSaverBlanking; ScreenSaverAllowExposures = defaultScreenSaverAllowExposures; #ifdef DPMSExtension DPMSStandbyTime = DPMSSuspendTime = DPMSOffTime = ScreenSaverTime; DPMSEnabled = TRUE; DPMSPowerLevel = 0; #endif InitBlockAndWakeupHandlers(); /* Perform any operating system dependent initializations you'd like */ OsInit(); if (serverGeneration == 1) { CreateWellKnownSockets(); for (i = 1; i < MAXCLIENTS; i++) clients[i] = NullClient; serverClient = calloc(sizeof(ClientRec), 1); if (!serverClient) FatalError("couldn't create server client"); InitClient(serverClient, 0, (pointer) NULL); } else ResetWellKnownSockets(); clients[0] = serverClient; currentMaxClients = 1; /* Initialize privates before first allocation */ dixResetPrivates(); /* Initialize server client devPrivates, to be reallocated as * more client privates are registered */ if (!dixAllocatePrivates(&serverClient->devPrivates, PRIVATE_CLIENT)) FatalError("failed to create server client privates"); if (!InitClientResources(serverClient)) /* for root resources */ FatalError("couldn't init server resources"); SetInputCheck(&alwaysCheckForInput[0], &alwaysCheckForInput[1]); screenInfo.numScreens = 0; InitAtoms(); InitEvents(); InitSelections(); InitGlyphCaching(); dixResetRegistry(); ResetFontPrivateIndex(); InitCallbackManager(); InitOutput(&screenInfo, argc, argv); if (screenInfo.numScreens < 1) FatalError("no screens found"); InitExtensions(argc, argv); for (i = 0; i < screenInfo.numGPUScreens; i++) { ScreenPtr pScreen = screenInfo.gpuscreens[i]; if (!CreateScratchPixmapsForScreen(pScreen)) FatalError("failed to create scratch pixmaps"); } for (i = 0; i < screenInfo.numScreens; i++) { ScreenPtr pScreen = screenInfo.screens[i]; if (!CreateScratchPixmapsForScreen(pScreen)) FatalError("failed to create scratch pixmaps"); if (pScreen->CreateScreenResources && !(*pScreen->CreateScreenResources) (pScreen)) FatalError("failed to create screen resources"); if (!CreateGCperDepth(i)) FatalError("failed to create scratch GCs"); if (!CreateDefaultStipple(i)) FatalError("failed to create default stipple"); if (!CreateRootWindow(pScreen)) FatalError("failed to create root window"); } InitFonts(); if (SetDefaultFontPath(defaultFontPath) != Success) { ErrorF("[dix] failed to set default font path '%s'", defaultFontPath); } if (!SetDefaultFont(defaultTextFont)) { FatalError("could not open default font '%s'", defaultTextFont); } if (!(rootCursor = CreateRootCursor(NULL, 0))) { FatalError("could not open default cursor font '%s'", defaultCursorFont); } #ifdef DPMSExtension /* check all screens, looking for DPMS Capabilities */ DPMSCapableFlag = DPMSSupported(); if (!DPMSCapableFlag) DPMSEnabled = FALSE; #endif #ifdef PANORAMIX /* * Consolidate window and colourmap information for each screen */ if (!noPanoramiXExtension) PanoramiXConsolidate(); #endif for (i = 0; i < screenInfo.numScreens; i++) InitRootWindow(screenInfo.screens[i]->root); InitCoreDevices(); InitInput(argc, argv); InitAndStartDevices(); ReserveClientIds(serverClient); dixSaveScreens(serverClient, SCREEN_SAVER_FORCER, ScreenSaverReset); #ifdef PANORAMIX if (!noPanoramiXExtension) { if (!PanoramiXCreateConnectionBlock()) { FatalError("could not create connection block info"); } } else #endif { if (!CreateConnectionBlock()) { FatalError("could not create connection block info"); } } #ifdef XQUARTZ /* Let the other threads know the server is done with its init */ pthread_mutex_lock(&serverRunningMutex); serverRunning = TRUE; pthread_cond_broadcast(&serverRunningCond); pthread_mutex_unlock(&serverRunningMutex); #endif NotifyParentProcess(); Dispatch(); #ifdef XQUARTZ /* Let the other threads know the server is no longer running */ pthread_mutex_lock(&serverRunningMutex); serverRunning = FALSE; pthread_mutex_unlock(&serverRunningMutex); #endif UndisplayDevices(); DisableAllDevices(); /* Now free up whatever must be freed */ if (screenIsSaved == SCREEN_SAVER_ON) dixSaveScreens(serverClient, SCREEN_SAVER_OFF, ScreenSaverReset); FreeScreenSaverTimer(); CloseDownExtensions(); #ifdef PANORAMIX { Bool remember_it = noPanoramiXExtension; noPanoramiXExtension = TRUE; FreeAllResources(); noPanoramiXExtension = remember_it; } #else FreeAllResources(); #endif CloseInput(); for (i = 0; i < screenInfo.numScreens; i++) screenInfo.screens[i]->root = NullWindow; CloseDownDevices(); CloseDownEvents(); for (i = screenInfo.numGPUScreens - 1; i >= 0; i--) { ScreenPtr pScreen = screenInfo.gpuscreens[i]; FreeScratchPixmapsForScreen(pScreen); (*pScreen->CloseScreen) (pScreen); dixFreePrivates(pScreen->devPrivates, PRIVATE_SCREEN); free(pScreen); screenInfo.numGPUScreens = i; } for (i = screenInfo.numScreens - 1; i >= 0; i--) { FreeScratchPixmapsForScreen(screenInfo.screens[i]); FreeGCperDepth(i); FreeDefaultStipple(i); dixFreeScreenSpecificPrivates(screenInfo.screens[i]); (*screenInfo.screens[i]->CloseScreen) (screenInfo.screens[i]); dixFreePrivates(screenInfo.screens[i]->devPrivates, PRIVATE_SCREEN); free(screenInfo.screens[i]); screenInfo.numScreens = i; } ReleaseClientIds(serverClient); dixFreePrivates(serverClient->devPrivates, PRIVATE_CLIENT); serverClient->devPrivates = NULL; FreeFonts(); FreeAuditTimer(); if (dispatchException & DE_TERMINATE) { CloseWellKnownConnections(); } OsCleanup((dispatchException & DE_TERMINATE) != 0); if (dispatchException & DE_TERMINATE) { ddxGiveUp(EXIT_NO_ERROR); break; } free(ConnectionInfo); ConnectionInfo = NULL; } return 0; }
void BenchmarkPlayback::Error() { RefPtr<Benchmark> ref(mMainThreadState); Dispatch(NS_NewRunnableFunction([this, ref]() { MainThreadShutdown(); })); }
NS_IMETHODIMP nsSocketTransportService::Run() { SOCKET_LOG(("STS thread init %d sockets\n", gMaxCount)); psm::InitializeSSLServerCertVerificationThreads(); gSocketThread = PR_GetCurrentThread(); { MutexAutoLock lock(mLock); mPollableEvent.reset(new PollableEvent()); // // NOTE: per bug 190000, this failure could be caused by Zone-Alarm // or similar software. // // NOTE: per bug 191739, this failure could also be caused by lack // of a loopback device on Windows and OS/2 platforms (it creates // a loopback socket pair on these platforms to implement a pollable // event object). if we can't create a pollable event, then we'll // have to "busy wait" to implement the socket event queue :-( // if (!mPollableEvent->Valid()) { mPollableEvent = nullptr; NS_WARNING("running socket transport thread without a pollable event"); SOCKET_LOG(("running socket transport thread without a pollable event")); } mPollList[0].fd = mPollableEvent ? mPollableEvent->PollableFD() : nullptr; mPollList[0].in_flags = PR_POLL_READ | PR_POLL_EXCEPT; mPollList[0].out_flags = 0; } mRawThread = NS_GetCurrentThread(); // hook ourselves up to observe event processing for this thread nsCOMPtr<nsIThreadInternal> threadInt = do_QueryInterface(mRawThread); threadInt->SetObserver(this); // make sure the pseudo random number generator is seeded on this thread srand(static_cast<unsigned>(PR_Now())); // For the calculation of the duration of the last cycle (i.e. the last for-loop // iteration before shutdown). TimeStamp startOfCycleForLastCycleCalc; int numberOfPendingEventsLastCycle; // For measuring of the poll iteration duration without time spent blocked // in poll(). TimeStamp pollCycleStart; // Time blocked in poll(). TimeDuration singlePollDuration; // For calculating the time needed for a new element to run. TimeStamp startOfIteration; TimeStamp startOfNextIteration; int numberOfPendingEvents; // If there is too many pending events queued, we will run some poll() // between them and the following variable is cumulative time spent // blocking in poll(). TimeDuration pollDuration; for (;;) { bool pendingEvents = false; numberOfPendingEvents = 0; numberOfPendingEventsLastCycle = 0; if (mTelemetryEnabledPref) { startOfCycleForLastCycleCalc = TimeStamp::NowLoRes(); startOfNextIteration = TimeStamp::NowLoRes(); } pollDuration = 0; do { if (mTelemetryEnabledPref) { pollCycleStart = TimeStamp::NowLoRes(); } DoPollIteration(&singlePollDuration); if (mTelemetryEnabledPref && !pollCycleStart.IsNull()) { Telemetry::Accumulate(Telemetry::STS_POLL_BLOCK_TIME, singlePollDuration.ToMilliseconds()); Telemetry::AccumulateTimeDelta( Telemetry::STS_POLL_CYCLE, pollCycleStart + singlePollDuration, TimeStamp::NowLoRes()); pollDuration += singlePollDuration; } mRawThread->HasPendingEvents(&pendingEvents); if (pendingEvents) { if (!mServingPendingQueue) { nsresult rv = Dispatch(NewRunnableMethod(this, &nsSocketTransportService::MarkTheLastElementOfPendingQueue), nsIEventTarget::DISPATCH_NORMAL); if (NS_FAILED(rv)) { NS_WARNING("Could not dispatch a new event on the " "socket thread."); } else { mServingPendingQueue = true; } if (mTelemetryEnabledPref) { startOfIteration = startOfNextIteration; // Everything that comes after this point will // be served in the next iteration. If no even // arrives, startOfNextIteration will be reset at the // beginning of each for-loop. startOfNextIteration = TimeStamp::NowLoRes(); } } TimeStamp eventQueueStart = TimeStamp::NowLoRes(); do { NS_ProcessNextEvent(mRawThread); numberOfPendingEvents++; pendingEvents = false; mRawThread->HasPendingEvents(&pendingEvents); } while (pendingEvents && mServingPendingQueue && ((TimeStamp::NowLoRes() - eventQueueStart).ToMilliseconds() < mMaxTimePerPollIter)); if (mTelemetryEnabledPref && !mServingPendingQueue && !startOfIteration.IsNull()) { Telemetry::AccumulateTimeDelta( Telemetry::STS_POLL_AND_EVENTS_CYCLE, startOfIteration + pollDuration, TimeStamp::NowLoRes()); Telemetry::Accumulate( Telemetry::STS_NUMBER_OF_PENDING_EVENTS, numberOfPendingEvents); numberOfPendingEventsLastCycle += numberOfPendingEvents; numberOfPendingEvents = 0; pollDuration = 0; } } } while (pendingEvents); bool goingOffline = false; // now that our event queue is empty, check to see if we should exit { MutexAutoLock lock(mLock); if (mShuttingDown) { if (mTelemetryEnabledPref && !startOfCycleForLastCycleCalc.IsNull()) { Telemetry::Accumulate( Telemetry::STS_NUMBER_OF_PENDING_EVENTS_IN_THE_LAST_CYCLE, numberOfPendingEventsLastCycle); Telemetry::AccumulateTimeDelta( Telemetry::STS_POLL_AND_EVENT_THE_LAST_CYCLE, startOfCycleForLastCycleCalc, TimeStamp::NowLoRes()); } break; } if (mGoingOffline) { mGoingOffline = false; goingOffline = true; } } // Avoid potential deadlock if (goingOffline) Reset(true); } SOCKET_LOG(("STS shutting down thread\n")); // detach all sockets, including locals Reset(false); // Final pass over the event queue. This makes sure that events posted by // socket detach handlers get processed. NS_ProcessPendingEvents(mRawThread); gSocketThread = nullptr; psm::StopSSLServerCertVerificationThreads(); SOCKET_LOG(("STS thread exit\n")); return NS_OK; }
nsresult LazyIdleThread::ShutdownThread() { ASSERT_OWNING_THREAD(); // Before calling Shutdown() on the real thread we need to put a queue in // place in case a runnable is posted to the thread while it's in the // process of shutting down. This will be our queue. nsAutoTArray<nsCOMPtr<nsIRunnable>, 10> queuedRunnables; nsresult rv; if (mThread) { if (mShutdownMethod == AutomaticShutdown && NS_IsMainThread()) { nsCOMPtr<nsIObserverService> obs = mozilla::services::GetObserverService(); NS_WARN_IF_FALSE(obs, "Failed to get observer service!"); if (obs && NS_FAILED(obs->RemoveObserver(this, "xpcom-shutdown-threads"))) { NS_WARNING("Failed to remove observer!"); } } if (mIdleObserver) { mIdleObserver->Observe(static_cast<nsIThread*>(this), IDLE_THREAD_TOPIC, nullptr); } #ifdef DEBUG { MutexAutoLock lock(mMutex); MOZ_ASSERT(!mThreadIsShuttingDown, "Huh?!"); } #endif nsCOMPtr<nsIRunnable> runnable = NS_NewRunnableMethod(this, &LazyIdleThread::CleanupThread); NS_ENSURE_TRUE(runnable, NS_ERROR_FAILURE); PreDispatch(); rv = mThread->Dispatch(runnable, NS_DISPATCH_NORMAL); NS_ENSURE_SUCCESS(rv, rv); // Put the temporary queue in place before calling Shutdown(). mQueuedRunnables = &queuedRunnables; if (NS_FAILED(mThread->Shutdown())) { NS_ERROR("Failed to shutdown the thread!"); } // Now unset the queue. mQueuedRunnables = nullptr; mThread = nullptr; { MutexAutoLock lock(mMutex); MOZ_ASSERT(!mPendingEventCount, "Huh?!"); MOZ_ASSERT(!mIdleNotificationCount, "Huh?!"); MOZ_ASSERT(mThreadIsShuttingDown, "Huh?!"); mThreadIsShuttingDown = false; } } if (mIdleTimer) { rv = mIdleTimer->Cancel(); NS_ENSURE_SUCCESS(rv, rv); mIdleTimer = nullptr; } // If our temporary queue has any runnables then we need to dispatch them. if (queuedRunnables.Length()) { // If the thread manager has gone away then these runnables will never run. if (mShutdown) { NS_ERROR("Runnables dispatched to LazyIdleThread will never run!"); return NS_OK; } // Re-dispatch the queued runnables. for (uint32_t index = 0; index < queuedRunnables.Length(); index++) { nsCOMPtr<nsIRunnable> runnable; runnable.swap(queuedRunnables[index]); MOZ_ASSERT(runnable, "Null runnable?!"); if (NS_FAILED(Dispatch(runnable, NS_DISPATCH_NORMAL))) { NS_ERROR("Failed to re-dispatch queued runnable!"); } } } return NS_OK; }
void sys_Dispatch(struct pt_regs * regs, LONG adjust) { struct ExecBase * SysBase = (struct ExecBase *)*(ULONG *)0x04; /* Hmm, interrupts are nesting, not a good idea... */ // if(user_mode(regs)) { // return; // } #if 0 D(bug("In %s!!!\n",__FUNCTION__)); D(bug("lr_svc=%x, r0=%x, r1=%x, r2=%x, r9=%x, r12=%x, sp=%x, lr=%x, cpsr=%x\n", regs->lr_svc, regs->r0, regs->r1, regs->r2, regs->r9, regs->r12, regs->sp, regs->lr, regs->cpsr)); #endif /* Check if a task switch is necessary */ /* 1. There has to be another task in the ready-list */ /* 2. The first task in the ready list hast to have the same or higher priority than the currently active task */ if( SysBase->TaskReady.lh_Head->ln_Succ != NULL /* ((BYTE)SysBase->ThisTask->tc_Node.ln_Pri <= (BYTE)((struct Task *)SysBase->TaskReady.lh_Head)->tc_Node.ln_Pri ) */ ) { /* Check if task switch is possible */ if( SysBase->TDNestCnt < 0 ) { if( SysBase->ThisTask->tc_State == TS_RUN ) { SysBase->ThisTask->tc_State = TS_READY; Reschedule(SysBase->ThisTask); SysBase->AttnResched |= 0x8000; } else if( SysBase->ThisTask->tc_State == TS_REMOVED ) SysBase->AttnResched |= 0x8000; } else SysBase->AttnResched |= 0x80; } /* Has an interrupt told us to dispatch when leaving */ if (SysBase->AttnResched & 0x8000) { SysBase->AttnResched &= ~0x8000; /* Save registers for this task (if there is one...) */ if (SysBase->ThisTask && SysBase->ThisTask->tc_State != TS_REMOVED) { regs->lr_svc -= adjust; // adjust is 0 or -4 SaveRegs(SysBase->ThisTask, regs); } /* Tell exec that we have actually switched tasks... */ Dispatch (); //D(bug("DISPATCHER: New task: %s\n",SysBase->ThisTask->tc_Node.ln_Name)); /* Get the registers of the old task */ RestoreRegs(SysBase->ThisTask, regs); regs->lr_svc += adjust; // adjust is 0 or -4 /* Make sure that the state of the interrupts is what the task expects. */ if (SysBase->IDNestCnt < 0) SC_ENABLE(regs); else SC_DISABLE(regs); #if 0 D(bug("after: lr_svc=%x, r0=%x, r1=%x, r2=%x, r9=%x, r12=%x, sp=%x, lr=%x, cpsr=%x (adjust=%d)\n", regs->lr_svc, regs->r0, regs->r1, regs->r2, regs->r9, regs->r12, regs->sp, regs->lr, regs->cpsr, adjust)); #endif /* Ok, the next step is to either drop back to the new task, or give it its Exception() if it wants one... */ if (SysBase->ThisTask->tc_Flags & TF_EXCEPT) { Disable(); Exception(); Enable(); } } /* Leave the interrupt. */ }
int DoRun() { // we must ensure that OnExit() is called even if an exception is thrown // from inside ProcessEvents() 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( ; ; ) { // generate and process idle events for as long as we don't // have anything else to do while ( !m_shouldExit && !Pending() && ProcessIdle() ) ; if ( m_shouldExit ) break; // a message came or no more idle processing to do, dispatch // all the pending events and call Dispatch() to wait for the // next message if ( !ProcessEvents() ) { // we got WM_QUIT break; } } // Process the remaining queued messages, both at the level of the // underlying toolkit level (Pending/Dispatch()) and wx level // (Has/ProcessPendingEvents()). // // We do run the risk of never exiting this loop if pending event // handlers endlessly generate new events but they shouldn't do // this in a well-behaved program and we shouldn't just discard the // events we already have, they might be important. for( ; ; ) { bool hasMoreEvents = false; if ( wxTheApp && wxTheApp->HasPendingEvents() ) { wxTheApp->ProcessPendingEvents(); hasMoreEvents = true; } if ( Pending() ) { Dispatch(); hasMoreEvents = true; } if ( !hasMoreEvents ) 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; }
NS_IMETHODIMP WorkletThread::DispatchFromScript(nsIRunnable* aRunnable, uint32_t aFlags) { nsCOMPtr<nsIRunnable> runnable(aRunnable); return Dispatch(runnable.forget(), aFlags); }
int MakeMain::Run(int argc, char **argv, char **env) { char *p = getenv("MAKEFLAGS"); if (p) { Variable *v = new Variable("MAKEFLAGS", p, Variable::f_recursive, Variable::o_environ); *VariableContainer::Instance() += v; p = getenv("MAKEOVERRIDES"); if (p) { Variable *v = new Variable("MAKEOVERRIDES", p, Variable::f_recursive, Variable::o_environ); *VariableContainer::Instance() += v; } Eval r(v->GetValue(), false); std::string cmdLine = r.Evaluate(); Dispatch(cmdLine.c_str()); } if (!switchParser.Parse(&argc, argv) || help.GetValue() || help2.GetValue()) { Utils::banner(argv[0]); Utils::usage(argv[0], usageText); } if (dir.GetValue().size()) { cwd = OS::GetWorkingDir(); if (!OS::SetWorkingDir(dir.GetValue())) { std::cout << "Cannot set working dir to: " << dir.GetValue() << std::endl; return 2; } } if (printDir.GetValue()) { std::cout << OS::GetWorkingDir() << std::endl; } if (cancelKeep.GetValue()) { cancelKeep.SetValue(false); keepGoing.SetValue(false); } bool done = false; Eval::Init(); Eval::SetWarnings(warnUndef.GetValue()); while (!done && !Eval::GetErrCount()) { VariableContainer::Instance()->Clear(); RuleContainer::Instance()->Clear(); Include::Instance()->Clear(); Maker::ClearFirstGoal(); LoadEnvironment(env); LoadCmdDefines(); SetVariable("MAKE", argv[0], Variable::o_environ, false); Variable *v = VariableContainer::Instance()->Lookup("SHELL"); if (!v) { v = VariableContainer::Instance()->Lookup("COMSPEC"); if (!v) v = VariableContainer::Instance()->Lookup("ComSpec"); if (v) { std::string val = v->GetValue(); SetVariable("SHELL", val, Variable::o_environ, true); } } std::string goals; for (int i=1; i < argc; i++) { if (goals.size()) goals += " "; goals += argv[i]; } SetVariable("MAKECMDGOALS", goals, Variable::o_command_line, false); SetMakeFlags(); if (restarts) { std::strstream str; std::string temp; str << restarts; str >> temp; SetVariable("MAKE_RESTARTS", temp, Variable::o_command_line, false); } v = VariableContainer::Instance()->Lookup("MAKE_LEVEL"); if (!v) { SetVariable("MAKE_LEVEL", "0", Variable::o_environ, true); } else { std::strstream str; std::string temp; str << v->GetValue(); int n; str >> n; n++; str << n; str >> temp; v->SetValue(temp); } SetVariable(".FEATURES","second-expansion order-only target-specific", Variable::o_environ, false); SetVariable(".DEFAULT_GOAL","", Variable::o_environ, false); SetVariable(".INCLUDE_DIRS",includes.GetValue(), Variable::o_command_line, false); SetVariable("VPATH",includes.GetValue(), Variable::o_environ, false); SetInternalVars(); v = VariableContainer::Instance()->Lookup("MAKEFILES"); if (v) { v->SetExport(true); Include::Instance()->AddFileList(v->GetValue(), true, true); } Rule *rule = new Rule(".SUFFIXES", ".c .o .cpp .nas .asm", "", new Command("", 0), "", 0, false); RuleList *ruleList = new RuleList(".SUFFIXES"); ruleList->Add(rule, false); *RuleContainer::Instance() += ruleList; std::string files = specifiedFiles.GetValue(); if (!files.size()) files = "makefile"; Include::Instance()->AddFileList(files, false, false); SetupImplicit(); RuleContainer::Instance()->SecondaryEval(); done = !Include::Instance()->MakeMakefiles(silent.GetValue()); if (!done) restarts++; } if (showDatabase.GetValue()) ShowDatabase(); int rv = 0; if (Eval::GetErrCount()) { rv = 2; } else { bool xsilent = silent.GetValue(); bool xignore = ignoreErrors.GetValue(); bool xdontrun = displayOnly.GetValue(); bool xtouch = touch.GetValue(); xdontrun |= xtouch || query.GetValue(); xsilent |= xtouch || query.GetValue(); Maker maker(xsilent, xdontrun, xignore, xtouch, rebuild.GetValue(), newFiles.GetValue(), oldFiles.GetValue()); for (int i = 1; i < argc; i++) { maker.AddGoal(argv[i]); } if (maker.CreateDependencyTree()) { rv = maker.RunCommands(keepGoing.GetValue()); if (query.GetValue() && rv == 0) rv = maker.HasCommands() ? 1 : 0; } else { rv = 2; } } if (dir.GetValue().size()) { OS::SetWorkingDir(cwd); } if (printDir.GetValue()) { std::cout << OS::GetWorkingDir() << std::endl; } return rv; }
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Dispatch command //#pragma comment(lib, "ComCtl32.lib") HRESULT Dispatch(PTSTR ptzCmd, CXT& XT) { // Get command ID UINT uCmd; PTSTR p = ptzCmd; for (uCmd = 0; uCmd < _NumOf(c_tzCmd); uCmd++) { if (UStrMatchI(p, c_tzCmd[uCmd]) >= CC_LEN) { // skip white space for (p += CC_LEN; (*p == ' ') || (*p == '\t'); p++); break; } } switch (uCmd) { case CMD_LOAD: return LOAD(p); case CMD_BATC: return BATC(p, XT); case CMD_IFEX: if (*p) { if (PTSTR ptzArg = UStrChr(p, CC_SEP)) { *ptzArg++ = 0; if (IFEX(p)) { Dispatch(ptzArg, XT); } return XT.hXVar; } else if (!IFEX(p)) { if (p = UStrStr(XT.ptzNext, TEXT("IFEX\r\n"))) { XT.ptzNext = p + CC_LEN + 2; return S_OK; } else if (p = UStrStr(XT.ptzNext, TEXT("IFEX\n"))) { XT.ptzNext = p + CC_LEN + 1; return S_OK; } else { XT.ptzNext = TEXT(""); return S_FALSE; } } } return S_OK; case CMD_ELSE: if (!g_bResult) Dispatch(p, XT); return XT.hXVar; case CMD_EVAL: return EVAL(p); case CMD_LINK: return LINK(p); case CMD_FILE: return FILe(p); case CMD_REGX: return REGX(p); case CMD_ENVI: return (*p == '$') ? ENVI(p + 1, TRUE) : ENVI(p); case CMD_SEND: return SEND(p); case CMD_WAIT: Sleep(UStrToInt(p)); return S_OK; case CMD_KILL: return KILL(p); case CMD_SHUT: return SHUT(p); case CMD_PLAY: return PLAY(p); case CMD_BEEP: return !MessageBeep(UStrToInt(p)); case CMD_MSGX: return MSGX(p); case CMD_DLGX: return (HRESULT) DialogBoxParam(g_hInst, MAKEINTRESOURCE(IDD_Dialog), NULL, DLGX, (LPARAM) p); case CMD_EXEC: return EXEC(p); case CMD_CDLL: return CDLL(p); case CMD_CCUI: return (HRESULT) DialogBoxParam(g_hInst, MAKEINTRESOURCE(IDD_Main), NULL, MAIN, (LPARAM) XT.ptzFile); case CMD_CALL: case CMD_GOTO: case CMD_PROC: UMemCopy(ptzCmd, c_tzCmd[(uCmd == CMD_PROC) ? CMD_ENDP : CMD_PROC], CC_LEN * sizeof(TCHAR)); if (p = UStrStr(XT.ptzNext, ptzCmd)) { p += CC_LEN; while (*p && (*p++ != '\n')); if (uCmd == CMD_CALL) { return Process(p, XT.ptzFile); } else { XT.ptzNext = p; } return S_OK; } else if (uCmd == CMD_PROC) { XT.ptzNext = TEXT(""); } return S_FALSE; case CMD_ENDP: XT.ptzNext = TEXT(""); return S_OK; case CMD_ASOC: return ASOC(p); case CMD_DEVI: return SERV(p); case CMD_SERV: return SERV(p); case CMD_PAGE: return PAGE(p); case CMD_DISP: return DISP(p); default: PTSTR ptzFile; if (ptzFile = UStrRChr(p, '\\')) { *ptzFile++ = 0; } return (*p == '!') ? OPEN(p + 1, ptzFile, TRUE) : OPEN(p, ptzFile); } }
int main(int argc, char *argv[]) { int i, oldumask; argcGlobal = argc; argvGlobal = argv; configfilename = NULL; /* init stuff */ ProcessCmdLine(argc, argv); /* * Do this first thing, to get any options that only take effect at * startup time. It is read again each time the server resets. */ if (ReadConfigFile(configfilename) != FSSuccess) { FatalError("couldn't read config file\n"); } InitErrors(); /* make sure at least world write access is disabled */ if (((oldumask = umask(022)) & 002) == 002) (void)umask(oldumask); SetDaemonState(); SetUserId(); while (1) { serverGeneration++; OsInit(); if (serverGeneration == 1) { /* do first time init */ CreateSockets(OldListenCount, OldListen); InitProcVectors(); clients = (ClientPtr *) fsalloc(MAXCLIENTS * sizeof(ClientPtr)); if (!clients) FatalError("couldn't create client array\n"); for (i = MINCLIENT; i < MAXCLIENTS; i++) clients[i] = NullClient; /* make serverClient */ serverClient = (ClientPtr) fsalloc(sizeof(ClientRec)); if (!serverClient) FatalError("couldn't create server client\n"); } ResetSockets(); /* init per-cycle stuff */ InitClient(serverClient, SERVER_CLIENT, (pointer) 0); clients[SERVER_CLIENT] = serverClient; currentMaxClients = MINCLIENT; currentClient = serverClient; if (!InitClientResources(serverClient)) FatalError("couldn't init server resources\n"); InitAtoms(); InitFonts(); SetConfigValues(); if (!create_connection_block()) FatalError("couldn't create connection block\n"); #ifdef DEBUG fprintf(stderr, "Entering Dispatch loop\n"); #endif Dispatch(); #ifdef DEBUG fprintf(stderr, "Leaving Dispatch loop\n"); #endif /* clean up per-cycle stuff */ if ((dispatchException & DE_TERMINATE) || drone_server) break; fsfree(ConnectionInfo); /* note that we're parsing it again, for each time the server resets */ if (ReadConfigFile(configfilename) != FSSuccess) FatalError("couldn't read config file\n"); } CloseSockets(); CloseErrors(); exit(0); }
bool VSTPlugin::Instance(const char *name,const char *subname) { bool ok = false; FLEXT_ASSERT(effect == NULL); try { /* if(!ok && dllname != name) { FreePlugin(); // freshly load plugin ok = NewPlugin(name) && InstPlugin(); } */ ok = NewPlugin(name) && InstPlugin(); if(ok && subname && *subname && Dispatch(effGetPlugCategory) == kPlugCategShell) { // sub plugin-name given -> scan plugs long plugid; char tmp[64]; // Waves5 continues with the next plug after the last loaded // that's not what we want - workaround: swallow all remaining while((plugid = Dispatch(effShellGetNextPlugin,0,0,tmp))) {} // restart from the beginning while((plugid = Dispatch(effShellGetNextPlugin,0,0,tmp))) { // subplug needs a name FLEXT_LOG1("subplug %s",tmp); if(!strcmp(subname,tmp)) // found break; } // re-init with plugid set if(plugid) ok = InstPlugin(plugid); } if(ok) { //init plugin effect->user = this; ok = Dispatch(effOpen) == 0; } if(ok) { ok = Dispatch(effIdentify) == 'NvEf'; } if(ok) { *productname = 0; long ret = Dispatch(effGetProductString,0,0,productname); if(!*productname) { // no product name given by plugin -> extract it from the filename std::string str1(dllname); std::string::size_type slpos = str1.rfind('\\'); if(slpos == std::string::npos) { slpos = str1.rfind('/'); if(slpos == std::string::npos) slpos = 0; else ++slpos; } else ++slpos; std::string str2 = str1.substr(slpos); int snip = str2.find('.'); if( snip != std::string::npos ) str1 = str2.substr(0,snip); else str1 = str2; strcpy(productname,str1.c_str()); } if(*productname) { char tmp[512]; sprintf(tmp,"vst~ - %s",productname); title = tmp; } else title = "vst~"; *vendorname = 0; Dispatch(effGetVendorString,0,0,vendorname); } } catch(std::exception &e) { flext::post("vst~ - caught exception while loading plugin: %s",e.what()); ok = false; } catch(...) { flext::post("vst~ - Caught exception while loading plugin"); ok = false; } if(!ok) Free(); return ok; }
void FLiveEditorManager::Tick(float DeltaTime) { //avoid multiple tick DOOM ( FTickableGameObject's get ticked once per UWorld that is active and Ticking ) float CurTime = GWorld->GetRealTimeSeconds(); if ( LastUpdateTime == CurTime ) { return; } LastUpdateTime = CurTime; if ( LiveEditorWorld == NULL ) { CreateLiveEditorWorld(); } RealWorld = GWorld; check( LiveEditorWorld != NULL ); GWorld = LiveEditorWorld; if ( ActiveBlueprints.Num() > 0 ) LiveEditorWorld->Tick( ELevelTick::LEVELTICK_All, DeltaTime ); // //update our ActiveBlueprints // int32 i = 0; while ( i < ActiveBlueprints.Num() ) { FActiveBlueprintRecord record = ActiveBlueprints[i]; ULiveEditorBlueprint *Instance = record.Blueprint.Get(); if ( Instance == NULL ) { ActiveBlueprints.RemoveAtSwap(i); //clean out the dead entry Activate( record.Name ); //try to ressurect the Blueprint (user has likely just recompiled it) continue; } Instance->Tick( DeltaTime ); ++i; } // // handle the actual MIDI messages // for( TMap< PmDeviceID, FLiveEditorDeviceInstance >::TIterator It(InputConnections); It; ++It ) { PmDeviceID DeviceID = (*It).Key; FLiveEditorDeviceInstance &DeviceInstance = (*It).Value; int NumRead = Pm_Read( DeviceInstance.Connection.MIDIStream, MIDIBuffer, DEFAULT_BUFFER_SIZE ); //needs to remain int (instead of int32) since numbers are derived from TPL that uses int if ( NumRead < 0 ) { continue; //error occurred, portmidi should handle this silently behind the scenes } else if ( NumRead > 0 ) { DeviceInstance.Data.LastInputTime = GWorld->GetTimeSeconds(); } //dispatch for ( int32 BufferIndex = 0; BufferIndex < NumRead; BufferIndex++ ) { PmMessage Msg = MIDIBuffer[BufferIndex].message; int Status = Pm_MessageStatus(Msg); //needs to remain int (instead of int32) since numbers are derived from TPL that uses int int Data1 = Pm_MessageData1(Msg); //needs to remain int (instead of int32) since numbers are derived from TPL that uses int int Data2 = Pm_MessageData2(Msg); //needs to remain int (instead of int32) since numbers are derived from TPL that uses int if ( ActiveWizard != NULL ) { ActiveWizard->ProcessMIDI( Status, Data1, Data2, DeviceID, DeviceInstance.Data ); } else { switch ( DeviceInstance.Data.ConfigState ) { case FLiveEditorDeviceData::UNCONFIGURED: break; case FLiveEditorDeviceData::CONFIGURED: Dispatch( Status, Data1, Data2, DeviceInstance.Data ); break; default: break; } } } } PieObjectCache.EvaluatePendingCreations(); GWorld = RealWorld; RealWorld = NULL; }
void GraphicsSystem::ApplyWindowChanges() { CreateSFMLWindow(); Dispatch(Event(EvtWindowResize, WindowResizeEventData(m_Width, m_Height))); }