diff --git a/es-core/src/AsyncHandle.h b/es-core/src/AsyncHandle.h index 4ea5a5482..5630890c0 100644 --- a/es-core/src/AsyncHandle.h +++ b/es-core/src/AsyncHandle.h @@ -12,7 +12,7 @@ #include enum AsyncHandleStatus { - ASYNC_IN_PROGRESS, + ASYNC_IN_PROGRESS, // Replace with AllowShortEnumsOnASingleLine: false (clang-format >=11.0). ASYNC_ERROR, ASYNC_DONE }; @@ -21,17 +21,24 @@ enum AsyncHandleStatus { class AsyncHandle { public: - AsyncHandle() : mStatus(ASYNC_IN_PROGRESS) {}; - virtual ~AsyncHandle() {}; + AsyncHandle() + : mStatus(ASYNC_IN_PROGRESS) + { + } + virtual ~AsyncHandle() {} virtual void update() = 0; // Update and return the latest status. - inline AsyncHandleStatus status() { update(); return mStatus; } + AsyncHandleStatus status() + { + update(); + return mStatus; + } // User-friendly string of our current status. // Will return error message if status() == SEARCH_ERROR. - inline std::string getStatusString() + std::string getStatusString() { switch (mStatus) { case ASYNC_IN_PROGRESS: @@ -46,8 +53,12 @@ public: } protected: - inline void setStatus(AsyncHandleStatus status) { mStatus = status; } - inline void setError(const std::string& error) { setStatus(ASYNC_ERROR); mError = error; } + void setStatus(AsyncHandleStatus status) { mStatus = status; } + void setError(const std::string& error) + { + setStatus(ASYNC_ERROR); + mError = error; + } std::string mError; AsyncHandleStatus mStatus; diff --git a/es-core/src/AudioManager.cpp b/es-core/src/AudioManager.cpp index 081589364..8ca75fa41 100644 --- a/es-core/src/AudioManager.cpp +++ b/es-core/src/AudioManager.cpp @@ -19,17 +19,20 @@ std::vector> AudioManager::sSoundVector; SDL_AudioDeviceID AudioManager::sAudioDevice = 0; SDL_AudioSpec AudioManager::sAudioFormat; SDL_AudioStream* AudioManager::sConversionStream; + bool AudioManager::sMuteStream = false; bool AudioManager::sHasAudioDevice = true; bool AudioManager::mIsClearingStream = false; AudioManager::AudioManager() { + // Init on construction. init(); } AudioManager::~AudioManager() { + // Deinit on destruction. deinit(); } @@ -74,7 +77,7 @@ void AudioManager::init() } sAudioDevice = SDL_OpenAudioDevice(0, 0, &sRequestedAudioFormat, &sAudioFormat, - SDL_AUDIO_ALLOW_ANY_CHANGE); + SDL_AUDIO_ALLOW_ANY_CHANGE); if (sAudioDevice == 0) { LOG(LogError) << "Unable to open audio device: " << SDL_GetError(); @@ -82,29 +85,30 @@ void AudioManager::init() } if (sAudioFormat.freq != sRequestedAudioFormat.freq) { - LOG(LogDebug) << "AudioManager::init(): Requested sample rate " << - std::to_string(sRequestedAudioFormat.freq) << " could not be " - "set, obtained " << std::to_string(sAudioFormat.freq); + LOG(LogDebug) << "AudioManager::init(): Requested sample rate " + << std::to_string(sRequestedAudioFormat.freq) + << " could not be set, obtained " << std::to_string(sAudioFormat.freq); } if (sAudioFormat.format != sRequestedAudioFormat.format) { - LOG(LogDebug) << "AudioManager::init(): Requested format " << - std::to_string(sRequestedAudioFormat.format) << " could not be " - "set, obtained " << std::to_string(sAudioFormat.format); + LOG(LogDebug) << "AudioManager::init(): Requested format " + << std::to_string(sRequestedAudioFormat.format) + << " could not be set, obtained " << std::to_string(sAudioFormat.format); } if (sAudioFormat.channels != sRequestedAudioFormat.channels) { - LOG(LogDebug) << "AudioManager::init(): Requested channel count " << - std::to_string(sRequestedAudioFormat.channels) << " could not be " - "set, obtained " << std::to_string(sAudioFormat.channels); + LOG(LogDebug) << "AudioManager::init(): Requested channel count " + << std::to_string(sRequestedAudioFormat.channels) + << " could not be set, obtained " << std::to_string(sAudioFormat.channels); } - #if defined(_WIN64) || defined(__APPLE__) +#if defined(_WIN64) || defined(__APPLE__) // Beats me why the buffer size is not divided by the channel count on some operating systems. if (sAudioFormat.samples != sRequestedAudioFormat.samples) { - #else +#else if (sAudioFormat.samples != sRequestedAudioFormat.samples / sRequestedAudioFormat.channels) { - #endif - LOG(LogDebug) << "AudioManager::init(): Requested sample buffer size " << - std::to_string(sRequestedAudioFormat.samples / sRequestedAudioFormat.channels) << - " could not be set, obtained " << std::to_string(sAudioFormat.samples); +#endif + LOG(LogDebug) << "AudioManager::init(): Requested sample buffer size " + << std::to_string(sRequestedAudioFormat.samples / + sRequestedAudioFormat.channels) + << " could not be set, obtained " << std::to_string(sAudioFormat.samples); } // Just in case someone changed the es_settings.xml file manually to invalid values. @@ -126,7 +130,7 @@ void AudioManager::deinit() // user on some operating systems such as macOS, and it's annoying to have a crash at the // end of debugging session. So we'll simply disable the function until it has been properly // fixed in the SDL library. -// SDL_FreeAudioStream(sConversionStream); + // SDL_FreeAudioStream(sConversionStream); SDL_CloseAudio(); SDL_QuitSubSystem(SDL_INIT_AUDIO); @@ -153,9 +157,9 @@ void AudioManager::mixAudio(void* /*unused*/, Uint8* stream, int len) restLength = len; } // Mix sample into stream. - SDL_MixAudioFormat(stream, &(sound->getData()[sound->getPosition()]), - sAudioFormat.format, restLength, static_cast(Settings::getInstance()-> - getInt("SoundVolumeNavigation") * 1.28f)); + SDL_MixAudioFormat( + stream, &(sound->getData()[sound->getPosition()]), sAudioFormat.format, restLength, + static_cast(Settings::getInstance()->getInt("SoundVolumeNavigation") * 1.28f)); if (sound->getPosition() + restLength < sound->getLength()) { // Sample hasn't ended yet. stillPlaying = true; @@ -191,8 +195,8 @@ void AudioManager::mixAudio(void* /*unused*/, Uint8* stream, int len) std::vector converted(chunkLength); - int processedLength = SDL_AudioStreamGet(sConversionStream, - static_cast(&converted.at(0)), chunkLength); + int processedLength = + SDL_AudioStreamGet(sConversionStream, static_cast(&converted.at(0)), chunkLength); if (processedLength < 0) { LOG(LogError) << "AudioManager::mixAudio(): Couldn't convert sound chunk:"; @@ -201,9 +205,9 @@ void AudioManager::mixAudio(void* /*unused*/, Uint8* stream, int len) } // Enable only when needed, as this generates a lot of debug output. -// LOG(LogDebug) << "AudioManager::mixAudio(): chunkLength " -// "/ processedLength / streamLength: " << chunkLength << " / " << -// " / " << processedLength << " / " << streamLength; + // LOG(LogDebug) << "AudioManager::mixAudio(): chunkLength " + // "/ processedLength / streamLength: " << chunkLength << " / " << + // " / " << processedLength << " / " << streamLength; // This mute flag is used to make sure that the audio buffer already sent to the // stream is not played when the video player has been stopped. Otherwise there would @@ -213,8 +217,9 @@ void AudioManager::mixAudio(void* /*unused*/, Uint8* stream, int len) SDL_MixAudioFormat(stream, &converted.at(0), sAudioFormat.format, processedLength, 0); } else { - SDL_MixAudioFormat(stream, &converted.at(0), sAudioFormat.format, processedLength, - static_cast(Settings::getInstance()->getInt("SoundVolumeVideos") * 1.28f)); + SDL_MixAudioFormat( + stream, &converted.at(0), sAudioFormat.format, processedLength, + static_cast(Settings::getInstance()->getInt("SoundVolumeVideos") * 1.28f)); } // If nothing is playing, pause the device until there is more audio to output. @@ -224,6 +229,7 @@ void AudioManager::mixAudio(void* /*unused*/, Uint8* stream, int len) void AudioManager::registerSound(std::shared_ptr& sound) { + // Add sound to sound vector. sSoundVector.push_back(sound); } @@ -267,7 +273,7 @@ void AudioManager::setupAudioStream(int sampleRate) // Used for streaming audio from videos. sConversionStream = SDL_NewAudioStream(AUDIO_F32, 2, sampleRate, sAudioFormat.format, - sAudioFormat.channels, sAudioFormat.freq); + sAudioFormat.channels, sAudioFormat.freq); if (sConversionStream == nullptr) { LOG(LogError) << "Failed to create audio conversion stream:"; LOG(LogError) << SDL_GetError(); @@ -298,7 +304,7 @@ void AudioManager::clearStream() // The SDL_AudioStreamClear() function is unstable and causes random crashes, so // we have to implement a workaround instead where SDL_AudioStreamGet() is used // to empty the stream. -// SDL_AudioStreamClear(sConversionStream); + // SDL_AudioStreamClear(sConversionStream); mIsClearingStream = true; @@ -307,8 +313,8 @@ void AudioManager::clearStream() while ((streamSize = SDL_AudioStreamAvailable(sConversionStream)) > 0) { std::vector readBuffer(length); - int processedLength = SDL_AudioStreamGet(sConversionStream, - static_cast(&readBuffer.at(0)), length); + int processedLength = + SDL_AudioStreamGet(sConversionStream, static_cast(&readBuffer.at(0)), length); if (processedLength <= 0) { break; } diff --git a/es-core/src/CECInput.cpp b/es-core/src/CECInput.cpp index 1750a37fb..dfd8caa49 100644 --- a/es-core/src/CECInput.cpp +++ b/es-core/src/CECInput.cpp @@ -33,11 +33,12 @@ extern int SDL_USER_CECBUTTONUP; CECInput* CECInput::sInstance = nullptr; #if defined(HAVE_LIBCEC) -static void onAlert(void* /*cbParam*/, const CEC::libcec_alert type, - const CEC::libcec_parameter param) +static void onAlert(void* /*cbParam*/, + const CEC::libcec_alert type, + const CEC::libcec_parameter param) { - LOG(LogDebug) << "CECInput::onAlert type: " << CECInput::getAlertTypeString(type) << - " parameter: " << reinterpret_cast(param.paramData); + LOG(LogDebug) << "CECInput::onAlert type: " << CECInput::getAlertTypeString(type) + << " parameter: " << reinterpret_cast(param.paramData); } static void onCommand(void* /*cbParam*/, const CEC::cec_command* command) @@ -50,7 +51,7 @@ static void onKeyPress(void* /*cbParam*/, const CEC::cec_keypress* key) LOG(LogDebug) << "CECInput::onKeyPress keycode: " << CECInput::getKeyCodeString(key->keycode); SDL_Event event; - event.type = (key->duration > 0) ? SDL_USER_CECBUTTONUP : SDL_USER_CECBUTTONDOWN; + event.type = (key->duration > 0) ? SDL_USER_CECBUTTONUP : SDL_USER_CECBUTTONDOWN; event.user.code = key->keycode; SDL_PushEvent(&event); } @@ -93,14 +94,15 @@ void CECInput::deinit() } } -CECInput::CECInput() : mlibCEC(nullptr) +CECInput::CECInput() + : mlibCEC(nullptr) { - #if defined(HAVE_LIBCEC) - #if defined(_RPI_) +#if defined(HAVE_LIBCEC) +#if defined(_RPI_) // Restart vchi tv and CEC in case we just came back from another app using CEC (like Kodi). vchi_tv_and_cec_deinit(); vchi_tv_and_cec_init(); - #endif // _RPI_ +#endif // _RPI_ CEC::ICECCallbacks callbacks; CEC::libcec_configuration config; @@ -136,8 +138,8 @@ CECInput::CECInput() : mlibCEC(nullptr) } for (int i = 0; i < numAdapters; i++) - LOG(LogDebug) << "CEC adapter: " << i << " path: " << adapters[i].strComPath << - " name: " << adapters[i].strComName; + LOG(LogDebug) << "CEC adapter: " << i << " path: " << adapters[i].strComPath + << " name: " << adapters[i].strComName; if (!mlibCEC->Open(adapters[0].strComName)) { LOG(LogError) << "CECInput::mAdapter->Open failed"; @@ -145,28 +147,29 @@ CECInput::CECInput() : mlibCEC(nullptr) mlibCEC = nullptr; return; } - #endif // HAVE_LIBCEC +#endif // HAVE_LIBCEC } CECInput::~CECInput() { - #if defined(HAVE_LIBCEC) +#if defined(HAVE_LIBCEC) if (mlibCEC) { mlibCEC->Close(); UnloadLibCec(mlibCEC); mlibCEC = nullptr; } - #if defined(_RPI_) +#if defined(_RPI_) // Deinit vchi tv and CEC in case we are going to launch another app using CEC (like Kodi). vchi_tv_and_cec_deinit(); - #endif // _RPI_ - #endif // HAVE_LIBCEC +#endif // _RPI_ +#endif // HAVE_LIBCEC } std::string CECInput::getAlertTypeString(const unsigned int _type) { + // clang-format off switch (_type) { #if defined(HAVE_LIBCEC) case CEC::CEC_ALERT_SERVICE_DEVICE: { return "Service-Device"; } break; @@ -180,10 +183,12 @@ std::string CECInput::getAlertTypeString(const unsigned int _type) #endif // HAVE_LIBCEC default: { return "Unknown"; } break; } + // clang-format on } std::string CECInput::getOpCodeString(const unsigned int _opCode) { + // clang-format off switch (_opCode) { #if defined(HAVE_LIBCEC) case CEC::CEC_OPCODE_ACTIVE_SOURCE: { return "Active-Source"; } break; @@ -261,10 +266,12 @@ std::string CECInput::getOpCodeString(const unsigned int _opCode) #endif // HAVE_LIBCEC default: { return "Unknown"; } break; } + // clang-format on } std::string CECInput::getKeyCodeString(const unsigned int _keyCode) { + // clang-format off switch (_keyCode) { #if defined(HAVE_LIBCEC) case CEC::CEC_USER_CONTROL_CODE_SELECT: { return "Select"; } break; @@ -358,5 +365,6 @@ std::string CECInput::getKeyCodeString(const unsigned int _keyCode) case 0: #endif // HAVE_LIBCEC default: { return "Unknown"; } break; + // clang-format off } } \ No newline at end of file diff --git a/es-core/src/CECInput.h b/es-core/src/CECInput.h index 4172f911b..216e849e0 100644 --- a/es-core/src/CECInput.h +++ b/es-core/src/CECInput.h @@ -11,7 +11,10 @@ #include -namespace CEC { class ICECAdapter; } +namespace CEC +{ + class ICECAdapter; +} class CECInput { @@ -23,7 +26,7 @@ public: static std::string getKeyCodeString(const unsigned int _keyCode); private: - CECInput(); + CECInput(); ~CECInput(); static CECInput* sInstance; diff --git a/es-core/src/GuiComponent.cpp b/es-core/src/GuiComponent.cpp index 66f5e1ea6..d3cf8e09e 100644 --- a/es-core/src/GuiComponent.cpp +++ b/es-core/src/GuiComponent.cpp @@ -8,31 +8,30 @@ #include "GuiComponent.h" -#include "animations/Animation.h" -#include "animations/AnimationController.h" -#include "renderers/Renderer.h" #include "Log.h" #include "ThemeData.h" #include "Window.h" +#include "animations/Animation.h" +#include "renderers/Renderer.h" #include GuiComponent::GuiComponent(Window* window) - : mWindow(window), - mParent(nullptr), - mColor(0), - mColorShift(0), - mColorShiftEnd(0), - mOpacity(255), - mSaturation(1.0), - mPosition(Vector3f::Zero()), - mOrigin(Vector2f::Zero()), - mRotationOrigin(0.5, 0.5), - mSize(Vector2f::Zero()), - mTransform(Transform4x4f::Identity()), - mIsProcessing(false), - mVisible(true), - mEnabled(true) + : mWindow(window) + , mParent(nullptr) + , mColor(0) + , mColorShift(0) + , mColorShiftEnd(0) + , mOpacity(255) + , mSaturation(1.0f) + , mPosition(Vector3f::Zero()) + , mOrigin(Vector2f::Zero()) + , mRotationOrigin(0.5f, 0.5f) + , mSize(Vector2f::Zero()) + , mTransform(Transform4x4f::Identity()) + , mIsProcessing(false) + , mVisible(true) + , mEnabled(true) { for (unsigned char i = 0; i < MAX_ANIMATIONS; i++) mAnimationMap[i] = nullptr; @@ -94,105 +93,30 @@ void GuiComponent::renderChildren(const Transform4x4f& transform) const getChild(i)->render(transform); } -Vector3f GuiComponent::getPosition() const -{ - return mPosition; -} - void GuiComponent::setPosition(float x, float y, float z) { mPosition = Vector3f(x, y, z); onPositionChanged(); } -Vector2f GuiComponent::getOrigin() const -{ - return mOrigin; -} - void GuiComponent::setOrigin(float x, float y) { mOrigin = Vector2f(x, y); onOriginChanged(); } -Vector2f GuiComponent::getRotationOrigin() const -{ - return mRotationOrigin; -} - -void GuiComponent::setRotationOrigin(float x, float y) -{ - mRotationOrigin = Vector2f(x, y); -} - -Vector2f GuiComponent::getSize() const -{ - return mSize; -} - void GuiComponent::setSize(float w, float h) { mSize = Vector2f(w, h); onSizeChanged(); } -float GuiComponent::getRotation() const -{ - return mRotation; -} - -void GuiComponent::setRotation(float rotation) -{ - mRotation = rotation; -} - -float GuiComponent::getScale() const -{ - return mScale; -} - -void GuiComponent::setScale(float scale) -{ - mScale = scale; -} - -float GuiComponent::getZIndex() const -{ - return mZIndex; -} - -void GuiComponent::setZIndex(float z) -{ - mZIndex = z; -} - -float GuiComponent::getDefaultZIndex() const -{ - return mDefaultZIndex; -} - -void GuiComponent::setDefaultZIndex(float z) -{ - mDefaultZIndex = z; -} - -bool GuiComponent::isVisible() const -{ - return mVisible; -} -void GuiComponent::setVisible(bool visible) -{ - mVisible = visible; -} - Vector2f GuiComponent::getCenter() const { - return Vector2f(mPosition.x() - (getSize().x() * mOrigin.x()) + getSize().x() / 2, - mPosition.y() - (getSize().y() * mOrigin.y()) + getSize().y() / 2); + return Vector2f(mPosition.x() - (getSize().x() * mOrigin.x()) + getSize().x() / 2.0f, + mPosition.y() - (getSize().y() * mOrigin.y()) + getSize().y() / 2.0f); } -// Children stuff. void GuiComponent::addChild(GuiComponent* cmp) { mChildren.push_back(cmp); @@ -222,11 +146,6 @@ void GuiComponent::removeChild(GuiComponent* cmp) } } -void GuiComponent::clearChildren() -{ - mChildren.clear(); -} - void GuiComponent::sortChildren() { std::stable_sort(mChildren.begin(), mChildren.end(), [](GuiComponent* a, GuiComponent* b) { @@ -234,15 +153,10 @@ void GuiComponent::sortChildren() }); } -unsigned int GuiComponent::getChildCount() const -{ - return static_cast(mChildren.size()); -} - int GuiComponent::getChildIndex() const { std::vector::iterator it = - std::find(getParent()->mChildren.begin(), getParent()->mChildren.end(), this); + std::find(getParent()->mChildren.begin(), getParent()->mChildren.end(), this); if (it != getParent()->mChildren.end()) return static_cast(std::distance(getParent()->mChildren.begin(), it)); @@ -250,26 +164,6 @@ int GuiComponent::getChildIndex() const return -1; } -GuiComponent* GuiComponent::getChild(unsigned int i) const -{ - return mChildren.at(i); -} - -void GuiComponent::setParent(GuiComponent* parent) -{ - mParent = parent; -} - -GuiComponent* GuiComponent::getParent() const -{ - return mParent; -} - -unsigned char GuiComponent::getOpacity() const -{ - return mOpacity; -} - void GuiComponent::setOpacity(unsigned char opacity) { mOpacity = opacity; @@ -277,92 +171,47 @@ void GuiComponent::setOpacity(unsigned char opacity) (*it)->setOpacity(opacity); } -unsigned int GuiComponent::getColor() const -{ - return mColor; -} - -unsigned int GuiComponent::getColorShift() const -{ - return mColorShift; -} - -void GuiComponent::setColor(unsigned int color) -{ - mColor = color; - mColorOpacity = mColor & 0x000000FF; -} - -float GuiComponent::getSaturation() const -{ - return static_cast(mColor); -} - -void GuiComponent::setSaturation(float saturation) -{ - mSaturation = saturation; -} - -void GuiComponent::setColorShift(unsigned int color) -{ - mColorShift = color; - mColorShiftEnd = color; -} - const Transform4x4f& GuiComponent::getTransform() { mTransform = Transform4x4f::Identity(); mTransform.translate(mPosition); - if (mScale != 1.0) + + if (mScale != 1.0f) mTransform.scale(mScale); - if (mRotation != 0.0) { + + if (mRotation != 0.0f) { // Calculate offset as difference between origin and rotation origin. Vector2f rotationSize = getRotationSize(); float xOff = (mOrigin.x() - mRotationOrigin.x()) * rotationSize.x(); float yOff = (mOrigin.y() - mRotationOrigin.y()) * rotationSize.y(); // Transform to offset point. - if (xOff != 0.0 || yOff != 0.0) - mTransform.translate(Vector3f(xOff * -1, yOff * -1, 0.0f)); + if (xOff != 0.0f || yOff != 0.0f) + mTransform.translate(Vector3f(xOff * -1.0f, yOff * -1.0f, 0.0f)); // Apply rotation transform. mTransform.rotateZ(mRotation); // Transform back to original point. - if (xOff != 0.0 || yOff != 0.0) + if (xOff != 0.0f || yOff != 0.0f) mTransform.translate(Vector3f(xOff, yOff, 0.0f)); } - mTransform.translate(Vector3f(mOrigin.x() * mSize.x() * -1, - mOrigin.y() * mSize.y() * -1, 0.0f)); + mTransform.translate( + Vector3f(mOrigin.x() * mSize.x() * -1.0f, mOrigin.y() * mSize.y() * -1.0f, 0.0f)); return mTransform; } -std::string GuiComponent::getValue() const -{ - return ""; -} - -void GuiComponent::setValue(const std::string& /*value*/) -{ -} - -std::string GuiComponent::getHiddenValue() const -{ - return ""; -} - -void GuiComponent::setHiddenValue(const std::string& /*value*/) -{ -} - void GuiComponent::textInput(const std::string& text) { for (auto iter = mChildren.cbegin(); iter != mChildren.cend(); iter++) (*iter)->textInput(text); } -void GuiComponent::setAnimation(Animation* anim, int delay, - std::function finishedCallback, bool reverse, unsigned char slot) +void GuiComponent::setAnimation(Animation* anim, + int delay, + std::function finishedCallback, + bool reverse, + unsigned char slot) { assert(slot < MAX_ANIMATIONS); @@ -447,29 +296,14 @@ void GuiComponent::cancelAllAnimations() cancelAnimation(i); } -bool GuiComponent::isAnimationPlaying(unsigned char slot) const -{ - return mAnimationMap[slot] != nullptr; -} - -bool GuiComponent::isAnimationReversed(unsigned char slot) const -{ - assert(mAnimationMap[slot] != nullptr); - return mAnimationMap[slot]->isReversed(); -} - -int GuiComponent::getAnimationTime(unsigned char slot) const -{ - assert(mAnimationMap[slot] != nullptr); - return mAnimationMap[slot]->getTime(); -} - void GuiComponent::applyTheme(const std::shared_ptr& theme, - const std::string& view, const std::string& element, unsigned int properties) + const std::string& view, + const std::string& element, + unsigned int properties) { - Vector2f scale = getParent() ? getParent()->getSize() - : Vector2f(static_cast(Renderer::getScreenWidth()), - static_cast(Renderer::getScreenHeight())); + Vector2f scale = getParent() ? getParent()->getSize() : + Vector2f(static_cast(Renderer::getScreenWidth()), + static_cast(Renderer::getScreenHeight())); const ThemeData::ThemeElement* elem = theme->getElement(view, element, ""); if (!elem) @@ -484,9 +318,9 @@ void GuiComponent::applyTheme(const std::shared_ptr& theme, if (properties & ThemeFlags::SIZE && elem->has("size")) setSize(elem->get("size") * scale); - // Position + size also implies origin - if ((properties & ORIGIN || (properties & POSITION && - properties & ThemeFlags::SIZE)) && elem->has("origin")) { + // Position + size also implies origin. + if ((properties & ORIGIN || (properties & POSITION && properties & ThemeFlags::SIZE)) && + elem->has("origin")) { setOrigin(elem->get("origin")); } @@ -521,16 +355,6 @@ void GuiComponent::updateHelpPrompts() mWindow->setHelpPrompts(prompts, getHelpStyle()); } -HelpStyle GuiComponent::getHelpStyle() -{ - return HelpStyle(); -} - -bool GuiComponent::isProcessing() const -{ - return mIsProcessing; -} - void GuiComponent::onShow() { for (unsigned int i = 0; i < getChildCount(); i++) diff --git a/es-core/src/GuiComponent.h b/es-core/src/GuiComponent.h index 3a7c41b7e..83901040f 100644 --- a/es-core/src/GuiComponent.h +++ b/es-core/src/GuiComponent.h @@ -9,11 +9,12 @@ #ifndef ES_CORE_GUI_COMPONENT_H #define ES_CORE_GUI_COMPONENT_H -#include "math/Misc.h" -#include "math/Transform4x4f.h" #include "HelpPrompt.h" #include "HelpStyle.h" #include "InputConfig.h" +#include "animations/AnimationController.h" +#include "math/Misc.h" +#include "math/Transform4x4f.h" #include #include @@ -65,72 +66,84 @@ public: // 4. Tell your children to render, based on your component's transform - renderChildren(t). virtual void render(const Transform4x4f& parentTrans); - Vector3f getPosition() const; - inline void setPosition(const Vector3f& offset) - { setPosition(offset.x(), offset.y(), offset.z()); } + Vector3f getPosition() const { return mPosition; } + void setPosition(const Vector3f& offset) { setPosition(offset.x(), offset.y(), offset.z()); } void setPosition(float x, float y, float z = 0.0f); - virtual void onPositionChanged() {}; + virtual void onPositionChanged() {} + Vector2f getOrigin() const { return mOrigin; } // Sets the origin as a percentage of this image. // (e.g. (0, 0) is top left, (0.5, 0.5) is the center.) - Vector2f getOrigin() const; void setOrigin(float originX, float originY); - inline void setOrigin(Vector2f origin) { setOrigin(origin.x(), origin.y()); } - virtual void onOriginChanged() {}; + void setOrigin(Vector2f origin) { setOrigin(origin.x(), origin.y()); } + virtual void onOriginChanged() {} + Vector2f getRotationOrigin() const { return mRotationOrigin; } // Sets the rotation origin as a percentage of this image. // (e.g. (0, 0) is top left, (0.5, 0.5) is the center.) - Vector2f getRotationOrigin() const; - void setRotationOrigin(float originX, float originY); - inline void setRotationOrigin(Vector2f origin) - { setRotationOrigin(origin.x(), origin.y()); } + void setRotationOrigin(float originX, float originY) + { + mRotationOrigin = Vector2f(originX, originY); + } + void setRotationOrigin(Vector2f origin) { setRotationOrigin(origin.x(), origin.y()); } - virtual Vector2f getSize() const; - inline void setSize(const Vector2f& size) { setSize(size.x(), size.y()); } + virtual Vector2f getSize() const { return mSize; } + void setSize(const Vector2f& size) { setSize(size.x(), size.y()); } void setSize(float w, float h); - virtual void setResize(float width, float height) {}; - virtual void onSizeChanged() {}; + virtual void setResize(float width, float height) {} + virtual void onSizeChanged() {} - virtual Vector2f getRotationSize() const { return getSize(); }; + virtual Vector2f getRotationSize() const { return getSize(); } + float getRotation() const { return mRotation; } + void setRotation(float rotation) { mRotation = rotation; } + void setRotationDegrees(float rotation) + { + setRotation(static_cast(ES_DEG_TO_RAD(rotation))); + } - float getRotation() const; - void setRotation(float rotation); - inline void setRotationDegrees(float rotation) { - setRotation(static_cast(ES_DEG_TO_RAD(rotation))); } + float getScale() const { return mScale; } + void setScale(float scale) { mScale = scale; } - float getScale() const; - void setScale(float scale); + float getZIndex() const { return mZIndex; } + void setZIndex(float zIndex) { mZIndex = zIndex; } - float getZIndex() const; - void setZIndex(float zIndex); + float getDefaultZIndex() const { return mDefaultZIndex; } + void setDefaultZIndex(float zIndex) { mDefaultZIndex = zIndex; } - float getDefaultZIndex() const; - void setDefaultZIndex(float zIndex); - - bool isVisible() const; - void setVisible(bool visible); + bool isVisible() const { return mVisible; } + void setVisible(bool visible) { mVisible = visible; } // Returns the center point of the image (takes origin into account). Vector2f getCenter() const; - void setParent(GuiComponent* parent); - GuiComponent* getParent() const; + void setParent(GuiComponent* parent) { mParent = parent; } + GuiComponent* getParent() const { return mParent; } void addChild(GuiComponent* cmp); void removeChild(GuiComponent* cmp); - void clearChildren(); + void clearChildren() { mChildren.clear(); } void sortChildren(); - unsigned int getChildCount() const; + unsigned int getChildCount() const { return static_cast(mChildren.size()); } int getChildIndex() const; - GuiComponent* getChild(unsigned int i) const; + GuiComponent* getChild(unsigned int i) const { return mChildren.at(i); } // Animation will be automatically deleted when it completes or is stopped. - bool isAnimationPlaying(unsigned char slot) const; - bool isAnimationReversed(unsigned char slot) const; - int getAnimationTime(unsigned char slot) const; - void setAnimation(Animation* animation, int delay = 0, - std::function finishedCallback = nullptr, - bool reverse = false, unsigned char slot = 0); + bool isAnimationPlaying(unsigned char slot) const { return mAnimationMap[slot] != nullptr; } + bool isAnimationReversed(unsigned char slot) const + { + assert(mAnimationMap[slot] != nullptr); + return mAnimationMap[slot]->isReversed(); + } + int getAnimationTime(unsigned char slot) const + { + assert(mAnimationMap[slot] != nullptr); + return mAnimationMap[slot]->getTime(); + } + void setAnimation(Animation* animation, + int delay = 0, + std::function finishedCallback = nullptr, + bool reverse = false, + unsigned char slot = 0); bool stopAnimation(unsigned char slot); // Like stopAnimation, but doesn't call finishedCallback - only removes the animation, leaving // things in their current state. Returns true if successful (an animation was in this slot). @@ -143,45 +156,53 @@ public: void stopAllAnimations(); void cancelAllAnimations(); - virtual bool isListScrolling() { return false; }; - virtual void stopListScrolling() {}; - virtual unsigned char getOpacity() const; + virtual bool isListScrolling() { return false; } + virtual void stopListScrolling() {} + virtual unsigned char getOpacity() const { return mOpacity; } virtual void setOpacity(unsigned char opacity); - virtual unsigned int getColor() const; - virtual unsigned int getColorShift() const; - virtual void setColor(unsigned int color); - virtual float getSaturation() const; - virtual void setSaturation(float saturation); - virtual void setColorShift(unsigned int color); - virtual void setOriginalColor(unsigned int color) { mColorOriginalValue = color; }; - virtual void setChangedColor(unsigned int color) { mColorChangedValue = color; }; + virtual unsigned int getColor() const { return mColor; } + virtual unsigned int getColorShift() const { return mColorShift; } + virtual void setColor(unsigned int color) + { + mColor = color; + mColorOpacity = mColor & 0x000000FF; + } + virtual float getSaturation() const { return static_cast(mColor); } + virtual void setSaturation(float saturation) { mSaturation = saturation; } + virtual void setColorShift(unsigned int color) + { + mColorShift = color; + mColorShiftEnd = color; + } + virtual void setOriginalColor(unsigned int color) { mColorOriginalValue = color; } + virtual void setChangedColor(unsigned int color) { mColorChangedValue = color; } // These functions are used to enable and disable options in menus, i.e. switches and similar. - virtual bool getEnabled() { return mEnabled; }; - virtual void setEnabled(bool state) { mEnabled = state; }; + virtual bool getEnabled() { return mEnabled; } + virtual void setEnabled(bool state) { mEnabled = state; } - virtual std::shared_ptr getFont() const { return nullptr; }; + virtual std::shared_ptr getFont() const { return nullptr; } const Transform4x4f& getTransform(); - virtual std::string getValue() const; - virtual void setValue(const std::string& value); + virtual std::string getValue() const { return ""; } + virtual void setValue(const std::string& value) {} - virtual std::string getHiddenValue() const; - virtual void setHiddenValue(const std::string& value); + virtual std::string getHiddenValue() const { return ""; } + virtual void setHiddenValue(const std::string& value) {} // Used to set the parameters for ScrollableContainer. - virtual void setScrollParameters(float, float, int) {}; + virtual void setScrollParameters(float, float, int) {} - virtual void onFocusGained() {}; - virtual void onFocusLost() {}; + virtual void onFocusGained() {} + virtual void onFocusLost() {} virtual void onShow(); virtual void onHide(); virtual void onStopVideo(); virtual void onPauseVideo(); virtual void onUnpauseVideo(); - virtual bool isVideoPaused() { return false; }; + virtual bool isVideoPaused() { return false; } virtual void onScreensaverActivate(); virtual void onScreensaverDeactivate(); @@ -192,18 +213,20 @@ public: // Default implementation just handles and tags as normalized float pairs. // You probably want to keep this behavior for any derived classes as well as add your own. virtual void applyTheme(const std::shared_ptr& theme, - const std::string& view, const std::string& element, unsigned int properties); + const std::string& view, + const std::string& element, + unsigned int properties); // Returns a list of help prompts. - virtual std::vector getHelpPrompts() { return std::vector(); }; + virtual std::vector getHelpPrompts() { return std::vector(); } // Called whenever help prompts change. void updateHelpPrompts(); - virtual HelpStyle getHelpStyle(); + virtual HelpStyle getHelpStyle() { return HelpStyle(); } // Returns true if the component is busy doing background processing (e.g. HTTP downloads). - bool isProcessing() const; + bool isProcessing() const { return mIsProcessing; } const static unsigned char MAX_ANIMATIONS = 4; diff --git a/es-core/src/HelpStyle.cpp b/es-core/src/HelpStyle.cpp index 2e7f7ea1f..b57d55e73 100644 --- a/es-core/src/HelpStyle.cpp +++ b/es-core/src/HelpStyle.cpp @@ -31,9 +31,9 @@ void HelpStyle::applyTheme(const std::shared_ptr& theme, const std::s return; if (elem->has("pos")) - position = elem->get("pos") * - Vector2f(static_cast(Renderer::getScreenWidth()), - static_cast(Renderer::getScreenHeight())); + position = + elem->get("pos") * Vector2f(static_cast(Renderer::getScreenWidth()), + static_cast(Renderer::getScreenHeight())); if (elem->has("origin")) origin = elem->get("origin"); diff --git a/es-core/src/HttpReq.cpp b/es-core/src/HttpReq.cpp index 09fc67565..4888d346d 100644 --- a/es-core/src/HttpReq.cpp +++ b/es-core/src/HttpReq.cpp @@ -10,21 +10,21 @@ #include "HttpReq.h" +#include "Log.h" #include "resources/ResourceManager.h" #include "utils/FileSystemUtil.h" -#include "Log.h" #include CURLM* HttpReq::s_multi_handle; std::map HttpReq::s_requests; -std::string HttpReq::urlEncode(const std::string &s) +std::string HttpReq::urlEncode(const std::string& s) { const std::string unreserved = - "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.~"; + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.~"; - std::string escaped=""; + std::string escaped = ""; for (size_t i = 0; i < s.length(); i++) { if (unreserved.find_first_of(s[i]) != std::string::npos) { escaped.push_back(s[i]); @@ -43,11 +43,13 @@ bool HttpReq::isUrl(const std::string& str) { // The worst guess. return (!str.empty() && !Utils::FileSystem::exists(str) && - (str.find("http://") != std::string::npos || str.find("https://") != - std::string::npos || str.find("www.") != std::string::npos)); + (str.find("http://") != std::string::npos || + str.find("https://") != std::string::npos || str.find("www.") != std::string::npos)); } -HttpReq::HttpReq(const std::string& url) : mStatus(REQ_IN_PROGRESS), mHandle(nullptr) +HttpReq::HttpReq(const std::string& url) + : mStatus(REQ_IN_PROGRESS) + , mHandle(nullptr) { // The multi-handle is cleaned up via a call from GuiScraperSearch after the scraping // has been completed for a game, meaning the handle is valid for all cURL requests @@ -57,14 +59,16 @@ HttpReq::HttpReq(const std::string& url) : mStatus(REQ_IN_PROGRESS), mHandle(nul mHandle = curl_easy_init(); +#if defined(_WIN64) // On Windows, use the bundled cURL TLS/SSL certificates (which actually come from the // Mozilla project). There is a possibility to use the OS provided Schannel certificates // but I haven't been able to get this to work and it also seems to be problematic on // older Windows versions. - #if defined(_WIN64) - curl_easy_setopt(mHandle, CURLOPT_CAINFO, ResourceManager::getInstance()-> - getResourcePath(":/certificates/curl-ca-bundle.crt").c_str()); - #endif + curl_easy_setopt(mHandle, CURLOPT_CAINFO, + ResourceManager::getInstance() + ->getResourcePath(":/certificates/curl-ca-bundle.crt") + .c_str()); +#endif if (mHandle == nullptr) { mStatus = REQ_IO_ERROR; @@ -140,8 +144,8 @@ HttpReq::~HttpReq() CURLMcode merr = curl_multi_remove_handle(s_multi_handle, mHandle); if (merr != CURLM_OK) { - LOG(LogError) << "Error removing curl_easy handle from curl_multi: " << - curl_multi_strerror(merr); + LOG(LogError) << "Error removing curl_easy handle from curl_multi: " + << curl_multi_strerror(merr); } curl_easy_cleanup(mHandle); @@ -194,16 +198,6 @@ std::string HttpReq::getContent() const return mContent.str(); } -void HttpReq::onError(const std::string& msg) -{ - mErrorMsg = msg; -} - -std::string HttpReq::getErrorMsg() -{ - return mErrorMsg; -} - // Used as a curl callback. // size = size of an element, nmemb = number of elements. // Return value is number of elements successfully read. diff --git a/es-core/src/HttpReq.h b/es-core/src/HttpReq.h index 3f294dbae..28a5ff228 100644 --- a/es-core/src/HttpReq.h +++ b/es-core/src/HttpReq.h @@ -43,6 +43,7 @@ public: ~HttpReq(); enum Status { + // clang-format off REQ_IN_PROGRESS, // Request is in progress. REQ_SUCCESS, // Request completed successfully, get it with getContent(). REQ_IO_ERROR, // Some error happened, get it with getErrorMsg(). @@ -50,13 +51,14 @@ public: REQ_BAD_STATUS_CODE, // Some invalid HTTP response status code happened (non-200). REQ_INVALID_RESPONSE, // The HTTP response was invalid. REQ_UNDEFINED_ERROR + // clang-format on }; Status status(); // Process any received data and return the status afterwards. - std::string getErrorMsg(); + std::string getErrorMsg() { return mErrorMsg; } std::string getContent() const; // mStatus must be REQ_SUCCESS. - static std::string urlEncode(const std::string &s); + static std::string urlEncode(const std::string& s); static bool isUrl(const std::string& s); static void cleanupCurlMulti() @@ -65,11 +67,11 @@ public: curl_multi_cleanup(s_multi_handle); s_multi_handle = nullptr; } - }; + } private: static size_t write_content(void* buff, size_t size, size_t nmemb, void* req_ptr); - void onError(const std::string& msg); + void onError(const std::string& msg) { mErrorMsg = msg; } // God dammit libcurl why can't you have some way to check the status of an // individual handle why do I have to handle ALL messages at once. diff --git a/es-core/src/ImageIO.cpp b/es-core/src/ImageIO.cpp index 54710c98c..6793fa79c 100644 --- a/es-core/src/ImageIO.cpp +++ b/es-core/src/ImageIO.cpp @@ -14,7 +14,9 @@ #include std::vector ImageIO::loadFromMemoryRGBA32(const unsigned char* data, - const size_t size, size_t& width, size_t& height) + const size_t size, + size_t& width, + size_t& height) { std::vector rawData; width = 0; @@ -44,8 +46,7 @@ std::vector ImageIO::loadFromMemoryRGBA32(const unsigned char* da // This is necessary, because width*height*bpp might not be == pitch. unsigned char* tempData = new unsigned char[width * height * 4]; for (size_t i = 0; i < height; i++) { - const BYTE* scanLine = - FreeImage_GetScanLine(fiBitmap, static_cast(i)); + const BYTE* scanLine = FreeImage_GetScanLine(fiBitmap, static_cast(i)); memcpy(tempData + (i * width * 4), scanLine, width * 4); } // Convert from BGRA to RGBA. @@ -69,8 +70,8 @@ std::vector ImageIO::loadFromMemoryRGBA32(const unsigned char* da } } else { - LOG(LogError) << "Couldn't load image, file is missing or the file type is " << - (format == FIF_UNKNOWN ? "unknown" : "unsupported"); + LOG(LogError) << "Couldn't load image, file is missing or the file type is " + << (format == FIF_UNKNOWN ? "unknown" : "unsupported"); } // Free fiMemory again. FreeImage_CloseMemory(fiMemory); diff --git a/es-core/src/ImageIO.h b/es-core/src/ImageIO.h index 60c83b03b..3fd62e267 100644 --- a/es-core/src/ImageIO.h +++ b/es-core/src/ImageIO.h @@ -16,7 +16,9 @@ class ImageIO { public: static std::vector loadFromMemoryRGBA32(const unsigned char* data, - const size_t size, size_t& width, size_t& height); + const size_t size, + size_t& width, + size_t& height); static void flipPixelsVert(unsigned char* imagePx, const size_t& width, const size_t& height); }; diff --git a/es-core/src/InputConfig.cpp b/es-core/src/InputConfig.cpp index 8980ba58e..2a68c3a8a 100644 --- a/es-core/src/InputConfig.cpp +++ b/es-core/src/InputConfig.cpp @@ -12,13 +12,10 @@ #include -InputConfig::InputConfig( - int deviceId, - const std::string& deviceName, - const std::string& deviceGUID) - : mDeviceId(deviceId), - mDeviceName(deviceName), - mDeviceGUID(deviceGUID) +InputConfig::InputConfig(int deviceId, const std::string& deviceName, const std::string& deviceGUID) + : mDeviceId(deviceId) + , mDeviceName(deviceName) + , mDeviceGUID(deviceGUID) { } @@ -59,16 +56,6 @@ std::string InputConfig::toLower(std::string str) return str; } -void InputConfig::clear() -{ - mNameMap.clear(); -} - -bool InputConfig::isConfigured() -{ - return mNameMap.size() > 0; -} - void InputConfig::mapInput(const std::string& name, Input input) { mNameMap[toLower(name)] = input; @@ -100,19 +87,19 @@ bool InputConfig::isMappedLike(const std::string& name, Input input) { if (name == "left") { return isMappedTo("left", input) || isMappedTo("leftthumbstickleft", input) || - isMappedTo("rightthumbstickleft", input); + isMappedTo("rightthumbstickleft", input); } else if (name == "right") { return isMappedTo("right", input) || isMappedTo("leftthumbstickright", input) || - isMappedTo("rightthumbstickright", input); + isMappedTo("rightthumbstickright", input); } else if (name == "up") { return isMappedTo("up", input) || isMappedTo("leftthumbstickup", input) || - isMappedTo("rightthumbstickup", input); + isMappedTo("rightthumbstickup", input); } else if (name == "down") { return isMappedTo("down", input) || isMappedTo("leftthumbstickdown", input) || - isMappedTo("rightthumbstickdown", input); + isMappedTo("rightthumbstickdown", input); } else if (name == "leftshoulder") { return isMappedTo("leftshoulder", input) || isMappedTo("pageup", input); @@ -182,8 +169,8 @@ void InputConfig::loadFromXML(pugi::xml_node& node) InputType typeEnum = stringToInputType(type); if (typeEnum == TYPE_COUNT) { - LOG(LogError) << "InputConfig load error - input of type \"" << type << - "\" is invalid! Skipping input \"" << name << "\".\n"; + LOG(LogError) << "InputConfig load error - input of type \"" << type + << "\" is invalid! Skipping input \"" << name << "\".\n"; continue; } @@ -191,8 +178,7 @@ void InputConfig::loadFromXML(pugi::xml_node& node) int value = input.attribute("value").as_int(); if (value == 0) { - LOG(LogWarning) << "InputConfig value is 0 for " << - type << " " << id << "!\n"; + LOG(LogWarning) << "InputConfig value is 0 for " << type << " " << id << "!\n"; } mNameMap[toLower(name)] = Input(mDeviceId, typeEnum, id, value, true); diff --git a/es-core/src/InputConfig.h b/es-core/src/InputConfig.h index 9f412c672..be7a06ee3 100644 --- a/es-core/src/InputConfig.h +++ b/es-core/src/InputConfig.h @@ -9,18 +9,18 @@ #ifndef ES_CORE_INPUT_CONFIG_H #define ES_CORE_INPUT_CONFIG_H +#include #include #include -#include #include #include #include #define DEVICE_KEYBOARD -1 -#define DEVICE_CEC -2 +#define DEVICE_CEC -2 enum InputType { - TYPE_AXIS, + TYPE_AXIS, // Replace with AllowShortEnumsOnASingleLine: false (clang-format >=11.0). TYPE_BUTTON, TYPE_KEY, TYPE_CEC_BUTTON, @@ -32,8 +32,7 @@ namespace pugi class xml_node; } -struct Input -{ +struct Input { public: int device; InputType type; @@ -50,23 +49,16 @@ public: type = TYPE_COUNT; } - Input( - int dev, - InputType t, - int i, - int val, - bool conf) - : device(dev), - type(t),id(i), - value(val), - configured(conf) + Input(int dev, InputType t, int i, int val, bool conf) + : device(dev) + , type(t) + , id(i) + , value(val) + , configured(conf) { } - std::string getCECButtonName(int keycode) - { - return CECInput::getKeyCodeString(keycode); - } + std::string getCECButtonName(int keycode) { return CECInput::getKeyCodeString(keycode); } std::string string() { @@ -113,8 +105,8 @@ public: InputType stringToInputType(const std::string& type); std::string toLower(std::string str); - void clear(); - bool isConfigured(); + void clear() { mNameMap.clear(); } + bool isConfigured() { return mNameMap.size() > 0; } void mapInput(const std::string& name, Input input); void unmapInput(const std::string& name); // Unmap all Inputs mapped to this name. @@ -134,9 +126,9 @@ public: void loadFromXML(pugi::xml_node& root); void writeToXML(pugi::xml_node& parent); - inline int getDeviceId() const { return mDeviceId; }; - inline const std::string& getDeviceName() { return mDeviceName; } - inline const std::string& getDeviceGUIDString() { return mDeviceGUID; } + int getDeviceId() const { return mDeviceId; } + const std::string& getDeviceName() { return mDeviceName; } + const std::string& getDeviceGUIDString() { return mDeviceGUID; } private: std::map mNameMap; diff --git a/es-core/src/InputManager.cpp b/es-core/src/InputManager.cpp index 92fff54e7..ad6ffb624 100644 --- a/es-core/src/InputManager.cpp +++ b/es-core/src/InputManager.cpp @@ -10,14 +10,14 @@ #include "InputManager.h" -#include "resources/ResourceManager.h" -#include "utils/FileSystemUtil.h" -#include "utils/StringUtil.h" #include "CECInput.h" #include "Log.h" #include "Platform.h" #include "Scripting.h" #include "Window.h" +#include "resources/ResourceManager.h" +#include "utils/FileSystemUtil.h" +#include "utils/StringUtil.h" #include #include @@ -30,12 +30,14 @@ int SDL_USER_CECBUTTONUP = -1; InputManager* InputManager::sInstance = nullptr; -InputManager::InputManager() : mKeyboardInputConfig(nullptr) +InputManager::InputManager() + : mKeyboardInputConfig(nullptr) { } InputManager::~InputManager() { + // Deinit when destroyed. deinit(); } @@ -66,8 +68,8 @@ void InputManager::init() mConfigFileExists = true; } - mKeyboardInputConfig = std::make_unique(DEVICE_KEYBOARD, - "Keyboard", KEYBOARD_GUID_STRING); + mKeyboardInputConfig = + std::make_unique(DEVICE_KEYBOARD, "Keyboard", KEYBOARD_GUID_STRING); bool customConfig = loadInputConfig(mKeyboardInputConfig.get()); @@ -84,18 +86,18 @@ void InputManager::init() // the bundled mapping is incorrect, or the SDL version is a bit older, it makes sense to be // able to customize this. If a controller GUID is present in the mappings file that is // already present inside SDL, the custom mapping will overwrite the bundled one. - std::string mappingsFile = Utils::FileSystem::getHomePath() + - "/.emulationstation/" + "es_controller_mappings.cfg"; + std::string mappingsFile = + Utils::FileSystem::getHomePath() + "/.emulationstation/" + "es_controller_mappings.cfg"; if (!Utils::FileSystem::exists(mappingsFile)) - mappingsFile = ResourceManager::getInstance()-> - getResourcePath(":/controllers/es_controller_mappings.cfg"); + mappingsFile = ResourceManager::getInstance()->getResourcePath( + ":/controllers/es_controller_mappings.cfg"); int controllerMappings = SDL_GameControllerAddMappingsFromFile(mappingsFile.c_str()); if (controllerMappings != -1 && controllerMappings != 0) { - LOG(LogInfo) << "Loaded " << controllerMappings << " controller " << - (controllerMappings == 1 ? "mapping" : "mappings"); + LOG(LogInfo) << "Loaded " << controllerMappings << " controller " + << (controllerMappings == 1 ? "mapping" : "mappings"); } int numJoysticks = SDL_NumJoysticks(); @@ -150,18 +152,20 @@ void InputManager::writeDeviceConfig(InputConfig* config) std::string path = getConfigPath(); LOG(LogDebug) << "InputManager::writeDeviceConfig(): " - "Saving input configuration file to \"" << path << "\""; + "Saving input configuration file to \"" + << path << "\""; pugi::xml_document doc; if (Utils::FileSystem::exists(path)) { // Merge files. - #if defined(_WIN64) + +#if defined(_WIN64) pugi::xml_parse_result result = - doc.load_file(Utils::String::stringToWideString(path).c_str()); - #else + doc.load_file(Utils::String::stringToWideString(path).c_str()); +#else pugi::xml_parse_result result = doc.load_file(path.c_str()); - #endif +#endif if (!result) { LOG(LogError) << "Couldn't parse input configuration file: " << result.description(); } @@ -172,8 +176,8 @@ void InputManager::writeDeviceConfig(InputConfig* config) // If inputAction @type=onfinish is set, let doOnFinish command take care of // creating input configuration. We just put the input configuration into a // temporary input config file. - pugi::xml_node actionnode = root.find_child_by_attribute("inputAction", - "type", "onfinish"); + pugi::xml_node actionnode = + root.find_child_by_attribute("inputAction", "type", "onfinish"); if (actionnode) { path = getTemporaryConfigPath(); doc.reset(); @@ -181,12 +185,12 @@ void InputManager::writeDeviceConfig(InputConfig* config) root.append_copy(actionnode); } else { - pugi::xml_node oldEntry = root.find_child_by_attribute("inputConfig", - "deviceGUID", config->getDeviceGUIDString().c_str()); + pugi::xml_node oldEntry = root.find_child_by_attribute( + "inputConfig", "deviceGUID", config->getDeviceGUIDString().c_str()); if (oldEntry) root.remove_child(oldEntry); oldEntry = root.find_child_by_attribute("inputConfig", "deviceName", - config->getDeviceName().c_str()); + config->getDeviceName().c_str()); if (oldEntry) root.remove_child(oldEntry); } @@ -200,11 +204,11 @@ void InputManager::writeDeviceConfig(InputConfig* config) config->writeToXML(root); - #if defined(_WIN64) +#if defined(_WIN64) doc.save_file(Utils::String::stringToWideString(path).c_str()); - #else +#else doc.save_file(path.c_str()); - #endif +#endif Scripting::fireEvent("config-changed"); Scripting::fireEvent("controls-changed"); @@ -222,12 +226,12 @@ void InputManager::doOnFinish() pugi::xml_document doc; if (Utils::FileSystem::exists(path)) { - #if defined(_WIN64) +#if defined(_WIN64) pugi::xml_parse_result result = - doc.load_file(Utils::String::stringToWideString(path).c_str()); - #else + doc.load_file(Utils::String::stringToWideString(path).c_str()); +#else pugi::xml_parse_result result = doc.load_file(path.c_str()); - #endif +#endif if (!result) { LOG(LogError) << "Couldn't parse input configuration file: " << result.description(); @@ -238,18 +242,18 @@ void InputManager::doOnFinish() root = root.find_child_by_attribute("inputAction", "type", "onfinish"); if (root) { for (pugi::xml_node command = root.child("command"); command; - command = command.next_sibling("command")) { + command = command.next_sibling("command")) { std::string tocall = command.text().get(); LOG(LogInfo) << " " << tocall; std::cout << "==============================================\n" - "input config finish command:\n"; + "input config finish command:\n"; int exitCode = runSystemCommand(tocall); std::cout << "==============================================\n"; if (exitCode != 0) { - LOG(LogWarning) << "...launch terminated with nonzero exit code " << - exitCode << "!"; + LOG(LogWarning) << "...launch terminated with nonzero exit code " + << exitCode << "!"; } } } @@ -298,11 +302,11 @@ int InputManager::getButtonCountByDevice(SDL_JoystickID id) if (id == DEVICE_KEYBOARD) return -1; else if (id == DEVICE_CEC) - #if defined(HAVE_CECLIB) +#if defined(HAVE_CECLIB) return CEC::CEC_USER_CONTROL_CODE_MAX; - #else +#else return 0; - #endif +#endif else return SDL_JoystickNumButtons(mJoysticks[id]); } @@ -343,10 +347,10 @@ bool InputManager::parseEvent(const SDL_Event& event, Window* window) switch (event.type) { case SDL_CONTROLLERAXISMOTION: { - // Whether to only accept input from the first controller. - if (Settings::getInstance()->getBool("InputOnlyFirstController")) - if (mInputConfigs.begin()->first != event.cdevice.which) - return false; + // Whether to only accept input from the first controller. + if (Settings::getInstance()->getBool("InputOnlyFirstController")) + if (mInputConfigs.begin()->first != event.cdevice.which) + return false; // This is needed for a situation which sometimes occur when a game is launched, // some axis input is generated and then the controller is disconnected before @@ -363,14 +367,17 @@ bool InputManager::parseEvent(const SDL_Event& event, Window* window) int deadzone = 0; if (event.caxis.axis == SDL_CONTROLLER_AXIS_TRIGGERLEFT || - event.caxis.axis == SDL_CONTROLLER_AXIS_TRIGGERRIGHT) + event.caxis.axis == SDL_CONTROLLER_AXIS_TRIGGERRIGHT) { deadzone = DEADZONE_TRIGGERS; - else + } + else { deadzone = DEADZONE_THUMBSTICKS; + } // Check if the input value switched boundaries. - if ((abs(axisValue) > deadzone) != (abs(mPrevAxisValues[ - std::make_pair(event.caxis.which, event.caxis.axis)]) > deadzone)) { + if ((abs(axisValue) > deadzone) != + (abs(mPrevAxisValues[std::make_pair(event.caxis.which, event.caxis.axis)]) > + deadzone)) { int normValue; if (abs(axisValue) <= deadzone) { normValue = 0; @@ -382,8 +389,9 @@ bool InputManager::parseEvent(const SDL_Event& event, Window* window) normValue = -1; } - window->input(getInputConfigByDevice(event.caxis.which), Input(event.caxis.which, - TYPE_AXIS, event.caxis.axis, normValue, false)); + window->input( + getInputConfigByDevice(event.caxis.which), + Input(event.caxis.which, TYPE_AXIS, event.caxis.axis, normValue, false)); causedEvent = true; } @@ -393,26 +401,27 @@ bool InputManager::parseEvent(const SDL_Event& event, Window* window) case SDL_CONTROLLERBUTTONDOWN: { } case SDL_CONTROLLERBUTTONUP: { - // Whether to only accept input from the first controller. - if (Settings::getInstance()->getBool("InputOnlyFirstController")) - if (mInputConfigs.begin()->first != event.cdevice.which) - return false; + // Whether to only accept input from the first controller. + if (Settings::getInstance()->getBool("InputOnlyFirstController")) + if (mInputConfigs.begin()->first != event.cdevice.which) + return false; // The event filtering below is required as some controllers send button presses // starting with the state 0 when using the D-pad. I consider this invalid behaviour // and the more popular controllers such as those from Microsoft and Sony do not show // this strange behavior. - int buttonState = mPrevButtonValues[ - std::make_pair(event.cbutton.which, event.cbutton.button)]; + int buttonState = + mPrevButtonValues[std::make_pair(event.cbutton.which, event.cbutton.button)]; if ((buttonState == -1 || buttonState == 0) && event.cbutton.state == 0) return false; mPrevButtonValues[std::make_pair(event.cbutton.which, event.cbutton.button)] = - event.cbutton.state; + event.cbutton.state; - window->input(getInputConfigByDevice(event.cbutton.which), Input(event.cbutton.which, - TYPE_BUTTON, event.cbutton.button, event.cbutton.state == SDL_PRESSED, false)); + window->input(getInputConfigByDevice(event.cbutton.which), + Input(event.cbutton.which, TYPE_BUTTON, event.cbutton.button, + event.cbutton.state == SDL_PRESSED, false)); return true; } @@ -430,13 +439,13 @@ bool InputManager::parseEvent(const SDL_Event& event, Window* window) return false; } - window->input(getInputConfigByDevice(DEVICE_KEYBOARD), Input(DEVICE_KEYBOARD, - TYPE_KEY, event.key.keysym.sym, 1, false)); + window->input(getInputConfigByDevice(DEVICE_KEYBOARD), + Input(DEVICE_KEYBOARD, TYPE_KEY, event.key.keysym.sym, 1, false)); return true; } case SDL_KEYUP: { - window->input(getInputConfigByDevice(DEVICE_KEYBOARD), Input(DEVICE_KEYBOARD, - TYPE_KEY, event.key.keysym.sym, 0, false)); + window->input(getInputConfigByDevice(DEVICE_KEYBOARD), + Input(DEVICE_KEYBOARD, TYPE_KEY, event.key.keysym.sym, 0, false)); return true; } case SDL_TEXTINPUT: { @@ -454,21 +463,17 @@ bool InputManager::parseEvent(const SDL_Event& event, Window* window) } if ((event.type == static_cast(SDL_USER_CECBUTTONDOWN)) || - (event.type == static_cast(SDL_USER_CECBUTTONUP))) { - window->input(getInputConfigByDevice(DEVICE_CEC), Input(DEVICE_CEC, - TYPE_CEC_BUTTON, event.user.code, event.type == - static_cast(SDL_USER_CECBUTTONDOWN), false)); + (event.type == static_cast(SDL_USER_CECBUTTONUP))) { + window->input(getInputConfigByDevice(DEVICE_CEC), + Input(DEVICE_CEC, TYPE_CEC_BUTTON, event.user.code, + event.type == static_cast(SDL_USER_CECBUTTONDOWN), + false)); return true; } return false; } -bool InputManager::initialized() const -{ - return mKeyboardInputConfig != nullptr; -} - bool InputManager::loadInputConfig(InputConfig* config) { if (!mConfigFileExists) @@ -477,11 +482,11 @@ bool InputManager::loadInputConfig(InputConfig* config) std::string path = getConfigPath(); pugi::xml_document doc; - #if defined(_WIN64) +#if defined(_WIN64) pugi::xml_parse_result res = doc.load_file(Utils::String::stringToWideString(path).c_str()); - #else +#else pugi::xml_parse_result res = doc.load_file(path.c_str()); - #endif +#endif if (!res) { LOG(LogError) << "Couldn't parse the input configuration file: " << res.description(); @@ -492,16 +497,16 @@ bool InputManager::loadInputConfig(InputConfig* config) if (!root) return false; - pugi::xml_node configNode = root.find_child_by_attribute("inputConfig", - "deviceGUID", config->getDeviceGUIDString().c_str()); + pugi::xml_node configNode = root.find_child_by_attribute("inputConfig", "deviceGUID", + config->getDeviceGUIDString().c_str()); // Enabling this will match an entry in es_input.xml based on the device name if there // was no GUID match. This is probably not a good idea as many controllers share the same // name even though the GUID differ and potentially the button configuration could be // different between them. Keeping the code for now though. -// if (!configNode) -// configNode = root.find_child_by_attribute("inputConfig", -// "deviceName", config->getDeviceName().c_str()); + // if (!configNode) + // configNode = root.find_child_by_attribute("inputConfig", + // "deviceName", config->getDeviceName().c_str()); // With the move to the SDL GameController API the button layout changed quite a lot, so // es_input.xml files generated using the old API will end up with a completely unusable @@ -535,11 +540,11 @@ void InputManager::loadDefaultKBConfig() cfg->mapInput("A", Input(DEVICE_KEYBOARD, TYPE_KEY, SDLK_RETURN, 1, true)); cfg->mapInput("B", Input(DEVICE_KEYBOARD, TYPE_KEY, SDLK_BACKSPACE, 1, true)); cfg->mapInput("X", Input(DEVICE_KEYBOARD, TYPE_KEY, SDLK_DELETE, 1, true)); - #if defined(__APPLE__) +#if defined(__APPLE__) cfg->mapInput("Y", Input(DEVICE_KEYBOARD, TYPE_KEY, SDLK_PRINTSCREEN, 1, true)); - #else +#else cfg->mapInput("Y", Input(DEVICE_KEYBOARD, TYPE_KEY, SDLK_INSERT, 1, true)); - #endif +#endif cfg->mapInput("Start", Input(DEVICE_KEYBOARD, TYPE_KEY, SDLK_ESCAPE, 1, true)); cfg->mapInput("Back", Input(DEVICE_KEYBOARD, TYPE_KEY, SDLK_F1, 1, true)); @@ -559,6 +564,7 @@ void InputManager::loadDefaultControllerConfig(SDL_JoystickID deviceIndex) if (cfg->isConfigured()) return; + // clang-format off cfg->mapInput("Up", Input(deviceIndex, TYPE_BUTTON, SDL_CONTROLLER_BUTTON_DPAD_UP, 1, true)); cfg->mapInput("Down", Input(deviceIndex, TYPE_BUTTON, SDL_CONTROLLER_BUTTON_DPAD_DOWN, 1, true)); cfg->mapInput("Left", Input(deviceIndex, TYPE_BUTTON, SDL_CONTROLLER_BUTTON_DPAD_LEFT, 1, true)); @@ -583,6 +589,7 @@ void InputManager::loadDefaultControllerConfig(SDL_JoystickID deviceIndex) cfg->mapInput("RightThumbstickLeft", Input(deviceIndex, TYPE_AXIS, SDL_CONTROLLER_AXIS_RIGHTX, -1, true)); cfg->mapInput("RightThumbstickRight", Input(deviceIndex, TYPE_AXIS, SDL_CONTROLLER_AXIS_RIGHTX, 1, true)); cfg->mapInput("RightThumbstickClick", Input(deviceIndex, TYPE_BUTTON, SDL_CONTROLLER_BUTTON_RIGHTSTICK, 1, true)); + // clang-format on } void InputManager::addControllerByDeviceIndex(int deviceIndex) @@ -599,21 +606,21 @@ void InputManager::addControllerByDeviceIndex(int deviceIndex) char guid[65]; SDL_JoystickGetGUIDString(SDL_JoystickGetGUID(joy), guid, 65); - mInputConfigs[joyID] = std::make_unique( - joyID, SDL_GameControllerName(mControllers[joyID]), guid); + mInputConfigs[joyID] = + std::make_unique(joyID, SDL_GameControllerName(mControllers[joyID]), guid); bool customConfig = loadInputConfig(mInputConfigs[joyID].get()); if (customConfig) { - LOG(LogInfo) << "Added controller with custom configuration: \"" << - SDL_GameControllerName(mControllers[joyID]) << "\" (GUID: " << guid << - ", instance ID: " << joyID << ", device index: " << deviceIndex << ")"; + LOG(LogInfo) << "Added controller with custom configuration: \"" + << SDL_GameControllerName(mControllers[joyID]) << "\" (GUID: " << guid + << ", instance ID: " << joyID << ", device index: " << deviceIndex << ")"; } else { loadDefaultControllerConfig(joyID); - LOG(LogInfo) << "Added controller with default configuration: \"" << - SDL_GameControllerName(mControllers[joyID]) << "\" (GUID: " << guid << - ", instance ID: " << joyID << ", device index: " << deviceIndex << ")"; + LOG(LogInfo) << "Added controller with default configuration: \"" + << SDL_GameControllerName(mControllers[joyID]) << "\" (GUID: " << guid + << ", instance ID: " << joyID << ", device index: " << deviceIndex << ")"; } int numAxes = SDL_JoystickNumAxes(joy); @@ -634,8 +641,8 @@ void InputManager::removeControllerByJoystickID(SDL_JoystickID joyID) SDL_Joystick* joy = SDL_JoystickFromInstanceID(joyID); SDL_JoystickGetGUIDString(SDL_JoystickGetGUID(joy), guid, 65); - LOG(LogInfo) << "Removed controller \"" << SDL_GameControllerName(mControllers[joyID]) << - "\" (GUID: " << guid << ", instance ID: " << joyID << ")"; + LOG(LogInfo) << "Removed controller \"" << SDL_GameControllerName(mControllers[joyID]) + << "\" (GUID: " << guid << ", instance ID: " << joyID << ")"; // Delete mPrevAxisValues for the device. int axisEntries = static_cast(mPrevAxisValues.size()); diff --git a/es-core/src/InputManager.h b/es-core/src/InputManager.h index b675db2e0..5bdc89ea2 100644 --- a/es-core/src/InputManager.h +++ b/es-core/src/InputManager.h @@ -55,7 +55,7 @@ public: int getNumJoysticks() { return static_cast(mJoysticks.size()); } private: - bool initialized() const; + bool initialized() const { return mKeyboardInputConfig != nullptr; } bool loadInputConfig(InputConfig* config); void loadDefaultKBConfig(); diff --git a/es-core/src/Log.cpp b/es-core/src/Log.cpp index 680070685..2530e5067 100644 --- a/es-core/src/Log.cpp +++ b/es-core/src/Log.cpp @@ -8,32 +8,16 @@ #include "Log.h" -#include "utils/FileSystemUtil.h" -#include "utils/StringUtil.h" #include "Platform.h" +#include "utils/StringUtil.h" #include -#include #include +#include LogLevel Log::reportingLevel = LogInfo; std::ofstream file; -LogLevel Log::getReportingLevel() -{ - return reportingLevel; -} - -std::string Log::getLogPath() -{ - return Utils::FileSystem::getHomePath() + "/.emulationstation/es_log.txt"; -} - -void Log::setReportingLevel(LogLevel level) -{ - reportingLevel = level; -} - void Log::init() { Utils::FileSystem::removeFile(getLogPath() + ".bak"); @@ -44,24 +28,24 @@ void Log::init() void Log::open() { - #if defined(_WIN64) +#if defined(_WIN64) file.open(Utils::String::stringToWideString(getLogPath()).c_str()); - #else +#else file.open(getLogPath().c_str()); - #endif +#endif } std::ostringstream& Log::get(LogLevel level) { time_t t = time(nullptr); struct tm tm; - #if defined(_WIN64) +#if defined(_WIN64) // Of course Windows does not follow standards and puts the parameters the other way // around compared to POSIX. localtime_s(&tm, &t); - #else +#else localtime_r(&t, &tm); - #endif +#endif os << std::put_time(&tm, "%b %d %T ") << logLevelMap[level] << ":\t"; messageLevel = level; @@ -70,6 +54,7 @@ std::ostringstream& Log::get(LogLevel level) void Log::flush() { + // This runs on application exit. file.flush(); } @@ -85,8 +70,8 @@ Log::~Log() if (!file.is_open()) { // Not open yet, print to stdout. - std::cerr << "ERROR - tried to write to log file before it was open! " - "The following won't be logged:\n"; + std::cerr << "Error: Tried to write to log file before it was open, " + "the following won't be logged:\n"; std::cerr << os.str(); return; } diff --git a/es-core/src/Log.h b/es-core/src/Log.h index d12f58934..da45efd9f 100644 --- a/es-core/src/Log.h +++ b/es-core/src/Log.h @@ -9,15 +9,19 @@ #ifndef ES_CORE_LOG_H #define ES_CORE_LOG_H +#include "utils/FileSystemUtil.h" + #include #include -#define LOG(level) \ -if (level > Log::getReportingLevel()); \ -else Log().get(level) +#define LOG(level) \ + if (level > Log::getReportingLevel()) \ + ; \ + else \ + Log().get(level) enum LogLevel { - LogError, + LogError, // Replace with AllowShortEnumsOnASingleLine: false (clang-format >=11.0). LogWarning, LogInfo, LogDebug @@ -29,10 +33,12 @@ public: ~Log(); std::ostringstream& get(LogLevel level = LogInfo); - static LogLevel getReportingLevel(); - static void setReportingLevel(LogLevel level); - - static std::string getLogPath(); + static LogLevel getReportingLevel() { return reportingLevel; } + static void setReportingLevel(LogLevel level) { reportingLevel = level; } + static std::string getLogPath() + { + return Utils::FileSystem::getHomePath() + "/.emulationstation/es_log.txt"; + } static void flush(); static void init(); @@ -43,11 +49,11 @@ protected: std::ostringstream os; private: - std::map logLevelMap { - { LogError, "Error" }, - { LogWarning, "Warn" }, - { LogInfo, "Info" }, - { LogDebug, "Debug" } + std::map logLevelMap { // Log level indicators. + { LogError, "Error" }, + { LogWarning, "Warn" }, + { LogInfo, "Info" }, + { LogDebug, "Debug" } }; static LogLevel reportingLevel; diff --git a/es-core/src/MameNames.cpp b/es-core/src/MameNames.cpp index 2d4a8c409..30b1f4748 100644 --- a/es-core/src/MameNames.cpp +++ b/es-core/src/MameNames.cpp @@ -11,10 +11,10 @@ #include "MameNames.h" +#include "Log.h" #include "resources/ResourceManager.h" #include "utils/FileSystemUtil.h" #include "utils/StringUtil.h" -#include "Log.h" #include #include @@ -53,25 +53,23 @@ MameNames::MameNames() LOG(LogInfo) << "Parsing MAME names file \"" << xmlpath << "\"..."; pugi::xml_document doc; - #if defined(_WIN64) +#if defined(_WIN64) pugi::xml_parse_result result = - doc.load_file(Utils::String::stringToWideString(xmlpath).c_str()); - #else + doc.load_file(Utils::String::stringToWideString(xmlpath).c_str()); +#else pugi::xml_parse_result result = doc.load_file(xmlpath.c_str()); - #endif +#endif if (!result) { - LOG(LogError) << "Error parsing MAME names file \"" << xmlpath << "\": " - << result.description(); + LOG(LogError) << "Error parsing MAME names file \"" << xmlpath + << "\": " << result.description(); return; } - for (pugi::xml_node gameNode = doc.child("game"); - gameNode; gameNode = gameNode.next_sibling("game")) { - NamePair namePair = { - gameNode.child("mamename").text().get(), - gameNode.child("realname").text().get() - }; + for (pugi::xml_node gameNode = doc.child("game"); gameNode; + gameNode = gameNode.next_sibling("game")) { + NamePair namePair = { gameNode.child("mamename").text().get(), + gameNode.child("realname").text().get() }; mNamePairs.push_back(namePair); } @@ -83,20 +81,20 @@ MameNames::MameNames() LOG(LogInfo) << "Parsing MAME BIOSes file \"" << xmlpath << "\"..."; - #if defined(_WIN64) +#if defined(_WIN64) result = doc.load_file(Utils::String::stringToWideString(xmlpath).c_str()); - #else +#else result = doc.load_file(xmlpath.c_str()); - #endif +#endif if (!result) { - LOG(LogError) << "Error parsing MAME BIOSes file \"" << xmlpath << "\": " - << result.description(); + LOG(LogError) << "Error parsing MAME BIOSes file \"" << xmlpath + << "\": " << result.description(); return; } - for (pugi::xml_node biosNode = doc.child("bios"); - biosNode; biosNode = biosNode.next_sibling("bios")) { + for (pugi::xml_node biosNode = doc.child("bios"); biosNode; + biosNode = biosNode.next_sibling("bios")) { std::string bios = biosNode.text().get(); mMameBioses.push_back(bios); } @@ -109,29 +107,25 @@ MameNames::MameNames() LOG(LogInfo) << "Parsing MAME devices file \"" << xmlpath << "\"..."; - #if defined(_WIN64) +#if defined(_WIN64) result = doc.load_file(Utils::String::stringToWideString(xmlpath).c_str()); - #else +#else result = doc.load_file(xmlpath.c_str()); - #endif +#endif if (!result) { - LOG(LogError) << "Error parsing MAME devices file \"" << xmlpath << "\": " - << result.description(); + LOG(LogError) << "Error parsing MAME devices file \"" << xmlpath + << "\": " << result.description(); return; } - for (pugi::xml_node deviceNode = doc.child("device"); - deviceNode; deviceNode = deviceNode.next_sibling("device")) { + for (pugi::xml_node deviceNode = doc.child("device"); deviceNode; + deviceNode = deviceNode.next_sibling("device")) { std::string device = deviceNode.text().get(); mMameDevices.push_back(device); } } -MameNames::~MameNames() -{ -} - std::string MameNames::getRealName(const std::string& _mameName) { size_t start = 0; @@ -158,17 +152,6 @@ std::string MameNames::getCleanName(const std::string& _mameName) return cleanName; } -const bool MameNames::isBios(const std::string& _biosName) -{ - return MameNames::find(mMameBioses, _biosName); -} - -const bool MameNames::isDevice(const std::string& _deviceName) -{ - return MameNames::find(mMameDevices, _deviceName); - -} - const bool MameNames::find(std::vector devices, const std::string& name) { size_t start = 0; diff --git a/es-core/src/MameNames.h b/es-core/src/MameNames.h index 9cbeee670..6ef25cf09 100644 --- a/es-core/src/MameNames.h +++ b/es-core/src/MameNames.h @@ -24,8 +24,14 @@ public: static MameNames* getInstance(); std::string getRealName(const std::string& _mameName); std::string getCleanName(const std::string& _mameName); - const bool isBios(const std::string& _biosName); - const bool isDevice(const std::string& _deviceName); + const bool isBios(const std::string& _biosName) + { + return MameNames::find(mMameBioses, _biosName); + } + const bool isDevice(const std::string& _deviceName) + { + return MameNames::find(mMameDevices, _deviceName); + } private: struct NamePair { @@ -35,8 +41,8 @@ private: typedef std::vector namePairVector; - MameNames(); - ~MameNames(); + MameNames(); + ~MameNames() {} static MameNames* sInstance; diff --git a/es-core/src/Platform.cpp b/es-core/src/Platform.cpp index 4e509cf1e..c90b4940f 100644 --- a/es-core/src/Platform.cpp +++ b/es-core/src/Platform.cpp @@ -8,12 +8,12 @@ #include "Platform.h" -#include "renderers/Renderer.h" -#include "utils/StringUtil.h" #include "AudioManager.h" #include "Log.h" #include "MameNames.h" #include "Settings.h" +#include "renderers/Renderer.h" +#include "utils/StringUtil.h" #include @@ -52,36 +52,36 @@ int runPoweroffCommand() int runSystemCommand(const std::string& cmd_utf8) { - #if defined(_WIN64) +#if defined(_WIN64) // On Windows we use _wsystem to support non-ASCII paths // which requires converting from UTF-8 to a wstring. std::wstring wchar_str = Utils::String::stringToWideString(cmd_utf8); return _wsystem(wchar_str.c_str()); - #else +#else return system(cmd_utf8.c_str()); - #endif +#endif } int runSystemCommand(const std::wstring& cmd_utf16) { - #if defined(_WIN64) +#if defined(_WIN64) return _wsystem(cmd_utf16.c_str()); - #else +#else return 0; - #endif +#endif } int launchGameUnix(const std::string& cmd_utf8, bool runInBackground) { - #if defined(__unix__) || defined (__APPLE__) +#if defined(__unix__) || defined(__APPLE__) std::string command = std::string(cmd_utf8) + " 2>&1 &"; // Launching games while keeping ES-DE running in the background is very crude as for // instance no output from the command is captured and no real error handling is // implemented. It should therefore only be used when absolutely necessary. if (runInBackground) { - LOG(LogDebug) << "Platform::launchGameUnix(): Launching game while keeping ES-DE " - "running in the background, no command output will be written to the log file"; + LOG(LogDebug) << "Platform::launchGameUnix(): Launching game while keeping ES-DE running " + "in the background, no command output will be written to the log file"; return system(command.c_str()); } @@ -106,12 +106,11 @@ int launchGameUnix(const std::string& cmd_utf8, bool runInBackground) // Remove any trailing newline from the command output. if (commandOutput.size()) { if (commandOutput.back() == '\n') - commandOutput.pop_back(); + commandOutput.pop_back(); } if (returnValue) { - LOG(LogError) << "launchGameUnix - return value " << - std::to_string(returnValue) + ":"; + LOG(LogError) << "launchGameUnix - return value " << std::to_string(returnValue) + ":"; if (commandOutput.size()) LOG(LogError) << commandOutput; else @@ -124,14 +123,14 @@ int launchGameUnix(const std::string& cmd_utf8, bool runInBackground) return returnValue; - #else // __unix__ +#else // __unix__ return 0; - #endif +#endif } int launchGameWindows(const std::wstring& cmd_utf16, bool runInBackground) { - #if defined(_WIN64) +#if defined(_WIN64) STARTUPINFOW si {}; PROCESS_INFORMATION pi; @@ -139,17 +138,19 @@ int launchGameWindows(const std::wstring& cmd_utf16, bool runInBackground) bool processReturnValue = true; DWORD errorCode = 0; + // clang-format off processReturnValue = CreateProcessW( - nullptr, // No application name (use command line). - const_cast(cmd_utf16.c_str()), // Command line. - nullptr, // Process attributes. - nullptr, // Thread attributes. - FALSE, // Handles inheritance. - 0, // Creation flags. - nullptr, // Use parent's environment block. - nullptr, // Use parent's starting directory. - &si, // Pointer to the STARTUPINFOW structure. - &pi); // Pointer to the PROCESS_INFORMATION structure. + nullptr, // No application name (use command line). + const_cast(cmd_utf16.c_str()), // Command line. + nullptr, // Process attributes. + nullptr, // Thread attributes. + FALSE, // Handles inheritance. + 0, // Creation flags. + nullptr, // Use parent's environment block. + nullptr, // Use parent's starting directory. + &si, // Pointer to the STARTUPINFOW structure. + &pi); // Pointer to the PROCESS_INFORMATION structure. + // clang-format on if (!runInBackground) { if (Settings::getInstance()->getBool("LaunchWorkaround")) { @@ -169,9 +170,9 @@ int launchGameWindows(const std::wstring& cmd_utf16, bool runInBackground) if (!processReturnValue) { LPWSTR pBuffer = nullptr; - FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER, - nullptr, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), - reinterpret_cast(&pBuffer), 0, nullptr); + FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER, nullptr, + GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), + reinterpret_cast(&pBuffer), 0, nullptr); errorCode = GetLastError(); @@ -186,8 +187,8 @@ int launchGameWindows(const std::wstring& cmd_utf16, bool runInBackground) } } - LOG(LogError) << "launchGameWindows - system error code " << - errorCode << ": " << errorMessage; + LOG(LogError) << "launchGameWindows - system error code " << errorCode << ": " + << errorMessage; } // Close process and thread handles. @@ -196,40 +197,40 @@ int launchGameWindows(const std::wstring& cmd_utf16, bool runInBackground) return errorCode; - #else // _WIN64 +#else // _WIN64 return 0; - #endif +#endif } unsigned int getTaskbarState() { - #if defined(_WIN64) +#if defined(_WIN64) APPBARDATA barData; barData.cbSize = sizeof(APPBARDATA); return static_cast(SHAppBarMessage(ABM_GETSTATE, &barData)); - #else +#else return 0; - #endif +#endif } void hideTaskbar() { - #if defined(_WIN64) +#if defined(_WIN64) APPBARDATA barData; barData.cbSize = sizeof(APPBARDATA); barData.lParam = ABS_AUTOHIDE; SHAppBarMessage(ABM_SETSTATE, &barData); - #endif +#endif } void revertTaskbarState(unsigned int& state) { - #if defined(_WIN64) +#if defined(_WIN64) APPBARDATA barData; barData.cbSize = sizeof(APPBARDATA); barData.lParam = state; SHAppBarMessage(ABM_SETSTATE, &barData); - #endif +#endif } QuitMode quitMode = QuitMode::QUIT; @@ -264,7 +265,7 @@ void touch(const std::string& filename) if (fp != nullptr) fclose(fp); #else - int fd = open(filename.c_str(), O_CREAT|O_WRONLY, 0644); + int fd = open(filename.c_str(), O_CREAT | O_WRONLY, 0644); if (fd >= 0) close(fd); #endif @@ -273,15 +274,18 @@ void touch(const std::string& filename) void processQuitMode() { switch (quitMode) { - case QuitMode::REBOOT: - LOG(LogInfo) << "Rebooting system"; - runRebootCommand(); - break; - case QuitMode::POWEROFF: - LOG(LogInfo) << "Powering off system"; - runPoweroffCommand(); - break; - default: - break; + case QuitMode::REBOOT: { + LOG(LogInfo) << "Rebooting system"; + runRebootCommand(); + break; + } + case QuitMode::POWEROFF: { + LOG(LogInfo) << "Powering off system"; + runPoweroffCommand(); + break; + } + default: { + break; + } } } diff --git a/es-core/src/Platform.h b/es-core/src/Platform.h index 580016e24..aca84afc7 100644 --- a/es-core/src/Platform.h +++ b/es-core/src/Platform.h @@ -12,11 +12,12 @@ #include #if defined(_WIN64) +#include #include #endif enum QuitMode { - QUIT = 0, + QUIT = 0, // Replace with AllowShortEnumsOnASingleLine: false (clang-format >=11.0). REBOOT = 1, POWEROFF = 2 }; @@ -35,6 +36,7 @@ void revertTaskbarState(unsigned int& state); // Clean, normal shutdown. int quitES(QuitMode mode = QuitMode::QUIT); + // Immediately shut down the application as cleanly as possible. void emergencyShutdown(); void processQuitMode(); diff --git a/es-core/src/Scripting.cpp b/es-core/src/Scripting.cpp index bdb3c8165..5e3cd926f 100644 --- a/es-core/src/Scripting.cpp +++ b/es-core/src/Scripting.cpp @@ -14,20 +14,20 @@ #include "Scripting.h" -#include "utils/FileSystemUtil.h" #include "Log.h" #include "Platform.h" #include "Settings.h" +#include "utils/FileSystemUtil.h" namespace Scripting { - void fireEvent(const std::string& eventName, const std::string& arg1, const std::string& arg2) - { + void fireEvent(const std::string& eventName, const std::string& arg1, const std::string& arg2) + { if (!Settings::getInstance()->getBool("CustomEventScripts")) return; - LOG(LogDebug) << "Scripting::fireEvent(): " << eventName << " \"" << arg1 << - "\" \"" << arg2 << "\""; + LOG(LogDebug) << "Scripting::fireEvent(): " << eventName << " \"" << arg1 << "\" \"" << arg2 + << "\""; std::list scriptDirList; std::string scriptDir; @@ -38,10 +38,10 @@ namespace Scripting scriptDirList.push_back(scriptDir); for (std::list::const_iterator dirIt = scriptDirList.cbegin(); - dirIt != scriptDirList.cend(); dirIt++) { + dirIt != scriptDirList.cend(); dirIt++) { std::list scripts = Utils::FileSystem::getDirContent(*dirIt); - for (std::list::const_iterator it = scripts.cbegin(); - it != scripts.cend(); it++) { + for (std::list::const_iterator it = scripts.cbegin(); // Line break. + it != scripts.cend(); it++) { std::string arg1Quotation; std::string arg2Quotation; // Add quotation marks around the arguments as long as these are not already @@ -51,10 +51,10 @@ namespace Scripting if (arg2.front() != '\"') arg2Quotation = "\""; std::string script = *it + " " + arg1Quotation + arg1 + arg1Quotation + " " + - arg2Quotation + arg2 + arg2Quotation; + arg2Quotation + arg2 + arg2Quotation; LOG(LogDebug) << "Executing: " << script; runSystemCommand(script); } } - } -} + } +} // namespace Scripting diff --git a/es-core/src/Scripting.h b/es-core/src/Scripting.h index 294ddf227..9df4ab399 100644 --- a/es-core/src/Scripting.h +++ b/es-core/src/Scripting.h @@ -20,7 +20,8 @@ namespace Scripting { void fireEvent(const std::string& eventName, - const std::string& arg1="", const std::string& arg2=""); + const std::string& arg1 = "", + const std::string& arg2 = ""); } -#endif //ES_CORE_SCRIPTING_H +#endif // ES_CORE_SCRIPTING_H diff --git a/es-core/src/Settings.cpp b/es-core/src/Settings.cpp index 4625f1c05..70964667c 100644 --- a/es-core/src/Settings.cpp +++ b/es-core/src/Settings.cpp @@ -9,11 +9,11 @@ #include "Settings.h" -#include "utils/FileSystemUtil.h" -#include "utils/StringUtil.h" #include "Log.h" #include "Platform.h" #include "Scripting.h" +#include "utils/FileSystemUtil.h" +#include "utils/StringUtil.h" #include #include @@ -25,7 +25,9 @@ Settings* Settings::sInstance = nullptr; // the in-program settings menu. Most can be set using command-line arguments, // but some are debug flags that are either hardcoded or set by internal debug // functions. -std::vector settings_dont_save { +std::vector settingsSkipSaving +{ + // clang-format off // These options can be set using command-line arguments: "WindowWidth", // Set via --resolution [width] [height] "WindowHeight", // set via --resolution [width] [height] @@ -55,6 +57,7 @@ std::vector settings_dont_save { "DebugImage", "SplashScreenProgress", "ScraperFilter" + // clang-format on }; Settings::Settings() @@ -174,9 +177,8 @@ void Settings::setDefaults() mBoolMap["ScreensaverSlideshowScanlines"] = { true, true }; mBoolMap["ScreensaverSlideshowCustomImages"] = { false, false }; mBoolMap["ScreensaverSlideshowRecurse"] = { false, false }; - mStringMap["ScreensaverSlideshowImageDir"] = { - "~/.emulationstation/slideshow/custom_images", - "~/.emulationstation/slideshow/custom_images" }; + mStringMap["ScreensaverSlideshowImageDir"] = { "~/.emulationstation/slideshow/custom_images", + "~/.emulationstation/slideshow/custom_images" }; // UI settings -> screensaver settings -> video screensaver settings. mIntMap["ScreensaverSwapVideoTimeout"] = { 0, 0 }; @@ -185,6 +187,7 @@ void Settings::setDefaults() mBoolMap["ScreensaverVideoScanlines"] = { true, true }; mBoolMap["ScreensaverVideoBlur"] = { false, false }; +#if defined(_RPI_) // Sound settings. // The ALSA Audio Card and Audio Device selection code is disabled at the moment. // As PulseAudio controls the sound devices for the desktop environment, it doesn't @@ -193,7 +196,6 @@ void Settings::setDefaults() // settings could be added later on, if needed. // The code is still active for Raspberry Pi though as I'm not sure if this is // useful for that device. - #if defined(_RPI_) mStringMap["AudioCard"] = { "default", "default" }; // Audio out device for volume control. //#endif @@ -201,9 +203,8 @@ void Settings::setDefaults() mStringMap["AudioDevice"] = { "PCM", "PCM" }; // Audio out device for Video playback using OMX player. mStringMap["OMXAudioDev"] = { "both", "both" }; - //#else - // mStringMap["AudioDevice"] = { "Master", "Master" }; - #endif +#endif + mIntMap["SoundVolumeNavigation"] = { 80, 80 }; mIntMap["SoundVolumeVideos"] = { 100, 100 }; mBoolMap["GamelistVideoAudio"] = { true, true }; @@ -223,32 +224,32 @@ void Settings::setDefaults() mBoolMap["UseCustomCollectionsSystem"] = { true, true }; mBoolMap["CollectionShowSystemInfo"] = { true, true }; - // Other settings. - #if defined(_RPI_) +// Other settings. +#if defined(_RPI_) mIntMap["MaxVRAM"] = { 80, 80 }; - #else +#else mIntMap["MaxVRAM"] = { 256, 256 }; - #endif +#endif mIntMap["DisplayIndex"] = { 1, 1 }; - #if defined (__unix__) +#if defined(__unix__) mStringMap["FullscreenMode"] = { "normal", "normal" }; - #endif - #if defined(BUILD_VLC_PLAYER) +#endif +#if defined(BUILD_VLC_PLAYER) mStringMap["VideoPlayer"] = { "ffmpeg", "ffmpeg" }; - #endif - #if defined(_RPI_) +#endif +#if defined(_RPI_) mBoolMap["VideoOmxPlayer"] = { false, false }; // We're defaulting to OMX Player for full screen video on the Pi. mBoolMap["ScreensaverOmxPlayer"] = { true, true }; - #endif +#endif mStringMap["SaveGamelistsMode"] = { "always", "always" }; - #if defined(_WIN64) +#if defined(_WIN64) mBoolMap["HideTaskbar"] = { false, false }; - #endif +#endif mBoolMap["RunInBackground"] = { false, false }; - #if defined(_WIN64) +#if defined(_WIN64) mBoolMap["LaunchWorkaround"] = { true, true }; - #endif +#endif mStringMap["MediaDirectory"] = { "", "" }; mBoolMap["VideoUpscaleFrameRate"] = { false, false }; mBoolMap["LaunchCommandOverride"] = { true, true }; @@ -256,15 +257,15 @@ void Settings::setDefaults() mBoolMap["ShowHiddenGames"] = { true, true }; mBoolMap["CustomEventScripts"] = { false, false }; mBoolMap["ParseGamelistOnly"] = { false, false }; - #if defined(__unix__) +#if defined(__unix__) mBoolMap["DisableComposition"] = { true, true }; - #endif +#endif mBoolMap["DisplayGPUStatistics"] = { false, false }; - // macOS requires root privileges to reboot and power off so it doesn't make much - // sense to enable this setting and menu entry for that operating system. - #if !defined(__APPLE__) +// macOS requires root privileges to reboot and power off so it doesn't make much +// sense to enable this setting and menu entry for that operating system. +#if !defined(__APPLE__) mBoolMap["ShowQuitMenu"] = { false, false }; - #endif +#endif // // Settings configured via command-line arguments. @@ -278,18 +279,18 @@ void Settings::setDefaults() mBoolMap["IgnoreGamelist"] = { false, false }; mBoolMap["SplashScreen"] = { true, true }; mBoolMap["VSync"] = { true, true }; - #if !defined(_WIN64) +#if !defined(_WIN64) mBoolMap["Windowed"] = { false, false }; - #endif - mIntMap["WindowWidth"] = { 0, 0 }; - mIntMap["WindowHeight"] = { 0, 0 }; - mIntMap["ScreenWidth"] = { 0, 0 }; +#endif + mIntMap["WindowWidth"] = { 0, 0 }; + mIntMap["WindowHeight"] = { 0, 0 }; + mIntMap["ScreenWidth"] = { 0, 0 }; // Undocumented options. - mIntMap["ScreenHeight"] = { 0, 0 }; + mIntMap["ScreenHeight"] = { 0, 0 }; mIntMap["ScreenOffsetX"] = { 0, 0 }; mIntMap["ScreenOffsetY"] = { 0, 0 }; - mIntMap["ScreenRotate"] = { 0, 0 }; + mIntMap["ScreenRotate"] = { 0, 0 }; // // Settings that can be changed in es_settings.xml @@ -317,9 +318,10 @@ void saveMap(pugi::xml_document& doc, std::map& map, const std::string& ty { for (auto iter = map.cbegin(); iter != map.cend(); iter++) { // Key is on the "don't save" list, so don't save it. - if (std::find(settings_dont_save.cbegin(), settings_dont_save.cend(), - iter->first) != settings_dont_save.cend()) + if (std::find(settingsSkipSaving.cbegin(), settingsSkipSaving.cend(), iter->first) != + settingsSkipSaving.cend()) { continue; + } pugi::xml_node node = doc.append_child(type.c_str()); node.append_attribute("name").set_value(iter->first.c_str()); @@ -330,8 +332,8 @@ void saveMap(pugi::xml_document& doc, std::map& map, const std::string& ty void Settings::saveFile() { LOG(LogDebug) << "Settings::saveFile(): Saving settings to es_settings.xml"; - const std::string path = Utils::FileSystem::getHomePath() + - "/.emulationstation/es_settings.xml"; + const std::string path = + Utils::FileSystem::getHomePath() + "/.emulationstation/es_settings.xml"; pugi::xml_document doc; @@ -345,11 +347,11 @@ void Settings::saveFile() node.append_attribute("value").set_value(iter->second.second.c_str()); } - #if defined(_WIN64) +#if defined(_WIN64) doc.save_file(Utils::String::stringToWideString(path).c_str()); - #else +#else doc.save_file(path.c_str()); - #endif +#endif Scripting::fireEvent("config-changed"); Scripting::fireEvent("settings-changed"); @@ -358,11 +360,11 @@ void Settings::saveFile() void Settings::loadFile() { // Prior to ES-DE v1.1, the configuration file had the .cfg suffix instead of .xml - const std::string legacyConfigFile = Utils::FileSystem::getHomePath() + - "/.emulationstation/es_settings.cfg"; + const std::string legacyConfigFile = + Utils::FileSystem::getHomePath() + "/.emulationstation/es_settings.cfg"; - const std::string configFile = Utils::FileSystem::getHomePath() + - "/.emulationstation/es_settings.xml"; + const std::string configFile = + Utils::FileSystem::getHomePath() + "/.emulationstation/es_settings.xml"; if (Utils::FileSystem::exists(legacyConfigFile) && !Utils::FileSystem::exists(configFile)) Utils::FileSystem::copyFile(legacyConfigFile, configFile, false); @@ -371,12 +373,12 @@ void Settings::loadFile() return; pugi::xml_document doc; - #if defined(_WIN64) +#if defined(_WIN64) pugi::xml_parse_result result = - doc.load_file(Utils::String::stringToWideString(configFile).c_str()); - #else + doc.load_file(Utils::String::stringToWideString(configFile).c_str()); +#else pugi::xml_parse_result result = doc.load_file(configFile.c_str()); - #endif +#endif if (!result) { LOG(LogError) << "Could not parse the es_settings.xml file\n " << result.description(); return; @@ -392,37 +394,37 @@ void Settings::loadFile() setString(node.attribute("name").as_string(), node.attribute("value").as_string()); } -// Print a warning message if the setting we're trying to get doesn't already exist in -// the map. Then return the value in the map. -#define SETTINGS_GETSET(type, mapName, getFunction, getDefaultFunction, setFunction) \ -type Settings::getFunction(const std::string& name) \ -{ \ - if (mapName.find(name) == mapName.cend()) { \ - LOG(LogError) << "Tried to use unset setting " << name; \ - } \ - return mapName[name].second; \ -} \ -type Settings::getDefaultFunction(const std::string& name) \ -{ \ - if (mapName.find(name) == mapName.cend()) { \ - LOG(LogError) << "Tried to use unset setting " << name; \ - } \ - return mapName[name].first; \ -} \ -bool Settings::setFunction(const std::string& name, type value) \ -{ \ - if (mapName.count(name) == 0 || mapName[name].second != value) { \ - mapName[name].second = value; \ -\ - if (std::find(settings_dont_save.cbegin(), settings_dont_save.cend(), name) \ - == settings_dont_save.cend()) \ - mWasChanged = true; \ -\ - return true; \ - } \ - return false; \ -} +// Macro to create the get and set functions for the various data types +#define SETTINGS_GETSET(type, mapName, getFunction, getDefaultFunction, setFunction) \ + type Settings::getFunction(const std::string& name) \ + { \ + if (mapName.find(name) == mapName.cend()) { \ + LOG(LogError) << "Tried to use unset setting " << name; \ + } \ + return mapName[name].second; \ + } \ + type Settings::getDefaultFunction(const std::string& name) \ + { \ + if (mapName.find(name) == mapName.cend()) { \ + LOG(LogError) << "Tried to use unset setting " << name; \ + } \ + return mapName[name].first; \ + } \ + bool Settings::setFunction(const std::string& name, type value) \ + { \ + if (mapName.count(name) == 0 || mapName[name].second != value) { \ + mapName[name].second = value; \ + \ + if (std::find(settingsSkipSaving.cbegin(), settingsSkipSaving.cend(), name) == \ + settingsSkipSaving.cend()) \ + mWasChanged = true; \ + \ + return true; \ + } \ + return false; \ + } +// Parameters for the macro defined above. SETTINGS_GETSET(bool, mBoolMap, getBool, getDefaultBool, setBool); SETTINGS_GETSET(int, mIntMap, getInt, getDefaultInt, setInt); SETTINGS_GETSET(float, mFloatMap, getFloat, getDefaultFloat, setFloat); diff --git a/es-core/src/Sound.cpp b/es-core/src/Sound.cpp index ab1dc64e5..496d513e3 100644 --- a/es-core/src/Sound.cpp +++ b/es-core/src/Sound.cpp @@ -9,11 +9,11 @@ #include "Sound.h" -#include "resources/ResourceManager.h" #include "AudioManager.h" #include "Log.h" #include "Settings.h" #include "ThemeData.h" +#include "resources/ResourceManager.h" NavigationSounds* NavigationSounds::sInstance = nullptr; @@ -32,11 +32,12 @@ std::shared_ptr Sound::get(const std::string& path) } std::shared_ptr Sound::getFromTheme(const std::shared_ptr& theme, - const std::string& view, const std::string& element) + const std::string& view, + const std::string& element) { if (!theme) { - LOG(LogDebug) << "Sound::getFromTheme(): Using fallback sound file for \"" - << element << "\""; + LOG(LogDebug) << "Sound::getFromTheme(): Using fallback sound file for \"" << element + << "\""; return get(ResourceManager::getInstance()->getResourcePath(":/sounds/" + element + ".wav")); } @@ -44,7 +45,7 @@ std::shared_ptr Sound::getFromTheme(const std::shared_ptr& the const ThemeData::ThemeElement* elem = theme->getElement(view, element, "sound"); if (!elem || !elem->has("path")) { - LOG(LogDebug) << "Sound::getFromTheme(): " << "Tag not found, using fallback sound file"; + LOG(LogDebug) << "Sound::getFromTheme(): Tag not found, using fallback sound file"; return get(ResourceManager::getInstance()->getResourcePath(":/sounds/" + element + ".wav")); } @@ -52,20 +53,15 @@ std::shared_ptr Sound::getFromTheme(const std::shared_ptr& the return get(elem->get("path")); } -Sound::Sound( - const std::string& path) - : mSampleData(nullptr), - mSamplePos(0), - mSampleLength(0), - playing(false) +Sound::Sound(const std::string& path) + : mSampleData(nullptr) + , mSamplePos(0) + , mSampleLength(0) + , playing(false) { loadFile(path); } -Sound::~Sound() -{ -} - void Sound::loadFile(const std::string& path) { mPath = path; @@ -91,9 +87,9 @@ void Sound::init() } // Convert sound file to the format required by ES-DE. - SDL_AudioStream *conversionStream = SDL_NewAudioStream(wave.format, wave.channels, wave.freq, - AudioManager::sAudioFormat.format, AudioManager::sAudioFormat.channels, - AudioManager::sAudioFormat.freq); + SDL_AudioStream* conversionStream = + SDL_NewAudioStream(wave.format, wave.channels, wave.freq, AudioManager::sAudioFormat.format, + AudioManager::sAudioFormat.channels, AudioManager::sAudioFormat.freq); if (conversionStream == nullptr) { LOG(LogError) << "Failed to create sample conversion stream:"; @@ -169,11 +165,6 @@ void Sound::play() AudioManager::getInstance()->play(); } -bool Sound::isPlaying() const -{ - return playing; -} - void Sound::stop() { // Flag our sample as not playing and rewind its position. @@ -183,16 +174,6 @@ void Sound::stop() SDL_UnlockAudioDevice(AudioManager::sAudioDevice); } -const Uint8* Sound::getData() const -{ - return mSampleData; -} - -Uint32 Sound::getPosition() const -{ - return mSamplePos; -} - void Sound::setPosition(Uint32 newPosition) { mSamplePos = newPosition; @@ -203,11 +184,6 @@ void Sound::setPosition(Uint32 newPosition) } } -Uint32 Sound::getLength() const -{ - return mSampleLength; -} - NavigationSounds* NavigationSounds::getInstance() { if (sInstance == nullptr) @@ -234,11 +210,12 @@ void NavigationSounds::loadThemeNavigationSounds(const std::shared_ptr get(const std::string& path); static std::shared_ptr getFromTheme(const std::shared_ptr& theme, - const std::string& view, const std::string& elem); + const std::string& view, + const std::string& elem); private: Sound(const std::string& path = ""); diff --git a/es-core/src/ThemeData.cpp b/es-core/src/ThemeData.cpp index 5d19b8908..72dbe06b1 100644 --- a/es-core/src/ThemeData.cpp +++ b/es-core/src/ThemeData.cpp @@ -10,190 +10,190 @@ #include "ThemeData.h" +#include "Log.h" +#include "Platform.h" +#include "Settings.h" #include "components/ImageComponent.h" #include "components/TextComponent.h" #include "utils/FileSystemUtil.h" #include "utils/StringUtil.h" -#include "Log.h" -#include "Platform.h" -#include "Settings.h" #include #include -std::vector ThemeData::sSupportedViews { - { "all" }, { "system" }, { "basic" }, { "detailed" }, { "grid" }, { "video" } }; +std::vector ThemeData::sSupportedViews { { "all" }, { "system" }, { "basic" }, + { "detailed" }, { "grid" }, { "video" } }; std::vector ThemeData::sSupportedFeatures { - { "navigationsounds" }, { "video" }, { "carousel" }, { "z-index" }, { "visible" } }; - -std::map> ThemeData::sElementMap { - { "image", { - { "pos", NORMALIZED_PAIR }, - { "size", NORMALIZED_PAIR }, - { "maxSize", NORMALIZED_PAIR }, - { "origin", NORMALIZED_PAIR }, - { "rotation", FLOAT }, - { "rotationOrigin", NORMALIZED_PAIR }, - { "path", PATH }, - { "default", PATH }, - { "tile", BOOLEAN }, - { "color", COLOR }, - { "colorEnd", COLOR }, - { "gradientType", STRING }, - { "visible", BOOLEAN }, - { "zIndex", FLOAT } } }, - { "imagegrid", { - { "pos", NORMALIZED_PAIR }, - { "size", NORMALIZED_PAIR }, - { "margin", NORMALIZED_PAIR }, - { "padding", NORMALIZED_RECT }, - { "autoLayout", NORMALIZED_PAIR }, - { "autoLayoutSelectedZoom", FLOAT }, - { "gameImage", PATH }, - { "folderImage", PATH }, - { "imageSource", STRING }, - { "scrollDirection", STRING }, - { "centerSelection", BOOLEAN }, - { "scrollLoop", BOOLEAN }, - { "animate", BOOLEAN }, - { "zIndex", FLOAT } } }, - { "gridtile", { - { "size", NORMALIZED_PAIR }, - { "padding", NORMALIZED_PAIR }, - { "imageColor", COLOR }, - { "backgroundImage", PATH }, - { "backgroundCornerSize", NORMALIZED_PAIR }, - { "backgroundColor", COLOR }, - { "backgroundCenterColor", COLOR }, - { "backgroundEdgeColor", COLOR } } }, - { "text", { - { "pos", NORMALIZED_PAIR }, - { "size", NORMALIZED_PAIR }, - { "origin", NORMALIZED_PAIR }, - { "rotation", FLOAT }, - { "rotationOrigin", NORMALIZED_PAIR }, - { "text", STRING }, - { "backgroundColor", COLOR }, - { "fontPath", PATH }, - { "fontSize", FLOAT }, - { "color", COLOR }, - { "alignment", STRING }, - { "forceUppercase", BOOLEAN }, - { "lineSpacing", FLOAT }, - { "value", STRING }, - { "visible", BOOLEAN }, - { "zIndex", FLOAT } } }, - { "textlist", { - { "pos", NORMALIZED_PAIR }, - { "size", NORMALIZED_PAIR }, - { "origin", NORMALIZED_PAIR }, - { "selectorHeight", FLOAT }, - { "selectorOffsetY", FLOAT }, - { "selectorColor", COLOR }, - { "selectorColorEnd", COLOR }, - { "selectorGradientType", STRING }, - { "selectorImagePath", PATH }, - { "selectorImageTile", BOOLEAN }, - { "selectedColor", COLOR }, - { "primaryColor", COLOR }, - { "secondaryColor", COLOR }, - { "fontPath", PATH }, - { "fontSize", FLOAT }, - { "scrollSound", PATH }, // Need to keep this for backward compatibility with old themes. - { "alignment", STRING }, - { "horizontalMargin", FLOAT }, - { "forceUppercase", BOOLEAN }, - { "lineSpacing", FLOAT }, - { "zIndex", FLOAT } } }, - { "container", { - { "pos", NORMALIZED_PAIR }, - { "size", NORMALIZED_PAIR }, - { "origin", NORMALIZED_PAIR }, - { "visible", BOOLEAN }, - { "zIndex", FLOAT } } }, - { "ninepatch", { - { "pos", NORMALIZED_PAIR }, - { "size", NORMALIZED_PAIR }, - { "path", PATH }, - { "visible", BOOLEAN }, - { "zIndex", FLOAT } } }, - { "datetime", { - { "pos", NORMALIZED_PAIR }, - { "size", NORMALIZED_PAIR }, - { "origin", NORMALIZED_PAIR }, - { "rotation", FLOAT }, - { "rotationOrigin", NORMALIZED_PAIR }, - { "backgroundColor", COLOR }, - { "fontPath", PATH }, - { "fontSize", FLOAT }, - { "color", COLOR }, - { "alignment", STRING }, - { "forceUppercase", BOOLEAN }, - { "lineSpacing", FLOAT }, - { "value", STRING }, - { "format", STRING }, - { "displayRelative", BOOLEAN }, - { "visible", BOOLEAN }, - { "zIndex", FLOAT } } }, - { "rating", { - { "pos", NORMALIZED_PAIR }, - { "size", NORMALIZED_PAIR }, - { "origin", NORMALIZED_PAIR }, - { "rotation", FLOAT }, - { "rotationOrigin", NORMALIZED_PAIR }, - { "color", COLOR }, - { "filledPath", PATH }, - { "unfilledPath", PATH }, - { "visible", BOOLEAN }, - { "zIndex", FLOAT } } }, - { "sound", { - { "path", PATH } } }, - { "helpsystem", { - { "pos", NORMALIZED_PAIR }, - { "origin", NORMALIZED_PAIR }, - { "textColor", COLOR }, - { "iconColor", COLOR }, - { "fontPath", PATH }, - { "fontSize", FLOAT } } }, - { "navigationsounds", { - { "systembrowseSound", PATH }, - { "quicksysselectSound", PATH }, - { "selectSound", PATH }, - { "backSound", PATH }, - { "scrollSound", PATH }, - { "favoriteSound", PATH }, - { "launchSound", PATH } } }, - { "video", { - { "pos", NORMALIZED_PAIR }, - { "size", NORMALIZED_PAIR }, - { "maxSize", NORMALIZED_PAIR }, - { "origin", NORMALIZED_PAIR }, - { "rotation", FLOAT }, - { "rotationOrigin", NORMALIZED_PAIR }, - { "default", PATH }, - { "delay", FLOAT }, - { "visible", BOOLEAN }, - { "zIndex", FLOAT }, - { "showSnapshotNoVideo", BOOLEAN }, - { "showSnapshotDelay", BOOLEAN } } }, - { "carousel", { - { "type", STRING }, - { "size", NORMALIZED_PAIR }, - { "pos", NORMALIZED_PAIR }, - { "origin", NORMALIZED_PAIR }, - { "color", COLOR }, - { "colorEnd", COLOR }, - { "gradientType", STRING }, - { "logoScale", FLOAT }, - { "logoRotation", FLOAT }, - { "logoRotationOrigin", NORMALIZED_PAIR }, - { "logoSize", NORMALIZED_PAIR }, - { "logoAlignment", STRING }, - { "maxLogoCount", FLOAT }, - { "zIndex", FLOAT } } } + { "navigationsounds" }, { "video" }, { "carousel" }, { "z-index" }, { "visible" } }; +std::map> + ThemeData::sElementMap { + { "image", + { { "pos", NORMALIZED_PAIR }, + { "size", NORMALIZED_PAIR }, + { "maxSize", NORMALIZED_PAIR }, + { "origin", NORMALIZED_PAIR }, + { "rotation", FLOAT }, + { "rotationOrigin", NORMALIZED_PAIR }, + { "path", PATH }, + { "default", PATH }, + { "tile", BOOLEAN }, + { "color", COLOR }, + { "colorEnd", COLOR }, + { "gradientType", STRING }, + { "visible", BOOLEAN }, + { "zIndex", FLOAT } } }, + { "imagegrid", + { { "pos", NORMALIZED_PAIR }, + { "size", NORMALIZED_PAIR }, + { "margin", NORMALIZED_PAIR }, + { "padding", NORMALIZED_RECT }, + { "autoLayout", NORMALIZED_PAIR }, + { "autoLayoutSelectedZoom", FLOAT }, + { "gameImage", PATH }, + { "folderImage", PATH }, + { "imageSource", STRING }, + { "scrollDirection", STRING }, + { "centerSelection", BOOLEAN }, + { "scrollLoop", BOOLEAN }, + { "animate", BOOLEAN }, + { "zIndex", FLOAT } } }, + { "gridtile", + { { "size", NORMALIZED_PAIR }, + { "padding", NORMALIZED_PAIR }, + { "imageColor", COLOR }, + { "backgroundImage", PATH }, + { "backgroundCornerSize", NORMALIZED_PAIR }, + { "backgroundColor", COLOR }, + { "backgroundCenterColor", COLOR }, + { "backgroundEdgeColor", COLOR } } }, + { "text", + { { "pos", NORMALIZED_PAIR }, + { "size", NORMALIZED_PAIR }, + { "origin", NORMALIZED_PAIR }, + { "rotation", FLOAT }, + { "rotationOrigin", NORMALIZED_PAIR }, + { "text", STRING }, + { "backgroundColor", COLOR }, + { "fontPath", PATH }, + { "fontSize", FLOAT }, + { "color", COLOR }, + { "alignment", STRING }, + { "forceUppercase", BOOLEAN }, + { "lineSpacing", FLOAT }, + { "value", STRING }, + { "visible", BOOLEAN }, + { "zIndex", FLOAT } } }, + { "textlist", + { { "pos", NORMALIZED_PAIR }, + { "size", NORMALIZED_PAIR }, + { "origin", NORMALIZED_PAIR }, + { "selectorHeight", FLOAT }, + { "selectorOffsetY", FLOAT }, + { "selectorColor", COLOR }, + { "selectorColorEnd", COLOR }, + { "selectorGradientType", STRING }, + { "selectorImagePath", PATH }, + { "selectorImageTile", BOOLEAN }, + { "selectedColor", COLOR }, + { "primaryColor", COLOR }, + { "secondaryColor", COLOR }, + { "fontPath", PATH }, + { "fontSize", FLOAT }, + { "scrollSound", PATH }, // For backward compatibility with old themes. + { "alignment", STRING }, + { "horizontalMargin", FLOAT }, + { "forceUppercase", BOOLEAN }, + { "lineSpacing", FLOAT }, + { "zIndex", FLOAT } } }, + { "container", + { { "pos", NORMALIZED_PAIR }, + { "size", NORMALIZED_PAIR }, + { "origin", NORMALIZED_PAIR }, + { "visible", BOOLEAN }, + { "zIndex", FLOAT } } }, + { "ninepatch", + { { "pos", NORMALIZED_PAIR }, + { "size", NORMALIZED_PAIR }, + { "path", PATH }, + { "visible", BOOLEAN }, + { "zIndex", FLOAT } } }, + { "datetime", + { { "pos", NORMALIZED_PAIR }, + { "size", NORMALIZED_PAIR }, + { "origin", NORMALIZED_PAIR }, + { "rotation", FLOAT }, + { "rotationOrigin", NORMALIZED_PAIR }, + { "backgroundColor", COLOR }, + { "fontPath", PATH }, + { "fontSize", FLOAT }, + { "color", COLOR }, + { "alignment", STRING }, + { "forceUppercase", BOOLEAN }, + { "lineSpacing", FLOAT }, + { "value", STRING }, + { "format", STRING }, + { "displayRelative", BOOLEAN }, + { "visible", BOOLEAN }, + { "zIndex", FLOAT } } }, + { "rating", + { { "pos", NORMALIZED_PAIR }, + { "size", NORMALIZED_PAIR }, + { "origin", NORMALIZED_PAIR }, + { "rotation", FLOAT }, + { "rotationOrigin", NORMALIZED_PAIR }, + { "color", COLOR }, + { "filledPath", PATH }, + { "unfilledPath", PATH }, + { "visible", BOOLEAN }, + { "zIndex", FLOAT } } }, + { "sound", { { "path", PATH } } }, + { "helpsystem", + { { "pos", NORMALIZED_PAIR }, + { "origin", NORMALIZED_PAIR }, + { "textColor", COLOR }, + { "iconColor", COLOR }, + { "fontPath", PATH }, + { "fontSize", FLOAT } } }, + { "navigationsounds", + { { "systembrowseSound", PATH }, + { "quicksysselectSound", PATH }, + { "selectSound", PATH }, + { "backSound", PATH }, + { "scrollSound", PATH }, + { "favoriteSound", PATH }, + { "launchSound", PATH } } }, + { "video", + { { "pos", NORMALIZED_PAIR }, + { "size", NORMALIZED_PAIR }, + { "maxSize", NORMALIZED_PAIR }, + { "origin", NORMALIZED_PAIR }, + { "rotation", FLOAT }, + { "rotationOrigin", NORMALIZED_PAIR }, + { "default", PATH }, + { "delay", FLOAT }, + { "visible", BOOLEAN }, + { "zIndex", FLOAT }, + { "showSnapshotNoVideo", BOOLEAN }, + { "showSnapshotDelay", BOOLEAN } } }, + { "carousel", + { { "type", STRING }, + { "size", NORMALIZED_PAIR }, + { "pos", NORMALIZED_PAIR }, + { "origin", NORMALIZED_PAIR }, + { "color", COLOR }, + { "colorEnd", COLOR }, + { "gradientType", STRING }, + { "logoScale", FLOAT }, + { "logoRotation", FLOAT }, + { "logoRotationOrigin", NORMALIZED_PAIR }, + { "logoSize", NORMALIZED_PAIR }, + { "logoAlignment", STRING }, + { "maxLogoCount", FLOAT }, + { "zIndex", FLOAT } } } + }; + #define MINIMUM_THEME_FORMAT_VERSION 3 #define CURRENT_THEME_FORMAT_VERSION 6 @@ -241,6 +241,7 @@ std::string resolvePlaceholders(const std::string& in) ThemeData::ThemeData() { + // The version will be loaded from the theme file. mVersion = 0; } @@ -261,11 +262,11 @@ void ThemeData::loadFile(std::map sysDataMap, const st mVariables.insert(sysDataMap.cbegin(), sysDataMap.cend()); pugi::xml_document doc; - #if defined(_WIN64) +#if defined(_WIN64) pugi::xml_parse_result res = doc.load_file(Utils::String::stringToWideString(path).c_str()); - #else +#else pugi::xml_parse_result res = doc.load_file(path.c_str()); - #endif +#endif if (!res) throw error << "XML parsing error: \n " << res.description(); @@ -276,13 +277,13 @@ void ThemeData::loadFile(std::map sysDataMap, const st // parse version mVersion = root.child("formatVersion").text().as_float(-404); if (mVersion == -404) - throw error << " tag missing!\n It's either out of date or you need " - "to add " << CURRENT_THEME_FORMAT_VERSION << - " inside your tag."; + throw error << " tag missing\n " + "It's either out of date or you need to add " + << CURRENT_THEME_FORMAT_VERSION << " inside your tag."; if (mVersion < MINIMUM_THEME_FORMAT_VERSION) - throw error << "Theme uses format version " << mVersion << - ". Minimum supported version is " << MINIMUM_THEME_FORMAT_VERSION << "."; + throw error << "Theme uses format version " << mVersion << ". Minimum supported version is " + << MINIMUM_THEME_FORMAT_VERSION << "."; parseVariables(root); parseIncludes(root); @@ -299,19 +300,18 @@ void ThemeData::parseIncludes(const pugi::xml_node& root) std::string relPath = resolvePlaceholders(node.text().as_string()); std::string path = Utils::FileSystem::resolveRelativePath(relPath, mPaths.back(), true); if (!ResourceManager::getInstance()->fileExists(path)) - throw error << " -> \"" << relPath << - "\" not found (resolved to \"" << path << "\")"; + throw error << " -> \"" << relPath << "\" not found (resolved to \"" << path << "\")"; error << " -> \"" << relPath << "\""; mPaths.push_back(path); pugi::xml_document includeDoc; - #if defined(_WIN64) +#if defined(_WIN64) pugi::xml_parse_result result = - includeDoc.load_file(Utils::String::stringToWideString(path).c_str()); - #else + includeDoc.load_file(Utils::String::stringToWideString(path).c_str()); +#else pugi::xml_parse_result result = includeDoc.load_file(path.c_str()); - #endif +#endif if (!result) throw error << ": Error parsing file: " << result.description(); @@ -339,9 +339,10 @@ void ThemeData::parseFeatures(const pugi::xml_node& root) const std::string supportedAttr = node.attribute("supported").as_string(); - if (std::find(sSupportedFeatures.cbegin(), sSupportedFeatures.cend(), - supportedAttr) != sSupportedFeatures.cend()) + if (std::find(sSupportedFeatures.cbegin(), sSupportedFeatures.cend(), supportedAttr) != + sSupportedFeatures.cend()) { parseViews(node); + } } } @@ -384,10 +385,11 @@ void ThemeData::parseViews(const pugi::xml_node& root) prevOff = nameAttr.find_first_not_of(delim, off); off = nameAttr.find_first_of(delim, prevOff); - if (std::find(sSupportedViews.cbegin(), sSupportedViews.cend(), - viewKey) != sSupportedViews.cend()) { - ThemeView& view = mViews.insert(std::pair(viewKey, ThemeView())).first->second; + if (std::find(sSupportedViews.cbegin(), sSupportedViews.cend(), viewKey) != + sSupportedViews.cend()) { + ThemeView& view = + mViews.insert(std::pair(viewKey, ThemeView())) + .first->second; parseView(node, view); } } @@ -416,19 +418,21 @@ void ThemeData::parseView(const pugi::xml_node& root, ThemeView& view) prevOff = nameAttr.find_first_not_of(delim, off); off = nameAttr.find_first_of(delim, prevOff); - parseElement(node, elemTypeIt->second, - view.elements.insert(std::pair(elemKey, ThemeElement())).first->second); + parseElement( + node, elemTypeIt->second, + view.elements.insert(std::pair(elemKey, ThemeElement())) + .first->second); - if (std::find(view.orderedKeys.cbegin(), view.orderedKeys.cend(), - elemKey) == view.orderedKeys.cend()) + if (std::find(view.orderedKeys.cbegin(), view.orderedKeys.cend(), elemKey) == + view.orderedKeys.cend()) view.orderedKeys.push_back(elemKey); } } } void ThemeData::parseElement(const pugi::xml_node& root, - const std::map& typeMap, ThemeElement& element) + const std::map& typeMap, + ThemeElement& element) { ThemeException error; error.setFiles(mPaths); @@ -439,85 +443,88 @@ void ThemeData::parseElement(const pugi::xml_node& root, for (pugi::xml_node node = root.first_child(); node; node = node.next_sibling()) { auto typeIt = typeMap.find(node.name()); if (typeIt == typeMap.cend()) - throw error << ": Unknown property type \"" << node.name() << - "\" (for element of type " << root.name() << ")"; + throw error << ": Unknown property type \"" << node.name() << "\" (for element of type " + << root.name() << ")"; std::string str = resolvePlaceholders(node.text().as_string()); switch (typeIt->second) { - case NORMALIZED_RECT: { - Vector4f val; + case NORMALIZED_RECT: { + Vector4f val; - auto splits = Utils::String::delimitedStringToVector(str, " "); - if (splits.size() == 2) { - val = Vector4f(static_cast(atof(splits.at(0).c_str())), - static_cast(atof(splits.at(1).c_str())), - static_cast(atof(splits.at(0).c_str())), - static_cast(atof(splits.at(1).c_str()))); + auto splits = Utils::String::delimitedStringToVector(str, " "); + if (splits.size() == 2) { + val = Vector4f(static_cast(atof(splits.at(0).c_str())), + static_cast(atof(splits.at(1).c_str())), + static_cast(atof(splits.at(0).c_str())), + static_cast(atof(splits.at(1).c_str()))); + } + else if (splits.size() == 4) { + val = Vector4f(static_cast(atof(splits.at(0).c_str())), + static_cast(atof(splits.at(1).c_str())), + static_cast(atof(splits.at(2).c_str())), + static_cast(atof(splits.at(3).c_str()))); + } + + element.properties[node.name()] = val; + break; } - else if (splits.size() == 4) { - val = Vector4f(static_cast(atof(splits.at(0).c_str())), - static_cast(atof(splits.at(1).c_str())), - static_cast(atof(splits.at(2).c_str())), - static_cast(atof(splits.at(3).c_str()))); + case NORMALIZED_PAIR: { + size_t divider = str.find(' '); + if (divider == std::string::npos) + throw error << "invalid normalized pair (property \"" << node.name() + << "\", value \"" << str.c_str() << "\")"; + + std::string first = str.substr(0, divider); + std::string second = str.substr(divider, std::string::npos); + + Vector2f val(static_cast(atof(first.c_str())), + static_cast(atof(second.c_str()))); + + element.properties[node.name()] = val; + break; } - - element.properties[node.name()] = val; - break; - } - case NORMALIZED_PAIR: { - size_t divider = str.find(' '); - if (divider == std::string::npos) - throw error << "invalid normalized pair (property \"" << node.name() << - "\", value \"" << str.c_str() << "\")"; - - std::string first = str.substr(0, divider); - std::string second = str.substr(divider, std::string::npos); - - Vector2f val(static_cast(atof(first.c_str())), - static_cast(atof(second.c_str()))); - - element.properties[node.name()] = val; - break; - } - case STRING: { - element.properties[node.name()] = str; - break; - } - case PATH: { - std::string path = Utils::FileSystem::resolveRelativePath(str, mPaths.back(), true); - if (!ResourceManager::getInstance()->fileExists(path)) { - std::stringstream ss; - // "From theme yadda yadda, included file yadda yadda. - LOG(LogWarning) << error.msg << ":"; - LOG(LogWarning) << "Could not find file \"" << node.text().get() << "\" " << - ((node.text().get() != path) ? "which resolves to \"" + path + "\"" : ""); + case STRING: { + element.properties[node.name()] = str; + break; } - element.properties[node.name()] = path; - break; - } - case COLOR: { - element.properties[node.name()] = getHexColor(str); - break; - } - case FLOAT: { - float floatVal = static_cast(strtod(str.c_str(), 0)); - element.properties[node.name()] = floatVal; - break; - } - case BOOLEAN: { - // Only look at first char. - char first = str[0]; - // 1*, t* (true), T* (True), y* (yes), Y* (YES) - bool boolVal = (first == '1' || first == 't' || first == 'T' || - first == 'y' || first == 'Y'); + case PATH: { + std::string path = Utils::FileSystem::resolveRelativePath(str, mPaths.back(), true); + if (!ResourceManager::getInstance()->fileExists(path)) { + std::stringstream ss; + // "From theme yadda yadda, included file yadda yadda. + LOG(LogWarning) << error.msg << ":"; + LOG(LogWarning) + << "Could not find file \"" << node.text().get() << "\" " + << ((node.text().get() != path) ? "which resolves to \"" + path + "\"" : + ""); + } + element.properties[node.name()] = path; + break; + } + case COLOR: { + element.properties[node.name()] = getHexColor(str); + break; + } + case FLOAT: { + float floatVal = static_cast(strtod(str.c_str(), 0)); + element.properties[node.name()] = floatVal; + break; + } + case BOOLEAN: { + // Only look at first char. + char first = str[0]; + // 1*, t* (true), T* (True), y* (yes), Y* (YES) + bool boolVal = + (first == '1' || first == 't' || first == 'T' || first == 'y' || first == 'Y'); - element.properties[node.name()] = boolVal; - break; - } - default: - throw error << "Unknown ElementPropertyType for \"" << - root.attribute("name").as_string() << "\", property " << node.name(); + element.properties[node.name()] = boolVal; + break; + } + default: { + throw error << "Unknown ElementPropertyType for \"" + << root.attribute("name").as_string() << "\", property " << node.name(); + } } } } @@ -529,7 +536,8 @@ bool ThemeData::hasView(const std::string& view) } const ThemeData::ThemeElement* ThemeData::getElement(const std::string& view, - const std::string& element, const std::string& expectedType) const + const std::string& element, + const std::string& expectedType) const { auto viewIt = mViews.find(view); if (viewIt == mViews.cend()) @@ -540,9 +548,9 @@ const ThemeData::ThemeElement* ThemeData::getElement(const std::string& view, return nullptr; if (elemIt->second.type != expectedType && !expectedType.empty()) { - LOG(LogWarning) << " requested mismatched theme type for [" << - view << "." << element << "] - expected \"" - << expectedType << "\", got \"" << elemIt->second.type << "\""; + LOG(LogWarning) << " requested mismatched theme type for [" << view << "." << element + << "] - expected \"" << expectedType << "\", got \"" << elemIt->second.type + << "\""; return nullptr; } @@ -555,14 +563,14 @@ const std::shared_ptr& ThemeData::getDefault() if (theme == nullptr) { theme = std::shared_ptr(new ThemeData()); - const std::string path = Utils::FileSystem::getHomePath() + - "/.emulationstation/es_theme_default.xml"; + const std::string path = + Utils::FileSystem::getHomePath() + "/.emulationstation/es_theme_default.xml"; if (Utils::FileSystem::exists(path)) { try { std::map emptyMap; theme->loadFile(emptyMap, path); } - catch(ThemeException& e) { + catch (ThemeException& e) { LOG(LogError) << e.what(); theme = std::shared_ptr(new ThemeData()); // Reset to empty. } @@ -573,7 +581,8 @@ const std::shared_ptr& ThemeData::getDefault() } std::vector ThemeData::makeExtras(const std::shared_ptr& theme, - const std::string& view, Window* window) + const std::string& view, + Window* window) { std::vector comps; @@ -581,8 +590,8 @@ std::vector ThemeData::makeExtras(const std::shared_ptrmViews.cend()) return comps; - for (auto it = viewIt->second.orderedKeys.cbegin(); - it != viewIt->second.orderedKeys.cend(); it++) { + for (auto it = viewIt->second.orderedKeys.cbegin(); // Line break. + it != viewIt->second.orderedKeys.cend(); it++) { ThemeElement& elem = viewIt->second.elements.at(*it); if (elem.extra) { GuiComponent* comp = nullptr; @@ -608,19 +617,20 @@ std::map ThemeData::getThemeSets() std::map sets; // Check for themes first under the home directory, then under the data installation - // directory (Unix only) and last under the ES executable directory. - #if defined(__unix__) || defined(__APPLE__) + // directory (Unix only) and last under the ES-DE binary directory. + +#if defined(__unix__) || defined(__APPLE__) static const size_t pathCount = 3; - #else +#else static const size_t pathCount = 2; - #endif +#endif std::string paths[pathCount] = { Utils::FileSystem::getExePath() + "/themes", - #if defined(__APPLE__) +#if defined(__APPLE__) Utils::FileSystem::getExePath() + "/../Resources/themes", - #elif defined(__unix__) +#elif defined(__unix__) Utils::FileSystem::getProgramDataPath() + "/themes", - #endif +#endif Utils::FileSystem::getHomePath() + "/.emulationstation/themes" }; @@ -631,9 +641,9 @@ std::map ThemeData::getThemeSets() Utils::FileSystem::stringList dirContent = Utils::FileSystem::getDirContent(paths[i]); for (Utils::FileSystem::stringList::const_iterator it = dirContent.cbegin(); - it != dirContent.cend(); it++) { + it != dirContent.cend(); it++) { if (Utils::FileSystem::isDirectory(*it)) { - ThemeSet set = {*it}; + ThemeSet set = { *it }; sets[set.getName()] = set; } } @@ -650,9 +660,9 @@ std::string ThemeData::getThemeFromCurrentSet(const std::string& system) return ""; std::map::const_iterator set = - themeSets.find(Settings::getInstance()->getString("ThemeSet")); + themeSets.find(Settings::getInstance()->getString("ThemeSet")); if (set == themeSets.cend()) { - // Currently selected theme set is missing, so just pick the first available set. + // Currently configured theme set is missing, so just pick the first available set. set = themeSets.cbegin(); Settings::getInstance()->setString("ThemeSet", set->first); } diff --git a/es-core/src/ThemeData.h b/es-core/src/ThemeData.h index d2855298f..d3e008b64 100644 --- a/es-core/src/ThemeData.h +++ b/es-core/src/ThemeData.h @@ -21,10 +21,12 @@ #include #include -namespace pugi { class xml_node; } +namespace pugi +{ + class xml_node; +} -template -class TextListComponent; +template class TextListComponent; class GuiComponent; class ImageComponent; @@ -63,10 +65,9 @@ public: virtual const char* what() const throw() { return msg.c_str(); } - template - friend ThemeException& operator<<(ThemeException& e, T msg); + template friend ThemeException& operator<<(ThemeException& e, T msg); - inline void setFiles(const std::deque& deque) + void setFiles(const std::deque& deque) { *this << "From theme \"" << deque.front() << "\""; for (auto it = deque.cbegin() + 1; it != deque.cend(); it++) @@ -74,8 +75,7 @@ public: } }; -template -ThemeException& operator<<(ThemeException& e, T appendMsg) +template ThemeException& operator<<(ThemeException& e, T appendMsg) { std::stringstream ss; ss << e.msg << appendMsg; @@ -83,13 +83,14 @@ ThemeException& operator<<(ThemeException& e, T appendMsg) return e; } -struct ThemeSet -{ +struct ThemeSet { std::string path; - inline std::string getName() const { return Utils::FileSystem::getStem(path); } - inline std::string getThemePath(const std::string& system) const - { return path + "/" + system + "/theme.xml"; } + std::string getName() const { return Utils::FileSystem::getStem(path); } + std::string getThemePath(const std::string& system) const + { + return path + "/" + system + "/theme.xml"; + } }; class ThemeData @@ -124,8 +125,7 @@ public: std::map properties; - template - const T get(const std::string& prop) const + template const T get(const std::string& prop) const { if (std::is_same::value) return *(const T*)&properties.at(prop).v; @@ -142,8 +142,10 @@ public: return T(); } - inline bool has(const std::string& prop) const - { return (properties.find(prop) != properties.cend()); } + bool has(const std::string& prop) const + { + return (properties.find(prop) != properties.cend()); + } }; private: @@ -173,11 +175,13 @@ public: bool hasView(const std::string& view); // If expectedType is an empty string, will do no type checking. - const ThemeElement* getElement(const std::string& view, const std::string& element, - const std::string& expectedType) const; + const ThemeElement* getElement(const std::string& view, + const std::string& element, + const std::string& expectedType) const; static std::vector makeExtras(const std::shared_ptr& theme, - const std::string& view, Window* window); + const std::string& view, + Window* window); static const std::shared_ptr& getDefault(); @@ -198,7 +202,8 @@ private: void parseViews(const pugi::xml_node& themeRoot); void parseView(const pugi::xml_node& viewNode, ThemeView& view); void parseElement(const pugi::xml_node& elementNode, - const std::map& typeMap, ThemeElement& element); + const std::map& typeMap, + ThemeElement& element); std::map mViews; }; diff --git a/es-core/src/Window.cpp b/es-core/src/Window.cpp index ae84f2889..e1820ecc6 100644 --- a/es-core/src/Window.cpp +++ b/es-core/src/Window.cpp @@ -14,40 +14,41 @@ #if defined(BUILD_VLC_PLAYER) #include "components/VideoVlcComponent.h" #endif -#include "resources/Font.h" #include "AudioManager.h" #include "InputManager.h" #include "Log.h" -#include "Scripting.h" #include "Sound.h" +#include "resources/Font.h" #include #include +#define CLOCK_BACKGROUND_CREATION false + Window::Window() - : mScreensaver(nullptr), - mMediaViewer(nullptr), - mLaunchScreen(nullptr), - mInfoPopup(nullptr), - mNormalizeNextUpdate(false), - mFrameTimeElapsed(0), - mFrameCountElapsed(0), - mAverageDeltaTime(10), - mAllowSleep(true), - mSleeping(false), - mTimeSinceLastInput(0), - mRenderScreensaver(false), - mRenderMediaViewer(false), - mRenderLaunchScreen(false), - mGameLaunchedState(false), - mAllowTextScrolling(true), - mCachedBackground(false), - mInvalidatedCachedBackground(false), - mVideoPlayerCount(0), - mTopOpacity(0), - mTopScale(0.5), - mListScrollOpacity(0), - mChangedThemeSet(false) + : mScreensaver(nullptr) + , mMediaViewer(nullptr) + , mLaunchScreen(nullptr) + , mInfoPopup(nullptr) + , mNormalizeNextUpdate(false) + , mFrameTimeElapsed(0) + , mFrameCountElapsed(0) + , mAverageDeltaTime(10) + , mAllowSleep(true) + , mSleeping(false) + , mTimeSinceLastInput(0) + , mRenderScreensaver(false) + , mRenderMediaViewer(false) + , mRenderLaunchScreen(false) + , mGameLaunchedState(false) + , mAllowTextScrolling(true) + , mCachedBackground(false) + , mInvalidatedCachedBackground(false) + , mVideoPlayerCount(0) + , mTopOpacity(0) + , mTopScale(0.5) + , mListScrollOpacity(0) + , mChangedThemeSet(false) { mHelp = new HelpComponent(this); mBackgroundOverlay = new ImageComponent(this); @@ -122,7 +123,7 @@ bool Window::init() mBackgroundOverlay->setImage(":/graphics/screen_gradient.png"); mBackgroundOverlay->setResize(static_cast(Renderer::getScreenWidth()), - static_cast(Renderer::getScreenHeight())); + static_cast(Renderer::getScreenHeight())); mListScrollFont = Font::get(FONT_SIZE_LARGE); @@ -141,9 +142,9 @@ void Window::deinit() InputManager::getInstance()->deinit(); ResourceManager::getInstance()->unloadAll(); - #if defined(BUILD_VLC_PLAYER) +#if defined(BUILD_VLC_PLAYER) VideoVlcComponent::deinit(); - #endif +#endif Renderer::deinit(); } @@ -154,8 +155,9 @@ void Window::input(InputConfig* config, Input input) // The DebugSkipInputLogging option has to be set manually in es_settings.xml as // it does not have any settings menu entry. if (Settings::getInstance()->getBool("Debug") && - !Settings::getInstance()->getBool("DebugSkipInputLogging")) + !Settings::getInstance()->getBool("DebugSkipInputLogging")) { logInput(config, input); + } if (mMediaViewer && mRenderMediaViewer) { if (config->isMappedLike("right", input) && input.value != 0) @@ -177,17 +179,17 @@ void Window::input(InputConfig* config, Input input) if (mScreensaver) { if (mScreensaver->isScreensaverActive() && - Settings::getInstance()->getBool("ScreensaverControls") && - ((Settings::getInstance()->getString("ScreensaverType") == "video") || - (Settings::getInstance()->getString("ScreensaverType") == "slideshow"))) { + Settings::getInstance()->getBool("ScreensaverControls") && + ((Settings::getInstance()->getString("ScreensaverType") == "video") || + (Settings::getInstance()->getString("ScreensaverType") == "slideshow"))) { bool customImageSlideshow = false; if (Settings::getInstance()->getString("ScreensaverType") == "slideshow" && - Settings::getInstance()->getBool("ScreensaverSlideshowCustomImages")) + Settings::getInstance()->getBool("ScreensaverSlideshowCustomImages")) customImageSlideshow = true; if ((customImageSlideshow || mScreensaver->getCurrentGame() != nullptr) && - (config->isMappedTo("a", input) || config->isMappedTo("y", input) || - config->isMappedLike("left", input) || config->isMappedLike("right", input))) { + (config->isMappedTo("a", input) || config->isMappedTo("y", input) || + config->isMappedLike("left", input) || config->isMappedLike("right", input))) { // Left or right browses to the next video or image. if (config->isMappedLike("left", input) || config->isMappedLike("right", input)) { if (input.value != 0) { @@ -230,22 +232,22 @@ void Window::input(InputConfig* config, Input input) } if (config->getDeviceId() == DEVICE_KEYBOARD && input.value && input.id == SDLK_g && - SDL_GetModState() & KMOD_LCTRL && Settings::getInstance()->getBool("Debug")) { + SDL_GetModState() & KMOD_LCTRL && Settings::getInstance()->getBool("Debug")) { // Toggle debug grid with Ctrl-G. Settings::getInstance()->setBool("DebugGrid", - !Settings::getInstance()->getBool("DebugGrid")); + !Settings::getInstance()->getBool("DebugGrid")); } else if (config->getDeviceId() == DEVICE_KEYBOARD && input.value && input.id == SDLK_t && - SDL_GetModState() & KMOD_LCTRL && Settings::getInstance()->getBool("Debug")) { + SDL_GetModState() & KMOD_LCTRL && Settings::getInstance()->getBool("Debug")) { // Toggle TextComponent debug view with Ctrl-T. Settings::getInstance()->setBool("DebugText", - !Settings::getInstance()->getBool("DebugText")); + !Settings::getInstance()->getBool("DebugText")); } else if (config->getDeviceId() == DEVICE_KEYBOARD && input.value && input.id == SDLK_i && - SDL_GetModState() & KMOD_LCTRL && Settings::getInstance()->getBool("Debug")) { + SDL_GetModState() & KMOD_LCTRL && Settings::getInstance()->getBool("Debug")) { // Toggle ImageComponent debug view with Ctrl-I. Settings::getInstance()->setBool("DebugImage", - !Settings::getInstance()->getBool("DebugImage")); + !Settings::getInstance()->getBool("DebugImage")); } else { if (peekGui()) @@ -270,8 +272,8 @@ void Window::logInput(InputConfig* config, Input input) mapname += ", "; } - LOG(LogDebug) << "Window::logInput(" << config->getDeviceName() << "): " << - input.string() << ", isMappedTo=" << mapname << "value=" << input.value; + LOG(LogDebug) << "Window::logInput(" << config->getDeviceName() << "): " << input.string() + << ", isMappedTo=" << mapname << "value=" << input.value; } void Window::update(int deltaTime) @@ -292,12 +294,13 @@ void Window::update(int deltaTime) std::stringstream ss; // FPS. - ss << std::fixed << std::setprecision(1) << - (1000.0f * static_cast(mFrameCountElapsed) / - static_cast(mFrameTimeElapsed)) << " FPS ("; - ss << std::fixed << std::setprecision(2) << - (static_cast(mFrameTimeElapsed) / - static_cast(mFrameCountElapsed)) << " ms)"; + ss << std::fixed << std::setprecision(1) + << (1000.0f * static_cast(mFrameCountElapsed) / + static_cast(mFrameTimeElapsed)) + << " FPS ("; + ss << std::fixed << std::setprecision(2) + << (static_cast(mFrameTimeElapsed) / static_cast(mFrameCountElapsed)) + << " ms)"; // The following calculations are not accurate, and the font calculation is completely // broken. For now, still report the figures as it's somehow useful to locate memory @@ -307,12 +310,12 @@ void Window::update(int deltaTime) float textureTotalUsageMiB = TextureResource::getTotalTextureSize() / 1024.0f / 1024.0f; float fontVramUsageMiB = Font::getTotalMemUsage() / 1024.0f / 1024.0f; - ss << "\nFont VRAM: " << fontVramUsageMiB << " MiB\nTexture VRAM: " << - textureVramUsageMiB << " MiB\nMax Texture VRAM: " << - textureTotalUsageMiB << " MiB"; - mFrameDataText = std::unique_ptr - (mDefaultFonts.at(0)->buildTextCache(ss.str(), Renderer::getScreenWidth() * - 0.02f, Renderer::getScreenHeight() * 0.02f, 0xFF00FFFF, 1.3f)); + ss << "\nFont VRAM: " << fontVramUsageMiB + << " MiB\nTexture VRAM: " << textureVramUsageMiB + << " MiB\nMax Texture VRAM: " << textureTotalUsageMiB << " MiB"; + mFrameDataText = std::unique_ptr(mDefaultFonts.at(0)->buildTextCache( + ss.str(), Renderer::getScreenWidth() * 0.02f, Renderer::getScreenHeight() * 0.02f, + 0xFF00FFFF, 1.3f)); } mFrameTimeElapsed = 0; @@ -368,27 +371,29 @@ void Window::render() else if (mRenderScreensaver && mScreensaver->isFallbackScreensaver()) renderBottom = true; else if (mRenderScreensaver && - Settings::getInstance()->getString("ScreensaverType") == "video") + Settings::getInstance()->getString("ScreensaverType") == "video") renderBottom = false; else if (mRenderScreensaver && - Settings::getInstance()->getString("ScreensaverType") == "slideshow") + Settings::getInstance()->getString("ScreensaverType") == "slideshow") renderBottom = false; if (renderBottom) bottom->render(transform); if (bottom != top || mRenderLaunchScreen) { - #if defined(USE_OPENGL_21) +#if defined(USE_OPENGL_21) if (!mCachedBackground) { // Generate a cache texture of the shaded background when opening the menu, which // will remain valid until the menu is closed. This is way faster than having to // render the shaders for every frame. -// const auto backgroundStartTime = std::chrono::system_clock::now(); +#if (CLOCK_BACKGROUND_CREATION) + const auto backgroundStartTime = std::chrono::system_clock::now(); +#endif std::shared_ptr mPostprocessedBackground; mPostprocessedBackground = TextureResource::get(""); - unsigned char* processedTexture = new unsigned char[Renderer::getScreenWidth() * - Renderer::getScreenHeight() * 4]; + unsigned char* processedTexture = + new unsigned char[Renderer::getScreenWidth() * Renderer::getScreenHeight() * 4]; // Defocus the background using multiple passes of gaussian blur, with the number // of iterations relative to the screen resolution. @@ -396,7 +401,7 @@ void Window::render() if (Settings::getInstance()->getBool("MenuBlurBackground")) { float heightModifier = Renderer::getScreenHeightModifier(); - + // clang-format off if (heightModifier < 1) backgroundParameters.blurPasses = 2; // Below 1080 else if (heightModifier >= 4) @@ -411,23 +416,25 @@ void Window::render() backgroundParameters.blurPasses = 3; // 1440 else if (heightModifier >= 1) backgroundParameters.blurPasses = 2; // 1080 + // clang-format on // Also dim the background slightly. backgroundParameters.fragmentDimValue = 0.60f; Renderer::shaderPostprocessing(Renderer::SHADER_BLUR_HORIZONTAL | - Renderer::SHADER_BLUR_VERTICAL | Renderer::SHADER_DIM, - backgroundParameters, processedTexture); + Renderer::SHADER_BLUR_VERTICAL | + Renderer::SHADER_DIM, + backgroundParameters, processedTexture); } else { // Dim the background slightly. backgroundParameters.fragmentDimValue = 0.60f; - Renderer::shaderPostprocessing( - Renderer::SHADER_DIM, backgroundParameters, processedTexture); + Renderer::shaderPostprocessing(Renderer::SHADER_DIM, backgroundParameters, + processedTexture); } - mPostprocessedBackground->initFromPixels(processedTexture, - Renderer::getScreenWidth(), Renderer::getScreenHeight()); + mPostprocessedBackground->initFromPixels( + processedTexture, Renderer::getScreenWidth(), Renderer::getScreenHeight()); mBackgroundOverlay->setImage(mPostprocessedBackground); @@ -444,10 +451,14 @@ void Window::render() delete[] processedTexture; mCachedBackground = true; -// const auto backgroundEndTime = std::chrono::system_clock::now(); -// LOG(LogDebug) << "Window::render(): Time to create cached background: " << -// std::chrono::duration_cast -// (backgroundEndTime - backgroundStartTime).count() << " ms"; +#if (CLOCK_BACKGROUND_CREATION) + const auto backgroundEndTime = std::chrono::system_clock::now(); + LOG(LogDebug) << "Window::render(): Time to create cached background: " + << std::chrono::duration_cast( + backgroundEndTime - backgroundStartTime) + .count() + << " ms"; +#endif } // Fade in the cached background if the menu opening effect has been set to scale-up. if (Settings::getInstance()->getString("MenuOpeningEffect") == "scale-up") { @@ -455,7 +466,7 @@ void Window::render() if (mBackgroundOverlayOpacity < 255) mBackgroundOverlayOpacity = Math::clamp(mBackgroundOverlayOpacity + 30, 0, 255); } - #endif +#endif // USE_OPENGL_21 mBackgroundOverlay->render(transform); @@ -464,8 +475,8 @@ void Window::render() if (mTopScale < 1.0f) { mTopScale = Math::clamp(mTopScale + 0.07f, 0.0f, 1.0f); Vector2f topCenter = top->getCenter(); - top->setOrigin({0.5, 0.5}); - top->setPosition({topCenter.x(), topCenter.y(), 0}); + top->setOrigin({ 0.5f, 0.5f }); + top->setPosition({ topCenter.x(), topCenter.y(), 0.0f }); top->setScale(mTopScale); } } @@ -476,7 +487,7 @@ void Window::render() else { mCachedBackground = false; mTopOpacity = 0; - mTopScale = 0.5; + mTopScale = 0.5f; } } @@ -484,15 +495,15 @@ void Window::render() if (mListScrollOpacity != 0) { Renderer::setMatrix(Transform4x4f::Identity()); Renderer::drawRect(0.0f, 0.0f, static_cast(Renderer::getScreenWidth()), - static_cast(Renderer::getScreenHeight()), - 0x00000000 | mListScrollOpacity, 0x00000000 | mListScrollOpacity); + static_cast(Renderer::getScreenHeight()), + 0x00000000 | mListScrollOpacity, 0x00000000 | mListScrollOpacity); Vector2f offset = mListScrollFont->sizeText(mListScrollText); offset[0] = (Renderer::getScreenWidth() - offset.x()) * 0.5f; offset[1] = (Renderer::getScreenHeight() - offset.y()) * 0.5f; - TextCache* cache = mListScrollFont->buildTextCache(mListScrollText, - offset.x(), offset.y(), 0xFFFFFF00 | mListScrollOpacity); + TextCache* cache = mListScrollFont->buildTextCache(mListScrollText, offset.x(), offset.y(), + 0xFFFFFF00 | mListScrollOpacity); mListScrollFont->renderTextCache(cache); delete cache; } @@ -501,7 +512,7 @@ void Window::render() mHelp->render(transform); unsigned int screensaverTimer = - static_cast(Settings::getInstance()->getInt("ScreensaverTimer")); + static_cast(Settings::getInstance()->getInt("ScreensaverTimer")); if (mTimeSinceLastInput >= screensaverTimer && screensaverTimer != 0) { // If the media viewer is running or if a menu is open, reset the screensaver timer so // that the screensaver won't start. @@ -549,17 +560,17 @@ void Window::renderLoadingScreen(std::string text) Transform4x4f trans = Transform4x4f::Identity(); Renderer::setMatrix(trans); Renderer::drawRect(0.0f, 0.0f, static_cast(Renderer::getScreenWidth()), - static_cast(Renderer::getScreenHeight()), 0x000000FF, 0x000000FF); + static_cast(Renderer::getScreenHeight()), 0x000000FF, 0x000000FF); ImageComponent splash(this, true); splash.setResize(Renderer::getScreenWidth() * 0.6f, 0.0f); splash.setImage(":/graphics/splash.svg"); - splash.setPosition((Renderer::getScreenWidth() - splash.getSize().x()) / 2, - (Renderer::getScreenHeight() - splash.getSize().y()) / 2 * 0.6f); + splash.setPosition((Renderer::getScreenWidth() - splash.getSize().x()) / 2.0f, + (Renderer::getScreenHeight() - splash.getSize().y()) / 2.0f * 0.6f); splash.render(trans); auto& font = mDefaultFonts.at(1); - TextCache* cache = font->buildTextCache(text, 0, 0, 0x656565FF); + TextCache* cache = font->buildTextCache(text, 0.0f, 0.0f, 0x656565FF); float x = std::round((Renderer::getScreenWidth() - cache->metrics.size.x()) / 2.0f); float y = std::round(Renderer::getScreenHeight() * 0.835f); @@ -602,20 +613,17 @@ void Window::setHelpPrompts(const std::vector& prompts, const HelpSt // Can we combine? (dpad only). if ((it->first == "up/down" && - addPrompts.at(mappedTo->second).first != "left/right") || - (it->first == "left/right" && - addPrompts.at(mappedTo->second).first != "up/down")) { - // Yes! + addPrompts.at(mappedTo->second).first != "left/right") || + (it->first == "left/right" && + addPrompts.at(mappedTo->second).first != "up/down")) { + // Yes. addPrompts.at(mappedTo->second).first = "up/down/left/right"; - // Don't need to add this to addPrompts since we just merged. } else { - // No, we can't combine! addPrompts.push_back(*it); } } else { - // No, it hasn't! mappedToSeenMap.emplace(it->second, static_cast(addPrompts.size())); addPrompts.push_back(*it); } @@ -624,29 +632,31 @@ void Window::setHelpPrompts(const std::vector& prompts, const HelpSt // Sort prompts so it goes [dpad_all] [dpad_u/d] [dpad_l/r] [a/b/x/y/l/r] [start/back]. std::sort(addPrompts.begin(), addPrompts.end(), - [](const HelpPrompt& a, const HelpPrompt& b) -> bool { + [](const HelpPrompt& a, const HelpPrompt& b) -> bool { + static const std::vector map = { "up/down/left/right", + "up/down", + "left/right", + "a", + "b", + "x", + "y", + "l", + "r", + "start", + "back" }; + int i = 0; + int aVal = 0; + int bVal = 0; + while (i < map.size()) { + if (a.first == map[i]) + aVal = i; + if (b.first == map[i]) + bVal = i; + i++; + } - static const std::vector map = { - "up/down/left/right", - "up/down", - "left/right", - "a", "b", "x", "y", "l", "r", - "start", "back" - }; - - int i = 0; - int aVal = 0; - int bVal = 0; - while (i < map.size()) { - if (a.first == map[i]) - aVal = i; - if (b.first == map[i]) - bVal = i; - i++; - } - - return aVal > bVal; - }); + return aVal > bVal; + }); mHelp->setPrompts(addPrompts); } @@ -789,18 +799,8 @@ void Window::invalidateCachedBackground() mInvalidatedCachedBackground = true; } -void Window::onSleep() -{ - Scripting::fireEvent("sleep"); -} - -void Window::onWake() -{ - Scripting::fireEvent("wake"); -} - bool Window::isProcessing() { - return count_if (mGuiStack.cbegin(), mGuiStack.cend(), [](GuiComponent* c) { - return c->isProcessing(); }) > 0; + return count_if(mGuiStack.cbegin(), mGuiStack.cend(), + [](GuiComponent* c) { return c->isProcessing(); }) > 0; } diff --git a/es-core/src/Window.h b/es-core/src/Window.h index 634c59c3e..5201b2902 100644 --- a/es-core/src/Window.h +++ b/es-core/src/Window.h @@ -10,10 +10,11 @@ #ifndef ES_CORE_WINDOW_H #define ES_CORE_WINDOW_H -#include "resources/TextureResource.h" #include "HelpPrompt.h" #include "InputConfig.h" +#include "Scripting.h" #include "Settings.h" +#include "resources/TextureResource.h" #include #include @@ -78,7 +79,7 @@ public: public: virtual void render(const Transform4x4f& parentTrans) = 0; virtual void stop() = 0; - virtual ~InfoPopup() {}; + virtual ~InfoPopup() {} }; Window(); @@ -87,7 +88,7 @@ public: void pushGui(GuiComponent* gui); void removeGui(GuiComponent* gui); GuiComponent* peekGui(); - inline int getGuiStackSize() { return static_cast(mGuiStack.size()); } + int getGuiStackSize() { return static_cast(mGuiStack.size()); } bool init(); void deinit(); @@ -102,7 +103,7 @@ public: bool getAllowSleep() { return mAllowSleep; } void setAllowSleep(bool sleep) { mAllowSleep = sleep; } - inline bool isSleeping() const { return mSleeping; } + bool isSleeping() const { return mSleeping; } void renderLoadingScreen(std::string text); // The list scroll overlay is triggered from IList when the highest scrolling tier is reached. @@ -148,8 +149,8 @@ public: bool getChangedThemeSet() { return mChangedThemeSet; } private: - void onSleep(); - void onWake(); + void onSleep() { Scripting::fireEvent("sleep"); } + void onWake() { Scripting::fireEvent("wake"); } // Returns true if at least one component on the stack is processing. bool isProcessing(); diff --git a/es-core/src/animations/Animation.h b/es-core/src/animations/Animation.h index b2eaf28d0..62c5a15f8 100644 --- a/es-core/src/animations/Animation.h +++ b/es-core/src/animations/Animation.h @@ -12,7 +12,7 @@ class Animation { public: - virtual ~Animation() {}; + virtual ~Animation() {} virtual int getDuration() const = 0; virtual void apply(float t) = 0; }; diff --git a/es-core/src/animations/AnimationController.cpp b/es-core/src/animations/AnimationController.cpp index 7f39ce946..e351b87ae 100644 --- a/es-core/src/animations/AnimationController.cpp +++ b/es-core/src/animations/AnimationController.cpp @@ -10,16 +10,15 @@ #include "animations/Animation.h" -AnimationController::AnimationController( - Animation* anim, - int delay, - std::function finishedCallback, - bool reverse) - : mAnimation(anim), - mFinishedCallback(finishedCallback), - mReverse(reverse), - mTime(-delay), - mDelay(delay) +AnimationController::AnimationController(Animation* anim, + int delay, + std::function finishedCallback, + bool reverse) + : mAnimation(anim) + , mFinishedCallback(finishedCallback) + , mReverse(reverse) + , mTime(-delay) + , mDelay(delay) { } diff --git a/es-core/src/animations/AnimationController.h b/es-core/src/animations/AnimationController.h index 786d44503..a44d23072 100644 --- a/es-core/src/animations/AnimationController.h +++ b/es-core/src/animations/AnimationController.h @@ -17,20 +17,22 @@ class AnimationController { public: // Takes ownership of anim (will delete in destructor). - AnimationController(Animation* anim, int delay = 0, - std::function finishedCallback = nullptr, bool reverse = false); + AnimationController(Animation* anim, + int delay = 0, + std::function finishedCallback = nullptr, + bool reverse = false); virtual ~AnimationController(); // Returns true if the animation is complete. bool update(int deltaTime); - inline bool isReversed() const { return mReverse; } - inline int getTime() const { return mTime; } - inline int getDelay() const { return mDelay; } - inline const std::function& getFinishedCallback() const { return mFinishedCallback; } - inline Animation* getAnimation() const { return mAnimation; } + bool isReversed() const { return mReverse; } + int getTime() const { return mTime; } + int getDelay() const { return mDelay; } + const std::function& getFinishedCallback() const { return mFinishedCallback; } + Animation* getAnimation() const { return mAnimation; } - inline void removeFinishedCallback() { mFinishedCallback = nullptr; } + void removeFinishedCallback() { mFinishedCallback = nullptr; } private: Animation* mAnimation; diff --git a/es-core/src/animations/LambdaAnimation.h b/es-core/src/animations/LambdaAnimation.h index 82055a492..974d3d5c4 100644 --- a/es-core/src/animations/LambdaAnimation.h +++ b/es-core/src/animations/LambdaAnimation.h @@ -19,16 +19,15 @@ class LambdaAnimation : public Animation { public: LambdaAnimation(const std::function& func, int duration) - : mFunction(func), mDuration(duration) {} + : mFunction(func) + , mDuration(duration) + { + } virtual ~LambdaAnimation() = default; int getDuration() const override { return mDuration; } - - void apply(float t) override - { - mFunction(t); - } + void apply(float t) override { mFunction(t); } private: std::function mFunction; diff --git a/es-core/src/components/AnimatedImageComponent.cpp b/es-core/src/components/AnimatedImageComponent.cpp index 9f655aa61..64cbc2b81 100644 --- a/es-core/src/components/AnimatedImageComponent.cpp +++ b/es-core/src/components/AnimatedImageComponent.cpp @@ -8,12 +8,13 @@ #include "components/AnimatedImageComponent.h" +#include "Log.h" #include "components/ImageComponent.h" #include "resources/ResourceManager.h" -#include "Log.h" AnimatedImageComponent::AnimatedImageComponent(Window* window) - : GuiComponent(window), mEnabled(false) + : GuiComponent(window) + , mEnabled(false) { } @@ -25,9 +26,9 @@ void AnimatedImageComponent::load(const AnimationDef* def) for (size_t i = 0; i < def->frameCount; i++) { if (def->frames[i].path != "" && - !ResourceManager::getInstance()->fileExists(def->frames[i].path)) { - LOG(LogError) << "Missing animation frame " << i << - " (\"" << def->frames[i].path << "\")"; + !ResourceManager::getInstance()->fileExists(def->frames[i].path)) { + LOG(LogError) << "Missing animation frame " << i << " (\"" << def->frames[i].path + << "\")"; continue; } diff --git a/es-core/src/components/BusyComponent.cpp b/es-core/src/components/BusyComponent.cpp index cd924cbe4..c66a5ae99 100644 --- a/es-core/src/components/BusyComponent.cpp +++ b/es-core/src/components/BusyComponent.cpp @@ -14,21 +14,23 @@ // Animation definition. AnimationFrame BUSY_ANIMATION_FRAMES[] = { - {":/graphics/busy_0.svg", 300}, - {":/graphics/busy_1.svg", 300}, - {":/graphics/busy_2.svg", 300}, - {":/graphics/busy_3.svg", 300}, + { ":/graphics/busy_0.svg", 300 }, + { ":/graphics/busy_1.svg", 300 }, + { ":/graphics/busy_2.svg", 300 }, + { ":/graphics/busy_3.svg", 300 }, }; const AnimationDef BUSY_ANIMATION_DEF = { BUSY_ANIMATION_FRAMES, 4, true }; -BusyComponent::BusyComponent(Window* window): GuiComponent(window), - mBackground(window, ":/graphics/frame.png"), mGrid(window, Vector2i(5, 3)) +BusyComponent::BusyComponent(Window* window) + : GuiComponent(window) + , mBackground(window, ":/graphics/frame.png") + , mGrid(window, Vector2i(5, 3)) { mAnimation = std::make_shared(mWindow); mAnimation->load(&BUSY_ANIMATION_DEF); - mText = std::make_shared(mWindow, "WORKING...", - Font::get(FONT_SIZE_MEDIUM), 0x777777FF); + mText = std::make_shared(mWindow, "WORKING...", Font::get(FONT_SIZE_MEDIUM), + 0x777777FF); // Col 0 = animation, col 1 = spacer, col 2 = text. mGrid.setEntry(mAnimation, Vector2i(1, 1), false, true); @@ -57,13 +59,13 @@ void BusyComponent::onSizeChanged() mGrid.setRowHeightPerc(1, textHeight / mSize.y()); mBackground.setCornerSize({ 16.0f * Renderer::getScreenWidthModifier(), - 16.0f * Renderer::getScreenHeightModifier() }); - mBackground.fitTo(Vector2f(mGrid.getColWidth(1) + mGrid.getColWidth(2) + - mGrid.getColWidth(3), textHeight + (2 * Renderer::getScreenHeightModifier())), - mAnimation->getPosition(), Vector2f(0, 0)); + 16.0f * Renderer::getScreenHeightModifier() }); + mBackground.fitTo(Vector2f(mGrid.getColWidth(1) + mGrid.getColWidth(2) + mGrid.getColWidth(3), + textHeight + (2.0f * Renderer::getScreenHeightModifier())), + mAnimation->getPosition(), Vector2f(0, 0)); } void BusyComponent::reset() { - //mAnimation->reset(); + // mAnimation->reset(); } diff --git a/es-core/src/components/BusyComponent.h b/es-core/src/components/BusyComponent.h index 0dd634e4c..e3c361905 100644 --- a/es-core/src/components/BusyComponent.h +++ b/es-core/src/components/BusyComponent.h @@ -9,9 +9,9 @@ #ifndef ES_CORE_COMPONENTS_BUSY_COMPONENT_H #define ES_CORE_COMPONENTS_BUSY_COMPONENT_H +#include "GuiComponent.h" #include "components/ComponentGrid.h" #include "components/NinePatchComponent.h" -#include "GuiComponent.h" class AnimatedImageComponent; class TextComponent; diff --git a/es-core/src/components/ButtonComponent.cpp b/es-core/src/components/ButtonComponent.cpp index caa82ad4b..06d7032d4 100644 --- a/es-core/src/components/ButtonComponent.cpp +++ b/es-core/src/components/ButtonComponent.cpp @@ -8,20 +8,21 @@ #include "components/ButtonComponent.h" +#include "Settings.h" #include "resources/Font.h" #include "utils/StringUtil.h" -#include "Settings.h" -ButtonComponent::ButtonComponent( - Window* window, const std::string& text, - const std::string& helpText, - const std::function& func) - : GuiComponent(window), - mBox(window, ":/graphics/button.svg"), - mFont(Font::get(FONT_SIZE_MEDIUM)), - mFocused(false), - mEnabled(true), - mTextColorFocused(0xFFFFFFFF), mTextColorUnfocused(0x777777FF) +ButtonComponent::ButtonComponent(Window* window, + const std::string& text, + const std::string& helpText, + const std::function& func) + : GuiComponent(window) + , mBox(window, ":/graphics/button.svg") + , mFont(Font::get(FONT_SIZE_MEDIUM)) + , mFocused(false) + , mEnabled(true) + , mTextColorFocused(0xFFFFFFFF) + , mTextColorUnfocused(0x777777FF) { setPressedFunc(func); setText(text, helpText); @@ -30,12 +31,8 @@ ButtonComponent::ButtonComponent( void ButtonComponent::onSizeChanged() { - mBox.fitTo(mSize, Vector3f::Zero(), Vector2f(-32, -32)); -} - -void ButtonComponent::setPressedFunc(std::function f) -{ - mPressedFunc = f; + // Fit to mBox. + mBox.fitTo(mSize, Vector3f::Zero(), Vector2f(-32.0f, -32.0f)); } bool ButtonComponent::input(InputConfig* config, Input input) @@ -56,9 +53,10 @@ void ButtonComponent::setText(const std::string& text, const std::string& helpTe mTextCache = std::unique_ptr(mFont->buildTextCache(mText, 0, 0, getCurTextColor())); - float minWidth = mFont->sizeText("DELETE").x() + (12 * Renderer::getScreenWidthModifier()); - setSize(std::max(mTextCache->metrics.size.x() + (12 * Renderer::getScreenWidthModifier()), - minWidth), mTextCache->metrics.size.y()); + float minWidth = mFont->sizeText("DELETE").x() + (12.0f * Renderer::getScreenWidthModifier()); + setSize(std::max(mTextCache->metrics.size.x() + (12.0f * Renderer::getScreenWidthModifier()), + minWidth), + mTextCache->metrics.size.y()); updateHelpPrompts(); } @@ -103,14 +101,14 @@ void ButtonComponent::render(const Transform4x4f& parentTrans) if (mTextCache) { Vector3f centerOffset((mSize.x() - mTextCache->metrics.size.x()) / 2.0f, - (mSize.y() - mTextCache->metrics.size.y()) / 2.0f, 0); + (mSize.y() - mTextCache->metrics.size.y()) / 2.0f, 0); trans = trans.translate(centerOffset); if (Settings::getInstance()->getBool("DebugText")) { - Renderer::drawRect(centerOffset.x(), 0.0f, mTextCache->metrics.size.x(), - mSize.y(), 0x00000033, 0x00000033); - Renderer::drawRect(mBox.getPosition().x(), 0.0f, mBox.getSize().x(), - mSize.y(), 0x0000FF33, 0x0000FF33); + Renderer::drawRect(centerOffset.x(), 0.0f, mTextCache->metrics.size.x(), mSize.y(), + 0x00000033, 0x00000033); + Renderer::drawRect(mBox.getPosition().x(), 0.0f, mBox.getSize().x(), mSize.y(), + 0x0000FF33, 0x0000FF33); } Renderer::setMatrix(trans); diff --git a/es-core/src/components/ButtonComponent.h b/es-core/src/components/ButtonComponent.h index ae38916a5..fd2c59171 100644 --- a/es-core/src/components/ButtonComponent.h +++ b/es-core/src/components/ButtonComponent.h @@ -9,18 +9,20 @@ #ifndef ES_CORE_COMPONENTS_BUTTON_COMPONENT_H #define ES_CORE_COMPONENTS_BUTTON_COMPONENT_H -#include "components/NinePatchComponent.h" #include "GuiComponent.h" +#include "components/NinePatchComponent.h" class TextCache; class ButtonComponent : public GuiComponent { public: - ButtonComponent(Window* window, const std::string& text = "", - const std::string& helpText = "", const std::function& func = nullptr); + ButtonComponent(Window* window, + const std::string& text = "", + const std::string& helpText = "", + const std::function& func = nullptr); - void setPressedFunc(std::function f); + void setPressedFunc(std::function f) { mPressedFunc = f; } void setEnabled(bool state) override; bool input(InputConfig* config, Input input) override; @@ -28,8 +30,8 @@ public: void setText(const std::string& text, const std::string& helpText); - inline const std::string& getText() const { return mText; }; - inline const std::function& getPressedFunc() const { return mPressedFunc; }; + const std::string& getText() const { return mText; } + const std::function& getPressedFunc() const { return mPressedFunc; } void onSizeChanged() override; void onFocusGained() override; diff --git a/es-core/src/components/ComponentGrid.cpp b/es-core/src/components/ComponentGrid.cpp index 183975e73..d8bf872d3 100644 --- a/es-core/src/components/ComponentGrid.cpp +++ b/es-core/src/components/ComponentGrid.cpp @@ -12,12 +12,10 @@ using namespace GridFlags; -ComponentGrid::ComponentGrid( - Window* window, - const Vector2i& gridDimensions) - : GuiComponent(window), - mGridSize(gridDimensions), - mCursor(0, 0) +ComponentGrid::ComponentGrid(Window* window, const Vector2i& gridDimensions) + : GuiComponent(window) + , mGridSize(gridDimensions) + , mCursor(0, 0) { assert(gridDimensions.x() > 0 && gridDimensions.y() > 0); @@ -25,6 +23,7 @@ ComponentGrid::ComponentGrid( mColWidths = new float[gridDimensions.x()]; mRowHeights = new float[gridDimensions.y()]; + for (int x = 0; x < gridDimensions.x(); x++) mColWidths[x] = 0; for (int y = 0; y < gridDimensions.y(); y++) @@ -90,14 +89,13 @@ void ComponentGrid::setRowHeightPerc(int row, float height, bool update) onSizeChanged(); } -void ComponentGrid::setEntry( - const std::shared_ptr& comp, - const Vector2i& pos, - bool canFocus, - bool resize, - const Vector2i& size, - unsigned int border, - GridFlags::UpdateType updateType) +void ComponentGrid::setEntry(const std::shared_ptr& comp, + const Vector2i& pos, + bool canFocus, + bool resize, + const Vector2i& size, + unsigned int border, + GridFlags::UpdateType updateType) { assert(pos.x() >= 0 && pos.x() < mGridSize.x() && pos.y() >= 0 && pos.y() < mGridSize.y()); assert(comp != nullptr); @@ -294,14 +292,14 @@ bool ComponentGrid::moveCursor(Vector2i dir) Vector2i searchAxis(dir.x() == 0, dir.y() == 0); while (mCursor.x() >= 0 && mCursor.y() >= 0 && mCursor.x() < mGridSize.x() && - mCursor.y() < mGridSize.y()) { + mCursor.y() < mGridSize.y()) { mCursor = mCursor + dir; Vector2i curDirPos = mCursor; const GridEntry* cursorEntry; // Spread out on search axis+ - while (mCursor.x() < mGridSize.x() && mCursor.y() < mGridSize.y() - && mCursor.x() >= 0 && mCursor.y() >= 0) { + while (mCursor.x() < mGridSize.x() && mCursor.y() < mGridSize.y() && mCursor.x() >= 0 && + mCursor.y() >= 0) { cursorEntry = getCellAt(mCursor); if (cursorEntry && cursorEntry->canFocus && cursorEntry != currentCursorEntry) { onCursorMoved(origCursor, mCursor); @@ -312,8 +310,8 @@ bool ComponentGrid::moveCursor(Vector2i dir) // Now again on search axis- mCursor = curDirPos; - while (mCursor.x() >= 0 && mCursor.y() >= 0 - && mCursor.x() < mGridSize.x() && mCursor.y() < mGridSize.y()) { + while (mCursor.x() >= 0 && mCursor.y() >= 0 && mCursor.x() < mGridSize.x() && + mCursor.y() < mGridSize.y()) { cursorEntry = getCellAt(mCursor); if (cursorEntry && cursorEntry->canFocus && cursorEntry != currentCursorEntry) { @@ -356,8 +354,9 @@ void ComponentGrid::update(int deltaTime) const GridEntry* cursorEntry = getCellAt(mCursor); for (auto it = mCells.cbegin(); it != mCells.cend(); it++) { if (it->updateType == UPDATE_ALWAYS || - (it->updateType == UPDATE_WHEN_SELECTED && cursorEntry == &(*it))) + (it->updateType == UPDATE_WHEN_SELECTED && cursorEntry == &(*it))) { it->component->update(deltaTime); + } } } @@ -371,7 +370,7 @@ void ComponentGrid::render(const Transform4x4f& parentTrans) for (size_t i = 0; i < mSeparators.size(); i++) { Renderer::setMatrix(trans); Renderer::drawRect(mSeparators[i][0], mSeparators[i][1], mSeparators[i][2], - mSeparators[i][3], 0xC6C7C6FF, 0xC6C7C6FF); + mSeparators[i][3], 0xC6C7C6FF, 0xC6C7C6FF); } } diff --git a/es-core/src/components/ComponentGrid.h b/es-core/src/components/ComponentGrid.h index 8b98e4950..9acd927e0 100644 --- a/es-core/src/components/ComponentGrid.h +++ b/es-core/src/components/ComponentGrid.h @@ -9,14 +9,14 @@ #ifndef ES_CORE_COMPONENTS_COMPONENT_GRID_H #define ES_CORE_COMPONENTS_COMPONENT_GRID_H +#include "GuiComponent.h" #include "math/Vector2i.h" #include "renderers/Renderer.h" -#include "GuiComponent.h" namespace GridFlags { enum UpdateType { - UPDATE_ALWAYS, + UPDATE_ALWAYS, // Replace with AllowShortEnumsOnASingleLine: false (clang-format >=11.0). UPDATE_WHEN_SELECTED, UPDATE_NEVER }; @@ -28,7 +28,7 @@ namespace GridFlags BORDER_LEFT = 4, BORDER_RIGHT = 8 }; -}; +}; // namespace GridFlags // Provides basic layout of components in an X*Y grid. class ComponentGrid : public GuiComponent @@ -39,14 +39,13 @@ public: bool removeEntry(const std::shared_ptr& comp); - void setEntry( - const std::shared_ptr& comp, - const Vector2i& pos, - bool canFocus, - bool resize = true, - const Vector2i& size = Vector2i(1, 1), - unsigned int border = GridFlags::BORDER_NONE, - GridFlags::UpdateType updateType = GridFlags::UPDATE_ALWAYS); + void setEntry(const std::shared_ptr& comp, + const Vector2i& pos, + bool canFocus, + bool resize = true, + const Vector2i& size = Vector2i(1, 1), + unsigned int border = GridFlags::BORDER_NONE, + GridFlags::UpdateType updateType = GridFlags::UPDATE_ALWAYS); void textInput(const std::string& text) override; bool input(InputConfig* config, Input input) override; @@ -69,7 +68,7 @@ public: bool moveCursor(Vector2i dir); void setCursorTo(const std::shared_ptr& comp); - inline std::shared_ptr getSelectedComponent() + std::shared_ptr getSelectedComponent() { const GridEntry* e = getCellAt(mCursor); if (e) @@ -95,28 +94,24 @@ private: GridFlags::UpdateType updateType; unsigned int border; - GridEntry( - const Vector2i& p = Vector2i::Zero(), - const Vector2i& d = Vector2i::Zero(), - const std::shared_ptr& cmp = nullptr, - bool f = false, - bool r = true, - GridFlags::UpdateType u = GridFlags::UPDATE_ALWAYS, - unsigned int b = - GridFlags::BORDER_NONE) - : pos(p), - dim(d), - component(cmp), - canFocus(f), - resize(r), - updateType(u), - border(b) - {}; - - operator bool() const + GridEntry(const Vector2i& p = Vector2i::Zero(), + const Vector2i& d = Vector2i::Zero(), + const std::shared_ptr& cmp = nullptr, + bool f = false, + bool r = true, + GridFlags::UpdateType u = GridFlags::UPDATE_ALWAYS, + unsigned int b = GridFlags::BORDER_NONE) + : pos(p) + , dim(d) + , component(cmp) + , canFocus(f) + , resize(r) + , updateType(u) + , border(b) { - return component != nullptr; } + + operator bool() const { return component != nullptr; } }; // Update position and size. @@ -125,9 +120,7 @@ private: void onCursorMoved(Vector2i from, Vector2i to); const GridEntry* getCellAt(int x, int y) const; - - inline const GridEntry* getCellAt(const Vector2i& pos) const - { return getCellAt(pos.x(), pos.y()); } + const GridEntry* getCellAt(const Vector2i& pos) const { return getCellAt(pos.x(), pos.y()); } std::vector> mSeparators; Vector2i mGridSize; diff --git a/es-core/src/components/ComponentList.cpp b/es-core/src/components/ComponentList.cpp index 6edff9740..9e1edfab3 100644 --- a/es-core/src/components/ComponentList.cpp +++ b/es-core/src/components/ComponentList.cpp @@ -10,14 +10,14 @@ #define TOTAL_HORIZONTAL_PADDING_PX 20.0f -ComponentList::ComponentList(Window* window) : IList(window, LIST_SCROLL_STYLE_SLOW, LIST_NEVER_LOOP) +ComponentList::ComponentList(Window* window) + : IList(window, LIST_SCROLL_STYLE_SLOW, LIST_NEVER_LOOP) { // Adjust the padding relative to the aspect ratio and screen resolution to make it look // coherent regardless of screen type. The 1.778 aspect ratio value is the 16:9 reference. float aspectValue = 1.778f / Renderer::getScreenAspectRatio(); - mHorizontalPadding = TOTAL_HORIZONTAL_PADDING_PX * aspectValue * - Renderer::getScreenWidthModifier(); + mHorizontalPadding = + TOTAL_HORIZONTAL_PADDING_PX * aspectValue * Renderer::getScreenWidthModifier(); mSelectorBarOffset = 0.0f; mCameraOffset = 0.0f; @@ -34,7 +34,7 @@ void ComponentList::addRow(const ComponentListRow& row, bool setCursorHere) this->add(e); for (auto it = mEntries.back().data.elements.cbegin(); - it != mEntries.back().data.elements.cend(); it++) + it != mEntries.back().data.elements.cend(); it++) addChild(it->component.get()); updateElementSize(mEntries.back().data); @@ -56,16 +56,6 @@ void ComponentList::onSizeChanged() updateCameraOffset(); } -void ComponentList::onFocusLost() -{ - mFocused = false; -} - -void ComponentList::onFocusGained() -{ - mFocused = true; -} - bool ComponentList::input(InputConfig* config, Input input) { if (size() == 0) @@ -122,7 +112,7 @@ void ComponentList::update(int deltaTime) if (size()) { // Update our currently selected row. for (auto it = mEntries.at(mCursor).data.elements.cbegin(); - it != mEntries.at(mCursor).data.elements.cend(); it++) + it != mEntries.at(mCursor).data.elements.cend(); it++) it->component->update(deltaTime); } } @@ -156,8 +146,8 @@ void ComponentList::updateCameraOffset() // Move the camera to scroll. const float totalHeight = getTotalRowHeight(); if (totalHeight > mSize.y()) { - float target = mSelectorBarOffset + - getRowHeight(mEntries.at(mCursor).data) / 2.0f - (mSize.y() / 2.0f); + float target = mSelectorBarOffset + getRowHeight(mEntries.at(mCursor).data) / 2.0f - + (mSize.y() / 2.0f); // Clamp the camera to prevent a fraction of a row from being displayed. mCameraOffset = 0.0f; @@ -187,9 +177,10 @@ void ComponentList::render(const Transform4x4f& parentTrans) // Clip everything to be inside our bounds. Vector3f dim(mSize.x(), mSize.y(), 0.0f); dim = trans * dim - trans.translation(); - Renderer::pushClipRect(Vector2i(static_cast(std::round(trans.translation().x())), - static_cast(std::round(trans.translation().y()))), Vector2i(static_cast( - std::round(dim.x())), static_cast(std::round(dim.y())))); + Renderer::pushClipRect( + Vector2i(static_cast(std::round(trans.translation().x())), + static_cast(std::round(trans.translation().y()))), + Vector2i(static_cast(std::round(dim.x())), static_cast(std::round(dim.y())))); // Scroll the camera. trans.translate(Vector3f(0.0f, -std::round(mCameraOffset), 0.0f)); @@ -205,7 +196,7 @@ void ComponentList::render(const Transform4x4f& parentTrans) // For the row where the cursor is at, we want to remove any hue from the // font or image before inverting, as it would otherwise lead to an ugly // inverted color (e.g. red inverting to a green hue). - if (i == mCursor && it->component->getValue() != "" ) { + if (i == mCursor && it->component->getValue() != "") { // Check if we're dealing with text or an image component. bool isTextComponent = true; unsigned int origColor = it->component->getColor(); @@ -260,13 +251,13 @@ void ComponentList::render(const Transform4x4f& parentTrans) const float selectedRowHeight = getRowHeight(mEntries.at(mCursor).data); if (opacity == 1) { - Renderer::drawRect(0.0f, mSelectorBarOffset, mSize.x(), - selectedRowHeight, 0xFFFFFFFF, 0xFFFFFFFF, false, opacity, trans, - Renderer::Blend::ONE_MINUS_DST_COLOR, Renderer::Blend::ZERO); + Renderer::drawRect(0.0f, mSelectorBarOffset, mSize.x(), selectedRowHeight, 0xFFFFFFFF, + 0xFFFFFFFF, false, opacity, trans, + Renderer::Blend::ONE_MINUS_DST_COLOR, Renderer::Blend::ZERO); - Renderer::drawRect(0.0f, mSelectorBarOffset, mSize.x(), - selectedRowHeight, 0x777777FF, 0x777777FF, false, opacity, trans, - Renderer::Blend::ONE, Renderer::Blend::ONE); + Renderer::drawRect(0.0f, mSelectorBarOffset, mSize.x(), selectedRowHeight, 0x777777FF, + 0x777777FF, false, opacity, trans, Renderer::Blend::ONE, + Renderer::Blend::ONE); } for (auto it = drawAfterCursor.cbegin(); it != drawAfterCursor.cend(); it++) @@ -281,12 +272,12 @@ void ComponentList::render(const Transform4x4f& parentTrans) float y = 0; for (unsigned int i = 0; i < mEntries.size(); i++) { Renderer::drawRect(0.0f, y, mSize.x(), 1.0f * Renderer::getScreenHeightModifier(), - 0xC6C7C6FF, 0xC6C7C6FF, false, opacity, trans); + 0xC6C7C6FF, 0xC6C7C6FF, false, opacity, trans); y += getRowHeight(mEntries.at(i).data); } - Renderer::drawRect(0.0f, y, mSize.x(), 1.0f * Renderer::getScreenHeightModifier(), - 0xC6C7C6FF, 0xC6C7C6FF, false, opacity, trans); + Renderer::drawRect(0.0f, y, mSize.x(), 1.0f * Renderer::getScreenHeightModifier(), 0xC6C7C6FF, + 0xC6C7C6FF, false, opacity, trans); Renderer::popClipRect(); } @@ -362,7 +353,7 @@ std::vector ComponentList::getHelpPrompts() return std::vector(); std::vector prompts = - mEntries.at(mCursor).data.elements.back().component->getHelpPrompts(); + mEntries.at(mCursor).data.elements.back().component->getHelpPrompts(); if (size() > 1) { bool addMovePrompt = true; diff --git a/es-core/src/components/ComponentList.h b/es-core/src/components/ComponentList.h index e4b6e4b31..309e2007c 100644 --- a/es-core/src/components/ComponentList.h +++ b/es-core/src/components/ComponentList.h @@ -12,21 +12,21 @@ #include "IList.h" struct ComponentListElement { - ComponentListElement( - const std::shared_ptr& cmp = nullptr, - bool resize_w = true, - bool inv = true) - : component(cmp), - resize_width(resize_w), - invert_when_selected(inv) {}; + ComponentListElement(const std::shared_ptr& cmp = nullptr, + bool resize_w = true, + bool inv = true) + : component(cmp) + , resize_width(resize_w) + , invert_when_selected(inv) + { + } std::shared_ptr component; bool resize_width; bool invert_when_selected; }; -struct ComponentListRow -{ +struct ComponentListRow { std::vector elements; // The input handler is called when the user enters any input while this row is @@ -36,14 +36,15 @@ struct ComponentListRow // to forward the input to the rightmost element in the currently selected row. std::function input_handler; - inline void addElement(const std::shared_ptr& component, - bool resize_width, bool invert_when_selected = true) + void addElement(const std::shared_ptr& component, + bool resize_width, + bool invert_when_selected = true) { elements.push_back(ComponentListElement(component, resize_width, invert_when_selected)); } // Utility function for making an input handler for "when the users presses A on this, do func". - inline void makeAcceptInputHandler(const std::function& func) + void makeAcceptInputHandler(const std::function& func) { input_handler = [func](InputConfig* config, Input input) -> bool { if (config->isMappedTo("a", input) && input.value != 0) { @@ -69,19 +70,23 @@ public: virtual std::vector getHelpPrompts() override; void onSizeChanged() override; - void onFocusGained() override; - void onFocusLost() override; + void onFocusGained() override { mFocused = true; } + void onFocusLost() override { mFocused = false; } bool moveCursor(int amt); - inline int getCursorId() const { return mCursor; } + int getCursorId() const { return mCursor; } float getTotalRowHeight() const; - inline float getRowHeight(int row) const { return getRowHeight(mEntries.at(row).data); } + float getRowHeight(int row) const { return getRowHeight(mEntries.at(row).data); } - inline void setCursorChangedCallback(const std::function& callback) - { mCursorChangedCallback = callback; }; - inline const std::function& getCursorChangedCallback() const - { return mCursorChangedCallback; }; + void setCursorChangedCallback(const std::function& callback) + { + mCursorChangedCallback = callback; + } + const std::function& getCursorChangedCallback() const + { + return mCursorChangedCallback; + } protected: void onCursorChanged(const CursorState& state) override; diff --git a/es-core/src/components/DateTimeComponent.cpp b/es-core/src/components/DateTimeComponent.cpp index 8d1913fd3..c1e670fce 100644 --- a/es-core/src/components/DateTimeComponent.cpp +++ b/es-core/src/components/DateTimeComponent.cpp @@ -10,28 +10,28 @@ #include "components/DateTimeComponent.h" -#include "utils/StringUtil.h" #include "Log.h" #include "Settings.h" +#include "utils/StringUtil.h" DateTimeComponent::DateTimeComponent(Window* window) - : TextComponent(window), mDisplayRelative(false) + : TextComponent(window) + , mDisplayRelative(false) { // ISO 8601 date format. setFormat("%Y-%m-%d"); } -DateTimeComponent::DateTimeComponent( - Window* window, - const std::string& text, - const std::shared_ptr& font, - unsigned int color, - Alignment align, - Vector3f pos, - Vector2f size, - unsigned int bgcolor) - : TextComponent(window, text, font, color, align, pos, size, bgcolor), - mDisplayRelative(false) +DateTimeComponent::DateTimeComponent(Window* window, + const std::string& text, + const std::shared_ptr& font, + unsigned int color, + Alignment align, + Vector3f pos, + Vector2f size, + unsigned int bgcolor) + : TextComponent(window, text, font, color, align, pos, size, bgcolor) + , mDisplayRelative(false) { // ISO 8601 date format. setFormat("%Y-%m-%d"); @@ -45,6 +45,7 @@ void DateTimeComponent::setValue(const std::string& val) std::string DateTimeComponent::getValue() const { + // Return time value as a string. return mTime; } @@ -79,17 +80,17 @@ std::string DateTimeComponent::getDisplayString() const std::string buf; if (dur.getDays() > 0) - buf = std::to_string(dur.getDays()) + " day" + - (dur.getDays() > 1 ? "s" : "") + " ago"; + buf = std::to_string(dur.getDays()) + " day" + // Line break. + (dur.getDays() > 1 ? "s" : "") + " ago"; else if (dur.getHours() > 0) - buf = std::to_string(dur.getHours()) + " hour" + - (dur.getHours() > 1 ? "s" : "") + " ago"; + buf = std::to_string(dur.getHours()) + " hour" + // Line break. + (dur.getHours() > 1 ? "s" : "") + " ago"; else if (dur.getMinutes() > 0) - buf = std::to_string(dur.getMinutes()) + " minute" + - (dur.getMinutes() > 1 ? "s" : "") + " ago"; + buf = std::to_string(dur.getMinutes()) + " minute" + // Line break. + (dur.getMinutes() > 1 ? "s" : "") + " ago"; else - buf = std::to_string(dur.getSeconds()) + " second" + - (dur.getSeconds() > 1 || dur.getSeconds() == 0 ? "s" : "") + " ago"; + buf = std::to_string(dur.getSeconds()) + " second" + // Line break. + (dur.getSeconds() > 1 || dur.getSeconds() == 0 ? "s" : "") + " ago"; return std::string(buf); } @@ -106,7 +107,9 @@ void DateTimeComponent::render(const Transform4x4f& parentTrans) } void DateTimeComponent::applyTheme(const std::shared_ptr& theme, - const std::string& view, const std::string& element, unsigned int properties) + const std::string& view, + const std::string& element, + unsigned int properties) { GuiComponent::applyTheme(theme, view, element, properties); @@ -140,7 +143,7 @@ void DateTimeComponent::applyTheme(const std::shared_ptr& theme, else if (str == "right") setHorizontalAlignment(ALIGN_RIGHT); else - LOG(LogError) << "Unknown text alignment string: " << str; + LOG(LogError) << "Unknown text alignment string: " << str; } if (properties & FORCE_UPPERCASE && elem->has("forceUppercase")) diff --git a/es-core/src/components/DateTimeComponent.h b/es-core/src/components/DateTimeComponent.h index 8d48f97fd..444484851 100644 --- a/es-core/src/components/DateTimeComponent.h +++ b/es-core/src/components/DateTimeComponent.h @@ -11,8 +11,8 @@ #ifndef ES_CORE_COMPONENTS_DATE_TIME_COMPONENT_H #define ES_CORE_COMPONENTS_DATE_TIME_COMPONENT_H -#include "utils/TimeUtil.h" #include "TextComponent.h" +#include "utils/TimeUtil.h" class ThemeData; @@ -21,15 +21,14 @@ class DateTimeComponent : public TextComponent { public: DateTimeComponent(Window* window); - DateTimeComponent( - Window* window, - const std::string& text, - const std::shared_ptr& font, - unsigned int color = 0x000000FF, - Alignment align = ALIGN_LEFT, - Vector3f pos = Vector3f::Zero(), - Vector2f size = Vector2f::Zero(), - unsigned int bgcolor = 0x00000000); + DateTimeComponent(Window* window, + const std::string& text, + const std::shared_ptr& font, + unsigned int color = 0x000000FF, + Alignment align = ALIGN_LEFT, + Vector3f pos = Vector3f::Zero(), + Vector2f size = Vector2f::Zero(), + unsigned int bgcolor = 0x00000000); void render(const Transform4x4f& parentTrans) override; @@ -39,8 +38,10 @@ public: void setFormat(const std::string& format); void setDisplayRelative(bool displayRelative); - virtual void applyTheme(const std::shared_ptr& theme, const std::string& view, - const std::string& element, unsigned int properties) override; + virtual void applyTheme(const std::shared_ptr& theme, + const std::string& view, + const std::string& element, + unsigned int properties) override; protected: void onTextChanged() override; diff --git a/es-core/src/components/DateTimeEditComponent.cpp b/es-core/src/components/DateTimeEditComponent.cpp index 119d256ee..ef91ed5f4 100644 --- a/es-core/src/components/DateTimeEditComponent.cpp +++ b/es-core/src/components/DateTimeEditComponent.cpp @@ -8,24 +8,21 @@ #include "components/DateTimeEditComponent.h" +#include "Settings.h" #include "resources/Font.h" #include "utils/StringUtil.h" -#include "Settings.h" -DateTimeEditComponent::DateTimeEditComponent( - Window* window, - bool alignRight, - DisplayMode dispMode) - : GuiComponent(window), - mEditing(false), - mEditIndex(0), - mDisplayMode(dispMode), - mRelativeUpdateAccumulator(0), - mColor(0x777777FF), - mFont(Font::get(FONT_SIZE_SMALL, FONT_PATH_LIGHT)), - mUppercase(false), - mAutoSize(true), - mAlignRight(alignRight) +DateTimeEditComponent::DateTimeEditComponent(Window* window, bool alignRight, DisplayMode dispMode) + : GuiComponent(window) + , mEditing(false) + , mEditIndex(0) + , mDisplayMode(dispMode) + , mRelativeUpdateAccumulator(0) + , mColor(0x777777FF) + , mFont(Font::get(FONT_SIZE_SMALL, FONT_PATH_LIGHT)) + , mUppercase(false) + , mAutoSize(true) + , mAlignRight(alignRight) { updateTextCache(); } @@ -68,8 +65,9 @@ bool DateTimeEditComponent::input(InputConfig* config, Input input) if (mEditing) { if (config->isMappedLike("lefttrigger", input) || - config->isMappedLike("righttrigger", input)) + config->isMappedLike("righttrigger", input)) { return true; + } if (config->isMappedTo("b", input)) { mEditing = false; @@ -101,23 +99,21 @@ bool DateTimeEditComponent::input(InputConfig* config, Input input) new_tm.tm_mon = 0; else if (new_tm.tm_mon < 0) new_tm.tm_mon = 11; - } else if (mEditIndex == 2) { const int days_in_month = - Utils::Time::daysInMonth(new_tm.tm_year + 1900, new_tm.tm_mon + 1); + Utils::Time::daysInMonth(new_tm.tm_year + 1900, new_tm.tm_mon + 1); new_tm.tm_mday += incDir; if (new_tm.tm_mday > days_in_month) new_tm.tm_mday = 1; else if (new_tm.tm_mday < 1) new_tm.tm_mday = days_in_month; - } // Validate day. const int days_in_month = - Utils::Time::daysInMonth(new_tm.tm_year + 1900, new_tm.tm_mon + 1); + Utils::Time::daysInMonth(new_tm.tm_year + 1900, new_tm.tm_mon + 1); if (new_tm.tm_mday > days_in_month) new_tm.tm_mday = days_in_month; @@ -185,11 +181,11 @@ void DateTimeEditComponent::render(const Transform4x4f& parentTrans) if (Settings::getInstance()->getBool("DebugText")) { Renderer::setMatrix(trans); if (mTextCache->metrics.size.x() > 0) { - Renderer::drawRect(0.0f, 0.0f - off.y(), - mSize.x() - off.x(), mSize.y(), 0x0000FF33, 0x0000FF33); + Renderer::drawRect(0.0f, 0.0f - off.y(), mSize.x() - off.x(), mSize.y(), 0x0000FF33, + 0x0000FF33); } Renderer::drawRect(0.0f, 0.0f, mTextCache->metrics.size.x(), - mTextCache->metrics.size.y(), 0x00000033, 0x00000033); + mTextCache->metrics.size.y(), 0x00000033, 0x00000033); } mTextCache->setColor((mColor & 0xFFFFFF00) | getOpacity()); @@ -198,8 +194,8 @@ void DateTimeEditComponent::render(const Transform4x4f& parentTrans) if (mEditing) { if (mEditIndex >= 0 && static_cast(mEditIndex) < mCursorBoxes.size()) Renderer::drawRect(mCursorBoxes[mEditIndex][0], mCursorBoxes[mEditIndex][1], - mCursorBoxes[mEditIndex][2], mCursorBoxes[mEditIndex][3], - 0x00000022, 0x00000022); + mCursorBoxes[mEditIndex][2], mCursorBoxes[mEditIndex][3], + 0x00000022, 0x00000022); } } } @@ -211,41 +207,24 @@ void DateTimeEditComponent::setValue(const std::string& val) updateTextCache(); } -std::string DateTimeEditComponent::getValue() const -{ - return mTime; -} - -DateTimeEditComponent::DisplayMode DateTimeEditComponent::getCurrentDisplayMode() const -{ -// if (mEditing) { -// if (mDisplayMode == DISP_RELATIVE_TO_NOW) { -// // TODO: if time component == 00:00:00, return DISP_DATE, else return DISP_DATE_TIME. -// return DISP_DATE; -// } -// } - - return mDisplayMode; -} - std::string DateTimeEditComponent::getDisplayString(DisplayMode mode) const { // ISO 8601 date format. std::string fmt; switch (mode) { - case DISP_DATE: { - if (mTime.getTime() == 0) - return "unknown"; - fmt = "%Y-%m-%d"; - break; - } - case DISP_DATE_TIME: { - if (mTime.getTime() == 0) - return "unknown"; - fmt = "%Y-%m-%d %H:%M:%S"; - break; - } - case DISP_RELATIVE_TO_NOW: { + case DISP_DATE: { + if (mTime.getTime() == 0) + return "unknown"; + fmt = "%Y-%m-%d"; + break; + } + case DISP_DATE_TIME: { + if (mTime.getTime() == 0) + return "unknown"; + fmt = "%Y-%m-%d %H:%M:%S"; + break; + } + case DISP_RELATIVE_TO_NOW: { // Relative time. if (mTime.getTime() == 0) return "never"; @@ -256,21 +235,22 @@ std::string DateTimeEditComponent::getDisplayString(DisplayMode mode) const std::string buf; if (dur.getDays() > 0) - buf = std::to_string(dur.getDays()) + " day" + - (dur.getDays() > 1 ? "s" : "") + " ago"; + buf = std::to_string(dur.getDays()) + // Line break. + " day" + (dur.getDays() > 1 ? "s" : "") + " ago"; else if (dur.getHours() > 0) - buf = std::to_string(dur.getHours()) + " hour" + - (dur.getHours() > 1 ? "s" : "") + " ago"; + buf = std::to_string(dur.getHours()) + // Line break. + " hour" + (dur.getHours() > 1 ? "s" : "") + " ago"; else if (dur.getMinutes() > 0) - buf = std::to_string(dur.getMinutes()) + " minute" + - (dur.getMinutes() > 1 ? "s" : "") + " ago"; + buf = std::to_string(dur.getMinutes()) + // Line break. + " minute" + (dur.getMinutes() > 1 ? "s" : "") + " ago"; else - buf = std::to_string(dur.getSeconds()) + " second" + - (dur.getSeconds() > 1 || dur.getSeconds() == 0 ? "s" : "") + " ago"; + buf = std::to_string(dur.getSeconds()) + // Line break. + " second" + (dur.getSeconds() > 1 || dur.getSeconds() == 0 ? "s" : "") + + " ago"; return std::string(buf); + break; } - break; } return Utils::Time::timeToString(mTime, fmt); @@ -296,16 +276,16 @@ void DateTimeEditComponent::updateTextCache() dispString = ""; } else { - dispString = mUppercase ? Utils::String::toUpper(getDisplayString(mode)) : - getDisplayString(mode); + dispString = + mUppercase ? Utils::String::toUpper(getDisplayString(mode)) : getDisplayString(mode); } std::shared_ptr font = getFont(); mTextCache = std::unique_ptr(font->buildTextCache(dispString, 0, 0, mColor)); if (mAutoSize) { mSize = mTextCache->metrics.size; - mAutoSize = false; + if (getParent()) getParent()->onSizeChanged(); } @@ -367,7 +347,9 @@ void DateTimeEditComponent::setUppercase(bool uppercase) } void DateTimeEditComponent::applyTheme(const std::shared_ptr& theme, - const std::string& view, const std::string& element, unsigned int properties) + const std::string& view, + const std::string& element, + unsigned int properties) { const ThemeData::ThemeElement* elem = theme->getElement(view, element, "datetime"); diff --git a/es-core/src/components/DateTimeEditComponent.h b/es-core/src/components/DateTimeEditComponent.h index cc79053b7..3273fe51b 100644 --- a/es-core/src/components/DateTimeEditComponent.h +++ b/es-core/src/components/DateTimeEditComponent.h @@ -9,8 +9,8 @@ #ifndef ES_CORE_COMPONENTS_DATE_TIME_EDIT_COMPONENT_H #define ES_CORE_COMPONENTS_DATE_TIME_EDIT_COMPONENT_H -#include "utils/TimeUtil.h" #include "GuiComponent.h" +#include "utils/TimeUtil.h" class TextCache; @@ -18,21 +18,22 @@ class TextCache; class DateTimeEditComponent : public GuiComponent { public: - enum DisplayMode{ - DISP_DATE, + enum DisplayMode { + DISP_DATE, // Replace with AllowShortEnumsOnASingleLine: false (clang-format >=11.0). DISP_DATE_TIME, DISP_RELATIVE_TO_NOW }; - DateTimeEditComponent(Window* window, bool alignRight = false, - DisplayMode dispMode = DISP_DATE); + DateTimeEditComponent(Window* window, + bool alignRight = false, + DisplayMode dispMode = DISP_DATE); void setValue(const std::string& val) override; - std::string getValue() const override; + std::string getValue() const override { return mTime; } bool input(InputConfig* config, Input input) override; void update(int deltaTime) override; - unsigned int getColor() const override { return mColor; }; + unsigned int getColor() const override { return mColor; } void render(const Transform4x4f& parentTrans) override; void onSizeChanged() override; @@ -45,19 +46,21 @@ public: // The initial value is DISP_DATE. void setDisplayMode(DisplayMode mode); - // Text color. + // Text color. void setColor(unsigned int color) override; // Font to use. Default is Font::get(FONT_SIZE_MEDIUM). - void setOriginalColor(unsigned int color) override { mColorOriginalValue = color; }; - void setChangedColor(unsigned int color) override { mColorChangedValue = color; }; + void setOriginalColor(unsigned int color) override { mColorOriginalValue = color; } + void setChangedColor(unsigned int color) override { mColorChangedValue = color; } void setFont(std::shared_ptr font); // Force text to be uppercase when in DISP_RELATIVE_TO_NOW mode. void setUppercase(bool uppercase); - virtual void applyTheme(const std::shared_ptr& theme, const std::string& view, - const std::string& element, unsigned int properties) override; + virtual void applyTheme(const std::shared_ptr& theme, + const std::string& view, + const std::string& element, + unsigned int properties) override; virtual std::vector getHelpPrompts() override; @@ -65,7 +68,7 @@ private: std::shared_ptr getFont() const override; std::string getDisplayString(DisplayMode mode) const; - DisplayMode getCurrentDisplayMode() const; + DisplayMode getCurrentDisplayMode() const { return mDisplayMode; } void updateTextCache(); diff --git a/es-core/src/components/GridTileComponent.cpp b/es-core/src/components/GridTileComponent.cpp index 4fa6a829a..af5a87136 100644 --- a/es-core/src/components/GridTileComponent.cpp +++ b/es-core/src/components/GridTileComponent.cpp @@ -8,16 +8,17 @@ #include "GridTileComponent.h" +#include "ThemeData.h" #include "animations/LambdaAnimation.h" #include "resources/TextureResource.h" -#include "ThemeData.h" -GridTileComponent::GridTileComponent(Window* window) : - GuiComponent(window), mBackground(window, ":/graphics/frame.png") +GridTileComponent::GridTileComponent(Window* window) + : GuiComponent(window) + , mBackground(window, ":/graphics/frame.png") { mDefaultProperties.mSize = getDefaultTileSize(); mDefaultProperties.mPadding = Vector2f(16.0f * Renderer::getScreenWidthModifier(), - 16.0f * Renderer::getScreenHeightModifier()); + 16.0f * Renderer::getScreenHeightModifier()); mDefaultProperties.mImageColor = 0xAAAAAABB; // Attempting to use frame.svg instead causes quite severe performance problems. mDefaultProperties.mBackgroundImage = ":/graphics/frame.png"; @@ -76,7 +77,7 @@ void GridTileComponent::update(int deltaTime) void applyThemeToProperties(const ThemeData::ThemeElement* elem, GridTileProperties* properties) { Vector2f screen = Vector2f(static_cast(Renderer::getScreenWidth()), - static_cast(Renderer::getScreenHeight())); + static_cast(Renderer::getScreenHeight())); if (elem->has("size")) properties->mSize = elem->get("size") * screen; @@ -106,10 +107,12 @@ void applyThemeToProperties(const ThemeData::ThemeElement* elem, GridTilePropert } void GridTileComponent::applyTheme(const std::shared_ptr& theme, - const std::string& view, const std::string& /*element*/, unsigned int /*properties*/) + const std::string& view, + const std::string& /*element*/, + unsigned int /*properties*/) { Vector2f screen = Vector2f(static_cast(Renderer::getScreenWidth()), - static_cast(Renderer::getScreenHeight())); + static_cast(Renderer::getScreenHeight())); // Apply theme to the default gridtile. const ThemeData::ThemeElement* elem = theme->getElement(view, "default", "gridtile"); @@ -133,26 +136,23 @@ void GridTileComponent::applyTheme(const std::shared_ptr& theme, Vector2f GridTileComponent::getDefaultTileSize() { Vector2f screen = Vector2f(static_cast(Renderer::getScreenWidth()), - static_cast(Renderer::getScreenHeight())); + static_cast(Renderer::getScreenHeight())); return screen * 0.22f; } Vector2f GridTileComponent::getSelectedTileSize() const { + // Return the tile size. return mDefaultProperties.mSize * 1.2f; } bool GridTileComponent::isSelected() const { + // Return whether the tile is selected. return mSelected; } -void GridTileComponent::reset() -{ - setImage(""); -} - void GridTileComponent::setImage(const std::string& path) { mImage->setImage(path); @@ -169,8 +169,10 @@ void GridTileComponent::setImage(const std::shared_ptr& texture resize(); } -void GridTileComponent::setSelected( - bool selected, bool allowAnimation, Vector3f* pPosition, bool force) +void GridTileComponent::setSelected(bool selected, + bool allowAnimation, + Vector3f* pPosition, + bool force) { if (mSelected == selected && !force) return; @@ -191,15 +193,18 @@ void GridTileComponent::setSelected( auto func = [this](float t) { t -= 1; // Cubic ease out. - float pct = Math::lerp(0, 1, t*t*t + 1); + float pct = Math::lerp(0, 1, t * t * t + 1); this->setSelectedZoom(pct); }; cancelAnimation(3); - setAnimation(new LambdaAnimation(func, 250), 0, [this] { - this->setSelectedZoom(1); - mAnimPosition = Vector3f(0, 0, 0); - }, false, 3); + setAnimation( + new LambdaAnimation(func, 250), 0, + [this] { + this->setSelectedZoom(1); + mAnimPosition = Vector3f(0, 0, 0); + }, + false, 3); } } else { @@ -213,15 +218,14 @@ void GridTileComponent::setSelected( this->setSelectedZoom(1); auto func = [this](float t) { - t -= 1; // Cubic ease out. - float pct = Math::lerp(0, 1, t*t*t + 1); + t -= 1.0f; // Cubic ease out. + float pct = Math::lerp(0, 1, t * t * t + 1.0f); this->setSelectedZoom(1.0f - pct); }; cancelAnimation(3); - setAnimation(new LambdaAnimation(func, 250), 0, [this] { - this->setSelectedZoom(0); - }, false, 3); + setAnimation( + new LambdaAnimation(func, 250), 0, [this] { this->setSelectedZoom(0); }, false, 3); } } } @@ -235,10 +239,7 @@ void GridTileComponent::setSelectedZoom(float percent) resize(); } -void GridTileComponent::setVisible(bool visible) -{ - mVisible = visible; -} +void GridTileComponent::setVisible(bool visible) { mVisible = visible; } void GridTileComponent::resize() { @@ -278,30 +279,31 @@ void GridTileComponent::calcCurrentProperties() if (mSelectedZoomPercent != 0.0f && mSelectedZoomPercent != 1.0f) { if (mDefaultProperties.mSize != mSelectedProperties.mSize) mCurrentProperties.mSize = mDefaultProperties.mSize * zoomPercentInverse + - mSelectedProperties.mSize * mSelectedZoomPercent; + mSelectedProperties.mSize * mSelectedZoomPercent; if (mDefaultProperties.mPadding != mSelectedProperties.mPadding) mCurrentProperties.mPadding = mDefaultProperties.mPadding * zoomPercentInverse + - mSelectedProperties.mPadding * mSelectedZoomPercent; + mSelectedProperties.mPadding * mSelectedZoomPercent; if (mDefaultProperties.mImageColor != mSelectedProperties.mImageColor) - mCurrentProperties.mImageColor = mixColors(mDefaultProperties.mImageColor, - mSelectedProperties.mImageColor, mSelectedZoomPercent); + mCurrentProperties.mImageColor = + mixColors(mDefaultProperties.mImageColor, mSelectedProperties.mImageColor, + mSelectedZoomPercent); if (mDefaultProperties.mBackgroundCornerSize != mSelectedProperties.mBackgroundCornerSize) - mCurrentProperties.mBackgroundCornerSize = mDefaultProperties.mBackgroundCornerSize * - zoomPercentInverse + mSelectedProperties.mBackgroundCornerSize * - mSelectedZoomPercent; + mCurrentProperties.mBackgroundCornerSize = + mDefaultProperties.mBackgroundCornerSize * zoomPercentInverse + + mSelectedProperties.mBackgroundCornerSize * mSelectedZoomPercent; if (mDefaultProperties.mBackgroundCenterColor != mSelectedProperties.mBackgroundCenterColor) mCurrentProperties.mBackgroundCenterColor = - mixColors(mDefaultProperties.mBackgroundCenterColor, - mSelectedProperties.mBackgroundCenterColor, mSelectedZoomPercent); + mixColors(mDefaultProperties.mBackgroundCenterColor, + mSelectedProperties.mBackgroundCenterColor, mSelectedZoomPercent); if (mDefaultProperties.mBackgroundEdgeColor != mSelectedProperties.mBackgroundEdgeColor) mCurrentProperties.mBackgroundEdgeColor = - mixColors(mDefaultProperties.mBackgroundEdgeColor, - mSelectedProperties.mBackgroundEdgeColor, mSelectedZoomPercent); + mixColors(mDefaultProperties.mBackgroundEdgeColor, + mSelectedProperties.mBackgroundEdgeColor, mSelectedZoomPercent); } } diff --git a/es-core/src/components/GridTileComponent.h b/es-core/src/components/GridTileComponent.h index 2936645d5..6c0d600ee 100644 --- a/es-core/src/components/GridTileComponent.h +++ b/es-core/src/components/GridTileComponent.h @@ -28,8 +28,10 @@ public: GridTileComponent(Window* window); void render(const Transform4x4f& parentTrans) override; - virtual void applyTheme(const std::shared_ptr& theme, const std::string& view, - const std::string& element, unsigned int properties) override; + virtual void applyTheme(const std::shared_ptr& theme, + const std::string& view, + const std::string& element, + unsigned int properties) override; // Made this a static function because the ImageGridComponent needs to know the default tile // max size to calculate the grid dimension before it instantiates the GridTileComponents. @@ -37,12 +39,14 @@ public: Vector2f getSelectedTileSize() const; bool isSelected() const; - void reset(); + void reset() { setImage(""); } void setImage(const std::string& path); void setImage(const std::shared_ptr& texture); - void setSelected(bool selected, bool allowAnimation = true, - Vector3f* pPosition = nullptr, bool force=false); + void setSelected(bool selected, + bool allowAnimation = true, + Vector3f* pPosition = nullptr, + bool force = false); void setVisible(bool visible); void forceSize(Vector2f size, float selectedZoom); diff --git a/es-core/src/components/HelpComponent.cpp b/es-core/src/components/HelpComponent.cpp index b784e7326..dd2c526a3 100644 --- a/es-core/src/components/HelpComponent.cpp +++ b/es-core/src/components/HelpComponent.cpp @@ -8,20 +8,21 @@ #include "components/HelpComponent.h" +#include "Log.h" +#include "Settings.h" #include "components/ComponentGrid.h" #include "components/ImageComponent.h" #include "components/TextComponent.h" #include "resources/TextureResource.h" #include "utils/StringUtil.h" -#include "Log.h" -#include "Settings.h" #define ICON_TEXT_SPACING 8 // Space between [icon] and [text] (px). #define ENTRY_SPACING 16 // Space between [text] and next [icon] (px). static std::map sIconPathMap {}; -HelpComponent::HelpComponent(Window* window) : GuiComponent(window) +HelpComponent::HelpComponent(Window* window) + : GuiComponent(window) { assignIcons(); } @@ -113,7 +114,7 @@ void HelpComponent::updateGrid() std::shared_ptr& font = mStyle.font; mGrid = std::make_shared(mWindow, - Vector2i(static_cast(mPrompts.size()) * 4, 1)); + Vector2i(static_cast(mPrompts.size()) * 4, 1)); // [icon] [spacer1] [text] [spacer2] @@ -130,12 +131,12 @@ void HelpComponent::updateGrid() icon->setResize(0, height); icons.push_back(icon); - auto lbl = std::make_shared(mWindow, - Utils::String::toUpper(it->second), font, mStyle.textColor); + auto lbl = std::make_shared(mWindow, Utils::String::toUpper(it->second), + font, mStyle.textColor); labels.push_back(lbl); width += icon->getSize().x() + lbl->getSize().x() + - ((ICON_TEXT_SPACING + ENTRY_SPACING) * Renderer::getScreenWidthModifier()); + ((ICON_TEXT_SPACING + ENTRY_SPACING) * Renderer::getScreenWidthModifier()); } mGrid->setSize(width, height); @@ -143,8 +144,8 @@ void HelpComponent::updateGrid() for (unsigned int i = 0; i < icons.size(); i++) { const int col = i * 4; mGrid->setColWidthPerc(col, icons.at(i)->getSize().x() / width); - mGrid->setColWidthPerc(col + 1, (ICON_TEXT_SPACING * - Renderer::getScreenWidthModifier()) / width); + mGrid->setColWidthPerc(col + 1, + (ICON_TEXT_SPACING * Renderer::getScreenWidthModifier()) / width); mGrid->setColWidthPerc(col + 2, labels.at(i)->getSize().x() / width); mGrid->setEntry(icons.at(i), Vector2i(col, 0), false, false); @@ -167,13 +168,13 @@ std::shared_ptr HelpComponent::getIconTexture(const char* name) return nullptr; } if (!ResourceManager::getInstance()->fileExists(pathLookup->second)) { - LOG(LogError) << "Couldn't load help icon \"" << name << - "\" as the file \"" << pathLookup->second << "\" is missing"; + LOG(LogError) << "Couldn't load help icon \"" << name << "\" as the file \"" + << pathLookup->second << "\" is missing"; return nullptr; } std::shared_ptr tex = - TextureResource::get(pathLookup->second, false, false, false); + TextureResource::get(pathLookup->second, false, false, false); mIconCache[std::string(name)] = tex; return tex; } diff --git a/es-core/src/components/IList.h b/es-core/src/components/IList.h index fc37bbb63..1c907a1b3 100644 --- a/es-core/src/components/IList.h +++ b/es-core/src/components/IList.h @@ -9,17 +9,17 @@ #ifndef ES_CORE_COMPONENTS_ILIST_H #define ES_CORE_COMPONENTS_ILIST_H +#include "Window.h" #include "components/ImageComponent.h" #include "utils/StringUtil.h" -#include "Window.h" enum CursorState { - CURSOR_STOPPED, + CURSOR_STOPPED, // Replace with AllowShortEnumsOnASingleLine: false (clang-format >=11.0). CURSOR_SCROLLING }; enum ListLoopType { - LIST_ALWAYS_LOOP, + LIST_ALWAYS_LOOP, // Replace with AllowShortEnumsOnASingleLine: false (clang-format >=11.0). LIST_PAUSE_AT_END, LIST_NEVER_LOOP }; @@ -35,10 +35,11 @@ struct ScrollTierList { }; // Default scroll tiers. +// clang-format off const ScrollTier QUICK_SCROLL_TIERS[] = { - {500, 500}, - {1200, 114}, - {0, 16} + { 500, 500 }, + { 1200, 114 }, + { 0, 16 } }; const ScrollTierList LIST_SCROLL_STYLE_QUICK = { 3, @@ -46,17 +47,17 @@ const ScrollTierList LIST_SCROLL_STYLE_QUICK = { }; const ScrollTier SLOW_SCROLL_TIERS[] = { - {500, 500}, - {0, 200} + { 500, 500 }, + { 0, 200 } }; const ScrollTierList LIST_SCROLL_STYLE_SLOW = { 2, SLOW_SCROLL_TIERS }; +// clang-format on -template -class IList : public GuiComponent +template class IList : public GuiComponent { public: struct Entry { @@ -82,14 +83,13 @@ protected: Window* mWindow; public: - IList( - Window* window, - const ScrollTierList& tierList = LIST_SCROLL_STYLE_QUICK, - const ListLoopType& loopType = LIST_PAUSE_AT_END) - : GuiComponent(window), - mTierList(tierList), - mLoopType(loopType), - mWindow(window) + IList(Window* window, + const ScrollTierList& tierList = LIST_SCROLL_STYLE_QUICK, + const ListLoopType& loopType = LIST_PAUSE_AT_END) + : GuiComponent(window) + , mTierList(tierList) + , mLoopType(loopType) + , mWindow(window) { mCursor = 0; mScrollTier = 0; @@ -101,15 +101,9 @@ public: mTitleOverlayColor = 0xFFFFFF00; } - bool isScrolling() const - { - return (mScrollVelocity != 0 && mScrollTier > 0); - } + bool isScrolling() const { return (mScrollVelocity != 0 && mScrollTier > 0); } - int getScrollingVelocity() - { - return mScrollVelocity; - } + int getScrollingVelocity() { return mScrollVelocity; } void stopScrolling() { @@ -128,43 +122,43 @@ public: onCursorChanged(CURSOR_STOPPED); } - inline const std::string& getSelectedName() + const std::string& getSelectedName() { assert(size() > 0); return mEntries.at(mCursor).name; } - inline const UserData& getSelected() const + const UserData& getSelected() const { assert(size() > 0); return mEntries.at(mCursor).object; } - inline const UserData& getNext() const + const UserData& getNext() const { // If there is a next entry, then return it, otherwise return the current entry. if (mCursor + 1 < mEntries.size()) - return mEntries.at(mCursor+1).object; + return mEntries.at(mCursor + 1).object; else return mEntries.at(mCursor).object; } - inline const UserData& getPrevious() const + const UserData& getPrevious() const { // If there is a previous entry, then return it, otherwise return the current entry. if (mCursor != 0) - return mEntries.at(mCursor-1).object; + return mEntries.at(mCursor - 1).object; else return mEntries.at(mCursor).object; } - inline const UserData& getFirst() const + const UserData& getFirst() const { assert(size() > 0); return mEntries.front().object; } - inline const UserData& getLast() const + const UserData& getLast() const { assert(size() > 0); return mEntries.back().object; @@ -192,10 +186,7 @@ public: } // Entry management. - void add(const Entry& e) - { - mEntries.push_back(e); - } + void add(const Entry& e) { mEntries.push_back(e); } bool remove(const UserData& obj) { @@ -209,10 +200,7 @@ public: return false; } - inline int size() const - { - return static_cast(mEntries.size()); - } + int size() const { return static_cast(mEntries.size()); } protected: void remove(typename std::vector::const_iterator& it) @@ -241,7 +229,6 @@ protected: return true; } - bool listInput(int velocity) // A velocity of 0 = stop scrolling. { mScrollVelocity = velocity; @@ -284,8 +271,8 @@ protected: } // Should we go to the next scrolling tier? - while (mScrollTier < mTierList.count - 1 && mScrollTierAccumulator >= - mTierList.tiers[mScrollTier].length) { + while (mScrollTier < mTierList.count - 1 && + mScrollTierAccumulator >= mTierList.tiers[mScrollTier].length) { mScrollTierAccumulator -= mTierList.tiers[mScrollTier].length; mScrollTier++; } @@ -314,11 +301,11 @@ protected: favoritesSorting = Settings::getInstance()->getBool("FavoritesFirst"); if (favoritesSorting && getSelected()->getFavorite()) { - #if defined(_MSC_VER) // MSVC compiler. +#if defined(_MSC_VER) // MSVC compiler. titleIndex = Utils::String::wideStringToString(L"\uF005"); - #else +#else titleIndex = "\uF005"; - #endif +#endif } else { titleIndex = getSelected()->getName(); diff --git a/es-core/src/components/ImageComponent.cpp b/es-core/src/components/ImageComponent.cpp index b53059b27..253d155b5 100644 --- a/es-core/src/components/ImageComponent.cpp +++ b/es-core/src/components/ImageComponent.cpp @@ -8,11 +8,11 @@ #include "components/ImageComponent.h" -#include "resources/TextureResource.h" -#include "utils/CImgUtil.h" #include "Log.h" #include "Settings.h" #include "ThemeData.h" +#include "resources/TextureResource.h" +#include "utils/CImgUtil.h" Vector2i ImageComponent::getTextureSize() const { @@ -27,34 +27,27 @@ Vector2f ImageComponent::getSize() const return GuiComponent::getSize() * (mBottomRightCrop - mTopLeftCrop); } -ImageComponent::ImageComponent( - Window* window, - bool forceLoad, - bool dynamic) - : GuiComponent(window), - mTargetIsMax(false), - mTargetIsMin(false), - mFlipX(false), - mFlipY(false), - mTargetSize(0, 0), - mColorShift(0xFFFFFFFF), - mColorShiftEnd(0xFFFFFFFF), - mColorGradientHorizontal(true), - mForceLoad(forceLoad), - mDynamic(dynamic), - mFadeOpacity(0), - mFading(false), - mRotateByTargetSize(false), - mTopLeftCrop(0.0f, 0.0f), - mBottomRightCrop(1.0f, 1.0f) +ImageComponent::ImageComponent(Window* window, bool forceLoad, bool dynamic) + : GuiComponent(window) + , mTargetIsMax(false) + , mTargetIsMin(false) + , mFlipX(false) + , mFlipY(false) + , mTargetSize(0, 0) + , mColorShift(0xFFFFFFFF) + , mColorShiftEnd(0xFFFFFFFF) + , mColorGradientHorizontal(true) + , mForceLoad(forceLoad) + , mDynamic(dynamic) + , mFadeOpacity(0) + , mFading(false) + , mRotateByTargetSize(false) + , mTopLeftCrop(0.0f, 0.0f) + , mBottomRightCrop(1.0f, 1.0f) { updateColors(); } -ImageComponent::~ImageComponent() -{ -} - void ImageComponent::resize() { if (!mTexture) @@ -91,8 +84,8 @@ void ImageComponent::resize() mSize[1] = floorf(mSize[1] * resizeScale.y()); // For SVG rasterization, always calculate width from rounded height (see comment // above). We need to make sure we're not creating an image larger than max size. - mSize[0] = std::min((mSize[1] / textureSize.y()) * textureSize.x(), - mTargetSize.x()); + mSize[0] = + std::min((mSize[1] / textureSize.y()) * textureSize.x(), mTargetSize.x()); } } else if (mTargetIsMin) { @@ -118,7 +111,6 @@ void ImageComponent::resize() // above). We need to make sure we're not creating an image smaller than min size. mSize[1] = std::max(floorf(mSize[1]), mTargetSize.y()); mSize[0] = std::max((mSize[1] / textureSize.y()) * textureSize.x(), mTargetSize.x()); - } else { // If both components are set, we just stretch. @@ -147,16 +139,6 @@ void ImageComponent::resize() onSizeChanged(); } -void ImageComponent::onSizeChanged() -{ - updateVertices(); -} - -void ImageComponent::setDefaultImage(std::string path) -{ - mDefaultPath = path; -} - void ImageComponent::setImage(std::string path, bool tile) { // Always load bundled graphic resources statically, unless mForceLoad has been set. @@ -218,16 +200,6 @@ void ImageComponent::setMinSize(float width, float height) resize(); } -Vector2f ImageComponent::getRotationSize() const -{ - return mRotateByTargetSize ? mTargetSize : mSize; -} - -void ImageComponent::setRotateByTargetSize(bool rotate) -{ - mRotateByTargetSize = rotate; -} - void ImageComponent::cropLeft(float percent) { assert(percent >= 0.0f && percent <= 1.0f); @@ -262,6 +234,7 @@ void ImageComponent::crop(float left, float top, float right, float bot) void ImageComponent::uncrop() { + // Remove any applied crop. crop(0, 0, 0, 0); } @@ -375,10 +348,12 @@ void ImageComponent::updateVertices() const float px = mTexture->isTiled() ? mSize.x() / getTextureSize().x() : 1.0f; const float py = mTexture->isTiled() ? mSize.y() / getTextureSize().y() : 1.0f; + // clang-format off mVertices[0] = { { topLeft.x(), topLeft.y() }, { mTopLeftCrop.x(), py - mTopLeftCrop.y() }, 0 }; mVertices[1] = { { topLeft.x(), bottomRight.y() }, { mTopLeftCrop.x(), 1.0f - mBottomRightCrop.y() }, 0 }; mVertices[2] = { { bottomRight.x(), topLeft.y() }, { mBottomRightCrop.x() * px, py - mTopLeftCrop.y() }, 0 }; mVertices[3] = { { bottomRight.x(), bottomRight.y() }, { mBottomRightCrop.x() * px, 1.0f - mBottomRightCrop.y() }, 0 }; + // clang-format on updateColors(); @@ -400,10 +375,11 @@ void ImageComponent::updateVertices() void ImageComponent::updateColors() { const float opacity = (mOpacity * (mFading ? mFadeOpacity / 255.0f : 1.0f)) / 255.0f; - const unsigned int color = Renderer::convertRGBAToABGR((mColorShift & 0xFFFFFF00) | - static_cast((mColorShift & 0xFF) * opacity)); - const unsigned int colorEnd = Renderer::convertRGBAToABGR((mColorShiftEnd & 0xFFFFFF00) | - static_cast((mColorShiftEnd & 0xFF) * opacity)); + const unsigned int color = Renderer::convertRGBAToABGR( + (mColorShift & 0xFFFFFF00) | static_cast((mColorShift & 0xFF) * opacity)); + const unsigned int colorEnd = + Renderer::convertRGBAToABGR((mColorShiftEnd & 0xFFFFFF00) | + static_cast((mColorShiftEnd & 0xFF) * opacity)); mVertices[0].col = color; mVertices[1].col = mColorGradientHorizontal ? colorEnd : color; @@ -423,7 +399,7 @@ void ImageComponent::render(const Transform4x4f& parentTrans) if (Settings::getInstance()->getBool("DebugImage")) { Vector2f targetSizePos = (mTargetSize - mSize) * mOrigin * -1; Renderer::drawRect(targetSizePos.x(), targetSizePos.y(), mTargetSize.x(), - mTargetSize.y(), 0xFF000033, 0xFF000033); + mTargetSize.y(), 0xFF000033, 0xFF000033); Renderer::drawRect(0.0f, 0.0f, mSize.x(), mSize.y(), 0xFF000033, 0xFF000033); } // An image with zero size would normally indicate a corrupt image file. @@ -433,12 +409,12 @@ void ImageComponent::render(const Transform4x4f& parentTrans) // texture is bound in this case but we want to handle a fade so it doesn't just // 'jump' in when it finally loads. fadeIn(mTexture->bind()); - #if defined(USE_OPENGL_21) +#if defined(USE_OPENGL_21) if (mSaturation < 1.0) { mVertices[0].shaders = Renderer::SHADER_DESATURATE; mVertices[0].saturation = mSaturation; } - #endif +#endif Renderer::drawTriangleStrips(&mVertices[0], 4, trans); } else { @@ -448,8 +424,8 @@ void ImageComponent::render(const Transform4x4f& parentTrans) else { std::string textureFilePath = mTexture->getTextureFilePath(); if (textureFilePath != "") { - LOG(LogError) << "Image texture for file \"" << textureFilePath << - "\" has zero size"; + LOG(LogError) << "Image texture for file \"" << textureFilePath + << "\" has zero size"; } else { LOG(LogError) << "Image texture has zero size"; @@ -492,26 +468,24 @@ void ImageComponent::fadeIn(bool textureLoaded) } } -bool ImageComponent::hasImage() -{ - return (bool)mTexture; -} - -void ImageComponent::applyTheme(const std::shared_ptr& theme, const std::string& view, - const std::string& element, unsigned int properties) +void ImageComponent::applyTheme(const std::shared_ptr& theme, + const std::string& view, + const std::string& element, + unsigned int properties) { using namespace ThemeFlags; - GuiComponent::applyTheme(theme, view, element, (properties ^ ThemeFlags::SIZE) | - ((properties & (ThemeFlags::SIZE | POSITION)) ? ORIGIN : 0)); + GuiComponent::applyTheme(theme, view, element, + (properties ^ ThemeFlags::SIZE) | + ((properties & (ThemeFlags::SIZE | POSITION)) ? ORIGIN : 0)); const ThemeData::ThemeElement* elem = theme->getElement(view, element, "image"); if (!elem) return; Vector2f scale = getParent() ? getParent()->getSize() : - Vector2f(static_cast(Renderer::getScreenWidth()), - static_cast(Renderer::getScreenHeight())); + Vector2f(static_cast(Renderer::getScreenWidth()), + static_cast(Renderer::getScreenHeight())); if (properties & ThemeFlags::SIZE) { if (elem->has("size")) @@ -536,8 +510,8 @@ void ImageComponent::applyTheme(const std::shared_ptr& theme, const s if (elem->has("colorEnd")) setColorShiftEnd(elem->get("colorEnd")); if (elem->has("gradientType")) - setColorGradientHorizontal(!(elem-> - get("gradientType").compare("horizontal"))); + setColorGradientHorizontal( + !(elem->get("gradientType").compare("horizontal"))); } } diff --git a/es-core/src/components/ImageComponent.h b/es-core/src/components/ImageComponent.h index eb58a3e3c..68da21126 100644 --- a/es-core/src/components/ImageComponent.h +++ b/es-core/src/components/ImageComponent.h @@ -9,9 +9,9 @@ #ifndef ES_CORE_COMPONENTS_IMAGE_COMPONENT_H #define ES_CORE_COMPONENTS_IMAGE_COMPONENT_H +#include "GuiComponent.h" #include "math/Vector2i.h" #include "renderers/Renderer.h" -#include "GuiComponent.h" class TextureResource; @@ -19,9 +19,9 @@ class ImageComponent : public GuiComponent { public: ImageComponent(Window* window, bool forceLoad = false, bool dynamic = true); - virtual ~ImageComponent(); + virtual ~ImageComponent() {} - void setDefaultImage(std::string path); + void setDefaultImage(std::string path) { mDefaultPath = path; } // Loads the image at the given filepath. Will tile if tile is true (retrieves texture // as tiling, creates vertices accordingly). @@ -31,7 +31,7 @@ public: // Use an already existing texture. void setImage(const std::shared_ptr& texture); - void onSizeChanged() override; + void onSizeChanged() override { updateVertices(); } // Resize the image to fit this size. If one axis is zero, scale that axis to maintain // aspect ratio. If both are non-zero, potentially break the aspect ratio. If both are @@ -39,18 +39,18 @@ public: // Can be set before or after an image is loaded. // setMaxSize() and setResize() are mutually exclusive. void setResize(float width, float height) override; - inline void setResize(const Vector2f& size) { setResize(size.x(), size.y()); } + void setResize(const Vector2f& size) { setResize(size.x(), size.y()); } // Resize the image to be as large as possible but fit within a box of this size. // Can be set before or after an image is loaded. // Never breaks the aspect ratio. setMaxSize() and setResize() are mutually exclusive. void setMaxSize(float width, float height); - inline void setMaxSize(const Vector2f& size) { setMaxSize(size.x(), size.y()); } + void setMaxSize(const Vector2f& size) { setMaxSize(size.x(), size.y()); } void setMinSize(float width, float height); - inline void setMinSize(const Vector2f& size) { setMinSize(size.x(), size.y()); } + void setMinSize(const Vector2f& size) { setMinSize(size.x(), size.y()); } - Vector2f getRotationSize() const override; + Vector2f getRotationSize() const override { return mRotateByTargetSize ? mTargetSize : mSize; } // Applied AFTER image positioning and sizing. // cropTop(0.2) will crop 20% of the top of the image. @@ -70,7 +70,7 @@ public: void setColorShiftEnd(unsigned int color); void setColorGradientHorizontal(bool horizontal); - unsigned int getColorShift() const override { return mColorShift; }; + unsigned int getColorShift() const override { return mColorShift; } void setOpacity(unsigned char opacity) override; void setSaturation(float saturation) override; @@ -79,7 +79,7 @@ public: void setFlipY(bool flip); // Mirror on the Y axis. // Flag indicating if rotation should be based on target size vs. actual size. - void setRotateByTargetSize(bool rotate); + void setRotateByTargetSize(bool rotate) { mRotateByTargetSize = rotate; } // Returns the size of the current texture, or (0, 0) if none is loaded. // May be different than drawn size (use getSize() for that). @@ -87,17 +87,18 @@ public: Vector2f getSize() const override; - bool hasImage(); + bool hasImage() { return static_cast(mTexture); } + std::shared_ptr getTexture() { return mTexture; } void render(const Transform4x4f& parentTrans) override; - virtual void applyTheme(const std::shared_ptr& theme, const std::string& view, - const std::string& element, unsigned int properties) override; + virtual void applyTheme(const std::shared_ptr& theme, + const std::string& view, + const std::string& element, + unsigned int properties) override; virtual std::vector getHelpPrompts() override; - std::shared_ptr getTexture() { return mTexture; }; - private: Vector2f mTargetSize; diff --git a/es-core/src/components/ImageGridComponent.h b/es-core/src/components/ImageGridComponent.h index b2d09913b..b3ac4c393 100644 --- a/es-core/src/components/ImageGridComponent.h +++ b/es-core/src/components/ImageGridComponent.h @@ -9,21 +9,21 @@ #ifndef ES_CORE_COMPONENTS_IMAGE_GRID_COMPONENT_H #define ES_CORE_COMPONENTS_IMAGE_GRID_COMPONENT_H +#include "GridTileComponent.h" +#include "Log.h" #include "animations/LambdaAnimation.h" #include "components/IList.h" #include "resources/TextureResource.h" -#include "GridTileComponent.h" -#include "Log.h" #define EXTRAITEMS 2 enum ScrollDirection { - SCROLL_VERTICALLY, + SCROLL_VERTICALLY, // Replace with AllowShortEnumsOnASingleLine: false (clang-format >=11.0). SCROLL_HORIZONTALLY }; enum ImageSource { - THUMBNAIL, + THUMBNAIL, // Replace with AllowShortEnumsOnASingleLine: false (clang-format >=11.0). IMAGE, MIXIMAGE, SCREENSHOT, @@ -36,8 +36,7 @@ struct ImageGridData { std::string texturePath; }; -template -class ImageGridComponent : public IList +template class ImageGridComponent : public IList { protected: using IList::mEntries; @@ -49,9 +48,6 @@ protected: using IList::mSize; using IList::mCursor; using IList::mWindow; - // The following change is required for compilation with Clang. - // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#2070 - // using IList::Entry; using IList::IList; public: @@ -66,14 +62,18 @@ public: bool input(InputConfig* config, Input input) override; void update(int deltaTime) override; void render(const Transform4x4f& parentTrans) override; - virtual void applyTheme(const std::shared_ptr& theme, const std::string& view, - const std::string& element, unsigned int properties) override; + virtual void applyTheme(const std::shared_ptr& theme, + const std::string& view, + const std::string& element, + unsigned int properties) override; void onSizeChanged() override; - inline void setCursorChangedCallback(const std::function& func) - { mCursorChangedCallback = func; } + void setCursorChangedCallback(const std::function& func) + { + mCursorChangedCallback = func; + } - ImageSource getImageSource() { return mImageSource; }; + ImageSource getImageSource() { return mImageSource; } protected: virtual void onCursorChanged(const CursorState& state) override; @@ -81,13 +81,14 @@ protected: private: // Tiles. void buildTiles(); - void updateTiles(bool ascending = true, bool allowAnimation = true, - bool updateSelectedState = true); + void updateTiles(bool ascending = true, + bool allowAnimation = true, + bool updateSelectedState = true); void updateTileAtPos(int tilePos, int imgPos, bool allowAnimation, bool updateSelectedState); void calcGridDimension(); bool isScrollLoop(); - bool isVertical() { return mScrollDirection == SCROLL_VERTICALLY; }; + bool isVertical() { return mScrollDirection == SCROLL_VERTICALLY; } // Images and entries. bool mEntriesDirty; @@ -121,11 +122,12 @@ private: std::function mCursorChangedCallback; }; -template -ImageGridComponent::ImageGridComponent(Window* window) : IList(window) +template +ImageGridComponent::ImageGridComponent(Window* window) + : IList(window) { Vector2f screen = Vector2f(static_cast(Renderer::getScreenWidth()), - static_cast(Renderer::getScreenHeight())); + static_cast(Renderer::getScreenHeight())); mCamera = 0.0; mCameraDirection = 1.0; @@ -152,7 +154,7 @@ ImageGridComponent::ImageGridComponent(Window* window) : IList +template void ImageGridComponent::add(const std::string& name, const std::string& imagePath, const T& obj) { typename IList::Entry entry; @@ -164,8 +166,7 @@ void ImageGridComponent::add(const std::string& name, const std::string& imag mEntriesDirty = true; } -template -bool ImageGridComponent::input(InputConfig* config, Input input) +template bool ImageGridComponent::input(InputConfig* config, Input input) { if (input.value != 0) { int idx = isVertical() ? 0 : 1; @@ -190,15 +191,15 @@ bool ImageGridComponent::input(InputConfig* config, Input input) } else { if (config->isMappedLike("up", input) || config->isMappedLike("down", input) || - config->isMappedLike("left", input) || config->isMappedLike("right", input)) + config->isMappedLike("left", input) || config->isMappedLike("right", input)) { stopScrolling(); + } } return GuiComponent::input(config, input); } -template -void ImageGridComponent::update(int deltaTime) +template void ImageGridComponent::update(int deltaTime) { GuiComponent::update(deltaTime); listUpdate(deltaTime); @@ -207,16 +208,15 @@ void ImageGridComponent::update(int deltaTime) (*it)->update(deltaTime); } -template -void ImageGridComponent::render(const Transform4x4f& parentTrans) +template void ImageGridComponent::render(const Transform4x4f& parentTrans) { Transform4x4f trans = getTransform() * parentTrans; Transform4x4f tileTrans = trans; - float offsetX = isVertical() ? 0.0f : mCamera * mCameraDirection * - (mTileSize.x() + mMargin.x()); - float offsetY = isVertical() ? mCamera * mCameraDirection * - (mTileSize.y() + mMargin.y()) : 0.0f; + float offsetX = + isVertical() ? 0.0f : mCamera * mCameraDirection * (mTileSize.x() + mMargin.x()); + float offsetY = + isVertical() ? mCamera * mCameraDirection * (mTileSize.y() + mMargin.y()) : 0.0f; tileTrans.translate(Vector3f(offsetX, offsetY, 0.0)); @@ -230,9 +230,9 @@ void ImageGridComponent::render(const Transform4x4f& parentTrans) float scaleY = trans.r1().y(); Vector2i pos(static_cast(std::round(trans.translation()[0])), - static_cast(std::round(trans.translation()[1]))); + static_cast(std::round(trans.translation()[1]))); Vector2i size(static_cast(std::round(mSize.x() * scaleX)), - static_cast(std::round(mSize.y() * scaleY))); + static_cast(std::round(mSize.y() * scaleY))); Renderer::pushClipRect(pos, size); @@ -258,9 +258,11 @@ void ImageGridComponent::render(const Transform4x4f& parentTrans) GuiComponent::renderChildren(trans); } -template +template void ImageGridComponent::applyTheme(const std::shared_ptr& theme, - const std::string& view, const std::string& element, unsigned int properties) + const std::string& view, + const std::string& element, + unsigned int properties) { // Apply theme to GuiComponent but not the size property, which will be applied // at the end of this function. @@ -270,7 +272,7 @@ void ImageGridComponent::applyTheme(const std::shared_ptr& theme, mTheme = theme; Vector2f screen = Vector2f(static_cast(Renderer::getScreenWidth()), - static_cast(Renderer::getScreenHeight())); + static_cast(Renderer::getScreenHeight())); const ThemeData::ThemeElement* elem = theme->getElement(view, element, "imagegrid"); if (elem) { @@ -279,7 +281,7 @@ void ImageGridComponent::applyTheme(const std::shared_ptr& theme, if (elem->has("padding")) mPadding = elem->get("padding") * - Vector4f(screen.x(), screen.y(), screen.x(), screen.y()); + Vector4f(screen.x(), screen.y(), screen.x(), screen.y()); if (elem->has("autoLayout")) mAutoLayout = elem->get("autoLayout"); @@ -309,8 +311,8 @@ void ImageGridComponent::applyTheme(const std::shared_ptr& theme, } if (elem->has("scrollDirection")) - mScrollDirection = (ScrollDirection)(elem-> - get("scrollDirection") == "horizontal"); + mScrollDirection = + (ScrollDirection)(elem->get("scrollDirection") == "horizontal"); if (elem->has("centerSelection")) { mCenterSelection = (elem->get("centerSelection")); @@ -367,9 +369,8 @@ void ImageGridComponent::applyTheme(const std::shared_ptr& theme, // grid dimension, and then (re)build the tiles. elem = theme->getElement(view, "default", "gridtile"); - mTileSize = elem && elem->has("size") ? - elem->get("size") * screen : - GridTileComponent::getDefaultTileSize(); + mTileSize = elem && elem->has("size") ? elem->get("size") * screen : + GridTileComponent::getDefaultTileSize(); // Apply size property which will trigger a call to onSizeChanged() which will build the tiles. GuiComponent::applyTheme(theme, view, element, ThemeFlags::SIZE); @@ -379,15 +380,13 @@ void ImageGridComponent::applyTheme(const std::shared_ptr& theme, buildTiles(); } -template -void ImageGridComponent::onSizeChanged() +template void ImageGridComponent::onSizeChanged() { buildTiles(); updateTiles(); } -template -void ImageGridComponent::onCursorChanged(const CursorState& state) +template void ImageGridComponent::onCursorChanged(const CursorState& state) { if (mLastCursor == mCursor) { if (state == CURSOR_STOPPED && mCursorChangedCallback) @@ -470,7 +469,7 @@ void ImageGridComponent::onCursorChanged(const CursorState& state) mStartPosition = lastScroll * dimOpposite; } else if ((maxCentralCol != centralCol && col == firstVisibleCol + maxCentralCol) || - col == firstVisibleCol + centralCol) { + col == firstVisibleCol + centralCol) { if (col == firstVisibleCol + maxCentralCol) mStartPosition = (col - maxCentralCol) * dimOpposite; else @@ -507,23 +506,23 @@ void ImageGridComponent::onCursorChanged(const CursorState& state) if (!moveCamera) return; - t -= 1; // Cubic ease out. - float pct = Math::lerp(0, 1, t*t*t + 1); + t -= 1.0f; // Cubic ease out. + float pct = Math::lerp(0, 1.0f, t * t * t + 1.0f); t = startPos * (1.0f - pct) + endPos * pct; mCamera = t; }; reinterpret_cast(this)->setAnimation( - new LambdaAnimation(func, 250), 0, [this, direction] { - mCamera = 0; - updateTiles(direction, false); - }, false, 2); + new LambdaAnimation(func, 250), 0, + [this, direction] { + mCamera = 0; + updateTiles(direction, false); + }, + false, 2); } - // Create and position tiles (mTiles). -template -void ImageGridComponent::buildTiles() +template void ImageGridComponent::buildTiles() { mStartPosition = 0; mTiles.clear(); @@ -531,18 +530,20 @@ void ImageGridComponent::buildTiles() calcGridDimension(); if (mCenterSelection) { - int dimScrollable = (isVertical() ? mGridDimension.y() : - mGridDimension.x()) - 2 * EXTRAITEMS; + int dimScrollable = + (isVertical() ? mGridDimension.y() : mGridDimension.x()) - 2 * EXTRAITEMS; mStartPosition -= static_cast(floorf(dimScrollable / 2.0f)); } Vector2f tileDistance = mTileSize + mMargin; if (mAutoLayout.x() != 0.0f && mAutoLayout.y() != 0.0f) { - auto x = (mSize.x() - (mMargin.x() * (mAutoLayout.x() - 1.0f)) - mPadding.x() - - mPadding.z()) / static_cast(mAutoLayout.x()); - auto y = (mSize.y() - (mMargin.y() * (mAutoLayout.y() - 1.0f)) - mPadding.y() - - mPadding.w()) / static_cast(mAutoLayout.y()); + auto x = + (mSize.x() - (mMargin.x() * (mAutoLayout.x() - 1.0f)) - mPadding.x() - mPadding.z()) / + static_cast(mAutoLayout.x()); + auto y = + (mSize.y() - (mMargin.y() * (mAutoLayout.y() - 1.0f)) - mPadding.y() - mPadding.w()) / + static_cast(mAutoLayout.y()); mTileSize = Vector2f(x, y); tileDistance = mTileSize + mMargin; @@ -566,8 +567,8 @@ void ImageGridComponent::buildTiles() X = vert ? x : y - EXTRAITEMS; Y = vert ? y - EXTRAITEMS : x; - tile->setPosition(X * tileDistance.x() + startPosition.x(), Y * - tileDistance.y() + startPosition.y()); + tile->setPosition(X * tileDistance.x() + startPosition.x(), + Y * tileDistance.y() + startPosition.y()); tile->setOrigin(0.5f, 0.5f); tile->setImage(""); @@ -582,9 +583,10 @@ void ImageGridComponent::buildTiles() } } -template -void ImageGridComponent::updateTiles(bool ascending, bool allowAnimation, - bool updateSelectedState) +template +void ImageGridComponent::updateTiles(bool ascending, + bool allowAnimation, + bool updateSelectedState) { if (!mTiles.size()) return; @@ -631,9 +633,11 @@ void ImageGridComponent::updateTiles(bool ascending, bool allowAnimation, mLastCursor = mCursor; } -template -void ImageGridComponent::updateTileAtPos(int tilePos, int imgPos, - bool allowAnimation, bool updateSelectedState) +template +void ImageGridComponent::updateTileAtPos(int tilePos, + int imgPos, + bool allowAnimation, + bool updateSelectedState) { std::shared_ptr tile = mTiles.at(tilePos); @@ -647,7 +651,7 @@ void ImageGridComponent::updateTileAtPos(int tilePos, int imgPos, // If we have more tiles than we can display on screen, hide them. // Same for tiles out of the buffer. if (imgPos < 0 || imgPos >= size() || tilePos < 0 || - tilePos >= static_cast(mTiles.size())) { + tilePos >= static_cast(mTiles.size())) { if (updateSelectedState) tile->setSelected(false, allowAnimation); tile->reset(); @@ -680,14 +684,12 @@ void ImageGridComponent::updateTileAtPos(int tilePos, int imgPos, tile->setSelected(imgPos == mCursor, allowAnimation); } } - } } // Calculate how many tiles of size mTileSize we can fit in a grid of size mSize using // a margin size of mMargin. -template -void ImageGridComponent::calcGridDimension() +template void ImageGridComponent::calcGridDimension() { // grid_size = columns * tile_size + (columns - 1) * margin // <=> columns = (grid_size + margin) / (tile_size + margin) @@ -700,7 +702,7 @@ void ImageGridComponent::calcGridDimension() // Ceil y dim so we can display partial last row. mGridDimension = Vector2i(static_cast(gridDimension.x()), - static_cast(ceilf(gridDimension.y()))); + static_cast(ceilf(gridDimension.y()))); // Grid dimension validation. if (mGridDimension.x() < 1) { @@ -717,13 +719,13 @@ void ImageGridComponent::calcGridDimension() mGridDimension.x() += 2 * EXTRAITEMS; } -template -bool ImageGridComponent::isScrollLoop() { +template bool ImageGridComponent::isScrollLoop() +{ if (!mScrollLoop) return false; if (isVertical()) return (mGridDimension.x() * (mGridDimension.y() - 2 * EXTRAITEMS)) <= mEntries.size(); return (mGridDimension.y() * (mGridDimension.x() - 2 * EXTRAITEMS)) <= mEntries.size(); -}; +} #endif // ES_CORE_COMPONENTS_IMAGE_GRID_COMPONENT_H diff --git a/es-core/src/components/MenuComponent.cpp b/es-core/src/components/MenuComponent.cpp index 6360285f9..ce7258599 100644 --- a/es-core/src/components/MenuComponent.cpp +++ b/es-core/src/components/MenuComponent.cpp @@ -8,22 +8,21 @@ #include "components/MenuComponent.h" -#include "components/ButtonComponent.h" #include "Settings.h" +#include "components/ButtonComponent.h" #define BUTTON_GRID_VERT_PADDING 32.0f #define BUTTON_GRID_HORIZ_PADDING 10.0f #define TITLE_HEIGHT (mTitle->getFont()->getLetterHeight() + TITLE_VERT_PADDING) -MenuComponent::MenuComponent( - Window* window, - std::string title, - const std::shared_ptr& titleFont) - : GuiComponent(window), - mBackground(window), - mGrid(window, Vector2i(1, 3)), - mNeedsSaving(false) +MenuComponent::MenuComponent(Window* window, + std::string title, + const std::shared_ptr& titleFont) + : GuiComponent(window) + , mBackground(window) + , mGrid(window, Vector2i(1, 3)) + , mNeedsSaving(false) { addChild(&mBackground); addChild(&mGrid); @@ -49,6 +48,7 @@ MenuComponent::MenuComponent( MenuComponent::~MenuComponent() { + // Save when destroyed. save(); } @@ -75,15 +75,15 @@ void MenuComponent::setTitle(std::string title, const std::shared_ptr& fon float MenuComponent::getButtonGridHeight() const { return (mButtonGrid ? mButtonGrid->getSize().y() : - Font::get(FONT_SIZE_MEDIUM)->getHeight() + - (BUTTON_GRID_VERT_PADDING * Renderer::getScreenHeightModifier())); + Font::get(FONT_SIZE_MEDIUM)->getHeight() + + (BUTTON_GRID_VERT_PADDING * Renderer::getScreenHeightModifier())); } void MenuComponent::updateSize() { const float maxHeight = Renderer::getScreenHeight() * 0.80f; float height = TITLE_HEIGHT + mList->getTotalRowHeight() + getButtonGridHeight() + - (2.0f * Renderer::getScreenHeightModifier()); + (2.0f * Renderer::getScreenHeightModifier()); if (height > maxHeight) { height = TITLE_HEIGHT + getButtonGridHeight(); int i = 0; @@ -98,14 +98,15 @@ void MenuComponent::updateSize() } } - float width = static_cast(std::min(static_cast(Renderer::getScreenHeight() * - 1.05f), static_cast(Renderer::getScreenWidth() * 0.90f))); + float width = + static_cast(std::min(static_cast(Renderer::getScreenHeight() * 1.05f), + static_cast(Renderer::getScreenWidth() * 0.90f))); setSize(width, height); } void MenuComponent::onSizeChanged() { - mBackground.fitTo(mSize, Vector3f::Zero(), Vector2f(-32, -32)); + mBackground.fitTo(mSize, Vector3f::Zero(), Vector2f(-32.0f, -32.0f)); // Update grid row/column sizes. mGrid.setRowHeightPerc(0, TITLE_HEIGHT / mSize.y()); @@ -115,10 +116,11 @@ void MenuComponent::onSizeChanged() } void MenuComponent::addButton(const std::string& name, - const std::string& helpText, const std::function& callback) + const std::string& helpText, + const std::function& callback) { - mButtons.push_back(std::make_shared - (mWindow,Utils::String::toUpper(name), helpText, callback)); + mButtons.push_back(std::make_shared(mWindow, Utils::String::toUpper(name), + helpText, callback)); updateGrid(); updateSize(); } @@ -136,30 +138,28 @@ void MenuComponent::updateGrid() } } -std::vector MenuComponent::getHelpPrompts() +std::shared_ptr makeButtonGrid( + Window* window, const std::vector>& buttons) { - return mGrid.getHelpPrompts(); -} - -std::shared_ptr makeButtonGrid(Window* window, - const std::vector>& buttons) -{ - std::shared_ptr buttonGrid = std::make_shared - (window, Vector2i(static_cast(buttons.size()), 2)); + std::shared_ptr buttonGrid = + std::make_shared(window, Vector2i(static_cast(buttons.size()), 2)); // Initialize to padding. - float buttonGridWidth = BUTTON_GRID_HORIZ_PADDING * - Renderer::getScreenWidthModifier() * buttons.size(); + float buttonGridWidth = + BUTTON_GRID_HORIZ_PADDING * Renderer::getScreenWidthModifier() * buttons.size(); for (int i = 0; i < static_cast(buttons.size()); i++) { buttonGrid->setEntry(buttons.at(i), Vector2i(i, 0), true, false); buttonGridWidth += buttons.at(i)->getSize().x(); } for (unsigned int i = 0; i < buttons.size(); i++) - buttonGrid->setColWidthPerc(i, (buttons.at(i)->getSize().x() + - BUTTON_GRID_HORIZ_PADDING * Renderer::getScreenWidthModifier()) / buttonGridWidth); + buttonGrid->setColWidthPerc( + i, (buttons.at(i)->getSize().x() + + BUTTON_GRID_HORIZ_PADDING * Renderer::getScreenWidthModifier()) / + buttonGridWidth); - buttonGrid->setSize(buttonGridWidth, buttons.at(0)->getSize().y() + - (BUTTON_GRID_VERT_PADDING * Renderer::getScreenHeightModifier()) + 2); + buttonGrid->setSize(buttonGridWidth, + buttons.at(0)->getSize().y() + + (BUTTON_GRID_VERT_PADDING * Renderer::getScreenHeightModifier()) + 2); // Spacer row to deal with dropshadow to make buttons look centered. buttonGrid->setRowHeightPerc(1, 2 / buttonGrid->getSize().y()); diff --git a/es-core/src/components/MenuComponent.h b/es-core/src/components/MenuComponent.h index e73ae37c5..b0d8e927f 100644 --- a/es-core/src/components/MenuComponent.h +++ b/es-core/src/components/MenuComponent.h @@ -17,20 +17,21 @@ #include +#define TITLE_VERT_PADDING (Renderer::getScreenHeight() * 0.0637f) + class ButtonComponent; class ImageComponent; -std::shared_ptr makeButtonGrid(Window* window, - const std::vector>& buttons); +std::shared_ptr makeButtonGrid( + Window* window, const std::vector>& buttons); std::shared_ptr makeArrow(Window* window); -#define TITLE_VERT_PADDING (Renderer::getScreenHeight() * 0.0637f) - class MenuComponent : public GuiComponent { public: - MenuComponent(Window* window, std::string title, - const std::shared_ptr& titleFont = Font::get(FONT_SIZE_LARGE)); + MenuComponent(Window* window, + std::string title, + const std::shared_ptr& titleFont = Font::get(FONT_SIZE_LARGE)); virtual ~MenuComponent(); void save(); @@ -38,31 +39,42 @@ public: void setNeedsSaving() { mNeedsSaving = true; } - inline void addRow(const ComponentListRow& row, bool setCursorHere = false) - { mList->addRow(row, setCursorHere); updateSize(); } + void addRow(const ComponentListRow& row, bool setCursorHere = false) + { + mList->addRow(row, setCursorHere); + updateSize(); + } - inline void addWithLabel(const std::string& label, const std::shared_ptr& comp, - bool setCursorHere = false, bool invert_when_selected = true) + void addWithLabel(const std::string& label, + const std::shared_ptr& comp, + bool setCursorHere = false, + bool invert_when_selected = true) { ComponentListRow row; - row.addElement(std::make_shared(mWindow, - Utils::String::toUpper(label), Font::get(FONT_SIZE_MEDIUM), 0x777777FF), true); + row.addElement(std::make_shared(mWindow, Utils::String::toUpper(label), + Font::get(FONT_SIZE_MEDIUM), 0x777777FF), + true); row.addElement(comp, false, invert_when_selected); addRow(row, setCursorHere); } - inline void addSaveFunc(const std::function& func) { mSaveFuncs.push_back(func); } + void addSaveFunc(const std::function& func) { mSaveFuncs.push_back(func); } - void addButton(const std::string& label, const std::string& helpText, - const std::function& callback); + void addButton(const std::string& label, + const std::string& helpText, + const std::function& callback); void setTitle(std::string title, const std::shared_ptr& font); void setCursorToFirstListEntry() { mList->moveCursor(-mList->getCursorId()); } - inline void setCursorToList() { mGrid.setCursorTo(mList); } - inline void setCursorToButtons() { assert(mButtonGrid); mGrid.setCursorTo(mButtonGrid); } + void setCursorToList() { mGrid.setCursorTo(mList); } + void setCursorToButtons() + { + assert(mButtonGrid); + mGrid.setCursorTo(mButtonGrid); + } - virtual std::vector getHelpPrompts() override; + virtual std::vector getHelpPrompts() override { return mGrid.getHelpPrompts(); } private: void updateSize(); diff --git a/es-core/src/components/NinePatchComponent.cpp b/es-core/src/components/NinePatchComponent.cpp index f8df08ef3..f14915086 100644 --- a/es-core/src/components/NinePatchComponent.cpp +++ b/es-core/src/components/NinePatchComponent.cpp @@ -8,21 +8,20 @@ #include "components/NinePatchComponent.h" -#include "resources/TextureResource.h" #include "Log.h" #include "ThemeData.h" +#include "resources/TextureResource.h" -NinePatchComponent::NinePatchComponent( - Window* window, - const std::string& path, - unsigned int edgeColor, - unsigned int centerColor) - : GuiComponent(window), - mCornerSize(16.0f, 16.0f), - mEdgeColor(edgeColor), - mCenterColor(centerColor), - mPath(path), - mVertices(nullptr) +NinePatchComponent::NinePatchComponent(Window* window, + const std::string& path, + unsigned int edgeColor, + unsigned int centerColor) + : GuiComponent(window) + , mCornerSize(16.0f, 16.0f) + , mEdgeColor(edgeColor) + , mCenterColor(centerColor) + , mPath(path) + , mVertices(nullptr) { if (!mPath.empty()) buildVertices(); @@ -42,8 +41,8 @@ void NinePatchComponent::updateColors() for (int i = 0; i < 6 * 9; i++) mVertices[i].col = edgeColor; - for (int i = 6*4; i < 6; i++) - mVertices[(6*4)+i].col = centerColor; + for (int i = 6 * 4; i < 6; i++) + mVertices[(6 * 4) + i].col = centerColor; } void NinePatchComponent::buildVertices() @@ -72,19 +71,21 @@ void NinePatchComponent::buildVertices() mVertices = new Renderer::Vertex[6 * 9]; texSize = Vector2f(static_cast(mTexture->getSize().x()), - static_cast(mTexture->getSize().y())); + static_cast(mTexture->getSize().y())); - const float imgSizeX[3] = { mCornerSize.x(), mSize.x() - mCornerSize.x() * 2, mCornerSize.x()}; - const float imgSizeY[3] = { mCornerSize.y(), mSize.y() - mCornerSize.y() * 2, mCornerSize.y()}; - const float imgPosX[3] = { 0, imgSizeX[0], imgSizeX[0] + imgSizeX[1]}; - const float imgPosY[3] = { 0, imgSizeY[0], imgSizeY[0] + imgSizeY[1]}; + // clang-format off + const float imgSizeX[3] = { mCornerSize.x(), mSize.x() - mCornerSize.x() * 2.0f, mCornerSize.x() }; + const float imgSizeY[3] = { mCornerSize.y(), mSize.y() - mCornerSize.y() * 2.0f, mCornerSize.y() }; + const float imgPosX[3] = { 0, imgSizeX[0], imgSizeX[0] + imgSizeX[1] }; + const float imgPosY[3] = { 0, imgSizeY[0], imgSizeY[0] + imgSizeY[1] }; // The "1 +" in posY and "-" in sizeY is to deal with texture coordinates having a bottom // left corner origin vs. verticies having a top left origin. - const float texSizeX[3] = { mCornerSize.x() / texSize.x(), (texSize.x() - mCornerSize.x() * 2) / texSize.x(), mCornerSize.x() / texSize.x() }; - const float texSizeY[3] = { -mCornerSize.y() / texSize.y(), -(texSize.y() - mCornerSize.y() * 2) / texSize.y(), -mCornerSize.y() / texSize.y() }; - const float texPosX[3] = { 0, texSizeX[0], texSizeX[0] + texSizeX[1] }; - const float texPosY[3] = { 1, 1 + texSizeY[0], 1 + texSizeY[0] + texSizeY[1] }; + const float texSizeX[3] = { mCornerSize.x() / texSize.x(), (texSize.x() - mCornerSize.x() * 2.0f) / texSize.x(), mCornerSize.x() / texSize.x() }; + const float texSizeY[3] = { -mCornerSize.y() / texSize.y(), -(texSize.y() - mCornerSize.y() * 2.0f) / texSize.y(), -mCornerSize.y() / texSize.y() }; + const float texPosX[3] = { 0.0f, texSizeX[0], texSizeX[0] + texSizeX[1] }; + const float texPosY[3] = { 1.0f, 1.0f + texSizeY[0], 1.0f + texSizeY[0] + texSizeY[1] }; + // clang-format on int v = 0; @@ -96,10 +97,12 @@ void NinePatchComponent::buildVertices() const Vector2f texPos = Vector2f(texPosX[sliceX], texPosY[sliceY]); const Vector2f texSize = Vector2f(texSizeX[sliceX], texSizeY[sliceY]); + // clang-format off mVertices[v + 1] = { { imgPos.x() , imgPos.y() }, { texPos.x(), texPos.y() }, 0 }; mVertices[v + 2] = { { imgPos.x() , imgPos.y() + imgSize.y() }, { texPos.x(), texPos.y() + texSize.y() }, 0 }; mVertices[v + 3] = { { imgPos.x() + imgSize.x(), imgPos.y() }, { texPos.x() + texSize.x(), texPos.y() }, 0 }; mVertices[v + 4] = { { imgPos.x() + imgSize.x(), imgPos.y() + imgSize.y() }, { texPos.x() + texSize.x(), texPos.y() + texSize.y() }, 0 }; + // clang-format on // Round vertices. for (int i = 1; i < 5; i++) @@ -141,10 +144,7 @@ void NinePatchComponent::render(const Transform4x4f& parentTrans) renderChildren(trans); } -void NinePatchComponent::onSizeChanged() -{ - buildVertices(); -} +void NinePatchComponent::onSizeChanged() { buildVertices(); } void NinePatchComponent::fitTo(Vector2f size, Vector3f position, Vector2f padding) { @@ -176,7 +176,9 @@ void NinePatchComponent::setCenterColor(unsigned int centerColor) } void NinePatchComponent::applyTheme(const std::shared_ptr& theme, - const std::string& view, const std::string& element, unsigned int properties) + const std::string& view, + const std::string& element, + unsigned int properties) { GuiComponent::applyTheme(theme, view, element, properties); diff --git a/es-core/src/components/NinePatchComponent.h b/es-core/src/components/NinePatchComponent.h index c7ff33145..9c0191ded 100644 --- a/es-core/src/components/NinePatchComponent.h +++ b/es-core/src/components/NinePatchComponent.h @@ -9,8 +9,8 @@ #ifndef ES_CORE_COMPONENTS_NINE_PATCH_COMPONENT_H #define ES_CORE_COMPONENTS_NINE_PATCH_COMPONENT_H -#include "renderers/Renderer.h" #include "GuiComponent.h" +#include "renderers/Renderer.h" class TextureResource; @@ -29,16 +29,19 @@ class TextureResource; class NinePatchComponent : public GuiComponent { public: - NinePatchComponent(Window* window, const std::string& path = "", - unsigned int edgeColor = 0xFFFFFFFF, unsigned int centerColor = 0xFFFFFFFF); + NinePatchComponent(Window* window, + const std::string& path = "", + unsigned int edgeColor = 0xFFFFFFFF, + unsigned int centerColor = 0xFFFFFFFF); virtual ~NinePatchComponent(); void render(const Transform4x4f& parentTrans) override; void onSizeChanged() override; - void fitTo(Vector2f size, Vector3f position = Vector3f::Zero(), - Vector2f padding = Vector2f::Zero()); + void fitTo(Vector2f size, + Vector3f position = Vector3f::Zero(), + Vector2f padding = Vector2f::Zero()); void setImagePath(const std::string& path); // Apply a color shift to the "edge" parts of the ninepatch. @@ -46,15 +49,17 @@ public: // Apply a color shift to the "center" part of the ninepatch. void setCenterColor(unsigned int centerColor); - virtual void applyTheme(const std::shared_ptr& theme, const std::string& view, - const std::string& element, unsigned int properties) override; + virtual void applyTheme(const std::shared_ptr& theme, + const std::string& view, + const std::string& element, + unsigned int properties) override; - inline const Vector2f& getCornerSize() const { return mCornerSize; }; - inline void setCornerSize(const Vector2f& size) + const Vector2f& getCornerSize() const { return mCornerSize; } + void setCornerSize(const Vector2f& size) { mCornerSize = size; buildVertices(); - }; + } private: void buildVertices(); diff --git a/es-core/src/components/OptionListComponent.h b/es-core/src/components/OptionListComponent.h index c608a6e55..223ec141f 100644 --- a/es-core/src/components/OptionListComponent.h +++ b/es-core/src/components/OptionListComponent.h @@ -21,28 +21,20 @@ // Used to display a list of options. // Can select one or multiple options. - -// if !multiSelect -// * <- curEntry -> -// Always -// * press a -> open full list. - -template -class OptionListComponent : public GuiComponent +template class OptionListComponent : public GuiComponent { public: - OptionListComponent( - Window* window, - const HelpStyle& helpstyle, - const std::string& name, - bool multiSelect = false) - : GuiComponent(window), - mHelpStyle(helpstyle), - mMultiSelect(multiSelect), - mName(name), - mText(window), - mLeftArrow(window), - mRightArrow(window) + OptionListComponent(Window* window, + const HelpStyle& helpstyle, + const std::string& name, + bool multiSelect = false) + : GuiComponent(window) + , mHelpStyle(helpstyle) + , mMultiSelect(multiSelect) + , mName(name) + , mText(window) + , mLeftArrow(window) + , mRightArrow(window) { auto font = Font::get(FONT_SIZE_MEDIUM, FONT_PATH_LIGHT); mText.setFont(font); @@ -79,15 +71,15 @@ public: LOG(LogWarning) << "OptionListComponent too narrow"; } - mText.setSize(mSize.x() - mLeftArrow.getSize().x() - - mRightArrow.getSize().x(), mText.getFont()->getHeight()); + mText.setSize(mSize.x() - mLeftArrow.getSize().x() - mRightArrow.getSize().x(), + mText.getFont()->getHeight()); // Position. mLeftArrow.setPosition(0, (mSize.y() - mLeftArrow.getSize().y()) / 2); mText.setPosition(mLeftArrow.getPosition().x() + mLeftArrow.getSize().x(), - (mSize.y() - mText.getSize().y()) / 2); + (mSize.y() - mText.getSize().y()) / 2); mRightArrow.setPosition(mText.getPosition().x() + mText.getSize().x(), - (mSize.y() - mRightArrow.getSize().y()) / 2); + (mSize.y() - mRightArrow.getSize().y()) / 2); } bool input(InputConfig* config, Input input) override @@ -115,7 +107,6 @@ public: mEntries.at(next).selected = true; onSelectedChanged(); return true; - } else if (config->isMappedLike("right", input)) { // Ignore input if the component has been disabled. @@ -205,7 +196,7 @@ public: void sortEntriesByName() { std::sort(std::begin(mEntries), std::end(mEntries), - [](OptionListData a, OptionListData b) { return a.name < b.name; }); + [](OptionListData a, OptionListData b) { return a.name < b.name; }); } unsigned int getSelectedId() @@ -217,11 +208,11 @@ public: } LOG(LogWarning) << "OptionListComponent::getSelectedId() - " - "no selected element found, defaulting to 0"; + "no selected element found, defaulting to 0"; return 0; } - HelpStyle getHelpStyle() override { return mHelpStyle; }; + HelpStyle getHelpStyle() override { return mHelpStyle; } private: struct OptionListData { @@ -232,10 +223,7 @@ private: HelpStyle mHelpStyle; - void open() - { - mWindow->pushGui(new OptionListPopup(mWindow, getHelpStyle(), this, mName)); - } + void open() { mWindow->pushGui(new OptionListPopup(mWindow, getHelpStyle(), this, mName)); } void onSelectedChanged() { @@ -246,7 +234,8 @@ private: mText.setText(ss.str()); mText.setSize(0, mText.getSize().y()); setSize(mText.getSize().x() + mRightArrow.getSize().x() + - 24 * Renderer::getScreenWidthModifier(), mText.getSize().y()); + 24 * Renderer::getScreenWidthModifier(), + mText.getSize().y()); if (mParent) // Hack since there's no "on child size changed" callback. mParent->onSizeChanged(); } @@ -257,8 +246,9 @@ private: mText.setText(Utils::String::toUpper(it->name)); mText.setSize(0, mText.getSize().y()); setSize(mText.getSize().x() + mLeftArrow.getSize().x() + - mRightArrow.getSize().x() + - 24 * Renderer::getScreenWidthModifier(), mText.getSize().y()); + mRightArrow.getSize().x() + + 24.0f * Renderer::getScreenWidthModifier(), + mText.getSize().y()); if (mParent) // Hack since there's no "on child size changed" callback. mParent->onSizeChanged(); break; @@ -290,15 +280,14 @@ private: class OptionListPopup : public GuiComponent { public: - OptionListPopup( - Window* window, - const HelpStyle& helpstyle, - OptionListComponent* parent, - const std::string& title) - : GuiComponent(window), - mHelpStyle(helpstyle), - mMenu(window, title.c_str()), - mParent(parent) + OptionListPopup(Window* window, + const HelpStyle& helpstyle, + OptionListComponent* parent, + const std::string& title) + : GuiComponent(window) + , mHelpStyle(helpstyle) + , mMenu(window, title.c_str()) + , mParent(parent) { auto font = Font::get(FONT_SIZE_MEDIUM); ComponentListRow row; @@ -308,8 +297,9 @@ private: for (auto it = mParent->mEntries.begin(); it != mParent->mEntries.end(); it++) { row.elements.clear(); - row.addElement(std::make_shared - (mWindow, Utils::String::toUpper(it->name), font, 0x777777FF), true); + row.addElement(std::make_shared( + mWindow, Utils::String::toUpper(it->name), font, 0x777777FF), + true); OptionListData& e = *it; @@ -367,7 +357,7 @@ private: } mMenu.setPosition((Renderer::getScreenWidth() - mMenu.getSize().x()) / 2.0f, - Renderer::getScreenHeight() * 0.13f); + Renderer::getScreenHeight() * 0.13f); addChild(&mMenu); } @@ -389,7 +379,7 @@ private: return prompts; } - HelpStyle getHelpStyle() override { return mHelpStyle; }; + HelpStyle getHelpStyle() override { return mHelpStyle; } private: MenuComponent mMenu; diff --git a/es-core/src/components/RatingComponent.cpp b/es-core/src/components/RatingComponent.cpp index 5710f9404..a2f1c8aba 100644 --- a/es-core/src/components/RatingComponent.cpp +++ b/es-core/src/components/RatingComponent.cpp @@ -9,25 +9,23 @@ #include "components/RatingComponent.h" -#include "resources/TextureResource.h" #include "Settings.h" #include "ThemeData.h" +#include "resources/TextureResource.h" -RatingComponent::RatingComponent( - Window* window, - bool colorizeChanges) - : GuiComponent(window), - mColorShift(DEFAULT_COLORSHIFT), - mColorShiftEnd(DEFAULT_COLORSHIFT), - mUnfilledColor(DEFAULT_COLORSHIFT), - mColorizeChanges(colorizeChanges), - mColorOriginalValue(DEFAULT_COLORSHIFT), - mColorChangedValue(DEFAULT_COLORSHIFT) +RatingComponent::RatingComponent(Window* window, bool colorizeChanges) + : GuiComponent(window) + , mColorShift(DEFAULT_COLORSHIFT) + , mColorShiftEnd(DEFAULT_COLORSHIFT) + , mUnfilledColor(DEFAULT_COLORSHIFT) + , mColorizeChanges(colorizeChanges) + , mColorOriginalValue(DEFAULT_COLORSHIFT) + , mColorChangedValue(DEFAULT_COLORSHIFT) { mFilledTexture = TextureResource::get(":/graphics/star_filled.svg", true); mUnfilledTexture = TextureResource::get(":/graphics/star_unfilled.svg", true); mValue = 0.5f; - mSize = Vector2f(64 * NUM_RATING_STARS, 64); + mSize = Vector2f(64.0f * NUM_RATING_STARS, 64.0f); updateVertices(); updateColors(); } @@ -39,13 +37,13 @@ void RatingComponent::setValue(const std::string& value) } else { // Round up to the closest .1 value, i.e. to the closest half-icon. - mValue = ceilf(stof(value) / 0.1f) / 10; - mOriginalValue = static_cast(mValue * 10); + mValue = ceilf(stof(value) / 0.1f) / 10.0f; + mOriginalValue = static_cast(mValue * 10.0f); // If the argument to colorize the rating icons has been passed, set the // color shift accordingly. if (mColorizeChanges) { - if (static_cast(mValue * 10) == mOriginalValue) + if (static_cast(mValue * 10.0f) == mOriginalValue) setColorShift(mColorOriginalValue); else setColorShift(mColorChangedValue); @@ -122,6 +120,7 @@ void RatingComponent::updateVertices() const float fw = getSize().y() * numStars; const unsigned int color = Renderer::convertRGBAToABGR(mColorShift); + // clang-format off mVertices[0] = { { 0.0f, 0.0f }, { 0.0f, 1.0f }, color }; mVertices[1] = { { 0.0f, h }, { 0.0f, 0.0f }, color }; mVertices[2] = { { w, 0.0f }, { mValue * numStars, 1.0f }, color }; @@ -131,13 +130,7 @@ void RatingComponent::updateVertices() mVertices[5] = { { 0.0f, h }, { 0.0f, 0.0f }, color }; mVertices[6] = { { fw, 0.0f }, { numStars, 1.0f }, color }; mVertices[7] = { { fw, h }, { numStars, 0.0f }, color }; - - -// Disabled this code as it caused subtle but strange rendering errors -// where the icons changed size slightly when changing rating scores. -// // Round vertices. -// for (int i = 0; i < 8; i++) -// mVertices[i].pos.round(); + // clang-format on } void RatingComponent::updateColors() @@ -159,8 +152,8 @@ void RatingComponent::render(const Transform4x4f& parentTrans) if (mOpacity > 0) { if (Settings::getInstance()->getBool("DebugImage")) { - Renderer::drawRect(0.0f, 0.0f, mSize.y() * NUM_RATING_STARS, - mSize.y(), 0xFF000033, 0xFF000033); + Renderer::drawRect(0.0f, 0.0f, mSize.y() * NUM_RATING_STARS, mSize.y(), 0xFF000033, + 0xFF000033); } if (mUnfilledTexture->bind()) { @@ -189,14 +182,14 @@ void RatingComponent::render(const Transform4x4f& parentTrans) bool RatingComponent::input(InputConfig* config, Input input) { if (config->isMappedTo("a", input) && input.value != 0) { - mValue += (1.f/2) / NUM_RATING_STARS; + mValue += (1.0f / 2.0f) / NUM_RATING_STARS; if (mValue > 1.05f) mValue = 0.0f; // If the argument to colorize the rating icons has been passed, // set the color shift accordingly. if (mColorizeChanges) { - if (static_cast(mValue * 10) == mOriginalValue) + if (static_cast(mValue * 10.0f) == mOriginalValue) setColorShift(mColorOriginalValue); else setColorShift(mColorChangedValue); @@ -208,7 +201,9 @@ bool RatingComponent::input(InputConfig* config, Input input) } void RatingComponent::applyTheme(const std::shared_ptr& theme, - const std::string& view, const std::string& element, unsigned int properties) + const std::string& view, + const std::string& element, + unsigned int properties) { using namespace ThemeFlags; diff --git a/es-core/src/components/RatingComponent.h b/es-core/src/components/RatingComponent.h index 747c6a310..dfb2be65c 100644 --- a/es-core/src/components/RatingComponent.h +++ b/es-core/src/components/RatingComponent.h @@ -10,18 +10,13 @@ #ifndef ES_APP_COMPONENTS_RATING_COMPONENT_H #define ES_APP_COMPONENTS_RATING_COMPONENT_H -#include "renderers/Renderer.h" #include "GuiComponent.h" +#include "renderers/Renderer.h" class TextureResource; #define NUM_RATING_STARS 5 -// Used to visually display/edit some sort of "score" - e.g. 5/10, 3/5, etc. -// setSize(x, y) works a little differently than you might expect: -// * (0, y != 0) - x will be automatically calculated (5*y). -// * (x != 0, 0) - y will be automatically calculated (x/5). -// * (x != 0, y != 0) - you better be sure x = y*5. class RatingComponent : public GuiComponent { public: @@ -40,13 +35,15 @@ public: // Multiply all pixels in the image by this color when rendering. void setColorShift(unsigned int color) override; - unsigned int getColorShift() const override { return mColorShift; }; + unsigned int getColorShift() const override { return mColorShift; } - void setOriginalColor(unsigned int color) override { mColorOriginalValue = color; }; - void setChangedColor(unsigned int color) override { mColorChangedValue = color; }; + void setOriginalColor(unsigned int color) override { mColorOriginalValue = color; } + void setChangedColor(unsigned int color) override { mColorChangedValue = color; } - virtual void applyTheme(const std::shared_ptr& theme, const std::string& view, - const std::string& element, unsigned int properties) override; + virtual void applyTheme(const std::shared_ptr& theme, + const std::string& view, + const std::string& element, + unsigned int properties) override; virtual std::vector getHelpPrompts() override; diff --git a/es-core/src/components/ScrollableContainer.cpp b/es-core/src/components/ScrollableContainer.cpp index f2d12ff54..d025ae89f 100644 --- a/es-core/src/components/ScrollableContainer.cpp +++ b/es-core/src/components/ScrollableContainer.cpp @@ -9,22 +9,21 @@ #include "components/ScrollableContainer.h" +#include "Window.h" #include "animations/LambdaAnimation.h" #include "math/Vector2i.h" #include "renderers/Renderer.h" #include "resources/Font.h" -#include "Window.h" -ScrollableContainer::ScrollableContainer( - Window* window) - : GuiComponent(window), - mAutoScrollDelay(0), - mAutoScrollSpeed(0), - mAutoScrollAccumulator(0), - mScrollPos(0, 0), - mScrollDir(0, 0), - mAutoScrollResetAccumulator(0), - mFontSize(0.0f) +ScrollableContainer::ScrollableContainer(Window* window) + : GuiComponent(window) + , mAutoScrollDelay(0) + , mAutoScrollSpeed(0) + , mAutoScrollAccumulator(0) + , mScrollPos(0, 0) + , mScrollDir(0, 0) + , mAutoScrollResetAccumulator(0) + , mFontSize(0.0f) { // Set the modifier to get equivalent scrolling speed regardless of screen resolution. mResolutionModifier = Renderer::getScreenHeightModifier(); @@ -33,7 +32,8 @@ ScrollableContainer::ScrollableContainer( // For narrower aspect ratios than 16:9 there is a need to set an additional compensation // to get somehow consistent scrolling speeds. float aspectCompensation = static_cast(Renderer::getScreenHeight()) / - static_cast(Renderer::getScreenWidth()) - 0.5625f; + static_cast(Renderer::getScreenWidth()) - + 0.5625f; if (aspectCompensation > 0) mResolutionModifier += aspectCompensation * 4.0f; @@ -42,24 +42,14 @@ ScrollableContainer::ScrollableContainer( mAutoScrollSpeedConstant = AUTO_SCROLL_SPEED; } -Vector2f ScrollableContainer::getScrollPos() const -{ - return mScrollPos; -} - -void ScrollableContainer::setScrollPos(const Vector2f& pos) -{ - mScrollPos = pos; -} - void ScrollableContainer::setAutoScroll(bool autoScroll) { if (autoScroll) { mScrollDir = Vector2f(0, 1); mAutoScrollDelay = static_cast(mAutoScrollDelayConstant); mAutoScrollSpeed = mAutoScrollSpeedConstant; - mAutoScrollSpeed = static_cast(static_cast(mAutoScrollSpeedConstant) / - mResolutionModifier); + mAutoScrollSpeed = + static_cast(static_cast(mAutoScrollSpeedConstant) / mResolutionModifier); reset(); } else { @@ -71,7 +61,8 @@ void ScrollableContainer::setAutoScroll(bool autoScroll) } void ScrollableContainer::setScrollParameters(float autoScrollDelayConstant, - float autoScrollResetDelayConstant, int autoScrollSpeedConstant) + float autoScrollResetDelayConstant, + int autoScrollSpeedConstant) { mAutoScrollResetDelayConstant = autoScrollResetDelayConstant; mAutoScrollDelayConstant = autoScrollDelayConstant; @@ -90,7 +81,7 @@ void ScrollableContainer::update(int deltaTime) { // Don't scroll if the media viewer or screensaver is active or if text scrolling is disabled; if (mWindow->isMediaViewerActive() || mWindow->isScreensaverActive() || - !mWindow->getAllowTextScrolling()) { + !mWindow->getAllowTextScrolling()) { if (mScrollPos != 0 && !mWindow->isLaunchScreenDisplayed()) reset(); return; @@ -105,8 +96,8 @@ void ScrollableContainer::update(int deltaTime) // Also adjust the scrolling speed based on the size of the font. float fontSizeModifier = mSmallFontSize / mFontSize; - adjustedAutoScrollSpeed = static_cast(adjustedAutoScrollSpeed * - fontSizeModifier * fontSizeModifier); + adjustedAutoScrollSpeed = + static_cast(adjustedAutoScrollSpeed * fontSizeModifier * fontSizeModifier); if (adjustedAutoScrollSpeed < 0) adjustedAutoScrollSpeed = 1; @@ -165,11 +156,11 @@ void ScrollableContainer::render(const Transform4x4f& parentTrans) Transform4x4f trans = parentTrans * getTransform(); Vector2i clipPos(static_cast(trans.translation().x()), - static_cast(trans.translation().y())); + static_cast(trans.translation().y())); Vector3f dimScaled = trans * Vector3f(mSize.x(), mSize.y(), 0); Vector2i clipDim(static_cast((dimScaled.x()) - trans.translation().x()), - static_cast((dimScaled.y()) - trans.translation().y())); + static_cast((dimScaled.y()) - trans.translation().y())); Renderer::pushClipRect(clipPos, clipDim); diff --git a/es-core/src/components/ScrollableContainer.h b/es-core/src/components/ScrollableContainer.h index 293d4d598..96d8b17f5 100644 --- a/es-core/src/components/ScrollableContainer.h +++ b/es-core/src/components/ScrollableContainer.h @@ -24,11 +24,13 @@ class ScrollableContainer : public GuiComponent public: ScrollableContainer(Window* window); - Vector2f getScrollPos() const; - void setScrollPos(const Vector2f& pos); + Vector2f getScrollPos() const { return mScrollPos; } + void setScrollPos(const Vector2f& pos) { mScrollPos = pos; } + void setAutoScroll(bool autoScroll); - void setScrollParameters(float autoScrollDelayConstant, float autoScrollResetDelayConstant, - int autoScrollSpeedConstant) override; + void setScrollParameters(float autoScrollDelayConstant, + float autoScrollResetDelayConstant, + int autoScrollSpeedConstant) override; void reset(); void update(int deltaTime) override; diff --git a/es-core/src/components/SliderComponent.cpp b/es-core/src/components/SliderComponent.cpp index 7749fdcc8..247b9fc1e 100644 --- a/es-core/src/components/SliderComponent.cpp +++ b/es-core/src/components/SliderComponent.cpp @@ -14,23 +14,19 @@ #define MOVE_REPEAT_RATE 40 SliderComponent::SliderComponent( - Window* window, - float min, - float max, - float increment, - const std::string& suffix) - : GuiComponent(window), - mMin(min), - mMax(max), - mSingleIncrement(increment), - mMoveRate(0), - mKnob(window), - mSuffix(suffix) + Window* window, float min, float max, float increment, const std::string& suffix) + : GuiComponent(window) + , mMin(min) + , mMax(max) + , mSingleIncrement(increment) + , mMoveRate(0) + , mKnob(window) + , mSuffix(suffix) { assert((min - max) != 0); // Some sane default value. - mValue = (max + min) / 2; + mValue = (max + min) / 2.0f; mKnob.setOrigin(0.5f, 0.5f); mKnob.setImage(":/graphics/slider_knob.svg"); @@ -87,14 +83,15 @@ void SliderComponent::render(const Transform4x4f& parentTrans) if (mValueCache) mFont->renderTextCache(mValueCache.get()); - float width = mSize.x() - mKnob.getSize().x() - - (mValueCache ? mValueCache->metrics.size.x() + - (4 * Renderer::getScreenWidthModifier()) : 0); + float width = + mSize.x() - mKnob.getSize().x() - + (mValueCache ? mValueCache->metrics.size.x() + (4.0f * Renderer::getScreenWidthModifier()) : + 0); // Render line. - const float lineWidth = 2 * Renderer::getScreenHeightModifier();; - Renderer::drawRect(mKnob.getSize().x() / 2, mSize.y() / 2 - - lineWidth / 2, width, lineWidth, 0x777777FF, 0x777777FF); + const float lineWidth = 2.0f * Renderer::getScreenHeightModifier(); + Renderer::drawRect(mKnob.getSize().x() / 2.0f, mSize.y() / 2.0f - lineWidth / 2.0f, width, + lineWidth, 0x777777FF, 0x777777FF); // Render knob. mKnob.render(trans); @@ -113,10 +110,7 @@ void SliderComponent::setValue(float value) onValueChanged(); } -float SliderComponent::getValue() -{ - return mValue; -} +float SliderComponent::getValue() { return mValue; } void SliderComponent::onSizeChanged() { @@ -146,18 +140,20 @@ void SliderComponent::onValueChanged() const std::string max = ss.str(); Vector2f textSize = mFont->sizeText(max); - mValueCache = std::shared_ptr(mFont->buildTextCache(val, mSize.x() - - textSize.x(), (mSize.y() - textSize.y()) / 2, 0x777777FF)); + mValueCache = std::shared_ptr(mFont->buildTextCache( + val, mSize.x() - textSize.x(), (mSize.y() - textSize.y()) / 2.0f, 0x777777FF)); mValueCache->metrics.size[0] = textSize.x(); // Fudge the width. } // Update knob position/size. mKnob.setResize(0, mSize.y() * 0.7f); - float lineLength = mSize.x() - mKnob.getSize().x() - - (mValueCache ? mValueCache->metrics.size.x() + - (4 * Renderer::getScreenWidthModifier()) : 0); - mKnob.setPosition(((mValue - mMin / 2) / mMax) * lineLength + - mKnob.getSize().x() / 2, mSize.y() / 2); + float lineLength = + mSize.x() - mKnob.getSize().x() - + (mValueCache ? mValueCache->metrics.size.x() + (4.0f * Renderer::getScreenWidthModifier()) : + 0); + + mKnob.setPosition(((mValue - mMin / 2.0f) / mMax) * lineLength + mKnob.getSize().x() / 2.0f, + mSize.y() / 2.0f); } std::vector SliderComponent::getHelpPrompts() diff --git a/es-core/src/components/SliderComponent.h b/es-core/src/components/SliderComponent.h index e10c3d913..3b9f7ec86 100644 --- a/es-core/src/components/SliderComponent.h +++ b/es-core/src/components/SliderComponent.h @@ -9,8 +9,8 @@ #ifndef ES_CORE_COMPONENTS_SLIDER_COMPONENT_H #define ES_CORE_COMPONENTS_SLIDER_COMPONENT_H -#include "components/ImageComponent.h" #include "GuiComponent.h" +#include "components/ImageComponent.h" class Font; class TextCache; @@ -20,13 +20,9 @@ class SliderComponent : public GuiComponent { public: // Minimum value (far left of the slider), maximum value (far right of the slider), - // increment size (how much just pressing L/R moves by), unit to display (optional). + // increment size (how much pressing L/R moves by), unit to display (optional). SliderComponent( - Window* window, - float min, - float max, - float increment, - const std::string& suffix = ""); + Window* window, float min, float max, float increment, const std::string& suffix = ""); void setValue(float val); float getValue(); diff --git a/es-core/src/components/SwitchComponent.cpp b/es-core/src/components/SwitchComponent.cpp index 961a0d9cf..18d1010a4 100644 --- a/es-core/src/components/SwitchComponent.cpp +++ b/es-core/src/components/SwitchComponent.cpp @@ -10,31 +10,19 @@ #include "resources/Font.h" -SwitchComponent::SwitchComponent( - Window* window, - bool state) - : GuiComponent(window), - mImage(window), - mState(state), - mOriginalValue(state), - mColorOriginalValue(DEFAULT_COLORSHIFT), - mColorChangedValue(DEFAULT_COLORSHIFT) +SwitchComponent::SwitchComponent(Window* window, bool state) + : GuiComponent(window) + , mImage(window) + , mState(state) + , mOriginalValue(state) + , mColorOriginalValue(DEFAULT_COLORSHIFT) + , mColorChangedValue(DEFAULT_COLORSHIFT) { mImage.setImage(":/graphics/off.svg"); mImage.setResize(0, Font::get(FONT_SIZE_MEDIUM)->getLetterHeight()); mSize = mImage.getSize(); } -void SwitchComponent::onSizeChanged() -{ - mImage.setSize(mSize); -} - -void SwitchComponent::setResize(float width, float height) -{ - mImage.setResize(width, height); -} - bool SwitchComponent::input(InputConfig* config, Input input) { if (config->isMappedTo("a", input) && input.value) { @@ -61,21 +49,13 @@ void SwitchComponent::render(const Transform4x4f& parentTrans) renderChildren(trans); } -bool SwitchComponent::getState() const -{ - return mState; -} - void SwitchComponent::setState(bool state) { mState = state; onStateChanged(); } -std::string SwitchComponent::getValue() const -{ - return mState ? "true" : "false"; -} +std::string SwitchComponent::getValue() const { return mState ? "true" : "false"; } void SwitchComponent::setValue(const std::string& statestring) { @@ -88,26 +68,6 @@ void SwitchComponent::setValue(const std::string& statestring) onStateChanged(); } -unsigned char SwitchComponent::getOpacity() const -{ - return mImage.getOpacity(); -} - -void SwitchComponent::setOpacity(unsigned char opacity) -{ - mImage.setOpacity(opacity); -} - -void SwitchComponent::setColorShift(unsigned int color) -{ - mImage.setColorShift(color); -} - -unsigned int SwitchComponent::getColorShift() const -{ - return mImage.getColorShift(); -} - void SwitchComponent::onStateChanged() { mImage.setImage(mState ? ":/graphics/on.svg" : ":/graphics/off.svg"); diff --git a/es-core/src/components/SwitchComponent.h b/es-core/src/components/SwitchComponent.h index 94f672ead..cc7cadf9d 100644 --- a/es-core/src/components/SwitchComponent.h +++ b/es-core/src/components/SwitchComponent.h @@ -9,8 +9,8 @@ #ifndef ES_CORE_COMPONENTS_SWITCH_COMPONENT_H #define ES_CORE_COMPONENTS_SWITCH_COMPONENT_H -#include "components/ImageComponent.h" #include "GuiComponent.h" +#include "components/ImageComponent.h" // A simple "on/off" switch. class SwitchComponent : public GuiComponent @@ -20,25 +20,25 @@ public: bool input(InputConfig* config, Input input) override; void render(const Transform4x4f& parentTrans) override; - void onSizeChanged() override; + void onSizeChanged() override { mImage.setSize(mSize); } - void setResize(float width, float height) override; + void setResize(float width, float height) override { mImage.setResize(width, height); } - bool getState() const; + bool getState() const { return mState; } void setState(bool state); std::string getValue() const override; void setValue(const std::string& statestring) override; - void setOriginalColor(unsigned int color) override { mColorOriginalValue = color; }; - void setChangedColor(unsigned int color) override { mColorChangedValue = color; }; - void setCallback(const std::function& callbackFunc) { mToggleCallback = callbackFunc; }; + void setOriginalColor(unsigned int color) override { mColorOriginalValue = color; } + void setChangedColor(unsigned int color) override { mColorChangedValue = color; } + void setCallback(const std::function& callbackFunc) { mToggleCallback = callbackFunc; } - unsigned char getOpacity() const override; - void setOpacity(unsigned char opacity) override; + unsigned char getOpacity() const override { return mImage.getOpacity(); } + void setOpacity(unsigned char opacity) override { mImage.setOpacity(opacity); } // Multiply all pixels in the image by this color when rendering. - void setColorShift(unsigned int color) override; + void setColorShift(unsigned int color) override { mImage.setColorShift(color); } - unsigned int getColorShift() const override; + unsigned int getColorShift() const override { return mImage.getColorShift(); } virtual std::vector getHelpPrompts() override; diff --git a/es-core/src/components/TextComponent.cpp b/es-core/src/components/TextComponent.cpp index 02ebc635f..332cc56c4 100644 --- a/es-core/src/components/TextComponent.cpp +++ b/es-core/src/components/TextComponent.cpp @@ -8,49 +8,47 @@ #include "components/TextComponent.h" -#include "utils/StringUtil.h" #include "Log.h" #include "Settings.h" +#include "utils/StringUtil.h" -TextComponent::TextComponent( - Window* window) - : GuiComponent(window), - mFont(Font::get(FONT_SIZE_MEDIUM)), - mUppercase(false), - mColor(0x000000FF), - mAutoCalcExtent(true, true), - mHorizontalAlignment(ALIGN_LEFT), - mVerticalAlignment(ALIGN_CENTER), - mLineSpacing(1.5f), - mNoTopMargin(false), - mBgColor(0), - mMargin(0.0f), - mRenderBackground(false) +TextComponent::TextComponent(Window* window) + : GuiComponent(window) + , mFont(Font::get(FONT_SIZE_MEDIUM)) + , mUppercase(false) + , mColor(0x000000FF) + , mAutoCalcExtent(true, true) + , mHorizontalAlignment(ALIGN_LEFT) + , mVerticalAlignment(ALIGN_CENTER) + , mLineSpacing(1.5f) + , mNoTopMargin(false) + , mBgColor(0) + , mMargin(0.0f) + , mRenderBackground(false) { } -TextComponent::TextComponent( - Window* window, - const std::string& text, - const std::shared_ptr& font, - unsigned int color, - Alignment align, - Vector3f pos, - Vector2f size, - unsigned int bgcolor, - float margin) - : GuiComponent(window), - mFont(nullptr), - mUppercase(false), - mColor(0x000000FF), - mAutoCalcExtent(true, true), - mHorizontalAlignment(align), - mVerticalAlignment(ALIGN_CENTER), - mLineSpacing(1.5f), - mNoTopMargin(false), - mBgColor(0), - mMargin(margin), - mRenderBackground(false) +TextComponent::TextComponent(Window* window, + const std::string& text, + const std::shared_ptr& font, + unsigned int color, + Alignment align, + Vector3f pos, + Vector2f size, + unsigned int bgcolor, + float margin) + : GuiComponent(window) + , mFont(nullptr) + , mUppercase(false) + , mColor(0x000000FF) + , mAutoCalcExtent(true, true) + , mHorizontalAlignment(align) + , mVerticalAlignment(ALIGN_CENTER) + , mLineSpacing(1.5f) + , mNoTopMargin(false) + , mBgColor(0) + , mMargin(margin) + , mRenderBackground(false) { setFont(font); setColor(color); @@ -87,45 +85,30 @@ void TextComponent::setBackgroundColor(unsigned int color) mBgColorOpacity = mBgColor & 0x000000FF; } -void TextComponent::setRenderBackground(bool render) -{ - mRenderBackground = render; -} - // Scale the opacity. void TextComponent::setOpacity(unsigned char opacity) { - // This function is mostly called to do fading in-out of the Text component element. - // Therefore, we assume here that opacity is a fractional value (expressed as an int 0-255), - // of the opacity originally set with setColor() or setBackgroundColor(). - unsigned char o = static_cast(static_cast(opacity) / 255.f * - static_cast(mColorOpacity)); + // This function is mostly called to do fade in and fade out of the text component element. + // Therefore we assume here that opacity is a fractional value (expressed as an unsigned + // char 0 - 255) of the opacity originally set with setColor() or setBackgroundColor(). + unsigned char o = static_cast(static_cast(opacity) / 255.0f * + static_cast(mColorOpacity)); mColor = (mColor & 0xFFFFFF00) | static_cast(o); - unsigned char bgo = static_cast(static_cast(opacity) / 255.f * - static_cast(mBgColorOpacity)); + unsigned char bgo = static_cast(static_cast(opacity) / 255.0f * + static_cast(mBgColorOpacity)); mBgColor = (mBgColor & 0xFFFFFF00) | static_cast(bgo); onColorChanged(); GuiComponent::setOpacity(opacity); } -unsigned char TextComponent::getOpacity() const -{ - return mColor & 0x000000FF; -} - void TextComponent::setText(const std::string& text) { mText = text; onTextChanged(); } -void TextComponent::setHiddenText(const std::string& text) -{ - mHiddenText = text; -} - void TextComponent::setUppercase(bool uppercase) { mUppercase = uppercase; @@ -148,17 +131,21 @@ void TextComponent::render(const Transform4x4f& parentTrans) const Vector2f& textSize = mTextCache->metrics.size; float yOff = 0; switch (mVerticalAlignment) { - case ALIGN_TOP: + case ALIGN_TOP: { yOff = 0; break; - case ALIGN_BOTTOM: + } + case ALIGN_BOTTOM: { yOff = (getSize().y() - textSize.y()); break; - case ALIGN_CENTER: + } + case ALIGN_CENTER: { yOff = (getSize().y() - textSize.y()) / 2.0f; break; - default: + } + default: { break; + } } Vector3f off(0, yOff, 0); @@ -174,22 +161,26 @@ void TextComponent::render(const Transform4x4f& parentTrans) // Draw the text area, where the text actually is located. if (Settings::getInstance()->getBool("DebugText")) { switch (mHorizontalAlignment) { - case ALIGN_LEFT: - Renderer::drawRect(0.0f, 0.0f, mTextCache->metrics.size.x(), - mTextCache->metrics.size.y(), 0x00000033, 0x00000033); - break; - case ALIGN_CENTER: - Renderer::drawRect((mSize.x() - mTextCache->metrics.size.x()) / 2.0f, 0.0f, - mTextCache->metrics.size.x(), mTextCache->metrics.size.y(), - 0x00000033, 0x00000033); - break; - case ALIGN_RIGHT: - Renderer::drawRect(mSize.x() - mTextCache->metrics.size.x(), 0.0f, - mTextCache->metrics.size.x(), mTextCache->metrics.size.y(), - 0x00000033, 0x00000033); - break; - default: - break; + case ALIGN_LEFT: { + Renderer::drawRect(0.0f, 0.0f, mTextCache->metrics.size.x(), + mTextCache->metrics.size.y(), 0x00000033, 0x00000033); + break; + } + case ALIGN_CENTER: { + Renderer::drawRect((mSize.x() - mTextCache->metrics.size.x()) / 2.0f, 0.0f, + mTextCache->metrics.size.x(), mTextCache->metrics.size.y(), + 0x00000033, 0x00000033); + break; + } + case ALIGN_RIGHT: { + Renderer::drawRect(mSize.x() - mTextCache->metrics.size.x(), 0.0f, + mTextCache->metrics.size.x(), mTextCache->metrics.size.y(), + 0x00000033, 0x00000033); + break; + } + default: { + break; + } } } mFont->renderTextCache(mTextCache.get()); @@ -203,8 +194,10 @@ void TextComponent::calculateExtent() } else { if (mAutoCalcExtent.y()) - mSize[1] = mFont->sizeWrappedText(mUppercase ? Utils::String::toUpper(mText) - : mText, getSize().x(), mLineSpacing).y(); + mSize[1] = mFont + ->sizeWrappedText(mUppercase ? Utils::String::toUpper(mText) : mText, + getSize().x(), mLineSpacing) + .y(); } } @@ -246,14 +239,14 @@ void TextComponent::onTextChanged() text.append(abbrev); - mTextCache = std::shared_ptr(f->buildTextCache(text, Vector2f(0, 0), - (mColor >> 8 << 8) | mOpacity, mSize.x(), mHorizontalAlignment, - mLineSpacing, mNoTopMargin)); + mTextCache = std::shared_ptr( + f->buildTextCache(text, Vector2f(0, 0), (mColor >> 8 << 8) | mOpacity, mSize.x(), + mHorizontalAlignment, mLineSpacing, mNoTopMargin)); } else { - mTextCache = std::shared_ptr(f->buildTextCache(f->wrapText( - text, mSize.x()), Vector2f(0, 0), (mColor >> 8 << 8) | mOpacity, mSize.x(), - mHorizontalAlignment, mLineSpacing, mNoTopMargin)); + mTextCache = std::shared_ptr(f->buildTextCache( + f->wrapText(text, mSize.x()), Vector2f(0, 0), (mColor >> 8 << 8) | mOpacity, mSize.x(), + mHorizontalAlignment, mLineSpacing, mNoTopMargin)); } } @@ -269,10 +262,7 @@ void TextComponent::setHorizontalAlignment(Alignment align) onTextChanged(); } -void TextComponent::setVerticalAlignment(Alignment align) -{ - mVerticalAlignment = align; -} +void TextComponent::setVerticalAlignment(Alignment align) { mVerticalAlignment = align; } void TextComponent::setLineSpacing(float spacing) { @@ -286,28 +276,10 @@ void TextComponent::setNoTopMargin(bool margin) onTextChanged(); } -std::string TextComponent::getValue() const -{ - return mText; -} - -void TextComponent::setValue(const std::string& value) -{ - setText(value); -} - -std::string TextComponent::getHiddenValue() const -{ - return mHiddenText; -} - -void TextComponent::setHiddenValue(const std::string& value) -{ - setHiddenText(value); -} - -void TextComponent::applyTheme(const std::shared_ptr& theme, const std::string& view, - const std::string& element, unsigned int properties) +void TextComponent::applyTheme(const std::shared_ptr& theme, + const std::string& view, + const std::string& element, + unsigned int properties) { GuiComponent::applyTheme(theme, view, element, properties); diff --git a/es-core/src/components/TextComponent.h b/es-core/src/components/TextComponent.h index 30070ffb4..52a65d373 100644 --- a/es-core/src/components/TextComponent.h +++ b/es-core/src/components/TextComponent.h @@ -9,8 +9,8 @@ #ifndef ES_CORE_COMPONENTS_TEXT_COMPONENT_H #define ES_CORE_COMPONENTS_TEXT_COMPONENT_H -#include "resources/Font.h" #include "GuiComponent.h" +#include "resources/Font.h" class ThemeData; @@ -25,46 +25,47 @@ class TextComponent : public GuiComponent { public: TextComponent(Window* window); - TextComponent( - Window* window, - const std::string& text, - const std::shared_ptr& font, - unsigned int color = 0x000000FF, - Alignment align = ALIGN_LEFT, - Vector3f pos = Vector3f::Zero(), - Vector2f size = Vector2f::Zero(), - unsigned int bgcolor = 0x00000000, - float margin = 0.0f); + TextComponent(Window* window, + const std::string& text, + const std::shared_ptr& font, + unsigned int color = 0x000000FF, + Alignment align = ALIGN_LEFT, + Vector3f pos = Vector3f::Zero(), + Vector2f size = Vector2f::Zero(), + unsigned int bgcolor = 0x00000000, + float margin = 0.0f); void setFont(const std::shared_ptr& font); void setUppercase(bool uppercase); void onSizeChanged() override; void setText(const std::string& text); - void setHiddenText(const std::string& text); + void setHiddenText(const std::string& text) { mHiddenText = text; } void setColor(unsigned int color) override; void setHorizontalAlignment(Alignment align); void setVerticalAlignment(Alignment align); void setLineSpacing(float spacing); void setNoTopMargin(bool margin); void setBackgroundColor(unsigned int color); - void setRenderBackground(bool render); + void setRenderBackground(bool render) { mRenderBackground = render; } void render(const Transform4x4f& parentTrans) override; - std::string getValue() const override; - void setValue(const std::string& value) override; + std::string getValue() const override { return mText; } + void setValue(const std::string& value) override { setText(value); } - std::string getHiddenValue() const override; - void setHiddenValue(const std::string& value) override; + std::string getHiddenValue() const override { return mHiddenText; } + void setHiddenValue(const std::string& value) override { setHiddenText(value); } - unsigned char getOpacity() const override; + unsigned char getOpacity() const override { return mColor & 0x000000FF; } void setOpacity(unsigned char opacity) override; - virtual void applyTheme(const std::shared_ptr& theme, const std::string& view, - const std::string& element, unsigned int properties) override; + virtual void applyTheme(const std::shared_ptr& theme, + const std::string& view, + const std::string& element, + unsigned int properties) override; - unsigned int getColor() const override { return mColor; }; - inline std::shared_ptr getFont() const override { return mFont; } + unsigned int getColor() const override { return mColor; } + std::shared_ptr getFont() const override { return mFont; } Alignment getHorizontalAlignment() { return mHorizontalAlignment; } Alignment getVerticalAlignment() { return mVerticalAlignment; } @@ -77,7 +78,6 @@ protected: private: void calculateExtent(); - void onColorChanged(); unsigned int mColor; diff --git a/es-core/src/components/TextEditComponent.cpp b/es-core/src/components/TextEditComponent.cpp index 23aeab722..de9bd028d 100644 --- a/es-core/src/components/TextEditComponent.cpp +++ b/es-core/src/components/TextEditComponent.cpp @@ -8,24 +8,23 @@ #include "components/TextEditComponent.h" -#include "resources/Font.h" #include "utils/StringUtil.h" -#define TEXT_PADDING_HORIZ 10 -#define TEXT_PADDING_VERT 2 +#define TEXT_PADDING_HORIZ 10.0f +#define TEXT_PADDING_VERT 2.0f #define CURSOR_REPEAT_START_DELAY 500 #define CURSOR_REPEAT_SPEED 28 // Lower is faster. -TextEditComponent::TextEditComponent( - Window* window) - : GuiComponent(window), - mBox(window, ":/graphics/textinput.svg"), - mFocused(false), - mScrollOffset(0.0f, 0.0f), - mCursor(0), mEditing(false), - mFont(Font::get(FONT_SIZE_MEDIUM, FONT_PATH_LIGHT)), - mCursorRepeatDir(0) +TextEditComponent::TextEditComponent(Window* window) + : GuiComponent(window) + , mBox(window, ":/graphics/textinput.svg") + , mFocused(false) + , mScrollOffset(0.0f, 0.0f) + , mCursor(0) + , mEditing(false) + , mFont(Font::get(FONT_SIZE_MEDIUM, FONT_PATH_LIGHT)) + , mCursorRepeatDir(0) { addChild(&mBox); onFocusLost(); @@ -47,8 +46,9 @@ void TextEditComponent::onFocusLost() void TextEditComponent::onSizeChanged() { - mBox.fitTo(mSize, Vector3f::Zero(), Vector2f(-34 + mResolutionAdjustment, -32 - - (TEXT_PADDING_VERT * Renderer::getScreenHeightModifier()))); + mBox.fitTo(mSize, Vector3f::Zero(), + Vector2f(-34 + mResolutionAdjustment, + -32 - (TEXT_PADDING_VERT * Renderer::getScreenHeightModifier()))); onTextChanged(); // Wrap point probably changed. } @@ -59,11 +59,6 @@ void TextEditComponent::setValue(const std::string& val) onTextChanged(); } -std::string TextEditComponent::getValue() const -{ - return mText; -} - void TextEditComponent::textInput(const std::string& text) { if (mEditing) { @@ -103,33 +98,35 @@ void TextEditComponent::stopEditing() bool TextEditComponent::input(InputConfig* config, Input input) { - bool const cursor_left = (config->getDeviceId() != DEVICE_KEYBOARD && - config->isMappedLike("left", input)) || (config->getDeviceId() == DEVICE_KEYBOARD && - input.id == SDLK_LEFT); - bool const cursor_right = (config->getDeviceId() != DEVICE_KEYBOARD && - config->isMappedLike("right", input)) || (config->getDeviceId() == DEVICE_KEYBOARD && - input.id == SDLK_RIGHT); - bool const cursor_up = (config->getDeviceId() != DEVICE_KEYBOARD && - config->isMappedLike("up", input)) || (config->getDeviceId() == DEVICE_KEYBOARD && - input.id == SDLK_UP); - bool const cursor_down = (config->getDeviceId() != DEVICE_KEYBOARD && - config->isMappedLike("down", input)) || (config->getDeviceId() == DEVICE_KEYBOARD && - input.id == SDLK_DOWN); + bool const cursor_left = + (config->getDeviceId() != DEVICE_KEYBOARD && config->isMappedLike("left", input)) || + (config->getDeviceId() == DEVICE_KEYBOARD && input.id == SDLK_LEFT); + bool const cursor_right = + (config->getDeviceId() != DEVICE_KEYBOARD && config->isMappedLike("right", input)) || + (config->getDeviceId() == DEVICE_KEYBOARD && input.id == SDLK_RIGHT); + bool const cursor_up = + (config->getDeviceId() != DEVICE_KEYBOARD && config->isMappedLike("up", input)) || + (config->getDeviceId() == DEVICE_KEYBOARD && input.id == SDLK_UP); + bool const cursor_down = + (config->getDeviceId() != DEVICE_KEYBOARD && config->isMappedLike("down", input)) || + (config->getDeviceId() == DEVICE_KEYBOARD && input.id == SDLK_DOWN); bool const shoulder_left = (config->isMappedLike("leftshoulder", input)); bool const shoulder_right = (config->isMappedLike("rightshoulder", input)); bool const trigger_left = (config->isMappedLike("lefttrigger", input)); bool const trigger_right = (config->isMappedLike("righttrigger", input)); if (input.value == 0) { - if (cursor_left || cursor_right || cursor_up || cursor_down || - shoulder_left || shoulder_right | trigger_left || trigger_right) + if (cursor_left || cursor_right || cursor_up || cursor_down || shoulder_left || + shoulder_right | trigger_left || trigger_right) { mCursorRepeatDir = 0; + } return false; } - if ((config->isMappedTo("a", input) || (config->getDeviceId() == DEVICE_KEYBOARD && - input.id == SDLK_RETURN)) && mFocused && !mEditing) { + if ((config->isMappedTo("a", input) || + (config->getDeviceId() == DEVICE_KEYBOARD && input.id == SDLK_RETURN)) && + mFocused && !mEditing) { startEditing(); return true; } @@ -146,8 +143,8 @@ bool TextEditComponent::input(InputConfig* config, Input input) // Done editing (accept changes). if ((config->getDeviceId() == DEVICE_KEYBOARD && input.id == SDLK_ESCAPE) || - (config->getDeviceId() != DEVICE_KEYBOARD && (config->isMappedTo("a", input) || - config->isMappedTo("b", input)))) { + (config->getDeviceId() != DEVICE_KEYBOARD && + (config->isMappedTo("a", input) || config->isMappedTo("b", input)))) { mTextOrig = mText; stopEditing(); return true; @@ -181,21 +178,22 @@ bool TextEditComponent::input(InputConfig* config, Input input) } else if (config->getDeviceId() == DEVICE_KEYBOARD) { switch (input.id) { - case SDLK_HOME: - setCursor(0); - break; - - case SDLK_END: - setCursor(std::string::npos); - break; - - case SDLK_DELETE: - if (mCursor < mText.length()) { - // Fake as Backspace one char to the right. - moveCursor(1); - textInput("\b"); + case SDLK_HOME: { + setCursor(0); + break; + } + case SDLK_END: { + setCursor(std::string::npos); + break; + } + case SDLK_DELETE: { + if (mCursor < mText.length()) { + // Fake as Backspace one char to the right. + moveCursor(1); + textInput("\b"); + } + break; } - break; } } // Consume all input when editing text. @@ -241,10 +239,10 @@ void TextEditComponent::setCursor(size_t pos) void TextEditComponent::onTextChanged() { - std::string wrappedText = (isMultiline() ? - mFont->wrapText(mText, getTextAreaSize().x()) : mText); - mTextCache = std::unique_ptr - (mFont->buildTextCache(wrappedText, 0, 0, 0x77777700 | getOpacity())); + std::string wrappedText = + (isMultiline() ? mFont->wrapText(mText, getTextAreaSize().x()) : mText); + mTextCache = std::unique_ptr( + mFont->buildTextCache(wrappedText, 0, 0, 0x77777700 | getOpacity())); if (mCursor > static_cast(mText.length())) mCursor = static_cast(mText.length()); @@ -253,13 +251,14 @@ void TextEditComponent::onTextChanged() void TextEditComponent::onCursorChanged() { if (isMultiline()) { - Vector2f textSize = mFont-> - getWrappedTextCursorOffset(mText, getTextAreaSize().x(), mCursor); + Vector2f textSize = + mFont->getWrappedTextCursorOffset(mText, getTextAreaSize().x(), mCursor); - if (mScrollOffset.y() + getTextAreaSize().y() < textSize.y() + - mFont->getHeight()) // Need to scroll down? + // Need to scroll down? + if (mScrollOffset.y() + getTextAreaSize().y() < textSize.y() + mFont->getHeight()) mScrollOffset[1] = textSize.y() - getTextAreaSize().y() + mFont->getHeight(); - else if (mScrollOffset.y() > textSize.y()) // Need to scroll up? + // Need to scroll up? + else if (mScrollOffset.y() > textSize.y()) mScrollOffset[1] = textSize.y(); } else { @@ -282,11 +281,11 @@ void TextEditComponent::render(const Transform4x4f& parentTrans) trans.translation() += Vector3f(getTextAreaPos().x(), getTextAreaPos().y(), 0); Vector2i clipPos(static_cast(trans.translation().x()), - static_cast(trans.translation().y())); + static_cast(trans.translation().y())); // Use "text area" size for clipping. Vector3f dimScaled = trans * Vector3f(getTextAreaSize().x(), getTextAreaSize().y(), 0); Vector2i clipDim(static_cast((dimScaled.x()) - trans.translation().x()), - static_cast((dimScaled.y()) - trans.translation().y())); + static_cast((dimScaled.y()) - trans.translation().y())); Renderer::pushClipRect(clipPos, clipDim); trans.translate(Vector3f(-mScrollOffset.x(), -mScrollOffset.y(), 0)); @@ -310,28 +309,24 @@ void TextEditComponent::render(const Transform4x4f& parentTrans) } float cursorHeight = mFont->getHeight() * 0.8f; - Renderer::drawRect(cursorPos.x(), cursorPos.y() + (mFont->getHeight() - cursorHeight) / 2, - 2.0f * Renderer::getScreenWidthModifier(), cursorHeight, 0x000000FF, 0x000000FF); + Renderer::drawRect( + cursorPos.x(), cursorPos.y() + (mFont->getHeight() - cursorHeight) / 2.0f, + 2.0f * Renderer::getScreenWidthModifier(), cursorHeight, 0x000000FF, 0x000000FF); } } -bool TextEditComponent::isMultiline() -{ - return (getSize().y() > mFont->getHeight() * 1.25f); -} - Vector2f TextEditComponent::getTextAreaPos() const { - return Vector2f((-mResolutionAdjustment + - (TEXT_PADDING_HORIZ * Renderer::getScreenWidthModifier())) / 2.0f, - (TEXT_PADDING_VERT * Renderer::getScreenHeightModifier()) / 2.0f); + return Vector2f( + (-mResolutionAdjustment + (TEXT_PADDING_HORIZ * Renderer::getScreenWidthModifier())) / 2.0f, + (TEXT_PADDING_VERT * Renderer::getScreenHeightModifier()) / 2.0f); } Vector2f TextEditComponent::getTextAreaSize() const { return Vector2f(mSize.x() + mResolutionAdjustment - - (TEXT_PADDING_HORIZ * Renderer::getScreenWidthModifier()), mSize.y() - - (TEXT_PADDING_VERT * Renderer::getScreenHeightModifier())); + (TEXT_PADDING_HORIZ * Renderer::getScreenWidthModifier()), + mSize.y() - (TEXT_PADDING_VERT * Renderer::getScreenHeightModifier())); } std::vector TextEditComponent::getHelpPrompts() diff --git a/es-core/src/components/TextEditComponent.h b/es-core/src/components/TextEditComponent.h index 1a97a7bbe..9365912a3 100644 --- a/es-core/src/components/TextEditComponent.h +++ b/es-core/src/components/TextEditComponent.h @@ -9,8 +9,9 @@ #ifndef ES_CORE_COMPONENTS_TEXT_EDIT_COMPONENT_H #define ES_CORE_COMPONENTS_TEXT_EDIT_COMPONENT_H -#include "components/NinePatchComponent.h" #include "GuiComponent.h" +#include "components/NinePatchComponent.h" +#include "resources/Font.h" class Font; class TextCache; @@ -32,13 +33,13 @@ public: void onSizeChanged() override; void setValue(const std::string& val) override; - std::string getValue() const override; + std::string getValue() const override { return mText; } void startEditing(); void stopEditing(); - inline bool isEditing() const { return mEditing; }; - inline std::shared_ptr getFont() const override{ return mFont; } + bool isEditing() const { return mEditing; } + std::shared_ptr getFont() const override { return mFont; } void setCursor(size_t pos); @@ -51,7 +52,7 @@ private: void updateCursorRepeat(int deltaTime); void moveCursor(int amt); - bool isMultiline(); + bool isMultiline() { return (getSize().y() > mFont->getHeight() * 1.25f); } Vector2f getTextAreaPos() const; Vector2f getTextAreaSize() const; diff --git a/es-core/src/components/TextListComponent.h b/es-core/src/components/TextListComponent.h index 0eec010a6..f38318a18 100644 --- a/es-core/src/components/TextListComponent.h +++ b/es-core/src/components/TextListComponent.h @@ -9,12 +9,12 @@ #ifndef ES_APP_COMPONENTS_TEXT_LIST_COMPONENT_H #define ES_APP_COMPONENTS_TEXT_LIST_COMPONENT_H +#include "Log.h" +#include "Sound.h" #include "components/IList.h" #include "math/Misc.h" #include "resources/Font.h" #include "utils/StringUtil.h" -#include "Log.h" -#include "Sound.h" #include @@ -26,8 +26,7 @@ struct TextListData { }; // A graphical list. Supports multiple colors for rows and scrolling. -template -class TextListComponent : public IList +template class TextListComponent : public IList { protected: using IList::mEntries; @@ -38,9 +37,6 @@ protected: using IList::mSize; using IList::mCursor; using IList::mWindow; - // The following change is required for compilation with Clang. - // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#2070 - // using IList::Entry; using IList::IList; public: @@ -53,45 +49,51 @@ public: bool input(InputConfig* config, Input input) override; void update(int deltaTime) override; void render(const Transform4x4f& parentTrans) override; - void applyTheme(const std::shared_ptr& theme, const std::string& view, - const std::string& element, unsigned int properties) override; + void applyTheme(const std::shared_ptr& theme, + const std::string& view, + const std::string& element, + unsigned int properties) override; void add(const std::string& name, const T& obj, unsigned int colorId); enum Alignment { - ALIGN_LEFT, + ALIGN_LEFT, // Replace with AllowShortEnumsOnASingleLine: false (clang-format >=11.0). ALIGN_CENTER, ALIGN_RIGHT }; - inline void setAlignment(Alignment align) { mAlignment = align; } + void setAlignment(Alignment align) { mAlignment = align; } - inline void setCursorChangedCallback(const std::function& func) - { mCursorChangedCallback = func; } + void setCursorChangedCallback(const std::function& func) + { + mCursorChangedCallback = func; + } - inline void setFont(const std::shared_ptr& font) + void setFont(const std::shared_ptr& font) { mFont = font; for (auto it = mEntries.begin(); it != mEntries.end(); it++) it->data.textCache.reset(); } - inline void setUppercase(bool /*uppercase*/) + void setUppercase(bool /*uppercase*/) { mUppercase = true; for (auto it = mEntries.begin(); it != mEntries.end(); it++) it->data.textCache.reset(); } - inline void setSelectorHeight(float selectorScale) { mSelectorHeight = selectorScale; } - inline void setSelectorOffsetY(float selectorOffsetY) { mSelectorOffsetY = selectorOffsetY; } - inline void setSelectorColor(unsigned int color) { mSelectorColor = color; } - inline void setSelectorColorEnd(unsigned int color) { mSelectorColorEnd = color; } - inline void setSelectorColorGradientHorizontal(bool horizontal) - { mSelectorColorGradientHorizontal = horizontal; } - inline void setSelectedColor(unsigned int color) { mSelectedColor = color; } - inline void setColor(unsigned int id, unsigned int color) { mColors[id] = color; } - inline void setLineSpacing(float lineSpacing) { mLineSpacing = lineSpacing; } + void setSelectorHeight(float selectorScale) { mSelectorHeight = selectorScale; } + void setSelectorOffsetY(float selectorOffsetY) { mSelectorOffsetY = selectorOffsetY; } + void setSelectorColor(unsigned int color) { mSelectorColor = color; } + void setSelectorColorEnd(unsigned int color) { mSelectorColorEnd = color; } + void setSelectorColorGradientHorizontal(bool horizontal) + { + mSelectorColorGradientHorizontal = horizontal; + } + void setSelectedColor(unsigned int color) { mSelectedColor = color; } + void setColor(unsigned int id, unsigned int color) { mColors[id] = color; } + void setLineSpacing(float lineSpacing) { mLineSpacing = lineSpacing; } protected: virtual void onScroll() override @@ -128,8 +130,9 @@ private: }; template -TextListComponent::TextListComponent(Window* window) : - IList(window), mSelectorImage(window) +TextListComponent::TextListComponent(Window* window) + : IList(window) + , mSelectorImage(window) { mMarqueeOffset = 0; mMarqueeOffset2 = 0; @@ -152,8 +155,7 @@ TextListComponent::TextListComponent(Window* window) : mColors[1] = 0x00FF00FF; } -template -void TextListComponent::render(const Transform4x4f& parentTrans) +template void TextListComponent::render(const Transform4x4f& parentTrans) { if (size() == 0) return; @@ -164,14 +166,14 @@ void TextListComponent::render(const Transform4x4f& parentTrans) int startEntry = 0; float y = 0; - const float entrySize = std::max(font->getHeight(1.0), - static_cast(font->getSize())) * mLineSpacing; + const float entrySize = + std::max(font->getHeight(1.0), static_cast(font->getSize())) * mLineSpacing; // Number of entries that can fit on the screen simultaneously. int screenCount = static_cast(mSize.y() / entrySize + 0.5f); if (size() >= screenCount) { - startEntry = mCursor - screenCount/2; + startEntry = mCursor - screenCount / 2; if (startEntry < 0) startEntry = 0; if (startEntry >= size() - screenCount) @@ -185,36 +187,31 @@ void TextListComponent::render(const Transform4x4f& parentTrans) // Draw selector bar. if (startEntry < listCutoff) { if (mSelectorImage.hasImage()) { - mSelectorImage.setPosition(0.0f, (mCursor - startEntry) * - entrySize + mSelectorOffsetY, 0.0f); + mSelectorImage.setPosition(0.0f, (mCursor - startEntry) * entrySize + mSelectorOffsetY, + 0.0f); mSelectorImage.render(trans); } else { Renderer::setMatrix(trans); - Renderer::drawRect( - 0.0f, - (mCursor - startEntry) * entrySize + mSelectorOffsetY, - mSize.x(), - mSelectorHeight, - mSelectorColor, - mSelectorColorEnd, - mSelectorColorGradientHorizontal); + Renderer::drawRect(0.0f, (mCursor - startEntry) * entrySize + mSelectorOffsetY, + mSize.x(), mSelectorHeight, mSelectorColor, mSelectorColorEnd, + mSelectorColorGradientHorizontal); } } if (Settings::getInstance()->getBool("DebugText")) { - Renderer::drawRect(mHorizontalMargin, 0.0f, mSize.x() - mHorizontalMargin * 2.0f, - mSize.y(), 0x00000033, 0x00000033); + Renderer::drawRect(mHorizontalMargin, 0.0f, mSize.x() - mHorizontalMargin * 2.0f, mSize.y(), + 0x00000033, 0x00000033); Renderer::drawRect(0.0f, 0.0f, mSize.x(), mSize.y(), 0x0000FF33, 0x0000FF33); } // Clip to inside margins. Vector3f dim(mSize.x(), mSize.y(), 0.0f); dim = trans * dim - trans.translation(); - Renderer::pushClipRect(Vector2i(static_cast(trans.translation().x() + - mHorizontalMargin), static_cast(trans.translation().y())), - Vector2i(static_cast(dim.x() - mHorizontalMargin * 2.0f), - static_cast(dim.y()))); + Renderer::pushClipRect( + Vector2i(static_cast(trans.translation().x() + mHorizontalMargin), + static_cast(trans.translation().y())), + Vector2i(static_cast(dim.x() - mHorizontalMargin * 2.0f), static_cast(dim.y()))); for (int i = startEntry; i < listCutoff; i++) { typename IList::Entry& entry = mEntries.at(static_cast(i)); @@ -226,9 +223,8 @@ void TextListComponent::render(const Transform4x4f& parentTrans) color = mColors[entry.data.colorId]; if (!entry.data.textCache) - entry.data.textCache = std::unique_ptr( - font->buildTextCache(mUppercase ? - Utils::String::toUpper(entry.name) : entry.name, 0, 0, 0x000000FF)); + entry.data.textCache = std::unique_ptr(font->buildTextCache( + mUppercase ? Utils::String::toUpper(entry.name) : entry.name, 0, 0, 0x000000FF)); // If a game is marked as hidden, lower the text opacity a lot. // If a game is marked to not be counted, lower the opacity a moderate amount. @@ -242,21 +238,21 @@ void TextListComponent::render(const Transform4x4f& parentTrans) Vector3f offset(0.0f, y, 0.0f); switch (mAlignment) { - case ALIGN_LEFT: - offset[0] = mHorizontalMargin; - break; - case ALIGN_CENTER: - offset[0] = static_cast((mSize.x() - - entry.data.textCache->metrics.size.x()) / 2.0f); - if (offset[0] < mHorizontalMargin) + case ALIGN_LEFT: offset[0] = mHorizontalMargin; - break; - case ALIGN_RIGHT: - offset[0] = (mSize.x() - entry.data.textCache->metrics.size.x()); - offset[0] -= mHorizontalMargin; - if (offset[0] < mHorizontalMargin) - offset[0] = mHorizontalMargin; - break; + break; + case ALIGN_CENTER: + offset[0] = + static_cast((mSize.x() - entry.data.textCache->metrics.size.x()) / 2.0f); + if (offset[0] < mHorizontalMargin) + offset[0] = mHorizontalMargin; + break; + case ALIGN_RIGHT: + offset[0] = (mSize.x() - entry.data.textCache->metrics.size.x()); + offset[0] -= mHorizontalMargin; + if (offset[0] < mHorizontalMargin) + offset[0] = mHorizontalMargin; + break; } // Render text. @@ -291,8 +287,7 @@ void TextListComponent::render(const Transform4x4f& parentTrans) GuiComponent::renderChildren(trans); } -template -bool TextListComponent::input(InputConfig* config, Input input) +template bool TextListComponent::input(InputConfig* config, Input input) { if (size() > 0) { if (input.value != 0) { @@ -324,12 +319,11 @@ bool TextListComponent::input(InputConfig* config, Input input) } } else { - if (config->isMappedLike("down", input) || - config->isMappedLike("up", input) || - config->isMappedLike("rightshoulder", input) || - config->isMappedLike("leftshoulder", input) || - config->isMappedLike("lefttrigger", input) || - config->isMappedLike("righttrigger", input)) + if (config->isMappedLike("down", input) || config->isMappedLike("up", input) || + config->isMappedLike("rightshoulder", input) || + config->isMappedLike("leftshoulder", input) || + config->isMappedLike("lefttrigger", input) || + config->isMappedLike("righttrigger", input)) stopScrolling(); } } @@ -337,8 +331,7 @@ bool TextListComponent::input(InputConfig* config, Input input) return GuiComponent::input(config, input); } -template -void TextListComponent::update(int deltaTime) +template void TextListComponent::update(int deltaTime) { listUpdate(deltaTime); @@ -351,8 +344,10 @@ void TextListComponent::update(int deltaTime) mMarqueeOffset2 = 0; // If we're not scrolling and this object's text exceeds our size, then marquee it. - const float textLength = mFont->sizeText(Utils::String::toUpper( - mEntries.at(static_cast(mCursor)).name)).x(); + const float textLength = mFont + ->sizeText(Utils::String::toUpper( + mEntries.at(static_cast(mCursor)).name)) + .x(); const float limit = mSize.x() - mHorizontalMargin * 2.0f; if (textLength > limit) { @@ -371,7 +366,8 @@ void TextListComponent::update(int deltaTime) mMarqueeTime -= maxTime; mMarqueeOffset = static_cast(Math::Scroll::loop(delay, scrollTime + returnTime, - static_cast(mMarqueeTime), scrollLength + returnLength)); + static_cast(mMarqueeTime), + scrollLength + returnLength)); if (mMarqueeOffset > (scrollLength - (limit - returnLength))) mMarqueeOffset2 = static_cast(mMarqueeOffset - (scrollLength + returnLength)); @@ -394,8 +390,7 @@ void TextListComponent::add(const std::string& name, const T& obj, unsigned i static_cast*>(this)->add(entry); } -template -void TextListComponent::onCursorChanged(const CursorState& state) +template void TextListComponent::onCursorChanged(const CursorState& state) { mMarqueeOffset = 0; mMarqueeOffset2 = 0; @@ -407,7 +402,9 @@ void TextListComponent::onCursorChanged(const CursorState& state) template void TextListComponent::applyTheme(const std::shared_ptr& theme, - const std::string& view, const std::string& element, unsigned int properties) + const std::string& view, + const std::string& element, + unsigned int properties) { GuiComponent::applyTheme(theme, view, element, properties); @@ -424,8 +421,8 @@ void TextListComponent::applyTheme(const std::shared_ptr& theme, if (elem->has("selectorColorEnd")) setSelectorColorEnd(elem->get("selectorColorEnd")); if (elem->has("selectorGradientType")) - setSelectorColorGradientHorizontal(!(elem->get - ("selectorGradientType").compare("horizontal"))); + setSelectorColorGradientHorizontal( + !(elem->get("selectorGradientType").compare("horizontal"))); if (elem->has("selectedColor")) setSelectedColor(elem->get("selectedColor")); if (elem->has("primaryColor")) @@ -435,8 +432,8 @@ void TextListComponent::applyTheme(const std::shared_ptr& theme, } setFont(Font::getFromTheme(elem, properties, mFont)); - const float selectorHeight = std::max(mFont->getHeight(1.0), - static_cast(mFont->getSize())) * mLineSpacing; + const float selectorHeight = + std::max(mFont->getHeight(1.0), static_cast(mFont->getSize())) * mLineSpacing; setSelectorHeight(selectorHeight); if (properties & ALIGNMENT) { @@ -453,8 +450,8 @@ void TextListComponent::applyTheme(const std::shared_ptr& theme, } if (elem->has("horizontalMargin")) { mHorizontalMargin = elem->get("horizontalMargin") * - (this->mParent ? this->mParent->getSize().x() : - static_cast(Renderer::getScreenWidth())); + (this->mParent ? this->mParent->getSize().x() : + static_cast(Renderer::getScreenWidth())); } } @@ -468,7 +465,7 @@ void TextListComponent::applyTheme(const std::shared_ptr& theme, setSelectorHeight(elem->get("selectorHeight") * Renderer::getScreenHeight()); if (elem->has("selectorOffsetY")) { float scale = this->mParent ? this->mParent->getSize().y() : - static_cast(Renderer::getScreenHeight()); + static_cast(Renderer::getScreenHeight()); setSelectorOffsetY(elem->get("selectorOffsetY") * scale); } else { diff --git a/es-core/src/components/VideoComponent.cpp b/es-core/src/components/VideoComponent.cpp index b7326be51..4ca19cc8e 100644 --- a/es-core/src/components/VideoComponent.cpp +++ b/es-core/src/components/VideoComponent.cpp @@ -8,39 +8,38 @@ #include "components/VideoComponent.h" -#include "resources/ResourceManager.h" -#include "utils/FileSystemUtil.h" #include "ThemeData.h" #include "Window.h" +#include "resources/ResourceManager.h" +#include "utils/FileSystemUtil.h" #include #define SCREENSAVER_FADE_IN_TIME 1100 #define MEDIA_VIEWER_FADE_IN_TIME 600 -VideoComponent::VideoComponent( - Window* window) - : GuiComponent(window), - mWindow(window), - mStaticImage(window), - mVideoHeight(0), - mVideoWidth(0), - mStartDelayed(false), - mIsPlaying(false), - mIsActuallyPlaying(false), - mPause(false), - mShowing(false), - mDisable(false), - mMediaViewerMode(false), - mScreensaverActive(false), - mScreensaverMode(false), - mGameLaunched(false), - mBlockPlayer(false), - mTargetIsMax(false), - mFadeIn(1.0), - mTargetSize(0, 0), - mVideoAreaPos(0, 0), - mVideoAreaSize(0, 0) +VideoComponent::VideoComponent(Window* window) + : GuiComponent(window) + , mWindow(window) + , mStaticImage(window) + , mVideoHeight(0) + , mVideoWidth(0) + , mStartDelayed(false) + , mIsPlaying(false) + , mIsActuallyPlaying(false) + , mPause(false) + , mShowing(false) + , mDisable(false) + , mMediaViewerMode(false) + , mScreensaverActive(false) + , mScreensaverMode(false) + , mGameLaunched(false) + , mBlockPlayer(false) + , mTargetIsMax(false) + , mFadeIn(1.0) + , mTargetSize(0, 0) + , mVideoAreaPos(0, 0) + , mVideoAreaSize(0, 0) { // Setup the default configuration. mConfig.showSnapshotDelay = false; @@ -79,11 +78,6 @@ bool VideoComponent::setVideo(std::string path) return false; } -void VideoComponent::setDefaultVideo() -{ - setVideo(mConfig.defaultVideoPath); -} - void VideoComponent::setImage(std::string path) { // Check that the image has changed. @@ -94,21 +88,6 @@ void VideoComponent::setImage(std::string path) mStaticImagePath = path; } -void VideoComponent::setScreensaverMode(bool isScreensaver) -{ - mScreensaverMode = isScreensaver; -} - -void VideoComponent::setMediaViewerMode(bool isMediaViewer) -{ - mMediaViewerMode = isMediaViewer; -} - -void VideoComponent::setOpacity(unsigned char opacity) -{ - mOpacity = opacity; -} - void VideoComponent::onShow() { mBlockPlayer = false; @@ -192,21 +171,6 @@ void VideoComponent::topWindow(bool isTop) manageState(); } -void VideoComponent::onOriginChanged() -{ - mStaticImage.setOrigin(mOrigin); -} - -void VideoComponent::onPositionChanged() -{ - mStaticImage.setPosition(mPosition); -} - -void VideoComponent::onSizeChanged() -{ - mStaticImage.onSizeChanged(); -} - void VideoComponent::render(const Transform4x4f& parentTrans) { if (!isVisible()) @@ -237,19 +201,22 @@ void VideoComponent::renderSnapshot(const Transform4x4f& parentTrans) // set to start playing the video immediately. Although this may seem a bit inconsistent it // simply looks better than leaving an empty space where the video would have been located. if (mWindow->getGuiStackSize() > 1 || (mConfig.showSnapshotNoVideo && mVideoPath.empty()) || - (mStartDelayed && mConfig.showSnapshotDelay)) { + (mStartDelayed && mConfig.showSnapshotDelay)) { mStaticImage.setOpacity(mOpacity); mStaticImage.render(parentTrans); } } -void VideoComponent::applyTheme(const std::shared_ptr& theme, const std::string& view, - const std::string& element, unsigned int properties) +void VideoComponent::applyTheme(const std::shared_ptr& theme, + const std::string& view, + const std::string& element, + unsigned int properties) { using namespace ThemeFlags; - GuiComponent::applyTheme(theme, view, element, (properties ^ ThemeFlags::SIZE) | - ((properties & (ThemeFlags::SIZE | POSITION)) ? ORIGIN : 0)); + GuiComponent::applyTheme(theme, view, element, + (properties ^ ThemeFlags::SIZE) | + ((properties & (ThemeFlags::SIZE | POSITION)) ? ORIGIN : 0)); const ThemeData::ThemeElement* elem = theme->getElement(view, element, "video"); @@ -257,8 +224,8 @@ void VideoComponent::applyTheme(const std::shared_ptr& theme, const s return; Vector2f scale = getParent() ? getParent()->getSize() : - Vector2f(static_cast(Renderer::getScreenWidth()), - static_cast(Renderer::getScreenHeight())); + Vector2f(static_cast(Renderer::getScreenWidth()), + static_cast(Renderer::getScreenHeight())); if (properties & ThemeFlags::SIZE) { if (elem->has("size")) { @@ -308,12 +275,12 @@ void VideoComponent::update(int deltaTime) // Fade in videos, the time period is a bit different between the screensaver, // media viewer and gamelist view. if (mScreensaverMode && mFadeIn < 1.0f) { - mFadeIn = Math::clamp(mFadeIn + (deltaTime / - static_cast(SCREENSAVER_FADE_IN_TIME)), 0.0f, 1.0f); + mFadeIn = Math::clamp(mFadeIn + (deltaTime / static_cast(SCREENSAVER_FADE_IN_TIME)), + 0.0f, 1.0f); } else if (mMediaViewerMode && mFadeIn < 1.0f) { - mFadeIn = Math::clamp(mFadeIn + (deltaTime / - static_cast(MEDIA_VIEWER_FADE_IN_TIME)), 0.0f, 1.0f); + mFadeIn = Math::clamp(mFadeIn + (deltaTime / static_cast(MEDIA_VIEWER_FADE_IN_TIME)), + 0.0f, 1.0f); } else if (mFadeIn < 1.0f) { mFadeIn = Math::clamp(mFadeIn + 0.01f, 0.0f, 1.0f); diff --git a/es-core/src/components/VideoComponent.h b/es-core/src/components/VideoComponent.h index 5905971aa..8a7653cc5 100644 --- a/es-core/src/components/VideoComponent.h +++ b/es-core/src/components/VideoComponent.h @@ -9,8 +9,8 @@ #ifndef ES_CORE_COMPONENTS_VIDEO_COMPONENT_H #define ES_CORE_COMPONENTS_VIDEO_COMPONENT_H -#include "components/ImageComponent.h" #include "GuiComponent.h" +#include "components/ImageComponent.h" #include @@ -34,15 +34,15 @@ public: // Loads the video at the given filepath. bool setVideo(std::string path); // Configures the component to show the default video. - void setDefaultVideo(); + void setDefaultVideo() { setVideo(mConfig.defaultVideoPath); } // Loads a static image that is displayed if the video cannot be played. void setImage(std::string path); // Sets whether we're in media viewer mode. - void setMediaViewerMode(bool isMediaViewer); + void setMediaViewerMode(bool isMediaViewer) { mMediaViewerMode = isMediaViewer; } // Sets whether we're in screensaver mode. - void setScreensaverMode(bool isScreensaver); + void setScreensaverMode(bool isScreensaver) { mScreensaverMode = isScreensaver; } // Set the opacity for the embedded static image. - void setOpacity(unsigned char opacity) override; + void setOpacity(unsigned char opacity) override { mOpacity = opacity; } virtual void onShow() override; virtual void onHide() override; @@ -57,15 +57,17 @@ public: virtual void topWindow(bool isTop) override; // These functions update the embedded static image. - void onOriginChanged() override; - void onPositionChanged() override; - void onSizeChanged() override; + void onOriginChanged() override { mStaticImage.setOrigin(mOrigin); } + void onPositionChanged() override { mStaticImage.setPosition(mPosition); } + void onSizeChanged() override { mStaticImage.onSizeChanged(); } void render(const Transform4x4f& parentTrans) override; void renderSnapshot(const Transform4x4f& parentTrans); - virtual void applyTheme(const std::shared_ptr& theme, const std::string& view, - const std::string& element, unsigned int properties) override; + virtual void applyTheme(const std::shared_ptr& theme, + const std::string& view, + const std::string& element, + unsigned int properties) override; virtual std::vector getHelpPrompts() override; @@ -76,24 +78,24 @@ public: // zero, no resizing. This can be set before or after a video is loaded. // setMaxSize() and setResize() are mutually exclusive. virtual void setResize(float width, float height) override = 0; - inline void setResize(const Vector2f& size) { setResize(size.x(), size.y()); } + void setResize(const Vector2f& size) { setResize(size.x(), size.y()); } // Resize the video to be as large as possible but fit within a box of this size. // This can be set before or after a video is loaded. // Never breaks the aspect ratio. setMaxSize() and setResize() are mutually exclusive. virtual void setMaxSize(float width, float height) = 0; - inline void setMaxSize(const Vector2f& size) { setMaxSize(size.x(), size.y()); } + void setMaxSize(const Vector2f& size) { setMaxSize(size.x(), size.y()); } private: // Start the video immediately. - virtual void startVideo() {}; + virtual void startVideo() {} // Stop the video. - virtual void stopVideo() {}; + virtual void stopVideo() {} // Pause the video when a game has been launched. - virtual void pauseVideo() {}; + virtual void pauseVideo() {} // Handle looping of the video. Must be called periodically. - virtual void handleLooping() {}; - virtual void updatePlayer() {}; + virtual void handleLooping() {} + virtual void updatePlayer() {} // Start the video after any configured delay. void startVideoWithDelay(); diff --git a/es-core/src/components/VideoFFmpegComponent.cpp b/es-core/src/components/VideoFFmpegComponent.cpp index ef64069fc..120d24c40 100644 --- a/es-core/src/components/VideoFFmpegComponent.cpp +++ b/es-core/src/components/VideoFFmpegComponent.cpp @@ -8,48 +8,44 @@ #include "components/VideoFFmpegComponent.h" -#include "resources/TextureResource.h" #include "AudioManager.h" #include "Settings.h" #include "Window.h" +#include "resources/TextureResource.h" #define DEBUG_VIDEO false -VideoFFmpegComponent::VideoFFmpegComponent( - Window* window) - : VideoComponent(window), - mFrameProcessingThread(nullptr), - mFormatContext(nullptr), - mVideoStream(nullptr), - mAudioStream(nullptr), - mVideoCodec(nullptr), - mAudioCodec(nullptr), - mVideoCodecContext(nullptr), - mAudioCodecContext(nullptr), - mVBufferSrcContext(nullptr), - mVBufferSinkContext(nullptr), - mVFilterGraph(nullptr), - mVFilterInputs(nullptr), - mVFilterOutputs(nullptr), - mABufferSrcContext(nullptr), - mABufferSinkContext(nullptr), - mAFilterGraph(nullptr), - mAFilterInputs(nullptr), - mAFilterOutputs(nullptr), - mVideoTimeBase(0.0l), - mVideoTargetQueueSize(0), - mAudioTargetQueueSize(0), - mAccumulatedTime(0), - mStartTimeAccumulation(false), - mDecodedFrame(false), - mEndOfVideo(false) +VideoFFmpegComponent::VideoFFmpegComponent(Window* window) + : VideoComponent(window) + , mFrameProcessingThread(nullptr) + , mFormatContext(nullptr) + , mVideoStream(nullptr) + , mAudioStream(nullptr) + , mVideoCodec(nullptr) + , mAudioCodec(nullptr) + , mVideoCodecContext(nullptr) + , mAudioCodecContext(nullptr) + , mVBufferSrcContext(nullptr) + , mVBufferSinkContext(nullptr) + , mVFilterGraph(nullptr) + , mVFilterInputs(nullptr) + , mVFilterOutputs(nullptr) + , mABufferSrcContext(nullptr) + , mABufferSinkContext(nullptr) + , mAFilterGraph(nullptr) + , mAFilterInputs(nullptr) + , mAFilterOutputs(nullptr) + , mVideoTimeBase(0.0l) + , mVideoTargetQueueSize(0) + , mAudioTargetQueueSize(0) + , mAccumulatedTime(0) + , mStartTimeAccumulation(false) + , mDecodedFrame(false) + , mEndOfVideo(false) { } -VideoFFmpegComponent::~VideoFFmpegComponent() -{ - stopVideo(); -} +VideoFFmpegComponent::~VideoFFmpegComponent() { stopVideo(); } void VideoFFmpegComponent::setResize(float width, float height) { @@ -96,7 +92,6 @@ void VideoFFmpegComponent::resize() mSize[1] = std::round(mSize[1]); mSize[0] = (mSize[1] / textureSize.y()) * textureSize.x(); - } else { // If both components are set, we just stretch. @@ -127,8 +122,8 @@ void VideoFFmpegComponent::render(const Transform4x4f& parentTrans) unsigned int color; if (mDecodedFrame && mFadeIn < 1) { const unsigned int fadeIn = static_cast(mFadeIn * 255.0f); - color = Renderer::convertRGBAToABGR((fadeIn << 24) | - (fadeIn << 16) | (fadeIn << 8) | 255); + color = + Renderer::convertRGBAToABGR((fadeIn << 24) | (fadeIn << 16) | (fadeIn << 8) | 255); } else { color = 0xFFFFFFFF; @@ -139,13 +134,16 @@ void VideoFFmpegComponent::render(const Transform4x4f& parentTrans) // Render the black rectangle behind the video. if (mVideoRectangleCoords.size() == 4) { Renderer::drawRect(mVideoRectangleCoords[0], mVideoRectangleCoords[1], - mVideoRectangleCoords[2], mVideoRectangleCoords[3], 0x000000FF, 0x000000FF); + mVideoRectangleCoords[2], mVideoRectangleCoords[3], // Line break. + 0x000000FF, 0x000000FF); } + // clang-format off vertices[0] = { { 0.0f , 0.0f }, { 0.0f, 0.0f }, color }; vertices[1] = { { 0.0f , mSize.y() }, { 0.0f, 1.0f }, color }; vertices[2] = { { mSize.x(), 0.0f }, { 1.0f, 0.0f }, color }; vertices[3] = { { mSize.x(), mSize.y() }, { 1.0f, 1.0f }, color }; + // clang-format on // Round vertices. for (int i = 0; i < 4; i++) @@ -167,8 +165,8 @@ void VideoFFmpegComponent::render(const Transform4x4f& parentTrans) int pictureHeight = 0; if (pictureSize > 0) { - tempPictureRGBA.insert(tempPictureRGBA.begin(), - mOutputPicture.pictureRGBA.begin(), mOutputPicture.pictureRGBA.end()); + tempPictureRGBA.insert(tempPictureRGBA.begin(), mOutputPicture.pictureRGBA.begin(), + mOutputPicture.pictureRGBA.end()); pictureWidth = mOutputPicture.width; pictureHeight = mOutputPicture.height; @@ -188,14 +186,14 @@ void VideoFFmpegComponent::render(const Transform4x4f& parentTrans) mTexture->bind(); - #if defined(USE_OPENGL_21) +#if defined(USE_OPENGL_21) // Render scanlines if this option is enabled. However, if this is the media viewer // or the video screensaver, then skip this as the scanline rendering is then handled // in those modules as a postprocessing step. if ((!mScreensaverMode && !mMediaViewerMode) && - Settings::getInstance()->getBool("GamelistVideoScanlines")) + Settings::getInstance()->getBool("GamelistVideoScanlines")) vertices[0].shaders = Renderer::SHADER_SCANLINES; - #endif +#endif // Render it. Renderer::setMatrix(trans); @@ -215,16 +213,17 @@ void VideoFFmpegComponent::updatePlayer() mAudioMutex.lock(); if (mOutputAudio.size()) { AudioManager::getInstance()->processStream(&mOutputAudio.at(0), - static_cast(mOutputAudio.size())); + static_cast(mOutputAudio.size())); mOutputAudio.clear(); } mAudioMutex.unlock(); if (mIsActuallyPlaying && mStartTimeAccumulation) { - mAccumulatedTime += static_cast( - std::chrono::duration_cast - (std::chrono::high_resolution_clock::now() - - mTimeReference).count()) / 1000000000.0l; + mAccumulatedTime += + static_cast(std::chrono::duration_cast( + std::chrono::high_resolution_clock::now() - mTimeReference) + .count()) / + 1000000000.0l; } mTimeReference = std::chrono::high_resolution_clock::now(); @@ -232,7 +231,7 @@ void VideoFFmpegComponent::updatePlayer() if (!mFrameProcessingThread) { AudioManager::getInstance()->unmuteStream(); mFrameProcessingThread = - std::make_unique(&VideoFFmpegComponent::frameProcessing, this); + std::make_unique(&VideoFFmpegComponent::frameProcessing, this); } } @@ -291,7 +290,7 @@ bool VideoFFmpegComponent::setupVideoFilters() if (!(mVFilterGraph = avfilter_graph_alloc())) { LOG(LogError) << "VideoFFmpegComponent::setupVideoFilters(): " - "Couldn't allocate filter graph"; + "Couldn't allocate filter graph"; return false; } @@ -302,14 +301,14 @@ bool VideoFFmpegComponent::setupVideoFilters() const AVFilter* bufferSrc = avfilter_get_by_name("buffer"); if (!bufferSrc) { LOG(LogError) << "VideoFFmpegComponent::setupVideoFilters(): " - "Couldn't find \"buffer\" filter"; + "Couldn't find \"buffer\" filter"; return false; } const AVFilter* bufferSink = avfilter_get_by_name("buffersink"); if (!bufferSink) { LOG(LogError) << "VideoFFmpegComponent::setupVideoFilters(): " - "Couldn't find \"buffersink\" filter"; + "Couldn't find \"buffersink\" filter"; return false; } @@ -322,41 +321,30 @@ bool VideoFFmpegComponent::setupVideoFilters() width += 16 - modulo; std::string filterArguments = - "width=" + std::to_string(width) + ":" + - "height=" + std::to_string(height) + - ":pix_fmt=" + av_get_pix_fmt_name(mVideoCodecContext->pix_fmt) + - ":time_base=" + std::to_string(mVideoStream->time_base.num) + "/" + - std::to_string(mVideoStream->time_base.den) + - ":sar=" + std::to_string(mVideoCodecContext->sample_aspect_ratio.num) + "/" + - std::to_string(mVideoCodecContext->sample_aspect_ratio.den); + "width=" + std::to_string(width) + ":" + "height=" + std::to_string(height) + + ":pix_fmt=" + av_get_pix_fmt_name(mVideoCodecContext->pix_fmt) + + ":time_base=" + std::to_string(mVideoStream->time_base.num) + "/" + + std::to_string(mVideoStream->time_base.den) + + ":sar=" + std::to_string(mVideoCodecContext->sample_aspect_ratio.num) + "/" + + std::to_string(mVideoCodecContext->sample_aspect_ratio.den); - returnValue = avfilter_graph_create_filter( - &mVBufferSrcContext, - bufferSrc, - "in", - filterArguments.c_str(), - nullptr, - mVFilterGraph); + returnValue = avfilter_graph_create_filter(&mVBufferSrcContext, bufferSrc, "in", + filterArguments.c_str(), nullptr, mVFilterGraph); if (returnValue < 0) { LOG(LogError) << "VideoFFmpegComponent::setupVideoFilters(): " - "Couldn't create filter instance for buffer source: " << - av_make_error_string(errorMessage, sizeof(errorMessage), returnValue); + "Couldn't create filter instance for buffer source: " + << av_make_error_string(errorMessage, sizeof(errorMessage), returnValue); return false; } - returnValue = avfilter_graph_create_filter( - &mVBufferSinkContext, - bufferSink, - "out", - nullptr, - nullptr, - mVFilterGraph); + returnValue = avfilter_graph_create_filter(&mVBufferSinkContext, bufferSink, "out", nullptr, + nullptr, mVFilterGraph); if (returnValue < 0) { LOG(LogError) << "VideoFFmpegComponent::setupVideoFilters(): " - "Couldn't create filter instance for buffer sink: " << - av_make_error_string(errorMessage, sizeof(errorMessage), returnValue); + "Couldn't create filter instance for buffer sink: " + << av_make_error_string(errorMessage, sizeof(errorMessage), returnValue); return false; } @@ -376,34 +364,32 @@ bool VideoFFmpegComponent::setupVideoFilters() // Whether to upscale the frame rate to 60 FPS. if (Settings::getInstance()->getBool("VideoUpscaleFrameRate")) { if (modulo > 0) - filterDescription = - "scale=width=" + std::to_string(width) + - ":height=" + std::to_string(height) + - ",fps=fps=60,"; + filterDescription = "scale=width=" + std::to_string(width) + + ":height=" + std::to_string(height) + ",fps=fps=60,"; else filterDescription = "fps=fps=60,"; // The "framerate" filter is a more advanced way to upscale the frame rate using // interpolation. However I have not been able to get this to work with slice // threading so the performance is poor. As such it's disabled for now. -// if (modulo > 0) -// filterDescription = -// "scale=width=" + std::to_string(width) + -// ":height=" + std::to_string(height) + -// ",framerate=fps=60,"; -// else -// filterDescription = "framerate=fps=60,"; + // if (modulo > 0) + // filterDescription = + // "scale=width=" + std::to_string(width) + + // ":height=" + std::to_string(height) + + // ",framerate=fps=60,"; + // else + // filterDescription = "framerate=fps=60,"; } filterDescription += "format=pix_fmts=" + std::string(av_get_pix_fmt_name(outPixFormats[0])); returnValue = avfilter_graph_parse_ptr(mVFilterGraph, filterDescription.c_str(), - &mVFilterInputs, &mVFilterOutputs, nullptr); + &mVFilterInputs, &mVFilterOutputs, nullptr); if (returnValue < 0) { LOG(LogError) << "VideoFFmpegComponent::setupVideoFilters(): " - "Couldn't add graph filter: " << - av_make_error_string(errorMessage, sizeof(errorMessage), returnValue); + "Couldn't add graph filter: " + << av_make_error_string(errorMessage, sizeof(errorMessage), returnValue); return false; } @@ -411,8 +397,8 @@ bool VideoFFmpegComponent::setupVideoFilters() if (returnValue < 0) { LOG(LogError) << "VideoFFmpegComponent::setupVideoFilters(): " - "Couldn't configure graph: " << - av_make_error_string(errorMessage, sizeof(errorMessage), returnValue); + "Couldn't configure graph: " + << av_make_error_string(errorMessage, sizeof(errorMessage), returnValue); return false; } @@ -431,7 +417,7 @@ bool VideoFFmpegComponent::setupAudioFilters() if (!(mAFilterGraph = avfilter_graph_alloc())) { LOG(LogError) << "VideoFFmpegComponent::setupAudioFilters(): " - "Couldn't allocate filter graph"; + "Couldn't allocate filter graph"; return false; } @@ -442,55 +428,45 @@ bool VideoFFmpegComponent::setupAudioFilters() const AVFilter* bufferSrc = avfilter_get_by_name("abuffer"); if (!bufferSrc) { LOG(LogError) << "VideoFFmpegComponent::setupAudioFilters(): " - "Couldn't find \"abuffer\" filter"; + "Couldn't find \"abuffer\" filter"; return false; } const AVFilter* bufferSink = avfilter_get_by_name("abuffersink"); if (!bufferSink) { LOG(LogError) << "VideoFFmpegComponent::setupAudioFilters(): " - "Couldn't find \"abuffersink\" filter"; + "Couldn't find \"abuffersink\" filter"; return false; } char channelLayout[512]; - av_get_channel_layout_string(channelLayout, sizeof(channelLayout), - mAudioCodecContext->channels, mAudioCodecContext->channel_layout); + av_get_channel_layout_string(channelLayout, sizeof(channelLayout), mAudioCodecContext->channels, + mAudioCodecContext->channel_layout); std::string filterArguments = - "time_base=" + std::to_string(mAudioStream->time_base.num) + "/" + - std::to_string(mAudioStream->time_base.den) + - ":sample_rate=" + std::to_string(mAudioCodecContext->sample_rate) + - ":sample_fmt=" + av_get_sample_fmt_name(mAudioCodecContext->sample_fmt) + - ":channel_layout=" + channelLayout; + "time_base=" + std::to_string(mAudioStream->time_base.num) + "/" + + std::to_string(mAudioStream->time_base.den) + + ":sample_rate=" + std::to_string(mAudioCodecContext->sample_rate) + + ":sample_fmt=" + av_get_sample_fmt_name(mAudioCodecContext->sample_fmt) + + ":channel_layout=" + channelLayout; - returnValue = avfilter_graph_create_filter( - &mABufferSrcContext, - bufferSrc, - "in", - filterArguments.c_str(), - nullptr, - mAFilterGraph); + returnValue = avfilter_graph_create_filter(&mABufferSrcContext, bufferSrc, "in", + filterArguments.c_str(), nullptr, mAFilterGraph); if (returnValue < 0) { LOG(LogError) << "VideoFFmpegComponent::setupAudioFilters(): " - "Couldn't create filter instance for buffer source: " << - av_make_error_string(errorMessage, sizeof(errorMessage), returnValue); + "Couldn't create filter instance for buffer source: " + << av_make_error_string(errorMessage, sizeof(errorMessage), returnValue); return false; } - returnValue = avfilter_graph_create_filter( - &mABufferSinkContext, - bufferSink, - "out", - nullptr, - nullptr, - mAFilterGraph); + returnValue = avfilter_graph_create_filter(&mABufferSinkContext, bufferSink, "out", nullptr, + nullptr, mAFilterGraph); if (returnValue < 0) { LOG(LogError) << "VideoFFmpegComponent::setupAudioFilters(): " - "Couldn't create filter instance for buffer sink: " << - av_make_error_string(errorMessage, sizeof(errorMessage), returnValue); + "Couldn't create filter instance for buffer sink: " + << av_make_error_string(errorMessage, sizeof(errorMessage), returnValue); return false; } @@ -506,18 +482,18 @@ bool VideoFFmpegComponent::setupAudioFilters() mAFilterOutputs->next = nullptr; std::string filterDescription = - "aresample=" + std::to_string(outSampleRates[0]) + "," + - "aformat=sample_fmts=" + av_get_sample_fmt_name(outSampleFormats[0]) + - ":channel_layouts=stereo," - "asetnsamples=n=1024:p=0"; + "aresample=" + std::to_string(outSampleRates[0]) + "," + + "aformat=sample_fmts=" + av_get_sample_fmt_name(outSampleFormats[0]) + + ":channel_layouts=stereo," + "asetnsamples=n=1024:p=0"; returnValue = avfilter_graph_parse_ptr(mAFilterGraph, filterDescription.c_str(), - &mAFilterInputs, &mAFilterOutputs, nullptr); + &mAFilterInputs, &mAFilterOutputs, nullptr); if (returnValue < 0) { LOG(LogError) << "VideoFFmpegComponent::setupAudioFilters(): " - "Couldn't add graph filter: " << - av_make_error_string(errorMessage, sizeof(errorMessage), returnValue); + "Couldn't add graph filter: " + << av_make_error_string(errorMessage, sizeof(errorMessage), returnValue); return false; } @@ -525,8 +501,8 @@ bool VideoFFmpegComponent::setupAudioFilters() if (returnValue < 0) { LOG(LogError) << "VideoFFmpegComponent::setupAudioFilters(): " - "Couldn't configure graph: " << - av_make_error_string(errorMessage, sizeof(errorMessage), returnValue); + "Couldn't configure graph: " + << av_make_error_string(errorMessage, sizeof(errorMessage), returnValue); return false; } @@ -544,20 +520,20 @@ void VideoFFmpegComponent::readFrames() return; if (mVideoCodecContext && mFormatContext) { - if (mVideoFrameQueue.size() < mVideoTargetQueueSize || (mAudioStreamIndex >= 0 && - mAudioFrameQueue.size() < mAudioTargetQueueSize)) { + if (mVideoFrameQueue.size() < mVideoTargetQueueSize || + (mAudioStreamIndex >= 0 && mAudioFrameQueue.size() < mAudioTargetQueueSize)) { while ((readFrameReturn = av_read_frame(mFormatContext, mPacket)) >= 0) { if (mPacket->stream_index == mVideoStreamIndex) { if (!avcodec_send_packet(mVideoCodecContext, mPacket) && - !avcodec_receive_frame(mVideoCodecContext, mVideoFrame)) { + !avcodec_receive_frame(mVideoCodecContext, mVideoFrame)) { // We have a video frame that needs conversion to RGBA format. - int returnValue = av_buffersrc_add_frame_flags(mVBufferSrcContext, - mVideoFrame, AV_BUFFERSRC_FLAG_KEEP_REF); + int returnValue = av_buffersrc_add_frame_flags( + mVBufferSrcContext, mVideoFrame, AV_BUFFERSRC_FLAG_KEEP_REF); if (returnValue < 0) { LOG(LogError) << "VideoFFmpegComponent::readFrames(): " - "Couldn't add video frame to buffer source"; + "Couldn't add video frame to buffer source"; } av_packet_unref(mPacket); @@ -566,15 +542,15 @@ void VideoFFmpegComponent::readFrames() } else if (mPacket->stream_index == mAudioStreamIndex) { if (!avcodec_send_packet(mAudioCodecContext, mPacket) && - !avcodec_receive_frame(mAudioCodecContext, mAudioFrame)) { + !avcodec_receive_frame(mAudioCodecContext, mAudioFrame)) { // We have an audio frame that needs conversion and resampling. - int returnValue = av_buffersrc_add_frame_flags(mABufferSrcContext, - mAudioFrame, AV_BUFFERSRC_FLAG_KEEP_REF); + int returnValue = av_buffersrc_add_frame_flags( + mABufferSrcContext, mAudioFrame, AV_BUFFERSRC_FLAG_KEEP_REF); if (returnValue < 0) { LOG(LogError) << "VideoFFmpegComponent::readFrames(): " - "Couldn't add audio frame to buffer source"; + "Couldn't add audio frame to buffer source"; } av_packet_unref(mPacket); @@ -606,21 +582,20 @@ void VideoFFmpegComponent::getProcessedFrames() // (picture) should be displayed. The packet DTS value is used for the basis of // the calculation as per the recommendation in the FFmpeg documentation for // the av_read_frame function. - double pts = static_cast(mVideoFrameResampled->pkt_dts) * - av_q2d(mVideoStream->time_base); + double pts = + static_cast(mVideoFrameResampled->pkt_dts) * av_q2d(mVideoStream->time_base); // Needs to be adjusted if changing the rate? double frameDuration = static_cast(mVideoFrameResampled->pkt_duration) * - av_q2d(mVideoStream->time_base); + av_q2d(mVideoStream->time_base); currFrame.pts = pts; currFrame.frameDuration = frameDuration; int bufferSize = mVideoFrameResampled->width * mVideoFrameResampled->height * 4; - currFrame.frameRGBA.insert(currFrame.frameRGBA.begin(), - &mVideoFrameResampled->data[0][0], - &mVideoFrameResampled->data[0][bufferSize]); + currFrame.frameRGBA.insert(currFrame.frameRGBA.begin(), &mVideoFrameResampled->data[0][0], + &mVideoFrameResampled->data[0][bufferSize]); mVideoFrameQueue.push(currFrame); av_frame_unref(mVideoFrameResampled); @@ -629,8 +604,8 @@ void VideoFFmpegComponent::getProcessedFrames() // Audio frames. // When resampling, we may not always get a frame returned from the sink as there may not // have been enough data available to the filter. - while (mAudioCodecContext && av_buffersink_get_frame(mABufferSinkContext, - mAudioFrameResampled) >= 0) { + while (mAudioCodecContext && + av_buffersink_get_frame(mABufferSinkContext, mAudioFrameResampled) >= 0) { AudioFrame currFrame; AVRational timeBase; @@ -644,11 +619,11 @@ void VideoFFmpegComponent::getProcessedFrames() currFrame.pts = pts; int bufferSize = mAudioFrameResampled->nb_samples * mAudioFrameResampled->channels * - av_get_bytes_per_sample(AV_SAMPLE_FMT_FLT); + av_get_bytes_per_sample(AV_SAMPLE_FMT_FLT); currFrame.resampledData.insert(currFrame.resampledData.begin(), - &mAudioFrameResampled->data[0][0], - &mAudioFrameResampled->data[0][bufferSize]); + &mAudioFrameResampled->data[0][0], + &mAudioFrameResampled->data[0][bufferSize]); mAudioFrameQueue.push(currFrame); av_frame_unref(mAudioFrameResampled); @@ -674,22 +649,21 @@ void VideoFFmpegComponent::outputFrames() if (mAudioFrameQueue.front().pts < mAccumulatedTime + AUDIO_BUFFER) { // Enable only when needed, as this generates a lot of debug output. if (DEBUG_VIDEO) { - LOG(LogDebug) << "Processing audio frame with PTS: " << - mAudioFrameQueue.front().pts; - LOG(LogDebug) << "Total audio frames processed / audio frame queue size: " << - mAudioFrameCount << " / " << std::to_string(mAudioFrameQueue.size()); + LOG(LogDebug) << "Processing audio frame with PTS: " + << mAudioFrameQueue.front().pts; + LOG(LogDebug) << "Total audio frames processed / audio frame queue size: " + << mAudioFrameCount << " / " + << std::to_string(mAudioFrameQueue.size()); } bool outputSound = false; if ((!mScreensaverMode && !mMediaViewerMode) && - Settings::getInstance()->getBool("GamelistVideoAudio")) + Settings::getInstance()->getBool("GamelistVideoAudio")) outputSound = true; - else if (mScreensaverMode && Settings::getInstance()-> - getBool("ScreensaverVideoAudio")) + else if (mScreensaverMode && Settings::getInstance()->getBool("ScreensaverVideoAudio")) outputSound = true; - else if (mMediaViewerMode && Settings::getInstance()-> - getBool("MediaViewerVideoAudio")) + else if (mMediaViewerMode && Settings::getInstance()->getBool("MediaViewerVideoAudio")) outputSound = true; if (outputSound) { @@ -697,8 +671,8 @@ void VideoFFmpegComponent::outputFrames() mAudioMutex.lock(); mOutputAudio.insert(mOutputAudio.end(), - mAudioFrameQueue.front().resampledData.begin(), - mAudioFrameQueue.front().resampledData.end()); + mAudioFrameQueue.front().resampledData.begin(), + mAudioFrameQueue.front().resampledData.end()); mAudioMutex.unlock(); } @@ -717,10 +691,11 @@ void VideoFFmpegComponent::outputFrames() if (mVideoFrameQueue.front().pts < mAccumulatedTime) { // Enable only when needed, as this generates a lot of debug output. if (DEBUG_VIDEO) { - LOG(LogDebug) << "Processing video frame with PTS: " << - mVideoFrameQueue.front().pts; - LOG(LogDebug) << "Total video frames processed / video frame queue size: " << - mVideoFrameCount << " / " << std::to_string(mVideoFrameQueue.size()); + LOG(LogDebug) << "Processing video frame with PTS: " + << mVideoFrameQueue.front().pts; + LOG(LogDebug) << "Total video frames processed / video frame queue size: " + << mVideoFrameCount << " / " + << std::to_string(mVideoFrameQueue.size()); } mPictureMutex.lock(); @@ -734,7 +709,7 @@ void VideoFFmpegComponent::outputFrames() // rates close to, or at, the rendering frame rate, for example 59.94 and 60 FPS. if (mDecodedFrame && !mOutputPicture.hasBeenRendered) { double timeDifference = mAccumulatedTime - mVideoFrameQueue.front().pts - - mVideoFrameQueue.front().frameDuration * 2.0l; + mVideoFrameQueue.front().frameDuration * 2.0l; if (timeDifference < mVideoFrameQueue.front().frameDuration) { mPictureMutex.unlock(); break; @@ -743,8 +718,8 @@ void VideoFFmpegComponent::outputFrames() mOutputPicture.pictureRGBA.clear(); mOutputPicture.pictureRGBA.insert(mOutputPicture.pictureRGBA.begin(), - mVideoFrameQueue.front().frameRGBA.begin(), - mVideoFrameQueue.front().frameRGBA.end()); + mVideoFrameQueue.front().frameRGBA.begin(), + mVideoFrameQueue.front().frameRGBA.end()); mOutputPicture.width = mVideoFrameQueue.front().width; mOutputPicture.height = mVideoFrameQueue.front().height; @@ -802,10 +777,10 @@ void VideoFFmpegComponent::calculateBlackRectangle() rectHeight = mSize.y(); } // Populate the rectangle coordinates to be used in render(). - mVideoRectangleCoords.push_back(std::round(mVideoAreaPos.x() - - rectWidth * mOrigin.x())); - mVideoRectangleCoords.push_back(std::round(mVideoAreaPos.y() - - rectHeight * mOrigin.y())); + mVideoRectangleCoords.push_back( + std::round(mVideoAreaPos.x() - rectWidth * mOrigin.x())); + mVideoRectangleCoords.push_back( + std::round(mVideoAreaPos.y() - rectHeight * mOrigin.y())); mVideoRectangleCoords.push_back(std::round(rectWidth)); mVideoRectangleCoords.push_back(std::round(rectHeight)); } @@ -852,14 +827,16 @@ void VideoFFmpegComponent::startVideo() // File operations and basic setup. if (avformat_open_input(&mFormatContext, filePath.c_str(), nullptr, nullptr)) { - LOG(LogError) << "VideoFFmpegComponent::startVideo(): Couldn't open video file \"" << - mVideoPath << "\""; + LOG(LogError) << "VideoFFmpegComponent::startVideo(): " + "Couldn't open video file \"" + << mVideoPath << "\""; return; } if (avformat_find_stream_info(mFormatContext, nullptr)) { - LOG(LogError) << "VideoFFmpegComponent::startVideo(): Couldn't read stream information" - "from video file \"" << mVideoPath << "\""; + LOG(LogError) << "VideoFFmpegComponent::startVideo(): " + "Couldn't read stream information from video file \"" + << mVideoPath << "\""; return; } @@ -868,12 +845,13 @@ void VideoFFmpegComponent::startVideo() // Video stream setup. - mVideoStreamIndex = av_find_best_stream( - mFormatContext, AVMEDIA_TYPE_VIDEO, -1, -1, nullptr, 0); + mVideoStreamIndex = + av_find_best_stream(mFormatContext, AVMEDIA_TYPE_VIDEO, -1, -1, nullptr, 0); if (mVideoStreamIndex < 0) { - LOG(LogError) << "VideoFFmpegComponent::startVideo(): Couldn't retrieve video stream " - "for file \"" << mVideoPath << "\""; + LOG(LogError) << "VideoFFmpegComponent::startVideo(): " + "Couldn't retrieve video stream for file \"" + << mVideoPath << "\""; return; } @@ -884,16 +862,18 @@ void VideoFFmpegComponent::startVideo() mVideoCodec = const_cast(avcodec_find_decoder(mVideoStream->codecpar->codec_id)); if (!mVideoCodec) { - LOG(LogError) << "VideoFFmpegComponent::startVideo(): Couldn't find a suitable video " - "codec for file \"" << mVideoPath << "\""; + LOG(LogError) << "VideoFFmpegComponent::startVideo(): " + "Couldn't find a suitable video codec for file \"" + << mVideoPath << "\""; return; } mVideoCodecContext = avcodec_alloc_context3(mVideoCodec); if (!mVideoCodec) { - LOG(LogError) << "VideoFFmpegComponent::startVideo(): Couldn't allocate video " - "codec context for file \"" << mVideoPath << "\""; + LOG(LogError) << "VideoFFmpegComponent::startVideo(): " + "Couldn't allocate video codec context for file \"" + << mVideoPath << "\""; return; } @@ -901,35 +881,38 @@ void VideoFFmpegComponent::startVideo() mVideoCodecContext->flags |= AV_CODEC_FLAG_TRUNCATED; if (avcodec_parameters_to_context(mVideoCodecContext, mVideoStream->codecpar)) { - LOG(LogError) << "VideoFFmpegComponent::startVideo(): Couldn't fill the video " - "codec context parameters for file \"" << mVideoPath << "\""; + LOG(LogError) << "VideoFFmpegComponent::startVideo(): " + "Couldn't fill the video codec context parameters for file \"" + << mVideoPath << "\""; return; } if (avcodec_open2(mVideoCodecContext, mVideoCodec, nullptr)) { - LOG(LogError) << "VideoFFmpegComponent::startVideo(): Couldn't initialize the " - "video codec context for file \"" << mVideoPath << "\""; + LOG(LogError) << "VideoFFmpegComponent::startVideo(): " + "Couldn't initialize the video codec context for file \"" + << mVideoPath << "\""; return; } // Audio stream setup, optional as some videos may not have any audio tracks. - mAudioStreamIndex = av_find_best_stream( - mFormatContext, AVMEDIA_TYPE_AUDIO, -1, -1, nullptr, 0); + mAudioStreamIndex = + av_find_best_stream(mFormatContext, AVMEDIA_TYPE_AUDIO, -1, -1, nullptr, 0); if (mAudioStreamIndex < 0) { - LOG(LogDebug) << "VideoFFmpegComponent::startVideo(): Couldn't retrieve audio stream " - "for file \"" << mVideoPath << "\""; + LOG(LogDebug) << "VideoFFmpegComponent::startVideo(): " + "Couldn't retrieve audio stream for file \"" + << mVideoPath << "\""; } if (mAudioStreamIndex >= 0) { mAudioStream = mFormatContext->streams[mAudioStreamIndex]; - mAudioCodec = const_cast( - avcodec_find_decoder(mAudioStream->codecpar->codec_id)); + mAudioCodec = + const_cast(avcodec_find_decoder(mAudioStream->codecpar->codec_id)); if (!mAudioCodec) { - LOG(LogError) << "Couldn't find a suitable audio codec for file \"" << - mVideoPath << "\""; + LOG(LogError) << "Couldn't find a suitable audio codec for file \"" << mVideoPath + << "\""; return; } @@ -943,14 +926,16 @@ void VideoFFmpegComponent::startVideo() mAudioCodecContext->flags |= AV_CODEC_FLAG_GLOBAL_HEADER; if (avcodec_parameters_to_context(mAudioCodecContext, mAudioStream->codecpar)) { - LOG(LogError) << "VideoFFmpegComponent::startVideo(): Couldn't fill the audio " - "codec context parameters for file \"" << mVideoPath << "\""; + LOG(LogError) << "VideoFFmpegComponent::startVideo(): " + "Couldn't fill the audio codec context parameters for file \"" + << mVideoPath << "\""; return; } if (avcodec_open2(mAudioCodecContext, mAudioCodec, nullptr)) { - LOG(LogError) << "VideoFFmpegComponent::startVideo(): Couldn't initialize the " - "audio codec context for file \"" << mVideoPath << "\""; + LOG(LogError) << "VideoFFmpegComponent::startVideo(): " + "Couldn't initialize the audio codec context for file \"" + << mVideoPath << "\""; return; } } @@ -959,7 +944,7 @@ void VideoFFmpegComponent::startVideo() // Set some reasonable target queue sizes (buffers). mVideoTargetQueueSize = static_cast(av_q2d(mVideoStream->avg_frame_rate) / 2.0l); - if (mAudioStreamIndex >=0) + if (mAudioStreamIndex >= 0) mAudioTargetQueueSize = mAudioStream->codecpar->channels * 15; else mAudioTargetQueueSize = 30; @@ -1035,7 +1020,7 @@ void VideoFFmpegComponent::handleLooping() // If the screensaver video swap time is set to 0, it means we should // skip to the next game when the video has finished playing. if (mScreensaverMode && - Settings::getInstance()->getInt("ScreensaverSwapVideoTimeout") == 0) { + Settings::getInstance()->getInt("ScreensaverSwapVideoTimeout") == 0) { mWindow->screensaverTriggerNextGame(); } else { diff --git a/es-core/src/components/VideoFFmpegComponent.h b/es-core/src/components/VideoFFmpegComponent.h index 619bb7f03..d7a134be8 100644 --- a/es-core/src/components/VideoFFmpegComponent.h +++ b/es-core/src/components/VideoFFmpegComponent.h @@ -14,8 +14,7 @@ #include "VideoComponent.h" -extern "C" -{ +extern "C" { #include #include #include @@ -89,8 +88,8 @@ private: AVFormatContext* mFormatContext; AVStream* mVideoStream; AVStream* mAudioStream; - AVCodec *mVideoCodec; - AVCodec *mAudioCodec; + AVCodec* mVideoCodec; + AVCodec* mAudioCodec; AVCodecContext* mVideoCodecContext; AVCodecContext* mAudioCodecContext; int mVideoStreamIndex; diff --git a/es-core/src/components/VideoOmxComponent.cpp b/es-core/src/components/VideoOmxComponent.cpp index f5dc43d06..4d537f244 100644 --- a/es-core/src/components/VideoOmxComponent.cpp +++ b/es-core/src/components/VideoOmxComponent.cpp @@ -9,10 +9,10 @@ #if defined(_RPI_) #include "components/VideoOmxComponent.h" -#include "renderers/Renderer.h" -#include "utils/StringUtil.h" #include "AudioManager.h" #include "Settings.h" +#include "renderers/Renderer.h" +#include "utils/StringUtil.h" #include #include @@ -21,18 +21,19 @@ class VolumeControl { public: - static std::shared_ptr & getInstance(); + static std::shared_ptr& getInstance(); int getVolume() const; }; -VideoOmxComponent::VideoOmxComponent(Window* window) : - VideoComponent(window), - mPlayerPid(-1) +VideoOmxComponent::VideoOmxComponent(Window* window) + : VideoComponent(window) + , mPlayerPid(-1) { } VideoOmxComponent::~VideoOmxComponent() { + // Stop video when destroyed. stopVideo(); } @@ -79,8 +80,8 @@ void VideoOmxComponent::startVideo() mPlayingVideoPath = mVideoPath; // Disable AudioManager so video can play, in case we're requesting ALSA. - if (Utils::String::startsWith(Settings::getInstance()-> - getString("OMXAudioDev").c_str(), "alsa")) + if (Utils::String::startsWith(Settings::getInstance()->getString("OMXAudioDev").c_str(), + "alsa")) AudioManager::getInstance()->deinit(); // Start the player process. @@ -112,66 +113,84 @@ void VideoOmxComponent::startVideo() const int x2 = static_cast(x1 + mSize.x()); const int y2 = static_cast(y1 + mSize.y()); sprintf(buf1, "%d,%d,%d,%d", x1, y1, x2, y2); - } - break; + } break; case 1: { - const int x1 = static_cast(Renderer::getWindowWidth() - - Renderer::getScreenOffsetY() - y - mSize.y()); + const int x1 = + static_cast(Renderer::getWindowWidth() - + Renderer::getScreenOffsetY() - y - mSize.y()); const int y1 = static_cast(Renderer::getScreenOffsetX() + x); const int x2 = static_cast(x1 + mSize.y()); const int y2 = static_cast(y1 + mSize.x()); sprintf(buf1, "%d,%d,%d,%d", x1, y1, x2, y2); - } - break; + } break; case 2: { - const int x1 = static_cast(Renderer::getWindowWidth() - - Renderer::getScreenOffsetX() - x - mSize.x()); - const int y1 = static_cast(Renderer::getWindowHeight() - - Renderer::getScreenOffsetY() - y - mSize.y()); + const int x1 = + static_cast(Renderer::getWindowWidth() - + Renderer::getScreenOffsetX() - x - mSize.x()); + const int y1 = + static_cast(Renderer::getWindowHeight() - + Renderer::getScreenOffsetY() - y - mSize.y()); const int x2 = static_cast(x1 + mSize.x()); const int y2 = static_cast(y1 + mSize.y()); sprintf(buf1, "%d,%d,%d,%d", x1, y1, x2, y2); - } - break; + } break; case 3: { const int x1 = static_cast(Renderer::getScreenOffsetY() + y); - const int y1 = static_cast(Renderer::getWindowHeight() - - Renderer::getScreenOffsetX() - x - mSize.x()); + const int y1 = + static_cast(Renderer::getWindowHeight() - + Renderer::getScreenOffsetX() - x - mSize.x()); const int x2 = static_cast(x1 + mSize.y()); const int y2 = static_cast(y1 + mSize.x()); sprintf(buf1, "%d,%d,%d,%d", x1, y1, x2, y2); - } - break; + } break; } // Rotate the video. switch (Renderer::getScreenRotate()) { - case 0: { sprintf(buf2, "%d", static_cast(0)); } break; - case 1: { sprintf(buf2, "%d", static_cast(90)); } break; - case 2: { sprintf(buf2, "%d", static_cast(180)); } break; - case 3: { sprintf(buf2, "%d", static_cast(270)); } break; + case 0: { + sprintf(buf2, "%d", static_cast(0)); + } break; + case 1: { + sprintf(buf2, "%d", static_cast(90)); + } break; + case 2: { + sprintf(buf2, "%d", static_cast(180)); + } break; + case 3: { + sprintf(buf2, "%d", static_cast(270)); + } break; } // We need to specify the layer of 10000 or above to ensure the video is // displayed on top of our SDL display. - const char* argv[] = { "", "--layer", "10010", "--loop", "--no-osd", - "--aspect-mode", "letterbox", "--vol", "0", "-o", "both", - "--win", buf1, "--orientation", buf2, "", "", "", "", "", "", - "", "", "", "", "", NULL }; + const char* argv[] = { "", "--layer", + "10010", "--loop", + "--no-osd", "--aspect-mode", + "letterbox", "--vol", + "0", "-o", + "both", "--win", + buf1, "--orientation", + buf2, "", + "", "", + "", "", + "", "", + "", "", + "", "", + NULL }; // Check if we want to mute the audio. if ((!Settings::getInstance()->getBool("GamelistVideoAudio") || - static_cast(VolumeControl::getInstance()->getVolume()) == 0) || - (!Settings::getInstance()->getBool("ScreensaverVideoAudio") && - mScreensaverMode)) { + static_cast(VolumeControl::getInstance()->getVolume()) == 0) || + (!Settings::getInstance()->getBool("ScreensaverVideoAudio") && + mScreensaverMode)) { argv[8] = "-1000000"; } else { float percentVolume = - static_cast(VolumeControl::getInstance()->getVolume()); + static_cast(VolumeControl::getInstance()->getVolume()); int OMXVolume = static_cast((percentVolume - 98) * 105); argv[8] = std::to_string(OMXVolume).c_str(); } diff --git a/es-core/src/components/VideoVlcComponent.cpp b/es-core/src/components/VideoVlcComponent.cpp index 077f6bcea..60dd46b83 100644 --- a/es-core/src/components/VideoVlcComponent.cpp +++ b/es-core/src/components/VideoVlcComponent.cpp @@ -10,12 +10,12 @@ #include "components/VideoVlcComponent.h" -#include "renderers/Renderer.h" -#include "resources/TextureResource.h" -#include "utils/StringUtil.h" #include "AudioManager.h" #include "Settings.h" #include "Window.h" +#include "renderers/Renderer.h" +#include "resources/TextureResource.h" +#include "utils/StringUtil.h" #if defined(__APPLE__) #include "utils/FileSystemUtil.h" @@ -26,19 +26,18 @@ #include #if defined(_WIN64) -#include #include +#include #endif libvlc_instance_t* VideoVlcComponent::mVLC = nullptr; -VideoVlcComponent::VideoVlcComponent( - Window* window) - : VideoComponent(window), - mMediaPlayer(nullptr), - mMedia(nullptr), - mContext({}), - mHasSetAudioVolume(false) +VideoVlcComponent::VideoVlcComponent(Window* window) + : VideoComponent(window) + , mMediaPlayer(nullptr) + , mMedia(nullptr) + , mContext({}) + , mHasSetAudioVolume(false) { // Get an empty texture for rendering the video. mTexture = TextureResource::get(""); @@ -86,7 +85,7 @@ void VideoVlcComponent::setupVLC() if (!mVLC) { const char* args[] = { "--quiet" }; - #if defined(__APPLE__) +#if defined(__APPLE__) // It's required to set the VLC_PLUGIN_PATH variable on macOS, or the libVLC // initialization will fail (with no error message). std::string vlcPluginPath = Utils::FileSystem::getExePath() + "/plugins"; @@ -94,7 +93,7 @@ void VideoVlcComponent::setupVLC() setenv("VLC_PLUGIN_PATH", vlcPluginPath.c_str(), 1); else setenv("VLC_PLUGIN_PATH", "/Applications/VLC.app/Contents/MacOS/plugins/", 1); - #endif +#endif mVLC = libvlc_new(1, args); } @@ -105,7 +104,8 @@ void VideoVlcComponent::setupContext() if (!mContext.valid) { // Create an RGBA surface to render the video into. mContext.surface = SDL_CreateRGBSurface(SDL_SWSURFACE, static_cast(mVideoWidth), - static_cast(mVideoHeight), 32, 0xff000000, 0x00ff0000, 0x0000ff00, 0x000000ff); + static_cast(mVideoHeight), 32, 0xff000000, + 0x00ff0000, 0x0000ff00, 0x000000ff); mContext.mutex = SDL_CreateMutex(); mContext.valid = true; resize(); @@ -148,7 +148,6 @@ void VideoVlcComponent::resize() mSize[1] = std::round(mSize[1]); mSize[0] = (mSize[1] / textureSize.y()) * textureSize.x(); - } else { // If both components are set, we just stretch. @@ -196,8 +195,8 @@ void VideoVlcComponent::render(const Transform4x4f& parentTrans) unsigned int color; if (mFadeIn < 1) { const unsigned int fadeIn = static_cast(mFadeIn * 255.0f); - color = Renderer::convertRGBAToABGR((fadeIn << 24) | - (fadeIn << 16) | (fadeIn << 8) | 255); + color = + Renderer::convertRGBAToABGR((fadeIn << 24) | (fadeIn << 16) | (fadeIn << 8) | 255); } else { color = 0xFFFFFFFF; @@ -209,13 +208,16 @@ void VideoVlcComponent::render(const Transform4x4f& parentTrans) // Render the black rectangle behind the video. if (mVideoRectangleCoords.size() == 4) { Renderer::drawRect(mVideoRectangleCoords[0], mVideoRectangleCoords[1], - mVideoRectangleCoords[2], mVideoRectangleCoords[3], 0x000000FF, 0x000000FF); + mVideoRectangleCoords[2], mVideoRectangleCoords[3], // Line break. + 0x000000FF, 0x000000FF); } + // clang-format off vertices[0] = { { 0.0f , 0.0f }, { 0.0f, 0.0f }, color }; vertices[1] = { { 0.0f , mSize.y() }, { 0.0f, 1.0f }, color }; vertices[2] = { { mSize.x(), 0.0f }, { 1.0f, 0.0f }, color }; vertices[3] = { { mSize.x(), mSize.y() }, { 1.0f, 1.0f }, color }; + // clang-format on // Round vertices. for (int i = 0; i < 4; i++) @@ -223,17 +225,18 @@ void VideoVlcComponent::render(const Transform4x4f& parentTrans) // Build a texture for the video frame. mTexture->initFromPixels(reinterpret_cast(mContext.surface->pixels), - mContext.surface->w, mContext.surface->h); + mContext.surface->w, mContext.surface->h); mTexture->bind(); - #if defined(USE_OPENGL_21) +#if defined(USE_OPENGL_21) // Render scanlines if this option is enabled. However, if this is the media viewer // or the video screensaver, then skip this as the scanline rendering is then handled // in those modules as a postprocessing step. if ((!mScreensaverMode && !mMediaViewerMode) && - Settings::getInstance()->getBool("GamelistVideoScanlines")) + Settings::getInstance()->getBool("GamelistVideoScanlines")) { vertices[0].shaders = Renderer::SHADER_SCANLINES; - #endif + } +#endif // Render it. Renderer::setMatrix(trans); @@ -283,10 +286,10 @@ void VideoVlcComponent::calculateBlackRectangle() rectHeight = mSize.y(); } // Populate the rectangle coordinates to be used in render(). - mVideoRectangleCoords.push_back(std::round(mVideoAreaPos.x() - - rectWidth * mOrigin.x())); - mVideoRectangleCoords.push_back(std::round(mVideoAreaPos.y() - - rectHeight * mOrigin.y())); + mVideoRectangleCoords.push_back( + std::round(mVideoAreaPos.x() - rectWidth * mOrigin.x())); + mVideoRectangleCoords.push_back( + std::round(mVideoAreaPos.y() - rectHeight * mOrigin.y())); mVideoRectangleCoords.push_back(std::round(rectWidth)); mVideoRectangleCoords.push_back(std::round(rectHeight)); } @@ -310,20 +313,18 @@ void VideoVlcComponent::setAudioVolume() bool outputSound = false; if ((!mScreensaverMode && !mMediaViewerMode) && - Settings::getInstance()->getBool("GamelistVideoAudio")) + Settings::getInstance()->getBool("GamelistVideoAudio")) outputSound = true; - else if (mScreensaverMode && Settings::getInstance()-> - getBool("ScreensaverVideoAudio")) + else if (mScreensaverMode && Settings::getInstance()->getBool("ScreensaverVideoAudio")) outputSound = true; - else if (mMediaViewerMode && Settings::getInstance()-> - getBool("MediaViewerVideoAudio")) + else if (mMediaViewerMode && Settings::getInstance()->getBool("MediaViewerVideoAudio")) outputSound = true; if (outputSound) { if (libvlc_audio_get_mute(mMediaPlayer) == 1) libvlc_audio_set_mute(mMediaPlayer, 0); libvlc_audio_set_volume(mMediaPlayer, - Settings::getInstance()->getInt("SoundVolumeVideos")); + Settings::getInstance()->getInt("SoundVolumeVideos")); } else { libvlc_audio_set_volume(mMediaPlayer, 0); @@ -339,11 +340,11 @@ void VideoVlcComponent::startVideo() mVideoWidth = 0; mVideoHeight = 0; - #if defined(_WIN64) +#if defined(_WIN64) std::string path(Utils::String::replace(mVideoPath, "/", "\\")); - #else +#else std::string path(mVideoPath); - #endif +#endif // Make sure we have a video path. if (mVLC && (path.size() > 0)) { // Set the video that we are going to be playing so we don't attempt to restart it. @@ -356,8 +357,8 @@ void VideoVlcComponent::startVideo() int parseResult; // Asynchronous media parsing. - libvlc_event_attach(libvlc_media_event_manager(mMedia), - libvlc_MediaParsedChanged, VlcMediaParseCallback, 0); + libvlc_event_attach(libvlc_media_event_manager(mMedia), libvlc_MediaParsedChanged, + VlcMediaParseCallback, 0); parseResult = libvlc_media_parse_with_options(mMedia, libvlc_media_parse_local, -1); if (!parseResult) { @@ -382,8 +383,8 @@ void VideoVlcComponent::startVideo() } libvlc_media_tracks_release(tracks, track_count); libvlc_media_parse_stop(mMedia); - libvlc_event_detach(libvlc_media_event_manager(mMedia), - libvlc_MediaParsedChanged, VlcMediaParseCallback, 0); + libvlc_event_detach(libvlc_media_event_manager(mMedia), libvlc_MediaParsedChanged, + VlcMediaParseCallback, 0); // Make sure we found a valid video track. if ((mVideoWidth > 0) && (mVideoHeight > 0)) { @@ -395,32 +396,36 @@ void VideoVlcComponent::startVideo() // The code below enables the libVLC audio output to be processed inside ES-DE. // Unfortunately this causes excessive stuttering for some reason that I still // don't understand, so at the moment this code is disabled. -// auto audioFormatCallback = [](void **data, char *format, -// unsigned *rate, unsigned *channels) -> int { -// format = const_cast("F32L"); -// *rate = 48000; -// *channels = 2; -// return 0; -// }; -// -// libvlc_audio_set_format_callbacks(mMediaPlayer, -// audioFormatCallback, nullptr); -// -// auto audioPlayCallback = [](void* data, const void* samples, -// unsigned count, int64_t pts) { -// AudioManager::getInstance()->processStream(samples, count); -// }; -// -// libvlc_audio_set_callbacks(mMediaPlayer, audioPlayCallback, -// nullptr, nullptr, nullptr, nullptr, this); + // auto audioFormatCallback = [](void **data, char *format, + // unsigned *rate, unsigned *channels) -> int { + // format = const_cast("F32L"); + // *rate = 48000; + // *channels = 2; + // return 0; + // }; + // + // libvlc_audio_set_format_callbacks(mMediaPlayer, + // audioFormatCallback, nullptr); + // + // auto audioPlayCallback = [](void* data, const void* + // samples, + // unsigned count, int64_t pts) { + // AudioManager::getInstance()->processStream(samples, + // count); + // }; + // + // libvlc_audio_set_callbacks(mMediaPlayer, + // audioPlayCallback, + // nullptr, nullptr, nullptr, nullptr, this); libvlc_video_set_format(mMediaPlayer, "RGBA", static_cast(mVideoWidth), - static_cast(mVideoHeight), static_cast(mVideoWidth * 4)); + static_cast(mVideoHeight), + static_cast(mVideoWidth * 4)); // Lock video memory as a preparation for rendering a frame. auto videoLockCallback = [](void* data, void** p_pixels) -> void* { struct VideoContext* videoContext = - reinterpret_cast(data); + reinterpret_cast(data); SDL_LockMutex(videoContext->mutex); SDL_LockSurface(videoContext->surface); *p_pixels = videoContext->surface->pixels; @@ -428,15 +433,15 @@ void VideoVlcComponent::startVideo() }; // Unlock the video memory after rendering a frame. - auto videoUnlockCallback = [](void* data, void*, void *const*) { + auto videoUnlockCallback = [](void* data, void*, void* const*) { struct VideoContext* videoContext = - reinterpret_cast(data); + reinterpret_cast(data); SDL_UnlockSurface(videoContext->surface); SDL_UnlockMutex(videoContext->mutex); }; - libvlc_video_set_callbacks(mMediaPlayer, videoLockCallback, - videoUnlockCallback, nullptr, reinterpret_cast(&mContext)); + libvlc_video_set_callbacks(mMediaPlayer, videoLockCallback, videoUnlockCallback, + nullptr, reinterpret_cast(&mContext)); libvlc_media_player_play(mMediaPlayer); @@ -517,7 +522,7 @@ void VideoVlcComponent::handleLooping() // If the screensaver video swap time is set to 0, it means we should // skip to the next game when the video has finished playing. if (mScreensaverMode && - Settings::getInstance()->getInt("ScreensaverSwapVideoTimeout") == 0) { + Settings::getInstance()->getInt("ScreensaverSwapVideoTimeout") == 0) { mWindow->screensaverTriggerNextGame(); } else { @@ -527,13 +532,13 @@ void VideoVlcComponent::handleLooping() bool outputSound = false; if ((!mScreensaverMode && !mMediaViewerMode) && - Settings::getInstance()->getBool("GamelistVideoAudio")) + Settings::getInstance()->getBool("GamelistVideoAudio")) outputSound = true; - else if (mScreensaverMode && Settings::getInstance()-> - getBool("ScreensaverVideoAudio")) + else if (mScreensaverMode && + Settings::getInstance()->getBool("ScreensaverVideoAudio")) outputSound = true; - else if (mMediaViewerMode && Settings::getInstance()-> - getBool("MediaViewerVideoAudio")) + else if (mMediaViewerMode && + Settings::getInstance()->getBool("MediaViewerVideoAudio")) outputSound = true; if (!outputSound) diff --git a/es-core/src/components/VideoVlcComponent.h b/es-core/src/components/VideoVlcComponent.h index c4b8f15cd..880852aa8 100644 --- a/es-core/src/components/VideoVlcComponent.h +++ b/es-core/src/components/VideoVlcComponent.h @@ -66,7 +66,7 @@ private: // Handle looping the video. Must be called periodically. virtual void handleLooping() override; - static void VlcMediaParseCallback(const libvlc_event_t *event, void *user_data) {}; + static void VlcMediaParseCallback(const libvlc_event_t* event, void* user_data) {} static VideoVlcComponent* sInstance; static libvlc_instance_t* mVLC; diff --git a/es-core/src/guis/GuiComplexTextEditPopup.cpp b/es-core/src/guis/GuiComplexTextEditPopup.cpp index 20d77fba7..d649976ba 100644 --- a/es-core/src/guis/GuiComplexTextEditPopup.cpp +++ b/es-core/src/guis/GuiComplexTextEditPopup.cpp @@ -10,68 +10,68 @@ #include "guis/GuiComplexTextEditPopup.h" +#include "Window.h" #include "components/ButtonComponent.h" #include "components/MenuComponent.h" #include "components/TextEditComponent.h" #include "guis/GuiMsgBox.h" -#include "Window.h" GuiComplexTextEditPopup::GuiComplexTextEditPopup( - Window* window, - const HelpStyle& helpstyle, - const std::string& title, - const std::string& infoString1, - const std::string& infoString2, - const std::string& initValue, - const std::function& okCallback, - bool multiLine, - const std::string& acceptBtnText, - const std::string& saveConfirmationText, - const std::string& loadBtnText, - const std::string& loadBtnHelpText, - const std::string& clearBtnText, - const std::string& clearBtnHelpText, - bool hideCancelButton) - : GuiComponent(window), - mHelpStyle(helpstyle), - mBackground(window, ":/graphics/frame.svg"), - mGrid(window, Vector2i(1, 5)), - mMultiLine(multiLine), - mInitValue(initValue), - mOkCallback(okCallback), - mSaveConfirmationText(saveConfirmationText), - mHideCancelButton(hideCancelButton) + Window* window, + const HelpStyle& helpstyle, + const std::string& title, + const std::string& infoString1, + const std::string& infoString2, + const std::string& initValue, + const std::function& okCallback, + bool multiLine, + const std::string& acceptBtnText, + const std::string& saveConfirmationText, + const std::string& loadBtnText, + const std::string& loadBtnHelpText, + const std::string& clearBtnText, + const std::string& clearBtnHelpText, + bool hideCancelButton) + : GuiComponent(window) + , mHelpStyle(helpstyle) + , mBackground(window, ":/graphics/frame.svg") + , mGrid(window, Vector2i(1, 5)) + , mMultiLine(multiLine) + , mInitValue(initValue) + , mOkCallback(okCallback) + , mSaveConfirmationText(saveConfirmationText) + , mHideCancelButton(hideCancelButton) { addChild(&mBackground); addChild(&mGrid); mTitle = std::make_shared(mWindow, Utils::String::toUpper(title), - Font::get(FONT_SIZE_MEDIUM), 0x555555FF, ALIGN_CENTER); - mInfoString1 = std::make_shared(mWindow, infoString1, - Font::get(FONT_SIZE_SMALL), 0x555555FF, ALIGN_CENTER); - mInfoString2 = std::make_shared(mWindow, infoString2, - Font::get(FONT_SIZE_SMALL), 0x555555FF, ALIGN_CENTER); + Font::get(FONT_SIZE_MEDIUM), 0x555555FF, ALIGN_CENTER); + mInfoString1 = std::make_shared(mWindow, infoString1, Font::get(FONT_SIZE_SMALL), + 0x555555FF, ALIGN_CENTER); + mInfoString2 = std::make_shared(mWindow, infoString2, Font::get(FONT_SIZE_SMALL), + 0x555555FF, ALIGN_CENTER); mText = std::make_shared(mWindow); mText->setValue(initValue); std::vector> buttons; buttons.push_back(std::make_shared(mWindow, acceptBtnText, acceptBtnText, - [this, okCallback] { - okCallback(mText->getValue()); - delete this; - })); + [this, okCallback] { + okCallback(mText->getValue()); + delete this; + })); buttons.push_back(std::make_shared(mWindow, loadBtnText, loadBtnHelpText, - [this, infoString2] { - mText->setValue(infoString2); - mText->setCursor(0); - mText->setCursor(infoString2.size()); - })); + [this, infoString2] { + mText->setValue(infoString2); + mText->setCursor(0); + mText->setCursor(infoString2.size()); + })); buttons.push_back(std::make_shared(mWindow, clearBtnText, clearBtnHelpText, - [this] { mText->setValue(""); })); + [this] { mText->setValue(""); })); if (!mHideCancelButton) buttons.push_back(std::make_shared(mWindow, "CANCEL", "discard changes", - [this] { delete this; })); + [this] { delete this; })); mButtonGrid = makeButtonGrid(mWindow, buttons); @@ -79,14 +79,14 @@ GuiComplexTextEditPopup::GuiComplexTextEditPopup( mGrid.setEntry(mInfoString1, Vector2i(0, 1), false, true); mGrid.setEntry(mInfoString2, Vector2i(0, 2), false, false); mGrid.setEntry(mText, Vector2i(0, 3), true, false, Vector2i(1, 1), - GridFlags::BORDER_TOP | GridFlags::BORDER_BOTTOM); + GridFlags::BORDER_TOP | GridFlags::BORDER_BOTTOM); mGrid.setEntry(mButtonGrid, Vector2i(0, 4), true, false); mGrid.setRowHeightPerc(1, 0.15f, true); float textHeight = mText->getFont()->getHeight(); if (multiLine) - textHeight *= 6; + textHeight *= 6.0f; // Adjust the width relative to the aspect ratio of the screen to make the GUI look coherent // regardless of screen type. The 1.778 aspect ratio value is the 16:9 reference. @@ -97,18 +97,17 @@ GuiComplexTextEditPopup::GuiComplexTextEditPopup( mText->setSize(0, textHeight); mInfoString2->setSize(infoWidth, mInfoString2->getFont()->getHeight()); - setSize(windowWidth, mTitle->getFont()->getHeight() + textHeight + - mButtonGrid->getSize().y() + mButtonGrid->getSize().y() * 1.85f); - setPosition((Renderer::getScreenWidth() - mSize.x()) / 2, - (Renderer::getScreenHeight() - mSize.y()) / 2); + setSize(windowWidth, mTitle->getFont()->getHeight() + textHeight + mButtonGrid->getSize().y() + + mButtonGrid->getSize().y() * 1.85f); + setPosition((Renderer::getScreenWidth() - mSize.x()) / 2.0f, + (Renderer::getScreenHeight() - mSize.y()) / 2.0f); mText->startEditing(); } void GuiComplexTextEditPopup::onSizeChanged() { - mBackground.fitTo(mSize, Vector3f::Zero(), Vector2f(-32, -32)); - - mText->setSize(mSize.x() - 40, mText->getSize().y()); + mBackground.fitTo(mSize, Vector3f::Zero(), Vector2f(-32.0f, -32.0f)); + mText->setSize(mSize.x() - 40.0f, mText->getSize().y()); // Update grid. mGrid.setRowHeightPerc(0, mTitle->getFont()->getHeight() / mSize.y()); @@ -122,13 +121,22 @@ bool GuiComplexTextEditPopup::input(InputConfig* config, Input input) return true; if (!mHideCancelButton) { - // Pressing back when not text editing closes us. + // Pressing back when not text editing closes us. if (config->isMappedTo("b", input) && input.value) { if (mText->getValue() != mInitValue) { // Changes were made, ask if the user wants to save them. - mWindow->pushGui(new GuiMsgBox(mWindow, mHelpStyle, mSaveConfirmationText, "YES", - [this] { this->mOkCallback(mText->getValue()); delete this; return true; }, - "NO", [this] { delete this; return false; })); + mWindow->pushGui(new GuiMsgBox( + mWindow, mHelpStyle, mSaveConfirmationText, "YES", + [this] { + this->mOkCallback(mText->getValue()); + delete this; + return true; + }, + "NO", + [this] { + delete this; + return false; + })); } else { delete this; diff --git a/es-core/src/guis/GuiComplexTextEditPopup.h b/es-core/src/guis/GuiComplexTextEditPopup.h index 7725f2db3..a1ffc8e41 100644 --- a/es-core/src/guis/GuiComplexTextEditPopup.h +++ b/es-core/src/guis/GuiComplexTextEditPopup.h @@ -11,9 +11,9 @@ #ifndef ES_CORE_GUIS_GUI_COMPLEX_TEXT_EDIT_POPUP_H #define ES_CORE_GUIS_GUI_COMPLEX_TEXT_EDIT_POPUP_H +#include "GuiComponent.h" #include "components/ComponentGrid.h" #include "components/NinePatchComponent.h" -#include "GuiComponent.h" class TextComponent; class TextEditComponent; @@ -21,28 +21,27 @@ class TextEditComponent; class GuiComplexTextEditPopup : public GuiComponent { public: - GuiComplexTextEditPopup( - Window* window, - const HelpStyle& helpstyle, - const std::string& title, - const std::string& infoString1, - const std::string& infoString2, - const std::string& initValue, - const std::function& okCallback, - bool multiLine, - const std::string& acceptBtnText = "OK", - const std::string& saveConfirmationText = "SAVE CHANGES?", - const std::string& loadBtnText = "LOAD", - const std::string& loadBtnHelpText = "load default", - const std::string& clearBtnText = "CLEAR", - const std::string& clearBtnHelpText = "clear", - bool hideCancelButton = false); + GuiComplexTextEditPopup(Window* window, + const HelpStyle& helpstyle, + const std::string& title, + const std::string& infoString1, + const std::string& infoString2, + const std::string& initValue, + const std::function& okCallback, + bool multiLine, + const std::string& acceptBtnText = "OK", + const std::string& saveConfirmationText = "SAVE CHANGES?", + const std::string& loadBtnText = "LOAD", + const std::string& loadBtnHelpText = "load default", + const std::string& clearBtnText = "CLEAR", + const std::string& clearBtnHelpText = "clear", + bool hideCancelButton = false); bool input(InputConfig* config, Input input) override; void onSizeChanged() override; std::vector getHelpPrompts() override; - HelpStyle getHelpStyle() override { return mHelpStyle; }; + HelpStyle getHelpStyle() override { return mHelpStyle; } private: NinePatchComponent mBackground; diff --git a/es-core/src/guis/GuiDetectDevice.cpp b/es-core/src/guis/GuiDetectDevice.cpp index 06495d460..2cf8d33ab 100644 --- a/es-core/src/guis/GuiDetectDevice.cpp +++ b/es-core/src/guis/GuiDetectDevice.cpp @@ -8,25 +8,24 @@ #include "guis/GuiDetectDevice.h" +#include "InputManager.h" +#include "Window.h" #include "components/TextComponent.h" #include "guis/GuiInputConfig.h" #include "utils/FileSystemUtil.h" #include "utils/StringUtil.h" -#include "InputManager.h" -#include "Window.h" #define HOLD_TIME 1000 -GuiDetectDevice::GuiDetectDevice( - Window* window, - bool firstRun, - bool forcedConfig, - const std::function& doneCallback) - : GuiComponent(window), - mFirstRun(firstRun), - mForcedConfig(forcedConfig), - mBackground(window, ":/graphics/frame.svg"), - mGrid(window, Vector2i(1, 5)) +GuiDetectDevice::GuiDetectDevice(Window* window, + bool firstRun, + bool forcedConfig, + const std::function& doneCallback) + : GuiComponent(window) + , mFirstRun(firstRun) + , mForcedConfig(forcedConfig) + , mBackground(window, ":/graphics/frame.svg") + , mGrid(window, Vector2i(1, 5)) { mHoldingConfig = nullptr; mHoldTime = 0; @@ -36,8 +35,9 @@ GuiDetectDevice::GuiDetectDevice( addChild(&mGrid); // Title. - mTitle = std::make_shared(mWindow, firstRun ? "WELCOME" : - "CONFIGURE INPUT DEVICE", Font::get(FONT_SIZE_LARGE), 0x555555FF, ALIGN_CENTER); + mTitle = + std::make_shared(mWindow, firstRun ? "WELCOME" : "CONFIGURE INPUT DEVICE", + Font::get(FONT_SIZE_LARGE), 0x555555FF, ALIGN_CENTER); mGrid.setEntry(mTitle, Vector2i(0, 0), false, true, Vector2i(1, 1), GridFlags::BORDER_BOTTOM); // Device info. @@ -52,33 +52,33 @@ GuiDetectDevice::GuiDetectDevice( if (numDevices > 1 && Settings::getInstance()->getBool("InputOnlyFirstController")) deviceInfo << " (ONLY ACCEPTING INPUT FROM FIRST CONTROLLER)"; - mDeviceInfo = std::make_shared(mWindow, deviceInfo.str(), - Font::get(FONT_SIZE_SMALL), 0x999999FF, ALIGN_CENTER); + mDeviceInfo = std::make_shared( + mWindow, deviceInfo.str(), Font::get(FONT_SIZE_SMALL), 0x999999FF, ALIGN_CENTER); mGrid.setEntry(mDeviceInfo, Vector2i(0, 1), false, true); // Message. if (numDevices > 0) { - mMsg1 = std::make_shared(mWindow, - "HOLD A BUTTON ON YOUR GAMEPAD OR KEYBOARD TO CONFIGURE IT", - Font::get(FONT_SIZE_SMALL), 0x777777FF, ALIGN_CENTER); + mMsg1 = std::make_shared( + mWindow, "HOLD A BUTTON ON YOUR GAMEPAD OR KEYBOARD TO CONFIGURE IT", + Font::get(FONT_SIZE_SMALL), 0x777777FF, ALIGN_CENTER); } else { - mMsg1 = std::make_shared(mWindow, - "HOLD A BUTTON ON YOUR KEYBOARD TO CONFIGURE IT", - Font::get(FONT_SIZE_SMALL), 0x777777FF, ALIGN_CENTER); + mMsg1 = std::make_shared( + mWindow, "HOLD A BUTTON ON YOUR KEYBOARD TO CONFIGURE IT", Font::get(FONT_SIZE_SMALL), + 0x777777FF, ALIGN_CENTER); } mGrid.setEntry(mMsg1, Vector2i(0, 2), false, true); - const std::string msg2str = firstRun ? - "PRESS ESC TO SKIP (OR F4 TO QUIT AT ANY TIME)" : "PRESS ESC TO CANCEL"; - mMsg2 = std::make_shared(mWindow, msg2str, - Font::get(FONT_SIZE_SMALL), 0x777777FF, ALIGN_CENTER); + const std::string msg2str = + firstRun ? "PRESS ESC TO SKIP (OR F4 TO QUIT AT ANY TIME)" : "PRESS ESC TO CANCEL"; + mMsg2 = std::make_shared(mWindow, msg2str, Font::get(FONT_SIZE_SMALL), + 0x777777FF, ALIGN_CENTER); mGrid.setEntry(mMsg2, Vector2i(0, 3), false, true); // Currently held device. - mDeviceHeld = std::make_shared(mWindow, "", - Font::get(FONT_SIZE_MEDIUM), 0xFFFFFFFF, ALIGN_CENTER); + mDeviceHeld = std::make_shared(mWindow, "", Font::get(FONT_SIZE_MEDIUM), + 0xFFFFFFFF, ALIGN_CENTER); mGrid.setEntry(mDeviceHeld, Vector2i(0, 4), false, true); // Adjust the width relative to the aspect ratio of the screen to make the GUI look coherent @@ -87,27 +87,27 @@ GuiDetectDevice::GuiDetectDevice( float width = Math::clamp(0.60f * aspectValue, 0.50f, 0.80f) * Renderer::getScreenWidth(); setSize(width, Renderer::getScreenHeight() * 0.5f); - setPosition((Renderer::getScreenWidth() - mSize.x()) / 2, - (Renderer::getScreenHeight() - mSize.y()) / 2); + setPosition((Renderer::getScreenWidth() - mSize.x()) / 2.0f, + (Renderer::getScreenHeight() - mSize.y()) / 2.0f); } void GuiDetectDevice::onSizeChanged() { - mBackground.fitTo(mSize, Vector3f::Zero(), Vector2f(-32, -32)); + mBackground.fitTo(mSize, Vector3f::Zero(), Vector2f(-32.0f, -32.0f)); // Grid. mGrid.setSize(mSize); mGrid.setRowHeightPerc(0, mTitle->getFont()->getHeight() / mSize.y()); - //mGrid.setRowHeightPerc(1, mDeviceInfo->getFont()->getHeight() / mSize.y()); + // mGrid.setRowHeightPerc(1, mDeviceInfo->getFont()->getHeight() / mSize.y()); mGrid.setRowHeightPerc(2, mMsg1->getFont()->getHeight() / mSize.y()); mGrid.setRowHeightPerc(3, mMsg2->getFont()->getHeight() / mSize.y()); - //mGrid.setRowHeightPerc(4, mDeviceHeld->getFont()->getHeight() / mSize.y()); + // mGrid.setRowHeightPerc(4, mDeviceHeld->getFont()->getHeight() / mSize.y()); } bool GuiDetectDevice::input(InputConfig* config, Input input) { - if (!mFirstRun && input.device == DEVICE_KEYBOARD && input.type == TYPE_KEY && - input.value && input.id == SDLK_ESCAPE) { + if (!mFirstRun && input.device == DEVICE_KEYBOARD && input.type == TYPE_KEY && input.value && + input.id == SDLK_ESCAPE) { // Cancel the configuration. delete this; // Delete GUI element. return true; @@ -115,15 +115,15 @@ bool GuiDetectDevice::input(InputConfig* config, Input input) // First run, but the user chooses to skip the configuration. This will default to the // built-in keyboard mappings. else if (mFirstRun && input.device == DEVICE_KEYBOARD && input.type == TYPE_KEY && - input.value && input.id == SDLK_ESCAPE) { - if (mDoneCallback) - mDoneCallback(); - delete this; // Delete GUI element. - return true; + input.value && input.id == SDLK_ESCAPE) { + if (mDoneCallback) + mDoneCallback(); + delete this; // Delete GUI element. + return true; } if (input.type == TYPE_BUTTON || input.type == TYPE_AXIS || input.type == TYPE_KEY || - input.type == TYPE_CEC_BUTTON) { + input.type == TYPE_CEC_BUTTON) { if (input.value && mHoldingConfig == nullptr) { // Started holding. mHoldingConfig = config; @@ -146,8 +146,8 @@ void GuiDetectDevice::update(int deltaTime) // configuration unless the flag to force the configuration was passed on the // command line. if (!mForcedConfig && mFirstRun && - Utils::FileSystem::exists(InputManager::getConfigPath()) && - InputManager::getInstance()->getNumConfiguredDevices() > 0) { + Utils::FileSystem::exists(InputManager::getConfigPath()) && + InputManager::getInstance()->getNumConfiguredDevices() > 0) { if (mDoneCallback) mDoneCallback(); delete this; // Delete GUI element. diff --git a/es-core/src/guis/GuiDetectDevice.h b/es-core/src/guis/GuiDetectDevice.h index d482491d4..a9a6da560 100644 --- a/es-core/src/guis/GuiDetectDevice.h +++ b/es-core/src/guis/GuiDetectDevice.h @@ -9,17 +9,19 @@ #ifndef ES_CORE_GUIS_GUI_DETECT_DEVICE_H #define ES_CORE_GUIS_GUI_DETECT_DEVICE_H +#include "GuiComponent.h" #include "components/ComponentGrid.h" #include "components/NinePatchComponent.h" -#include "GuiComponent.h" class TextComponent; class GuiDetectDevice : public GuiComponent { public: - GuiDetectDevice(Window* window, bool firstRun, bool forcedConfig, - const std::function& doneCallback); + GuiDetectDevice(Window* window, + bool firstRun, + bool forcedConfig, + const std::function& doneCallback); bool input(InputConfig* config, Input input) override; void update(int deltaTime) override; diff --git a/es-core/src/guis/GuiInputConfig.cpp b/es-core/src/guis/GuiInputConfig.cpp index 1c97db6ab..c3c76e692 100644 --- a/es-core/src/guis/GuiInputConfig.cpp +++ b/es-core/src/guis/GuiInputConfig.cpp @@ -8,12 +8,12 @@ #include "guis/GuiInputConfig.h" -#include "components/ButtonComponent.h" -#include "components/MenuComponent.h" -#include "guis/GuiMsgBox.h" #include "InputManager.h" #include "Log.h" #include "Window.h" +#include "components/ButtonComponent.h" +#include "components/MenuComponent.h" +#include "guis/GuiMsgBox.h" #define HOLD_TO_SKIP_MS 1000 @@ -27,23 +27,22 @@ struct InputConfigStructure { static const int inputCount = 24; static InputConfigStructure sGuiInputConfigList[inputCount]; -GuiInputConfig::GuiInputConfig( - Window* window, - InputConfig* target, - bool reconfigureAll, - const std::function& okCallback) - : GuiComponent(window), - mBackground(window, ":/graphics/frame.svg"), - mGrid(window, Vector2i(1, 7)), - mTargetConfig(target), - mHoldingInput(false) +GuiInputConfig::GuiInputConfig(Window* window, + InputConfig* target, + bool reconfigureAll, + const std::function& okCallback) + : GuiComponent(window) + , mBackground(window, ":/graphics/frame.svg") + , mGrid(window, Vector2i(1, 7)) + , mTargetConfig(target) + , mHoldingInput(false) { // Populate the configuration list with the text and icons applicable to the // configured controller type. populateConfigList(); - LOG(LogInfo) << "Configuring device " << target->getDeviceId() << " (" << - target->getDeviceName() << ")."; + LOG(LogInfo) << "Configuring device " << target->getDeviceId() << " (" + << target->getDeviceName() << ")."; if (reconfigureAll) target->clear(); @@ -57,8 +56,8 @@ GuiInputConfig::GuiInputConfig( // 0 is a spacer row. mGrid.setEntry(std::make_shared(mWindow), Vector2i(0, 0), false); - mTitle = std::make_shared(mWindow, "CONFIGURING", - Font::get(FONT_SIZE_LARGE), 0x555555FF, ALIGN_CENTER); + mTitle = std::make_shared(mWindow, "CONFIGURING", Font::get(FONT_SIZE_LARGE), + 0x555555FF, ALIGN_CENTER); mGrid.setEntry(mTitle, Vector2i(0, 1), false, true); std::stringstream ss; @@ -67,13 +66,15 @@ GuiInputConfig::GuiInputConfig( else if (target->getDeviceId() == DEVICE_CEC) ss << "CEC"; else - ss << "GAMEPAD " << (target->getDeviceId() + 1) << " (" << target->getDeviceName() << ")"; - mSubtitle1 = std::make_shared(mWindow, Utils::String::toUpper(ss.str()), - Font::get(FONT_SIZE_MEDIUM), 0x555555FF, ALIGN_CENTER); + ss << "GAMEPAD " << (target->getDeviceId() + 1) << " (" << target->getDeviceName() << ")"; + mSubtitle1 = + std::make_shared(mWindow, Utils::String::toUpper(ss.str()), + Font::get(FONT_SIZE_MEDIUM), 0x555555FF, ALIGN_CENTER); mGrid.setEntry(mSubtitle1, Vector2i(0, 2), false, true); - mSubtitle2 = std::make_shared(mWindow, "HOLD ANY BUTTON 1 SECOND TO SKIP", - Font::get(FONT_SIZE_SMALL), 0x999999FF, ALIGN_CENTER); + mSubtitle2 = + std::make_shared(mWindow, "HOLD ANY BUTTON 1 SECOND TO SKIP", + Font::get(FONT_SIZE_SMALL), 0x999999FF, ALIGN_CENTER); // The opacity will be set to visible for any row that is skippable. mSubtitle2->setOpacity(0); @@ -98,12 +99,13 @@ GuiInputConfig::GuiInputConfig( spacer->setSize(16, 0); row.addElement(spacer, false); - auto text = std::make_shared(mWindow, - sGuiInputConfigList[i].dispName, Font::get(FONT_SIZE_MEDIUM), 0x777777FF); + auto text = std::make_shared(mWindow, sGuiInputConfigList[i].dispName, + Font::get(FONT_SIZE_MEDIUM), 0x777777FF); row.addElement(text, true); auto mapping = std::make_shared(mWindow, "-NOT DEFINED-", - Font::get(FONT_SIZE_MEDIUM, FONT_PATH_LIGHT), 0x999999FF, ALIGN_RIGHT); + Font::get(FONT_SIZE_MEDIUM, FONT_PATH_LIGHT), + 0x999999FF, ALIGN_RIGHT); setNotDefined(mapping); // Overrides the text and color set above. row.addElement(mapping, true); mMappings.push_back(mapping); @@ -142,9 +144,10 @@ GuiInputConfig::GuiInputConfig( else { // Button released. Make sure we were holding something and we let go of // what we were previously holding. - if (!mHoldingInput || mHeldInput.device != input.device || mHeldInput.id != - input.id || mHeldInput.type != input.type) + if (!mHoldingInput || mHeldInput.device != input.device || + mHeldInput.id != input.id || mHeldInput.type != input.type) { return true; + } mHoldingInput = false; @@ -177,8 +180,8 @@ GuiInputConfig::GuiInputConfig( delete this; }; - buttons.push_back(std::make_shared - (mWindow, "OK", "ok", [this, okFunction] { okFunction(); })); + buttons.push_back(std::make_shared(mWindow, "OK", "ok", + [this, okFunction] { okFunction(); })); mButtonGrid = makeButtonGrid(mWindow, buttons); mGrid.setEntry(mButtonGrid, Vector2i(0, 6), true, false); @@ -190,122 +193,76 @@ GuiInputConfig::GuiInputConfig( setSize(width, Renderer::getScreenHeight() * 0.75f); setPosition((Renderer::getScreenWidth() - mSize.x()) / 2.0f, - (Renderer::getScreenHeight() - mSize.y()) / 2.0f); + (Renderer::getScreenHeight() - mSize.y()) / 2.0f); } void GuiInputConfig::populateConfigList() { std::string controllerType = Settings::getInstance()->getString("InputControllerType"); - sGuiInputConfigList[0] = - { "Up", false, "D-PAD UP", ":/help/dpad_up.svg" }; - sGuiInputConfigList[1] = - { "Down", false, "D-PAD DOWN", ":/help/dpad_down.svg" }; - sGuiInputConfigList[2] = - { "Left", false, "D-PAD LEFT", ":/help/dpad_left.svg" }; - sGuiInputConfigList[3] = - { "Right", false, "D-PAD RIGHT", ":/help/dpad_right.svg" }; + // clang-format off + sGuiInputConfigList[0] = { "Up", false, "D-PAD UP", ":/help/dpad_up.svg" }; + sGuiInputConfigList[1] = { "Down", false, "D-PAD DOWN", ":/help/dpad_down.svg" }; + sGuiInputConfigList[2] = { "Left", false, "D-PAD LEFT", ":/help/dpad_left.svg" }; + sGuiInputConfigList[3] = { "Right", false, "D-PAD RIGHT", ":/help/dpad_right.svg" }; if (controllerType == "snes") { - sGuiInputConfigList[4] = - { "Back", false, "SELECT", ":/help/button_back_SNES.svg" }; - sGuiInputConfigList[5] = - { "Start", false, "START", ":/help/button_start_SNES.svg" }; - sGuiInputConfigList[6] = - { "A", false, "B", ":/help/mbuttons_a_SNES.svg" }; - sGuiInputConfigList[7] = - { "B", false, "A", ":/help/mbuttons_b_SNES.svg" }; - sGuiInputConfigList[8] = - { "X", true, "Y", ":/help/mbuttons_x_SNES.svg" }; - sGuiInputConfigList[9] = - { "Y", true, "X", ":/help/mbuttons_y_SNES.svg" }; + sGuiInputConfigList[4] = { "Back", false, "SELECT", ":/help/button_back_SNES.svg" }; + sGuiInputConfigList[5] = { "Start", false, "START", ":/help/button_start_SNES.svg" }; + sGuiInputConfigList[6] = { "A", false, "B", ":/help/mbuttons_a_SNES.svg" }; + sGuiInputConfigList[7] = { "B", false, "A", ":/help/mbuttons_b_SNES.svg" }; + sGuiInputConfigList[8] = { "X", true, "Y", ":/help/mbuttons_x_SNES.svg" }; + sGuiInputConfigList[9] = { "Y", true, "X", ":/help/mbuttons_y_SNES.svg" }; } else if (controllerType == "ps4") { - sGuiInputConfigList[4] = - { "Back", false, "SHARE", ":/help/button_back_PS4.svg" }; - sGuiInputConfigList[5] = - { "Start", false, "OPTIONS", ":/help/button_start_PS4.svg" }; - sGuiInputConfigList[6] = - { "A", false, "CROSS", ":/help/mbuttons_a_PS.svg" }; - sGuiInputConfigList[7] = - { "B", false, "CIRCLE", ":/help/mbuttons_b_PS.svg" }; - sGuiInputConfigList[8] = - { "X", true, "SQUARE", ":/help/mbuttons_x_PS.svg" }; - sGuiInputConfigList[9] = - { "Y", true, "TRIANGLE", ":/help/mbuttons_y_PS.svg" }; + sGuiInputConfigList[4] = { "Back", false, "SHARE", ":/help/button_back_PS4.svg" }; + sGuiInputConfigList[5] = { "Start", false, "OPTIONS", ":/help/button_start_PS4.svg" }; + sGuiInputConfigList[6] = { "A", false, "CROSS", ":/help/mbuttons_a_PS.svg" }; + sGuiInputConfigList[7] = { "B", false, "CIRCLE", ":/help/mbuttons_b_PS.svg" }; + sGuiInputConfigList[8] = { "X", true, "SQUARE", ":/help/mbuttons_x_PS.svg" }; + sGuiInputConfigList[9] = { "Y", true, "TRIANGLE", ":/help/mbuttons_y_PS.svg" }; } else if (controllerType == "ps5") { - sGuiInputConfigList[4] = - { "Back", false, "CREATE", ":/help/button_back_PS5.svg" }; - sGuiInputConfigList[5] = - { "Start", false, "OPTIONS", ":/help/button_start_PS5.svg" }; - sGuiInputConfigList[6] = - { "A", false, "CROSS", ":/help/mbuttons_a_PS.svg" }; - sGuiInputConfigList[7] = - { "B", false, "CIRCLE", ":/help/mbuttons_b_PS.svg" }; - sGuiInputConfigList[8] = - { "X", true, "SQUARE", ":/help/mbuttons_x_PS.svg" }; - sGuiInputConfigList[9] = - { "Y", true, "TRIANGLE", ":/help/mbuttons_y_PS.svg" }; + sGuiInputConfigList[4] = { "Back", false, "CREATE", ":/help/button_back_PS5.svg" }; + sGuiInputConfigList[5] = { "Start", false, "OPTIONS", ":/help/button_start_PS5.svg" }; + sGuiInputConfigList[6] = { "A", false, "CROSS", ":/help/mbuttons_a_PS.svg" }; + sGuiInputConfigList[7] = { "B", false, "CIRCLE", ":/help/mbuttons_b_PS.svg" }; + sGuiInputConfigList[8] = { "X", true, "SQUARE", ":/help/mbuttons_x_PS.svg" }; + sGuiInputConfigList[9] = { "Y", true, "TRIANGLE", ":/help/mbuttons_y_PS.svg" }; } else if (controllerType == "xbox360") { - sGuiInputConfigList[4] = - { "Back", false, "BACK", ":/help/button_back_XBOX360.svg" }; - sGuiInputConfigList[5] = - { "Start", false, "START", ":/help/button_start_XBOX360.svg" }; - sGuiInputConfigList[6] = - { "A", false, "A", ":/help/mbuttons_a_XBOX.svg" }; - sGuiInputConfigList[7] = - { "B", false, "B", ":/help/mbuttons_b_XBOX.svg" }; - sGuiInputConfigList[8] = - { "X", true, "X", ":/help/mbuttons_x_XBOX.svg" }; - sGuiInputConfigList[9] = - { "Y", true, "Y", ":/help/mbuttons_y_XBOX.svg" }; + sGuiInputConfigList[4] = { "Back", false, "BACK", ":/help/button_back_XBOX360.svg" }; + sGuiInputConfigList[5] = { "Start", false, "START", ":/help/button_start_XBOX360.svg" }; + sGuiInputConfigList[6] = { "A", false, "A", ":/help/mbuttons_a_XBOX.svg" }; + sGuiInputConfigList[7] = { "B", false, "B", ":/help/mbuttons_b_XBOX.svg" }; + sGuiInputConfigList[8] = { "X", true, "X", ":/help/mbuttons_x_XBOX.svg" }; + sGuiInputConfigList[9] = { "Y", true, "Y", ":/help/mbuttons_y_XBOX.svg" }; } else { // Xbox One and later. - sGuiInputConfigList[4] = - { "Back", false, "VIEW", ":/help/button_back_XBOX.svg" }; - sGuiInputConfigList[5] = - { "Start", false, "MENU", ":/help/button_start_XBOX.svg" }; - sGuiInputConfigList[6] = - { "A", false, "A", ":/help/mbuttons_a_XBOX.svg" }; - sGuiInputConfigList[7] = - { "B", false, "B", ":/help/mbuttons_b_XBOX.svg" }; - sGuiInputConfigList[8] = - { "X", true, "X", ":/help/mbuttons_x_XBOX.svg" }; - sGuiInputConfigList[9] = - { "Y", true, "Y", ":/help/mbuttons_y_XBOX.svg" }; + sGuiInputConfigList[4] = { "Back", false, "VIEW", ":/help/button_back_XBOX.svg" }; + sGuiInputConfigList[5] = { "Start", false, "MENU", ":/help/button_start_XBOX.svg" }; + sGuiInputConfigList[6] = { "A", false, "A", ":/help/mbuttons_a_XBOX.svg" }; + sGuiInputConfigList[7] = { "B", false, "B", ":/help/mbuttons_b_XBOX.svg" }; + sGuiInputConfigList[8] = { "X", true, "X", ":/help/mbuttons_x_XBOX.svg" }; + sGuiInputConfigList[9] = { "Y", true, "Y", ":/help/mbuttons_y_XBOX.svg" }; } - sGuiInputConfigList[10] = - { "LeftShoulder", true, "LEFT SHOULDER", ":/help/button_l.svg" }; - sGuiInputConfigList[11] = - { "RightShoulder", true, "RIGHT SHOULDER", ":/help/button_r.svg" }; - sGuiInputConfigList[12] = - { "LeftTrigger", true, "LEFT TRIGGER", ":/help/button_lt.svg" }; - sGuiInputConfigList[13] = - { "RightTrigger", true, "RIGHT TRIGGER", ":/help/button_rt.svg" }; - sGuiInputConfigList[14] = - { "LeftThumbstickUp", true, "LEFT THUMBSTICK UP", ":/help/thumbstick_up.svg" }; - sGuiInputConfigList[15] = - { "LeftThumbstickDown", true, "LEFT THUMBSTICK DOWN", ":/help/thumbstick_down.svg" }; - sGuiInputConfigList[16] = - { "LeftThumbstickLeft", true, "LEFT THUMBSTICK LEFT", ":/help/thumbstick_left.svg" }; - sGuiInputConfigList[17] = - { "LeftThumbstickRight", true, "LEFT THUMBSTICK RIGHT", ":/help/thumbstick_right.svg" }; - sGuiInputConfigList[18] = - { "LeftThumbstickClick", true, "LEFT THUMBSTICK CLICK", ":/help/thumbstick_click.svg" }; - sGuiInputConfigList[19] = - { "RightThumbstickUp", true, "RIGHT THUMBSTICK UP", ":/help/thumbstick_up.svg" }; - sGuiInputConfigList[20] = - { "RightThumbstickDown", true, "RIGHT THUMBSTICK DOWN", ":/help/thumbstick_down.svg" }; - sGuiInputConfigList[21] = - { "RightThumbstickLeft", true, "RIGHT THUMBSTICK LEFT", ":/help/thumbstick_left.svg" }; - sGuiInputConfigList[22] = - { "RightThumbstickRight", true, "RIGHT THUMBSTICK RIGHT", ":/help/thumbstick_right.svg" }; - sGuiInputConfigList[23] = - { "RightThumbstickClick", true, "RIGHT THUMBSTICK CLICK", ":/help/thumbstick_click.svg" }; + sGuiInputConfigList[10] = { "LeftShoulder", true, "LEFT SHOULDER", ":/help/button_l.svg" }; + sGuiInputConfigList[11] = { "RightShoulder", true, "RIGHT SHOULDER", ":/help/button_r.svg" }; + sGuiInputConfigList[12] = { "LeftTrigger", true, "LEFT TRIGGER", ":/help/button_lt.svg" }; + sGuiInputConfigList[13] = { "RightTrigger", true, "RIGHT TRIGGER", ":/help/button_rt.svg" }; + sGuiInputConfigList[14] = { "LeftThumbstickUp", true, "LEFT THUMBSTICK UP", ":/help/thumbstick_up.svg" }; + sGuiInputConfigList[15] = { "LeftThumbstickDown", true, "LEFT THUMBSTICK DOWN", ":/help/thumbstick_down.svg" }; + sGuiInputConfigList[16] = { "LeftThumbstickLeft", true, "LEFT THUMBSTICK LEFT", ":/help/thumbstick_left.svg" }; + sGuiInputConfigList[17] = { "LeftThumbstickRight", true, "LEFT THUMBSTICK RIGHT", ":/help/thumbstick_right.svg" }; + sGuiInputConfigList[18] = { "LeftThumbstickClick", true, "LEFT THUMBSTICK CLICK", ":/help/thumbstick_click.svg" }; + sGuiInputConfigList[19] = { "RightThumbstickUp", true, "RIGHT THUMBSTICK UP", ":/help/thumbstick_up.svg" }; + sGuiInputConfigList[20] = { "RightThumbstickDown", true, "RIGHT THUMBSTICK DOWN", ":/help/thumbstick_down.svg" }; + sGuiInputConfigList[21] = { "RightThumbstickLeft", true, "RIGHT THUMBSTICK LEFT", ":/help/thumbstick_left.svg" }; + sGuiInputConfigList[22] = { "RightThumbstickRight", true, "RIGHT THUMBSTICK RIGHT", ":/help/thumbstick_right.svg" }; + sGuiInputConfigList[23] = { "RightThumbstickClick", true, "RIGHT THUMBSTICK CLICK", ":/help/thumbstick_click.svg" }; + // clang-format on } void GuiInputConfig::update(int deltaTime) @@ -336,7 +293,7 @@ void GuiInputConfig::update(int deltaTime) void GuiInputConfig::onSizeChanged() { - mBackground.fitTo(mSize, Vector3f::Zero(), Vector2f(-32, -32)); + mBackground.fitTo(mSize, Vector3f::Zero(), Vector2f(-32.0f, -32.0f)); // Update grid. mGrid.setSize(mSize); @@ -400,8 +357,8 @@ bool GuiInputConfig::assign(Input input, int inputId) // If this input is mapped to something other than "nothing" or the current row, // generate an error. (If it's the same as what it was before, allow it.) if (mTargetConfig->getMappedTo(input).size() > 0 && - !mTargetConfig->isMappedTo(sGuiInputConfigList[inputId].name, input) && - sGuiInputConfigList[inputId].name != "HotKeyEnable") { + !mTargetConfig->isMappedTo(sGuiInputConfigList[inputId].name, input) && + sGuiInputConfigList[inputId].name != "HotKeyEnable") { error(mMappings.at(inputId), "Already mapped!"); return false; } @@ -411,8 +368,8 @@ bool GuiInputConfig::assign(Input input, int inputId) input.configured = true; mTargetConfig->mapInput(sGuiInputConfigList[inputId].name, input); - LOG(LogInfo) << "Mapping [" << input.string() << "] to [" << - sGuiInputConfigList[inputId].name << "]"; + LOG(LogInfo) << "Mapping [" << input.string() << "] to [" << sGuiInputConfigList[inputId].name + << "]"; return true; } diff --git a/es-core/src/guis/GuiInputConfig.h b/es-core/src/guis/GuiInputConfig.h index 97c31b31e..317c2d3c5 100644 --- a/es-core/src/guis/GuiInputConfig.h +++ b/es-core/src/guis/GuiInputConfig.h @@ -9,9 +9,9 @@ #ifndef ES_CORE_GUIS_GUI_INPUT_CONFIG_H #define ES_CORE_GUIS_GUI_INPUT_CONFIG_H +#include "GuiComponent.h" #include "components/ComponentGrid.h" #include "components/NinePatchComponent.h" -#include "GuiComponent.h" class ComponentList; class TextComponent; @@ -19,8 +19,10 @@ class TextComponent; class GuiInputConfig : public GuiComponent { public: - GuiInputConfig(Window* window, InputConfig* target, bool reconfigureAll, - const std::function& okCallback); + GuiInputConfig(Window* window, + InputConfig* target, + bool reconfigureAll, + const std::function& okCallback); void populateConfigList(); diff --git a/es-core/src/guis/GuiMsgBox.cpp b/es-core/src/guis/GuiMsgBox.cpp index 16b87ef5b..9006fec4e 100644 --- a/es-core/src/guis/GuiMsgBox.cpp +++ b/es-core/src/guis/GuiMsgBox.cpp @@ -14,50 +14,55 @@ #define HORIZONTAL_PADDING_PX 20 -GuiMsgBox::GuiMsgBox(Window* window, const HelpStyle& helpstyle, const std::string& text, - const std::string& name1, const std::function& func1, - const std::string& name2, const std::function& func2, - const std::string& name3, const std::function& func3, - bool disableBackButton, - bool deleteOnButtonPress) - : GuiComponent(window), - mHelpStyle(helpstyle), - mBackground(window, ":/graphics/frame.svg"), - mGrid(window, Vector2i(1, 2)), - mDisableBackButton(disableBackButton), - mDeleteOnButtonPress(deleteOnButtonPress) +GuiMsgBox::GuiMsgBox(Window* window, + const HelpStyle& helpstyle, + const std::string& text, + const std::string& name1, + const std::function& func1, + const std::string& name2, + const std::function& func2, + const std::string& name3, + const std::function& func3, + bool disableBackButton, + bool deleteOnButtonPress) + : GuiComponent(window) + , mHelpStyle(helpstyle) + , mBackground(window, ":/graphics/frame.svg") + , mGrid(window, Vector2i(1, 2)) + , mDisableBackButton(disableBackButton) + , mDeleteOnButtonPress(deleteOnButtonPress) { // Adjust the width relative to the aspect ratio of the screen to make the GUI look coherent // regardless of screen type. The 1.778 aspect ratio value is the 16:9 reference. float aspectValue = 1.778f / Renderer::getScreenAspectRatio(); - float width = floorf(Math::clamp(0.60f * aspectValue, 0.60f, 0.80f) * - Renderer::getScreenWidth()); - float minWidth = floorf(Math::clamp(0.30f * aspectValue, 0.10f, 0.50f) * - Renderer::getScreenWidth()); + float width = + floorf(Math::clamp(0.60f * aspectValue, 0.60f, 0.80f) * Renderer::getScreenWidth()); + float minWidth = + floorf(Math::clamp(0.30f * aspectValue, 0.10f, 0.50f) * Renderer::getScreenWidth()); - mMsg = std::make_shared(mWindow, text, Font::get(FONT_SIZE_MEDIUM), - 0x777777FF, ALIGN_CENTER); + mMsg = std::make_shared(mWindow, text, Font::get(FONT_SIZE_MEDIUM), 0x777777FF, + ALIGN_CENTER); mGrid.setEntry(mMsg, Vector2i(0, 0), false, false); // Create the buttons. - mButtons.push_back(std::make_shared - (mWindow, name1, name1, std::bind(&GuiMsgBox::deleteMeAndCall, this, func1))); + mButtons.push_back(std::make_shared( + mWindow, name1, name1, std::bind(&GuiMsgBox::deleteMeAndCall, this, func1))); if (!name2.empty()) - mButtons.push_back(std::make_shared - (mWindow, name2, name2, std::bind(&GuiMsgBox::deleteMeAndCall, this, func2))); + mButtons.push_back(std::make_shared( + mWindow, name2, name2, std::bind(&GuiMsgBox::deleteMeAndCall, this, func2))); if (!name3.empty()) - mButtons.push_back(std::make_shared - (mWindow, name3, name3, std::bind(&GuiMsgBox::deleteMeAndCall, this, func3))); + mButtons.push_back(std::make_shared( + mWindow, name3, name3, std::bind(&GuiMsgBox::deleteMeAndCall, this, func3))); - // Set accelerator automatically (button to press when "b" is pressed). + // Set accelerator automatically (button to press when "B" is pressed). if (mButtons.size() == 1) { mAcceleratorFunc = mButtons.front()->getPressedFunc(); } else { for (auto it = mButtons.cbegin(); it != mButtons.cend(); it++) { if (Utils::String::toUpper((*it)->getText()) == "OK" || - Utils::String::toUpper((*it)->getText()) == "NO") { + Utils::String::toUpper((*it)->getText()) == "NO") { mAcceleratorFunc = (*it)->getPressedFunc(); break; } @@ -80,14 +85,14 @@ GuiMsgBox::GuiMsgBox(Window* window, const HelpStyle& helpstyle, const std::stri // Now that we know width, we can find height. mMsg->setSize(width, 0); // mMsg->getSize.y() now returns the proper length. - const float msgHeight = std::max(Font::get(FONT_SIZE_LARGE)->getHeight(), - mMsg->getSize().y() * 1.225f); + const float msgHeight = + std::max(Font::get(FONT_SIZE_LARGE)->getHeight(), mMsg->getSize().y() * 1.225f); setSize(width + HORIZONTAL_PADDING_PX * 2 * Renderer::getScreenWidthModifier(), msgHeight + mButtonGrid->getSize().y()); // Center for good measure. setPosition((Renderer::getScreenWidth() - mSize.x()) / 2.0f, - (Renderer::getScreenHeight() - mSize.y()) / 2.0f); + (Renderer::getScreenHeight() - mSize.y()) / 2.0f); addChild(&mBackground); addChild(&mGrid); @@ -103,8 +108,8 @@ void GuiMsgBox::changeText(const std::string& newText) // reference. float aspectValue = 1.778f / Renderer::getScreenAspectRatio(); - float width = floorf(Math::clamp(0.60f * aspectValue, 0.60f, 0.80f) * - Renderer::getScreenWidth()); + float width = + floorf(Math::clamp(0.60f * aspectValue, 0.60f, 0.80f) * Renderer::getScreenWidth()); float minWidth = Renderer::getScreenWidth() * 0.3f; // Decide final width. @@ -119,8 +124,8 @@ void GuiMsgBox::changeText(const std::string& newText) // Now that we know width, we can find height. mMsg->setSize(width, 0); // mMsg->getSize.y() now returns the proper length. - const float msgHeight = std::max(Font::get(FONT_SIZE_LARGE)->getHeight(), - mMsg->getSize().y() * 1.225f); + const float msgHeight = + std::max(Font::get(FONT_SIZE_LARGE)->getHeight(), mMsg->getSize().y() * 1.225f); setSize(width + HORIZONTAL_PADDING_PX * 2 * Renderer::getScreenWidthModifier(), msgHeight + mButtonGrid->getSize().y()); } @@ -152,10 +157,10 @@ void GuiMsgBox::onSizeChanged() // Update messagebox size. mMsg->setSize(mSize.x() - HORIZONTAL_PADDING_PX * 2 * Renderer::getScreenWidthModifier(), - mGrid.getRowHeight(0)); + mGrid.getRowHeight(0)); mGrid.onSizeChanged(); - mBackground.fitTo(mSize, Vector3f::Zero(), Vector2f(-32, -32)); + mBackground.fitTo(mSize, Vector3f::Zero(), Vector2f(-32.0f, -32.0f)); } void GuiMsgBox::deleteMeAndCall(const std::function& func) diff --git a/es-core/src/guis/GuiMsgBox.h b/es-core/src/guis/GuiMsgBox.h index 9997c4d8b..edb04b697 100644 --- a/es-core/src/guis/GuiMsgBox.h +++ b/es-core/src/guis/GuiMsgBox.h @@ -10,9 +10,9 @@ #ifndef ES_CORE_GUIS_GUI_MSG_BOX_H #define ES_CORE_GUIS_GUI_MSG_BOX_H +#include "GuiComponent.h" #include "components/ComponentGrid.h" #include "components/NinePatchComponent.h" -#include "GuiComponent.h" class ButtonComponent; class TextComponent; @@ -20,18 +20,17 @@ class TextComponent; class GuiMsgBox : public GuiComponent { public: - GuiMsgBox( - Window* window, - const HelpStyle& helpstyle, - const std::string& text, - const std::string& name1 = "OK", - const std::function& func1 = nullptr, - const std::string& name2 = "", - const std::function& func2 = nullptr, - const std::string& name3 = "", - const std::function& func3 = nullptr, - bool disableBackButton = false, - bool deleteOnButtonPress = true); + GuiMsgBox(Window* window, + const HelpStyle& helpstyle, + const std::string& text, + const std::string& name1 = "OK", + const std::function& func1 = nullptr, + const std::string& name2 = "", + const std::function& func2 = nullptr, + const std::string& name3 = "", + const std::function& func3 = nullptr, + bool disableBackButton = false, + bool deleteOnButtonPress = true); void changeText(const std::string& newText); @@ -39,7 +38,7 @@ public: void onSizeChanged() override; std::vector getHelpPrompts() override; - HelpStyle getHelpStyle() override { return mHelpStyle; }; + HelpStyle getHelpStyle() override { return mHelpStyle; } private: void deleteMeAndCall(const std::function& func); diff --git a/es-core/src/guis/GuiTextEditPopup.cpp b/es-core/src/guis/GuiTextEditPopup.cpp index 1bdb06961..27fe9eb1d 100644 --- a/es-core/src/guis/GuiTextEditPopup.cpp +++ b/es-core/src/guis/GuiTextEditPopup.cpp @@ -8,58 +8,60 @@ #include "guis/GuiTextEditPopup.h" +#include "Window.h" #include "components/ButtonComponent.h" #include "components/MenuComponent.h" #include "components/TextEditComponent.h" #include "guis/GuiMsgBox.h" -#include "Window.h" -GuiTextEditPopup::GuiTextEditPopup( - Window* window, - const HelpStyle& helpstyle, - const std::string& title, - const std::string& initValue, - const std::function& okCallback, - bool multiLine, - const std::string& acceptBtnText, - const std::string& saveConfirmationText) - : GuiComponent(window), - mHelpStyle(helpstyle), - mBackground(window, ":/graphics/frame.svg"), - mGrid(window, Vector2i(1, 3)), - mMultiLine(multiLine), - mInitValue(initValue), - mOkCallback(okCallback), - mSaveConfirmationText(saveConfirmationText) +GuiTextEditPopup::GuiTextEditPopup(Window* window, + const HelpStyle& helpstyle, + const std::string& title, + const std::string& initValue, + const std::function& okCallback, + bool multiLine, + const std::string& acceptBtnText, + const std::string& saveConfirmationText) + : GuiComponent(window) + , mHelpStyle(helpstyle) + , mBackground(window, ":/graphics/frame.svg") + , mGrid(window, Vector2i(1, 3)) + , mMultiLine(multiLine) + , mInitValue(initValue) + , mOkCallback(okCallback) + , mSaveConfirmationText(saveConfirmationText) { addChild(&mBackground); addChild(&mGrid); mTitle = std::make_shared(mWindow, Utils::String::toUpper(title), - Font::get(FONT_SIZE_MEDIUM), 0x555555FF, ALIGN_CENTER); + Font::get(FONT_SIZE_MEDIUM), 0x555555FF, ALIGN_CENTER); mText = std::make_shared(mWindow); mText->setValue(initValue); std::vector> buttons; buttons.push_back(std::make_shared(mWindow, acceptBtnText, acceptBtnText, - [this, okCallback] { okCallback(mText->getValue()); delete this; })); + [this, okCallback] { + okCallback(mText->getValue()); + delete this; + })); buttons.push_back(std::make_shared(mWindow, "CLEAR", "clear", - [this] { mText->setValue(""); })); + [this] { mText->setValue(""); })); buttons.push_back(std::make_shared(mWindow, "CANCEL", "discard changes", - [this] { delete this; })); + [this] { delete this; })); mButtonGrid = makeButtonGrid(mWindow, buttons); mGrid.setEntry(mTitle, Vector2i(0, 0), false, true); mGrid.setEntry(mText, Vector2i(0, 1), true, false, Vector2i(1, 1), - GridFlags::BORDER_TOP | GridFlags::BORDER_BOTTOM); + GridFlags::BORDER_TOP | GridFlags::BORDER_BOTTOM); mGrid.setEntry(mButtonGrid, Vector2i(0, 2), true, false); float textHeight = mText->getFont()->getHeight(); if (multiLine) - textHeight *= 6; + textHeight *= 6.0f; mText->setSize(0, textHeight); // Adjust the width relative to the aspect ratio of the screen to make the GUI look coherent @@ -67,16 +69,16 @@ GuiTextEditPopup::GuiTextEditPopup( float aspectValue = 1.778f / Renderer::getScreenAspectRatio(); float width = Math::clamp(0.50f * aspectValue, 0.40f, 0.70f) * Renderer::getScreenWidth(); - setSize(width, mTitle->getFont()->getHeight() + - textHeight + mButtonGrid->getSize().y() + mButtonGrid->getSize().y() / 2); - setPosition((Renderer::getScreenWidth() - mSize.x()) / 2, (Renderer::getScreenHeight() - - mSize.y()) / 2); + setSize(width, mTitle->getFont()->getHeight() + textHeight + mButtonGrid->getSize().y() + + mButtonGrid->getSize().y() / 2.0f); + setPosition((Renderer::getScreenWidth() - mSize.x()) / 2.0f, + (Renderer::getScreenHeight() - mSize.y()) / 2.0f); mText->startEditing(); } void GuiTextEditPopup::onSizeChanged() { - mBackground.fitTo(mSize, Vector3f::Zero(), Vector2f(-32, -32)); + mBackground.fitTo(mSize, Vector3f::Zero(), Vector2f(-32.0f, -32.0f)); mText->setSize(mSize.x() - 40, mText->getSize().y()); @@ -95,9 +97,18 @@ bool GuiTextEditPopup::input(InputConfig* config, Input input) if (config->isMappedTo("b", input) && input.value) { if (mText->getValue() != mInitValue) { // Changes were made, ask if the user wants to save them. - mWindow->pushGui(new GuiMsgBox(mWindow, mHelpStyle, mSaveConfirmationText, "YES", - [this] { this->mOkCallback(mText->getValue()); delete this; return true; }, - "NO", [this] { delete this; return false; })); + mWindow->pushGui(new GuiMsgBox( + mWindow, mHelpStyle, mSaveConfirmationText, "YES", + [this] { + this->mOkCallback(mText->getValue()); + delete this; + return true; + }, + "NO", + [this] { + delete this; + return false; + })); } else { delete this; diff --git a/es-core/src/guis/GuiTextEditPopup.h b/es-core/src/guis/GuiTextEditPopup.h index c5bd1eb1a..fe07b53a4 100644 --- a/es-core/src/guis/GuiTextEditPopup.h +++ b/es-core/src/guis/GuiTextEditPopup.h @@ -9,9 +9,9 @@ #ifndef ES_CORE_GUIS_GUI_TEXT_EDIT_POPUP_H #define ES_CORE_GUIS_GUI_TEXT_EDIT_POPUP_H +#include "GuiComponent.h" #include "components/ComponentGrid.h" #include "components/NinePatchComponent.h" -#include "GuiComponent.h" class TextComponent; class TextEditComponent; @@ -19,21 +19,20 @@ class TextEditComponent; class GuiTextEditPopup : public GuiComponent { public: - GuiTextEditPopup( - Window* window, - const HelpStyle& helpstyle, - const std::string& title, - const std::string& initValue, - const std::function& okCallback, - bool multiLine, - const std::string& acceptBtnText = "OK", - const std::string& saveConfirmationText = "SAVE CHANGES?"); + GuiTextEditPopup(Window* window, + const HelpStyle& helpstyle, + const std::string& title, + const std::string& initValue, + const std::function& okCallback, + bool multiLine, + const std::string& acceptBtnText = "OK", + const std::string& saveConfirmationText = "SAVE CHANGES?"); bool input(InputConfig* config, Input input) override; void onSizeChanged() override; std::vector getHelpPrompts() override; - HelpStyle getHelpStyle() override { return mHelpStyle; }; + HelpStyle getHelpStyle() override { return mHelpStyle; } private: NinePatchComponent mBackground; diff --git a/es-core/src/math/Misc.cpp b/es-core/src/math/Misc.cpp index a8b216e98..6e14e0e10 100644 --- a/es-core/src/math/Misc.cpp +++ b/es-core/src/math/Misc.cpp @@ -17,20 +17,22 @@ namespace Math float smoothStep(const float _left, const float _right, const float _x) { - const float x = clamp((_x - _left)/(_right - _left), 0.0f, 1.0f); + const float x = clamp((_x - _left) / (_right - _left), 0.0f, 1.0f); return x * x * (3 - (2 * x)); } float smootherStep(const float _left, const float _right, const float _x) { - const float x = clamp((_x - _left)/(_right - _left), 0.0f, 1.0f); + const float x = clamp((_x - _left) / (_right - _left), 0.0f, 1.0f); return x * x * x * (x * ((x * 6) - 15) + 10); } namespace Scroll { - float bounce(const float _delayTime, const float _scrollTime, - const float _currentTime, const float _scrollLength) + float bounce(const float _delayTime, + const float _scrollTime, + const float _currentTime, + const float _scrollLength) { if (_currentTime < _delayTime) { // Wait. @@ -47,16 +49,18 @@ namespace Math } else if (_currentTime < (_delayTime + _scrollTime + _delayTime + _scrollTime)) { // Lerp back from scrollLength to 0. - const float fraction = (_currentTime - _delayTime - _scrollTime - - _delayTime) / _scrollTime; + const float fraction = + (_currentTime - _delayTime - _scrollTime - _delayTime) / _scrollTime; return lerp(_scrollLength, 0.0f, smootherStep(0, 1, fraction)); } // And back to waiting. return 0; } - float loop(const float _delayTime, const float _scrollTime, - const float _currentTime, const float _scrollLength) + float loop(const float _delayTime, + const float _scrollTime, + const float _currentTime, + const float _scrollLength) { if (_currentTime < _delayTime) { // Wait. @@ -72,5 +76,7 @@ namespace Math return 0; } // Math::Scroll::loop - } // Math::Scroll:: -} // Math:: + + } // namespace Scroll + +} // namespace Math diff --git a/es-core/src/math/Misc.h b/es-core/src/math/Misc.h index dfb07acb8..e3e85ba91 100644 --- a/es-core/src/math/Misc.h +++ b/es-core/src/math/Misc.h @@ -11,15 +11,14 @@ #include -#define ES_PI (3.1415926535897932384626433832795028841971693993751058209749445923) -#define ES_RAD_TO_DEG(_x) ((_x) * (180.0 / ES_PI)) -#define ES_DEG_TO_RAD(_x) ((_x) * (ES_PI / 180.0)) +#define ES_PI (3.1415926535897932384626433832795028841971693993751058209749445923) +#define ES_RAD_TO_DEG(_x) ((_x) * (180.0 / ES_PI)) +#define ES_DEG_TO_RAD(_x) ((_x) * (ES_PI / 180.0)) namespace Math { // When moving to the C++20 standard these functions are no longer required. - template - T const& clamp(const T& _num, const T& _min, const T& _max) + template T const& clamp(const T& _num, const T& _min, const T& _max) { return std::max(std::min(_num, _max), _min); } @@ -30,11 +29,16 @@ namespace Math namespace Scroll { - float bounce(const float _delayTime, const float _scrollTime, - const float _currentTime, const float _scrollLength); - float loop(const float _delayTime, const float _scrollTime, - const float _currentTime, const float _scrollLength); - } -} + float bounce(const float _delayTime, + const float _scrollTime, + const float _currentTime, + const float _scrollLength); + float loop(const float _delayTime, + const float _scrollTime, + const float _currentTime, + const float _scrollLength); + } // namespace Scroll + +} // namespace Math #endif // ES_CORE_MATH_MISC_H diff --git a/es-core/src/math/Transform4x4f.cpp b/es-core/src/math/Transform4x4f.cpp index 071bc9b25..5d565a79d 100644 --- a/es-core/src/math/Transform4x4f.cpp +++ b/es-core/src/math/Transform4x4f.cpp @@ -10,6 +10,7 @@ #include +// clang-format off const Transform4x4f Transform4x4f::operator*(const Transform4x4f& _other) const { const float* tm = reinterpret_cast(this); @@ -321,3 +322,4 @@ Transform4x4f& Transform4x4f::round() return *this; } +// clang-format on diff --git a/es-core/src/math/Transform4x4f.h b/es-core/src/math/Transform4x4f.h index dd49bdc37..c9f07da13 100644 --- a/es-core/src/math/Transform4x4f.h +++ b/es-core/src/math/Transform4x4f.h @@ -9,44 +9,43 @@ #ifndef ES_CORE_MATH_TRANSFORM4X4F_H #define ES_CORE_MATH_TRANSFORM4X4F_H -#include "math/Vector4f.h" #include "math/Vector3f.h" +#include "math/Vector4f.h" class Transform4x4f { public: Transform4x4f() {} - Transform4x4f( - const Vector4f& _r0, - const Vector4f& _r1, - const Vector4f& _r2, - const Vector4f& _r3) - : mR0(_r0), - mR1(_r1), - mR2(_r2), - mR3(_r3) {} + Transform4x4f(const Vector4f& _r0, + const Vector4f& _r1, + const Vector4f& _r2, + const Vector4f& _r3) + : mR0(_r0) + , mR1(_r1) + , mR2(_r2) + , mR3(_r3) + { + } const Transform4x4f operator*(const Transform4x4f& _other) const; const Vector3f operator*(const Vector3f& _other) const; Transform4x4f& operator*=(const Transform4x4f& _other) - { *this = *this * _other; return *this; } + { + *this = *this * _other; + return *this; + } - inline Vector4f& r0() { return mR0; } - inline Vector4f& r1() { return mR1; } - inline Vector4f& r2() { return mR2; } - inline Vector4f& r3() { return mR3; } - inline const Vector4f& r0() const { return mR0; } - inline const Vector4f& r1() const { return mR1; } - inline const Vector4f& r2() const { return mR2; } - inline const Vector4f& r3() const { return mR3; } + Vector4f& r0() { return mR0; } + Vector4f& r1() { return mR1; } + Vector4f& r2() { return mR2; } + Vector4f& r3() { return mR3; } + const Vector4f& r0() const { return mR0; } + const Vector4f& r1() const { return mR1; } + const Vector4f& r2() const { return mR2; } + const Vector4f& r3() const { return mR3; } Transform4x4f& orthoProjection( - float _left, - float _right, - float _bottom, - float _top, - float _near, - float _far); + float _left, float _right, float _bottom, float _top, float _near, float _far); Transform4x4f& invert(const Transform4x4f& _other); Transform4x4f& scale(const Vector3f& _scale); Transform4x4f& rotate(const float _angle, const Vector3f& _axis); @@ -56,11 +55,13 @@ public: Transform4x4f& translate(const Vector3f& _translation); Transform4x4f& round(); - inline Vector3f& translation() { return mR3.v3(); } - inline const Vector3f& translation() const { return mR3.v3(); } + Vector3f& translation() { return mR3.v3(); } + const Vector3f& translation() const { return mR3.v3(); } static const Transform4x4f Identity() - { return { { 1, 0, 0, 0 }, { 0, 1, 0, 0 }, { 0, 0, 1, 0 }, { 0, 0, 0, 1 } }; } + { + return { { 1, 0, 0, 0 }, { 0, 1, 0, 0 }, { 0, 0, 1, 0 }, { 0, 0, 0, 1 } }; + } protected: Vector4f mR0; diff --git a/es-core/src/math/Vector2f.h b/es-core/src/math/Vector2f.h index 0acf407b1..193776e68 100644 --- a/es-core/src/math/Vector2f.h +++ b/es-core/src/math/Vector2f.h @@ -20,26 +20,41 @@ class Vector2f { public: Vector2f() {} - Vector2f(const float _f) : mX(_f), mY(_f) {} - Vector2f(const float _x, const float _y) : mX(_x), mY(_y) {} - explicit Vector2f(const Vector3f& _v) : mX((reinterpret_cast(_v)).mX), - mY((reinterpret_cast(_v)).mY) {} - explicit Vector2f(const Vector4f& _v) : mX((reinterpret_cast(_v)).mX), - mY((reinterpret_cast(_v)).mY) {} + Vector2f(const float _f) + : mX(_f) + , mY(_f) + { + } + Vector2f(const float _x, const float _y) + : mX(_x) + , mY(_y) + { + } + explicit Vector2f(const Vector3f& _v) + : mX((reinterpret_cast(_v)).mX) + , mY((reinterpret_cast(_v)).mY) + { + } + explicit Vector2f(const Vector4f& _v) + : mX((reinterpret_cast(_v)).mX) + , mY((reinterpret_cast(_v)).mY) + { + } + // clang-format off const bool operator==(const Vector2f& _other) const - { return ((mX == _other.mX) && (mY == _other.mY)); } + { return ((mX == _other.mX) && (mY == _other.mY)); } const bool operator!=(const Vector2f& _other) const - { return ((mX != _other.mX) || (mY != _other.mY)); } + { return ((mX != _other.mX) || (mY != _other.mY)); } const Vector2f operator+(const Vector2f& _other) const - { return { mX + _other.mX, mY + _other.mY }; } + { return { mX + _other.mX, mY + _other.mY }; } const Vector2f operator-(const Vector2f& _other) const - { return { mX - _other.mX, mY - _other.mY }; } + { return { mX - _other.mX, mY - _other.mY }; } const Vector2f operator*(const Vector2f& _other) const - { return { mX * _other.mX, mY * _other.mY }; } + { return { mX * _other.mX, mY * _other.mY }; } const Vector2f operator/(const Vector2f& _other) const - { return { mX / _other.mX, mY / _other.mY }; } + { return { mX / _other.mX, mY / _other.mY }; } const Vector2f operator+(const float& _other) const { return { mX + _other, mY + _other }; } const Vector2f operator-(const float& _other) const { return { mX - _other, mY - _other }; } @@ -59,21 +74,22 @@ public: Vector2f& operator/=(const float& _other) { *this = *this / _other; return *this; } float& operator[](const int _index) - { assert(_index < 2 && "index out of range"); return (&mX)[_index]; } + { assert(_index < 2 && "index out of range"); return (&mX)[_index]; } const float& operator[](const int _index) const - { assert(_index < 2 && "index out of range"); return (&mX)[_index]; } + { assert(_index < 2 && "index out of range"); return (&mX)[_index]; } + // clang-format on - inline float& x() { return mX; } - inline float& y() { return mY; } - inline const float& x() const { return mX; } - inline const float& y() const { return mY; } + float& x() { return mX; } + float& y() { return mY; } + const float& x() const { return mX; } + const float& y() const { return mY; } Vector2f& round(); - Vector2f& lerp (const Vector2f& _start, const Vector2f& _end, const float _fraction); + Vector2f& lerp(const Vector2f& _start, const Vector2f& _end, const float _fraction); - static const Vector2f Zero() { return { 0, 0 }; } - static const Vector2f UnitX() { return { 1, 0 }; } - static const Vector2f UnitY() { return { 0, 1 }; } + static const Vector2f Zero() { return { 0.0f, 0.0f }; } + static const Vector2f UnitX() { return { 1.0f, 0.0f }; } + static const Vector2f UnitY() { return { 0.0f, 1.0f }; } private: float mX; diff --git a/es-core/src/math/Vector2i.h b/es-core/src/math/Vector2i.h index 55c47d0e7..1924852d6 100644 --- a/es-core/src/math/Vector2i.h +++ b/es-core/src/math/Vector2i.h @@ -15,22 +15,31 @@ class Vector2i { public: Vector2i() {} - Vector2i(const int _i) : mX(_i), mY(_i) {} - Vector2i(const int _x, const int _y) : mX(_x), mY(_y) {} + Vector2i(const int _i) + : mX(_i) + , mY(_i) + { + } + Vector2i(const int _x, const int _y) + : mX(_x) + , mY(_y) + { + } + // clang-format off const bool operator==(const Vector2i& _other) const - { return ((mX == _other.mX) && (mY == _other.mY)); } + { return ((mX == _other.mX) && (mY == _other.mY)); } const bool operator!=(const Vector2i& _other) const - { return ((mX != _other.mX) || (mY != _other.mY)); } + { return ((mX != _other.mX) || (mY != _other.mY)); } const Vector2i operator+(const Vector2i& _other) const - { return { mX + _other.mX, mY + _other.mY }; } + { return { mX + _other.mX, mY + _other.mY }; } const Vector2i operator-(const Vector2i& _other) const - { return { mX - _other.mX, mY - _other.mY }; } + { return { mX - _other.mX, mY - _other.mY }; } const Vector2i operator*(const Vector2i& _other) const - { return { mX * _other.mX, mY * _other.mY }; } + { return { mX * _other.mX, mY * _other.mY }; } const Vector2i operator/(const Vector2i& _other) const - { return { mX / _other.mX, mY / _other.mY }; } + { return { mX / _other.mX, mY / _other.mY }; } const Vector2i operator+(const int& _other) const { return { mX + _other, mY + _other }; } const Vector2i operator-(const int& _other) const { return { mX - _other, mY - _other }; } @@ -50,14 +59,15 @@ public: Vector2i& operator/=(const int& _other) { *this = *this / _other; return *this; } int& operator[](const int _index) - { assert(_index < 2 && "index out of range"); return (&mX)[_index]; } + { assert(_index < 2 && "index out of range"); return (&mX)[_index]; } const int& operator[](const int _index) const - { assert(_index < 2 && "index out of range"); return (&mX)[_index]; } + { assert(_index < 2 && "index out of range"); return (&mX)[_index]; } + // clang-format on - inline int& x() { return mX; } - inline int& y() { return mY; } - inline const int& x() const { return mX; } - inline const int& y() const { return mY; } + int& x() { return mX; } + int& y() { return mY; } + const int& x() const { return mX; } + const int& y() const { return mY; } static const Vector2i Zero() { return { 0, 0 }; } static const Vector2i UnitX() { return { 1, 0 }; } diff --git a/es-core/src/math/Vector3f.h b/es-core/src/math/Vector3f.h index c14829b69..73a05f71d 100644 --- a/es-core/src/math/Vector3f.h +++ b/es-core/src/math/Vector3f.h @@ -20,39 +20,60 @@ class Vector3f { public: Vector3f() {} - Vector3f(const float _f) : mX(_f), mY(_f), mZ(_f) {} - Vector3f(const float _x, const float _y, const float _z) : mX(_x), mY(_y), mZ(_z) {} - explicit Vector3f(const Vector2f& _v) : mX((reinterpret_cast(_v)).mX), - mY((reinterpret_cast(_v)).mY), mZ(0) {} + Vector3f(const float _f) + : mX(_f) + , mY(_f) + , mZ(_f) + { + } + Vector3f(const float _x, const float _y, const float _z) + : mX(_x) + , mY(_y) + , mZ(_z) + { + } + explicit Vector3f(const Vector2f& _v) + : mX((reinterpret_cast(_v)).mX) + , mY((reinterpret_cast(_v)).mY) + , mZ(0) + { + } explicit Vector3f(const Vector2f& _v, const float _z) - : mX((reinterpret_cast(_v)).mX), - mY((reinterpret_cast(_v)).mY), mZ(_z) {} - explicit Vector3f(const Vector4f& _v) : mX((reinterpret_cast(_v)).mX), - mY((reinterpret_cast(_v)).mY), - mZ((reinterpret_cast(_v)).mZ) {} + : mX((reinterpret_cast(_v)).mX) + , mY((reinterpret_cast(_v)).mY) + , mZ(_z) + { + } + explicit Vector3f(const Vector4f& _v) + : mX((reinterpret_cast(_v)).mX) + , mY((reinterpret_cast(_v)).mY) + , mZ((reinterpret_cast(_v)).mZ) + { + } + // clang-format off const bool operator==(const Vector3f& _other) const - { return ((mX == _other.mX) && (mY == _other.mY) && (mZ == _other.mZ)); } + { return ((mX == _other.mX) && (mY == _other.mY) && (mZ == _other.mZ)); } const bool operator!=(const Vector3f& _other) const - { return ((mX != _other.mX) || (mY != _other.mY) || (mZ != _other.mZ)); } + { return ((mX != _other.mX) || (mY != _other.mY) || (mZ != _other.mZ)); } const Vector3f operator+(const Vector3f& _other) const - { return { mX + _other.mX, mY + _other.mY, mZ + _other.mZ }; } + { return { mX + _other.mX, mY + _other.mY, mZ + _other.mZ }; } const Vector3f operator-(const Vector3f& _other) const - { return { mX - _other.mX, mY - _other.mY, mZ - _other.mZ }; } + { return { mX - _other.mX, mY - _other.mY, mZ - _other.mZ }; } const Vector3f operator*(const Vector3f& _other) const - { return { mX * _other.mX, mY * _other.mY, mZ * _other.mZ }; } + { return { mX * _other.mX, mY * _other.mY, mZ * _other.mZ }; } const Vector3f operator/(const Vector3f& _other) const - { return { mX / _other.mX, mY / _other.mY, mZ / _other.mZ }; } + { return { mX / _other.mX, mY / _other.mY, mZ / _other.mZ }; } const Vector3f operator+(const float& _other) const - { return { mX + _other, mY + _other, mZ + _other }; } + { return { mX + _other, mY + _other, mZ + _other }; } const Vector3f operator-(const float& _other) const - { return { mX - _other, mY - _other, mZ - _other }; } + { return { mX - _other, mY - _other, mZ - _other }; } const Vector3f operator*(const float& _other) const - { return { mX * _other, mY * _other, mZ * _other }; } + { return { mX * _other, mY * _other, mZ * _other }; } const Vector3f operator/(const float& _other) const - { return { mX / _other, mY / _other, mZ / _other }; } + { return { mX / _other, mY / _other, mZ / _other }; } const Vector3f operator-() const { return { -mX , -mY, -mZ }; } @@ -67,27 +88,28 @@ public: Vector3f& operator/=(const float& _other) { *this = *this / _other; return *this; } float& operator[](const int _index) - { assert(_index < 3 && "index out of range"); return (&mX)[_index]; } + { assert(_index < 3 && "index out of range"); return (&mX)[_index]; } const float& operator[](const int _index) const - { assert(_index < 3 && "index out of range"); return (&mX)[_index]; } + { assert(_index < 3 && "index out of range"); return (&mX)[_index]; } + // clang-format on - inline float& x() { return mX; } - inline float& y() { return mY; } - inline float& z() { return mZ; } - inline const float& x() const { return mX; } - inline const float& y() const { return mY; } - inline const float& z() const { return mZ; } + float& x() { return mX; } + float& y() { return mY; } + float& z() { return mZ; } + const float& x() const { return mX; } + const float& y() const { return mY; } + const float& z() const { return mZ; } - inline Vector2f& v2() { return *reinterpret_cast(this); } - inline const Vector2f& v2() const { return *reinterpret_cast(this); } + Vector2f& v2() { return *reinterpret_cast(this); } + const Vector2f& v2() const { return *reinterpret_cast(this); } Vector3f& round(); Vector3f& lerp(const Vector3f& _start, const Vector3f& _end, const float _fraction); - static const Vector3f Zero() { return { 0, 0, 0 }; } - static const Vector3f UnitX() { return { 1, 0, 0 }; } - static const Vector3f UnitY() { return { 0, 1, 0 }; } - static const Vector3f UnitZ() { return { 0, 0, 1 }; } + static const Vector3f Zero() { return { 0.0f, 0.0f, 0.0f }; } + static const Vector3f UnitX() { return { 1.0f, 0.0f, 0.0f }; } + static const Vector3f UnitY() { return { 0.0f, 1.0f, 0.0f }; } + static const Vector3f UnitZ() { return { 0.0f, 0.0f, 1.0f }; } private: float mX; diff --git a/es-core/src/math/Vector4f.h b/es-core/src/math/Vector4f.h index 22439d386..000684ada 100644 --- a/es-core/src/math/Vector4f.h +++ b/es-core/src/math/Vector4f.h @@ -20,51 +20,81 @@ class Vector4f { public: Vector4f() {} - Vector4f(const float _f) : mX(_f), mY(_f), mZ(_f), mW(_f) {} + Vector4f(const float _f) + : mX(_f) + , mY(_f) + , mZ(_f) + , mW(_f) + { + } Vector4f(const float _x, const float _y, const float _z, const float _w) - : mX(_x), mY(_y), mZ(_z), mW(_w) {} + : mX(_x) + , mY(_y) + , mZ(_z) + , mW(_w) + { + } explicit Vector4f(const Vector2f& _v) - : mX((reinterpret_cast(_v)).mX), - mY((reinterpret_cast(_v)).mY), mZ(0), mW(0) {} + : mX((reinterpret_cast(_v)).mX) + , mY((reinterpret_cast(_v)).mY) + , mZ(0) + , mW(0) + { + } explicit Vector4f(const Vector2f& _v, const float _z) - : mX((reinterpret_cast(_v)).mX), - mY((reinterpret_cast(_v)).mY), mZ(_z), mW(0) {} + : mX((reinterpret_cast(_v)).mX) + , mY((reinterpret_cast(_v)).mY) + , mZ(_z) + , mW(0) + { + } explicit Vector4f(const Vector2f& _v, const float _z, const float _w) - : mX((reinterpret_cast(_v)).mX), - mY((reinterpret_cast(_v)).mY), mZ(_z), mW(_w) {} + : mX((reinterpret_cast(_v)).mX) + , mY((reinterpret_cast(_v)).mY) + , mZ(_z) + , mW(_w) + { + } explicit Vector4f(const Vector3f& _v) - : mX((reinterpret_cast(_v)).mX), - mY((reinterpret_cast(_v)).mY), - mZ((reinterpret_cast(_v)).mZ), mW(0) {} + : mX((reinterpret_cast(_v)).mX) + , mY((reinterpret_cast(_v)).mY) + , mZ((reinterpret_cast(_v)).mZ) + , mW(0) + { + } explicit Vector4f(const Vector3f& _v, const float _w) - : mX((reinterpret_cast(_v)).mX), - mY((reinterpret_cast(_v)).mY), - mZ((reinterpret_cast(_v)).mZ), mW(_w) {} + : mX((reinterpret_cast(_v)).mX) + , mY((reinterpret_cast(_v)).mY) + , mZ((reinterpret_cast(_v)).mZ) + , mW(_w) + { + } + // clang-format off const bool operator==(const Vector4f& _other) const - { return ((mX == _other.mX) && (mY == _other.mY) && - (mZ == _other.mZ) && (mW == _other.mW)); } + { return ((mX == _other.mX) && (mY == _other.mY) && + (mZ == _other.mZ) && (mW == _other.mW)); } const bool operator!=(const Vector4f& _other) const - { return ((mX != _other.mX) || (mY != _other.mY) || - (mZ != _other.mZ) || (mW != _other.mW)); } + { return ((mX != _other.mX) || (mY != _other.mY) || + (mZ != _other.mZ) || (mW != _other.mW)); } const Vector4f operator+(const Vector4f& _other) const - { return { mX + _other.mX, mY + _other.mY, mZ + _other.mZ, mW + _other.mW }; } + { return { mX + _other.mX, mY + _other.mY, mZ + _other.mZ, mW + _other.mW }; } const Vector4f operator-(const Vector4f& _other) const - { return { mX - _other.mX, mY - _other.mY, mZ - _other.mZ, mW - _other.mW }; } + { return { mX - _other.mX, mY - _other.mY, mZ - _other.mZ, mW - _other.mW }; } const Vector4f operator*(const Vector4f& _other) const - { return { mX * _other.mX, mY * _other.mY, mZ * _other.mZ, mW * _other.mW }; } + { return { mX * _other.mX, mY * _other.mY, mZ * _other.mZ, mW * _other.mW }; } const Vector4f operator/(const Vector4f& _other) const - { return { mX / _other.mX, mY / _other.mY, mZ / _other.mZ, mW / _other.mW }; } + { return { mX / _other.mX, mY / _other.mY, mZ / _other.mZ, mW / _other.mW }; } const Vector4f operator+(const float& _other) const - { return { mX + _other, mY + _other, mZ + _other, mW + _other }; } + { return { mX + _other, mY + _other, mZ + _other, mW + _other }; } const Vector4f operator-(const float& _other) const - { return { mX - _other, mY - _other, mZ - _other, mW - _other }; } + { return { mX - _other, mY - _other, mZ - _other, mW - _other }; } const Vector4f operator*(const float& _other) const - { return { mX * _other, mY * _other, mZ * _other, mW * _other }; } + { return { mX * _other, mY * _other, mZ * _other, mW * _other }; } const Vector4f operator/(const float& _other) const - { return { mX / _other, mY / _other, mZ / _other, mW / _other }; } + { return { mX / _other, mY / _other, mZ / _other, mW / _other }; } const Vector4f operator-() const { return {-mX , -mY, -mZ, -mW }; } @@ -79,33 +109,34 @@ public: Vector4f& operator/=(const float& _other) { *this = *this / _other; return *this; } float& operator[](const int _index) - { assert(_index < 4 && "index out of range"); return (&mX)[_index]; } + { assert(_index < 4 && "index out of range"); return (&mX)[_index]; } const float& operator[](const int _index) const - { assert(_index < 4 && "index out of range"); return (&mX)[_index]; } + { assert(_index < 4 && "index out of range"); return (&mX)[_index]; } + // clang-format on - inline float& x() { return mX; } - inline float& y() { return mY; } - inline float& z() { return mZ; } - inline float& w() { return mW; } - inline const float& x() const { return mX; } - inline const float& y() const { return mY; } - inline const float& z() const { return mZ; } - inline const float& w() const { return mW; } + float& x() { return mX; } + float& y() { return mY; } + float& z() { return mZ; } + float& w() { return mW; } + const float& x() const { return mX; } + const float& y() const { return mY; } + const float& z() const { return mZ; } + const float& w() const { return mW; } - inline Vector2f& v2() { return *reinterpret_cast(this); } - inline const Vector2f& v2() const { return *reinterpret_cast(this); } + Vector2f& v2() { return *reinterpret_cast(this); } + const Vector2f& v2() const { return *reinterpret_cast(this); } - inline Vector3f& v3() { return *reinterpret_cast(this); } - inline const Vector3f& v3() const { return *reinterpret_cast(this); } + Vector3f& v3() { return *reinterpret_cast(this); } + const Vector3f& v3() const { return *reinterpret_cast(this); } Vector4f& round(); - Vector4f& lerp (const Vector4f& _start, const Vector4f& _end, const float _fraction); + Vector4f& lerp(const Vector4f& _start, const Vector4f& _end, const float _fraction); - static const Vector4f Zero() { return { 0, 0, 0, 0 }; } - static const Vector4f UnitX() { return { 1, 0, 0, 0 }; } - static const Vector4f UnitY() { return { 0, 1, 0, 0 }; } - static const Vector4f UnitZ() { return { 0, 0, 1, 0 }; } - static const Vector4f UnitW() { return { 0, 0, 0, 1 }; } + static const Vector4f Zero() { return { 0.0f, 0.0f, 0.0f, 0.0f }; } + static const Vector4f UnitX() { return { 1.0f, 0.0f, 0.0f, 0.0f }; } + static const Vector4f UnitY() { return { 0.0f, 1.0f, 0.0f, 0.0f }; } + static const Vector4f UnitZ() { return { 0.0f, 0.0f, 1.0f, 0.0f }; } + static const Vector4f UnitW() { return { 0.0f, 0.0f, 0.0f, 1.0f }; } private: float mX; diff --git a/es-core/src/renderers/Renderer.cpp b/es-core/src/renderers/Renderer.cpp index e80b01516..7b96c6d56 100644 --- a/es-core/src/renderers/Renderer.cpp +++ b/es-core/src/renderers/Renderer.cpp @@ -8,18 +8,18 @@ #include "renderers/Renderer.h" -#include "math/Transform4x4f.h" -#include "math/Vector2i.h" -#include "resources/ResourceManager.h" #include "ImageIO.h" #include "Log.h" #include "Settings.h" #include "Shader_GL21.h" +#include "math/Transform4x4f.h" +#include "math/Vector2i.h" +#include "resources/ResourceManager.h" #include #include -#if defined (_WIN64) +#if defined(_WIN64) #include #endif @@ -44,31 +44,31 @@ namespace Renderer { size_t width = 0; size_t height = 0; - ResourceData resData = ResourceManager::getInstance()-> - getFileData(":/graphics/window_icon_256.png"); + ResourceData resData = + ResourceManager::getInstance()->getFileData(":/graphics/window_icon_256.png"); std::vector rawData = - ImageIO::loadFromMemoryRGBA32(resData.ptr.get(), resData.length, width, height); + ImageIO::loadFromMemoryRGBA32(resData.ptr.get(), resData.length, width, height); if (!rawData.empty()) { ImageIO::flipPixelsVert(rawData.data(), width, height); - #if SDL_BYTEORDER == SDL_BIG_ENDIAN +#if SDL_BYTEORDER == SDL_BIG_ENDIAN unsigned int rmask = 0xFF000000; unsigned int gmask = 0x00FF0000; unsigned int bmask = 0x0000FF00; unsigned int amask = 0x000000FF; - #else +#else unsigned int rmask = 0x000000FF; unsigned int gmask = 0x0000FF00; unsigned int bmask = 0x00FF0000; unsigned int amask = 0xFF000000; - #endif +#endif // Try creating SDL surface from logo data. - SDL_Surface* logoSurface = SDL_CreateRGBSurfaceFrom( - static_cast(rawData.data()), - static_cast(width), static_cast(height), 32, - static_cast((width * 4)), rmask, gmask, bmask, amask); + SDL_Surface* logoSurface = + SDL_CreateRGBSurfaceFrom(static_cast(rawData.data()), + static_cast(width), static_cast(height), 32, + static_cast((width * 4)), rmask, gmask, bmask, amask); if (logoSurface != nullptr) { SDL_SetWindowIcon(sdlWindow, logoSurface); @@ -100,8 +100,8 @@ namespace Renderer int availableDisplays = SDL_GetNumVideoDisplays(); if (displayIndex > availableDisplays - 1) { - LOG(LogWarning) << "Requested display " << std::to_string(displayIndex + 1) << - " does not exist, changing to display 1"; + LOG(LogWarning) << "Requested display " << std::to_string(displayIndex + 1) + << " does not exist, changing to display 1"; displayIndex = 0; } else { @@ -111,7 +111,7 @@ namespace Renderer SDL_DisplayMode displayMode; SDL_GetDesktopDisplayMode(displayIndex, &displayMode); - #if defined (_WIN64) +#if defined(_WIN64) // Tell Windows that we're DPI aware so that we can set a physical resolution and // avoid any automatic DPI scaling. SetProcessDPIAware(); @@ -122,28 +122,35 @@ namespace Renderer SDL_GetDisplayBounds(displayIndex, &displayBounds); displayMode.w = displayBounds.w; displayMode.h = displayBounds.h; - #endif +#endif windowWidth = Settings::getInstance()->getInt("WindowWidth") ? - Settings::getInstance()->getInt("WindowWidth") : displayMode.w; + Settings::getInstance()->getInt("WindowWidth") : + displayMode.w; windowHeight = Settings::getInstance()->getInt("WindowHeight") ? - Settings::getInstance()->getInt("WindowHeight") : displayMode.h; + Settings::getInstance()->getInt("WindowHeight") : + displayMode.h; screenWidth = Settings::getInstance()->getInt("ScreenWidth") ? - Settings::getInstance()->getInt("ScreenWidth") : windowWidth; + Settings::getInstance()->getInt("ScreenWidth") : + windowWidth; screenHeight = Settings::getInstance()->getInt("ScreenHeight") ? - Settings::getInstance()->getInt("ScreenHeight") : windowHeight; + Settings::getInstance()->getInt("ScreenHeight") : + windowHeight; screenOffsetX = Settings::getInstance()->getInt("ScreenOffsetX") ? - Settings::getInstance()->getInt("ScreenOffsetX") : 0; + Settings::getInstance()->getInt("ScreenOffsetX") : + 0; screenOffsetY = Settings::getInstance()->getInt("ScreenOffsetY") ? - Settings::getInstance()->getInt("ScreenOffsetY") : 0; + Settings::getInstance()->getInt("ScreenOffsetY") : + 0; screenRotate = Settings::getInstance()->getInt("ScreenRotate") ? - Settings::getInstance()->getInt("ScreenRotate") : 0; + Settings::getInstance()->getInt("ScreenRotate") : + 0; // Prevent the application window from minimizing when switching windows (when launching // games or when manually switching windows using the task switcher). SDL_SetHint(SDL_HINT_VIDEO_MINIMIZE_ON_FOCUS_LOSS, "0"); - #if defined(__unix__) +#if defined(__unix__) // Disabling desktop composition can lead to better framerates and a more fluid user // interface, but with some drivers it can cause strange behaviours when returning to // the desktop. @@ -151,29 +158,28 @@ namespace Renderer SDL_SetHint(SDL_HINT_VIDEO_X11_NET_WM_BYPASS_COMPOSITOR, "1"); else SDL_SetHint(SDL_HINT_VIDEO_X11_NET_WM_BYPASS_COMPOSITOR, "0"); - #endif +#endif - #if defined(__APPLE__) || defined(__unix__) +#if defined(__APPLE__) || defined(__unix__) bool userResolution = false; // Check if the user has changed the resolution from the command line. if (windowWidth != displayMode.w || windowHeight != displayMode.h) userResolution = true; - // Not sure if this could be a useful setting for some users. -// SDL_SetHint(SDL_HINT_VIDEO_MAC_FULLSCREEN_SPACES, "0"); - #endif - - setupWindow(); + // Not sure if this could be a useful setting for some users. + // SDL_SetHint(SDL_HINT_VIDEO_MAC_FULLSCREEN_SPACES, "0"); +#endif unsigned int windowFlags; + setupWindow(); - #if defined(_WIN64) +#if defined(_WIN64) // For Windows, always set the mode to windowed, as full screen mode seems to // behave quite erratic. There may be a proper fix for this, but for now windowed // mode seems to behave well and it's almost completely seamless, especially with // a hidden taskbar. As well, setting SDL_WINDOW_BORDERLESS introduces issues too // so unfortunately this needs to be avoided. windowFlags = getWindowFlags(); - #elif defined(__APPLE__) +#elif defined(__APPLE__) // This seems to be the only full window mode that somehow works on macOS as a real // fullscreen mode will do lots of weird stuff like preventing window switching // or refusing to let emulators run at all. SDL_WINDOW_FULLSCREEN_DESKTOP almost @@ -190,7 +196,7 @@ namespace Renderer // If the user has changed the resolution from the command line, then add a // border to the window. windowFlags = SDL_WINDOW_ALLOW_HIGHDPI | getWindowFlags(); - #else +#else if (Settings::getInstance()->getBool("Windowed")) { windowFlags = getWindowFlags(); } @@ -205,17 +211,17 @@ namespace Renderer else { windowFlags = SDL_WINDOW_FULLSCREEN | getWindowFlags(); } - #endif +#endif - if ((sdlWindow = SDL_CreateWindow("EmulationStation", - SDL_WINDOWPOS_UNDEFINED_DISPLAY(displayIndex), - SDL_WINDOWPOS_UNDEFINED_DISPLAY(displayIndex), - windowWidth, windowHeight, windowFlags)) == nullptr) { + if ((sdlWindow = + SDL_CreateWindow("EmulationStation", SDL_WINDOWPOS_UNDEFINED_DISPLAY(displayIndex), + SDL_WINDOWPOS_UNDEFINED_DISPLAY(displayIndex), windowWidth, + windowHeight, windowFlags)) == nullptr) { LOG(LogError) << "Couldn't create SDL window. " << SDL_GetError(); return false; } - #if defined(__APPLE__) +#if defined(__APPLE__) // The code below is required as the high DPI scaling on macOS is very bizarre and is // measured in "points" rather than pixels (even though the naming convention sure looks // like pixels). For example there could be a 1920x1080 entry in the OS display settings @@ -231,25 +237,25 @@ namespace Renderer SDL_GL_GetDrawableSize(sdlWindow, &width, nullptr); int scaleFactor = static_cast(width / windowWidth); - LOG(LogInfo) << "Display resolution: " << std::to_string(displayMode.w) << "x" << - std::to_string(displayMode.h) << " (physical resolution " << - std::to_string(displayMode.w * scaleFactor) << "x" << - std::to_string(displayMode.h * scaleFactor) << ")"; - LOG(LogInfo) << "EmulationStation resolution: " << std::to_string(windowWidth) << "x" << - std::to_string(windowHeight) << " (physical resolution " << - std::to_string(windowWidth * scaleFactor) << "x" << - std::to_string(windowHeight * scaleFactor) << ")"; + LOG(LogInfo) << "Display resolution: " << std::to_string(displayMode.w) << "x" + << std::to_string(displayMode.h) << " (physical resolution " + << std::to_string(displayMode.w * scaleFactor) << "x" + << std::to_string(displayMode.h * scaleFactor) << ")"; + LOG(LogInfo) << "EmulationStation resolution: " << std::to_string(windowWidth) << "x" + << std::to_string(windowHeight) << " (physical resolution " + << std::to_string(windowWidth * scaleFactor) << "x" + << std::to_string(windowHeight * scaleFactor) << ")"; windowWidth *= scaleFactor; windowHeight *= scaleFactor; screenWidth *= scaleFactor; screenHeight *= scaleFactor; - #else - LOG(LogInfo) << "Display resolution: " << std::to_string(displayMode.w) << "x" << - std::to_string(displayMode.h); - LOG(LogInfo) << "EmulationStation resolution: " << std::to_string(windowWidth) << "x" << - std::to_string(windowHeight); - #endif +#else + LOG(LogInfo) << "Display resolution: " << std::to_string(displayMode.w) << "x" + << std::to_string(displayMode.h); + LOG(LogInfo) << "EmulationStation resolution: " << std::to_string(windowWidth) << "x" + << std::to_string(windowHeight); +#endif screenHeightModifier = static_cast(screenHeight) / 1080.0f; screenWidthModifier = static_cast(screenWidth) / 1920.0f; @@ -263,14 +269,14 @@ namespace Renderer setIcon(); setSwapInterval(); +#if defined(_WIN64) // It seems as if Windows needs this to avoid a brief white screen flash on startup. // Possibly this is driver-specific rather than OS-specific. There is additional code // in init() to work around the white screen flash issue on all operating systems. - #if defined(_WIN64) swapBuffers(); - #endif +#endif - #if defined(USE_OPENGL_21) +#if defined(USE_OPENGL_21) LOG(LogInfo) << "Loading shaders..."; std::vector shaderFiles; @@ -294,19 +300,17 @@ namespace Renderer sShaderProgramVector.push_back(loadShader); } - #endif +#endif return true; } static void destroyWindow() { - #if defined(USE_OPENGL_21) - for (auto it = sShaderProgramVector.cbegin(); - it != sShaderProgramVector.cend(); it++) { +#if defined(USE_OPENGL_21) + for (auto it = sShaderProgramVector.cbegin(); it != sShaderProgramVector.cend(); it++) delete *it; - } - #endif +#endif destroyContext(); SDL_DestroyWindow(sdlWindow); @@ -332,42 +336,42 @@ namespace Renderer viewport.w = screenWidth; viewport.h = screenHeight; projection.orthoProjection(0.0f, static_cast(screenWidth), - static_cast(screenHeight), 0.0f, -1.0f, 1.0f); + static_cast(screenHeight), 0.0f, -1.0f, 1.0f); + break; } - break; case 1: { viewport.x = windowWidth - screenOffsetY - screenHeight; viewport.y = screenOffsetX; viewport.w = screenHeight; viewport.h = screenWidth; projection.orthoProjection(0.0f, static_cast(screenHeight), - static_cast(screenWidth), 0.0f, -1.0f, 1.0f); - projection.rotate(static_cast(ES_DEG_TO_RAD(90)), {0, 0, 1}); - projection.translate({0, screenHeight * -1.0f, 0}); + static_cast(screenWidth), 0.0f, -1.0f, 1.0f); + projection.rotate(static_cast(ES_DEG_TO_RAD(90)), { 0, 0, 1 }); + projection.translate({ 0, screenHeight * -1.0f, 0 }); + break; } - break; case 2: { - viewport.x = windowWidth - screenOffsetX - screenWidth; + viewport.x = windowWidth - screenOffsetX - screenWidth; viewport.y = windowHeight - screenOffsetY - screenHeight; viewport.w = screenWidth; viewport.h = screenHeight; projection.orthoProjection(0.0f, static_cast(screenWidth), - static_cast(screenHeight), 0.0f, -1.0f, 1.0f); - projection.rotate(static_cast(ES_DEG_TO_RAD(180)), {0, 0, 1}); - projection.translate({screenWidth * -1.0f, screenHeight * -1.0f, 0}); + static_cast(screenHeight), 0.0f, -1.0f, 1.0f); + projection.rotate(static_cast(ES_DEG_TO_RAD(180)), { 0, 0, 1 }); + projection.translate({ screenWidth * -1.0f, screenHeight * -1.0f, 0 }); + break; } - break; case 3: { viewport.x = screenOffsetY; viewport.y = windowHeight - screenOffsetX - screenWidth; viewport.w = screenHeight; viewport.h = screenWidth; projection.orthoProjection(0.0f, static_cast(screenHeight), - static_cast(screenWidth), 0.0f, -1.0f, 1.0f); - projection.rotate(static_cast(ES_DEG_TO_RAD(270)), {0, 0, 1}); - projection.translate({screenWidth * -1.0f, 0, 0}); + static_cast(screenWidth), 0.0f, -1.0f, 1.0f); + projection.rotate(static_cast(ES_DEG_TO_RAD(270)), { 0, 0, 1 }); + projection.translate({ screenWidth * -1.0f, 0, 0 }); + break; } - break; } mProjectionMatrix = projection; @@ -377,7 +381,7 @@ namespace Renderer // This is required to avoid a brief white screen flash during startup on some systems. Renderer::drawRect(0.0f, 0.0f, static_cast(Renderer::getScreenWidth()), - static_cast(Renderer::getScreenHeight()), 0x000000FF, 0x000000FF); + static_cast(Renderer::getScreenHeight()), 0x000000FF, 0x000000FF); swapBuffers(); return true; @@ -385,6 +389,7 @@ namespace Renderer void deinit() { + // Destroy the window. destroyWindow(); } @@ -400,32 +405,38 @@ namespace Renderer switch (screenRotate) { case 0: box = Rect(screenOffsetX + box.x, screenOffsetY + box.y, box.w, box.h); - break; + break; case 1: - box = Rect(windowWidth - screenOffsetY - box.y - box.h, - screenOffsetX + box.x, box.h, box.w); - break; + box = Rect(windowWidth - screenOffsetY - box.y - box.h, screenOffsetX + box.x, + box.h, box.w); + break; case 2: - box = Rect(windowWidth - screenOffsetX - box.x - box.w, windowHeight - - screenOffsetY - box.y - box.h, box.w, box.h); - break; + box = Rect(windowWidth - screenOffsetX - box.x - box.w, + windowHeight - screenOffsetY - box.y - box.h, box.w, box.h); + break; case 3: - box = Rect(screenOffsetY + box.y, windowHeight - - screenOffsetX - box.x - box.w, box.h, box.w); - break; + box = Rect(screenOffsetY + box.y, windowHeight - screenOffsetX - box.x - box.w, + box.h, box.w); + break; } // Make sure the box fits within clipStack.top(), and clip further accordingly. if (clipStack.size()) { const Rect& top = clipStack.top(); - if ( top.x > box.x) box.x = top.x; - if ( top.y > box.y) box.y = top.y; - if ((top.x + top.w) < (box.x + box.w)) box.w = (top.x + top.w) - box.x; - if ((top.y + top.h) < (box.y + box.h)) box.h = (top.y + top.h) - box.y; + if (top.x > box.x) + box.x = top.x; + if (top.y > box.y) + box.y = top.y; + if ((top.x + top.w) < (box.x + box.w)) + box.w = (top.x + top.w) - box.x; + if ((top.y + top.h) < (box.y + box.h)) + box.h = (top.y + top.h) - box.y; } - if (box.w < 0) box.w = 0; - if (box.h < 0) box.h = 0; + if (box.w < 0) + box.w = 0; + if (box.h < 0) + box.h = 0; clipStack.push(box); @@ -447,18 +458,17 @@ namespace Renderer setScissor(clipStack.top()); } - void drawRect( - const float _x, - const float _y, - const float _w, - const float _h, - const unsigned int _color, - const unsigned int _colorEnd, - bool horizontalGradient, - const float _opacity, - const Transform4x4f& _trans, - const Blend::Factor _srcBlendFactor, - const Blend::Factor _dstBlendFactor) + void drawRect(const float _x, + const float _y, + const float _w, + const float _h, + const unsigned int _color, + const unsigned int _colorEnd, + bool horizontalGradient, + const float _opacity, + const Transform4x4f& _trans, + const Blend::Factor _srcBlendFactor, + const Blend::Factor _dstBlendFactor) { const unsigned int color = convertRGBAToABGR(_color); const unsigned int colorEnd = convertRGBAToABGR(_colorEnd); @@ -474,10 +484,12 @@ namespace Renderer if (_hL > 0.0f && _hL < 1.0f) _hL = 1.0f; + // clang-format off vertices[0] = { { _x , _y }, { 0.0f, 0.0f }, color }; vertices[1] = { { _x , _y + _hL }, { 0.0f, 0.0f }, horizontalGradient ? colorEnd : color }; vertices[2] = { { _x + _wL, _y }, { 0.0f, 0.0f }, horizontalGradient ? color : colorEnd }; vertices[3] = { { _x + _wL, _y + _hL }, { 0.0f, 0.0f }, colorEnd }; + // clang-format on // Round vertices. for (int i = 0; i < 4; i++) @@ -524,17 +536,13 @@ namespace Renderer index++; } - if (sShaderProgramVector.size() > index-1) - return sShaderProgramVector[index-1]; + if (sShaderProgramVector.size() > index - 1) + return sShaderProgramVector[index - 1]; else return nullptr; }; - const Transform4x4f getProjectionMatrix() - { - return mProjectionMatrix; - } - + const Transform4x4f getProjectionMatrix() { return mProjectionMatrix; } SDL_Window* getSDLWindow() { return sdlWindow; } int getWindowWidth() { return windowWidth; } int getWindowHeight() { return windowHeight; } @@ -547,4 +555,4 @@ namespace Renderer float getScreenHeightModifier() { return screenHeightModifier; } float getScreenAspectRatio() { return screenAspectRatio; } -} // Renderer:: +} // namespace Renderer diff --git a/es-core/src/renderers/Renderer.h b/es-core/src/renderers/Renderer.h index 8d5f99aa4..5fec1600e 100644 --- a/es-core/src/renderers/Renderer.h +++ b/es-core/src/renderers/Renderer.h @@ -9,26 +9,27 @@ #ifndef ES_CORE_RENDERER_RENDERER_H #define ES_CORE_RENDERER_RENDERER_H -#include "math/Transform4x4f.h" -#include "math/Vector2f.h" #include "Log.h" #include "Shader_GL21.h" +#include "math/Transform4x4f.h" +#include "math/Vector2f.h" #include #include -class Transform4x4f; -class Vector2i; struct SDL_Window; +class Transform4x4f; +class Vector2i; + namespace Renderer { - const unsigned int SHADER_DESATURATE = 1; - const unsigned int SHADER_OPACITY = 2; - const unsigned int SHADER_DIM = 4; - const unsigned int SHADER_BLUR_HORIZONTAL = 8; - const unsigned int SHADER_BLUR_VERTICAL = 16; - const unsigned int SHADER_SCANLINES = 32; + const unsigned int SHADER_DESATURATE = 1; + const unsigned int SHADER_OPACITY = 2; + const unsigned int SHADER_DIM = 4; + const unsigned int SHADER_BLUR_HORIZONTAL = 8; + const unsigned int SHADER_BLUR_VERTICAL = 16; + const unsigned int SHADER_SCANLINES = 32; struct shaderParameters { std::array textureSize; @@ -39,40 +40,40 @@ namespace Renderer unsigned int blurPasses; shaderParameters() - : textureSize({0.0f, 0.0f}), - textureCoordinates({0.0f, 0.0f, 0.0f, 0.0f}), - fragmentSaturation(1.0f), - fragmentDimValue(0.4f), - fragmentOpacity(1.0f), - blurPasses(1) - {}; + : textureSize({ 0.0f, 0.0f }) + , textureCoordinates({ 0.0f, 0.0f, 0.0f, 0.0f }) + , fragmentSaturation(1.0f) + , fragmentDimValue(0.4f) + , fragmentOpacity(1.0f) + , blurPasses(1) + { + } }; static std::vector sShaderProgramVector; static GLuint shaderFBO; static Transform4x4f mProjectionMatrix; - #if !defined(NDEBUG) - #define GL_CHECK_ERROR(Function) (Function, _GLCheckError(#Function)) +#if !defined(NDEBUG) +#define GL_CHECK_ERROR(Function) (Function, _GLCheckError(#Function)) static void _GLCheckError(const std::string& _funcName) { const GLenum errorCode = glGetError(); if (errorCode != GL_NO_ERROR) { - #if defined(USE_OPENGL_21) - LOG(LogError) << "OpenGL error: " << _funcName << - " failed with error code: 0x" << std::hex << errorCode; - #else - LOG(LogError) << "OpenGLES error: " << _funcName << - " failed with error code: 0x" << std::hex << errorCode; - #endif - +#if defined(USE_OPENGL_21) + LOG(LogError) << "OpenGL error: " << _funcName << " failed with error code: 0x" + << std::hex << errorCode; +#else + LOG(LogError) << "OpenGLES error: " << _funcName << " failed with error code: 0x" + << std::hex << errorCode; +#endif } } - #else - #define GL_CHECK_ERROR(Function) (Function) - #endif +#else +#define GL_CHECK_ERROR(Function) (Function) +#endif namespace Blend { @@ -93,37 +94,33 @@ namespace Renderer namespace Texture { enum Type { - RGBA = 0, + RGBA = 0, // Replace with AllowShortEnumsOnASingleLine: false (clang-format >=11.0). ALPHA = 1 }; } struct Rect { - Rect( - const int _x, - const int _y, - const int _w, - const int _h) - : x(_x), - y(_y), - w(_w), - h(_h) {} + Rect(const int _x, const int _y, const int _w, const int _h) + : x(_x) + , y(_y) + , w(_w) + , h(_h) + { + } int x; int y; int w; int h; }; - struct Vertex - { + struct Vertex { Vertex() {} - Vertex( - const Vector2f& _pos, - const Vector2f& _tex, - const unsigned int _col) - : pos(_pos), - tex(_tex), - col(_col) { } + Vertex(const Vector2f& _pos, const Vector2f& _tex, const unsigned int _col) + : pos(_pos) + , tex(_tex) + , col(_col) + { + } Vector2f pos; Vector2f tex; unsigned int col; @@ -136,18 +133,17 @@ namespace Renderer void deinit(); void pushClipRect(const Vector2i& _pos, const Vector2i& _size); void popClipRect(); - void drawRect( - const float _x, - const float _y, - const float _w, - const float _h, - const unsigned int _color, - const unsigned int _colorEnd, - bool horizontalGradient = false, - const float _opacity = 1.0, - const Transform4x4f& _trans = Transform4x4f::Identity(), - const Blend::Factor _srcBlendFactor = Blend::SRC_ALPHA, - const Blend::Factor _dstBlendFactor = Blend::ONE_MINUS_SRC_ALPHA); + void drawRect(const float _x, + const float _y, + const float _w, + const float _h, + const unsigned int _color, + const unsigned int _colorEnd, + bool horizontalGradient = false, + const float _opacity = 1.0, + const Transform4x4f& _trans = Transform4x4f::Identity(), + const Blend::Factor _srcBlendFactor = Blend::SRC_ALPHA, + const Blend::Factor _dstBlendFactor = Blend::ONE_MINUS_SRC_ALPHA); SDL_Window* getSDLWindow(); int getWindowWidth(); int getWindowHeight(); @@ -166,49 +162,46 @@ namespace Renderer Shader* getShaderProgram(unsigned int shaderID); const Transform4x4f getProjectionMatrix(); void shaderPostprocessing(unsigned int shaders, - const Renderer::shaderParameters& parameters = shaderParameters(), - unsigned char* textureRGBA = nullptr); + const Renderer::shaderParameters& parameters = shaderParameters(), + unsigned char* textureRGBA = nullptr); + + static unsigned int getWindowFlags() { return SDL_WINDOW_OPENGL; } - // API specific. - unsigned int getWindowFlags(); void setupWindow(); bool createContext(); void destroyContext(); - unsigned int createTexture( - const Texture::Type _type, - const bool _linear, - const bool _repeat, - const unsigned int _width, - const unsigned int _height, - void* _data); + unsigned int createTexture(const Texture::Type _type, + const bool _linear, + const bool _repeat, + const unsigned int _width, + const unsigned int _height, + void* _data); void destroyTexture(const unsigned int _texture); - void updateTexture( - const unsigned int _texture, - const Texture::Type _type, - const unsigned int _x, - const unsigned _y, - const unsigned int _width, - const unsigned int _height, - void* _data); + void updateTexture(const unsigned int _texture, + const Texture::Type _type, + const unsigned int _x, + const unsigned _y, + const unsigned int _width, + const unsigned int _height, + void* _data); void bindTexture(const unsigned int _texture); - void drawLines( - const Vertex* _vertices, - const unsigned int _numVertices, - const Blend::Factor _srcBlendFactor = Blend::SRC_ALPHA, - const Blend::Factor _dstBlendFactor = Blend::ONE_MINUS_SRC_ALPHA); - void drawTriangleStrips( - const Vertex* _vertices, - const unsigned int _numVertices, - const Transform4x4f& _trans = Transform4x4f::Identity(), - const Blend::Factor _srcBlendFactor = Blend::SRC_ALPHA, - const Blend::Factor _dstBlendFactor = Blend::ONE_MINUS_SRC_ALPHA, - const shaderParameters& _parameters = shaderParameters()); + void drawLines(const Vertex* _vertices, + const unsigned int _numVertices, + const Blend::Factor _srcBlendFactor = Blend::SRC_ALPHA, + const Blend::Factor _dstBlendFactor = Blend::ONE_MINUS_SRC_ALPHA); + void drawTriangleStrips(const Vertex* _vertices, + const unsigned int _numVertices, + const Transform4x4f& _trans = Transform4x4f::Identity(), + const Blend::Factor _srcBlendFactor = Blend::SRC_ALPHA, + const Blend::Factor _dstBlendFactor = Blend::ONE_MINUS_SRC_ALPHA, + const shaderParameters& _parameters = shaderParameters()); void setProjection(const Transform4x4f& _projection); void setMatrix(const Transform4x4f& _matrix); void setViewport(const Rect& _viewport); void setScissor(const Rect& _scissor); void setSwapInterval(); void swapBuffers(); -} + +} // namespace Renderer #endif // ES_CORE_RENDERER_RENDERER_H diff --git a/es-core/src/renderers/Renderer_GL21.cpp b/es-core/src/renderers/Renderer_GL21.cpp index 2aab81706..7f236ec8c 100644 --- a/es-core/src/renderers/Renderer_GL21.cpp +++ b/es-core/src/renderers/Renderer_GL21.cpp @@ -8,10 +8,10 @@ #if defined(USE_OPENGL_21) -#include "math/Transform4x4f.h" -#include "renderers/Renderer.h" #include "Settings.h" #include "Shader_GL21.h" +#include "math/Transform4x4f.h" +#include "renderers/Renderer.h" namespace Renderer { @@ -20,6 +20,7 @@ namespace Renderer static GLenum convertBlendFactor(const Blend::Factor _blendFactor) { + // clang-format off switch (_blendFactor) { case Blend::ZERO: { return GL_ZERO; } break; case Blend::ONE: { return GL_ONE; } break; @@ -33,31 +34,29 @@ namespace Renderer case Blend::ONE_MINUS_DST_ALPHA: { return GL_ONE_MINUS_DST_ALPHA; } break; default: { return GL_ZERO; } } + // clang-format on } static GLenum convertTextureType(const Texture::Type _type) { + // clang-format off switch (_type) { case Texture::RGBA: { return GL_RGBA; } break; case Texture::ALPHA: { return GL_ALPHA; } break; default: { return GL_ZERO; } } - } - - unsigned int getWindowFlags() - { - return SDL_WINDOW_OPENGL; + // clang-format on } void setupWindow() { - #if defined(__APPLE__) +#if defined(__APPLE__) // This is required on macOS, as the operating system will otherwise insist on using // a newer OpenGL version which completely breaks the application. SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_COMPATIBILITY); - #else +#else SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE); - #endif +#endif SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1); @@ -78,32 +77,34 @@ namespace Renderer return false; } - #if defined(_WIN64) +#if defined(_WIN64) glewInit(); - #endif +#endif SDL_GL_MakeCurrent(getSDLWindow(), sdlContext); - std::string vendor = glGetString(GL_VENDOR) ? - reinterpret_cast(glGetString(GL_VENDOR)) : ""; - std::string renderer = glGetString(GL_RENDERER) ? - reinterpret_cast(glGetString(GL_RENDERER)) : ""; - std::string version = glGetString(GL_VERSION) ? - reinterpret_cast(glGetString(GL_VERSION)) : ""; + std::string vendor = + glGetString(GL_VENDOR) ? reinterpret_cast(glGetString(GL_VENDOR)) : ""; + std::string renderer = + glGetString(GL_RENDERER) ? reinterpret_cast(glGetString(GL_RENDERER)) : ""; + std::string version = + glGetString(GL_VERSION) ? reinterpret_cast(glGetString(GL_VERSION)) : ""; std::string extensions = glGetString(GL_EXTENSIONS) ? - reinterpret_cast(glGetString(GL_EXTENSIONS)) : ""; + reinterpret_cast(glGetString(GL_EXTENSIONS)) : + ""; LOG(LogInfo) << "GL vendor: " << vendor; LOG(LogInfo) << "GL renderer: " << renderer; LOG(LogInfo) << "GL version: " << version; - #if defined(_WIN64) +#if defined(_WIN64) LOG(LogInfo) << "EmulationStation renderer: OpenGL 2.1 with GLEW"; - #else +#else LOG(LogInfo) << "EmulationStation renderer: OpenGL 2.1"; - #endif +#endif LOG(LogInfo) << "Checking available OpenGL extensions..."; std::string glExts = glGetString(GL_EXTENSIONS) ? - reinterpret_cast(glGetString(GL_EXTENSIONS)) : ""; + reinterpret_cast(glGetString(GL_EXTENSIONS)) : + ""; if (extensions.find("GL_ARB_texture_non_power_of_two") == std::string::npos) { LOG(LogError) << "GL_ARB_texture_non_power_of_two: MISSING"; missingExtension = true; @@ -137,7 +138,7 @@ namespace Renderer return false; } - uint8_t data[4] = {255, 255, 255, 255}; + uint8_t data[4] = { 255, 255, 255, 255 }; whiteTexture = createTexture(Texture::RGBA, false, true, 1, 1, data); GL_CHECK_ERROR(glClearColor(0.0f, 0.0f, 0.0f, 1.0f)); @@ -162,13 +163,12 @@ namespace Renderer sdlContext = nullptr; } - unsigned int createTexture( - const Texture::Type _type, - const bool _linear, - const bool _repeat, - const unsigned int _width, - const unsigned int _height, - void* _data) + unsigned int createTexture(const Texture::Type _type, + const bool _linear, + const bool _repeat, + const unsigned int _width, + const unsigned int _height, + void* _data) { const GLenum type = convertTextureType(_type); unsigned int texture; @@ -176,16 +176,19 @@ namespace Renderer GL_CHECK_ERROR(glGenTextures(1, &texture)); GL_CHECK_ERROR(glBindTexture(GL_TEXTURE_2D, texture)); - GL_CHECK_ERROR(glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, _repeat ? - static_cast(GL_REPEAT) : static_cast(GL_CLAMP_TO_EDGE))); - GL_CHECK_ERROR(glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, _repeat ? - static_cast(GL_REPEAT) : static_cast(GL_CLAMP_TO_EDGE))); - GL_CHECK_ERROR(glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, _linear ? - static_cast(GL_LINEAR) : static_cast(GL_NEAREST))); + GL_CHECK_ERROR(glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, + _repeat ? static_cast(GL_REPEAT) : + static_cast(GL_CLAMP_TO_EDGE))); + GL_CHECK_ERROR(glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, + _repeat ? static_cast(GL_REPEAT) : + static_cast(GL_CLAMP_TO_EDGE))); + GL_CHECK_ERROR(glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, + _linear ? static_cast(GL_LINEAR) : + static_cast(GL_NEAREST))); GL_CHECK_ERROR(glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST)); GL_CHECK_ERROR(glTexImage2D(GL_TEXTURE_2D, 0, type, _width, _height, 0, type, - GL_UNSIGNED_BYTE, _data)); + GL_UNSIGNED_BYTE, _data)); return texture; } @@ -195,20 +198,19 @@ namespace Renderer GL_CHECK_ERROR(glDeleteTextures(1, &_texture)); } - void updateTexture( - const unsigned int _texture, - const Texture::Type _type, - const unsigned int _x, - const unsigned _y, - const unsigned int _width, - const unsigned int _height, - void* _data) + void updateTexture(const unsigned int _texture, + const Texture::Type _type, + const unsigned int _x, + const unsigned _y, + const unsigned int _width, + const unsigned int _height, + void* _data) { const GLenum type = convertTextureType(_type); GL_CHECK_ERROR(glBindTexture(GL_TEXTURE_2D, _texture)); - GL_CHECK_ERROR(glTexSubImage2D(GL_TEXTURE_2D, 0, _x, _y, _width, _height, - type, GL_UNSIGNED_BYTE, _data)); + GL_CHECK_ERROR(glTexSubImage2D(GL_TEXTURE_2D, 0, _x, _y, _width, _height, type, + GL_UNSIGNED_BYTE, _data)); GL_CHECK_ERROR(glBindTexture(GL_TEXTURE_2D, whiteTexture)); } @@ -220,29 +222,27 @@ namespace Renderer GL_CHECK_ERROR(glBindTexture(GL_TEXTURE_2D, _texture)); } - void drawLines( - const Vertex* _vertices, - const unsigned int _numVertices, - const Blend::Factor _srcBlendFactor, - const Blend::Factor _dstBlendFactor) + void drawLines(const Vertex* _vertices, + const unsigned int _numVertices, + const Blend::Factor _srcBlendFactor, + const Blend::Factor _dstBlendFactor) { GL_CHECK_ERROR(glVertexPointer(2, GL_FLOAT, sizeof(Vertex), &_vertices[0].pos)); GL_CHECK_ERROR(glTexCoordPointer(2, GL_FLOAT, sizeof(Vertex), &_vertices[0].tex)); - GL_CHECK_ERROR(glColorPointer( 4, GL_UNSIGNED_BYTE, sizeof(Vertex), &_vertices[0].col)); + GL_CHECK_ERROR(glColorPointer(4, GL_UNSIGNED_BYTE, sizeof(Vertex), &_vertices[0].col)); - GL_CHECK_ERROR(glBlendFunc(convertBlendFactor(_srcBlendFactor), - convertBlendFactor(_dstBlendFactor))); + GL_CHECK_ERROR( + glBlendFunc(convertBlendFactor(_srcBlendFactor), convertBlendFactor(_dstBlendFactor))); GL_CHECK_ERROR(glDrawArrays(GL_LINES, 0, _numVertices)); } - void drawTriangleStrips( - const Vertex* _vertices, - const unsigned int _numVertices, - const Transform4x4f& _trans, - const Blend::Factor _srcBlendFactor, - const Blend::Factor _dstBlendFactor, - const shaderParameters& _parameters) + void drawTriangleStrips(const Vertex* _vertices, + const unsigned int _numVertices, + const Transform4x4f& _trans, + const Blend::Factor _srcBlendFactor, + const Blend::Factor _dstBlendFactor, + const shaderParameters& _parameters) { float width = _vertices[3].pos[0]; float height = _vertices[3].pos[1]; @@ -251,17 +251,17 @@ namespace Renderer GL_CHECK_ERROR(glTexCoordPointer(2, GL_FLOAT, sizeof(Vertex), &_vertices[0].tex)); GL_CHECK_ERROR(glColorPointer(4, GL_UNSIGNED_BYTE, sizeof(Vertex), &_vertices[0].col)); - GL_CHECK_ERROR(glBlendFunc(convertBlendFactor(_srcBlendFactor), - convertBlendFactor(_dstBlendFactor))); + GL_CHECK_ERROR( + glBlendFunc(convertBlendFactor(_srcBlendFactor), convertBlendFactor(_dstBlendFactor))); - #if defined(USE_OPENGL_21) +#if defined(USE_OPENGL_21) if (_vertices[0].shaders == 0) { GL_CHECK_ERROR(glDrawArrays(GL_TRIANGLE_STRIP, 0, _numVertices)); } else { // If saturation is set below the maximum (default) value, run the // desaturation shader. - if (_vertices->saturation < 1.0 || _parameters.fragmentSaturation < 1.0) { + if (_vertices->saturation < 1.0f || _parameters.fragmentSaturation < 1.0f) { Shader* runShader = getShaderProgram(SHADER_DESATURATE); // Only try to use the shader if it has been loaded properly. if (runShader) { @@ -278,9 +278,8 @@ namespace Renderer if (runShader) { runShader->activateShaders(); runShader->setModelViewProjectionMatrix(getProjectionMatrix() * _trans); - _vertices->opacity < 1.0 ? - runShader->setOpacity(_vertices->opacity) : - runShader->setOpacity(_parameters.fragmentOpacity); + _vertices->opacity < 1.0f ? runShader->setOpacity(_vertices->opacity) : + runShader->setOpacity(_parameters.fragmentOpacity); GL_CHECK_ERROR(glDrawArrays(GL_TRIANGLE_STRIP, 0, _numVertices)); runShader->deactivateShaders(); } @@ -303,7 +302,7 @@ namespace Renderer if (runShader) { runShader->activateShaders(); runShader->setModelViewProjectionMatrix(getProjectionMatrix() * _trans); - runShader->setTextureSize({width, height}); + runShader->setTextureSize({ width, height }); GL_CHECK_ERROR(glDrawArrays(GL_TRIANGLE_STRIP, 0, _numVertices)); runShader->deactivateShaders(); } @@ -314,7 +313,7 @@ namespace Renderer if (runShader) { runShader->activateShaders(); runShader->setModelViewProjectionMatrix(getProjectionMatrix() * _trans); - runShader->setTextureSize({width, height}); + runShader->setTextureSize({ width, height }); GL_CHECK_ERROR(glDrawArrays(GL_TRIANGLE_STRIP, 0, _numVertices)); runShader->deactivateShaders(); } @@ -338,20 +337,20 @@ namespace Renderer // scanlines to videos with non-standard aspect ratios. float relativeWidth = width / getScreenWidth(); float relativeAdjustment = (relativeWidth + relativeHeight) / 2.0f; - float modifier = 1.41f + relativeAdjustment / 7.0f - - (0.14f * screenHeightModifier); + float modifier = + 1.41f + relativeAdjustment / 7.0f - (0.14f * screenHeightModifier); shaderHeight = height * modifier; } if (runShader) { runShader->activateShaders(); runShader->setModelViewProjectionMatrix(getProjectionMatrix() * _trans); - runShader->setTextureSize({shaderWidth, shaderHeight}); + runShader->setTextureSize({ shaderWidth, shaderHeight }); GL_CHECK_ERROR(glDrawArrays(GL_TRIANGLE_STRIP, 0, _numVertices)); runShader->deactivateShaders(); } } } - #endif +#endif } void setProjection(const Transform4x4f& _projection) @@ -372,8 +371,8 @@ namespace Renderer void setViewport(const Rect& _viewport) { // glViewport starts at the bottom left of the window. - GL_CHECK_ERROR(glViewport( _viewport.x, getWindowHeight() - - _viewport.y - _viewport.h, _viewport.w, _viewport.h)); + GL_CHECK_ERROR(glViewport(_viewport.x, getWindowHeight() - _viewport.y - _viewport.h, + _viewport.w, _viewport.h)); } void setScissor(const Rect& _scissor) @@ -383,8 +382,8 @@ namespace Renderer } else { // glScissor starts at the bottom left of the window. - GL_CHECK_ERROR(glScissor(_scissor.x, getWindowHeight() - - _scissor.y - _scissor.h, _scissor.w, _scissor.h)); + GL_CHECK_ERROR(glScissor(_scissor.x, getWindowHeight() - _scissor.y - _scissor.h, + _scissor.w, _scissor.h)); GL_CHECK_ERROR(glEnable(GL_SCISSOR_TEST)); } } @@ -413,11 +412,12 @@ namespace Renderer GL_CHECK_ERROR(glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)); } - void shaderPostprocessing(unsigned int shaders, const Renderer::shaderParameters& parameters, - unsigned char* textureRGBA) + void shaderPostprocessing(unsigned int shaders, + const Renderer::shaderParameters& parameters, + unsigned char* textureRGBA) { Vertex vertices[4]; - std::vectorshaderList; + std::vector shaderList; GLuint width = getScreenWidth(); GLuint height = getScreenHeight(); float widthf = static_cast(width); @@ -425,10 +425,12 @@ namespace Renderer // Set vertex positions and texture coordinates to full screen as all // postprocessing is applied to the complete screen area. - vertices[0] = { { 0, 0 }, { 0, 1 }, 0 }; - vertices[1] = { { 0, heightf }, { 0, 0 }, 0 }; - vertices[2] = { { widthf, 0 }, { 1, 1 }, 0 }; - vertices[3] = { { widthf, heightf }, { 1, 0 }, 0}; + // clang-format off + vertices[0] = { { 0.0f , 0.0f }, { 0.0f, 1.0f }, 0 }; + vertices[1] = { { 0.0f , heightf }, { 0.0f, 0.0f }, 0 }; + vertices[2] = { { widthf, 0.0f }, { 1.0f, 1.0f }, 0 }; + vertices[3] = { { widthf, heightf }, { 1.0f, 0.0f }, 0 }; + // clang-format on if (shaders & Renderer::SHADER_DESATURATE) shaderList.push_back(Renderer::SHADER_DESATURATE); @@ -457,27 +459,24 @@ namespace Renderer // For the blur shaders there is an optional variable to set the number of passes // to execute, which proportionally affects the blur amount. if (shaderList[i] == Renderer::SHADER_BLUR_HORIZONTAL || - shaderList[i] == Renderer::SHADER_BLUR_VERTICAL) + shaderList[i] == Renderer::SHADER_BLUR_VERTICAL) { shaderPasses = parameters.blurPasses; + } for (int p = 0; p < shaderPasses; p++) { GL_CHECK_ERROR(glBindFramebuffer(GL_DRAW_FRAMEBUFFER, shaderFBO)); // Attach the texture to the shader framebuffer. - GL_CHECK_ERROR(glFramebufferTexture2D( - GL_FRAMEBUFFER, - GL_COLOR_ATTACHMENT0, - GL_TEXTURE_2D, - screenTexture, - 0)); + GL_CHECK_ERROR(glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, + GL_TEXTURE_2D, screenTexture, 0)); // Blit the screen contents to screenTexture. GL_CHECK_ERROR(glBlitFramebuffer(0, 0, width, height, 0, 0, width, height, - GL_COLOR_BUFFER_BIT, GL_NEAREST)); + GL_COLOR_BUFFER_BIT, GL_NEAREST)); // Apply/render the shaders. - drawTriangleStrips(vertices, 4, Transform4x4f::Identity(), - Blend::SRC_ALPHA, Blend::ONE_MINUS_SRC_ALPHA, parameters); + drawTriangleStrips(vertices, 4, Transform4x4f::Identity(), Blend::SRC_ALPHA, + Blend::ONE_MINUS_SRC_ALPHA, parameters); // If textureRGBA has an address, it means that the output should go to this // texture rather than to the screen. The glReadPixels() function is slow, but @@ -485,8 +484,8 @@ namespace Renderer // screen texture, it doesn't really matter. if (textureRGBA) { GL_CHECK_ERROR(glBindFramebuffer(GL_READ_FRAMEBUFFER, shaderFBO)); - GL_CHECK_ERROR(glReadPixels(0, 0, width, height, - GL_RGBA, GL_UNSIGNED_BYTE, textureRGBA)); + GL_CHECK_ERROR( + glReadPixels(0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE, textureRGBA)); GL_CHECK_ERROR(glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0)); } else { @@ -494,7 +493,7 @@ namespace Renderer GL_CHECK_ERROR(glBindFramebuffer(GL_READ_FRAMEBUFFER, shaderFBO)); GL_CHECK_ERROR(glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0)); GL_CHECK_ERROR(glBlitFramebuffer(0, 0, width, height, 0, 0, width, height, - GL_COLOR_BUFFER_BIT, GL_NEAREST)); + GL_COLOR_BUFFER_BIT, GL_NEAREST)); } } } @@ -503,6 +502,6 @@ namespace Renderer destroyTexture(screenTexture); } -} // Renderer:: +} // namespace Renderer #endif // USE_OPENGL_21 diff --git a/es-core/src/renderers/Renderer_GLES10.cpp b/es-core/src/renderers/Renderer_GLES10.cpp index e9e3a03f1..a179ca5fe 100644 --- a/es-core/src/renderers/Renderer_GLES10.cpp +++ b/es-core/src/renderers/Renderer_GLES10.cpp @@ -8,10 +8,10 @@ #if defined(USE_OPENGLES_10) -#include "renderers/Renderer.h" -#include "math/Transform4x4f.h" #include "Log.h" #include "Settings.h" +#include "math/Transform4x4f.h" +#include "renderers/Renderer.h" #include #include @@ -23,6 +23,7 @@ namespace Renderer static GLenum convertBlendFactor(const Blend::Factor _blendFactor) { + // clang-format off switch (_blendFactor) { case Blend::ZERO: { return GL_ZERO; } break; case Blend::ONE: { return GL_ONE; } break; @@ -36,20 +37,18 @@ namespace Renderer case Blend::ONE_MINUS_DST_ALPHA: { return GL_ONE_MINUS_DST_ALPHA; } break; default: { return GL_ZERO; } } + // clang-format on } static GLenum convertTextureType(const Texture::Type _type) { + // clang-format off switch (_type) { case Texture::RGBA: { return GL_RGBA; } break; case Texture::ALPHA: { return GL_ALPHA; } break; default: { return GL_ZERO; } } - } - - unsigned int getWindowFlags() - { - return SDL_WINDOW_OPENGL; + // clang-format on } void setupWindow() @@ -70,14 +69,15 @@ namespace Renderer sdlContext = SDL_GL_CreateContext(getSDLWindow()); SDL_GL_MakeCurrent(getSDLWindow(), sdlContext); - std::string vendor = glGetString(GL_VENDOR) ? - reinterpret_cast(glGetString(GL_VENDOR)) : ""; - std::string renderer = glGetString(GL_RENDERER) ? - reinterpret_cast(glGetString(GL_RENDERER)) : ""; - std::string version = glGetString(GL_VERSION) ? - reinterpret_cast(glGetString(GL_VERSION)) : ""; + std::string vendor = + glGetString(GL_VENDOR) ? reinterpret_cast(glGetString(GL_VENDOR)) : ""; + std::string renderer = + glGetString(GL_RENDERER) ? reinterpret_cast(glGetString(GL_RENDERER)) : ""; + std::string version = + glGetString(GL_VERSION) ? reinterpret_cast(glGetString(GL_VERSION)) : ""; std::string extensions = glGetString(GL_EXTENSIONS) ? - reinterpret_cast(glGetString(GL_EXTENSIONS)) : ""; + reinterpret_cast(glGetString(GL_EXTENSIONS)) : + ""; LOG(LogInfo) << "GL vendor: " << vendor; LOG(LogInfo) << "GL renderer: " << renderer; @@ -85,12 +85,13 @@ namespace Renderer LOG(LogInfo) << "EmulationStation renderer: OpenGL ES 1.0"; LOG(LogInfo) << "Checking available OpenGL ES extensions..."; std::string glExts = glGetString(GL_EXTENSIONS) ? - reinterpret_cast(glGetString(GL_EXTENSIONS)) : ""; - LOG(LogInfo) << "GL_OES_texture_npot: " << - (extensions.find("GL_OES_texture_npot") != - std::string::npos ? "OK" : "MISSING"); + reinterpret_cast(glGetString(GL_EXTENSIONS)) : + ""; + LOG(LogInfo) << "GL_OES_texture_npot: " + << (extensions.find("GL_OES_texture_npot") != std::string::npos ? "OK" : + "MISSING"); - uint8_t data[4] = {255, 255, 255, 255}; + uint8_t data[4] = { 255, 255, 255, 255 }; whiteTexture = createTexture(Texture::RGBA, false, true, 1, 1, data); GL_CHECK_ERROR(glClearColor(0.0f, 0.0f, 0.0f, 1.0f)); @@ -111,13 +112,12 @@ namespace Renderer sdlContext = nullptr; } - unsigned int createTexture( - const Texture::Type _type, - const bool _linear, - const bool _repeat, - const unsigned int _width, - const unsigned int _height, - void* _data) + unsigned int createTexture(const Texture::Type _type, + const bool _linear, + const bool _repeat, + const unsigned int _width, + const unsigned int _height, + void* _data) { const GLenum type = convertTextureType(_type); unsigned int texture; @@ -125,16 +125,16 @@ namespace Renderer GL_CHECK_ERROR(glGenTextures(1, &texture)); GL_CHECK_ERROR(glBindTexture(GL_TEXTURE_2D, texture)); - GL_CHECK_ERROR(glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, _repeat ? - GL_REPEAT : GL_CLAMP_TO_EDGE)); - GL_CHECK_ERROR(glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, _repeat ? - GL_REPEAT : GL_CLAMP_TO_EDGE)); - GL_CHECK_ERROR(glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, _linear ? - GL_LINEAR : GL_NEAREST)); + GL_CHECK_ERROR(glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, + _repeat ? GL_REPEAT : GL_CLAMP_TO_EDGE)); + GL_CHECK_ERROR(glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, + _repeat ? GL_REPEAT : GL_CLAMP_TO_EDGE)); + GL_CHECK_ERROR(glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, + _linear ? GL_LINEAR : GL_NEAREST)); GL_CHECK_ERROR(glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST)); GL_CHECK_ERROR(glTexImage2D(GL_TEXTURE_2D, 0, type, _width, _height, 0, type, - GL_UNSIGNED_BYTE, _data)); + GL_UNSIGNED_BYTE, _data)); return texture; } @@ -144,20 +144,19 @@ namespace Renderer GL_CHECK_ERROR(glDeleteTextures(1, &_texture)); } - void updateTexture( - const unsigned int _texture, - const Texture::Type _type, - const unsigned int _x, - const unsigned _y, - const unsigned int _width, - const unsigned int _height, - void* _data) + void updateTexture(const unsigned int _texture, + const Texture::Type _type, + const unsigned int _x, + const unsigned _y, + const unsigned int _width, + const unsigned int _height, + void* _data) { const GLenum type = convertTextureType(_type); GL_CHECK_ERROR(glBindTexture(GL_TEXTURE_2D, _texture)); GL_CHECK_ERROR(glTexSubImage2D(GL_TEXTURE_2D, 0, _x, _y, _width, _height, type, - GL_UNSIGNED_BYTE, _data)); + GL_UNSIGNED_BYTE, _data)); GL_CHECK_ERROR(glBindTexture(GL_TEXTURE_2D, whiteTexture)); } @@ -169,36 +168,34 @@ namespace Renderer GL_CHECK_ERROR(glBindTexture(GL_TEXTURE_2D, _texture)); } - void drawLines( - const Vertex* _vertices, - const unsigned int _numVertices, - const Blend::Factor _srcBlendFactor, - const Blend::Factor _dstBlendFactor) + void drawLines(const Vertex* _vertices, + const unsigned int _numVertices, + const Blend::Factor _srcBlendFactor, + const Blend::Factor _dstBlendFactor) { GL_CHECK_ERROR(glVertexPointer(2, GL_FLOAT, sizeof(Vertex), &_vertices[0].pos)); GL_CHECK_ERROR(glTexCoordPointer(2, GL_FLOAT, sizeof(Vertex), &_vertices[0].tex)); GL_CHECK_ERROR(glColorPointer(4, GL_UNSIGNED_BYTE, sizeof(Vertex), &_vertices[0].col)); - GL_CHECK_ERROR(glBlendFunc(convertBlendFactor(_srcBlendFactor), - convertBlendFactor(_dstBlendFactor))); + GL_CHECK_ERROR( + glBlendFunc(convertBlendFactor(_srcBlendFactor), convertBlendFactor(_dstBlendFactor))); GL_CHECK_ERROR(glDrawArrays(GL_LINES, 0, _numVertices)); } - void drawTriangleStrips( - const Vertex* _vertices, - const unsigned int _numVertices, - const Transform4x4f& _trans, - const Blend::Factor _srcBlendFactor, - const Blend::Factor _dstBlendFactor, - const shaderParameters& _parameters) + void drawTriangleStrips(const Vertex* _vertices, + const unsigned int _numVertices, + const Transform4x4f& _trans, + const Blend::Factor _srcBlendFactor, + const Blend::Factor _dstBlendFactor, + const shaderParameters& _parameters) { GL_CHECK_ERROR(glVertexPointer(2, GL_FLOAT, sizeof(Vertex), &_vertices[0].pos)); GL_CHECK_ERROR(glTexCoordPointer(2, GL_FLOAT, sizeof(Vertex), &_vertices[0].tex)); GL_CHECK_ERROR(glColorPointer(4, GL_UNSIGNED_BYTE, sizeof(Vertex), &_vertices[0].col)); - GL_CHECK_ERROR(glBlendFunc(convertBlendFactor(_srcBlendFactor), - convertBlendFactor(_dstBlendFactor))); + GL_CHECK_ERROR( + glBlendFunc(convertBlendFactor(_srcBlendFactor), convertBlendFactor(_dstBlendFactor))); GL_CHECK_ERROR(glDrawArrays(GL_TRIANGLE_STRIP, 0, _numVertices)); } @@ -221,8 +218,8 @@ namespace Renderer void setViewport(const Rect& _viewport) { // glViewport starts at the bottom left of the window. - GL_CHECK_ERROR(glViewport( _viewport.x, getWindowHeight() - - _viewport.y - _viewport.h, _viewport.w, _viewport.h)); + GL_CHECK_ERROR(glViewport(_viewport.x, getWindowHeight() - _viewport.y - _viewport.h, + _viewport.w, _viewport.h)); } void setScissor(const Rect& _scissor) @@ -232,8 +229,8 @@ namespace Renderer } else { // glScissor starts at the bottom left of the window. - GL_CHECK_ERROR(glScissor(_scissor.x, getWindowHeight() - - _scissor.y - _scissor.h, _scissor.w, _scissor.h)); + GL_CHECK_ERROR(glScissor(_scissor.x, getWindowHeight() - _scissor.y - _scissor.h, + _scissor.w, _scissor.h)); GL_CHECK_ERROR(glEnable(GL_SCISSOR_TEST)); } } @@ -262,6 +259,6 @@ namespace Renderer GL_CHECK_ERROR(glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)); } -} // Renderer:: +} // namespace Renderer #endif // USE_OPENGLES_10 diff --git a/es-core/src/renderers/Shader_GL21.cpp b/es-core/src/renderers/Shader_GL21.cpp index 44b467de6..52d376e53 100644 --- a/es-core/src/renderers/Shader_GL21.cpp +++ b/es-core/src/renderers/Shader_GL21.cpp @@ -10,26 +10,27 @@ #include "Shader_GL21.h" +#include "Log.h" #include "renderers/Renderer.h" #include "resources/ResourceManager.h" -#include "Log.h" namespace Renderer { Renderer::Shader::Shader() - : mProgramID(-1), - shaderMVPMatrix(-1), - shaderTextureSize(-1), - shaderTextureCoord(-1), - shaderColor(-1), - shaderSaturation(-1), - shaderOpacity(-1), - shaderDimValue(-1) + : mProgramID(-1) + , shaderMVPMatrix(-1) + , shaderTextureSize(-1) + , shaderTextureCoord(-1) + , shaderColor(-1) + , shaderSaturation(-1) + , shaderOpacity(-1) + , shaderDimValue(-1) { } Renderer::Shader::~Shader() { + // Delete the shader program when destroyed. deleteProgram(mProgramID); } @@ -52,8 +53,7 @@ namespace Renderer else if (shaderType == GL_FRAGMENT_SHADER) preprocessorDefines += "#define FRAGMENT\n"; - shaderVector.push_back(std::make_tuple( - path, preprocessorDefines + shaderCode, shaderType)); + shaderVector.push_back(std::make_tuple(path, preprocessorDefines + shaderCode, shaderType)); } bool Renderer::Shader::createProgram() @@ -67,16 +67,16 @@ namespace Renderer GLuint currentShader = glCreateShader(std::get<2>(*it)); GLchar const* shaderCodePtr = std::get<1>(*it).c_str(); - glShaderSource(currentShader, 1, - reinterpret_cast(&shaderCodePtr), nullptr); + glShaderSource(currentShader, 1, reinterpret_cast(&shaderCodePtr), + nullptr); glCompileShader(currentShader); GLint shaderCompiled; glGetShaderiv(currentShader, GL_COMPILE_STATUS, &shaderCompiled); if (shaderCompiled != GL_TRUE) { - LOG(LogError) << "OpenGL error: Unable to compile shader " << - currentShader << " (" << std::get<0>(*it) << ")."; + LOG(LogError) << "OpenGL error: Unable to compile shader " << currentShader << " (" + << std::get<0>(*it) << ")."; printShaderInfoLog(currentShader, std::get<2>(*it)); return false; } @@ -118,7 +118,7 @@ namespace Renderer { if (shaderMVPMatrix != -1) GL_CHECK_ERROR(glUniformMatrix4fv(shaderMVPMatrix, 1, GL_FALSE, - reinterpret_cast(&mvpMatrix))); + reinterpret_cast(&mvpMatrix))); } void Renderer::Shader::setTextureSize(std::array shaderVec2) @@ -130,16 +130,16 @@ namespace Renderer void Renderer::Shader::setTextureCoordinates(std::array shaderVec4) { if (shaderTextureCoord != -1) { - glVertexAttrib4f(shaderTextureCoord, shaderVec4[0], shaderVec4[1], - shaderVec4[2], shaderVec4[3]); + glVertexAttrib4f(shaderTextureCoord, shaderVec4[0], shaderVec4[1], shaderVec4[2], + shaderVec4[3]); } } void Renderer::Shader::setColor(std::array shaderVec4) { if (shaderColor != -1) - GL_CHECK_ERROR(glUniform4f(shaderColor, shaderVec4[0], - shaderVec4[1], shaderVec4[2], shaderVec4[3])); + GL_CHECK_ERROR(glUniform4f(shaderColor, shaderVec4[0], shaderVec4[1], shaderVec4[2], + shaderVec4[3])); } void Renderer::Shader::setSaturation(GLfloat saturation) @@ -162,19 +162,16 @@ namespace Renderer void Renderer::Shader::activateShaders() { + // Install the shader program. GL_CHECK_ERROR(glUseProgram(mProgramID)); } void Renderer::Shader::deactivateShaders() { + // Remove the shader program. GL_CHECK_ERROR(glUseProgram(0)); } - GLuint Renderer::Shader::getProgramID() - { - return mProgramID; - } - void Renderer::Shader::printProgramInfoLog(GLuint programID) { if (glIsProgram(programID)) { @@ -187,8 +184,8 @@ namespace Renderer glGetProgramInfoLog(programID, maxLength, &logLength, &infoLog.front()); if (logLength > 0) { - LOG(LogDebug) << "Renderer_GL21::printProgramLog():\n" << - std::string(infoLog.begin(), infoLog.end()); + LOG(LogDebug) << "Renderer_GL21::printProgramLog():\n" + << std::string(infoLog.begin(), infoLog.end()); } } else { @@ -208,9 +205,10 @@ namespace Renderer glGetShaderInfoLog(shaderID, maxLength, &logLength, &infoLog.front()); if (logLength > 0) { - LOG(LogDebug) << "Renderer_GL21::printShaderLog(): Error in " << - (shaderType == GL_VERTEX_SHADER ? "VERTEX section:\n" : - "FRAGMENT section:\n") << std::string(infoLog.begin(), infoLog.end()); + LOG(LogDebug) << "Renderer_GL21::printShaderLog(): Error in " + << (shaderType == GL_VERTEX_SHADER ? "VERTEX section:\n" : + "FRAGMENT section:\n") + << std::string(infoLog.begin(), infoLog.end()); } } else { @@ -218,6 +216,6 @@ namespace Renderer } } -} // Renderer +} // namespace Renderer #endif // USE_OPENGL_21 diff --git a/es-core/src/renderers/Shader_GL21.h b/es-core/src/renderers/Shader_GL21.h index f92e6e28b..94a78b40f 100644 --- a/es-core/src/renderers/Shader_GL21.h +++ b/es-core/src/renderers/Shader_GL21.h @@ -52,7 +52,7 @@ namespace Renderer // Sets the shader program to 0 which reverts to the fixed function pipeline. void deactivateShaders(); // Returns the program ID that was generated by glCreateProgram(). - GLuint getProgramID(); + GLuint getProgramID() { return mProgramID; } // Only used for error logging if the shaders fail to compile or link. void printProgramInfoLog(GLuint programID); void printShaderInfoLog(GLuint shaderID, GLenum shaderType); @@ -71,6 +71,6 @@ namespace Renderer GLint shaderDimValue; }; -} // Renderer +} // namespace Renderer #endif // ES_CORE_RENDERER_SHADER_GL21_H diff --git a/es-core/src/resources/Font.cpp b/es-core/src/resources/Font.cpp index 5f3f6f94b..59011ce8f 100644 --- a/es-core/src/resources/Font.cpp +++ b/es-core/src/resources/Font.cpp @@ -9,20 +9,20 @@ #include "resources/Font.h" +#include "Log.h" #include "renderers/Renderer.h" #include "utils/FileSystemUtil.h" #include "utils/StringUtil.h" -#include "Log.h" FT_Library Font::sLibrary = nullptr; -int Font::getSize() const { return mSize; } - std::map, std::weak_ptr> Font::sFontMap; -Font::FontFace::FontFace(ResourceData&& d, int size) : data(d) +Font::FontFace::FontFace(ResourceData&& d, int size) + : data(d) { - int err = FT_New_Memory_Face(sLibrary, data.ptr.get(), (FT_Long)data.length, 0, &face); + int err = + FT_New_Memory_Face(sLibrary, data.ptr.get(), static_cast(data.length), 0, &face); assert(!err); if (!err) @@ -38,6 +38,7 @@ Font::FontFace::~FontFace() void Font::initLibrary() { assert(sLibrary == nullptr); + if (FT_Init_FreeType(&sLibrary)) { sLibrary = nullptr; LOG(LogError) << "Couldn't initialize FreeType"; @@ -74,7 +75,9 @@ size_t Font::getTotalMemUsage() return total; } -Font::Font(int size, const std::string& path) : mSize(size), mPath(path) +Font::Font(int size, const std::string& path) + : mSize(size) + , mPath(path) { assert(mSize > 0); @@ -96,9 +99,8 @@ Font::~Font() auto fontEntry = sFontMap.find(std::pair(mPath, mSize)); - if (fontEntry != sFontMap.cend()) { + if (fontEntry != sFontMap.cend()) sFontMap.erase(fontEntry); - } if (sFontMap.empty() && sLibrary) { FT_Done_FreeType(sLibrary); @@ -106,21 +108,11 @@ Font::~Font() } } -void Font::reload(std::shared_ptr& /*rm*/) -{ - rebuildTextures(); -} - -void Font::unload(std::shared_ptr& /*rm*/) -{ - unloadTextures(); -} - std::shared_ptr Font::get(int size, const std::string& path) { const std::string canonicalPath = Utils::FileSystem::getCanonicalPath(path); - std::pair def(canonicalPath.empty() ? getDefaultPath() : canonicalPath, size); + auto foundFont = sFontMap.find(def); if (foundFont != sFontMap.cend()) { if (!foundFont->second.expired()) @@ -152,6 +144,7 @@ Font::FontTexture::FontTexture(const int mSize) Font::FontTexture::~FontTexture() { + // Deinit the texture when destroyed. deinitTexture(); } @@ -162,14 +155,12 @@ bool Font::FontTexture::findEmpty(const Vector2i& size, Vector2i& cursor_out) if (writePos.x() + size.x() >= textureSize.x() && writePos.y() + rowHeight + size.y() + 1 < textureSize.y()) { - // Row full, but it should fit on the next row. - // Move cursor to next row. + // Row full, but it should fit on the next row so move the cursor there. writePos = Vector2i(0, writePos.y() + rowHeight + 1); // Leave 1px of space between glyphs. rowHeight = 0; } - if (writePos.x() + size.x() >= textureSize.x() || - writePos.y() + size.y() >= textureSize.y()) { + if (writePos.x() + size.x() >= textureSize.x() || writePos.y() + size.y() >= textureSize.y()) { // Nope, still won't fit. return false; } @@ -186,21 +177,21 @@ bool Font::FontTexture::findEmpty(const Vector2i& size, Vector2i& cursor_out) void Font::FontTexture::initTexture() { assert(textureId == 0); - textureId = Renderer::createTexture(Renderer::Texture::ALPHA, false, false, - textureSize.x(), textureSize.y(), nullptr); + textureId = Renderer::createTexture(Renderer::Texture::ALPHA, false, false, textureSize.x(), + textureSize.y(), nullptr); } void Font::FontTexture::deinitTexture() { - if (textureId != 0) - { + if (textureId != 0) { Renderer::destroyTexture(textureId); textureId = 0; } } void Font::getTextureForNewGlyph(const Vector2i& glyphSize, - FontTexture*& tex_out, Vector2i& cursor_out) + FontTexture*& tex_out, + Vector2i& cursor_out) { if (mTextures.size()) { // Check if the most recent texture has space. @@ -218,8 +209,8 @@ void Font::getTextureForNewGlyph(const Vector2i& glyphSize, bool ok = tex_out->findEmpty(glyphSize, cursor_out); if (!ok) { - LOG(LogError) << "Glyph too big to fit on a new texture (glyph size > " << - tex_out->textureSize.x() << ", " << tex_out->textureSize.y() << ")"; + LOG(LogError) << "Glyph too big to fit on a new texture (glyph size > " + << tex_out->textureSize.x() << ", " << tex_out->textureSize.y() << ")"; tex_out = nullptr; } } @@ -234,23 +225,20 @@ std::vector getFallbackFontPaths() ResourceManager::getInstance()->getResourcePath(":/fonts/Akrobat-SemiBold.ttf"); // Vera sans Unicode. - fontPaths.push_back(ResourceManager::getInstance()-> - getResourcePath(":/fonts/DejaVuSans.ttf")); + fontPaths.push_back(ResourceManager::getInstance()->getResourcePath(":/fonts/DejaVuSans.ttf")); // GNU FreeFont monospaced. - fontPaths.push_back(ResourceManager::getInstance()-> - getResourcePath(":/fonts/FreeMono.ttf")); + fontPaths.push_back(ResourceManager::getInstance()->getResourcePath(":/fonts/FreeMono.ttf")); // Various languages, such as Japanese and Chinese. - fontPaths.push_back(ResourceManager::getInstance()-> - getResourcePath(":/fonts/DroidSansFallbackFull.ttf")); + fontPaths.push_back( + ResourceManager::getInstance()->getResourcePath(":/fonts/DroidSansFallbackFull.ttf")); // Korean. - fontPaths.push_back(ResourceManager::getInstance()-> - getResourcePath(":/fonts/NanumMyeongjo.ttf")); + fontPaths.push_back( + ResourceManager::getInstance()->getResourcePath(":/fonts/NanumMyeongjo.ttf")); // Font Awesome icon glyphs, used for various special symbols like stars, folders etc. - fontPaths.push_back(ResourceManager::getInstance()-> - getResourcePath(":/fonts/fontawesome-webfont.ttf")); + fontPaths.push_back( + ResourceManager::getInstance()->getResourcePath(":/fonts/fontawesome-webfont.ttf")); // This is only needed for some really rare special characters. - fontPaths.push_back(ResourceManager::getInstance()-> - getResourcePath(":/fonts/Ubuntu-C.ttf")); + fontPaths.push_back(ResourceManager::getInstance()->getResourcePath(":/fonts/Ubuntu-C.ttf")); fontPaths.shrink_to_fit(); return fontPaths; @@ -283,10 +271,7 @@ FT_Face Font::getFaceForChar(unsigned int id) return mFaceCache.cbegin()->second->face; } -void Font::clearFaceCache() -{ - mFaceCache.clear(); -} +void Font::clearFaceCache() { mFaceCache.clear(); } Font::Glyph* Font::getGlyph(unsigned int id) { @@ -298,16 +283,16 @@ Font::Glyph* Font::getGlyph(unsigned int id) // Nope, need to make a glyph. FT_Face face = getFaceForChar(id); if (!face) { - LOG(LogError) << "Couldn't find appropriate font face for character " << - id << " for font " << mPath; + LOG(LogError) << "Couldn't find appropriate font face for character " << id << " for font " + << mPath; return nullptr; } FT_GlyphSlot g = face->glyph; if (FT_Load_Char(face, id, FT_LOAD_RENDER)) { - LOG(LogError) << "Couldn't find glyph for character " << - id << " for font " << mPath << ", size " << mSize; + LOG(LogError) << "Couldn't find glyph for character " << id << " for font " << mPath + << ", size " << mSize; return nullptr; } @@ -320,8 +305,8 @@ Font::Glyph* Font::getGlyph(unsigned int id) // getTextureForNewGlyph can fail if the glyph is bigger than the max texture // size (absurdly large font size). if (tex == nullptr) { - LOG(LogError) << "Couldn't create glyph for character " << id << " for font " << - mPath << ", size " << mSize << " (no suitable texture found)"; + LOG(LogError) << "Couldn't create glyph for character " << id << " for font " << mPath + << ", size " << mSize << " (no suitable texture found)"; return nullptr; } @@ -330,18 +315,18 @@ Font::Glyph* Font::getGlyph(unsigned int id) glyph.texture = tex; glyph.texPos = Vector2f(cursor.x() / static_cast(tex->textureSize.x()), - cursor.y() / static_cast(tex->textureSize.y())); + cursor.y() / static_cast(tex->textureSize.y())); glyph.texSize = Vector2f(glyphSize.x() / static_cast(tex->textureSize.x()), - glyphSize.y() / static_cast(tex->textureSize.y())); + glyphSize.y() / static_cast(tex->textureSize.y())); glyph.advance = Vector2f(static_cast(g->metrics.horiAdvance) / 64.0f, - static_cast(g->metrics.vertAdvance) / 64.0f); + static_cast(g->metrics.vertAdvance) / 64.0f); glyph.bearing = Vector2f(static_cast(g->metrics.horiBearingX) / 64.0f, - static_cast(g->metrics.horiBearingY) / 64.0f); + static_cast(g->metrics.horiBearingY) / 64.0f); // Upload glyph bitmap to texture. - Renderer::updateTexture(tex->textureId, Renderer::Texture::ALPHA, cursor.x(), - cursor.y(), glyphSize.x(), glyphSize.y(), g->bitmap.buffer); + Renderer::updateTexture(tex->textureId, Renderer::Texture::ALPHA, cursor.x(), cursor.y(), + glyphSize.x(), glyphSize.y(), g->bitmap.buffer); // Update max glyph height. if (glyphSize.y() > mMaxGlyphHeight) @@ -358,7 +343,7 @@ void Font::rebuildTextures() for (auto it = mTextures.begin(); it != mTextures.end(); it++) it->initTexture(); - // Reupload the texture data. + // Re-upload the texture data. for (auto it = mGlyphMap.cbegin(); it != mGlyphMap.cend(); it++) { FT_Face face = getFaceForChar(it->first); FT_GlyphSlot glyphSlot = face->glyph; @@ -370,13 +355,13 @@ void Font::rebuildTextures() // Find the position/size. Vector2i cursor(static_cast(it->second.texPos.x() * tex->textureSize.x()), - static_cast(it->second.texPos.y() * tex->textureSize.y())); + static_cast(it->second.texPos.y() * tex->textureSize.y())); Vector2i glyphSize(static_cast(it->second.texSize.x() * tex->textureSize.x()), - static_cast(it->second.texSize.y() * tex->textureSize.y())); + static_cast(it->second.texSize.y() * tex->textureSize.y())); // Upload to texture. - Renderer::updateTexture(tex->textureId, Renderer::Texture::ALPHA, - cursor.x(), cursor.y(), glyphSize.x(), glyphSize.y(), glyphSlot->bitmap.buffer); + Renderer::updateTexture(tex->textureId, Renderer::Texture::ALPHA, cursor.x(), cursor.y(), + glyphSize.x(), glyphSize.y(), glyphSlot->bitmap.buffer); } } @@ -394,7 +379,7 @@ void Font::renderTextCache(TextCache* cache) Renderer::bindTexture(*it->textureIdPtr); Renderer::drawTriangleStrips(&it->verts[0], - static_cast(it->verts.size())); + static_cast(it->verts.size())); } } @@ -442,6 +427,7 @@ std::string Font::getTextMaxWidth(std::string text, float maxWidth) float Font::getHeight(float lineSpacing) const { + // Return overall height including line spacing. return mMaxGlyphHeight * lineSpacing; } @@ -466,7 +452,7 @@ std::string Font::wrapText(std::string text, float xLen) float dotsSize = sizeText("...").x(); // While there's text or we still have text to render. - while (text.length() > 0) { + while (text.length() > 0) { space = text.find_first_of(" \t\n"); if (space == std::string::npos) space = text.length() - 1; @@ -515,8 +501,10 @@ Vector2f Font::sizeWrappedText(std::string text, float xLen, float lineSpacing) return sizeText(text, lineSpacing); } -Vector2f Font::getWrappedTextCursorOffset(std::string text, float xLen, - size_t stop, float lineSpacing) +Vector2f Font::getWrappedTextCursorOffset(std::string text, + float xLen, + size_t stop, + float lineSpacing) { std::string wrappedText = wrapText(text, xLen); @@ -557,36 +545,43 @@ Vector2f Font::getWrappedTextCursorOffset(std::string text, float xLen, // TextCache. // -float Font::getNewlineStartOffset(const std::string& text, const unsigned int& charStart, - const float& xLen, const Alignment& alignment) +float Font::getNewlineStartOffset(const std::string& text, + const unsigned int& charStart, + const float& xLen, + const Alignment& alignment) { switch (alignment) { - case ALIGN_LEFT: - return 0; - case ALIGN_CENTER: { + case ALIGN_LEFT: { + return 0; + } + case ALIGN_CENTER: { int endChar = 0; endChar = static_cast(text.find('\n', charStart)); - return (xLen - sizeText(text.substr(charStart, endChar != - std::string::npos ? endChar - charStart : endChar)).x()) / 2.0f; - } - case ALIGN_RIGHT: { + return (xLen - sizeText(text.substr(charStart, endChar != std::string::npos ? + endChar - charStart : + endChar)) + .x()) / + 2.0f; + } + case ALIGN_RIGHT: { int endChar = static_cast(text.find('\n', charStart)); - return xLen - (sizeText(text.substr(charStart, endChar != - std::string::npos ? endChar - charStart : endChar)).x()); - } - default: - return 0; + return xLen - (sizeText(text.substr(charStart, endChar != std::string::npos ? + endChar - charStart : + endChar)) + .x()); + } + default: + return 0; } } -TextCache* Font::buildTextCache( - const std::string& text, - Vector2f offset, - unsigned int color, - float xLen, - Alignment alignment, - float lineSpacing, - bool noTopMargin) +TextCache* Font::buildTextCache(const std::string& text, + Vector2f offset, + unsigned int color, + float xLen, + Alignment alignment, + float lineSpacing, + bool noTopMargin) { float x = offset[0] + (xLen != 0 ? getNewlineStartOffset(text, 0, xLen, alignment) : 0); float yTop = 0; @@ -618,9 +613,12 @@ TextCache* Font::buildTextCache( if (character == '\n') { y += getHeight(lineSpacing); - x = offset[0] + (xLen != 0 ? getNewlineStartOffset(text, - static_cast(cursor) /* cursor is already advanced */, - xLen, alignment) : 0); + x = offset[0] + (xLen != 0 ? + getNewlineStartOffset(text, + static_cast( + cursor) /* cursor is already advanced */, + xLen, alignment) : + 0); continue; } @@ -637,23 +635,22 @@ TextCache* Font::buildTextCache( const Vector2i& textureSize = glyph->texture->textureSize; const unsigned int convertedColor = Renderer::convertRGBAToABGR(color); - vertices[1] = { - { glyphStartX, y - glyph->bearing.y() }, - { glyph->texPos.x(), glyph->texPos.y() }, - convertedColor }; - vertices[2] = { - { glyphStartX, y - glyph->bearing.y() + (glyph->texSize.y() * textureSize.y()) }, - { glyph->texPos.x(), glyph->texPos.y() + glyph->texSize.y() }, - convertedColor }; - vertices[3] = { - { glyphStartX + glyph->texSize.x() * textureSize.x(), y - glyph->bearing.y() }, - { glyph->texPos.x() + glyph->texSize.x(), glyph->texPos.y() }, - convertedColor }; - vertices[4] = { - { glyphStartX + glyph->texSize.x() * textureSize.x(), y - glyph->bearing.y() + - (glyph->texSize.y() * textureSize.y()) }, - { glyph->texPos.x() + glyph->texSize.x(), glyph->texPos.y() + glyph->texSize.y() }, - convertedColor }; + vertices[1] = { { glyphStartX, y - glyph->bearing.y() }, + { glyph->texPos.x(), glyph->texPos.y() }, + convertedColor }; + vertices[2] = { { glyphStartX, + y - glyph->bearing.y() + (glyph->texSize.y() * textureSize.y()) }, + { glyph->texPos.x(), glyph->texPos.y() + glyph->texSize.y() }, + convertedColor }; + vertices[3] = { { glyphStartX + glyph->texSize.x() * textureSize.x(), + y - glyph->bearing.y() }, + { glyph->texPos.x() + glyph->texSize.x(), glyph->texPos.y() }, + convertedColor }; + vertices[4] = { { glyphStartX + glyph->texSize.x() * textureSize.x(), + y - glyph->bearing.y() + (glyph->texSize.y() * textureSize.y()) }, + { glyph->texPos.x() + glyph->texSize.x(), + glyph->texPos.y() + glyph->texSize.y() }, + convertedColor }; // Round vertices. for (int i = 1; i < 5; i++) @@ -667,7 +664,7 @@ TextCache* Font::buildTextCache( x += glyph->advance.x(); } - //TextCache::CacheMetrics metrics = { sizeText(text, lineSpacing) }; + // TextCache::CacheMetrics metrics = { sizeText(text, lineSpacing) }; TextCache* cache = new TextCache(); cache->vertexLists.resize(vertMap.size()); @@ -682,20 +679,18 @@ TextCache* Font::buildTextCache( } clearFaceCache(); - return cache; } -TextCache* Font::buildTextCache( - const std::string& text, - float offsetX, - float offsetY, - unsigned int color, - float lineSpacing, - bool noTopMargin) +TextCache* Font::buildTextCache(const std::string& text, + float offsetX, + float offsetY, + unsigned int color, + float lineSpacing, + bool noTopMargin) { - return buildTextCache(text, Vector2f(offsetX, offsetY), color, 0.0f, ALIGN_LEFT, - lineSpacing, noTopMargin); + return buildTextCache(text, Vector2f(offsetX, offsetY), color, 0.0f, ALIGN_LEFT, lineSpacing, + noTopMargin); } void TextCache::setColor(unsigned int color) @@ -708,7 +703,8 @@ void TextCache::setColor(unsigned int color) } std::shared_ptr Font::getFromTheme(const ThemeData::ThemeElement* elem, - unsigned int properties, const std::shared_ptr& orig) + unsigned int properties, + const std::shared_ptr& orig) { using namespace ThemeFlags; if (!(properties & FONT_PATH) && !(properties & FONT_SIZE)) @@ -725,8 +721,10 @@ std::shared_ptr Font::getFromTheme(const ThemeData::ThemeElement* elem, path = elem->get("fontPath"); if (!((path[0] == ':') && (path[1] == '/')) && !Utils::FileSystem::exists(path)) { - LOG(LogError) << "Font file \"" << path << "\" defined by the theme does not exist, " - "falling back to \"" << getDefaultPath() << "\""; + LOG(LogError) << "Font file \"" << path + << "\" defined by the theme does not exist, " + "falling back to \"" + << getDefaultPath() << "\""; path = getDefaultPath(); } diff --git a/es-core/src/resources/Font.h b/es-core/src/resources/Font.h index 15365cbcb..63bc3a757 100644 --- a/es-core/src/resources/Font.h +++ b/es-core/src/resources/Font.h @@ -10,11 +10,11 @@ #ifndef ES_CORE_RESOURCES_FONT_H #define ES_CORE_RESOURCES_FONT_H +#include "ThemeData.h" #include "math/Vector2f.h" #include "math/Vector2i.h" #include "renderers/Renderer.h" #include "resources/ResourceManager.h" -#include "ThemeData.h" #include #include FT_FREETYPE_H @@ -22,6 +22,7 @@ class TextCache; +// clang-format off #define FONT_SIZE_MINI (static_cast(0.030f * \ std::min(Renderer::getScreenHeight(), Renderer::getScreenWidth()))) #define FONT_SIZE_SMALL (static_cast(0.035f * \ @@ -30,6 +31,7 @@ class TextCache; std::min(Renderer::getScreenHeight(), Renderer::getScreenWidth()))) #define FONT_SIZE_LARGE (static_cast(0.085f * \ std::min(Renderer::getScreenHeight(), Renderer::getScreenWidth()))) +// clang-format on #define FONT_PATH_LIGHT ":/fonts/Akrobat-Regular.ttf" #define FONT_PATH_REGULAR ":/fonts/Akrobat-SemiBold.ttf" @@ -47,54 +49,58 @@ enum Alignment { class Font : public IReloadable { public: - static void initLibrary(); - - static std::shared_ptr get(int size, const std::string& path = getDefaultPath()); - virtual ~Font(); + static void initLibrary(); + static std::shared_ptr get(int size, const std::string& path = getDefaultPath()); // Returns the expected size of a string when rendered. Extra spacing is applied to the Y axis. Vector2f sizeText(std::string text, float lineSpacing = 1.5f); + // Returns the portion of a string that fits within the passed argument maxWidth. std::string getTextMaxWidth(std::string text, float maxWidth); - TextCache* buildTextCache( - const std::string& text, - float offsetX, - float offsetY, - unsigned int color, - float lineSpacing = 1.5f, - bool noTopMargin = false); - TextCache* buildTextCache( - const std::string& text, - Vector2f offset, - unsigned int color, - float xLen, - Alignment alignment = ALIGN_LEFT, - float lineSpacing = 1.5f, - bool noTopMargin = false); + + TextCache* buildTextCache(const std::string& text, + float offsetX, + float offsetY, + unsigned int color, + float lineSpacing = 1.5f, + bool noTopMargin = false); + + TextCache* buildTextCache(const std::string& text, + Vector2f offset, + unsigned int color, + float xLen, + Alignment alignment = ALIGN_LEFT, + float lineSpacing = 1.5f, + bool noTopMargin = false); + void renderTextCache(TextCache* cache); // Inserts newlines into text to make it wrap properly. std::string wrapText(std::string text, float xLen); + // Returns the expected size of a string after wrapping is applied. Vector2f sizeWrappedText(std::string text, float xLen, float lineSpacing = 1.5f); - // Returns the position of of the cursor after moving "cursor" characters. - Vector2f getWrappedTextCursorOffset(std::string text, float xLen, size_t cursor, - float lineSpacing = 1.5f); + + // Returns the position of the cursor after moving a "cursor" amount of characters. + Vector2f getWrappedTextCursorOffset(std::string text, + float xLen, + size_t cursor, + float lineSpacing = 1.5f); float getHeight(float lineSpacing = 1.5f) const; float getLetterHeight(); - void unload(std::shared_ptr& rm) override; - void reload(std::shared_ptr& rm) override; + void reload(std::shared_ptr& rm) override { rebuildTextures(); } + void unload(std::shared_ptr& rm) override { unloadTextures(); } - int getSize() const; - inline const std::string& getPath() const { return mPath; } - - inline static std::string getDefaultPath() { return FONT_PATH_REGULAR; } + int getSize() const { return mSize; } + const std::string& getPath() const { return mPath; } + static std::string getDefaultPath() { return FONT_PATH_REGULAR; } static std::shared_ptr getFromTheme(const ThemeData::ThemeElement* elem, - unsigned int properties, const std::shared_ptr& orig); + unsigned int properties, + const std::shared_ptr& orig); // Returns an approximation of VRAM used by this font's texture (in bytes). size_t getMemUsage() const; @@ -122,6 +128,7 @@ private: // Initializes the OpenGL texture according to this FontTexture's settings, // updating textureId. void initTexture(); + // Deinitializes the OpenGL texture if any exists, is automatically called // in the destructor. void deinitTexture(); @@ -140,8 +147,9 @@ private: std::vector mTextures; - void getTextureForNewGlyph(const Vector2i& glyphSize, FontTexture*& tex_out, - Vector2i& cursor_out); + void getTextureForNewGlyph(const Vector2i& glyphSize, + FontTexture*& tex_out, + Vector2i& cursor_out); std::map> mFaceCache; FT_Face getFaceForChar(unsigned int id); @@ -166,8 +174,10 @@ private: const int mSize; const std::string mPath; - float getNewlineStartOffset(const std::string& text, const unsigned int& charStart, - const float& xLen, const Alignment& alignment); + float getNewlineStartOffset(const std::string& text, + const unsigned int& charStart, + const float& xLen, + const Alignment& alignment); friend TextCache; }; diff --git a/es-core/src/resources/ResourceManager.cpp b/es-core/src/resources/ResourceManager.cpp index c75ae5787..e61d69ea9 100644 --- a/es-core/src/resources/ResourceManager.cpp +++ b/es-core/src/resources/ResourceManager.cpp @@ -9,23 +9,19 @@ #include "ResourceManager.h" -#include "utils/FileSystemUtil.h" -#include "utils/StringUtil.h" #include "Log.h" #include "Platform.h" #include "Scripting.h" +#include "utils/FileSystemUtil.h" +#include "utils/StringUtil.h" #include auto array_deleter = [](unsigned char* p) { delete[] p; }; -auto nop_deleter = [](unsigned char* /*p*/) { }; +auto nop_deleter = [](unsigned char* /*p*/) {}; std::shared_ptr ResourceManager::sInstance = nullptr; -ResourceManager::ResourceManager() -{ -} - std::shared_ptr& ResourceManager::getInstance() { if (!sInstance) @@ -34,8 +30,7 @@ std::shared_ptr& ResourceManager::getInstance() return sInstance; } -std::string ResourceManager::getResourcePath(const std::string& path, - bool terminateOnFailure) const +std::string ResourceManager::getResourcePath(const std::string& path, bool terminateOnFailure) const { // Check if this is a resource file. if ((path[0] == ':') && (path[1] == '/')) { @@ -47,17 +42,17 @@ std::string ResourceManager::getResourcePath(const std::string& path, if (Utils::FileSystem::exists(testHome)) return testHome; +#if defined(__APPLE__) // For macOS, check in the ../Resources directory relative to the executable directory. - #if defined(__APPLE__) std::string applePackagePath = - Utils::FileSystem::getExePath() + "/../Resources/resources/" + &path[2]; + Utils::FileSystem::getExePath() + "/../Resources/resources/" + &path[2]; if (Utils::FileSystem::exists(applePackagePath)) { return applePackagePath; } +#elif defined(__unix__) // Check under the data installation directory (Unix only). - #elif defined(__unix__) std::string testDataPath; testDataPath = Utils::FileSystem::getProgramDataPath() + "/resources/" + &path[2]; @@ -65,7 +60,7 @@ std::string ResourceManager::getResourcePath(const std::string& path, if (Utils::FileSystem::exists(testDataPath)) { return testDataPath; } - #endif +#endif // Check under the ES executable directory. std::string testExePath = Utils::FileSystem::getExePath() + "/resources/" + &path[2]; @@ -81,11 +76,11 @@ std::string ResourceManager::getResourcePath(const std::string& path, LOG(LogError) << "Program resource missing: " << path; LOG(LogError) << "Tried to find the resource in the following locations:"; LOG(LogError) << testHome; - #if defined(__APPLE__) +#if defined(__APPLE__) LOG(LogError) << applePackagePath; - #elif defined(__unix__) +#elif defined(__unix__) LOG(LogError) << testDataPath; - #endif +#endif LOG(LogError) << testExePath; LOG(LogError) << "Has EmulationStation been properly installed?"; Scripting::fireEvent("quit"); @@ -112,17 +107,17 @@ const ResourceData ResourceManager::getFileData(const std::string& path) const } // If the file doesn't exist, return an "empty" ResourceData. - ResourceData data = {nullptr, 0}; + ResourceData data = { nullptr, 0 }; return data; } ResourceData ResourceManager::loadFile(const std::string& path) const { - #if defined(_WIN64) +#if defined(_WIN64) std::ifstream stream(Utils::String::stringToWideString(path).c_str(), std::ios::binary); - #else +#else std::ifstream stream(path, std::ios::binary); - #endif +#endif stream.seekg(0, stream.end); size_t size = static_cast(stream.tellg()); @@ -133,7 +128,7 @@ ResourceData ResourceManager::loadFile(const std::string& path) const stream.read(reinterpret_cast(data.get()), size); stream.close(); - ResourceData ret = {data, size}; + ResourceData ret = { data, size }; return ret; } diff --git a/es-core/src/resources/ResourceManager.h b/es-core/src/resources/ResourceManager.h index 5ddfcc310..e668bff99 100644 --- a/es-core/src/resources/ResourceManager.h +++ b/es-core/src/resources/ResourceManager.h @@ -47,7 +47,7 @@ public: bool fileExists(const std::string& path) const; private: - ResourceManager(); + ResourceManager() {} static std::shared_ptr sInstance; std::list> mReloadables; diff --git a/es-core/src/resources/TextureData.cpp b/es-core/src/resources/TextureData.cpp index c43298804..58b114c4e 100644 --- a/es-core/src/resources/TextureData.cpp +++ b/es-core/src/resources/TextureData.cpp @@ -11,11 +11,11 @@ #include "resources/TextureData.h" +#include "ImageIO.h" +#include "Log.h" #include "math/Misc.h" #include "renderers/Renderer.h" #include "resources/ResourceManager.h" -#include "ImageIO.h" -#include "Log.h" #include #include @@ -23,17 +23,16 @@ #define DPI 96 -TextureData::TextureData( - bool tile) - : mTile(tile), - mTextureID(0), - mDataRGBA({}), - mScaleDuringLoad(1.0f), - mScalable(false), - mWidth(0), - mHeight(0), - mSourceWidth(0.0f), - mSourceHeight(0.0f) +TextureData::TextureData(bool tile) + : mTile(tile) + , mTextureID(0) + , mDataRGBA({}) + , mScaleDuringLoad(1.0f) + , mScalable(false) + , mWidth(0) + , mHeight(0) + , mSourceWidth(0.0f) + , mSourceHeight(0.0f) { } @@ -78,13 +77,13 @@ bool TextureData::initSVGFromMemory(const std::string& fileData) if (mWidth == 0) { // Auto scale width to keep aspect ratio. - mWidth = static_cast(std::round((static_cast(mHeight) / - svgImage->height) * svgImage->width)); + mWidth = static_cast( + std::round((static_cast(mHeight) / svgImage->height) * svgImage->width)); } else if (mHeight == 0) { // Auto scale height to keep aspect ratio. - mHeight = static_cast(std::round((static_cast(mWidth) / - svgImage->width) * svgImage->height)); + mHeight = static_cast( + std::round((static_cast(mWidth) / svgImage->width) * svgImage->height)); } std::vector tempVector; @@ -93,14 +92,15 @@ bool TextureData::initSVGFromMemory(const std::string& fileData) NSVGrasterizer* rast = nsvgCreateRasterizer(); nsvgRasterize(rast, svgImage, 0, 0, mHeight / svgImage->height, tempVector.data(), - static_cast(mWidth), static_cast(mHeight), static_cast(mWidth) * 4); + static_cast(mWidth), static_cast(mHeight), + static_cast(mWidth) * 4); // This is important in order to avoid memory leaks. nsvgDeleteRasterizer(rast); nsvgDelete(svgImage); - mDataRGBA.insert(mDataRGBA.begin(), - tempVector.data(), tempVector.data() + (mWidth * mHeight * 4)); + mDataRGBA.insert(mDataRGBA.begin(), tempVector.data(), + tempVector.data() + (mWidth * mHeight * 4)); ImageIO::flipPixelsVert(mDataRGBA.data(), mWidth, mHeight); @@ -120,12 +120,13 @@ bool TextureData::initImageFromMemory(const unsigned char* fileData, size_t leng } std::vector imageRGBA = ImageIO::loadFromMemoryRGBA32( - static_cast(fileData), length, width, height); + static_cast(fileData), length, width, height); if (imageRGBA.size() == 0) { - LOG(LogError) << "Couldn't initialize texture from memory, invalid data (" << - (mPath != "" ? "file path: \"" + mPath + "\", " : "") << "data ptr: " << - reinterpret_cast(fileData) << ", reported size: " << length << ")"; + LOG(LogError) << "Couldn't initialize texture from memory, invalid data (" + << (mPath != "" ? "file path: \"" + mPath + "\", " : "") + << "data ptr: " << reinterpret_cast(fileData) + << ", reported size: " << length << ")"; return false; } @@ -167,8 +168,8 @@ bool TextureData::load() retval = initSVGFromMemory(dataString); } else { - retval = initImageFromMemory(static_cast(data.ptr.get()), - data.length); + retval = + initImageFromMemory(static_cast(data.ptr.get()), data.length); } } return retval; @@ -196,9 +197,9 @@ bool TextureData::uploadAndBind() return false; // Upload texture. - mTextureID = Renderer::createTexture(Renderer::Texture::RGBA, true, mTile, - static_cast(mWidth), static_cast(mHeight), - mDataRGBA.data()); + mTextureID = Renderer::createTexture( + Renderer::Texture::RGBA, true, mTile, static_cast(mWidth), + static_cast(mHeight), mDataRGBA.data()); } return true; } diff --git a/es-core/src/resources/TextureData.h b/es-core/src/resources/TextureData.h index 8a65c0b18..d038f0123 100644 --- a/es-core/src/resources/TextureData.h +++ b/es-core/src/resources/TextureData.h @@ -24,7 +24,7 @@ public: // These functions populate mDataRGBA but do not upload the texture to VRAM. - //!!!! Needs to be canonical path. Caller should check for duplicates before calling this. + // Needs to be canonical path. Caller should check for duplicates before calling this. void initFromPath(const std::string& path); bool initSVGFromMemory(const std::string& fileData); bool initImageFromMemory(const unsigned char* fileData, size_t length); diff --git a/es-core/src/resources/TextureDataManager.cpp b/es-core/src/resources/TextureDataManager.cpp index 3f4e79fcf..b4a64de2a 100644 --- a/es-core/src/resources/TextureDataManager.cpp +++ b/es-core/src/resources/TextureDataManager.cpp @@ -8,20 +8,20 @@ #include "resources/TextureDataManager.h" -#include "resources/TextureData.h" -#include "resources/TextureResource.h" #include "Log.h" #include "Settings.h" +#include "resources/TextureData.h" +#include "resources/TextureResource.h" TextureDataManager::TextureDataManager() { unsigned char data[5 * 5 * 4]; mBlank = std::shared_ptr(new TextureData(false)); for (int i = 0; i < (5 * 5); i++) { - data[i*4] = (i % 2) * 255; - data[i*4+1] = (i % 2) * 255; - data[i*4+2] = (i % 2) * 255; - data[i*4+3] = 0; + data[i * 4] = (i % 2) * 255; + data[i * 4 + 1] = (i % 2) * 255; + data[i * 4 + 2] = (i % 2) * 255; + data[i * 4 + 3] = 0; } mBlank->initFromRGBA(data, 5, 5); mLoader = new TextureLoader; @@ -29,6 +29,7 @@ TextureDataManager::TextureDataManager() TextureDataManager::~TextureDataManager() { + // Delete TextureLoader object when destroyed. delete mLoader; } @@ -103,6 +104,7 @@ size_t TextureDataManager::getCommittedSize() size_t TextureDataManager::getQueueSize() { + // Return queue size. return mLoader->getQueueSize(); } @@ -116,14 +118,14 @@ void TextureDataManager::load(std::shared_ptr tex, bool block) size_t settingVRAM = static_cast(Settings::getInstance()->getInt("MaxVRAM")); if (settingVRAM < 80) { - LOG(LogWarning) << "MaxVRAM is too low at " << settingVRAM << - " MiB, setting it to the minimum allowed value of 80 MiB"; + LOG(LogWarning) << "MaxVRAM is too low at " << settingVRAM + << " MiB, setting it to the minimum allowed value of 80 MiB"; Settings::getInstance()->setInt("MaxVRAM", 80); settingVRAM = 80; } else if (settingVRAM > 1024) { - LOG(LogWarning) << "MaxVRAM is too high at " << settingVRAM << - " MiB, setting it to the maximum allowed value of 1024 MiB"; + LOG(LogWarning) << "MaxVRAM is too high at " << settingVRAM + << " MiB, setting it to the maximum allowed value of 1024 MiB"; Settings::getInstance()->setInt("MaxVRAM", 1024); settingVRAM = 1024; } @@ -133,7 +135,6 @@ void TextureDataManager::load(std::shared_ptr tex, bool block) for (auto it = mTextures.crbegin(); it != mTextures.crend(); it++) { if (size < max_texture) break; - //size -= (*it)->getVRAMUsage(); (*it)->releaseVRAM(); (*it)->releaseRAM(); // It may be already in the loader queue. In this case it wouldn't have been using @@ -141,13 +142,15 @@ void TextureDataManager::load(std::shared_ptr tex, bool block) mLoader->remove(*it); size = TextureResource::getTotalMemUsage(); } + if (!block) mLoader->load(tex); else tex->load(); } -TextureLoader::TextureLoader() : mExit(false) +TextureLoader::TextureLoader() + : mExit(false) { mThread = std::make_unique(&TextureLoader::threadProc, this); } diff --git a/es-core/src/resources/TextureDataManager.h b/es-core/src/resources/TextureDataManager.h index 84890cc41..1989e1915 100644 --- a/es-core/src/resources/TextureDataManager.h +++ b/es-core/src/resources/TextureDataManager.h @@ -35,8 +35,8 @@ private: void threadProc(); std::list> mTextureDataQ; - std::map>::const_iterator> mTextureDataLookup; + std::map>::const_iterator> + mTextureDataLookup; std::unique_ptr mThread; std::mutex mMutex; @@ -75,19 +75,19 @@ public: bool bind(const TextureResource* key); // Get the total size of all textures managed by this object, loaded and unloaded in bytes. - size_t getTotalSize(); + size_t getTotalSize(); // Get the total size of all committed textures (in VRAM) in bytes. - size_t getCommittedSize(); + size_t getCommittedSize(); // Get the total size of all load-pending textures in the queue - these will // be committed to VRAM as the queue is processed. - size_t getQueueSize(); + size_t getQueueSize(); // Load a texture, freeing resources as necessary to make space. void load(std::shared_ptr tex, bool block = false); private: std::list> mTextures; - std::map>::const_iterator> mTextureLookup; + std::map>::const_iterator> + mTextureLookup; std::shared_ptr mBlank; TextureLoader* mLoader; }; diff --git a/es-core/src/resources/TextureResource.cpp b/es-core/src/resources/TextureResource.cpp index 5aef84b3f..268a98e52 100644 --- a/es-core/src/resources/TextureResource.cpp +++ b/es-core/src/resources/TextureResource.cpp @@ -8,21 +8,20 @@ #include "resources/TextureResource.h" -#include "utils/FileSystemUtil.h" #include "resources/TextureData.h" +#include "utils/FileSystemUtil.h" TextureDataManager TextureResource::sTextureDataManager; -std::map< TextureResource::TextureKeyType, - std::weak_ptr> TextureResource::sTextureMap; +std::map> + TextureResource::sTextureMap; std::set TextureResource::sAllTextures; -TextureResource::TextureResource( - const std::string& path, - bool tile, - bool dynamic, - float scaleDuringLoad) - : mTextureData(nullptr), - mForceLoad(false) +TextureResource::TextureResource(const std::string& path, + bool tile, + bool dynamic, + float scaleDuringLoad) + : mTextureData(nullptr) + , mForceLoad(false) { // Create a texture data object for this texture. if (!path.empty()) { @@ -88,8 +87,8 @@ void TextureResource::initFromMemory(const char* data, size_t length) mTextureData->releaseRAM(); mTextureData->initImageFromMemory(reinterpret_cast(data), length); // Get the size from the texture data. - mSize = Vector2i(static_cast(mTextureData->width()), - static_cast(mTextureData->height())); + mSize = + Vector2i(static_cast(mTextureData->width()), static_cast(mTextureData->height())); mSourceSize = Vector2f(mTextureData->sourceWidth(), mTextureData->sourceHeight()); } @@ -125,11 +124,6 @@ std::string TextureResource::getTextureFilePath() return ""; } -const Vector2i TextureResource::getSize() const -{ - return mSize; -} - bool TextureResource::isTiled() const { if (mTextureData != nullptr) @@ -150,11 +144,7 @@ bool TextureResource::bind() } std::shared_ptr TextureResource::get( - const std::string& path, - bool tile, - bool forceLoad, - bool dynamic, - float scaleDuringLoad) + const std::string& path, bool tile, bool forceLoad, bool dynamic, float scaleDuringLoad) { std::shared_ptr& rm = ResourceManager::getInstance(); @@ -177,7 +167,7 @@ std::shared_ptr TextureResource::get( // Need to create it. std::shared_ptr tex; tex = std::shared_ptr( - new TextureResource(key.first, tile, dynamic, scaleDuringLoad)); + new TextureResource(key.first, tile, dynamic, scaleDuringLoad)); std::shared_ptr data = sTextureDataManager.get(tex.get()); // Is it an SVG? @@ -213,16 +203,6 @@ void TextureResource::rasterizeAt(size_t width, size_t height) data->load(); } -Vector2f TextureResource::getSourceImageSize() const -{ - return mSourceSize; -} - -bool TextureResource::isInitialized() const -{ - return true; -} - size_t TextureResource::getTotalMemUsage() { size_t total = 0; diff --git a/es-core/src/resources/TextureResource.h b/es-core/src/resources/TextureResource.h index 380be1787..ef0eae958 100644 --- a/es-core/src/resources/TextureResource.h +++ b/es-core/src/resources/TextureResource.h @@ -26,12 +26,11 @@ class TextureData; class TextureResource : public IReloadable { public: - static std::shared_ptr get( - const std::string& path, - bool tile = false, - bool forceLoad = false, - bool dynamic = true, - float scaleDuringLoad = 1.0f); + static std::shared_ptr get(const std::string& path, + bool tile = false, + bool forceLoad = false, + bool dynamic = true, + float scaleDuringLoad = 1.0f); void initFromPixels(const unsigned char* dataRGBA, size_t width, size_t height); virtual void initFromMemory(const char* data, size_t length); static void manualUnload(std::string path, bool tile); @@ -46,14 +45,14 @@ public: // situations. An alternative is to set a scaling factor directly when loading the texture // using get(), by using the scaleDuringLoad parameter (which also works for raster graphics). void rasterizeAt(size_t width, size_t height); - Vector2f getSourceImageSize() const; + Vector2f getSourceImageSize() const { return mSourceSize; } virtual ~TextureResource(); - bool isInitialized() const; + bool isInitialized() const { return true; } bool isTiled() const; - const Vector2i getSize() const; + const Vector2i getSize() const { return mSize; } bool bind(); // Returns an approximation of total VRAM used by textures (in bytes). diff --git a/es-core/src/utils/CImgUtil.cpp b/es-core/src/utils/CImgUtil.cpp index e873a2077..4b23b9027 100644 --- a/es-core/src/utils/CImgUtil.cpp +++ b/es-core/src/utils/CImgUtil.cpp @@ -13,7 +13,7 @@ namespace Utils namespace CImg { void convertRGBAToCImg(std::vector imageRGBA, - cimg_library::CImg& image) + cimg_library::CImg& image) { // CImg does not interleave the pixels as in RGBARGBARGBA so a conversion is required. int counter = 0; @@ -29,20 +29,20 @@ namespace Utils } void convertCImgToRGBA(cimg_library::CImg image, - std::vector& imageRGBA) + std::vector& imageRGBA) { for (int r = image.height() - 1; r >= 0; r--) { for (int c = 0; c < image.width(); c++) { - imageRGBA.push_back((unsigned char)image(c,r,0,2)); - imageRGBA.push_back((unsigned char)image(c,r,0,1)); - imageRGBA.push_back((unsigned char)image(c,r,0,0)); - imageRGBA.push_back((unsigned char)image(c,r,0,3)); + imageRGBA.push_back((unsigned char)image(c, r, 0, 2)); + imageRGBA.push_back((unsigned char)image(c, r, 0, 1)); + imageRGBA.push_back((unsigned char)image(c, r, 0, 0)); + imageRGBA.push_back((unsigned char)image(c, r, 0, 3)); } } } void getTransparentPaddingCoords(cimg_library::CImg& image, - int (&imageCoords)[4]) + int (&imageCoords)[4]) { // Check that the image actually has an alpha channel. if (image.spectrum() != 4) @@ -147,8 +147,7 @@ namespace Utils } if (rowCounterTop > 0) - image.crop(0, 0, 0, 3, image.width() - 1, image.height() - 1 - - rowCounterTop, 0, 0); + image.crop(0, 0, 0, 3, image.width() - 1, image.height() - 1 - rowCounterTop, 0, 0); if (rowCounterBottom > 0) image.crop(0, rowCounterBottom, 0, 3, image.width() - 1, image.height() - 1, 0, 0); @@ -157,8 +156,8 @@ namespace Utils image.crop(columnCounterLeft, 0, 0, 3, image.width() - 1, image.height() - 1, 0, 0); if (columnCounterRight > 0) - image.crop(0, 0, 0, 3, image.width() - columnCounterRight - 1, - image.height() - 1, 0, 0); + image.crop(0, 0, 0, 3, image.width() - columnCounterRight - 1, image.height() - 1, + 0, 0); } void cropLetterboxes(cimg_library::CImg& image) @@ -190,8 +189,8 @@ namespace Utils } if (rowCounterUpper > 0) - image.crop(0, 0, 0, 3, image.width() - 1, image.height() - 1 - - rowCounterUpper, 0, 0); + image.crop(0, 0, 0, 3, image.width() - 1, image.height() - 1 - rowCounterUpper, 0, + 0); if (rowCounterLower > 0) image.crop(0, rowCounterLower, 0, 3, image.width() - 1, image.height() - 1, 0, 0); @@ -229,20 +228,23 @@ namespace Utils image.crop(columnCounterLeft, 0, 0, 3, image.width() - 1, image.height() - 1, 0, 0); if (columnCounterRight > 0) - image.crop(0, 0, 0, 3, image.width() - columnCounterRight - 1, - image.height() - 1, 0, 0); + image.crop(0, 0, 0, 3, image.width() - columnCounterRight - 1, image.height() - 1, + 0, 0); } - void addDropShadow(cimg_library::CImg& image, unsigned int shadowDistance, - float transparency, unsigned int iterations) + void addDropShadow(cimg_library::CImg& image, + unsigned int shadowDistance, + float transparency, + unsigned int iterations) { // Check that the image actually has an alpha channel. if (image.spectrum() != 4) return; - // Make the shadow image larger than the source image to leave space for the drop shadow. - cimg_library::CImg shadowImage(image.width() + shadowDistance * 3, - image.height() + shadowDistance * 3, 1, 4, 0); + // Make the shadow image larger than the source image to leave space for the + // drop shadow. + cimg_library::CImg shadowImage( + image.width() + shadowDistance * 3, image.height() + shadowDistance * 3, 1, 4, 0); // Create a mask image. cimg_library::CImg maskImage(image.width(), image.height(), 1, 4, 0); @@ -256,20 +258,20 @@ namespace Utils // Lower the transparency and apply the blur. shadowImage.get_shared_channel(3) /= transparency; shadowImage.blur_box(static_cast(shadowDistance), - static_cast(shadowDistance), 1, true, iterations); + static_cast(shadowDistance), 1, true, iterations); // Add the mask to the alpha channel of the shadow image. shadowImage.get_shared_channel(3).draw_image(0, 0, maskImage.get_shared_channels(0, 0), - maskImage.get_shared_channel(3), 1, 255); + maskImage.get_shared_channel(3), 1, 255); // Draw the source image on top of the shadow image. shadowImage.draw_image(0, 0, image.get_shared_channels(0, 2), - image.get_shared_channel(3), 1, 255); + image.get_shared_channel(3), 1, 255); // Remove the any unused space that we added to leave room for the shadow. removeTransparentPadding(shadowImage); image = shadowImage; } - } // CImg:: + } // namespace CImg -} // Utils:: +} // namespace Utils diff --git a/es-core/src/utils/CImgUtil.h b/es-core/src/utils/CImgUtil.h index e611911b4..66e177d1d 100644 --- a/es-core/src/utils/CImgUtil.h +++ b/es-core/src/utils/CImgUtil.h @@ -20,17 +20,20 @@ namespace Utils namespace CImg { void convertRGBAToCImg(std::vector imageRGBA, - cimg_library::CImg& image); + cimg_library::CImg& image); void convertCImgToRGBA(cimg_library::CImg image, - std::vector& imageRGBA); + std::vector& imageRGBA); void getTransparentPaddingCoords(cimg_library::CImg& image, - int (&imageCoords)[4]); + int (&imageCoords)[4]); void removeTransparentPadding(cimg_library::CImg& image); void cropLetterboxes(cimg_library::CImg& image); void cropPillarboxes(cimg_library::CImg& image); - void addDropShadow(cimg_library::CImg& image, unsigned int shadowDistance, - float transparency, unsigned int iterations); - } -} + void addDropShadow(cimg_library::CImg& image, + unsigned int shadowDistance, + float transparency, + unsigned int iterations); + } // namespace CImg + +} // namespace Utils #endif // ES_CORE_UTILS_CIMG_UTIL_H diff --git a/es-core/src/utils/FileSystemUtil.cpp b/es-core/src/utils/FileSystemUtil.cpp index 91b3ad710..1e6075d62 100644 --- a/es-core/src/utils/FileSystemUtil.cpp +++ b/es-core/src/utils/FileSystemUtil.cpp @@ -16,20 +16,20 @@ #include "utils/FileSystemUtil.h" -#include "utils/StringUtil.h" #include "Log.h" +#include "utils/StringUtil.h" -#include #include #include +#include #if defined(_WIN64) -#include #include +#include #if defined(_MSC_VER) // MSVC compiler. #define stat64 _stat64 -#define S_ISREG(x) (((x) & S_IFMT) == S_IFREG) -#define S_ISDIR(x) (((x) & S_IFMT) == S_IFDIR) +#define S_ISREG(x) (((x)&S_IFMT) == S_IFREG) +#define S_ISDIR(x) (((x)&S_IFMT) == S_IFDIR) #endif #else #include @@ -69,7 +69,7 @@ namespace Utils // Only parse the directory, if it's a directory. if (isDirectory(genericPath)) { - #if defined(_WIN64) +#if defined(_WIN64) WIN32_FIND_DATAW findData; std::wstring wildcard = Utils::String::stringToWideString(genericPath) + L"/*"; HANDLE hFind = FindFirstFileW(wildcard.c_str(), &findData); @@ -88,11 +88,10 @@ namespace Utils contentList.merge(getDirContent(fullName, true)); } } - } - while (FindNextFileW(hFind, &findData)); + } while (FindNextFileW(hFind, &findData)); FindClose(hFind); } - #else +#else DIR* dir = opendir(genericPath.c_str()); if (dir != nullptr) { @@ -114,7 +113,7 @@ namespace Utils } closedir(dir); } - #endif +#endif } contentList.sort(); return contentList; @@ -142,6 +141,7 @@ namespace Utils void setHomePath(const std::string& path) { + // Set home path. homePath = getGenericPath(path); } @@ -151,33 +151,33 @@ namespace Utils if (homePath.length()) return homePath; - #if defined(_WIN64) +#if defined(_WIN64) // On Windows we need to check HOMEDRIVE and HOMEPATH. if (!homePath.length()) { std::wstring envHomeDrive; std::wstring envHomePath; - #if defined(_MSC_VER) // MSVC compiler. +#if defined(_MSC_VER) // MSVC compiler. wchar_t* buffer; if (!_wdupenv_s(&buffer, nullptr, L"HOMEDRIVE")) envHomeDrive = buffer; if (!_wdupenv_s(&buffer, nullptr, L"HOMEPATH")) envHomePath = buffer; - #else +#else envHomeDrive = _wgetenv(L"HOMEDRIVE"); envHomePath = _wgetenv(L"HOMEPATH"); - #endif +#endif if (envHomeDrive.length() && envHomePath.length()) homePath = getGenericPath(Utils::String::wideStringToString(envHomeDrive) + - "/" + Utils::String::wideStringToString(envHomePath)); + "/" + Utils::String::wideStringToString(envHomePath)); } - #else +#else if (!homePath.length()) { std::string envHome = getenv("HOME"); if (envHome.length()) homePath = getGenericPath(envHome); } - #endif +#endif // No homepath found, fall back to current working directory. if (!homePath.length()) @@ -189,24 +189,26 @@ namespace Utils std::string getCWDPath() { // Return current working directory. - #if defined(_WIN64) + +#if defined(_WIN64) wchar_t tempWide[512]; return (_wgetcwd(tempWide, 512) ? - getGenericPath(Utils::String::wideStringToString(tempWide)) : ""); - #else + getGenericPath(Utils::String::wideStringToString(tempWide)) : + ""); +#else char temp[512]; return (getcwd(temp, 512) ? getGenericPath(temp) : ""); - #endif +#endif } std::string getPathToBinary(const std::string& executable) { - #if defined(_WIN64) +#if defined(_WIN64) return ""; - #else +#else std::string pathVariable = std::string(getenv("PATH")); std::vector pathList = - Utils::String::delimitedStringToVector(pathVariable, ":"); + Utils::String::delimitedStringToVector(pathVariable, ":"); std::string pathTest; @@ -216,21 +218,21 @@ namespace Utils return it->c_str(); } return ""; - #endif +#endif } void setExePath(const std::string& path) { constexpr int pathMax = 32767; - #if defined(_WIN64) +#if defined(_WIN64) std::wstring result(pathMax, 0); if (GetModuleFileNameW(nullptr, &result[0], pathMax) != 0) exePath = Utils::String::wideStringToString(result); - #else +#else std::string result(pathMax, 0); if (readlink("/proc/self/exe", &result[0], pathMax) != -1) exePath = result; - #endif +#endif exePath = getCanonicalPath(exePath); // Fallback to argv[0] if everything else fails. @@ -242,27 +244,28 @@ namespace Utils std::string getExePath() { + // Return executable path. return exePath; } std::string getProgramDataPath() { - #if defined(__unix__) +#if defined(__unix__) return installPrefix + "/share/emulationstation"; - #else +#else return ""; - #endif +#endif } std::string getPreferredPath(const std::string& path) { std::string preferredPath = path; size_t offset = std::string::npos; - #if defined(_WIN64) +#if defined(_WIN64) // Convert '/' to '\\' while ((offset = preferredPath.find('/')) != std::string::npos) preferredPath.replace(offset, 1, "\\"); - #endif +#endif return preferredPath; } @@ -277,15 +280,15 @@ namespace Utils // Convert '\\' to '/' while ((offset = genericPath.find('\\')) != std::string::npos) - genericPath.replace(offset, 1 ,"/"); + genericPath.replace(offset, 1, "/"); // Remove double '/' while ((offset = genericPath.find("//")) != std::string::npos) genericPath.erase(offset, 1); // Remove trailing '/' when the path is more than a simple '/' - while (genericPath.length() > 1 && ((offset = genericPath.find_last_of('/')) == - (genericPath.length() - 1))) + while (genericPath.length() > 1 && + ((offset = genericPath.find_last_of('/')) == (genericPath.length() - 1))) genericPath.erase(offset, 1); return genericPath; @@ -295,10 +298,10 @@ namespace Utils { std::string escapedPath = getGenericPath(path); - #if defined(_WIN64) +#if defined(_WIN64) // Windows escapes stuff by just putting everything in quotes. return '"' + getPreferredPath(escapedPath) + '"'; - #else +#else // Insert a backslash before most characters that would mess up a bash path. const char* invalidChars = "\\ '\"!$^&*(){}[]?;<>"; const char* invalidChar = invalidChars; @@ -318,7 +321,7 @@ namespace Utils invalidChar++; } return escapedPath; - #endif +#endif } std::string getCanonicalPath(const std::string& path) @@ -337,8 +340,8 @@ namespace Utils canonicalPath.clear(); scan = false; - for (stringList::const_iterator it = pathList.cbegin(); - it != pathList.cend(); it++) { + for (stringList::const_iterator it = pathList.cbegin(); it != pathList.cend(); + it++) { // Ignore empty. if ((*it).empty()) continue; @@ -353,13 +356,13 @@ namespace Utils continue; } - #if defined(_WIN64) +#if defined(_WIN64) // Append folder to path. canonicalPath += (canonicalPath.size() == 0) ? (*it) : ("/" + (*it)); - #else +#else // Append folder to path. canonicalPath += ("/" + (*it)); - #endif +#endif if (isSymlink(canonicalPath)) { std::string resolved = resolveSymlink(canonicalPath); @@ -389,8 +392,7 @@ namespace Utils std::string baseVar = isAbsolute(base) ? getGenericPath(base) : getAbsolutePath(base); return isAbsolute(absolutePath) ? absolutePath : - getGenericPath(baseVar + "/" + absolutePath); - + getGenericPath(baseVar + "/" + absolutePath); } std::string getParent(const std::string& path) @@ -414,7 +416,7 @@ namespace Utils // Find last '/' and return the filename. if ((offset = genericPath.find_last_of('/')) != std::string::npos) return ((genericPath[offset + 1] == 0) ? "." : - std::string(genericPath, offset + 1)); + std::string(genericPath, offset + 1)); // No '/' found, entire path is a filename. return genericPath; @@ -466,11 +468,12 @@ namespace Utils } std::string resolveRelativePath(const std::string& path, - const std::string& relativeTo, const bool allowHome) + const std::string& relativeTo, + const bool allowHome) { std::string genericPath = getGenericPath(path); - std::string relativeToVar = isDirectory(relativeTo) ? - getGenericPath(relativeTo) : getParent(relativeTo); + std::string relativeToVar = + isDirectory(relativeTo) ? getGenericPath(relativeTo) : getParent(relativeTo); // Nothing to resolve. if (!genericPath.length()) @@ -489,7 +492,8 @@ namespace Utils } std::string createRelativePath(const std::string& path, - const std::string& relativeTo, const bool allowHome) + const std::string& relativeTo, + const bool allowHome) { bool contains = false; std::string relativePath = removeCommonPath(path, relativeTo, contains); @@ -507,11 +511,12 @@ namespace Utils } std::string removeCommonPath(const std::string& path, - const std::string& commonArg, bool& contains) + const std::string& commonArg, + bool& contains) { std::string genericPath = getGenericPath(path); - std::string common = isDirectory(commonArg) ? - getGenericPath(commonArg) : getParent(commonArg); + std::string common = + isDirectory(commonArg) ? getGenericPath(commonArg) : getParent(commonArg); if (genericPath.find(common) == 0) { contains = true; @@ -527,37 +532,39 @@ namespace Utils std::string genericPath = getGenericPath(path); std::string resolved; - #if defined(_WIN64) +#if defined(_WIN64) std::wstring resolvedW; HANDLE hFile = CreateFileW(Utils::String::stringToWideString(genericPath).c_str(), - FILE_READ_ATTRIBUTES, FILE_SHARE_READ, 0, - OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, 0); + FILE_READ_ATTRIBUTES, FILE_SHARE_READ, 0, OPEN_EXISTING, + FILE_FLAG_BACKUP_SEMANTICS, 0); if (hFile != INVALID_HANDLE_VALUE) { - resolvedW.resize(GetFinalPathNameByHandleW(hFile, nullptr, 0, - FILE_NAME_NORMALIZED) + 1); - if (GetFinalPathNameByHandleW(hFile, const_cast(resolvedW.data()), - static_cast(resolvedW.size()), FILE_NAME_NORMALIZED) > 0) { + resolvedW.resize( + GetFinalPathNameByHandleW(hFile, nullptr, 0, FILE_NAME_NORMALIZED) + 1); + if (GetFinalPathNameByHandleW(hFile, const_cast(resolvedW.data()), + static_cast(resolvedW.size()), + FILE_NAME_NORMALIZED) > 0) { resolvedW.resize(resolvedW.size() - 1); resolved = getGenericPath(Utils::String::wideStringToString(resolvedW)); } CloseHandle(hFile); } - #else +#else struct stat info; // Check if lstat succeeded. if (lstat(genericPath.c_str(), &info) == 0) { resolved.resize(info.st_size); if (readlink(genericPath.c_str(), const_cast(resolved.data()), - resolved.size()) > 0) + resolved.size()) > 0) resolved = getGenericPath(resolved); } - #endif +#endif return resolved; } bool copyFile(const std::string& sourcePath, - const std::string& destinationPath, bool overwrite) + const std::string& destinationPath, + bool overwrite) { if (!exists(sourcePath)) { LOG(LogError) << "Can't copy file, source file does not exist:"; @@ -573,34 +580,34 @@ namespace Utils if (!overwrite && exists(destinationPath)) { LOG(LogError) << "Destination file exists and the overwrite flag " - "has not been set"; + "has not been set"; return true; } - #if defined(_WIN64) - std::ifstream sourceFile( - Utils::String::stringToWideString(sourcePath).c_str(), std::ios::binary); - #else +#if defined(_WIN64) + std::ifstream sourceFile(Utils::String::stringToWideString(sourcePath).c_str(), + std::ios::binary); +#else std::ifstream sourceFile(sourcePath, std::ios::binary); - #endif +#endif if (sourceFile.fail()) { - LOG(LogError) << "Couldn't read from source file \"" << sourcePath << - "\", permission problems?"; + LOG(LogError) << "Couldn't read from source file \"" << sourcePath + << "\", permission problems?"; sourceFile.close(); return true; } - #if defined(_WIN64) - std::ofstream targetFile( - Utils::String::stringToWideString(destinationPath).c_str(), std::ios::binary); - #else +#if defined(_WIN64) + std::ofstream targetFile(Utils::String::stringToWideString(destinationPath).c_str(), + std::ios::binary); +#else std::ofstream targetFile(destinationPath, std::ios::binary); - #endif +#endif if (targetFile.fail()) { - LOG(LogError) << "Couldn't write to target file \"" << destinationPath << - "\", permission problems?"; + LOG(LogError) << "Couldn't write to target file \"" << destinationPath + << "\", permission problems?"; targetFile.close(); return true; } @@ -614,7 +621,8 @@ namespace Utils } bool renameFile(const std::string& sourcePath, - const std::string& destinationPath, bool overwrite) + const std::string& destinationPath, + bool overwrite) { // Don't print any error message for a missing source file as Log will use this // function when initializing the logging. It would always generate an error in @@ -630,17 +638,16 @@ namespace Utils } if (!overwrite && exists(destinationPath)) { - LOG(LogError) << "Destination file exists and the overwrite flag " - "has not been set"; + LOG(LogError) << "Destination file exists and the overwrite flag has not been set"; return true; } - #if defined(_WIN64) +#if defined(_WIN64) _wrename(Utils::String::stringToWideString(sourcePath).c_str(), - Utils::String::stringToWideString(destinationPath).c_str()); - #else + Utils::String::stringToWideString(destinationPath).c_str()); +#else std::rename(sourcePath.c_str(), destinationPath.c_str()); - #endif +#endif return false; } @@ -653,7 +660,7 @@ namespace Utils if (!exists(genericPath)) return true; - #if defined(_WIN64) +#if defined(_WIN64) if (_wunlink(Utils::String::stringToWideString(genericPath).c_str()) != 0) { LOG(LogError) << "Couldn't delete file, permission problems?"; LOG(LogError) << genericPath; @@ -662,7 +669,7 @@ namespace Utils else { return false; } - #else +#else if (unlink(genericPath.c_str()) != 0) { LOG(LogError) << "Couldn't delete file, permission problems?"; LOG(LogError) << genericPath; @@ -672,7 +679,7 @@ namespace Utils return false; } return (unlink(genericPath.c_str()) == 0); - #endif +#endif } bool removeDirectory(const std::string& path) @@ -687,17 +694,17 @@ namespace Utils LOG(LogError) << path; return false; } - #if defined(_WIN64) +#if defined(_WIN64) if (_wrmdir(Utils::String::stringToWideString(path).c_str()) != 0) { - #else +#else if (rmdir(path.c_str()) != 0) { - #endif +#endif LOG(LogError) << "Couldn't delete directory, permission problems?"; LOG(LogError) << path; return false; } return true; - } + } // namespace FileSystem bool createDirectory(const std::string& path) { @@ -706,13 +713,13 @@ namespace Utils if (exists(genericPath)) return true; - #if defined(_WIN64) +#if defined(_WIN64) if (_wmkdir(Utils::String::stringToWideString(genericPath).c_str()) == 0) return true; - #else +#else if (mkdir(genericPath.c_str(), 0755) == 0) return true; - #endif +#endif // Failed to create directory, try to create the parent. std::string parent = getParent(genericPath); @@ -721,33 +728,34 @@ namespace Utils if (parent != genericPath) createDirectory(parent); - // Try to create directory again now that the parent should exist. - #if defined(_WIN64) + // Try to create directory again now that the parent should exist. + +#if defined(_WIN64) return (_wmkdir(Utils::String::stringToWideString(genericPath).c_str()) == 0); - #else +#else return (mkdir(genericPath.c_str(), 0755) == 0); - #endif +#endif } bool exists(const std::string& path) { std::string genericPath = getGenericPath(path); - #if defined(__APPLE__) || defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) +#if defined(__APPLE__) || defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) struct stat info; return (stat(genericPath.c_str(), &info) == 0); - #elif defined(_WIN64) +#elif defined(_WIN64) struct _stat64 info; return (_wstat64(Utils::String::stringToWideString(genericPath).c_str(), &info) == 0); - #else - struct stat64 info; - return (stat64(genericPath.c_str(), &info) == 0); - #endif +#else + struct stat64 info; + return (stat64(genericPath.c_str(), &info) == 0); +#endif } bool driveExists(const std::string& path) { - #if defined(_WIN64) +#if defined(_WIN64) std::string genericPath = getGenericPath(path); // Try to add a dot or a backslash and a dot depending on how the drive // letter was defined by the user. @@ -759,39 +767,39 @@ namespace Utils struct _stat64 info; return (_wstat64(Utils::String::stringToWideString(genericPath).c_str(), &info) == 0); - #else +#else return false; - #endif +#endif } bool isAbsolute(const std::string& path) { std::string genericPath = getGenericPath(path); - #if defined(_WIN64) +#if defined(_WIN64) return ((genericPath.size() > 1) && (genericPath[1] == ':')); - #else +#else return ((genericPath.size() > 0) && (genericPath[0] == '/')); - #endif +#endif } bool isRegularFile(const std::string& path) { std::string genericPath = getGenericPath(path); - #if defined(__APPLE__) || defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) +#if defined(__APPLE__) || defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) struct stat info; if (stat(genericPath.c_str(), &info) != 0) return false; - #elif defined(_WIN64) +#elif defined(_WIN64) struct stat64 info; if (_wstat64(Utils::String::stringToWideString(genericPath).c_str(), &info) != 0) return false; - #else - struct stat64 info; - if (stat64(genericPath.c_str(), &info) != 0) - return false; - #endif +#else + struct stat64 info; + if (stat64(genericPath.c_str(), &info) != 0) + return false; +#endif // Check for S_IFREG attribute. return (S_ISREG(info.st_mode)); @@ -801,19 +809,19 @@ namespace Utils { std::string genericPath = getGenericPath(path); - #if defined(__APPLE__) || defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) +#if defined(__APPLE__) || defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) struct stat info; if (stat(genericPath.c_str(), &info) != 0) return false; - #elif defined(_WIN64) +#elif defined(_WIN64) struct stat64 info; if (_wstat64(Utils::String::stringToWideString(genericPath).c_str(), &info) != 0) return false; - #else - struct stat64 info; - if (stat64(genericPath.c_str(), &info) != 0) - return false; - #endif +#else + struct stat64 info; + if (stat64(genericPath.c_str(), &info) != 0) + return false; +#endif // Check for S_IFDIR attribute. return (S_ISDIR(info.st_mode)); @@ -823,30 +831,30 @@ namespace Utils { std::string genericPath = getGenericPath(path); - #if defined(_WIN64) +#if defined(_WIN64) // Check for symlink attribute. const DWORD Attributes = - GetFileAttributesW(Utils::String::stringToWideString(genericPath).c_str()); + GetFileAttributesW(Utils::String::stringToWideString(genericPath).c_str()); if ((Attributes != INVALID_FILE_ATTRIBUTES) && - (Attributes & FILE_ATTRIBUTE_REPARSE_POINT)) + (Attributes & FILE_ATTRIBUTE_REPARSE_POINT)) return true; - #else +#else - #if defined(__APPLE__) || defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) +#if defined(__APPLE__) || defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) struct stat info; if (lstat(genericPath.c_str(), &info) != 0) return false; - #else +#else struct stat64 info; if (lstat64(genericPath.c_str(), &info) != 0) return false; - #endif +#endif // Check for S_IFLNK attribute. return (S_ISLNK(info.st_mode)); - #endif +#endif // Not a symlink. return false; @@ -856,13 +864,13 @@ namespace Utils { std::string genericPath = getGenericPath(path); - #if defined(_WIN64) +#if defined(_WIN64) // Check for hidden attribute. const DWORD Attributes = - GetFileAttributesW(Utils::String::stringToWideString(genericPath).c_str()); + GetFileAttributesW(Utils::String::stringToWideString(genericPath).c_str()); if ((Attributes != INVALID_FILE_ATTRIBUTES) && (Attributes & FILE_ATTRIBUTE_HIDDEN)) return true; - #endif +#endif // Filenames starting with . are hidden in Linux, but // we do this check for windows as well. @@ -872,6 +880,6 @@ namespace Utils return false; } - } // FileSystem:: + } // namespace FileSystem -} // Utils:: +} // namespace Utils diff --git a/es-core/src/utils/FileSystemUtil.h b/es-core/src/utils/FileSystemUtil.h index 95ef4c31b..b8f07e31f 100644 --- a/es-core/src/utils/FileSystemUtil.h +++ b/es-core/src/utils/FileSystemUtil.h @@ -34,23 +34,28 @@ namespace Utils std::string getEscapedPath(const std::string& path); std::string getCanonicalPath(const std::string& path); std::string getAbsolutePath(const std::string& path, - const std::string& base = getCWDPath()); + const std::string& base = getCWDPath()); std::string getParent(const std::string& path); std::string getFileName(const std::string& path); std::string getStem(const std::string& path); std::string getExtension(const std::string& path); std::string expandHomePath(const std::string& path); std::string resolveRelativePath(const std::string& path, - const std::string& relativeTo, const bool allowHome); + const std::string& relativeTo, + const bool allowHome); std::string createRelativePath(const std::string& path, - const std::string& relativeTo, const bool allowHome); + const std::string& relativeTo, + const bool allowHome); std::string removeCommonPath(const std::string& path, - const std::string& commonArg, bool& contains); + const std::string& commonArg, + bool& contains); std::string resolveSymlink(const std::string& path); bool copyFile(const std::string& sourcePath, - const std::string& destinationPath, bool overwrite); + const std::string& destinationPath, + bool overwrite); bool renameFile(const std::string& sourcePath, - const std::string& destinationPath, bool overwrite); + const std::string& destinationPath, + bool overwrite); bool removeFile(const std::string& path); bool removeDirectory(const std::string& path); bool createDirectory(const std::string& path); @@ -61,7 +66,8 @@ namespace Utils bool isDirectory(const std::string& path); bool isSymlink(const std::string& path); bool isHidden(const std::string& path); - } -} + } // namespace FileSystem + +} // namespace Utils #endif // ES_CORE_UTILS_FILE_SYSTEM_UTIL_H diff --git a/es-core/src/utils/StringUtil.cpp b/es-core/src/utils/StringUtil.cpp index eb9f3c2ef..552b23d7b 100644 --- a/es-core/src/utils/StringUtil.cpp +++ b/es-core/src/utils/StringUtil.cpp @@ -19,160 +19,278 @@ namespace Utils { // Unicode case conversion mapping table, based on data from this site: // https://www.ibm.com/support/knowledgecenter/ssw_ibm_i_71/nls/rbagslowtoupmaptable.htm - static wchar_t unicodeLowercase[] = - { - (wchar_t)0x0061, (wchar_t)0x0062, (wchar_t)0x0063, (wchar_t)0x0064, (wchar_t)0x0065, (wchar_t)0x0066, (wchar_t)0x0067, (wchar_t)0x0068, (wchar_t)0x0069, - (wchar_t)0x006A, (wchar_t)0x006B, (wchar_t)0x006C, (wchar_t)0x006D, (wchar_t)0x006E, (wchar_t)0x006F, (wchar_t)0x0070, (wchar_t)0x0071, (wchar_t)0x0072, - (wchar_t)0x0073, (wchar_t)0x0074, (wchar_t)0x0075, (wchar_t)0x0076, (wchar_t)0x0077, (wchar_t)0x0078, (wchar_t)0x0079, (wchar_t)0x007A, (wchar_t)0x00E0, - (wchar_t)0x00E1, (wchar_t)0x00E2, (wchar_t)0x00E3, (wchar_t)0x00E4, (wchar_t)0x00E5, (wchar_t)0x00E6, (wchar_t)0x00E7, (wchar_t)0x00E8, (wchar_t)0x00E9, - (wchar_t)0x00EA, (wchar_t)0x00EB, (wchar_t)0x00EC, (wchar_t)0x00ED, (wchar_t)0x00EE, (wchar_t)0x00EF, (wchar_t)0x00F0, (wchar_t)0x00F1, (wchar_t)0x00F2, - (wchar_t)0x00F3, (wchar_t)0x00F4, (wchar_t)0x00F5, (wchar_t)0x00F6, (wchar_t)0x00F8, (wchar_t)0x00F9, (wchar_t)0x00FA, (wchar_t)0x00FB, (wchar_t)0x00FC, - (wchar_t)0x00FD, (wchar_t)0x00FE, (wchar_t)0x00FF, (wchar_t)0x0101, (wchar_t)0x0103, (wchar_t)0x0105, (wchar_t)0x0107, (wchar_t)0x0109, (wchar_t)0x010B, - (wchar_t)0x010D, (wchar_t)0x010F, (wchar_t)0x0111, (wchar_t)0x0113, (wchar_t)0x0115, (wchar_t)0x0117, (wchar_t)0x0119, (wchar_t)0x011B, (wchar_t)0x011D, - (wchar_t)0x011F, (wchar_t)0x0121, (wchar_t)0x0123, (wchar_t)0x0125, (wchar_t)0x0127, (wchar_t)0x0129, (wchar_t)0x012B, (wchar_t)0x012D, (wchar_t)0x012F, - (wchar_t)0x0131, (wchar_t)0x0133, (wchar_t)0x0135, (wchar_t)0x0137, (wchar_t)0x013A, (wchar_t)0x013C, (wchar_t)0x013E, (wchar_t)0x0140, (wchar_t)0x0142, - (wchar_t)0x0144, (wchar_t)0x0146, (wchar_t)0x0148, (wchar_t)0x014B, (wchar_t)0x014D, (wchar_t)0x014F, (wchar_t)0x0151, (wchar_t)0x0153, (wchar_t)0x0155, - (wchar_t)0x0157, (wchar_t)0x0159, (wchar_t)0x015B, (wchar_t)0x015D, (wchar_t)0x015F, (wchar_t)0x0161, (wchar_t)0x0163, (wchar_t)0x0165, (wchar_t)0x0167, - (wchar_t)0x0169, (wchar_t)0x016B, (wchar_t)0x016D, (wchar_t)0x016F, (wchar_t)0x0171, (wchar_t)0x0173, (wchar_t)0x0175, (wchar_t)0x0177, (wchar_t)0x017A, - (wchar_t)0x017C, (wchar_t)0x017E, (wchar_t)0x0183, (wchar_t)0x0185, (wchar_t)0x0188, (wchar_t)0x018C, (wchar_t)0x0192, (wchar_t)0x0199, (wchar_t)0x01A1, - (wchar_t)0x01A3, (wchar_t)0x01A5, (wchar_t)0x01A8, (wchar_t)0x01AD, (wchar_t)0x01B0, (wchar_t)0x01B4, (wchar_t)0x01B6, (wchar_t)0x01B9, (wchar_t)0x01BD, - (wchar_t)0x01C6, (wchar_t)0x01C9, (wchar_t)0x01CC, (wchar_t)0x01CE, (wchar_t)0x01D0, (wchar_t)0x01D2, (wchar_t)0x01D4, (wchar_t)0x01D6, (wchar_t)0x01D8, - (wchar_t)0x01DA, (wchar_t)0x01DC, (wchar_t)0x01DF, (wchar_t)0x01E1, (wchar_t)0x01E3, (wchar_t)0x01E5, (wchar_t)0x01E7, (wchar_t)0x01E9, (wchar_t)0x01EB, - (wchar_t)0x01ED, (wchar_t)0x01EF, (wchar_t)0x01F3, (wchar_t)0x01F5, (wchar_t)0x01FB, (wchar_t)0x01FD, (wchar_t)0x01FF, (wchar_t)0x0201, (wchar_t)0x0203, - (wchar_t)0x0205, (wchar_t)0x0207, (wchar_t)0x0209, (wchar_t)0x020B, (wchar_t)0x020D, (wchar_t)0x020F, (wchar_t)0x0211, (wchar_t)0x0213, (wchar_t)0x0215, - (wchar_t)0x0217, (wchar_t)0x0253, (wchar_t)0x0254, (wchar_t)0x0257, (wchar_t)0x0258, (wchar_t)0x0259, (wchar_t)0x025B, (wchar_t)0x0260, (wchar_t)0x0263, - (wchar_t)0x0268, (wchar_t)0x0269, (wchar_t)0x026F, (wchar_t)0x0272, (wchar_t)0x0275, (wchar_t)0x0283, (wchar_t)0x0288, (wchar_t)0x028A, (wchar_t)0x028B, - (wchar_t)0x0292, (wchar_t)0x03AC, (wchar_t)0x03AD, (wchar_t)0x03AE, (wchar_t)0x03AF, (wchar_t)0x03B1, (wchar_t)0x03B2, (wchar_t)0x03B3, (wchar_t)0x03B4, - (wchar_t)0x03B5, (wchar_t)0x03B6, (wchar_t)0x03B7, (wchar_t)0x03B8, (wchar_t)0x03B9, (wchar_t)0x03BA, (wchar_t)0x03BB, (wchar_t)0x03BC, (wchar_t)0x03BD, - (wchar_t)0x03BE, (wchar_t)0x03BF, (wchar_t)0x03C0, (wchar_t)0x03C1, (wchar_t)0x03C3, (wchar_t)0x03C4, (wchar_t)0x03C5, (wchar_t)0x03C6, (wchar_t)0x03C7, - (wchar_t)0x03C8, (wchar_t)0x03C9, (wchar_t)0x03CA, (wchar_t)0x03CB, (wchar_t)0x03CC, (wchar_t)0x03CD, (wchar_t)0x03CE, (wchar_t)0x03E3, (wchar_t)0x03E5, - (wchar_t)0x03E7, (wchar_t)0x03E9, (wchar_t)0x03EB, (wchar_t)0x03ED, (wchar_t)0x03EF, (wchar_t)0x0430, (wchar_t)0x0431, (wchar_t)0x0432, (wchar_t)0x0433, - (wchar_t)0x0434, (wchar_t)0x0435, (wchar_t)0x0436, (wchar_t)0x0437, (wchar_t)0x0438, (wchar_t)0x0439, (wchar_t)0x043A, (wchar_t)0x043B, (wchar_t)0x043C, - (wchar_t)0x043D, (wchar_t)0x043E, (wchar_t)0x043F, (wchar_t)0x0440, (wchar_t)0x0441, (wchar_t)0x0442, (wchar_t)0x0443, (wchar_t)0x0444, (wchar_t)0x0445, - (wchar_t)0x0446, (wchar_t)0x0447, (wchar_t)0x0448, (wchar_t)0x0449, (wchar_t)0x044A, (wchar_t)0x044B, (wchar_t)0x044C, (wchar_t)0x044D, (wchar_t)0x044E, - (wchar_t)0x044F, (wchar_t)0x0451, (wchar_t)0x0452, (wchar_t)0x0453, (wchar_t)0x0454, (wchar_t)0x0455, (wchar_t)0x0456, (wchar_t)0x0457, (wchar_t)0x0458, - (wchar_t)0x0459, (wchar_t)0x045A, (wchar_t)0x045B, (wchar_t)0x045C, (wchar_t)0x045E, (wchar_t)0x045F, (wchar_t)0x0461, (wchar_t)0x0463, (wchar_t)0x0465, - (wchar_t)0x0467, (wchar_t)0x0469, (wchar_t)0x046B, (wchar_t)0x046D, (wchar_t)0x046F, (wchar_t)0x0471, (wchar_t)0x0473, (wchar_t)0x0475, (wchar_t)0x0477, - (wchar_t)0x0479, (wchar_t)0x047B, (wchar_t)0x047D, (wchar_t)0x047F, (wchar_t)0x0481, (wchar_t)0x0491, (wchar_t)0x0493, (wchar_t)0x0495, (wchar_t)0x0497, - (wchar_t)0x0499, (wchar_t)0x049B, (wchar_t)0x049D, (wchar_t)0x049F, (wchar_t)0x04A1, (wchar_t)0x04A3, (wchar_t)0x04A5, (wchar_t)0x04A7, (wchar_t)0x04A9, - (wchar_t)0x04AB, (wchar_t)0x04AD, (wchar_t)0x04AF, (wchar_t)0x04B1, (wchar_t)0x04B3, (wchar_t)0x04B5, (wchar_t)0x04B7, (wchar_t)0x04B9, (wchar_t)0x04BB, - (wchar_t)0x04BD, (wchar_t)0x04BF, (wchar_t)0x04C2, (wchar_t)0x04C4, (wchar_t)0x04C8, (wchar_t)0x04CC, (wchar_t)0x04D1, (wchar_t)0x04D3, (wchar_t)0x04D5, - (wchar_t)0x04D7, (wchar_t)0x04D9, (wchar_t)0x04DB, (wchar_t)0x04DD, (wchar_t)0x04DF, (wchar_t)0x04E1, (wchar_t)0x04E3, (wchar_t)0x04E5, (wchar_t)0x04E7, - (wchar_t)0x04E9, (wchar_t)0x04EB, (wchar_t)0x04EF, (wchar_t)0x04F1, (wchar_t)0x04F3, (wchar_t)0x04F5, (wchar_t)0x04F9, (wchar_t)0x0561, (wchar_t)0x0562, - (wchar_t)0x0563, (wchar_t)0x0564, (wchar_t)0x0565, (wchar_t)0x0566, (wchar_t)0x0567, (wchar_t)0x0568, (wchar_t)0x0569, (wchar_t)0x056A, (wchar_t)0x056B, - (wchar_t)0x056C, (wchar_t)0x056D, (wchar_t)0x056E, (wchar_t)0x056F, (wchar_t)0x0570, (wchar_t)0x0571, (wchar_t)0x0572, (wchar_t)0x0573, (wchar_t)0x0574, - (wchar_t)0x0575, (wchar_t)0x0576, (wchar_t)0x0577, (wchar_t)0x0578, (wchar_t)0x0579, (wchar_t)0x057A, (wchar_t)0x057B, (wchar_t)0x057C, (wchar_t)0x057D, - (wchar_t)0x057E, (wchar_t)0x057F, (wchar_t)0x0580, (wchar_t)0x0581, (wchar_t)0x0582, (wchar_t)0x0583, (wchar_t)0x0584, (wchar_t)0x0585, (wchar_t)0x0586, - (wchar_t)0x10D0, (wchar_t)0x10D1, (wchar_t)0x10D2, (wchar_t)0x10D3, (wchar_t)0x10D4, (wchar_t)0x10D5, (wchar_t)0x10D6, (wchar_t)0x10D7, (wchar_t)0x10D8, - (wchar_t)0x10D9, (wchar_t)0x10DA, (wchar_t)0x10DB, (wchar_t)0x10DC, (wchar_t)0x10DD, (wchar_t)0x10DE, (wchar_t)0x10DF, (wchar_t)0x10E0, (wchar_t)0x10E1, - (wchar_t)0x10E2, (wchar_t)0x10E3, (wchar_t)0x10E4, (wchar_t)0x10E5, (wchar_t)0x10E6, (wchar_t)0x10E7, (wchar_t)0x10E8, (wchar_t)0x10E9, (wchar_t)0x10EA, - (wchar_t)0x10EB, (wchar_t)0x10EC, (wchar_t)0x10ED, (wchar_t)0x10EE, (wchar_t)0x10EF, (wchar_t)0x10F0, (wchar_t)0x10F1, (wchar_t)0x10F2, (wchar_t)0x10F3, - (wchar_t)0x10F4, (wchar_t)0x10F5, (wchar_t)0x1E01, (wchar_t)0x1E03, (wchar_t)0x1E05, (wchar_t)0x1E07, (wchar_t)0x1E09, (wchar_t)0x1E0B, (wchar_t)0x1E0D, - (wchar_t)0x1E0F, (wchar_t)0x1E11, (wchar_t)0x1E13, (wchar_t)0x1E15, (wchar_t)0x1E17, (wchar_t)0x1E19, (wchar_t)0x1E1B, (wchar_t)0x1E1D, (wchar_t)0x1E1F, - (wchar_t)0x1E21, (wchar_t)0x1E23, (wchar_t)0x1E25, (wchar_t)0x1E27, (wchar_t)0x1E29, (wchar_t)0x1E2B, (wchar_t)0x1E2D, (wchar_t)0x1E2F, (wchar_t)0x1E31, - (wchar_t)0x1E33, (wchar_t)0x1E35, (wchar_t)0x1E37, (wchar_t)0x1E39, (wchar_t)0x1E3B, (wchar_t)0x1E3D, (wchar_t)0x1E3F, (wchar_t)0x1E41, (wchar_t)0x1E43, - (wchar_t)0x1E45, (wchar_t)0x1E47, (wchar_t)0x1E49, (wchar_t)0x1E4B, (wchar_t)0x1E4D, (wchar_t)0x1E4F, (wchar_t)0x1E51, (wchar_t)0x1E53, (wchar_t)0x1E55, - (wchar_t)0x1E57, (wchar_t)0x1E59, (wchar_t)0x1E5B, (wchar_t)0x1E5D, (wchar_t)0x1E5F, (wchar_t)0x1E61, (wchar_t)0x1E63, (wchar_t)0x1E65, (wchar_t)0x1E67, - (wchar_t)0x1E69, (wchar_t)0x1E6B, (wchar_t)0x1E6D, (wchar_t)0x1E6F, (wchar_t)0x1E71, (wchar_t)0x1E73, (wchar_t)0x1E75, (wchar_t)0x1E77, (wchar_t)0x1E79, - (wchar_t)0x1E7B, (wchar_t)0x1E7D, (wchar_t)0x1E7F, (wchar_t)0x1E81, (wchar_t)0x1E83, (wchar_t)0x1E85, (wchar_t)0x1E87, (wchar_t)0x1E89, (wchar_t)0x1E8B, - (wchar_t)0x1E8D, (wchar_t)0x1E8F, (wchar_t)0x1E91, (wchar_t)0x1E93, (wchar_t)0x1E95, (wchar_t)0x1EA1, (wchar_t)0x1EA3, (wchar_t)0x1EA5, (wchar_t)0x1EA7, - (wchar_t)0x1EA9, (wchar_t)0x1EAB, (wchar_t)0x1EAD, (wchar_t)0x1EAF, (wchar_t)0x1EB1, (wchar_t)0x1EB3, (wchar_t)0x1EB5, (wchar_t)0x1EB7, (wchar_t)0x1EB9, - (wchar_t)0x1EBB, (wchar_t)0x1EBD, (wchar_t)0x1EBF, (wchar_t)0x1EC1, (wchar_t)0x1EC3, (wchar_t)0x1EC5, (wchar_t)0x1EC7, (wchar_t)0x1EC9, (wchar_t)0x1ECB, - (wchar_t)0x1ECD, (wchar_t)0x1ECF, (wchar_t)0x1ED1, (wchar_t)0x1ED3, (wchar_t)0x1ED5, (wchar_t)0x1ED7, (wchar_t)0x1ED9, (wchar_t)0x1EDB, (wchar_t)0x1EDD, - (wchar_t)0x1EDF, (wchar_t)0x1EE1, (wchar_t)0x1EE3, (wchar_t)0x1EE5, (wchar_t)0x1EE7, (wchar_t)0x1EE9, (wchar_t)0x1EEB, (wchar_t)0x1EED, (wchar_t)0x1EEF, - (wchar_t)0x1EF1, (wchar_t)0x1EF3, (wchar_t)0x1EF5, (wchar_t)0x1EF7, (wchar_t)0x1EF9, (wchar_t)0x1F00, (wchar_t)0x1F01, (wchar_t)0x1F02, (wchar_t)0x1F03, - (wchar_t)0x1F04, (wchar_t)0x1F05, (wchar_t)0x1F06, (wchar_t)0x1F07, (wchar_t)0x1F10, (wchar_t)0x1F11, (wchar_t)0x1F12, (wchar_t)0x1F13, (wchar_t)0x1F14, - (wchar_t)0x1F15, (wchar_t)0x1F20, (wchar_t)0x1F21, (wchar_t)0x1F22, (wchar_t)0x1F23, (wchar_t)0x1F24, (wchar_t)0x1F25, (wchar_t)0x1F26, (wchar_t)0x1F27, - (wchar_t)0x1F30, (wchar_t)0x1F31, (wchar_t)0x1F32, (wchar_t)0x1F33, (wchar_t)0x1F34, (wchar_t)0x1F35, (wchar_t)0x1F36, (wchar_t)0x1F37, (wchar_t)0x1F40, - (wchar_t)0x1F41, (wchar_t)0x1F42, (wchar_t)0x1F43, (wchar_t)0x1F44, (wchar_t)0x1F45, (wchar_t)0x1F51, (wchar_t)0x1F53, (wchar_t)0x1F55, (wchar_t)0x1F57, - (wchar_t)0x1F60, (wchar_t)0x1F61, (wchar_t)0x1F62, (wchar_t)0x1F63, (wchar_t)0x1F64, (wchar_t)0x1F65, (wchar_t)0x1F66, (wchar_t)0x1F67, (wchar_t)0x1F80, - (wchar_t)0x1F81, (wchar_t)0x1F82, (wchar_t)0x1F83, (wchar_t)0x1F84, (wchar_t)0x1F85, (wchar_t)0x1F86, (wchar_t)0x1F87, (wchar_t)0x1F90, (wchar_t)0x1F91, - (wchar_t)0x1F92, (wchar_t)0x1F93, (wchar_t)0x1F94, (wchar_t)0x1F95, (wchar_t)0x1F96, (wchar_t)0x1F97, (wchar_t)0x1FA0, (wchar_t)0x1FA1, (wchar_t)0x1FA2, - (wchar_t)0x1FA3, (wchar_t)0x1FA4, (wchar_t)0x1FA5, (wchar_t)0x1FA6, (wchar_t)0x1FA7, (wchar_t)0x1FB0, (wchar_t)0x1FB1, (wchar_t)0x1FD0, (wchar_t)0x1FD1, - (wchar_t)0x1FE0, (wchar_t)0x1FE1, (wchar_t)0x24D0, (wchar_t)0x24D1, (wchar_t)0x24D2, (wchar_t)0x24D3, (wchar_t)0x24D4, (wchar_t)0x24D5, (wchar_t)0x24D6, - (wchar_t)0x24D7, (wchar_t)0x24D8, (wchar_t)0x24D9, (wchar_t)0x24DA, (wchar_t)0x24DB, (wchar_t)0x24DC, (wchar_t)0x24DD, (wchar_t)0x24DE, (wchar_t)0x24DF, - (wchar_t)0x24E0, (wchar_t)0x24E1, (wchar_t)0x24E2, (wchar_t)0x24E3, (wchar_t)0x24E4, (wchar_t)0x24E5, (wchar_t)0x24E6, (wchar_t)0x24E7, (wchar_t)0x24E8, - (wchar_t)0x24E9, (wchar_t)0xFF41, (wchar_t)0xFF42, (wchar_t)0xFF43, (wchar_t)0xFF44, (wchar_t)0xFF45, (wchar_t)0xFF46, (wchar_t)0xFF47, (wchar_t)0xFF48, - (wchar_t)0xFF49, (wchar_t)0xFF4A, (wchar_t)0xFF4B, (wchar_t)0xFF4C, (wchar_t)0xFF4D, (wchar_t)0xFF4E, (wchar_t)0xFF4F, (wchar_t)0xFF50, (wchar_t)0xFF51, - (wchar_t)0xFF52, (wchar_t)0xFF53, (wchar_t)0xFF54, (wchar_t)0xFF55, (wchar_t)0xFF56, (wchar_t)0xFF57, (wchar_t)0xFF58, (wchar_t)0xFF59, (wchar_t)0xFF5A + static wchar_t unicodeLowercase[] = { + (wchar_t)0x0061, (wchar_t)0x0062, (wchar_t)0x0063, (wchar_t)0x0064, (wchar_t)0x0065, + (wchar_t)0x0066, (wchar_t)0x0067, (wchar_t)0x0068, (wchar_t)0x0069, (wchar_t)0x006A, + (wchar_t)0x006B, (wchar_t)0x006C, (wchar_t)0x006D, (wchar_t)0x006E, (wchar_t)0x006F, + (wchar_t)0x0070, (wchar_t)0x0071, (wchar_t)0x0072, (wchar_t)0x0073, (wchar_t)0x0074, + (wchar_t)0x0075, (wchar_t)0x0076, (wchar_t)0x0077, (wchar_t)0x0078, (wchar_t)0x0079, + (wchar_t)0x007A, (wchar_t)0x00E0, (wchar_t)0x00E1, (wchar_t)0x00E2, (wchar_t)0x00E3, + (wchar_t)0x00E4, (wchar_t)0x00E5, (wchar_t)0x00E6, (wchar_t)0x00E7, (wchar_t)0x00E8, + (wchar_t)0x00E9, (wchar_t)0x00EA, (wchar_t)0x00EB, (wchar_t)0x00EC, (wchar_t)0x00ED, + (wchar_t)0x00EE, (wchar_t)0x00EF, (wchar_t)0x00F0, (wchar_t)0x00F1, (wchar_t)0x00F2, + (wchar_t)0x00F3, (wchar_t)0x00F4, (wchar_t)0x00F5, (wchar_t)0x00F6, (wchar_t)0x00F8, + (wchar_t)0x00F9, (wchar_t)0x00FA, (wchar_t)0x00FB, (wchar_t)0x00FC, (wchar_t)0x00FD, + (wchar_t)0x00FE, (wchar_t)0x00FF, (wchar_t)0x0101, (wchar_t)0x0103, (wchar_t)0x0105, + (wchar_t)0x0107, (wchar_t)0x0109, (wchar_t)0x010B, (wchar_t)0x010D, (wchar_t)0x010F, + (wchar_t)0x0111, (wchar_t)0x0113, (wchar_t)0x0115, (wchar_t)0x0117, (wchar_t)0x0119, + (wchar_t)0x011B, (wchar_t)0x011D, (wchar_t)0x011F, (wchar_t)0x0121, (wchar_t)0x0123, + (wchar_t)0x0125, (wchar_t)0x0127, (wchar_t)0x0129, (wchar_t)0x012B, (wchar_t)0x012D, + (wchar_t)0x012F, (wchar_t)0x0131, (wchar_t)0x0133, (wchar_t)0x0135, (wchar_t)0x0137, + (wchar_t)0x013A, (wchar_t)0x013C, (wchar_t)0x013E, (wchar_t)0x0140, (wchar_t)0x0142, + (wchar_t)0x0144, (wchar_t)0x0146, (wchar_t)0x0148, (wchar_t)0x014B, (wchar_t)0x014D, + (wchar_t)0x014F, (wchar_t)0x0151, (wchar_t)0x0153, (wchar_t)0x0155, (wchar_t)0x0157, + (wchar_t)0x0159, (wchar_t)0x015B, (wchar_t)0x015D, (wchar_t)0x015F, (wchar_t)0x0161, + (wchar_t)0x0163, (wchar_t)0x0165, (wchar_t)0x0167, (wchar_t)0x0169, (wchar_t)0x016B, + (wchar_t)0x016D, (wchar_t)0x016F, (wchar_t)0x0171, (wchar_t)0x0173, (wchar_t)0x0175, + (wchar_t)0x0177, (wchar_t)0x017A, (wchar_t)0x017C, (wchar_t)0x017E, (wchar_t)0x0183, + (wchar_t)0x0185, (wchar_t)0x0188, (wchar_t)0x018C, (wchar_t)0x0192, (wchar_t)0x0199, + (wchar_t)0x01A1, (wchar_t)0x01A3, (wchar_t)0x01A5, (wchar_t)0x01A8, (wchar_t)0x01AD, + (wchar_t)0x01B0, (wchar_t)0x01B4, (wchar_t)0x01B6, (wchar_t)0x01B9, (wchar_t)0x01BD, + (wchar_t)0x01C6, (wchar_t)0x01C9, (wchar_t)0x01CC, (wchar_t)0x01CE, (wchar_t)0x01D0, + (wchar_t)0x01D2, (wchar_t)0x01D4, (wchar_t)0x01D6, (wchar_t)0x01D8, (wchar_t)0x01DA, + (wchar_t)0x01DC, (wchar_t)0x01DF, (wchar_t)0x01E1, (wchar_t)0x01E3, (wchar_t)0x01E5, + (wchar_t)0x01E7, (wchar_t)0x01E9, (wchar_t)0x01EB, (wchar_t)0x01ED, (wchar_t)0x01EF, + (wchar_t)0x01F3, (wchar_t)0x01F5, (wchar_t)0x01FB, (wchar_t)0x01FD, (wchar_t)0x01FF, + (wchar_t)0x0201, (wchar_t)0x0203, (wchar_t)0x0205, (wchar_t)0x0207, (wchar_t)0x0209, + (wchar_t)0x020B, (wchar_t)0x020D, (wchar_t)0x020F, (wchar_t)0x0211, (wchar_t)0x0213, + (wchar_t)0x0215, (wchar_t)0x0217, (wchar_t)0x0253, (wchar_t)0x0254, (wchar_t)0x0257, + (wchar_t)0x0258, (wchar_t)0x0259, (wchar_t)0x025B, (wchar_t)0x0260, (wchar_t)0x0263, + (wchar_t)0x0268, (wchar_t)0x0269, (wchar_t)0x026F, (wchar_t)0x0272, (wchar_t)0x0275, + (wchar_t)0x0283, (wchar_t)0x0288, (wchar_t)0x028A, (wchar_t)0x028B, (wchar_t)0x0292, + (wchar_t)0x03AC, (wchar_t)0x03AD, (wchar_t)0x03AE, (wchar_t)0x03AF, (wchar_t)0x03B1, + (wchar_t)0x03B2, (wchar_t)0x03B3, (wchar_t)0x03B4, (wchar_t)0x03B5, (wchar_t)0x03B6, + (wchar_t)0x03B7, (wchar_t)0x03B8, (wchar_t)0x03B9, (wchar_t)0x03BA, (wchar_t)0x03BB, + (wchar_t)0x03BC, (wchar_t)0x03BD, (wchar_t)0x03BE, (wchar_t)0x03BF, (wchar_t)0x03C0, + (wchar_t)0x03C1, (wchar_t)0x03C3, (wchar_t)0x03C4, (wchar_t)0x03C5, (wchar_t)0x03C6, + (wchar_t)0x03C7, (wchar_t)0x03C8, (wchar_t)0x03C9, (wchar_t)0x03CA, (wchar_t)0x03CB, + (wchar_t)0x03CC, (wchar_t)0x03CD, (wchar_t)0x03CE, (wchar_t)0x03E3, (wchar_t)0x03E5, + (wchar_t)0x03E7, (wchar_t)0x03E9, (wchar_t)0x03EB, (wchar_t)0x03ED, (wchar_t)0x03EF, + (wchar_t)0x0430, (wchar_t)0x0431, (wchar_t)0x0432, (wchar_t)0x0433, (wchar_t)0x0434, + (wchar_t)0x0435, (wchar_t)0x0436, (wchar_t)0x0437, (wchar_t)0x0438, (wchar_t)0x0439, + (wchar_t)0x043A, (wchar_t)0x043B, (wchar_t)0x043C, (wchar_t)0x043D, (wchar_t)0x043E, + (wchar_t)0x043F, (wchar_t)0x0440, (wchar_t)0x0441, (wchar_t)0x0442, (wchar_t)0x0443, + (wchar_t)0x0444, (wchar_t)0x0445, (wchar_t)0x0446, (wchar_t)0x0447, (wchar_t)0x0448, + (wchar_t)0x0449, (wchar_t)0x044A, (wchar_t)0x044B, (wchar_t)0x044C, (wchar_t)0x044D, + (wchar_t)0x044E, (wchar_t)0x044F, (wchar_t)0x0451, (wchar_t)0x0452, (wchar_t)0x0453, + (wchar_t)0x0454, (wchar_t)0x0455, (wchar_t)0x0456, (wchar_t)0x0457, (wchar_t)0x0458, + (wchar_t)0x0459, (wchar_t)0x045A, (wchar_t)0x045B, (wchar_t)0x045C, (wchar_t)0x045E, + (wchar_t)0x045F, (wchar_t)0x0461, (wchar_t)0x0463, (wchar_t)0x0465, (wchar_t)0x0467, + (wchar_t)0x0469, (wchar_t)0x046B, (wchar_t)0x046D, (wchar_t)0x046F, (wchar_t)0x0471, + (wchar_t)0x0473, (wchar_t)0x0475, (wchar_t)0x0477, (wchar_t)0x0479, (wchar_t)0x047B, + (wchar_t)0x047D, (wchar_t)0x047F, (wchar_t)0x0481, (wchar_t)0x0491, (wchar_t)0x0493, + (wchar_t)0x0495, (wchar_t)0x0497, (wchar_t)0x0499, (wchar_t)0x049B, (wchar_t)0x049D, + (wchar_t)0x049F, (wchar_t)0x04A1, (wchar_t)0x04A3, (wchar_t)0x04A5, (wchar_t)0x04A7, + (wchar_t)0x04A9, (wchar_t)0x04AB, (wchar_t)0x04AD, (wchar_t)0x04AF, (wchar_t)0x04B1, + (wchar_t)0x04B3, (wchar_t)0x04B5, (wchar_t)0x04B7, (wchar_t)0x04B9, (wchar_t)0x04BB, + (wchar_t)0x04BD, (wchar_t)0x04BF, (wchar_t)0x04C2, (wchar_t)0x04C4, (wchar_t)0x04C8, + (wchar_t)0x04CC, (wchar_t)0x04D1, (wchar_t)0x04D3, (wchar_t)0x04D5, (wchar_t)0x04D7, + (wchar_t)0x04D9, (wchar_t)0x04DB, (wchar_t)0x04DD, (wchar_t)0x04DF, (wchar_t)0x04E1, + (wchar_t)0x04E3, (wchar_t)0x04E5, (wchar_t)0x04E7, (wchar_t)0x04E9, (wchar_t)0x04EB, + (wchar_t)0x04EF, (wchar_t)0x04F1, (wchar_t)0x04F3, (wchar_t)0x04F5, (wchar_t)0x04F9, + (wchar_t)0x0561, (wchar_t)0x0562, (wchar_t)0x0563, (wchar_t)0x0564, (wchar_t)0x0565, + (wchar_t)0x0566, (wchar_t)0x0567, (wchar_t)0x0568, (wchar_t)0x0569, (wchar_t)0x056A, + (wchar_t)0x056B, (wchar_t)0x056C, (wchar_t)0x056D, (wchar_t)0x056E, (wchar_t)0x056F, + (wchar_t)0x0570, (wchar_t)0x0571, (wchar_t)0x0572, (wchar_t)0x0573, (wchar_t)0x0574, + (wchar_t)0x0575, (wchar_t)0x0576, (wchar_t)0x0577, (wchar_t)0x0578, (wchar_t)0x0579, + (wchar_t)0x057A, (wchar_t)0x057B, (wchar_t)0x057C, (wchar_t)0x057D, (wchar_t)0x057E, + (wchar_t)0x057F, (wchar_t)0x0580, (wchar_t)0x0581, (wchar_t)0x0582, (wchar_t)0x0583, + (wchar_t)0x0584, (wchar_t)0x0585, (wchar_t)0x0586, (wchar_t)0x10D0, (wchar_t)0x10D1, + (wchar_t)0x10D2, (wchar_t)0x10D3, (wchar_t)0x10D4, (wchar_t)0x10D5, (wchar_t)0x10D6, + (wchar_t)0x10D7, (wchar_t)0x10D8, (wchar_t)0x10D9, (wchar_t)0x10DA, (wchar_t)0x10DB, + (wchar_t)0x10DC, (wchar_t)0x10DD, (wchar_t)0x10DE, (wchar_t)0x10DF, (wchar_t)0x10E0, + (wchar_t)0x10E1, (wchar_t)0x10E2, (wchar_t)0x10E3, (wchar_t)0x10E4, (wchar_t)0x10E5, + (wchar_t)0x10E6, (wchar_t)0x10E7, (wchar_t)0x10E8, (wchar_t)0x10E9, (wchar_t)0x10EA, + (wchar_t)0x10EB, (wchar_t)0x10EC, (wchar_t)0x10ED, (wchar_t)0x10EE, (wchar_t)0x10EF, + (wchar_t)0x10F0, (wchar_t)0x10F1, (wchar_t)0x10F2, (wchar_t)0x10F3, (wchar_t)0x10F4, + (wchar_t)0x10F5, (wchar_t)0x1E01, (wchar_t)0x1E03, (wchar_t)0x1E05, (wchar_t)0x1E07, + (wchar_t)0x1E09, (wchar_t)0x1E0B, (wchar_t)0x1E0D, (wchar_t)0x1E0F, (wchar_t)0x1E11, + (wchar_t)0x1E13, (wchar_t)0x1E15, (wchar_t)0x1E17, (wchar_t)0x1E19, (wchar_t)0x1E1B, + (wchar_t)0x1E1D, (wchar_t)0x1E1F, (wchar_t)0x1E21, (wchar_t)0x1E23, (wchar_t)0x1E25, + (wchar_t)0x1E27, (wchar_t)0x1E29, (wchar_t)0x1E2B, (wchar_t)0x1E2D, (wchar_t)0x1E2F, + (wchar_t)0x1E31, (wchar_t)0x1E33, (wchar_t)0x1E35, (wchar_t)0x1E37, (wchar_t)0x1E39, + (wchar_t)0x1E3B, (wchar_t)0x1E3D, (wchar_t)0x1E3F, (wchar_t)0x1E41, (wchar_t)0x1E43, + (wchar_t)0x1E45, (wchar_t)0x1E47, (wchar_t)0x1E49, (wchar_t)0x1E4B, (wchar_t)0x1E4D, + (wchar_t)0x1E4F, (wchar_t)0x1E51, (wchar_t)0x1E53, (wchar_t)0x1E55, (wchar_t)0x1E57, + (wchar_t)0x1E59, (wchar_t)0x1E5B, (wchar_t)0x1E5D, (wchar_t)0x1E5F, (wchar_t)0x1E61, + (wchar_t)0x1E63, (wchar_t)0x1E65, (wchar_t)0x1E67, (wchar_t)0x1E69, (wchar_t)0x1E6B, + (wchar_t)0x1E6D, (wchar_t)0x1E6F, (wchar_t)0x1E71, (wchar_t)0x1E73, (wchar_t)0x1E75, + (wchar_t)0x1E77, (wchar_t)0x1E79, (wchar_t)0x1E7B, (wchar_t)0x1E7D, (wchar_t)0x1E7F, + (wchar_t)0x1E81, (wchar_t)0x1E83, (wchar_t)0x1E85, (wchar_t)0x1E87, (wchar_t)0x1E89, + (wchar_t)0x1E8B, (wchar_t)0x1E8D, (wchar_t)0x1E8F, (wchar_t)0x1E91, (wchar_t)0x1E93, + (wchar_t)0x1E95, (wchar_t)0x1EA1, (wchar_t)0x1EA3, (wchar_t)0x1EA5, (wchar_t)0x1EA7, + (wchar_t)0x1EA9, (wchar_t)0x1EAB, (wchar_t)0x1EAD, (wchar_t)0x1EAF, (wchar_t)0x1EB1, + (wchar_t)0x1EB3, (wchar_t)0x1EB5, (wchar_t)0x1EB7, (wchar_t)0x1EB9, (wchar_t)0x1EBB, + (wchar_t)0x1EBD, (wchar_t)0x1EBF, (wchar_t)0x1EC1, (wchar_t)0x1EC3, (wchar_t)0x1EC5, + (wchar_t)0x1EC7, (wchar_t)0x1EC9, (wchar_t)0x1ECB, (wchar_t)0x1ECD, (wchar_t)0x1ECF, + (wchar_t)0x1ED1, (wchar_t)0x1ED3, (wchar_t)0x1ED5, (wchar_t)0x1ED7, (wchar_t)0x1ED9, + (wchar_t)0x1EDB, (wchar_t)0x1EDD, (wchar_t)0x1EDF, (wchar_t)0x1EE1, (wchar_t)0x1EE3, + (wchar_t)0x1EE5, (wchar_t)0x1EE7, (wchar_t)0x1EE9, (wchar_t)0x1EEB, (wchar_t)0x1EED, + (wchar_t)0x1EEF, (wchar_t)0x1EF1, (wchar_t)0x1EF3, (wchar_t)0x1EF5, (wchar_t)0x1EF7, + (wchar_t)0x1EF9, (wchar_t)0x1F00, (wchar_t)0x1F01, (wchar_t)0x1F02, (wchar_t)0x1F03, + (wchar_t)0x1F04, (wchar_t)0x1F05, (wchar_t)0x1F06, (wchar_t)0x1F07, (wchar_t)0x1F10, + (wchar_t)0x1F11, (wchar_t)0x1F12, (wchar_t)0x1F13, (wchar_t)0x1F14, (wchar_t)0x1F15, + (wchar_t)0x1F20, (wchar_t)0x1F21, (wchar_t)0x1F22, (wchar_t)0x1F23, (wchar_t)0x1F24, + (wchar_t)0x1F25, (wchar_t)0x1F26, (wchar_t)0x1F27, (wchar_t)0x1F30, (wchar_t)0x1F31, + (wchar_t)0x1F32, (wchar_t)0x1F33, (wchar_t)0x1F34, (wchar_t)0x1F35, (wchar_t)0x1F36, + (wchar_t)0x1F37, (wchar_t)0x1F40, (wchar_t)0x1F41, (wchar_t)0x1F42, (wchar_t)0x1F43, + (wchar_t)0x1F44, (wchar_t)0x1F45, (wchar_t)0x1F51, (wchar_t)0x1F53, (wchar_t)0x1F55, + (wchar_t)0x1F57, (wchar_t)0x1F60, (wchar_t)0x1F61, (wchar_t)0x1F62, (wchar_t)0x1F63, + (wchar_t)0x1F64, (wchar_t)0x1F65, (wchar_t)0x1F66, (wchar_t)0x1F67, (wchar_t)0x1F80, + (wchar_t)0x1F81, (wchar_t)0x1F82, (wchar_t)0x1F83, (wchar_t)0x1F84, (wchar_t)0x1F85, + (wchar_t)0x1F86, (wchar_t)0x1F87, (wchar_t)0x1F90, (wchar_t)0x1F91, (wchar_t)0x1F92, + (wchar_t)0x1F93, (wchar_t)0x1F94, (wchar_t)0x1F95, (wchar_t)0x1F96, (wchar_t)0x1F97, + (wchar_t)0x1FA0, (wchar_t)0x1FA1, (wchar_t)0x1FA2, (wchar_t)0x1FA3, (wchar_t)0x1FA4, + (wchar_t)0x1FA5, (wchar_t)0x1FA6, (wchar_t)0x1FA7, (wchar_t)0x1FB0, (wchar_t)0x1FB1, + (wchar_t)0x1FD0, (wchar_t)0x1FD1, (wchar_t)0x1FE0, (wchar_t)0x1FE1, (wchar_t)0x24D0, + (wchar_t)0x24D1, (wchar_t)0x24D2, (wchar_t)0x24D3, (wchar_t)0x24D4, (wchar_t)0x24D5, + (wchar_t)0x24D6, (wchar_t)0x24D7, (wchar_t)0x24D8, (wchar_t)0x24D9, (wchar_t)0x24DA, + (wchar_t)0x24DB, (wchar_t)0x24DC, (wchar_t)0x24DD, (wchar_t)0x24DE, (wchar_t)0x24DF, + (wchar_t)0x24E0, (wchar_t)0x24E1, (wchar_t)0x24E2, (wchar_t)0x24E3, (wchar_t)0x24E4, + (wchar_t)0x24E5, (wchar_t)0x24E6, (wchar_t)0x24E7, (wchar_t)0x24E8, (wchar_t)0x24E9, + (wchar_t)0xFF41, (wchar_t)0xFF42, (wchar_t)0xFF43, (wchar_t)0xFF44, (wchar_t)0xFF45, + (wchar_t)0xFF46, (wchar_t)0xFF47, (wchar_t)0xFF48, (wchar_t)0xFF49, (wchar_t)0xFF4A, + (wchar_t)0xFF4B, (wchar_t)0xFF4C, (wchar_t)0xFF4D, (wchar_t)0xFF4E, (wchar_t)0xFF4F, + (wchar_t)0xFF50, (wchar_t)0xFF51, (wchar_t)0xFF52, (wchar_t)0xFF53, (wchar_t)0xFF54, + (wchar_t)0xFF55, (wchar_t)0xFF56, (wchar_t)0xFF57, (wchar_t)0xFF58, (wchar_t)0xFF59, + (wchar_t)0xFF5A }; - static wchar_t unicodeUppercase[] = - { - (wchar_t)0x0041, (wchar_t)0x0042, (wchar_t)0x0043, (wchar_t)0x0044, (wchar_t)0x0045, (wchar_t)0x0046, (wchar_t)0x0047, (wchar_t)0x0048, (wchar_t)0x0049, - (wchar_t)0x004A, (wchar_t)0x004B, (wchar_t)0x004C, (wchar_t)0x004D, (wchar_t)0x004E, (wchar_t)0x004F, (wchar_t)0x0050, (wchar_t)0x0051, (wchar_t)0x0052, - (wchar_t)0x0053, (wchar_t)0x0054, (wchar_t)0x0055, (wchar_t)0x0056, (wchar_t)0x0057, (wchar_t)0x0058, (wchar_t)0x0059, (wchar_t)0x005A, (wchar_t)0x00C0, - (wchar_t)0x00C1, (wchar_t)0x00C2, (wchar_t)0x00C3, (wchar_t)0x00C4, (wchar_t)0x00C5, (wchar_t)0x00C6, (wchar_t)0x00C7, (wchar_t)0x00C8, (wchar_t)0x00C9, - (wchar_t)0x00CA, (wchar_t)0x00CB, (wchar_t)0x00CC, (wchar_t)0x00CD, (wchar_t)0x00CE, (wchar_t)0x00CF, (wchar_t)0x00D0, (wchar_t)0x00D1, (wchar_t)0x00D2, - (wchar_t)0x00D3, (wchar_t)0x00D4, (wchar_t)0x00D5, (wchar_t)0x00D6, (wchar_t)0x00D8, (wchar_t)0x00D9, (wchar_t)0x00DA, (wchar_t)0x00DB, (wchar_t)0x00DC, - (wchar_t)0x00DD, (wchar_t)0x00DE, (wchar_t)0x0178, (wchar_t)0x0100, (wchar_t)0x0102, (wchar_t)0x0104, (wchar_t)0x0106, (wchar_t)0x0108, (wchar_t)0x010A, - (wchar_t)0x010C, (wchar_t)0x010E, (wchar_t)0x0110, (wchar_t)0x0112, (wchar_t)0x0114, (wchar_t)0x0116, (wchar_t)0x0118, (wchar_t)0x011A, (wchar_t)0x011C, - (wchar_t)0x011E, (wchar_t)0x0120, (wchar_t)0x0122, (wchar_t)0x0124, (wchar_t)0x0126, (wchar_t)0x0128, (wchar_t)0x012A, (wchar_t)0x012C, (wchar_t)0x012E, - (wchar_t)0x0049, (wchar_t)0x0132, (wchar_t)0x0134, (wchar_t)0x0136, (wchar_t)0x0139, (wchar_t)0x013B, (wchar_t)0x013D, (wchar_t)0x013F, (wchar_t)0x0141, - (wchar_t)0x0143, (wchar_t)0x0145, (wchar_t)0x0147, (wchar_t)0x014A, (wchar_t)0x014C, (wchar_t)0x014E, (wchar_t)0x0150, (wchar_t)0x0152, (wchar_t)0x0154, - (wchar_t)0x0156, (wchar_t)0x0158, (wchar_t)0x015A, (wchar_t)0x015C, (wchar_t)0x015E, (wchar_t)0x0160, (wchar_t)0x0162, (wchar_t)0x0164, (wchar_t)0x0166, - (wchar_t)0x0168, (wchar_t)0x016A, (wchar_t)0x016C, (wchar_t)0x016E, (wchar_t)0x0170, (wchar_t)0x0172, (wchar_t)0x0174, (wchar_t)0x0176, (wchar_t)0x0179, - (wchar_t)0x017B, (wchar_t)0x017D, (wchar_t)0x0182, (wchar_t)0x0184, (wchar_t)0x0187, (wchar_t)0x018B, (wchar_t)0x0191, (wchar_t)0x0198, (wchar_t)0x01A0, - (wchar_t)0x01A2, (wchar_t)0x01A4, (wchar_t)0x01A7, (wchar_t)0x01AC, (wchar_t)0x01AF, (wchar_t)0x01B3, (wchar_t)0x01B5, (wchar_t)0x01B8, (wchar_t)0x01BC, - (wchar_t)0x01C4, (wchar_t)0x01C7, (wchar_t)0x01CA, (wchar_t)0x01CD, (wchar_t)0x01CF, (wchar_t)0x01D1, (wchar_t)0x01D3, (wchar_t)0x01D5, (wchar_t)0x01D7, - (wchar_t)0x01D9, (wchar_t)0x01DB, (wchar_t)0x01DE, (wchar_t)0x01E0, (wchar_t)0x01E2, (wchar_t)0x01E4, (wchar_t)0x01E6, (wchar_t)0x01E8, (wchar_t)0x01EA, - (wchar_t)0x01EC, (wchar_t)0x01EE, (wchar_t)0x01F1, (wchar_t)0x01F4, (wchar_t)0x01FA, (wchar_t)0x01FC, (wchar_t)0x01FE, (wchar_t)0x0200, (wchar_t)0x0202, - (wchar_t)0x0204, (wchar_t)0x0206, (wchar_t)0x0208, (wchar_t)0x020A, (wchar_t)0x020C, (wchar_t)0x020E, (wchar_t)0x0210, (wchar_t)0x0212, (wchar_t)0x0214, - (wchar_t)0x0216, (wchar_t)0x0181, (wchar_t)0x0186, (wchar_t)0x018A, (wchar_t)0x018E, (wchar_t)0x018F, (wchar_t)0x0190, (wchar_t)0x0193, (wchar_t)0x0194, - (wchar_t)0x0197, (wchar_t)0x0196, (wchar_t)0x019C, (wchar_t)0x019D, (wchar_t)0x019F, (wchar_t)0x01A9, (wchar_t)0x01AE, (wchar_t)0x01B1, (wchar_t)0x01B2, - (wchar_t)0x01B7, (wchar_t)0x0386, (wchar_t)0x0388, (wchar_t)0x0389, (wchar_t)0x038A, (wchar_t)0x0391, (wchar_t)0x0392, (wchar_t)0x0393, (wchar_t)0x0394, - (wchar_t)0x0395, (wchar_t)0x0396, (wchar_t)0x0397, (wchar_t)0x0398, (wchar_t)0x0399, (wchar_t)0x039A, (wchar_t)0x039B, (wchar_t)0x039C, (wchar_t)0x039D, - (wchar_t)0x039E, (wchar_t)0x039F, (wchar_t)0x03A0, (wchar_t)0x03A1, (wchar_t)0x03A3, (wchar_t)0x03A4, (wchar_t)0x03A5, (wchar_t)0x03A6, (wchar_t)0x03A7, - (wchar_t)0x03A8, (wchar_t)0x03A9, (wchar_t)0x03AA, (wchar_t)0x03AB, (wchar_t)0x038C, (wchar_t)0x038E, (wchar_t)0x038F, (wchar_t)0x03E2, (wchar_t)0x03E4, - (wchar_t)0x03E6, (wchar_t)0x03E8, (wchar_t)0x03EA, (wchar_t)0x03EC, (wchar_t)0x03EE, (wchar_t)0x0410, (wchar_t)0x0411, (wchar_t)0x0412, (wchar_t)0x0413, - (wchar_t)0x0414, (wchar_t)0x0415, (wchar_t)0x0416, (wchar_t)0x0417, (wchar_t)0x0418, (wchar_t)0x0419, (wchar_t)0x041A, (wchar_t)0x041B, (wchar_t)0x041C, - (wchar_t)0x041D, (wchar_t)0x041E, (wchar_t)0x041F, (wchar_t)0x0420, (wchar_t)0x0421, (wchar_t)0x0422, (wchar_t)0x0423, (wchar_t)0x0424, (wchar_t)0x0425, - (wchar_t)0x0426, (wchar_t)0x0427, (wchar_t)0x0428, (wchar_t)0x0429, (wchar_t)0x042A, (wchar_t)0x042B, (wchar_t)0x042C, (wchar_t)0x042D, (wchar_t)0x042E, - (wchar_t)0x042F, (wchar_t)0x0401, (wchar_t)0x0402, (wchar_t)0x0403, (wchar_t)0x0404, (wchar_t)0x0405, (wchar_t)0x0406, (wchar_t)0x0407, (wchar_t)0x0408, - (wchar_t)0x0409, (wchar_t)0x040A, (wchar_t)0x040B, (wchar_t)0x040C, (wchar_t)0x040E, (wchar_t)0x040F, (wchar_t)0x0460, (wchar_t)0x0462, (wchar_t)0x0464, - (wchar_t)0x0466, (wchar_t)0x0468, (wchar_t)0x046A, (wchar_t)0x046C, (wchar_t)0x046E, (wchar_t)0x0470, (wchar_t)0x0472, (wchar_t)0x0474, (wchar_t)0x0476, - (wchar_t)0x0478, (wchar_t)0x047A, (wchar_t)0x047C, (wchar_t)0x047E, (wchar_t)0x0480, (wchar_t)0x0490, (wchar_t)0x0492, (wchar_t)0x0494, (wchar_t)0x0496, - (wchar_t)0x0498, (wchar_t)0x049A, (wchar_t)0x049C, (wchar_t)0x049E, (wchar_t)0x04A0, (wchar_t)0x04A2, (wchar_t)0x04A4, (wchar_t)0x04A6, (wchar_t)0x04A8, - (wchar_t)0x04AA, (wchar_t)0x04AC, (wchar_t)0x04AE, (wchar_t)0x04B0, (wchar_t)0x04B2, (wchar_t)0x04B4, (wchar_t)0x04B6, (wchar_t)0x04B8, (wchar_t)0x04BA, - (wchar_t)0x04BC, (wchar_t)0x04BE, (wchar_t)0x04C1, (wchar_t)0x04C3, (wchar_t)0x04C7, (wchar_t)0x04CB, (wchar_t)0x04D0, (wchar_t)0x04D2, (wchar_t)0x04D4, - (wchar_t)0x04D6, (wchar_t)0x04D8, (wchar_t)0x04DA, (wchar_t)0x04DC, (wchar_t)0x04DE, (wchar_t)0x04E0, (wchar_t)0x04E2, (wchar_t)0x04E4, (wchar_t)0x04E6, - (wchar_t)0x04E8, (wchar_t)0x04EA, (wchar_t)0x04EE, (wchar_t)0x04F0, (wchar_t)0x04F2, (wchar_t)0x04F4, (wchar_t)0x04F8, (wchar_t)0x0531, (wchar_t)0x0532, - (wchar_t)0x0533, (wchar_t)0x0534, (wchar_t)0x0535, (wchar_t)0x0536, (wchar_t)0x0537, (wchar_t)0x0538, (wchar_t)0x0539, (wchar_t)0x053A, (wchar_t)0x053B, - (wchar_t)0x053C, (wchar_t)0x053D, (wchar_t)0x053E, (wchar_t)0x053F, (wchar_t)0x0540, (wchar_t)0x0541, (wchar_t)0x0542, (wchar_t)0x0543, (wchar_t)0x0544, - (wchar_t)0x0545, (wchar_t)0x0546, (wchar_t)0x0547, (wchar_t)0x0548, (wchar_t)0x0549, (wchar_t)0x054A, (wchar_t)0x054B, (wchar_t)0x054C, (wchar_t)0x054D, - (wchar_t)0x054E, (wchar_t)0x054F, (wchar_t)0x0550, (wchar_t)0x0551, (wchar_t)0x0552, (wchar_t)0x0553, (wchar_t)0x0554, (wchar_t)0x0555, (wchar_t)0x0556, - (wchar_t)0x10A0, (wchar_t)0x10A1, (wchar_t)0x10A2, (wchar_t)0x10A3, (wchar_t)0x10A4, (wchar_t)0x10A5, (wchar_t)0x10A6, (wchar_t)0x10A7, (wchar_t)0x10A8, - (wchar_t)0x10A9, (wchar_t)0x10AA, (wchar_t)0x10AB, (wchar_t)0x10AC, (wchar_t)0x10AD, (wchar_t)0x10AE, (wchar_t)0x10AF, (wchar_t)0x10B0, (wchar_t)0x10B1, - (wchar_t)0x10B2, (wchar_t)0x10B3, (wchar_t)0x10B4, (wchar_t)0x10B5, (wchar_t)0x10B6, (wchar_t)0x10B7, (wchar_t)0x10B8, (wchar_t)0x10B9, (wchar_t)0x10BA, - (wchar_t)0x10BB, (wchar_t)0x10BC, (wchar_t)0x10BD, (wchar_t)0x10BE, (wchar_t)0x10BF, (wchar_t)0x10C0, (wchar_t)0x10C1, (wchar_t)0x10C2, (wchar_t)0x10C3, - (wchar_t)0x10C4, (wchar_t)0x10C5, (wchar_t)0x1E00, (wchar_t)0x1E02, (wchar_t)0x1E04, (wchar_t)0x1E06, (wchar_t)0x1E08, (wchar_t)0x1E0A, (wchar_t)0x1E0C, - (wchar_t)0x1E0E, (wchar_t)0x1E10, (wchar_t)0x1E12, (wchar_t)0x1E14, (wchar_t)0x1E16, (wchar_t)0x1E18, (wchar_t)0x1E1A, (wchar_t)0x1E1C, (wchar_t)0x1E1E, - (wchar_t)0x1E20, (wchar_t)0x1E22, (wchar_t)0x1E24, (wchar_t)0x1E26, (wchar_t)0x1E28, (wchar_t)0x1E2A, (wchar_t)0x1E2C, (wchar_t)0x1E2E, (wchar_t)0x1E30, - (wchar_t)0x1E32, (wchar_t)0x1E34, (wchar_t)0x1E36, (wchar_t)0x1E38, (wchar_t)0x1E3A, (wchar_t)0x1E3C, (wchar_t)0x1E3E, (wchar_t)0x1E40, (wchar_t)0x1E42, - (wchar_t)0x1E44, (wchar_t)0x1E46, (wchar_t)0x1E48, (wchar_t)0x1E4A, (wchar_t)0x1E4C, (wchar_t)0x1E4E, (wchar_t)0x1E50, (wchar_t)0x1E52, (wchar_t)0x1E54, - (wchar_t)0x1E56, (wchar_t)0x1E58, (wchar_t)0x1E5A, (wchar_t)0x1E5C, (wchar_t)0x1E5E, (wchar_t)0x1E60, (wchar_t)0x1E62, (wchar_t)0x1E64, (wchar_t)0x1E66, - (wchar_t)0x1E68, (wchar_t)0x1E6A, (wchar_t)0x1E6C, (wchar_t)0x1E6E, (wchar_t)0x1E70, (wchar_t)0x1E72, (wchar_t)0x1E74, (wchar_t)0x1E76, (wchar_t)0x1E78, - (wchar_t)0x1E7A, (wchar_t)0x1E7C, (wchar_t)0x1E7E, (wchar_t)0x1E80, (wchar_t)0x1E82, (wchar_t)0x1E84, (wchar_t)0x1E86, (wchar_t)0x1E88, (wchar_t)0x1E8A, - (wchar_t)0x1E8C, (wchar_t)0x1E8E, (wchar_t)0x1E90, (wchar_t)0x1E92, (wchar_t)0x1E94, (wchar_t)0x1EA0, (wchar_t)0x1EA2, (wchar_t)0x1EA4, (wchar_t)0x1EA6, - (wchar_t)0x1EA8, (wchar_t)0x1EAA, (wchar_t)0x1EAC, (wchar_t)0x1EAE, (wchar_t)0x1EB0, (wchar_t)0x1EB2, (wchar_t)0x1EB4, (wchar_t)0x1EB6, (wchar_t)0x1EB8, - (wchar_t)0x1EBA, (wchar_t)0x1EBC, (wchar_t)0x1EBE, (wchar_t)0x1EC0, (wchar_t)0x1EC2, (wchar_t)0x1EC4, (wchar_t)0x1EC6, (wchar_t)0x1EC8, (wchar_t)0x1ECA, - (wchar_t)0x1ECC, (wchar_t)0x1ECE, (wchar_t)0x1ED0, (wchar_t)0x1ED2, (wchar_t)0x1ED4, (wchar_t)0x1ED6, (wchar_t)0x1ED8, (wchar_t)0x1EDA, (wchar_t)0x1EDC, - (wchar_t)0x1EDE, (wchar_t)0x1EE0, (wchar_t)0x1EE2, (wchar_t)0x1EE4, (wchar_t)0x1EE6, (wchar_t)0x1EE8, (wchar_t)0x1EEA, (wchar_t)0x1EEC, (wchar_t)0x1EEE, - (wchar_t)0x1EF0, (wchar_t)0x1EF2, (wchar_t)0x1EF4, (wchar_t)0x1EF6, (wchar_t)0x1EF8, (wchar_t)0x1F08, (wchar_t)0x1F09, (wchar_t)0x1F0A, (wchar_t)0x1F0B, - (wchar_t)0x1F0C, (wchar_t)0x1F0D, (wchar_t)0x1F0E, (wchar_t)0x1F0F, (wchar_t)0x1F18, (wchar_t)0x1F19, (wchar_t)0x1F1A, (wchar_t)0x1F1B, (wchar_t)0x1F1C, - (wchar_t)0x1F1D, (wchar_t)0x1F28, (wchar_t)0x1F29, (wchar_t)0x1F2A, (wchar_t)0x1F2B, (wchar_t)0x1F2C, (wchar_t)0x1F2D, (wchar_t)0x1F2E, (wchar_t)0x1F2F, - (wchar_t)0x1F38, (wchar_t)0x1F39, (wchar_t)0x1F3A, (wchar_t)0x1F3B, (wchar_t)0x1F3C, (wchar_t)0x1F3D, (wchar_t)0x1F3E, (wchar_t)0x1F3F, (wchar_t)0x1F48, - (wchar_t)0x1F49, (wchar_t)0x1F4A, (wchar_t)0x1F4B, (wchar_t)0x1F4C, (wchar_t)0x1F4D, (wchar_t)0x1F59, (wchar_t)0x1F5B, (wchar_t)0x1F5D, (wchar_t)0x1F5F, - (wchar_t)0x1F68, (wchar_t)0x1F69, (wchar_t)0x1F6A, (wchar_t)0x1F6B, (wchar_t)0x1F6C, (wchar_t)0x1F6D, (wchar_t)0x1F6E, (wchar_t)0x1F6F, (wchar_t)0x1F88, - (wchar_t)0x1F89, (wchar_t)0x1F8A, (wchar_t)0x1F8B, (wchar_t)0x1F8C, (wchar_t)0x1F8D, (wchar_t)0x1F8E, (wchar_t)0x1F8F, (wchar_t)0x1F98, (wchar_t)0x1F99, - (wchar_t)0x1F9A, (wchar_t)0x1F9B, (wchar_t)0x1F9C, (wchar_t)0x1F9D, (wchar_t)0x1F9E, (wchar_t)0x1F9F, (wchar_t)0x1FA8, (wchar_t)0x1FA9, (wchar_t)0x1FAA, - (wchar_t)0x1FAB, (wchar_t)0x1FAC, (wchar_t)0x1FAD, (wchar_t)0x1FAE, (wchar_t)0x1FAF, (wchar_t)0x1FB8, (wchar_t)0x1FB9, (wchar_t)0x1FD8, (wchar_t)0x1FD9, - (wchar_t)0x1FE8, (wchar_t)0x1FE9, (wchar_t)0x24B6, (wchar_t)0x24B7, (wchar_t)0x24B8, (wchar_t)0x24B9, (wchar_t)0x24BA, (wchar_t)0x24BB, (wchar_t)0x24BC, - (wchar_t)0x24BD, (wchar_t)0x24BE, (wchar_t)0x24BF, (wchar_t)0x24C0, (wchar_t)0x24C1, (wchar_t)0x24C2, (wchar_t)0x24C3, (wchar_t)0x24C4, (wchar_t)0x24C5, - (wchar_t)0x24C6, (wchar_t)0x24C7, (wchar_t)0x24C8, (wchar_t)0x24C9, (wchar_t)0x24CA, (wchar_t)0x24CB, (wchar_t)0x24CC, (wchar_t)0x24CD, (wchar_t)0x24CE, - (wchar_t)0x24CF, (wchar_t)0xFF21, (wchar_t)0xFF22, (wchar_t)0xFF23, (wchar_t)0xFF24, (wchar_t)0xFF25, (wchar_t)0xFF26, (wchar_t)0xFF27, (wchar_t)0xFF28, - (wchar_t)0xFF29, (wchar_t)0xFF2A, (wchar_t)0xFF2B, (wchar_t)0xFF2C, (wchar_t)0xFF2D, (wchar_t)0xFF2E, (wchar_t)0xFF2F, (wchar_t)0xFF30, (wchar_t)0xFF31, - (wchar_t)0xFF32, (wchar_t)0xFF33, (wchar_t)0xFF34, (wchar_t)0xFF35, (wchar_t)0xFF36, (wchar_t)0xFF37, (wchar_t)0xFF38, (wchar_t)0xFF39, (wchar_t)0xFF3A + static wchar_t unicodeUppercase[] = { + (wchar_t)0x0041, (wchar_t)0x0042, (wchar_t)0x0043, (wchar_t)0x0044, (wchar_t)0x0045, + (wchar_t)0x0046, (wchar_t)0x0047, (wchar_t)0x0048, (wchar_t)0x0049, (wchar_t)0x004A, + (wchar_t)0x004B, (wchar_t)0x004C, (wchar_t)0x004D, (wchar_t)0x004E, (wchar_t)0x004F, + (wchar_t)0x0050, (wchar_t)0x0051, (wchar_t)0x0052, (wchar_t)0x0053, (wchar_t)0x0054, + (wchar_t)0x0055, (wchar_t)0x0056, (wchar_t)0x0057, (wchar_t)0x0058, (wchar_t)0x0059, + (wchar_t)0x005A, (wchar_t)0x00C0, (wchar_t)0x00C1, (wchar_t)0x00C2, (wchar_t)0x00C3, + (wchar_t)0x00C4, (wchar_t)0x00C5, (wchar_t)0x00C6, (wchar_t)0x00C7, (wchar_t)0x00C8, + (wchar_t)0x00C9, (wchar_t)0x00CA, (wchar_t)0x00CB, (wchar_t)0x00CC, (wchar_t)0x00CD, + (wchar_t)0x00CE, (wchar_t)0x00CF, (wchar_t)0x00D0, (wchar_t)0x00D1, (wchar_t)0x00D2, + (wchar_t)0x00D3, (wchar_t)0x00D4, (wchar_t)0x00D5, (wchar_t)0x00D6, (wchar_t)0x00D8, + (wchar_t)0x00D9, (wchar_t)0x00DA, (wchar_t)0x00DB, (wchar_t)0x00DC, (wchar_t)0x00DD, + (wchar_t)0x00DE, (wchar_t)0x0178, (wchar_t)0x0100, (wchar_t)0x0102, (wchar_t)0x0104, + (wchar_t)0x0106, (wchar_t)0x0108, (wchar_t)0x010A, (wchar_t)0x010C, (wchar_t)0x010E, + (wchar_t)0x0110, (wchar_t)0x0112, (wchar_t)0x0114, (wchar_t)0x0116, (wchar_t)0x0118, + (wchar_t)0x011A, (wchar_t)0x011C, (wchar_t)0x011E, (wchar_t)0x0120, (wchar_t)0x0122, + (wchar_t)0x0124, (wchar_t)0x0126, (wchar_t)0x0128, (wchar_t)0x012A, (wchar_t)0x012C, + (wchar_t)0x012E, (wchar_t)0x0049, (wchar_t)0x0132, (wchar_t)0x0134, (wchar_t)0x0136, + (wchar_t)0x0139, (wchar_t)0x013B, (wchar_t)0x013D, (wchar_t)0x013F, (wchar_t)0x0141, + (wchar_t)0x0143, (wchar_t)0x0145, (wchar_t)0x0147, (wchar_t)0x014A, (wchar_t)0x014C, + (wchar_t)0x014E, (wchar_t)0x0150, (wchar_t)0x0152, (wchar_t)0x0154, (wchar_t)0x0156, + (wchar_t)0x0158, (wchar_t)0x015A, (wchar_t)0x015C, (wchar_t)0x015E, (wchar_t)0x0160, + (wchar_t)0x0162, (wchar_t)0x0164, (wchar_t)0x0166, (wchar_t)0x0168, (wchar_t)0x016A, + (wchar_t)0x016C, (wchar_t)0x016E, (wchar_t)0x0170, (wchar_t)0x0172, (wchar_t)0x0174, + (wchar_t)0x0176, (wchar_t)0x0179, (wchar_t)0x017B, (wchar_t)0x017D, (wchar_t)0x0182, + (wchar_t)0x0184, (wchar_t)0x0187, (wchar_t)0x018B, (wchar_t)0x0191, (wchar_t)0x0198, + (wchar_t)0x01A0, (wchar_t)0x01A2, (wchar_t)0x01A4, (wchar_t)0x01A7, (wchar_t)0x01AC, + (wchar_t)0x01AF, (wchar_t)0x01B3, (wchar_t)0x01B5, (wchar_t)0x01B8, (wchar_t)0x01BC, + (wchar_t)0x01C4, (wchar_t)0x01C7, (wchar_t)0x01CA, (wchar_t)0x01CD, (wchar_t)0x01CF, + (wchar_t)0x01D1, (wchar_t)0x01D3, (wchar_t)0x01D5, (wchar_t)0x01D7, (wchar_t)0x01D9, + (wchar_t)0x01DB, (wchar_t)0x01DE, (wchar_t)0x01E0, (wchar_t)0x01E2, (wchar_t)0x01E4, + (wchar_t)0x01E6, (wchar_t)0x01E8, (wchar_t)0x01EA, (wchar_t)0x01EC, (wchar_t)0x01EE, + (wchar_t)0x01F1, (wchar_t)0x01F4, (wchar_t)0x01FA, (wchar_t)0x01FC, (wchar_t)0x01FE, + (wchar_t)0x0200, (wchar_t)0x0202, (wchar_t)0x0204, (wchar_t)0x0206, (wchar_t)0x0208, + (wchar_t)0x020A, (wchar_t)0x020C, (wchar_t)0x020E, (wchar_t)0x0210, (wchar_t)0x0212, + (wchar_t)0x0214, (wchar_t)0x0216, (wchar_t)0x0181, (wchar_t)0x0186, (wchar_t)0x018A, + (wchar_t)0x018E, (wchar_t)0x018F, (wchar_t)0x0190, (wchar_t)0x0193, (wchar_t)0x0194, + (wchar_t)0x0197, (wchar_t)0x0196, (wchar_t)0x019C, (wchar_t)0x019D, (wchar_t)0x019F, + (wchar_t)0x01A9, (wchar_t)0x01AE, (wchar_t)0x01B1, (wchar_t)0x01B2, (wchar_t)0x01B7, + (wchar_t)0x0386, (wchar_t)0x0388, (wchar_t)0x0389, (wchar_t)0x038A, (wchar_t)0x0391, + (wchar_t)0x0392, (wchar_t)0x0393, (wchar_t)0x0394, (wchar_t)0x0395, (wchar_t)0x0396, + (wchar_t)0x0397, (wchar_t)0x0398, (wchar_t)0x0399, (wchar_t)0x039A, (wchar_t)0x039B, + (wchar_t)0x039C, (wchar_t)0x039D, (wchar_t)0x039E, (wchar_t)0x039F, (wchar_t)0x03A0, + (wchar_t)0x03A1, (wchar_t)0x03A3, (wchar_t)0x03A4, (wchar_t)0x03A5, (wchar_t)0x03A6, + (wchar_t)0x03A7, (wchar_t)0x03A8, (wchar_t)0x03A9, (wchar_t)0x03AA, (wchar_t)0x03AB, + (wchar_t)0x038C, (wchar_t)0x038E, (wchar_t)0x038F, (wchar_t)0x03E2, (wchar_t)0x03E4, + (wchar_t)0x03E6, (wchar_t)0x03E8, (wchar_t)0x03EA, (wchar_t)0x03EC, (wchar_t)0x03EE, + (wchar_t)0x0410, (wchar_t)0x0411, (wchar_t)0x0412, (wchar_t)0x0413, (wchar_t)0x0414, + (wchar_t)0x0415, (wchar_t)0x0416, (wchar_t)0x0417, (wchar_t)0x0418, (wchar_t)0x0419, + (wchar_t)0x041A, (wchar_t)0x041B, (wchar_t)0x041C, (wchar_t)0x041D, (wchar_t)0x041E, + (wchar_t)0x041F, (wchar_t)0x0420, (wchar_t)0x0421, (wchar_t)0x0422, (wchar_t)0x0423, + (wchar_t)0x0424, (wchar_t)0x0425, (wchar_t)0x0426, (wchar_t)0x0427, (wchar_t)0x0428, + (wchar_t)0x0429, (wchar_t)0x042A, (wchar_t)0x042B, (wchar_t)0x042C, (wchar_t)0x042D, + (wchar_t)0x042E, (wchar_t)0x042F, (wchar_t)0x0401, (wchar_t)0x0402, (wchar_t)0x0403, + (wchar_t)0x0404, (wchar_t)0x0405, (wchar_t)0x0406, (wchar_t)0x0407, (wchar_t)0x0408, + (wchar_t)0x0409, (wchar_t)0x040A, (wchar_t)0x040B, (wchar_t)0x040C, (wchar_t)0x040E, + (wchar_t)0x040F, (wchar_t)0x0460, (wchar_t)0x0462, (wchar_t)0x0464, (wchar_t)0x0466, + (wchar_t)0x0468, (wchar_t)0x046A, (wchar_t)0x046C, (wchar_t)0x046E, (wchar_t)0x0470, + (wchar_t)0x0472, (wchar_t)0x0474, (wchar_t)0x0476, (wchar_t)0x0478, (wchar_t)0x047A, + (wchar_t)0x047C, (wchar_t)0x047E, (wchar_t)0x0480, (wchar_t)0x0490, (wchar_t)0x0492, + (wchar_t)0x0494, (wchar_t)0x0496, (wchar_t)0x0498, (wchar_t)0x049A, (wchar_t)0x049C, + (wchar_t)0x049E, (wchar_t)0x04A0, (wchar_t)0x04A2, (wchar_t)0x04A4, (wchar_t)0x04A6, + (wchar_t)0x04A8, (wchar_t)0x04AA, (wchar_t)0x04AC, (wchar_t)0x04AE, (wchar_t)0x04B0, + (wchar_t)0x04B2, (wchar_t)0x04B4, (wchar_t)0x04B6, (wchar_t)0x04B8, (wchar_t)0x04BA, + (wchar_t)0x04BC, (wchar_t)0x04BE, (wchar_t)0x04C1, (wchar_t)0x04C3, (wchar_t)0x04C7, + (wchar_t)0x04CB, (wchar_t)0x04D0, (wchar_t)0x04D2, (wchar_t)0x04D4, (wchar_t)0x04D6, + (wchar_t)0x04D8, (wchar_t)0x04DA, (wchar_t)0x04DC, (wchar_t)0x04DE, (wchar_t)0x04E0, + (wchar_t)0x04E2, (wchar_t)0x04E4, (wchar_t)0x04E6, (wchar_t)0x04E8, (wchar_t)0x04EA, + (wchar_t)0x04EE, (wchar_t)0x04F0, (wchar_t)0x04F2, (wchar_t)0x04F4, (wchar_t)0x04F8, + (wchar_t)0x0531, (wchar_t)0x0532, (wchar_t)0x0533, (wchar_t)0x0534, (wchar_t)0x0535, + (wchar_t)0x0536, (wchar_t)0x0537, (wchar_t)0x0538, (wchar_t)0x0539, (wchar_t)0x053A, + (wchar_t)0x053B, (wchar_t)0x053C, (wchar_t)0x053D, (wchar_t)0x053E, (wchar_t)0x053F, + (wchar_t)0x0540, (wchar_t)0x0541, (wchar_t)0x0542, (wchar_t)0x0543, (wchar_t)0x0544, + (wchar_t)0x0545, (wchar_t)0x0546, (wchar_t)0x0547, (wchar_t)0x0548, (wchar_t)0x0549, + (wchar_t)0x054A, (wchar_t)0x054B, (wchar_t)0x054C, (wchar_t)0x054D, (wchar_t)0x054E, + (wchar_t)0x054F, (wchar_t)0x0550, (wchar_t)0x0551, (wchar_t)0x0552, (wchar_t)0x0553, + (wchar_t)0x0554, (wchar_t)0x0555, (wchar_t)0x0556, (wchar_t)0x10A0, (wchar_t)0x10A1, + (wchar_t)0x10A2, (wchar_t)0x10A3, (wchar_t)0x10A4, (wchar_t)0x10A5, (wchar_t)0x10A6, + (wchar_t)0x10A7, (wchar_t)0x10A8, (wchar_t)0x10A9, (wchar_t)0x10AA, (wchar_t)0x10AB, + (wchar_t)0x10AC, (wchar_t)0x10AD, (wchar_t)0x10AE, (wchar_t)0x10AF, (wchar_t)0x10B0, + (wchar_t)0x10B1, (wchar_t)0x10B2, (wchar_t)0x10B3, (wchar_t)0x10B4, (wchar_t)0x10B5, + (wchar_t)0x10B6, (wchar_t)0x10B7, (wchar_t)0x10B8, (wchar_t)0x10B9, (wchar_t)0x10BA, + (wchar_t)0x10BB, (wchar_t)0x10BC, (wchar_t)0x10BD, (wchar_t)0x10BE, (wchar_t)0x10BF, + (wchar_t)0x10C0, (wchar_t)0x10C1, (wchar_t)0x10C2, (wchar_t)0x10C3, (wchar_t)0x10C4, + (wchar_t)0x10C5, (wchar_t)0x1E00, (wchar_t)0x1E02, (wchar_t)0x1E04, (wchar_t)0x1E06, + (wchar_t)0x1E08, (wchar_t)0x1E0A, (wchar_t)0x1E0C, (wchar_t)0x1E0E, (wchar_t)0x1E10, + (wchar_t)0x1E12, (wchar_t)0x1E14, (wchar_t)0x1E16, (wchar_t)0x1E18, (wchar_t)0x1E1A, + (wchar_t)0x1E1C, (wchar_t)0x1E1E, (wchar_t)0x1E20, (wchar_t)0x1E22, (wchar_t)0x1E24, + (wchar_t)0x1E26, (wchar_t)0x1E28, (wchar_t)0x1E2A, (wchar_t)0x1E2C, (wchar_t)0x1E2E, + (wchar_t)0x1E30, (wchar_t)0x1E32, (wchar_t)0x1E34, (wchar_t)0x1E36, (wchar_t)0x1E38, + (wchar_t)0x1E3A, (wchar_t)0x1E3C, (wchar_t)0x1E3E, (wchar_t)0x1E40, (wchar_t)0x1E42, + (wchar_t)0x1E44, (wchar_t)0x1E46, (wchar_t)0x1E48, (wchar_t)0x1E4A, (wchar_t)0x1E4C, + (wchar_t)0x1E4E, (wchar_t)0x1E50, (wchar_t)0x1E52, (wchar_t)0x1E54, (wchar_t)0x1E56, + (wchar_t)0x1E58, (wchar_t)0x1E5A, (wchar_t)0x1E5C, (wchar_t)0x1E5E, (wchar_t)0x1E60, + (wchar_t)0x1E62, (wchar_t)0x1E64, (wchar_t)0x1E66, (wchar_t)0x1E68, (wchar_t)0x1E6A, + (wchar_t)0x1E6C, (wchar_t)0x1E6E, (wchar_t)0x1E70, (wchar_t)0x1E72, (wchar_t)0x1E74, + (wchar_t)0x1E76, (wchar_t)0x1E78, (wchar_t)0x1E7A, (wchar_t)0x1E7C, (wchar_t)0x1E7E, + (wchar_t)0x1E80, (wchar_t)0x1E82, (wchar_t)0x1E84, (wchar_t)0x1E86, (wchar_t)0x1E88, + (wchar_t)0x1E8A, (wchar_t)0x1E8C, (wchar_t)0x1E8E, (wchar_t)0x1E90, (wchar_t)0x1E92, + (wchar_t)0x1E94, (wchar_t)0x1EA0, (wchar_t)0x1EA2, (wchar_t)0x1EA4, (wchar_t)0x1EA6, + (wchar_t)0x1EA8, (wchar_t)0x1EAA, (wchar_t)0x1EAC, (wchar_t)0x1EAE, (wchar_t)0x1EB0, + (wchar_t)0x1EB2, (wchar_t)0x1EB4, (wchar_t)0x1EB6, (wchar_t)0x1EB8, (wchar_t)0x1EBA, + (wchar_t)0x1EBC, (wchar_t)0x1EBE, (wchar_t)0x1EC0, (wchar_t)0x1EC2, (wchar_t)0x1EC4, + (wchar_t)0x1EC6, (wchar_t)0x1EC8, (wchar_t)0x1ECA, (wchar_t)0x1ECC, (wchar_t)0x1ECE, + (wchar_t)0x1ED0, (wchar_t)0x1ED2, (wchar_t)0x1ED4, (wchar_t)0x1ED6, (wchar_t)0x1ED8, + (wchar_t)0x1EDA, (wchar_t)0x1EDC, (wchar_t)0x1EDE, (wchar_t)0x1EE0, (wchar_t)0x1EE2, + (wchar_t)0x1EE4, (wchar_t)0x1EE6, (wchar_t)0x1EE8, (wchar_t)0x1EEA, (wchar_t)0x1EEC, + (wchar_t)0x1EEE, (wchar_t)0x1EF0, (wchar_t)0x1EF2, (wchar_t)0x1EF4, (wchar_t)0x1EF6, + (wchar_t)0x1EF8, (wchar_t)0x1F08, (wchar_t)0x1F09, (wchar_t)0x1F0A, (wchar_t)0x1F0B, + (wchar_t)0x1F0C, (wchar_t)0x1F0D, (wchar_t)0x1F0E, (wchar_t)0x1F0F, (wchar_t)0x1F18, + (wchar_t)0x1F19, (wchar_t)0x1F1A, (wchar_t)0x1F1B, (wchar_t)0x1F1C, (wchar_t)0x1F1D, + (wchar_t)0x1F28, (wchar_t)0x1F29, (wchar_t)0x1F2A, (wchar_t)0x1F2B, (wchar_t)0x1F2C, + (wchar_t)0x1F2D, (wchar_t)0x1F2E, (wchar_t)0x1F2F, (wchar_t)0x1F38, (wchar_t)0x1F39, + (wchar_t)0x1F3A, (wchar_t)0x1F3B, (wchar_t)0x1F3C, (wchar_t)0x1F3D, (wchar_t)0x1F3E, + (wchar_t)0x1F3F, (wchar_t)0x1F48, (wchar_t)0x1F49, (wchar_t)0x1F4A, (wchar_t)0x1F4B, + (wchar_t)0x1F4C, (wchar_t)0x1F4D, (wchar_t)0x1F59, (wchar_t)0x1F5B, (wchar_t)0x1F5D, + (wchar_t)0x1F5F, (wchar_t)0x1F68, (wchar_t)0x1F69, (wchar_t)0x1F6A, (wchar_t)0x1F6B, + (wchar_t)0x1F6C, (wchar_t)0x1F6D, (wchar_t)0x1F6E, (wchar_t)0x1F6F, (wchar_t)0x1F88, + (wchar_t)0x1F89, (wchar_t)0x1F8A, (wchar_t)0x1F8B, (wchar_t)0x1F8C, (wchar_t)0x1F8D, + (wchar_t)0x1F8E, (wchar_t)0x1F8F, (wchar_t)0x1F98, (wchar_t)0x1F99, (wchar_t)0x1F9A, + (wchar_t)0x1F9B, (wchar_t)0x1F9C, (wchar_t)0x1F9D, (wchar_t)0x1F9E, (wchar_t)0x1F9F, + (wchar_t)0x1FA8, (wchar_t)0x1FA9, (wchar_t)0x1FAA, (wchar_t)0x1FAB, (wchar_t)0x1FAC, + (wchar_t)0x1FAD, (wchar_t)0x1FAE, (wchar_t)0x1FAF, (wchar_t)0x1FB8, (wchar_t)0x1FB9, + (wchar_t)0x1FD8, (wchar_t)0x1FD9, (wchar_t)0x1FE8, (wchar_t)0x1FE9, (wchar_t)0x24B6, + (wchar_t)0x24B7, (wchar_t)0x24B8, (wchar_t)0x24B9, (wchar_t)0x24BA, (wchar_t)0x24BB, + (wchar_t)0x24BC, (wchar_t)0x24BD, (wchar_t)0x24BE, (wchar_t)0x24BF, (wchar_t)0x24C0, + (wchar_t)0x24C1, (wchar_t)0x24C2, (wchar_t)0x24C3, (wchar_t)0x24C4, (wchar_t)0x24C5, + (wchar_t)0x24C6, (wchar_t)0x24C7, (wchar_t)0x24C8, (wchar_t)0x24C9, (wchar_t)0x24CA, + (wchar_t)0x24CB, (wchar_t)0x24CC, (wchar_t)0x24CD, (wchar_t)0x24CE, (wchar_t)0x24CF, + (wchar_t)0xFF21, (wchar_t)0xFF22, (wchar_t)0xFF23, (wchar_t)0xFF24, (wchar_t)0xFF25, + (wchar_t)0xFF26, (wchar_t)0xFF27, (wchar_t)0xFF28, (wchar_t)0xFF29, (wchar_t)0xFF2A, + (wchar_t)0xFF2B, (wchar_t)0xFF2C, (wchar_t)0xFF2D, (wchar_t)0xFF2E, (wchar_t)0xFF2F, + (wchar_t)0xFF30, (wchar_t)0xFF31, (wchar_t)0xFF32, (wchar_t)0xFF33, (wchar_t)0xFF34, + (wchar_t)0xFF35, (wchar_t)0xFF36, (wchar_t)0xFF37, (wchar_t)0xFF38, (wchar_t)0xFF39, + (wchar_t)0xFF3A }; unsigned int chars2Unicode(const std::string& stringArg, size_t& cursor) @@ -183,27 +301,27 @@ namespace Utils // 0xxxxxxx, one byte character. if (checkCharType <= 0x7F) { // 0xxxxxxx - result = ((stringArg[cursor++])); + result = (stringArg[cursor++]); } // 11110xxx, four byte character. else if (checkCharType >= 0xF0) { // 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx result = (stringArg[cursor++] & 0x07) << 18; result |= (stringArg[cursor++] & 0x3F) << 12; - result |= (stringArg[cursor++] & 0x3F) << 6; + result |= (stringArg[cursor++] & 0x3F) << 6; result |= stringArg[cursor++] & 0x3F; } // 1110xxxx, three byte character. else if (checkCharType >= 0xE0) { // 1110xxxx 10xxxxxx 10xxxxxx result = (stringArg[cursor++] & 0x0F) << 12; - result |= (stringArg[cursor++] & 0x3F) << 6; + result |= (stringArg[cursor++] & 0x3F) << 6; result |= stringArg[cursor++] & 0x3F; } // 110xxxxx, two byte character. else if (checkCharType >= 0xC0) { // 110xxxxx 10xxxxxx - result = (stringArg[cursor++] & 0x1F) << 6; + result = (stringArg[cursor++] & 0x1F) << 6; result |= stringArg[cursor++] & 0x3F; } else { @@ -220,25 +338,25 @@ namespace Utils // Normal UTF-8 ASCII character. if (unicodeArg < 0x80) { - result += ((unicodeArg ) & 0xFF); + result += (unicodeArg & 0xFF); } // Two-byte character. - else if (unicodeArg < 0x800) { - result += ((unicodeArg >> 6) & 0xFF) | 0xC0; - result += ((unicodeArg ) & 0x3F) | 0x80; + else if (unicodeArg < 0x800) { + result += ((unicodeArg >> 6) & 0xFF) | 0xC0; + result += (unicodeArg & 0x3F) | 0x80; } // Three-byte character. else if (unicodeArg < 0xFFFF) { result += ((unicodeArg >> 12) & 0xFF) | 0xE0; - result += ((unicodeArg >> 6) & 0x3F) | 0x80; - result += ((unicodeArg ) & 0x3F) | 0x80; + result += ((unicodeArg >> 6) & 0x3F) | 0x80; + result += (unicodeArg & 0x3F) | 0x80; } // Four-byte character. else if (unicodeArg <= 0x1fffff) { result += ((unicodeArg >> 18) & 0xFF) | 0xF0; result += ((unicodeArg >> 12) & 0x3F) | 0x80; - result += ((unicodeArg >> 6) & 0x3F) | 0x80; - result += ((unicodeArg ) & 0x3F) | 0x80; + result += ((unicodeArg >> 6) & 0x3F) | 0x80; + result += (unicodeArg & 0x3F) | 0x80; } else { // Error, invalid character. @@ -432,15 +550,16 @@ namespace Utils return stringArg.substr(strBegin, strEnd - strBegin + 1); } - std::string replace(const std::string& stringArg, const std::string& replace, - const std::string& with) + std::string replace(const std::string& stringArg, + const std::string& replace, + const std::string& with) { std::string stringReplace = stringArg; size_t pos; while ((pos = stringReplace.find(replace)) != std::string::npos) - stringReplace = stringReplace.replace(pos, replace.length(), - with.c_str(), with.length()); + stringReplace = + stringReplace.replace(pos, replace.length(), with.c_str(), with.length()); return stringReplace; } @@ -497,7 +616,9 @@ namespace Utils } std::vector delimitedStringToVector(const std::string& stringArg, - const std::string& delimiter, bool sort, bool caseInsensitive) + const std::string& delimiter, + bool sort, + bool caseInsensitive) { std::vector vectorResult; size_t start = 0; @@ -513,8 +634,9 @@ namespace Utils if (sort) { if (caseInsensitive) std::sort(std::begin(vectorResult), std::end(vectorResult), - [](std::string a, std::string b) { - return std::toupper(a.front()) < std::toupper(b.front()); }); + [](std::string a, std::string b) { + return std::toupper(a.front()) < std::toupper(b.front()); + }); else std::sort(vectorResult.begin(), vectorResult.end()); } @@ -523,19 +645,23 @@ namespace Utils } std::string vectorToDelimitedString(std::vector vectorArg, - const std::string& delimiter, bool caseInsensitive) + const std::string& delimiter, + bool caseInsensitive) { std::string resultString; - if (caseInsensitive) + if (caseInsensitive) { std::sort(std::begin(vectorArg), std::end(vectorArg), - [](std::string a, std::string b) { - return std::toupper(a.front()) < std::toupper(b.front()); }); - else + [](std::string a, std::string b) { + return std::toupper(a.front()) < std::toupper(b.front()); + }); + } + else { std::sort(vectorArg.begin(), vectorArg.end()); + } for (std::vector::const_iterator it = vectorArg.cbegin(); - it != vectorArg.cend(); it++) + it != vectorArg.cend(); it++) resultString += (resultString.length() ? delimiter : "") + (*it); return resultString; @@ -551,6 +677,6 @@ namespace Utils return buffer; } - } // String:: + } // namespace String -} // Utils:: +} // namespace Utils diff --git a/es-core/src/utils/StringUtil.h b/es-core/src/utils/StringUtil.h index 92e39d181..98b1ecb23 100644 --- a/es-core/src/utils/StringUtil.h +++ b/es-core/src/utils/StringUtil.h @@ -27,19 +27,24 @@ namespace Utils std::string toLower(const std::string& stringArg); std::string toUpper(const std::string& stringArg); std::string trim(const std::string& stringArg); - std::string replace(const std::string& stringArg, const std::string& replace, - const std::string& with); + std::string replace(const std::string& stringArg, + const std::string& replace, + const std::string& with); std::wstring stringToWideString(const std::string& stringArg); std::string wideStringToString(const std::wstring& stringArg); bool startsWith(const std::string& stringArg, const std::string& start); bool endsWith(const std::string& stringArg, const std::string& end); std::string removeParenthesis(const std::string& stringArg); std::vector delimitedStringToVector(const std::string& stringArg, - const std::string& delimiter, bool sort = false, bool caseInsensitive = false); + const std::string& delimiter, + bool sort = false, + bool caseInsensitive = false); std::string vectorToDelimitedString(std::vector vectorArg, - const std::string& delimiter, bool caseInsensitive = false); + const std::string& delimiter, + bool caseInsensitive = false); std::string scramble(const std::string& input, const std::string& key); - } -} + } // namespace String + +} // namespace Utils #endif // ES_CORE_UTILS_STRING_UTIL_H diff --git a/es-core/src/utils/TimeUtil.cpp b/es-core/src/utils/TimeUtil.cpp index 0830615c5..6d4a46cb1 100644 --- a/es-core/src/utils/TimeUtil.cpp +++ b/es-core/src/utils/TimeUtil.cpp @@ -24,41 +24,42 @@ namespace Utils DateTime::DateTime(const time_t& time) { + // Set time. setTime(time); } DateTime::DateTime(const tm& timeStruct) { + // Set time struct. setTimeStruct(timeStruct); } DateTime::DateTime(const std::string& isoString) { + // Set ISO string. setIsoString(isoString); } - DateTime::~DateTime() - { - } - void DateTime::setTime(const time_t& time) { mTime = (time < 0) ? 0 : time; - #if defined(_WIN64) +#if defined(_WIN64) localtime_s(&mTimeStruct, &mTime); - #else +#else localtime_r(&mTime, &mTimeStruct); - #endif +#endif mIsoString = timeToString(mTime); } void DateTime::setTimeStruct(const tm& timeStruct) { + // Set time based on struct. setTime(mktime(const_cast(&timeStruct))); } void DateTime::setIsoString(const std::string& isoString) { + // Set time based on ISO string. setTime(stringToTime(isoString)); } @@ -71,10 +72,6 @@ namespace Utils mSeconds = mTotalSeconds % 60; } - Duration::~Duration() - { - } - time_t now() { time_t time; @@ -86,7 +83,7 @@ namespace Utils { const char* s = string.c_str(); const char* f = format.c_str(); - tm timeStruct = { 0, 0, 0, 1, 0, 0, 0, 0, -1 }; + tm timeStruct = { 0, 0, 0, 1, 0, 0, 0, 0, -1 }; size_t parsedChars = 0; if (string == "19700101T010000") @@ -97,71 +94,65 @@ namespace Utils f++; switch (*f++) { - // Year, including century [1970,xxxx] - case 'Y': { - if ((parsedChars + 4) <= string.length()) { - timeStruct.tm_year = (*s++ - '0') * 1000; - timeStruct.tm_year += (*s++ - '0') * 100; - timeStruct.tm_year += (*s++ - '0') * 10; - timeStruct.tm_year += (*s++ - '0'); - if (timeStruct.tm_year >= 1900) - timeStruct.tm_year -= 1900; - } - parsedChars += 4; - } - break; + // Year, including century [1970,xxxx] + case 'Y': { + if ((parsedChars + 4) <= string.length()) { + timeStruct.tm_year = (*s++ - '0') * 1000; + timeStruct.tm_year += (*s++ - '0') * 100; + timeStruct.tm_year += (*s++ - '0') * 10; + timeStruct.tm_year += (*s++ - '0'); + if (timeStruct.tm_year >= 1900) + timeStruct.tm_year -= 1900; + } + parsedChars += 4; + } break; - // Month number [01,12] - case 'm': { - if ((parsedChars + 2) <= string.length()) { - timeStruct.tm_mon = (*s++ - '0') * 10; - timeStruct.tm_mon += (*s++ - '0'); - if (timeStruct.tm_mon >= 1) - timeStruct.tm_mon -= 1; - } - parsedChars += 2; - } - break; + // Month number [01,12] + case 'm': { + if ((parsedChars + 2) <= string.length()) { + timeStruct.tm_mon = (*s++ - '0') * 10; + timeStruct.tm_mon += (*s++ - '0'); + if (timeStruct.tm_mon >= 1) + timeStruct.tm_mon -= 1; + } + parsedChars += 2; + } break; - // Day of the month [01,31] - case 'd': { - if ((parsedChars + 2) <= string.length()) { - timeStruct.tm_mday = (*s++ - '0') * 10; - timeStruct.tm_mday += (*s++ - '0'); - } - parsedChars += 2; - } - break; + // Day of the month [01,31] + case 'd': { + if ((parsedChars + 2) <= string.length()) { + timeStruct.tm_mday = (*s++ - '0') * 10; + timeStruct.tm_mday += (*s++ - '0'); + } + parsedChars += 2; + } break; - // Hour (24-hour clock) [00,23] - case 'H': { - if ((parsedChars + 2) <= string.length()) { - timeStruct.tm_hour = (*s++ - '0') * 10; - timeStruct.tm_hour += (*s++ - '0'); - } - parsedChars += 2; - } - break; + // Hour (24-hour clock) [00,23] + case 'H': { + if ((parsedChars + 2) <= string.length()) { + timeStruct.tm_hour = (*s++ - '0') * 10; + timeStruct.tm_hour += (*s++ - '0'); + } + parsedChars += 2; + } break; - // Minute [00,59] - case 'M': { - if ((parsedChars + 2) <= string.length()) { - timeStruct.tm_min = (*s++ - '0') * 10; - timeStruct.tm_min += (*s++ - '0'); - } - parsedChars += 2; - } - break; + // Minute [00,59] + case 'M': { + if ((parsedChars + 2) <= string.length()) { + timeStruct.tm_min = (*s++ - '0') * 10; + timeStruct.tm_min += (*s++ - '0'); + } + parsedChars += 2; + } break; - // Second [00,59] - case 'S': { - if ((parsedChars + 2) <= string.length()) { - timeStruct.tm_sec = (*s++ - '0') * 10; - timeStruct.tm_sec += (*s++ - '0'); - } - parsedChars += 2; - } - break; + // Second [00,59] + case 'S': { + if ((parsedChars + 2) <= string.length()) { + timeStruct.tm_sec = (*s++ - '0') * 10; + timeStruct.tm_sec += (*s++ - '0'); + } + parsedChars += 2; + } break; } } else { @@ -176,11 +167,11 @@ namespace Utils { const char* f = format.c_str(); tm timeStruct; - #if defined(_WIN64) +#if defined(_WIN64) localtime_s(&timeStruct, &time); - #else +#else localtime_r(&time, &timeStruct); - #endif +#endif char buf[256] = { '\0' }; char* s = buf; @@ -189,51 +180,45 @@ namespace Utils f++; switch (*f++) { - // Year, including century [1970,xxxx] - case 'Y': { - const int year = timeStruct.tm_year + 1900; - *s++ = static_cast((year - (year % 1000)) / 1000) + '0'; - *s++ = static_cast(((year % 1000) - (year % 100)) / 100) + '0'; - *s++ = static_cast(((year % 100) - (year % 10)) / 10) + '0'; - *s++ = static_cast(year % 10) + '0'; - } - break; + // Year, including century [1970,xxxx] + case 'Y': { + const int year = timeStruct.tm_year + 1900; + *s++ = static_cast((year - (year % 1000)) / 1000) + '0'; + *s++ = static_cast(((year % 1000) - (year % 100)) / 100) + '0'; + *s++ = static_cast(((year % 100) - (year % 10)) / 10) + '0'; + *s++ = static_cast(year % 10) + '0'; + } break; - // Month number [00,11] - case 'm': { - const int mon = timeStruct.tm_mon + 1; - *s++ = static_cast(mon / 10) + '0'; - *s++ = static_cast(mon % 10) + '0'; - } - break; + // Month number [00,11] + case 'm': { + const int mon = timeStruct.tm_mon + 1; + *s++ = static_cast(mon / 10) + '0'; + *s++ = static_cast(mon % 10) + '0'; + } break; - // Day of the month [01,31] - case 'd': { - *s++ = static_cast(timeStruct.tm_mday / 10) + '0'; - *s++ = static_cast(timeStruct.tm_mday % 10) + '0'; - } - break; + // Day of the month [01,31] + case 'd': { + *s++ = static_cast(timeStruct.tm_mday / 10) + '0'; + *s++ = static_cast(timeStruct.tm_mday % 10) + '0'; + } break; - // Hour (24-hour clock) [00,23] - case 'H': { - *s++ = static_cast(timeStruct.tm_hour / 10) + '0'; - *s++ = static_cast(timeStruct.tm_hour % 10) + '0'; - } - break; + // Hour (24-hour clock) [00,23] + case 'H': { + *s++ = static_cast(timeStruct.tm_hour / 10) + '0'; + *s++ = static_cast(timeStruct.tm_hour % 10) + '0'; + } break; - // Minute [00,59] - case 'M': { - *s++ = static_cast(timeStruct.tm_min / 10) + '0'; - *s++ = static_cast(timeStruct.tm_min % 10) + '0'; - } - break; + // Minute [00,59] + case 'M': { + *s++ = static_cast(timeStruct.tm_min / 10) + '0'; + *s++ = static_cast(timeStruct.tm_min % 10) + '0'; + } break; - // Second [00,59] - case 'S': { - *s++ = static_cast(timeStruct.tm_sec / 10) + '0'; - *s++ = static_cast(timeStruct.tm_sec % 10) + '0'; - } - break; + // Second [00,59] + case 'S': { + *s++ = static_cast(timeStruct.tm_sec / 10) + '0'; + *s++ = static_cast(timeStruct.tm_sec % 10) + '0'; + } break; } } else { @@ -260,6 +245,6 @@ namespace Utils return timeStruct.tm_yday + 1; } - } // Time:: + } // namespace Time -} // Utils:: +} // namespace Utils diff --git a/es-core/src/utils/TimeUtil.h b/es-core/src/utils/TimeUtil.h index 967eb7926..a92d4edd2 100644 --- a/es-core/src/utils/TimeUtil.h +++ b/es-core/src/utils/TimeUtil.h @@ -29,7 +29,7 @@ namespace Utils DateTime(const time_t& time); DateTime(const tm& timeStruct); DateTime(const std::string& isoString); - ~DateTime(); + ~DateTime() {} const bool operator<(const DateTime& other) const { return (mTime < other.mTime); } const bool operator<=(const DateTime& other) const { return (mTime <= other.mTime); } @@ -43,8 +43,8 @@ namespace Utils const time_t& getTime() const { return mTime; } void setTimeStruct(const tm& timeStruct); const tm& getTimeStruct() const { return mTimeStruct; } - void setIsoString (const std::string& isoString); - const std::string& getIsoString () const { return mIsoString; } + void setIsoString(const std::string& isoString); + const std::string& getIsoString() const { return mIsoString; } private: time_t mTime; @@ -56,7 +56,7 @@ namespace Utils { public: Duration(const time_t& time); - ~Duration(); + ~Duration() {} unsigned int getDays() const { return mDays; } unsigned int getHours() const { return mHours; } @@ -76,7 +76,8 @@ namespace Utils std::string timeToString(const time_t& time, const std::string& format = "%Y%m%dT%H%M%S"); int daysInMonth(const int year, const int month); int daysInYear(const int year); - } -} // Utils:: + } // namespace Time + +} // namespace Utils #endif // ES_CORE_UTILS_TIME_UTIL_H