From d7eeaea240b277adff6bf131088ec1bdac6a0cc5 Mon Sep 17 00:00:00 2001 From: Chris Thrasher Date: Tue, 25 Jun 2024 14:22:42 -0600 Subject: [PATCH] Add clang-tidy `readability-else-after-return` check --- .clang-tidy | 1 - examples/cocoa/NSString+stdstring.mm | 4 +- examples/voip/Client.cpp | 6 +- examples/vulkan/Vulkan.cpp | 2 +- include/SFML/Graphics/Rect.inl | 6 +- include/SFML/Graphics/Transform.inl | 6 +- src/SFML/Audio/SoundBuffer.cpp | 30 ++--- src/SFML/Audio/SoundFileReaderFlac.cpp | 36 ++---- src/SFML/Audio/SoundFileReaderOgg.cpp | 6 +- src/SFML/Audio/SoundFileWriterWav.cpp | 3 +- src/SFML/Graphics/Font.cpp | 44 +++---- src/SFML/Graphics/Image.cpp | 48 +++----- src/SFML/Graphics/RenderTexture.cpp | 6 +- src/SFML/Graphics/Shader.cpp | 43 ++++--- src/SFML/Graphics/Texture.cpp | 92 +++++++------- src/SFML/Graphics/VertexArray.cpp | 8 +- src/SFML/Network/Ftp.cpp | 32 +++-- src/SFML/Network/TcpSocket.cpp | 114 +++++++++--------- src/SFML/System/Err.cpp | 10 +- src/SFML/Window/Android/WindowImplAndroid.cpp | 2 +- src/SFML/Window/Context.cpp | 4 +- src/SFML/Window/DRM/InputImpl.cpp | 68 +++++------ src/SFML/Window/DRM/VideoModeImpl.cpp | 4 +- src/SFML/Window/GlContext.cpp | 50 +++----- src/SFML/Window/Unix/ClipboardImpl.cpp | 8 +- src/SFML/Window/Unix/CursorImpl.cpp | 4 +- src/SFML/Window/Unix/GlxContext.cpp | 10 +- src/SFML/Window/Unix/InputImpl.cpp | 6 +- src/SFML/Window/Unix/JoystickImpl.cpp | 8 +- src/SFML/Window/Unix/WindowImplX11.cpp | 30 ++--- src/SFML/Window/VideoMode.cpp | 12 +- src/SFML/Window/Win32/CursorImpl.cpp | 16 +-- src/SFML/Window/Win32/InputImpl.cpp | 6 +- src/SFML/Window/Win32/JoystickImpl.cpp | 10 +- src/SFML/Window/Window.cpp | 12 +- src/SFML/Window/iOS/ClipboardImpl.mm | 6 +- src/SFML/Window/iOS/SFAppDelegate.mm | 4 +- src/SFML/Window/macOS/CursorImpl.mm | 4 +- src/SFML/Window/macOS/SFContext.mm | 8 +- .../Window/macOS/SFOpenGLView+keyboard.mm | 8 +- 40 files changed, 335 insertions(+), 442 deletions(-) diff --git a/.clang-tidy b/.clang-tidy index 780876b7c..705cb24e5 100644 --- a/.clang-tidy +++ b/.clang-tidy @@ -63,7 +63,6 @@ Checks: > -readability-avoid-nested-conditional-operator, -readability-braces-around-statements, -readability-convert-member-functions-to-static, - -readability-else-after-return, -readability-function-cognitive-complexity, -readability-function-size, -readability-identifier-length, diff --git a/examples/cocoa/NSString+stdstring.mm b/examples/cocoa/NSString+stdstring.mm index 6d74ef0f6..577a07ffd 100644 --- a/examples/cocoa/NSString+stdstring.mm +++ b/examples/cocoa/NSString+stdstring.mm @@ -58,8 +58,8 @@ if (cstr != nullptr) return std::string(cstr); - else - return ""; + + return ""; } - (std::wstring)tostdwstring diff --git a/examples/voip/Client.cpp b/examples/voip/Client.cpp index cd906b00b..6c85ffe2b 100644 --- a/examples/voip/Client.cpp +++ b/examples/voip/Client.cpp @@ -58,10 +58,8 @@ private: std::cout << "Connected to server " << m_host << std::endl; return true; } - else - { - return false; - } + + return false; } //////////////////////////////////////////////////////////// diff --git a/examples/vulkan/Vulkan.cpp b/examples/vulkan/Vulkan.cpp index 57157f5d4..afa2a79a9 100644 --- a/examples/vulkan/Vulkan.cpp +++ b/examples/vulkan/Vulkan.cpp @@ -630,7 +630,7 @@ public: gpu = dev; break; } - else if (deviceProperties.deviceType == VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU) + if (deviceProperties.deviceType == VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU) { gpu = dev; } diff --git a/include/SFML/Graphics/Rect.inl b/include/SFML/Graphics/Rect.inl index 170a4fd76..898ef71de 100644 --- a/include/SFML/Graphics/Rect.inl +++ b/include/SFML/Graphics/Rect.inl @@ -103,10 +103,8 @@ constexpr std::optional> Rect::findIntersection(const Rect& rectan { return Rect({interLeft, interTop}, {interRight - interLeft, interBottom - interTop}); } - else - { - return std::nullopt; - } + + return std::nullopt; } diff --git a/include/SFML/Graphics/Transform.inl b/include/SFML/Graphics/Transform.inl index f6bc856ab..6250ebabf 100644 --- a/include/SFML/Graphics/Transform.inl +++ b/include/SFML/Graphics/Transform.inl @@ -85,10 +85,8 @@ constexpr Transform Transform::getInverse() const (m_matrix[5] * m_matrix[0] - m_matrix[1] * m_matrix[4]) / det}; // clang-format on } - else - { - return Identity; - } + + return Identity; } diff --git a/src/SFML/Audio/SoundBuffer.cpp b/src/SFML/Audio/SoundBuffer.cpp index ae9b331b0..7c58d2cf6 100644 --- a/src/SFML/Audio/SoundBuffer.cpp +++ b/src/SFML/Audio/SoundBuffer.cpp @@ -118,17 +118,15 @@ std::optional SoundBuffer::loadFromSamples( return std::nullopt; return soundBuffer; } - else - { - // Error... - err() << "Failed to load sound buffer from samples (" - << "array: " << samples << ", " - << "count: " << sampleCount << ", " - << "channels: " << channelCount << ", " - << "samplerate: " << sampleRate << ")" << std::endl; - return std::nullopt; - } + // Error... + err() << "Failed to load sound buffer from samples (" + << "array: " << samples << ", " + << "count: " << sampleCount << ", " + << "channels: " << channelCount << ", " + << "samplerate: " << sampleRate << ")" << std::endl; + + return std::nullopt; } @@ -143,10 +141,8 @@ bool SoundBuffer::saveToFile(const std::filesystem::path& filename) const return true; } - else - { - return false; - } + + return false; } @@ -233,10 +229,8 @@ std::optional SoundBuffer::initialize(InputSoundFile& file) return soundBuffer; } - else - { - return std::nullopt; - } + + return std::nullopt; } diff --git a/src/SFML/Audio/SoundFileReaderFlac.cpp b/src/SFML/Audio/SoundFileReaderFlac.cpp index 610084933..21875adca 100644 --- a/src/SFML/Audio/SoundFileReaderFlac.cpp +++ b/src/SFML/Audio/SoundFileReaderFlac.cpp @@ -51,15 +51,11 @@ FLAC__StreamDecoderReadStatus streamRead(const FLAC__StreamDecoder*, FLAC__byte *bytes = *count; return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE; } - else - { - return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM; - } - } - else - { - return FLAC__STREAM_DECODER_READ_STATUS_ABORT; + + return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM; } + + return FLAC__STREAM_DECODER_READ_STATUS_ABORT; } FLAC__StreamDecoderSeekStatus streamSeek(const FLAC__StreamDecoder*, FLAC__uint64 absoluteByteOffset, void* clientData) @@ -68,8 +64,8 @@ FLAC__StreamDecoderSeekStatus streamSeek(const FLAC__StreamDecoder*, FLAC__uint6 if (data->stream->seek(static_cast(absoluteByteOffset)).has_value()) return FLAC__STREAM_DECODER_SEEK_STATUS_OK; - else - return FLAC__STREAM_DECODER_SEEK_STATUS_ERROR; + + return FLAC__STREAM_DECODER_SEEK_STATUS_ERROR; } FLAC__StreamDecoderTellStatus streamTell(const FLAC__StreamDecoder*, FLAC__uint64* absoluteByteOffset, void* clientData) @@ -81,10 +77,8 @@ FLAC__StreamDecoderTellStatus streamTell(const FLAC__StreamDecoder*, FLAC__uint6 *absoluteByteOffset = *position; return FLAC__STREAM_DECODER_TELL_STATUS_OK; } - else - { - return FLAC__STREAM_DECODER_TELL_STATUS_ERROR; - } + + return FLAC__STREAM_DECODER_TELL_STATUS_ERROR; } FLAC__StreamDecoderLengthStatus streamLength(const FLAC__StreamDecoder*, FLAC__uint64* streamLength, void* clientData) @@ -96,10 +90,8 @@ FLAC__StreamDecoderLengthStatus streamLength(const FLAC__StreamDecoder*, FLAC__u *streamLength = *count; return FLAC__STREAM_DECODER_LENGTH_STATUS_OK; } - else - { - return FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR; - } + + return FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR; } FLAC__bool streamEof(const FLAC__StreamDecoder*, void* clientData) @@ -379,11 +371,9 @@ std::uint64_t SoundFileReaderFlac::read(std::int16_t* samples, std::uint64_t max m_clientData.leftovers.swap(leftovers); return maxCount; } - else - { - // We can use all the leftovers and decode new frames - std::copy(m_clientData.leftovers.begin(), m_clientData.leftovers.end(), samples); - } + + // We can use all the leftovers and decode new frames + std::copy(m_clientData.leftovers.begin(), m_clientData.leftovers.end(), samples); } // Reset the data that will be used in the callback diff --git a/src/SFML/Audio/SoundFileReaderOgg.cpp b/src/SFML/Audio/SoundFileReaderOgg.cpp index ee289e95e..9ea735657 100644 --- a/src/SFML/Audio/SoundFileReaderOgg.cpp +++ b/src/SFML/Audio/SoundFileReaderOgg.cpp @@ -83,10 +83,8 @@ bool SoundFileReaderOgg::check(InputStream& stream) ov_clear(&file); return true; } - else - { - return false; - } + + return false; } diff --git a/src/SFML/Audio/SoundFileWriterWav.cpp b/src/SFML/Audio/SoundFileWriterWav.cpp index ee3c220c0..f2abc0125 100644 --- a/src/SFML/Audio/SoundFileWriterWav.cpp +++ b/src/SFML/Audio/SoundFileWriterWav.cpp @@ -97,7 +97,8 @@ bool SoundFileWriterWav::open(const std::filesystem::path& filename, err() << "WAV sound file channel count 0" << std::endl; return false; } - else if (channelCount == 1) + + if (channelCount == 1) { m_remapTable[0] = 0; } diff --git a/src/SFML/Graphics/Font.cpp b/src/SFML/Graphics/Font.cpp index f1783a616..f4bb079ec 100644 --- a/src/SFML/Graphics/Font.cpp +++ b/src/SFML/Graphics/Font.cpp @@ -60,11 +60,11 @@ unsigned long read(FT_Stream rec, unsigned long offset, unsigned char* buffer, u { if (count > 0) return static_cast(stream->read(reinterpret_cast(buffer), count).value()); - else - return 0; + + return 0; } - else - return count > 0 ? 0 : 1; // error code is 0 if we're reading, or nonzero if we're seeking + + return count > 0 ? 0 : 1; // error code is 0 if we're reading, or nonzero if we're seeking } void close(FT_Stream) { @@ -313,12 +313,10 @@ const Glyph& Font::getGlyph(std::uint32_t codePoint, unsigned int characterSize, // Found: just return it return it->second; } - else - { - // Not found: we have to load it - const Glyph glyph = loadGlyph(codePoint, characterSize, bold, outlineThickness); - return glyphs.emplace(key, glyph).first->second; - } + + // Not found: we have to load it + const Glyph glyph = loadGlyph(codePoint, characterSize, bold, outlineThickness); + return glyphs.emplace(key, glyph).first->second; } @@ -364,11 +362,9 @@ float Font::getKerning(std::uint32_t first, std::uint32_t second, unsigned int c // Flooring is required as we use FT_KERNING_UNFITTED flag which is not quantized in 64 based grid return std::floor((secondLsbDelta - firstRsbDelta + static_cast(kerning.x) + 32) / float{1 << 6}); } - else - { - // Invalid font - return 0.f; - } + + // Invalid font + return 0.f; } @@ -383,10 +379,8 @@ float Font::getLineSpacing(unsigned int characterSize) const { return static_cast(face->size->metrics.height) / float{1 << 6}; } - else - { - return 0.f; - } + + return 0.f; } @@ -405,10 +399,8 @@ float Font::getUnderlinePosition(unsigned int characterSize) const return -static_cast(FT_MulFix(face->underline_position, face->size->metrics.y_scale)) / float{1 << 6}; } - else - { - return 0.f; - } + + return 0.f; } @@ -427,10 +419,8 @@ float Font::getUnderlineThickness(unsigned int characterSize) const return static_cast(FT_MulFix(face->underline_thickness, face->size->metrics.y_scale)) / float{1 << 6}; } - else - { - return 0.f; - } + + return 0.f; } diff --git a/src/SFML/Graphics/Image.cpp b/src/SFML/Graphics/Image.cpp index a09b2cdf8..8a4457e91 100644 --- a/src/SFML/Graphics/Image.cpp +++ b/src/SFML/Graphics/Image.cpp @@ -185,14 +185,13 @@ std::optional Image::loadFromFile(const std::filesystem::path& filename) { return Image(Vector2u(Vector2i(width, height)), {ptr.get(), ptr.get() + width * height * 4}); } - else - { - // Error, failed to load the image - err() << "Failed to load image\n" - << formatDebugPathInfo(filename) << "\nReason: " << stbi_failure_reason() << std::endl; - return std::nullopt; - } + + // Error, failed to load the image + err() << "Failed to load image\n" + << formatDebugPathInfo(filename) << "\nReason: " << stbi_failure_reason() << std::endl; + + return std::nullopt; } @@ -214,19 +213,15 @@ std::optional Image::loadFromMemory(const void* data, std::size_t size) { return Image(Vector2u(Vector2i(width, height)), {ptr.get(), ptr.get() + width * height * 4}); } - else - { - // Error, failed to load the image - err() << "Failed to load image from memory. Reason: " << stbi_failure_reason() << std::endl; - return std::nullopt; - } - } - else - { - err() << "Failed to load image from memory, no data provided" << std::endl; + // Error, failed to load the image + err() << "Failed to load image from memory. Reason: " << stbi_failure_reason() << std::endl; + return std::nullopt; } + + err() << "Failed to load image from memory, no data provided" << std::endl; + return std::nullopt; } @@ -256,12 +251,11 @@ std::optional Image::loadFromStream(InputStream& stream) { return Image(Vector2u(Vector2i(width, height)), {ptr.get(), ptr.get() + width * height * 4}); } - else - { - // Error, failed to load the image - err() << "Failed to load image from stream. Reason: " << stbi_failure_reason() << std::endl; - return std::nullopt; - } + + // Error, failed to load the image + err() << "Failed to load image from stream. Reason: " << stbi_failure_reason() << std::endl; + + return std::nullopt; } @@ -503,11 +497,9 @@ const std::uint8_t* Image::getPixelsPtr() const { return m_pixels.data(); } - else - { - err() << "Trying to access the pixels of an empty image" << std::endl; - return nullptr; - } + + err() << "Trying to access the pixels of an empty image" << std::endl; + return nullptr; } diff --git a/src/SFML/Graphics/RenderTexture.cpp b/src/SFML/Graphics/RenderTexture.cpp index c149b7bb1..a631c0ef7 100644 --- a/src/SFML/Graphics/RenderTexture.cpp +++ b/src/SFML/Graphics/RenderTexture.cpp @@ -99,10 +99,8 @@ unsigned int RenderTexture::getMaximumAntialiasingLevel() { return priv::RenderTextureImplFBO::getMaximumAntialiasingLevel(); } - else - { - return priv::RenderTextureImplDefault::getMaximumAntialiasingLevel(); - } + + return priv::RenderTextureImplDefault::getMaximumAntialiasingLevel(); } diff --git a/src/SFML/Graphics/Shader.cpp b/src/SFML/Graphics/Shader.cpp index ab9bca871..1963c6b14 100644 --- a/src/SFML/Graphics/Shader.cpp +++ b/src/SFML/Graphics/Shader.cpp @@ -95,10 +95,8 @@ bool getFileContents(const std::filesystem::path& filename, std::vector& b buffer.push_back('\0'); return true; } - else - { - return false; - } + + return false; } // Read the contents of a stream into an array of char @@ -283,10 +281,11 @@ std::optional Shader::loadFromFile(const std::filesystem::path& filename // Compile the shader program if (type == Type::Vertex) return compile(shader.data(), {}, {}); - else if (type == Type::Geometry) + + if (type == Type::Geometry) return compile({}, shader.data(), {}); - else - return compile({}, {}, shader.data()); + + return compile({}, {}, shader.data()); } @@ -355,10 +354,11 @@ std::optional Shader::loadFromMemory(std::string_view shader, Type type) // Compile the shader program if (type == Type::Vertex) return compile(shader, {}, {}); - else if (type == Type::Geometry) + + if (type == Type::Geometry) return compile({}, shader, {}); - else - return compile({}, {}, shader); + + return compile({}, {}, shader); } @@ -394,10 +394,11 @@ std::optional Shader::loadFromStream(InputStream& stream, Type type) // Compile the shader program if (type == Type::Vertex) return compile(shader.data(), {}, {}); - else if (type == Type::Geometry) + + if (type == Type::Geometry) return compile({}, shader.data(), {}); - else - return compile({}, {}, shader.data()); + + return compile({}, {}, shader.data()); } @@ -939,17 +940,15 @@ int Shader::getUniformLocation(const std::string& name) // Already in cache, return it return it->second; } - else - { - // Not in cache, request the location from OpenGL - const int location = GLEXT_glGetUniformLocation(castToGlHandle(m_shaderProgram), name.c_str()); - m_uniforms.emplace(name, location); - if (location == -1) - err() << "Uniform " << std::quoted(name) << " not found in shader" << std::endl; + // Not in cache, request the location from OpenGL + const int location = GLEXT_glGetUniformLocation(castToGlHandle(m_shaderProgram), name.c_str()); + m_uniforms.emplace(name, location); - return location; - } + if (location == -1) + err() << "Uniform " << std::quoted(name) << " not found in shader" << std::endl; + + return location; } } // namespace sf diff --git a/src/SFML/Graphics/Texture.cpp b/src/SFML/Graphics/Texture.cpp index 76174c2c1..6d7a357b1 100644 --- a/src/SFML/Graphics/Texture.cpp +++ b/src/SFML/Graphics/Texture.cpp @@ -312,55 +312,49 @@ std::optional Texture::loadFromImage(const Image& image, bool sRgb, con texture->update(image); return texture; } - else - { - // Error message generated in called function. - return std::nullopt; - } + + // Error message generated in called function. + return std::nullopt; } - else + + // Load a sub-area of the image + + // Adjust the rectangle to the size of the image + IntRect rectangle = area; + rectangle.position.x = std::max(rectangle.position.x, 0); + rectangle.position.y = std::max(rectangle.position.y, 0); + rectangle.size.x = std::min(rectangle.size.x, size.x - rectangle.position.x); + rectangle.size.y = std::min(rectangle.size.y, size.y - rectangle.position.y); + + // Create the texture and upload the pixels + if (auto texture = sf::Texture::create(Vector2u(rectangle.size), sRgb)) { - // Load a sub-area of the image + const TransientContextLock lock; - // Adjust the rectangle to the size of the image - IntRect rectangle = area; - rectangle.position.x = std::max(rectangle.position.x, 0); - rectangle.position.y = std::max(rectangle.position.y, 0); - rectangle.size.x = std::min(rectangle.size.x, size.x - rectangle.position.x); - rectangle.size.y = std::min(rectangle.size.y, size.y - rectangle.position.y); + // Make sure that the current texture binding will be preserved + const priv::TextureSaver save; - // Create the texture and upload the pixels - if (auto texture = sf::Texture::create(Vector2u(rectangle.size), sRgb)) + // Copy the pixels to the texture, row by row + const std::uint8_t* pixels = image.getPixelsPtr() + 4 * (rectangle.position.x + (size.x * rectangle.position.y)); + glCheck(glBindTexture(GL_TEXTURE_2D, texture->m_texture)); + for (int i = 0; i < rectangle.size.y; ++i) { - const TransientContextLock lock; - - // Make sure that the current texture binding will be preserved - const priv::TextureSaver save; - - // Copy the pixels to the texture, row by row - const std::uint8_t* pixels = image.getPixelsPtr() + 4 * (rectangle.position.x + (size.x * rectangle.position.y)); - glCheck(glBindTexture(GL_TEXTURE_2D, texture->m_texture)); - for (int i = 0; i < rectangle.size.y; ++i) - { - glCheck(glTexSubImage2D(GL_TEXTURE_2D, 0, 0, i, rectangle.size.x, 1, GL_RGBA, GL_UNSIGNED_BYTE, pixels)); - pixels += 4 * size.x; - } - - glCheck(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST)); - texture->m_hasMipmap = false; - - // Force an OpenGL flush, so that the texture will appear updated - // in all contexts immediately (solves problems in multi-threaded apps) - glCheck(glFlush()); - - return texture; - } - else - { - // Error message generated in called function. - return std::nullopt; + glCheck(glTexSubImage2D(GL_TEXTURE_2D, 0, 0, i, rectangle.size.x, 1, GL_RGBA, GL_UNSIGNED_BYTE, pixels)); + pixels += 4 * size.x; } + + glCheck(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST)); + texture->m_hasMipmap = false; + + // Force an OpenGL flush, so that the texture will appear updated + // in all contexts immediately (solves problems in multi-threaded apps) + glCheck(glFlush()); + + return texture; } + + // Error message generated in called function. + return std::nullopt; } @@ -974,15 +968,13 @@ unsigned int Texture::getValidSize(unsigned int size) // If hardware supports NPOT textures, then just return the unmodified size return size; } - else - { - // If hardware doesn't support NPOT textures, we calculate the nearest power of two - unsigned int powerOfTwo = 1; - while (powerOfTwo < size) - powerOfTwo *= 2; - return powerOfTwo; - } + // If hardware doesn't support NPOT textures, we calculate the nearest power of two + unsigned int powerOfTwo = 1; + while (powerOfTwo < size) + powerOfTwo *= 2; + + return powerOfTwo; } diff --git a/src/SFML/Graphics/VertexArray.cpp b/src/SFML/Graphics/VertexArray.cpp index a502f0005..904c839e1 100644 --- a/src/SFML/Graphics/VertexArray.cpp +++ b/src/SFML/Graphics/VertexArray.cpp @@ -126,11 +126,9 @@ FloatRect VertexArray::getBounds() const return {{left, top}, {right - left, bottom - top}}; } - else - { - // Array is empty - return {}; - } + + // Array is empty + return {}; } diff --git a/src/SFML/Network/Ftp.cpp b/src/SFML/Network/Ftp.cpp index 3be7413f2..8fb4a3e50 100644 --- a/src/SFML/Network/Ftp.cpp +++ b/src/SFML/Network/Ftp.cpp @@ -457,25 +457,23 @@ Ftp::Response Ftp::getResponse() // Return the response code and message return Response(static_cast(code), message); } - else + + // The line we just read was actually not a response, + // only a new part of the current multiline response + + // Extract the line + std::string line; + std::getline(in, line); + + if (!line.empty()) { - // The line we just read was actually not a response, - // only a new part of the current multiline response + // Remove the ending '\r' (all lines are terminated by "\r\n") + line.erase(line.length() - 1); - // Extract the line - std::string line; - std::getline(in, line); - - if (!line.empty()) - { - // Remove the ending '\r' (all lines are terminated by "\r\n") - line.erase(line.length() - 1); - - // Append it to the current message - std::ostringstream out; - out << code << separator << line << '\n'; - message += out.str(); - } + // Append it to the current message + std::ostringstream out; + out << code << separator << line << '\n'; + message += out.str(); } } } diff --git a/src/SFML/Network/TcpSocket.cpp b/src/SFML/Network/TcpSocket.cpp index fb24f2f16..dc4eded50 100644 --- a/src/SFML/Network/TcpSocket.cpp +++ b/src/SFML/Network/TcpSocket.cpp @@ -141,73 +141,71 @@ Socket::Status TcpSocket::connect(const IpAddress& remoteAddress, unsigned short // Connection succeeded return Status::Done; } - else + + // ----- We're using a timeout: we'll need a few tricks to make it work ----- + + // Save the previous blocking state + const bool blocking = isBlocking(); + + // Switch to non-blocking to enable our connection timeout + if (blocking) + setBlocking(false); + + // Try to connect to the remote address + if (::connect(getNativeHandle(), reinterpret_cast(&address), sizeof(address)) >= 0) { - // ----- We're using a timeout: we'll need a few tricks to make it work ----- + // We got instantly connected! (it may no happen a lot...) + setBlocking(blocking); + return Status::Done; + } - // Save the previous blocking state - const bool blocking = isBlocking(); + // Get the error status + Status status = priv::SocketImpl::getErrorStatus(); - // Switch to non-blocking to enable our connection timeout - if (blocking) - setBlocking(false); + // If we were in non-blocking mode, return immediately + if (!blocking) + return status; - // Try to connect to the remote address - if (::connect(getNativeHandle(), reinterpret_cast(&address), sizeof(address)) >= 0) + // Otherwise, wait until something happens to our socket (success, timeout or error) + if (status == Socket::Status::NotReady) + { + // Setup the selector + fd_set selector; + FD_ZERO(&selector); + FD_SET(getNativeHandle(), &selector); + + // Setup the timeout + timeval time{}; + time.tv_sec = static_cast(timeout.asMicroseconds() / 1000000); + time.tv_usec = static_cast(timeout.asMicroseconds() % 1000000); + + // Wait for something to write on our socket (which means that the connection request has returned) + if (select(static_cast(getNativeHandle() + 1), nullptr, &selector, nullptr, &time) > 0) { - // We got instantly connected! (it may no happen a lot...) - setBlocking(blocking); - return Status::Done; - } - - // Get the error status - Status status = priv::SocketImpl::getErrorStatus(); - - // If we were in non-blocking mode, return immediately - if (!blocking) - return status; - - // Otherwise, wait until something happens to our socket (success, timeout or error) - if (status == Socket::Status::NotReady) - { - // Setup the selector - fd_set selector; - FD_ZERO(&selector); - FD_SET(getNativeHandle(), &selector); - - // Setup the timeout - timeval time{}; - time.tv_sec = static_cast(timeout.asMicroseconds() / 1000000); - time.tv_usec = static_cast(timeout.asMicroseconds() % 1000000); - - // Wait for something to write on our socket (which means that the connection request has returned) - if (select(static_cast(getNativeHandle() + 1), nullptr, &selector, nullptr, &time) > 0) + // At this point the connection may have been either accepted or refused. + // To know whether it's a success or a failure, we must check the address of the connected peer + if (getRemoteAddress().has_value()) { - // At this point the connection may have been either accepted or refused. - // To know whether it's a success or a failure, we must check the address of the connected peer - if (getRemoteAddress().has_value()) - { - // Connection accepted - status = Status::Done; - } - else - { - // Connection refused - status = priv::SocketImpl::getErrorStatus(); - } + // Connection accepted + status = Status::Done; } else { - // Failed to connect before timeout is over + // Connection refused status = priv::SocketImpl::getErrorStatus(); } } - - // Switch back to blocking mode - setBlocking(true); - - return status; + else + { + // Failed to connect before timeout is over + status = priv::SocketImpl::getErrorStatus(); + } } + + // Switch back to blocking mode + setBlocking(true); + + return status; } @@ -299,14 +297,12 @@ Socket::Status TcpSocket::receive(void* data, std::size_t size, std::size_t& rec received = static_cast(sizeReceived); return Status::Done; } - else if (sizeReceived == 0) + if (sizeReceived == 0) { return Socket::Status::Disconnected; } - else - { - return priv::SocketImpl::getErrorStatus(); - } + + return priv::SocketImpl::getErrorStatus(); } diff --git a/src/SFML/System/Err.cpp b/src/SFML/System/Err.cpp index 0f56dcd28..a210f91fc 100644 --- a/src/SFML/System/Err.cpp +++ b/src/SFML/System/Err.cpp @@ -65,17 +65,15 @@ private: // Valid character return sputc(static_cast(character)); } - else if (character != EOF) + if (character != EOF) { // Not enough space in the buffer: synchronize output and try again sync(); return overflow(character); } - else - { - // Invalid character: synchronize output - return sync(); - } + + // Invalid character: synchronize output + return sync(); } int sync() override diff --git a/src/SFML/Window/Android/WindowImplAndroid.cpp b/src/SFML/Window/Android/WindowImplAndroid.cpp index f8d4c89fe..421b9bd8d 100644 --- a/src/SFML/Window/Android/WindowImplAndroid.cpp +++ b/src/SFML/Window/Android/WindowImplAndroid.cpp @@ -444,7 +444,7 @@ int WindowImplAndroid::processKeyEvent(AInputEvent* inputEvent, ActivityStates& // https://code.google.com/p/android/issues/detail?id=33998 return 0; } - else if (auto unicode = static_cast(getUnicode(inputEvent))) // This is a repeated sequence + if (auto unicode = static_cast(getUnicode(inputEvent))) // This is a repeated sequence { const Event event(Event::TextEntered{static_cast(unicode)}); diff --git a/src/SFML/Window/Context.cpp b/src/SFML/Window/Context.cpp index 46656f9bd..2af3d5322 100644 --- a/src/SFML/Window/Context.cpp +++ b/src/SFML/Window/Context.cpp @@ -113,8 +113,8 @@ const Context* Context::getActiveContext() // We have to check that the last activated sf::Context is still active (a RenderTarget activation may have deactivated it) if (currentContext && currentContext->m_context.get() == priv::GlContext::getActiveContext()) return currentContext; - else - return nullptr; + + return nullptr; } diff --git a/src/SFML/Window/DRM/InputImpl.cpp b/src/SFML/Window/DRM/InputImpl.cpp index 9e8ebb2a1..77931cc7c 100644 --- a/src/SFML/Window/DRM/InputImpl.cpp +++ b/src/SFML/Window/DRM/InputImpl.cpp @@ -377,48 +377,46 @@ std::optional eventProcess() if (inputEvent.value) return sf::Event::MouseButtonPressed{*mb, mousePos}; - else - return sf::Event::MouseButtonReleased{*mb, mousePos}; + + return sf::Event::MouseButtonReleased{*mb, mousePos}; } - else + + const sf::Keyboard::Key kb = toKey(inputEvent.code); + + unsigned int special = 0; + if ((kb == sf::Keyboard::Key::Delete) || (kb == sf::Keyboard::Key::Backspace)) + special = (kb == sf::Keyboard::Key::Delete) ? 127 : 8; + + if (inputEvent.value == 2) { - const sf::Keyboard::Key kb = toKey(inputEvent.code); - - unsigned int special = 0; - if ((kb == sf::Keyboard::Key::Delete) || (kb == sf::Keyboard::Key::Backspace)) - special = (kb == sf::Keyboard::Key::Delete) ? 127 : 8; - - if (inputEvent.value == 2) + // key repeat events + // + if (special) { - // key repeat events - // - if (special) - { - return sf::Event::TextEntered{special}; - } + return sf::Event::TextEntered{special}; } - else if (kb != sf::Keyboard::Key::Unknown) - { - // key down and key up events - // - sf::Event::KeyChanged keyChanged; - keyChanged.code = kb; - keyChanged.scancode = sf::Keyboard::Scan::Unknown; // TODO: not implemented - keyChanged.alt = altDown(); - keyChanged.control = controlDown(); - keyChanged.shift = shiftDown(); - keyChanged.system = systemDown(); + } + else if (kb != sf::Keyboard::Key::Unknown) + { + // key down and key up events + // + sf::Event::KeyChanged keyChanged; + keyChanged.code = kb; + keyChanged.scancode = sf::Keyboard::Scan::Unknown; // TODO: not implemented + keyChanged.alt = altDown(); + keyChanged.control = controlDown(); + keyChanged.shift = shiftDown(); + keyChanged.system = systemDown(); - keyMap[kb] = inputEvent.value; + keyMap[kb] = inputEvent.value; - if (special && inputEvent.value) - doDeferredText = special; + if (special && inputEvent.value) + doDeferredText = special; - if (inputEvent.value) - return sf::Event::KeyPressed{keyChanged}; - else - return sf::Event::KeyReleased{keyChanged}; - } + if (inputEvent.value) + return sf::Event::KeyPressed{keyChanged}; + + return sf::Event::KeyReleased{keyChanged}; } } else if (inputEvent.type == EV_REL) diff --git a/src/SFML/Window/DRM/VideoModeImpl.cpp b/src/SFML/Window/DRM/VideoModeImpl.cpp index 9cade8739..0281b40ee 100644 --- a/src/SFML/Window/DRM/VideoModeImpl.cpp +++ b/src/SFML/Window/DRM/VideoModeImpl.cpp @@ -60,8 +60,8 @@ VideoMode VideoModeImpl::getDesktopMode() drmModeModeInfoPtr ptr = drm.mode; if (ptr) return VideoMode({ptr->hdisplay, ptr->vdisplay}); - else - return VideoMode({0, 0}); + + return VideoMode({0, 0}); } } // namespace sf::priv diff --git a/src/SFML/Window/GlContext.cpp b/src/SFML/Window/GlContext.cpp index c23653ac1..bd01335fa 100644 --- a/src/SFML/Window/GlContext.cpp +++ b/src/SFML/Window/GlContext.cpp @@ -764,45 +764,35 @@ bool GlContext::setActive(bool active) currentContext.ptr = this; return true; } - else - { - return false; - } - } - else - { - // This context is already the active one on this thread, don't do anything - return true; + + return false; } + + // This context is already the active one on this thread, don't do anything + return true; } - else + + if (m_impl->id == currentContext.id) { - if (m_impl->id == currentContext.id) - { - // We can't and don't need to lock when we are currently creating the shared context - std::unique_lock lock; + // We can't and don't need to lock when we are currently creating the shared context + std::unique_lock lock; - if (sharedContext) - lock = std::unique_lock(sharedContext->mutex); + if (sharedContext) + lock = std::unique_lock(sharedContext->mutex); - // Deactivate the context - if (makeCurrent(false)) - { - currentContext.id = 0; - currentContext.ptr = nullptr; - return true; - } - else - { - return false; - } - } - else + // Deactivate the context + if (makeCurrent(false)) { - // This context is not the active one on this thread, don't do anything + currentContext.id = 0; + currentContext.ptr = nullptr; return true; } + + return false; } + + // This context is not the active one on this thread, don't do anything + return true; } diff --git a/src/SFML/Window/Unix/ClipboardImpl.cpp b/src/SFML/Window/Unix/ClipboardImpl.cpp index 8e23551d8..de60cce31 100644 --- a/src/SFML/Window/Unix/ClipboardImpl.cpp +++ b/src/SFML/Window/Unix/ClipboardImpl.cpp @@ -314,8 +314,8 @@ void ClipboardImpl::processEvent(XEvent& windowEvent) break; } - else if ((selectionRequestEvent.target == XA_STRING) || - ((m_utf8String == None) && (selectionRequestEvent.target == m_text))) + if ((selectionRequestEvent.target == XA_STRING) || + ((m_utf8String == None) && (selectionRequestEvent.target == m_text))) { // Respond to a request for conversion to a Latin-1 string const std::string data = m_clipboardContents.toAnsiString(); @@ -340,8 +340,8 @@ void ClipboardImpl::processEvent(XEvent& windowEvent) break; } - else if ((m_utf8String != None) && - ((selectionRequestEvent.target == m_utf8String) || (selectionRequestEvent.target == m_text))) + if ((m_utf8String != None) && + ((selectionRequestEvent.target == m_utf8String) || (selectionRequestEvent.target == m_text))) { // Respond to a request for conversion to a UTF-8 string // or an encoding of our choosing (we always choose UTF-8) diff --git a/src/SFML/Window/Unix/CursorImpl.cpp b/src/SFML/Window/Unix/CursorImpl.cpp index 0476fe9d4..1cfcbf29c 100644 --- a/src/SFML/Window/Unix/CursorImpl.cpp +++ b/src/SFML/Window/Unix/CursorImpl.cpp @@ -70,8 +70,8 @@ bool CursorImpl::loadFromPixels(const std::uint8_t* pixels, Vector2u size, Vecto if (isColorCursorSupported()) return loadFromPixelsARGB(pixels, size, hotspot); - else - return loadFromPixelsMonochrome(pixels, size, hotspot); + + return loadFromPixelsMonochrome(pixels, size, hotspot); } diff --git a/src/SFML/Window/Unix/GlxContext.cpp b/src/SFML/Window/Unix/GlxContext.cpp index 028c05f96..0a6c8483f 100644 --- a/src/SFML/Window/Unix/GlxContext.cpp +++ b/src/SFML/Window/Unix/GlxContext.cpp @@ -379,13 +379,11 @@ XVisualInfo GlxContext::selectBestVisual(::Display* display, unsigned int bitsPe return bestVisual; } - else - { - // Should never happen... - err() << "No GLX visual found. You should check your graphics driver" << std::endl; - return {}; - } + // Should never happen... + err() << "No GLX visual found. You should check your graphics driver" << std::endl; + + return {}; } diff --git a/src/SFML/Window/Unix/InputImpl.cpp b/src/SFML/Window/Unix/InputImpl.cpp index 00182662a..51730027d 100644 --- a/src/SFML/Window/Unix/InputImpl.cpp +++ b/src/SFML/Window/Unix/InputImpl.cpp @@ -158,10 +158,8 @@ Vector2i getMousePosition(const WindowBase& relativeTo) return {x, y}; } - else - { - return {}; - } + + return {}; } diff --git a/src/SFML/Window/Unix/JoystickImpl.cpp b/src/SFML/Window/Unix/JoystickImpl.cpp index 316898cf6..7bd1b9608 100644 --- a/src/SFML/Window/Unix/JoystickImpl.cpp +++ b/src/SFML/Window/Unix/JoystickImpl.cpp @@ -141,7 +141,7 @@ void updatePluggedList(udev_device* udevDevice = nullptr) recordIt->systemPath = syspath ? syspath : ""; break; } - else if (std::strstr(action, "remove")) + if (std::strstr(action, "remove")) { recordIt->plugged = false; break; @@ -561,10 +561,8 @@ bool JoystickImpl::open(unsigned int index) return true; } - else - { - err() << "Failed to open joystick " << devnode << ": " << errno << std::endl; - } + + err() << "Failed to open joystick " << devnode << ": " << errno << std::endl; } return false; diff --git a/src/SFML/Window/Unix/WindowImplX11.cpp b/src/SFML/Window/Unix/WindowImplX11.cpp index e9bac176f..281af1ce5 100644 --- a/src/SFML/Window/Unix/WindowImplX11.cpp +++ b/src/SFML/Window/Unix/WindowImplX11.cpp @@ -767,22 +767,18 @@ void WindowImplX11::processEvents() event = nextEvent; break; } - else - { - // Ignore both events - processThisEvent = false; - break; - } - } - else - { - // This sequence of events does not come from maintaining a key down, - // so process the KeyRelease event normally, - processEvent(event); - // but loop because the next event can be the first half - // of a sequence coming from maintaining a key down. - event = nextEvent; + + // Ignore both events + processThisEvent = false; + break; } + + // This sequence of events does not come from maintaining a key down, + // so process the KeyRelease event normally, + processEvent(event); + // but loop because the next event can be the first half + // of a sequence coming from maintaining a key down. + event = nextEvent; } else { @@ -2106,8 +2102,8 @@ RROutput WindowImplX11::getOutputPrimary(::Window& rootWindow, XRRScreenResource // Check if returned output is valid, otherwise use the first screen if (output == None) return res->outputs[0]; - else - return output; + + return output; } diff --git a/src/SFML/Window/VideoMode.cpp b/src/SFML/Window/VideoMode.cpp index 0d16ddbc6..ae7ffbb9e 100644 --- a/src/SFML/Window/VideoMode.cpp +++ b/src/SFML/Window/VideoMode.cpp @@ -96,15 +96,11 @@ bool operator<(const VideoMode& left, const VideoMode& right) { return left.size.y < right.size.y; } - else - { - return left.size.x < right.size.x; - } - } - else - { - return left.bitsPerPixel < right.bitsPerPixel; + + return left.size.x < right.size.x; } + + return left.bitsPerPixel < right.bitsPerPixel; } diff --git a/src/SFML/Window/Win32/CursorImpl.cpp b/src/SFML/Window/Win32/CursorImpl.cpp index a17553d42..a2e485120 100644 --- a/src/SFML/Window/Win32/CursorImpl.cpp +++ b/src/SFML/Window/Win32/CursorImpl.cpp @@ -117,11 +117,9 @@ bool CursorImpl::loadFromPixels(const std::uint8_t* pixels, Vector2u size, Vecto { return true; } - else - { - err() << "Failed to create cursor from bitmaps" << std::endl; - return false; - } + + err() << "Failed to create cursor from bitmaps" << std::endl; + return false; } @@ -167,11 +165,9 @@ bool CursorImpl::loadFromSystem(Cursor::Type type) { return true; } - else - { - err() << "Could not create copy of a system cursor" << std::endl; - return false; - } + + err() << "Could not create copy of a system cursor" << std::endl; + return false; } diff --git a/src/SFML/Window/Win32/InputImpl.cpp b/src/SFML/Window/Win32/InputImpl.cpp index b01acb864..154d66ef0 100644 --- a/src/SFML/Window/Win32/InputImpl.cpp +++ b/src/SFML/Window/Win32/InputImpl.cpp @@ -711,10 +711,8 @@ Vector2i getMousePosition(const WindowBase& relativeTo) ScreenToClient(handle, &point); return {point.x, point.y}; } - else - { - return {}; - } + + return {}; } diff --git a/src/SFML/Window/Win32/JoystickImpl.cpp b/src/SFML/Window/Win32/JoystickImpl.cpp index 0d8e5ce51..d4f23effd 100644 --- a/src/SFML/Window/Win32/JoystickImpl.cpp +++ b/src/SFML/Window/Win32/JoystickImpl.cpp @@ -362,10 +362,8 @@ JoystickState JoystickImpl::update() { return updateDInputBuffered(); } - else - { - return updateDInputPolled(); - } + + return updateDInputPolled(); } JoystickState state; @@ -1147,7 +1145,7 @@ BOOL CALLBACK JoystickImpl::deviceObjectEnumerationCallback(const DIDEVICEOBJECT return DIENUM_CONTINUE; } - else if (DIDFT_GETTYPE(deviceObjectInstance->dwType) & DIDFT_POV) + if (DIDFT_GETTYPE(deviceObjectInstance->dwType) & DIDFT_POV) { // POVs if (deviceObjectInstance->guidType == guids::GUID_POV) @@ -1161,7 +1159,7 @@ BOOL CALLBACK JoystickImpl::deviceObjectEnumerationCallback(const DIDEVICEOBJECT return DIENUM_CONTINUE; } - else if (DIDFT_GETTYPE(deviceObjectInstance->dwType) & DIDFT_BUTTON) + if (DIDFT_GETTYPE(deviceObjectInstance->dwType) & DIDFT_BUTTON) { // Buttons for (unsigned int i = 0; i < Joystick::ButtonCount; ++i) diff --git a/src/SFML/Window/Window.cpp b/src/SFML/Window/Window.cpp index 4b00bc106..8ee5979eb 100644 --- a/src/SFML/Window/Window.cpp +++ b/src/SFML/Window/Window.cpp @@ -164,16 +164,12 @@ bool Window::setActive(bool active) const { return true; } - else - { - err() << "Failed to activate the window's context" << std::endl; - return false; - } - } - else - { + + err() << "Failed to activate the window's context" << std::endl; return false; } + + return false; } diff --git a/src/SFML/Window/iOS/ClipboardImpl.mm b/src/SFML/Window/iOS/ClipboardImpl.mm index 811da52ca..b1ad8afac 100644 --- a/src/SFML/Window/iOS/ClipboardImpl.mm +++ b/src/SFML/Window/iOS/ClipboardImpl.mm @@ -47,10 +47,8 @@ String ClipboardImpl::getString() return String::fromUtf8(utf8, utf8 + length); } - else - { - return {}; - } + + return {}; } diff --git a/src/SFML/Window/iOS/SFAppDelegate.mm b/src/SFML/Window/iOS/SFAppDelegate.mm index d05dc0232..f234040b8 100644 --- a/src/SFML/Window/iOS/SFAppDelegate.mm +++ b/src/SFML/Window/iOS/SFAppDelegate.mm @@ -235,8 +235,8 @@ std::vector touchPositions; { if (index < touchPositions.size()) return touchPositions[index]; - else - return sf::Vector2i(-1, -1); + + return sf::Vector2i(-1, -1); } diff --git a/src/SFML/Window/macOS/CursorImpl.mm b/src/SFML/Window/macOS/CursorImpl.mm index 4da21d90e..5b4ea4112 100644 --- a/src/SFML/Window/macOS/CursorImpl.mm +++ b/src/SFML/Window/macOS/CursorImpl.mm @@ -41,8 +41,8 @@ NSCursor* loadFromSelector(SEL selector) // The caller is responsible for retaining the cursor. if ([NSCursor respondsToSelector:selector]) return [NSCursor performSelector:selector]; - else - return nil; + + return nil; } } diff --git a/src/SFML/Window/macOS/SFContext.mm b/src/SFML/Window/macOS/SFContext.mm index 0bd5c0125..ba6baf308 100644 --- a/src/SFML/Window/macOS/SFContext.mm +++ b/src/SFML/Window/macOS/SFContext.mm @@ -128,11 +128,9 @@ bool SFContext::makeCurrent(bool current) [m_context makeCurrentContext]; return m_context == [NSOpenGLContext currentContext]; // Should be true. } - else - { - [NSOpenGLContext clearCurrentContext]; - return m_context != [NSOpenGLContext currentContext]; // Should be true. - } + + [NSOpenGLContext clearCurrentContext]; + return m_context != [NSOpenGLContext currentContext]; // Should be true. } diff --git a/src/SFML/Window/macOS/SFOpenGLView+keyboard.mm b/src/SFML/Window/macOS/SFOpenGLView+keyboard.mm index 5f68f8e73..9d94e29e8 100644 --- a/src/SFML/Window/macOS/SFOpenGLView+keyboard.mm +++ b/src/SFML/Window/macOS/SFOpenGLView+keyboard.mm @@ -197,15 +197,13 @@ { return false; } - else if ([[event characters] length] > 0) + if ([[event characters] length] > 0) { unichar code = [[event characters] characterAtIndex:0]; return (code < 0xF700) || (code > 0xF8FF); } - else - { - return true; - } + + return true; } @end