Add clang-tidy readability-else-after-return check

This commit is contained in:
Chris Thrasher 2024-06-25 14:22:42 -06:00
parent be63ffa8d4
commit d7eeaea240
40 changed files with 335 additions and 442 deletions

View File

@ -63,7 +63,6 @@ Checks: >
-readability-avoid-nested-conditional-operator, -readability-avoid-nested-conditional-operator,
-readability-braces-around-statements, -readability-braces-around-statements,
-readability-convert-member-functions-to-static, -readability-convert-member-functions-to-static,
-readability-else-after-return,
-readability-function-cognitive-complexity, -readability-function-cognitive-complexity,
-readability-function-size, -readability-function-size,
-readability-identifier-length, -readability-identifier-length,

View File

@ -58,8 +58,8 @@
if (cstr != nullptr) if (cstr != nullptr)
return std::string(cstr); return std::string(cstr);
else
return ""; return "";
} }
- (std::wstring)tostdwstring - (std::wstring)tostdwstring

View File

@ -58,10 +58,8 @@ private:
std::cout << "Connected to server " << m_host << std::endl; std::cout << "Connected to server " << m_host << std::endl;
return true; return true;
} }
else
{ return false;
return false;
}
} }
//////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////

View File

@ -630,7 +630,7 @@ public:
gpu = dev; gpu = dev;
break; break;
} }
else if (deviceProperties.deviceType == VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU) if (deviceProperties.deviceType == VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU)
{ {
gpu = dev; gpu = dev;
} }

View File

@ -103,10 +103,8 @@ constexpr std::optional<Rect<T>> Rect<T>::findIntersection(const Rect<T>& rectan
{ {
return Rect<T>({interLeft, interTop}, {interRight - interLeft, interBottom - interTop}); return Rect<T>({interLeft, interTop}, {interRight - interLeft, interBottom - interTop});
} }
else
{ return std::nullopt;
return std::nullopt;
}
} }

View File

@ -85,10 +85,8 @@ constexpr Transform Transform::getInverse() const
(m_matrix[5] * m_matrix[0] - m_matrix[1] * m_matrix[4]) / det}; (m_matrix[5] * m_matrix[0] - m_matrix[1] * m_matrix[4]) / det};
// clang-format on // clang-format on
} }
else
{ return Identity;
return Identity;
}
} }

View File

@ -118,17 +118,15 @@ std::optional<SoundBuffer> SoundBuffer::loadFromSamples(
return std::nullopt; return std::nullopt;
return soundBuffer; 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; return true;
} }
else
{ return false;
return false;
}
} }
@ -233,10 +229,8 @@ std::optional<SoundBuffer> SoundBuffer::initialize(InputSoundFile& file)
return soundBuffer; return soundBuffer;
} }
else
{ return std::nullopt;
return std::nullopt;
}
} }

View File

@ -51,15 +51,11 @@ FLAC__StreamDecoderReadStatus streamRead(const FLAC__StreamDecoder*, FLAC__byte
*bytes = *count; *bytes = *count;
return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE; return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
} }
else
{ return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
}
}
else
{
return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
} }
return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
} }
FLAC__StreamDecoderSeekStatus streamSeek(const FLAC__StreamDecoder*, FLAC__uint64 absoluteByteOffset, void* clientData) 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<std::size_t>(absoluteByteOffset)).has_value()) if (data->stream->seek(static_cast<std::size_t>(absoluteByteOffset)).has_value())
return FLAC__STREAM_DECODER_SEEK_STATUS_OK; 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) 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; *absoluteByteOffset = *position;
return FLAC__STREAM_DECODER_TELL_STATUS_OK; 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) 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; *streamLength = *count;
return FLAC__STREAM_DECODER_LENGTH_STATUS_OK; 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) 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); m_clientData.leftovers.swap(leftovers);
return maxCount; return maxCount;
} }
else
{ // We can use all the leftovers and decode new frames
// We can use all the leftovers and decode new frames std::copy(m_clientData.leftovers.begin(), m_clientData.leftovers.end(), samples);
std::copy(m_clientData.leftovers.begin(), m_clientData.leftovers.end(), samples);
}
} }
// Reset the data that will be used in the callback // Reset the data that will be used in the callback

