AuroraRuntime/Source/Loop/Loop.NT.cpp

117 lines
3.3 KiB
C++

/***
Copyright (C) 2021 J Reece Wilson (a/k/a "Reece"). All rights reserved.
File: Loop.NT.cpp
Date: 2021-10-1
Author: Reece
***/
#include <Source/RuntimeInternal.hpp>
#include "Loop.NT.hpp"
#include "ILoopSourceEx.hpp"
namespace Aurora::Loop
{
AUKN_SYM AuList<AuSPtr<ILoopSource>> WaitMultipleOrObjects(const AuList<AuSPtr<ILoopSource>> &objects, AuUInt32 timeout)
{
bool isWinLoop;
AuList<AuSPtr<ILoopSourceEx>> loopSourceExs;
AuList<AuSPtr<ILoopSource>> triggered;
AuList<HANDLE> handleArray;
AuSPtr<ILoopSource> msgSource;
isWinLoop = false;
loopSourceExs.reserve(objects.size());
handleArray.reserve(objects.size());
triggered.reserve(triggered.size());
for (const auto &source : objects)
{
if (!source)
{
continue;
}
if (source->GetType() == ELoopSource::eSourceWin32)
{
isWinLoop = true;
msgSource = source;
continue;
}
if (auto extended = std::dynamic_pointer_cast<ILoopSourceEx>(source))
{
loopSourceExs.push_back(extended);
for (const auto &handle : extended->GetHandles())
{
auto nthandle = reinterpret_cast<HANDLE>(handle);
handleArray.push_back(nthandle);
}
}
}
for (const auto &source : loopSourceExs)
{
source->OnPresleep();
}
DWORD ret;
if (isWinLoop)
{
ret = ::MsgWaitForMultipleObjectsEx(handleArray.size(), handleArray.data(), timeout ? timeout : INFINITE, QS_ALLPOSTMESSAGE | QS_ALLINPUT | QS_ALLEVENTS, MWMO_INPUTAVAILABLE);
}
else
{
ret = ::WaitForMultipleObjectsEx(handleArray.size(), handleArray.data(), false, timeout ? timeout : INFINITE, true);
}
bool error = ((ret == WAIT_TIMEOUT) ||
(ret == WAIT_IO_COMPLETION) ||
(ret == WAIT_FAILED));
bool isPump = WAIT_OBJECT_0 + handleArray.size() == ret;
AuUInt firstTriggered {};
if (!error)
{
if (!isPump)
{
firstTriggered = reinterpret_cast<AuUInt>(handleArray[ret - WAIT_OBJECT_0]);
}
}
for (const auto &source : loopSourceExs)
{
if (!error)
{
AuUInt lastHandle {};
bool wasTriggered {};
for (const auto &handle : source->GetHandles())
{
if ((firstTriggered == handle) ||
(WaitForSingleObject(reinterpret_cast<HANDLE>(handle), 0) == WAIT_OBJECT_0))
{
lastHandle = handle;
wasTriggered = true;
continue;
}
}
if (source->OnTrigger(lastHandle, wasTriggered))
{
triggered.push_back(source);
}
}
source->OnFinishSleep();
}
if (isPump)
{
triggered.push_back(msgSource);
}
return triggered;
}
}