View File

@ -83,10 +83,8 @@ bool SoundFileReaderOgg::check(InputStream& stream)
ov_clear(&file); ov_clear(&file);
return true; return true;
} }
else
{ return false;
return false;
}
} }

View File

@ -97,7 +97,8 @@ bool SoundFileWriterWav::open(const std::filesystem::path& filename,
err() << "WAV sound file channel count 0" << std::endl; err() << "WAV sound file channel count 0" << std::endl;
return false; return false;
} }
else if (channelCount == 1)
if (channelCount == 1)
{ {
m_remapTable[0] = 0; m_remapTable[0] = 0;
} }

View File

@ -60,11 +60,11 @@ unsigned long read(FT_Stream rec, unsigned long offset, unsigned char* buffer, u
{ {
if (count > 0) if (count > 0)
return static_cast<unsigned long>(stream->read(reinterpret_cast<char*>(buffer), count).value()); return static_cast<unsigned long>(stream->read(reinterpret_cast<char*>(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) void close(FT_Stream)
{ {
@ -313,12 +313,10 @@ const Glyph& Font::getGlyph(std::uint32_t codePoint, unsigned int characterSize,
// Found: just return it // Found: just return it
return it->second; return it->second;
} }
else
{ // Not found: we have to load it
// Not found: we have to load it const Glyph glyph = loadGlyph(codePoint, characterSize, bold, outlineThickness);
const Glyph glyph = loadGlyph(codePoint, characterSize, bold, outlineThickness); return glyphs.emplace(key, glyph).first->second;
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 // 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<float>(kerning.x) + 32) / float{1 << 6}); return std::floor((secondLsbDelta - firstRsbDelta + static_cast<float>(kerning.x) + 32) / float{1 << 6});
} }
else
{ // Invalid font
// Invalid font return 0.f;
return 0.f;
}
} }
@ -383,10 +379,8 @@ float Font::getLineSpacing(unsigned int characterSize) const
{ {
return static_cast<float>(face->size->metrics.height) / float{1 << 6}; return static_cast<float>(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<float>(FT_MulFix(face->underline_position, face->size->metrics.y_scale)) / float{1 << 6}; return -static_cast<float>(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<float>(FT_MulFix(face->underline_thickness, face->size->metrics.y_scale)) / float{1 << 6}; return static_cast<float>(FT_MulFix(face->underline_thickness, face->size->metrics.y_scale)) / float{1 << 6};
} }
else
{ return 0.f;
return 0.f;
}
} }

View File

@ -185,14 +185,13 @@ std::optional<Image> Image::loadFromFile(const std::filesystem::path& filename)
{ {
return Image(Vector2u(Vector2i(width, height)), {ptr.get(), ptr.get() + width * height * 4}); 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> Image::loadFromMemory(const void* data, std::size_t size)
{ {
return Image(Vector2u(Vector2i(width, height)), {ptr.get(), ptr.get() + width * height * 4}); 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; // Error, failed to load the image
} err() << "Failed to load image from memory. Reason: " << stbi_failure_reason() << std::endl;
}
else
{
err() << "Failed to load image from memory, no data provided" << std::endl;
return std::nullopt; 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> Image::loadFromStream(InputStream& stream)
{ {
return Image(Vector2u(Vector2i(width, height)), {ptr.get(), ptr.get() + width * height * 4}); return Image(Vector2u(Vector2i(width, height)), {ptr.get(), ptr.get() + width * height * 4});
} }
else
{ // Error, failed to load the image
// Error, failed to load the image err() << "Failed to load image from stream. Reason: " << stbi_failure_reason() << std::endl;
err() << "Failed to load image from stream. Reason: " << stbi_failure_reason() << std::endl;
return std::nullopt; return std::nullopt;
}
} }
@ -503,11 +497,9 @@ const std::uint8_t* Image::getPixelsPtr() const
{ {
return m_pixels.data(); return m_pixels.data();
} }
else
{ err() << "Trying to access the pixels of an empty image" << std::endl;
err() << "Trying to access the pixels of an empty image" << std::endl; return nullptr;
return nullptr;
}
} }

View File

@ -99,10 +99,8 @@ unsigned int RenderTexture::getMaximumAntialiasingLevel()
{ {
return priv::RenderTextureImplFBO::getMaximumAntialiasingLevel(); return priv::RenderTextureImplFBO::getMaximumAntialiasingLevel();
} }
else
{ return priv::RenderTextureImplDefault::getMaximumAntialiasingLevel();
return priv::RenderTextureImplDefault::getMaximumAntialiasingLevel();
}
} }

View File

@ -95,10 +95,8 @@ bool getFileContents(const std::filesystem::path& filename, std::vector<char>& b
buffer.push_back('\0'); buffer.push_back('\0');
return true; return true;
} }
else
{ return false;
return false;
}
} }
// Read the contents of a stream into an array of char // Read the contents of a stream into an array of char
@ -283,10 +281,11 @@ std::optional<Shader> Shader::loadFromFile(const std::filesystem::path& filename
// Compile the shader program // Compile the shader program
if (type == Type::Vertex) if (type == Type::Vertex)
return compile(shader.data(), {}, {}); return compile(shader.data(), {}, {});
else if (type == Type::Geometry)
if (type == Type::Geometry)
return compile({}, shader.data(), {}); return compile({}, shader.data(), {});
else
return compile({}, {}, shader.data()); return compile({}, {}, shader.data());
} }
@ -355,10 +354,11 @@ std::optional<Shader> Shader::loadFromMemory(std::string_view shader, Type type)
// Compile the shader program // Compile the shader program
if (type == Type::Vertex) if (type == Type::Vertex)
return compile(shader, {}, {}); return compile(shader, {}, {});
else if (type == Type::Geometry)
if (type == Type::Geometry)
return compile({}, shader, {}); return compile({}, shader, {});
else
return compile({}, {}, shader); return compile({}, {}, shader);
} }
@ -394,10 +394,11 @@ std::optional<Shader> Shader::loadFromStream(InputStream& stream, Type type)
// Compile the shader program // Compile the shader program
if (type == Type::Vertex) if (type == Type::Vertex)
return compile(shader.data(), {}, {}); return compile(shader.data(), {}, {});
else if (type == Type::Geometry)
if (type == Type::Geometry)
return compile({}, shader.data(), {}); 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 // Already in cache, return it
return it->second; 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) // Not in cache, request the location from OpenGL
err() << "Uniform " << std::quoted(name) << " not found in shader" << std::endl; 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 } // namespace sf

View File

@ -312,55 +312,49 @@ std::optional<Texture> Texture::loadFromImage(const Image& image, bool sRgb, con
texture->update(image); texture->update(image);
return texture; return texture;
} }
else
{ // Error message generated in called function.
// Error message generated in called function. return std::nullopt;
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 // Make sure that the current texture binding will be preserved
IntRect rectangle = area; const priv::TextureSaver save;
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 // Copy the pixels to the texture, row by row
if (auto texture = sf::Texture::create(Vector2u(rectangle.size), sRgb)) 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; glCheck(glTexSubImage2D(GL_TEXTURE_2D, 0, 0, i, rectangle.size.x, 1, GL_RGBA, GL_UNSIGNED_BYTE, pixels));
pixels += 4 * size.x;
// 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(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 // If hardware supports NPOT textures, then just return the unmodified size
return 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;
} }

View File

@ -126,11 +126,9 @@ FloatRect VertexArray::getBounds() const
return {{left, top}, {right - left, bottom - top}}; return {{left, top}, {right - left, bottom - top}};
} }
else
{ // Array is empty
// Array is empty return {};
return {};
}
} }

View File

@ -457,25 +457,23 @@ Ftp::Response Ftp::getResponse()
// Return the response code and message // Return the response code and message
return Response(static_cast<Response::Status>(code), message); return Response(static_cast<Response::Status>(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, // Remove the ending '\r' (all lines are terminated by "\r\n")
// only a new part of the current multiline response line.erase(line.length() - 1);
// Extract the line // Append it to the current message
std::string line; std::ostringstream out;
std::getline(in, line); out << code << separator << line << '\n';
message += out.str();
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();
}
} }
} }
} }

View File

@ -141,73 +141,71 @@ Socket::Status TcpSocket::connect(const IpAddress& remoteAddress, unsigned short
// Connection succeeded // Connection succeeded
return Status::Done; 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<sockaddr*>(&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 // Get the error status
const bool blocking = isBlocking(); Status status = priv::SocketImpl::getErrorStatus();
// Switch to non-blocking to enable our connection timeout // If we were in non-blocking mode, return immediately
if (blocking) if (!blocking)
setBlocking(false); return status;
// Try to connect to the remote address // Otherwise, wait until something happens to our socket (success, timeout or error)
if (::connect(getNativeHandle(), reinterpret_cast<sockaddr*>(&address), sizeof(address)) >= 0) 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<long>(timeout.asMicroseconds() / 1000000);
time.tv_usec = static_cast<int>(timeout.asMicroseconds() % 1000000);
// Wait for something to write on our socket (which means that the connection request has returned)
if (select(static_cast<int>(getNativeHandle() + 1), nullptr, &selector, nullptr, &time) > 0)
{ {
// We got instantly connected! (it may no happen a lot...) // At this point the connection may have been either accepted or refused.
setBlocking(blocking); // To know whether it's a success or a failure, we must check the address of the connected peer
return Status::Done; if (getRemoteAddress().has_value())
}
// 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<long>(timeout.asMicroseconds() / 1000000);
time.tv_usec = static_cast<int>(timeout.asMicroseconds() % 1000000);
// Wait for something to write on our socket (which means that the connection request has returned)
if (select(static_cast<int>(getNativeHandle() + 1), nullptr, &selector, nullptr, &time) > 0)
{ {
// At this point the connection may have been either accepted or refused. // Connection accepted
// To know whether it's a success or a failure, we must check the address of the connected peer status = Status::Done;
if (getRemoteAddress().has_value())
{
// Connection accepted
status = Status::Done;
}
else
{
// Connection refused
status = priv::SocketImpl::getErrorStatus();
}
} }
else else
{ {
// Failed to connect before timeout is over // Connection refused
status = priv::SocketImpl::getErrorStatus(); status = priv::SocketImpl::getErrorStatus();
} }
} }
else
// Switch back to blocking mode {
setBlocking(true); // Failed to connect before timeout is over
status = priv::SocketImpl::getErrorStatus();
return status; }
} }
// 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<std::size_t>(sizeReceived); received = static_cast<std::size_t>(sizeReceived);
return Status::Done; return Status::Done;
} }
else if (sizeReceived == 0) if (sizeReceived == 0)
{ {
return Socket::Status::Disconnected; return Socket::Status::Disconnected;
} }
else
{ return priv::SocketImpl::getErrorStatus();
return priv::SocketImpl::getErrorStatus();
}
} }

View File

@ -65,17 +65,15 @@ private:
// Valid character // Valid character
return sputc(static_cast<char>(character)); return sputc(static_cast<char>(character));
} }
else if (character != EOF) if (character != EOF)
{ {
// Not enough space in the buffer: synchronize output and try again // Not enough space in the buffer: synchronize output and try again
sync(); sync();
return overflow(character); return overflow(character);
} }
else
{ // Invalid character: synchronize output
// Invalid character: synchronize output return sync();
return sync();
}
} }
int sync() override int sync() override

View File

@ -444,7 +444,7 @@ int WindowImplAndroid::processKeyEvent(AInputEvent* inputEvent, ActivityStates&
// https://code.google.com/p/android/issues/detail?id=33998 // https://code.google.com/p/android/issues/detail?id=33998
return 0; return 0;
} }
else if (auto unicode = static_cast<std::uint32_t>(getUnicode(inputEvent))) // This is a repeated sequence if (auto unicode = static_cast<std::uint32_t>(getUnicode(inputEvent))) // This is a repeated sequence
{ {
const Event event(Event::TextEntered{static_cast<std::uint32_t>(unicode)}); const Event event(Event::TextEntered{static_cast<std::uint32_t>(unicode)});

View File

@ -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) // 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()) if (currentContext && currentContext->m_context.get() == priv::GlContext::getActiveContext())
return currentContext; return currentContext;
else
return nullptr; return nullptr;
} }

View File

@ -377,48 +377,46 @@ std::optional<sf::Event> eventProcess()
if (inputEvent.value) if (inputEvent.value)
return sf::Event::MouseButtonPressed{*mb, mousePos}; 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); // key repeat events
//
unsigned int special = 0; if (special)
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 return sf::Event::TextEntered{special};
//
if (special)
{
return sf::Event::TextEntered{special};
}
} }
else if (kb != sf::Keyboard::Key::Unknown) }
{ else if (kb != sf::Keyboard::Key::Unknown)
// key down and key up events {
// // key down and key up events
sf::Event::KeyChanged keyChanged; //
keyChanged.code = kb; sf::Event::KeyChanged keyChanged;
keyChanged.scancode = sf::Keyboard::Scan::Unknown; // TODO: not implemented keyChanged.code = kb;
keyChanged.alt = altDown(); keyChanged.scancode = sf::Keyboard::Scan::Unknown; // TODO: not implemented
keyChanged.control = controlDown(); keyChanged.alt = altDown();
keyChanged.shift = shiftDown(); keyChanged.control = controlDown();
keyChanged.system = systemDown(); keyChanged.shift = shiftDown();
keyChanged.system = systemDown();
keyMap[kb] = inputEvent.value; keyMap[kb] = inputEvent.value;
if (special && inputEvent.value) if (special && inputEvent.value)
doDeferredText = special; doDeferredText = special;
if (inputEvent.value) if (inputEvent.value)
return sf::Event::KeyPressed{keyChanged}; return sf::Event::KeyPressed{keyChanged};
else
return sf::Event::KeyReleased{keyChanged}; return sf::Event::KeyReleased{keyChanged};
}
} }
} }
else if (inputEvent.type == EV_REL) else if (inputEvent.type == EV_REL)

View File

@ -60,8 +60,8 @@ VideoMode VideoModeImpl::getDesktopMode()
drmModeModeInfoPtr ptr = drm.mode; drmModeModeInfoPtr ptr = drm.mode;
if (ptr) if (ptr)
return VideoMode({ptr->hdisplay, ptr->vdisplay}); return VideoMode({ptr->hdisplay, ptr->vdisplay});
else
return VideoMode({0, 0}); return VideoMode({0, 0});
} }
} // namespace sf::priv } // namespace sf::priv

View File

@ -764,45 +764,35 @@ bool GlContext::setActive(bool active)
currentContext.ptr = this; currentContext.ptr = this;
return true; return true;
} }
else
{ return false;
return false;
}
}
else
{
// This context is already the active one on this thread, don't do anything
return true;
} }
// 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<std::recursive_mutex> lock;
// We can't and don't need to lock when we are currently creating the shared context
std::unique_lock<std::recursive_mutex> lock;
if (sharedContext) if (sharedContext)
lock = std::unique_lock(sharedContext->mutex); lock = std::unique_lock(sharedContext->mutex);
// Deactivate the context // Deactivate the context
if (makeCurrent(false)) if (makeCurrent(false))
{
currentContext.id = 0;
currentContext.ptr = nullptr;
return true;
}
else
{
return false;
}
}
else
{ {
// This context is not the active one on this thread, don't do anything currentContext.id = 0;
currentContext.ptr = nullptr;
return true; return true;
} }
return false;
} }
// This context is not the active one on this thread, don't do anything
return true;
} }

View File

@ -314,8 +314,8 @@ void ClipboardImpl::processEvent(XEvent& windowEvent)
break; break;
} }
else if ((selectionRequestEvent.target == XA_STRING) || if ((selectionRequestEvent.target == XA_STRING) ||
((m_utf8String == None) && (selectionRequestEvent.target == m_text))) ((m_utf8String == None) && (selectionRequestEvent.target == m_text)))
{ {
// Respond to a request for conversion to a Latin-1 string // Respond to a request for conversion to a Latin-1 string
const std::string data = m_clipboardContents.toAnsiString(); const std::string data = m_clipboardContents.toAnsiString();
@ -340,8 +340,8 @@ void ClipboardImpl::processEvent(XEvent& windowEvent)
break; break;
} }
else if ((m_utf8String != None) && if ((m_utf8String != None) &&
((selectionRequestEvent.target == m_utf8String) || (selectionRequestEvent.target == m_text))) ((selectionRequestEvent.target == m_utf8String) || (selectionRequestEvent.target == m_text)))
{ {
// Respond to a request for conversion to a UTF-8 string // Respond to a request for conversion to a UTF-8 string
// or an encoding of our choosing (we always choose UTF-8) // or an encoding of our choosing (we always choose UTF-8)

View File

@ -70,8 +70,8 @@ bool CursorImpl::loadFromPixels(const std::uint8_t* pixels, Vector2u size, Vecto
if (isColorCursorSupported()) if (isColorCursorSupported())
return loadFromPixelsARGB(pixels, size, hotspot); return loadFromPixelsARGB(pixels, size, hotspot);
else
return loadFromPixelsMonochrome(pixels, size, hotspot); return loadFromPixelsMonochrome(pixels, size, hotspot);
} }

View File

@ -379,13 +379,11 @@ XVisualInfo GlxContext::selectBestVisual(::Display* display, unsigned int bitsPe
return bestVisual; 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 {};
} }

View File

@ -158,10 +158,8 @@ Vector2i getMousePosition(const WindowBase& relativeTo)
return {x, y}; return {x, y};
} }
else
{ return {};
return {};
}
} }

View File

@ -141,7 +141,7 @@ void updatePluggedList(udev_device* udevDevice = nullptr)
recordIt->systemPath = syspath ? syspath : ""; recordIt->systemPath = syspath ? syspath : "";
break; break;
} }
else if (std::strstr(action, "remove")) if (std::strstr(action, "remove"))
{ {
recordIt->plugged = false; recordIt->plugged = false;
break; break;
@ -561,10 +561,8 @@ bool JoystickImpl::open(unsigned int index)
return true; return true;
} }
else
{ err() << "Failed to open joystick " << devnode << ": " << errno << std::endl;
err() << "Failed to open joystick " << devnode << ": " << errno << std::endl;
}
} }
return false; return false;

View File

@ -767,22 +767,18 @@ void WindowImplX11::processEvents()
event = nextEvent; event = nextEvent;
break; break;
} }
else
{ // Ignore both events
// Ignore both events processThisEvent = false;
processThisEvent = false; break;
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;
} }
// 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 else
{ {
@ -2106,8 +2102,8 @@ RROutput WindowImplX11::getOutputPrimary(::Window& rootWindow, XRRScreenResource
// Check if returned output is valid, otherwise use the first screen // Check if returned output is valid, otherwise use the first screen
if (output == None) if (output == None)
return res->outputs[0]; return res->outputs[0];
else
return output; return output;
} }

View File

@ -96,15 +96,11 @@ bool operator<(const VideoMode& left, const VideoMode& right)
{ {
return left.size.y < right.size.y; return left.size.y < right.size.y;
} }
else
{ return left.size.x < right.size.x;
return left.size.x < right.size.x;
}
}
else
{
return left.bitsPerPixel < right.bitsPerPixel;
} }
return left.bitsPerPixel < right.bitsPerPixel;
} }

View File

@ -117,11 +117,9 @@ bool CursorImpl::loadFromPixels(const std::uint8_t* pixels, Vector2u size, Vecto
{ {
return true; return true;
} }
else
{ err() << "Failed to create cursor from bitmaps" << std::endl;
err() << "Failed to create cursor from bitmaps" << std::endl; return false;
return false;
}
} }
@ -167,11 +165,9 @@ bool CursorImpl::loadFromSystem(Cursor::Type type)
{ {
return true; return true;
} }
else
{ err() << "Could not create copy of a system cursor" << std::endl;
err() << "Could not create copy of a system cursor" << std::endl; return false;
return false;
}
} }

View File

@ -711,10 +711,8 @@ Vector2i getMousePosition(const WindowBase& relativeTo)
ScreenToClient(handle, &point); ScreenToClient(handle, &point);
return {point.x, point.y}; return {point.x, point.y};
} }
else
{ return {};
return {};
}
} }

View File

@ -362,10 +362,8 @@ JoystickState JoystickImpl::update()
{ {
return updateDInputBuffered(); return updateDInputBuffered();
} }
else
{ return updateDInputPolled();
return updateDInputPolled();
}
} }
JoystickState state; JoystickState state;
@ -1147,7 +1145,7 @@ BOOL CALLBACK JoystickImpl::deviceObjectEnumerationCallback(const DIDEVICEOBJECT
return DIENUM_CONTINUE; return DIENUM_CONTINUE;
} }
else if (DIDFT_GETTYPE(deviceObjectInstance->dwType) & DIDFT_POV) if (DIDFT_GETTYPE(deviceObjectInstance->dwType) & DIDFT_POV)
{ {
// POVs // POVs
if (deviceObjectInstance->guidType == guids::GUID_POV) if (deviceObjectInstance->guidType == guids::GUID_POV)
@ -1161,7 +1159,7 @@ BOOL CALLBACK JoystickImpl::deviceObjectEnumerationCallback(const DIDEVICEOBJECT
return DIENUM_CONTINUE; return DIENUM_CONTINUE;
} }
else if (DIDFT_GETTYPE(deviceObjectInstance->dwType) & DIDFT_BUTTON) if (DIDFT_GETTYPE(deviceObjectInstance->dwType) & DIDFT_BUTTON)
{ {
// Buttons // Buttons
for (unsigned int i = 0; i < Joystick::ButtonCount; ++i) for (unsigned int i = 0; i < Joystick::ButtonCount; ++i)

View File

@ -164,16 +164,12 @@ bool Window::setActive(bool active) const
{ {
return true; return true;
} }
else
{ err() << "Failed to activate the window's context" << std::endl;
err() << "Failed to activate the window's context" << std::endl;
return false;
}
}
else
{
return false; return false;
} }
return false;
} }

View File

@ -47,10 +47,8 @@ String ClipboardImpl::getString()
return String::fromUtf8(utf8, utf8 + length); return String::fromUtf8(utf8, utf8 + length);
} }
else
{ return {};
return {};
}
} }

View File

@ -235,8 +235,8 @@ std::vector<sf::Vector2i> touchPositions;
{ {
if (index < touchPositions.size()) if (index < touchPositions.size())
return touchPositions[index]; return touchPositions[index];
else
return sf::Vector2i(-1, -1); return sf::Vector2i(-1, -1);
} }

View File

@ -41,8 +41,8 @@ NSCursor* loadFromSelector(SEL selector)
// The caller is responsible for retaining the cursor. // The caller is responsible for retaining the cursor.
if ([NSCursor respondsToSelector:selector]) if ([NSCursor respondsToSelector:selector])
return [NSCursor performSelector:selector]; return [NSCursor performSelector:selector];
else
return nil; return nil;
} }
} }

View File

@ -128,11 +128,9 @@ bool SFContext::makeCurrent(bool current)
[m_context makeCurrentContext]; [m_context makeCurrentContext];
return m_context == [NSOpenGLContext currentContext]; // Should be true. return m_context == [NSOpenGLContext currentContext]; // Should be true.
} }
else
{ [NSOpenGLContext clearCurrentContext];
[NSOpenGLContext clearCurrentContext]; return m_context != [NSOpenGLContext currentContext]; // Should be true.
return m_context != [NSOpenGLContext currentContext]; // Should be true.
}
} }

View File

@ -197,15 +197,13 @@
{ {
return false; return false;
} }
else if ([[event characters] length] > 0) if ([[event characters] length] > 0)
{ {
unichar code = [[event characters] characterAtIndex:0]; unichar code = [[event characters] characterAtIndex:0];
return (code < 0xF700) || (code > 0xF8FF); return (code < 0xF700) || (code > 0xF8FF);
} }
else
{ return true;
return true;
}
} }
@end @end