From 8d19207adca24d04e98247f10ac17084f7e7a26e Mon Sep 17 00:00:00 2001 From: Robert Adam Date: Sat, 29 Oct 2022 09:58:24 +0200 Subject: [PATCH 01/13] DOCS: Add comments to PacketDataStream impl --- src/PacketDataStream.h | 20 +++++++++++++------- 1 file changed, 13 insertions(+), 7 deletions(-) diff --git a/src/PacketDataStream.h b/src/PacketDataStream.h index c86b72db28b..e559a5f9c16 100644 --- a/src/PacketDataStream.h +++ b/src/PacketDataStream.h @@ -144,40 +144,46 @@ class PacketDataStream { // Signed number. i = ~i; if (i <= 0x3) { - // Shortcase for -1 to -4 + // Special case for -1 to -4. The most significant bits of the first byte must be (in binary) 111111 + // followed by the 2 bits representing the absolute value of the encoded number. Shortcase for -1 to -4 append(0xFC | i); return *this; } else { + // Add flag byte, whose most significant bits are (in binary) 111110 that indicates + // that what follows is the varint encoding of the absolute value of i, but that the + // value itself is supposed to be negative. append(0xF8); } } if (i < 0x80) { - // Need top bit clear + // Encode as 7-bit, positive number -> most significant bit of first byte must be zero append(i); } else if (i < 0x4000) { - // Need top two bits clear + // Encode as 14-bit, positive number -> most significant bits of first byte must be (in binary) 10 append((i >> 8) | 0x80); append(i & 0xFF); } else if (i < 0x200000) { - // Need top three bits clear + // Encode as 21-bit, positive number -> most significant bits of first byte must be (in binary) 110 append((i >> 16) | 0xC0); append((i >> 8) & 0xFF); append(i & 0xFF); } else if (i < 0x10000000) { - // Need top four bits clear + // Encode as 28-bit, positive number -> most significant bits of first byte must be (in binary) 1110 append((i >> 24) | 0xE0); append((i >> 16) & 0xFF); append((i >> 8) & 0xFF); append(i & 0xFF); } else if (i < 0x100000000LL) { - // It's a full 32-bit integer. + // Encode as 32-bit, positive number -> most significant bits of first byte must be (in binary) 111100 + // Remaining bits in first byte remain unused append(0xF0); append((i >> 24) & 0xFF); append((i >> 16) & 0xFF); append((i >> 8) & 0xFF); append(i & 0xFF); } else { - // It's a 64-bit value. + // Encode as 64-bit, positive number -> most significant bits of first byte must be (in binary) 111101 + // Remaining bits in first byte remain unused append(0xF4); append((i >> 56) & 0xFF); append((i >> 48) & 0xFF); From 34f334b29f621adbb2cae9ef39ca8947a6a9b031 Mon Sep 17 00:00:00 2001 From: Robert Adam Date: Sun, 31 Dec 2023 09:50:23 +0100 Subject: [PATCH 02/13] MAINT: Update nlohmann::json --- .gitmodules | 2 +- 3rdparty/nlohmann_json | 2 +- src/mumble/CMakeLists.txt | 3 ++- 3 files changed, 4 insertions(+), 3 deletions(-) diff --git a/.gitmodules b/.gitmodules index c19da4099cd..ce395a65949 100644 --- a/.gitmodules +++ b/.gitmodules @@ -18,7 +18,7 @@ url = https://github.com/wolfpld/tracy.git [submodule "3rdparty/nlohmann_json"] path = 3rdparty/nlohmann_json - url = https://github.com/ArthurSonzogni/nlohmann_json_cmake_fetchcontent + url = https://github.com/nlohmann/json.git [submodule "3rdparty/gsl"] path = 3rdparty/gsl url = https://github.com/microsoft/GSL.git diff --git a/3rdparty/nlohmann_json b/3rdparty/nlohmann_json index b48095ee99a..9cca280a4d0 160000 --- a/3rdparty/nlohmann_json +++ b/3rdparty/nlohmann_json @@ -1 +1 @@ -Subproject commit b48095ee99aff048dc4760dd644b848bc1e6f0c3 +Subproject commit 9cca280a4d0ccf0c08f47a99aa71d1b0e52f8d03 diff --git a/src/mumble/CMakeLists.txt b/src/mumble/CMakeLists.txt index f09cd697bd1..195b3e125a8 100644 --- a/src/mumble/CMakeLists.txt +++ b/src/mumble/CMakeLists.txt @@ -491,7 +491,8 @@ endif() if(bundled-json) set(JSON_BuildTests OFF CACHE INTERNAL "") - set(JSON_ImplicitConversions OFF CACHE INTERNAL "") + set(JSON_ImplicitConversions ON CACHE INTERNAL "") + set(JSON_SystemInclude ON CACHE INTERNAL "") add_subdirectory("${3RDPARTY_DIR}/nlohmann_json/" "${CMAKE_CURRENT_BINARY_DIR}/nlohmann_json/" EXCLUDE_FROM_ALL) else() find_pkg("nlohmann_json" REQUIRED) From 9d5f484b7dda2d3da9bf750331dcf9fbb8cad571 Mon Sep 17 00:00:00 2001 From: Robert Adam Date: Sun, 13 Nov 2022 17:30:00 +0100 Subject: [PATCH 03/13] MAINT: Add cmake-compiler-flags submodule --- .gitmodules | 3 +++ 3rdparty/cmake-compiler-flags | 1 + 2 files changed, 4 insertions(+) create mode 160000 3rdparty/cmake-compiler-flags diff --git a/.gitmodules b/.gitmodules index ce395a65949..cc1152655c0 100644 --- a/.gitmodules +++ b/.gitmodules @@ -25,3 +25,6 @@ [submodule "3rdparty/SPSCQueue"] path = 3rdparty/SPSCQueue url = https://github.com/rigtorp/SPSCQueue.git +[submodule "3rdparty/cmake-compiler-flags"] + path = 3rdparty/cmake-compiler-flags + url = https://github.com/Krzmbrzl/cmake-compiler-flags.git diff --git a/3rdparty/cmake-compiler-flags b/3rdparty/cmake-compiler-flags new file mode 160000 index 00000000000..c0e8552d47b --- /dev/null +++ b/3rdparty/cmake-compiler-flags @@ -0,0 +1 @@ +Subproject commit c0e8552d47be4270a1c31b0be693c43faff51537 From f8c79aed156b9d36f7a5567781f5c7f74226ab17 Mon Sep 17 00:00:00 2001 From: Robert Adam Date: Thu, 4 Jan 2024 14:02:36 +0100 Subject: [PATCH 04/13] MAINT: Update SPSCQueue submodule We use our own fork in order to be able to mark included files as system files to avoid warnings from them. --- .gitmodules | 2 +- 3rdparty/SPSCQueue | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.gitmodules b/.gitmodules index cc1152655c0..18a21bf33f0 100644 --- a/.gitmodules +++ b/.gitmodules @@ -24,7 +24,7 @@ url = https://github.com/microsoft/GSL.git [submodule "3rdparty/SPSCQueue"] path = 3rdparty/SPSCQueue - url = https://github.com/rigtorp/SPSCQueue.git + url = https://github.com/mumble-voip/SPSCQueue.git [submodule "3rdparty/cmake-compiler-flags"] path = 3rdparty/cmake-compiler-flags url = https://github.com/Krzmbrzl/cmake-compiler-flags.git diff --git a/3rdparty/SPSCQueue b/3rdparty/SPSCQueue index 945c7c532ba..fefa146bd25 160000 --- a/3rdparty/SPSCQueue +++ b/3rdparty/SPSCQueue @@ -1 +1 @@ -Subproject commit 945c7c532bac85f028b386f2e2ab74d38e93e333 +Subproject commit fefa146bd2552d1bfb6e8066d5e5d624f32bb40e From 2e7e7ee6661b2f372be9fddf7fe4308fd2c367a3 Mon Sep 17 00:00:00 2001 From: Robert Adam Date: Sun, 13 Nov 2022 17:30:54 +0100 Subject: [PATCH 05/13] BUILD(cmake): Module to fetch compiler-dependent flags Using a separate module instead of encoding the different flags for different compilers into our own cmake source code should clean things up a bit and make the intention more clear (as the flags sometimes have rather cryptic names). This commit also contains a functional change in that it removes the "fast-math" compile option (from optimized builds) as this is incompatible with at least Opus. --- CMakeLists.txt | 1 + cmake/compiler.cmake | 56 ++++++++++++++++++++---------------------- overlay/CMakeLists.txt | 3 +++ src/CMakeLists.txt | 2 ++ 4 files changed, 32 insertions(+), 30 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index c5180625424..1d45412096d 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -44,6 +44,7 @@ list(APPEND CMAKE_MODULE_PATH "${CMAKE_SOURCE_DIR}/cmake" "${CMAKE_SOURCE_DIR}/cmake/FindModules" "${3RDPARTY_DIR}/FindPythonInterpreter" + "${3RDPARTY_DIR}/cmake-compiler-flags" ) diff --git a/cmake/compiler.cmake b/cmake/compiler.cmake index 7e7b4582217..b76d791059e 100644 --- a/cmake/compiler.cmake +++ b/cmake/compiler.cmake @@ -3,6 +3,7 @@ # that can be found in the LICENSE file at the root of the # Mumble source tree or at . +include(CompilerFlags) include(CheckCXXCompilerFlag) if(${CMAKE_SIZEOF_VOID_P} EQUAL 8) @@ -20,15 +21,26 @@ if(WIN32) add_compile_definitions(_WIN32_WINNT=0x0601) endif() -if(MSVC) - add_compile_options( - "$<$:/Ox>" - "$<$:/fp:fast>" - ) +set(WANTED_FEATURES "ENABLE_MOST_WARNINGS") + +if(CMAKE_BUILD_TYPE STREQUAL "Release") + list(APPEND WANTED_FEATURES "OPTIMIZE_FOR_SPEED") +elseif(CMAKE_BUILD_TYPE STREQUAL "Debug") + list(APPEND WANTED_FEATURES "OPTIMIZE_FOR_DEBUG") +endif() - # Needed in order to not run into C1128: number of sections exceeded object file format limit - add_compile_options(/bigobj) +if(warnings-as-errors) + list(APPEND WANTED_FEATURES "ENABLE_WARNINGS_AS_ERRORS") +endif() + +get_compiler_flags( + ${WANTED_FEATURES} + OUTPUT_VARIABLE MUMBLE_COMPILER_FLAGS +) + +message(STATUS "Using (among others) the following compiler flags: ${MUMBLE_COMPILER_FLAGS}") +if(MSVC) if(32_BIT) # SSE2 code is generated by default, unless an explicit arch is set. # Our 32 bit binaries should not contain any SSE2 code, so override the default. @@ -54,35 +66,17 @@ if(MSVC) "/ignore:4099" ) endif() - - if(warnings-as-errors) - add_compile_options("/WX") - add_link_options("/WX") - endif() elseif(UNIX OR MINGW) add_compile_options( "-fvisibility=hidden" - "-Wall" - "-Wextra" ) - # Avoid "File too big" error - check_cxx_compiler_flag("-Wa,-mbig-obj" COMPILER_HAS_MBIG_OBJ) - if (${COMPILER_HAS_MBIG_OBJ}) - add_compile_options("-Wa,-mbig-obj") - endif() - if(optimize) add_compile_options( - "-O3" "-march=native" ) endif() - if(warnings-as-errors) - add_compile_options("-Werror") - endif() - if(APPLE) add_link_options("-Wl,-dead_strip") @@ -129,9 +123,11 @@ elseif(UNIX OR MINGW) endif() function(target_disable_warnings TARGET) - if(MSVC) - target_compile_options(${TARGET} PRIVATE "/w") - else() - target_compile_options(${TARGET} PRIVATE "-w") - endif() + get_compiler_flags( + DISABLE_ALL_WARNINGS + DISABLE_DEFAULT_FLAGS + OUTPUT_VARIABLE NO_WARNING_FLAGS + ) + + target_compile_options(${TARGET} PRIVATE ${NO_WARNING_FLAGS}) endfunction() diff --git a/overlay/CMakeLists.txt b/overlay/CMakeLists.txt index 2f3dc8814af..e1baab678e2 100644 --- a/overlay/CMakeLists.txt +++ b/overlay/CMakeLists.txt @@ -14,6 +14,7 @@ if(BUILD_OVERLAY_XCOMPILE) LANGUAGES CXX ) + list(APPEND CMAKE_MODULE_PATH "${3RDPARTY_DIR}/cmake-compiler-flags") include("${MUMBLE_SOURCE_ROOT}/cmake/compiler.cmake") endif() @@ -162,6 +163,7 @@ if(64_BIT AND MSVC) "-DMUMBLE_SOURCE_ROOT=${CMAKE_SOURCE_DIR}" "-DMUMBLE_BINARY_DIR=${CMAKE_BINARY_DIR}" "-DCMAKE_BUILD_TYPE=${CMAKE_BUILD_TYPE}" + "-D3RDPARTY_DIR=${3RDPARTY_DIR}" # Force MSVC, because CMake prioritizes MinGW over it. "-DCMAKE_C_COMPILER=cl.exe" "-DCMAKE_CXX_COMPILER=cl.exe" @@ -184,6 +186,7 @@ if(64_BIT AND MSVC) "-DMUMBLE_SOURCE_ROOT=${CMAKE_SOURCE_DIR}" "-DMUMBLE_BINARY_DIR=${CMAKE_BINARY_DIR}" "-DCMAKE_BUILD_TYPE=${CMAKE_BUILD_TYPE}" + "-D3RDPARTY_DIR=${3RDPARTY_DIR}" # Force MSVC, because CMake prioritizes MinGW over it. "-DCMAKE_C_COMPILER=cl.exe" "-DCMAKE_CXX_COMPILER=cl.exe" diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 0bd281cc5a6..f1b7cb02df7 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -34,6 +34,8 @@ find_pkg(OpenSSL find_pkg(Protobuf REQUIRED) +add_compile_options(${MUMBLE_COMPILER_FLAGS}) + add_library(shared STATIC) protobuf_generate(LANGUAGE cpp TARGET shared PROTOS ${PROTO_FILE} OUT_VAR BUILT_PROTO_FILES) From 1e365e2f4346f8fa58bfd3a9de93d9bc70cf0127 Mon Sep 17 00:00:00 2001 From: Robert Adam Date: Sun, 13 Nov 2022 18:48:45 +0100 Subject: [PATCH 06/13] BUILD(cmake): Ensure plain char type is always signed This eradicates some platform differences Fixes #3845 --- cmake/compiler.cmake | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cmake/compiler.cmake b/cmake/compiler.cmake index b76d791059e..856bae18082 100644 --- a/cmake/compiler.cmake +++ b/cmake/compiler.cmake @@ -21,7 +21,7 @@ if(WIN32) add_compile_definitions(_WIN32_WINNT=0x0601) endif() -set(WANTED_FEATURES "ENABLE_MOST_WARNINGS") +set(WANTED_FEATURES "ENABLE_MOST_WARNINGS" "ENSURE_DEFAULT_CHAR_IS_SIGNED") if(CMAKE_BUILD_TYPE STREQUAL "Release") list(APPEND WANTED_FEATURES "OPTIMIZE_FOR_SPEED") From efa86846b16ad5dfeb605beddad8b657ef2a36fd Mon Sep 17 00:00:00 2001 From: Robert Adam Date: Sat, 31 Dec 2022 18:50:46 +0100 Subject: [PATCH 07/13] BUILD(cmake): Explicitly disable compiler extensions --- CMakeLists.txt | 1 + 1 file changed, 1 insertion(+) diff --git a/CMakeLists.txt b/CMakeLists.txt index 1d45412096d..d4738dc686f 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -38,6 +38,7 @@ set(3RDPARTY_DIR "${CMAKE_SOURCE_DIR}/3rdparty") set(PLUGINS_DIR "${CMAKE_SOURCE_DIR}/plugins") set(CMAKE_CXX_STANDARD 14) +set(CMAKE_CXX_EXTENSIONS OFF) set(CMAKE_OSX_DEPLOYMENT_TARGET 10.13) list(APPEND CMAKE_MODULE_PATH From 04fb05c1f38011881717256ba73b1d0d219a857a Mon Sep 17 00:00:00 2001 From: Robert Adam Date: Sun, 31 Dec 2023 10:00:40 +0100 Subject: [PATCH 08/13] BUILD: Silence Windows CRT security warnings --- cmake/os.cmake | 2 ++ 1 file changed, 2 insertions(+) diff --git a/cmake/os.cmake b/cmake/os.cmake index a8f7ce7512e..97a6696f9eb 100644 --- a/cmake/os.cmake +++ b/cmake/os.cmake @@ -34,6 +34,8 @@ if(WIN32) "-DWIN32_LEAN_AND_MEAN" # Prevent Windows headers from defining the macros "min" and "max" that mess up e.g. std::min usage "-DNOMINMAX" + # Prevent warnings such as "use strcpy_s instead of strcpy" + "-D_CRT_SECURE_NO_WARNINGS" ) else() if(${CMAKE_SYSTEM_NAME} STREQUAL "FreeBSD") From 5a38d322d3879dd11d4f91c60640a19c43d154e5 Mon Sep 17 00:00:00 2001 From: Robert Adam Date: Sat, 31 Dec 2022 19:31:14 +0100 Subject: [PATCH 09/13] REFAC: Replace goto with RAII --- src/mumble/OSS.cpp | 30 +++++++++++++++++++++++------- 1 file changed, 23 insertions(+), 7 deletions(-) diff --git a/src/mumble/OSS.cpp b/src/mumble/OSS.cpp index 8bca8fdc15d..c1a0f4a0123 100644 --- a/src/mumble/OSS.cpp +++ b/src/mumble/OSS.cpp @@ -14,6 +14,9 @@ #include "User.h" #include "Global.h" +#include +#include + #define NBLOCKS 8 class OSSEnumerator { @@ -175,6 +178,22 @@ OSSInput::~OSSInput() { wait(); } +class FileDescriptor { +public: + FileDescriptor(int fd = -1) : m_fd(fd) {} + ~FileDescriptor() { + if (m_fd != -1) { + close(m_fd); + m_fd = -1; + } + } + + operator int() const { return m_fd; } + +private: + int m_fd = -1; +}; + void OSSInput::run() { QByteArray device = cards->qhDevices.value(Global::get().s.qsOSSInput).toLatin1(); if (device.isEmpty()) { @@ -182,7 +201,7 @@ void OSSInput::run() { device = cards->qhDevices.value(QString()).toLatin1(); } - int fd = open(device.constData(), O_RDONLY, 0); + FileDescriptor fd(open(device.constData(), O_RDONLY, 0)); if (fd == -1) { qWarning("OSSInput: Failed to open %s", device.constData()); return; @@ -193,20 +212,20 @@ void OSSInput::run() { ival = AFMT_S16_NE; if ((ioctl(fd, SNDCTL_DSP_SETFMT, &ival) == -1) || (ival != AFMT_S16_NE)) { qWarning("OSSInput: Failed to set sound format"); - goto out; + return; } ival = 1; if ((ioctl(fd, SNDCTL_DSP_CHANNELS, &ival) == -1)) { qWarning("OSSInput: Failed to set mono mode"); - goto out; + return; } iMicChannels = ival; ival = SAMPLE_RATE; if (ioctl(fd, SNDCTL_DSP_SPEED, &ival) == -1) { qWarning("OSSInput: Failed to set speed"); - goto out; + return; } iMicFreq = ival; @@ -229,9 +248,6 @@ void OSSInput::run() { qWarning("OSSInput: Releasing."); ioctl(fd, SNDCTL_DSP_RESET, nullptr); - -out: - close(fd); } OSSOutput::OSSOutput() { From 6c565689ae2f5db2cd2104bfdebe36a926e7e079 Mon Sep 17 00:00:00 2001 From: Robert Adam Date: Fri, 3 Feb 2023 14:51:10 +0100 Subject: [PATCH 10/13] REFAC: Get rid of union in HostAddress The way this union was accessed is not covered by the C++ standard and was therefore undefined behavior. Therefore, the code was rewritten to stick to standard C++. --- src/HostAddress.cpp | 165 +++++++++++++++++++++------------ src/HostAddress.h | 40 ++++---- src/ServerAddress.cpp | 3 - src/ServerAddress.h | 6 +- src/murmur/DBus.cpp | 2 +- src/murmur/MumbleServerIce.cpp | 25 ++--- src/murmur/Server.cpp | 5 +- 7 files changed, 148 insertions(+), 98 deletions(-) diff --git a/src/HostAddress.cpp b/src/HostAddress.cpp index fa5b1103688..432377379fc 100644 --- a/src/HostAddress.cpp +++ b/src/HostAddress.cpp @@ -20,102 +20,129 @@ # endif #endif -HostAddress::HostAddress() { - addr[0] = addr[1] = 0ULL; -} +#include +#include +#include HostAddress::HostAddress(const Q_IPV6ADDR &address) { - memcpy(qip6.c, address.c, 16); + memcpy(m_byteRepresentation.data(), address.c, m_byteRepresentation.size()); } HostAddress::HostAddress(const std::string &address) { - if (address.length() != 16) - addr[0] = addr[1] = 0ULL; - else - for (int i = 0; i < 16; ++i) - qip6[i] = address[i]; + if (address.length() != 16) { + // This is an invalid address -> reset the currently stored address + m_byteRepresentation.fill(0); + } else { + for (std::size_t i = 0; i < m_byteRepresentation.size(); ++i) { + m_byteRepresentation[i] = static_cast< unsigned char >(address[i]); + } + } } HostAddress::HostAddress(const QByteArray &address) { - if (address.length() != 16) - addr[0] = addr[1] = 0ULL; - else - for (int i = 0; i < 16; ++i) - qip6[i] = address[i]; + if (address.length() != 16) { + // This is an invalid address -> reset the currently stored address + m_byteRepresentation.fill(0); + } else { + for (unsigned int i = 0; i < m_byteRepresentation.size(); ++i) { + m_byteRepresentation[i] = static_cast< unsigned char >(address[i]); + } + } } HostAddress::HostAddress(const QHostAddress &address) { if (address.protocol() == QAbstractSocket::IPv6Protocol) { const Q_IPV6ADDR &a = address.toIPv6Address(); - memcpy(qip6.c, a.c, 16); + memcpy(m_byteRepresentation.data(), a.c, m_byteRepresentation.size()); } else { - addr[0] = 0ULL; - shorts[4] = 0; - shorts[5] = 0xffff; - hash[3] = htonl(address.toIPv4Address()); + fromIPv4(address.toIPv4Address()); } } HostAddress::HostAddress(const sockaddr_storage &address) { if (address.ss_family == AF_INET) { const struct sockaddr_in *in = reinterpret_cast< const struct sockaddr_in * >(&address); - addr[0] = 0ULL; - shorts[4] = 0; - shorts[5] = 0xffff; - hash[3] = in->sin_addr.s_addr; + fromIPv4(in->sin_addr.s_addr, false); } else if (address.ss_family == AF_INET6) { const struct sockaddr_in6 *in6 = reinterpret_cast< const struct sockaddr_in6 * >(&address); - memcpy(qip6.c, in6->sin6_addr.s6_addr, 16); + memcpy(m_byteRepresentation.data(), in6->sin6_addr.s6_addr, m_byteRepresentation.size()); } else { - addr[0] = addr[1] = 0ULL; + m_byteRepresentation.fill(0); } } +void HostAddress::fromIPv4(std::uint32_t address, bool convertToNetworkOrder) { + // Store IPv4 address in IPv6 format: + // - address is stored in the 4 last bytes in network byte order + // - the 2 bytes just before that are set to 0xFF respectively + m_byteRepresentation.fill(0); + + m_byteRepresentation[10] = 0xFF; + m_byteRepresentation[11] = 0xFF; + + if (convertToNetworkOrder) { + address = htonl(address); + } + + memcpy(&m_byteRepresentation[12], &address, sizeof(std::uint32_t)); +} + bool HostAddress::operator<(const HostAddress &other) const { - return memcmp(qip6.c, other.qip6.c, 16) < 0; + return m_byteRepresentation < other.m_byteRepresentation; } bool HostAddress::operator==(const HostAddress &other) const { - return ((addr[0] == other.addr[0]) && (addr[1] == other.addr[1])); + return m_byteRepresentation == other.m_byteRepresentation; } -bool HostAddress::match(const HostAddress &netmask, int bits) const { - quint64 mask[2]; +bool HostAddress::match(const HostAddress &netmask, unsigned int bits) const { + for (std::size_t i = 0; i < m_byteRepresentation.size(); ++i) { + if (bits >= 8) { + // Compare full byte + if (m_byteRepresentation[i] != netmask.m_byteRepresentation[i]) { + return false; + } + bits -= 8; + } else { + // Compare only the first bits bits (no this is not a typo) + using mask_t = std::uint8_t; + mask_t mask = + static_cast< mask_t >(std::numeric_limits< mask_t >::max() >> (sizeof(mask_t) * CHAR_BIT - bits)); + mask = static_cast< mask_t >(htons(mask)); + + if ((m_byteRepresentation[i] & mask) != (netmask.m_byteRepresentation[i] & mask)) { + return false; + } - if (bits == 128) { - mask[0] = mask[1] = 0xffffffffffffffffULL; - } else if (bits > 64) { - mask[0] = 0xffffffffffffffffULL; - mask[1] = SWAP64(~((1ULL << (128 - bits)) - 1)); - } else { - mask[0] = SWAP64(~((1ULL << (64 - bits)) - 1)); - mask[1] = 0ULL; + break; + } } - return ((addr[0] & mask[0]) == (netmask.addr[0] & mask[0])) && ((addr[1] & mask[1]) == (netmask.addr[1] & mask[1])); + + return true; } std::string HostAddress::toStdString() const { - return std::string(reinterpret_cast< const char * >(qip6.c), 16); + return std::string(reinterpret_cast< const char * >(m_byteRepresentation.data()), m_byteRepresentation.size()); } bool HostAddress::isV6() const { - return (addr[0] != 0ULL) || (shorts[4] != 0) || (shorts[5] != 0xffff); + std::uint64_t firstEightBytes = *(reinterpret_cast< const std::uint64_t * >(m_byteRepresentation.data())); + std::uint16_t bytesNineAndTen = *(reinterpret_cast< const std::uint16_t * >(&m_byteRepresentation[8])); + std::uint16_t bytesElevenAndTwelve = *(reinterpret_cast< const std::uint16_t * >(&m_byteRepresentation[10])); + return firstEightBytes != 0 || bytesNineAndTen != 0 || bytesElevenAndTwelve != 0xFFFF; } bool HostAddress::isValid() const { - return (addr[0] != 0ULL) || (addr[1] != 0ULL); + return m_byteRepresentation != decltype(m_byteRepresentation){}; } QHostAddress HostAddress::toAddress() const { - if (isV6()) - return QHostAddress(qip6); - else { - return QHostAddress(ntohl(hash[3])); - } + return QHostAddress(m_byteRepresentation.data()); } QByteArray HostAddress::toByteArray() const { - return QByteArray(reinterpret_cast< const char * >(qip6.c), 16); + return QByteArray(reinterpret_cast< const char * >(m_byteRepresentation.data()), + static_cast< int >(m_byteRepresentation.size())); } void HostAddress::toSockaddr(sockaddr_storage *dst) const { @@ -123,16 +150,34 @@ void HostAddress::toSockaddr(sockaddr_storage *dst) const { if (isV6()) { struct sockaddr_in6 *in6 = reinterpret_cast< struct sockaddr_in6 * >(dst); dst->ss_family = AF_INET6; - memcpy(in6->sin6_addr.s6_addr, qip6.c, 16); + memcpy(in6->sin6_addr.s6_addr, m_byteRepresentation.data(), m_byteRepresentation.size()); } else { struct sockaddr_in *in = reinterpret_cast< struct sockaddr_in * >(dst); dst->ss_family = AF_INET; - in->sin_addr.s_addr = hash[3]; + in->sin_addr.s_addr = toIPv4(); } } +std::uint32_t HostAddress::toIPv4() const { + // The IPv4 address is stored in the last four bytes (in network byte order) + return *(reinterpret_cast< const std::uint32_t * >(m_byteRepresentation[12])); +} + +const std::array< std::uint8_t, 16 > &HostAddress::getByteRepresentation() const { + return m_byteRepresentation; +} + +void HostAddress::reset() { + m_byteRepresentation.fill(0); +} + +void HostAddress::setByte(std::size_t idx, std::uint8_t value) { + assert(idx < m_byteRepresentation.size()); + m_byteRepresentation[idx] = value; +} + quint32 qHash(const HostAddress &ha) { - return (ha.hash[0] ^ ha.hash[1] ^ ha.hash[2] ^ ha.hash[3]); + return qHashRange(ha.m_byteRepresentation.begin(), ha.m_byteRepresentation.end()); } QString HostAddress::toString(bool bracketEnclosed) const { @@ -145,21 +190,19 @@ QString HostAddress::toString(bool bracketEnclosed) const { squareBracketOpen = "["; squareBracketClose = "]"; } -#if QT_VERSION >= 0x050500 - str = QString::asprintf("%s%x:%x:%x:%x:%x:%x:%x:%x%s", squareBracketOpen, ntohs(shorts[0]), - ntohs(shorts[1]), ntohs(shorts[2]), ntohs(shorts[3]), ntohs(shorts[4]), - ntohs(shorts[5]), ntohs(shorts[6]), ntohs(shorts[7]), squareBracketClose); -#else - // sprintf() has been deprecated in Qt 5.5 in favor for the static QString::asprintf() - str.sprintf("%s%x:%x:%x:%x:%x:%x:%x:%x%s", squareBracketOpen, ntohs(shorts[0]), ntohs(shorts[1]), - ntohs(shorts[2]), ntohs(shorts[3]), ntohs(shorts[4]), ntohs(shorts[5]), ntohs(shorts[6]), - ntohs(shorts[7]), squareBracketClose); -#endif + + const std::uint16_t *shortArray = reinterpret_cast< const std::uint16_t * >(m_byteRepresentation.data()); + + str = QString::asprintf("%s%x:%x:%x:%x:%x:%x:%x:%x%s", squareBracketOpen, ntohs(shortArray[0]), + ntohs(shortArray[1]), ntohs(shortArray[2]), ntohs(shortArray[3]), + ntohs(shortArray[4]), ntohs(shortArray[5]), ntohs(shortArray[6]), + ntohs(shortArray[7]), squareBracketClose); + return str.replace(QRegExp(QLatin1String("(:0)+")), QLatin1String(":")); } else { return bracketEnclosed ? QLatin1String("[::]") : QLatin1String("::"); } } else { - return QHostAddress(ntohl(hash[3])).toString(); + return toAddress().toString(); } } diff --git a/src/HostAddress.h b/src/HostAddress.h index 247fa2e5dcf..c9b693e88fa 100644 --- a/src/HostAddress.h +++ b/src/HostAddress.h @@ -6,34 +6,31 @@ #ifndef MUMBLE_HOSTADDRESS_H_ #define MUMBLE_HOSTADDRESS_H_ -#include -#include -#include -#include -#include +#include +#include +#include +#include + +#include +#include struct HostAddress { - union { - Q_IPV6ADDR qip6; - quint16 shorts[8]; - quint32 hash[4]; - quint64 addr[2]; - }; - - HostAddress(); + HostAddress() = default; HostAddress(const Q_IPV6ADDR &); HostAddress(const std::string &); HostAddress(const QHostAddress &); HostAddress(const QByteArray &); HostAddress(const struct sockaddr_storage &); + void fromIPv4(std::uint32_t address, bool convertToNetworkOrder = true); + bool isV6() const; bool isValid() const; bool operator<(const HostAddress &) const; bool operator==(const HostAddress &) const; - bool match(const HostAddress &, int bits) const; + bool match(const HostAddress &, unsigned int bits) const; QString toString(bool bracketEnclosed = true) const; @@ -41,10 +38,21 @@ struct HostAddress { QHostAddress toAddress() const; QByteArray toByteArray() const; void toSockaddr(struct sockaddr_storage *dst) const; + std::uint32_t toIPv4() const; + + const std::array< std::uint8_t, 16 > &getByteRepresentation() const; + + void reset(); + + void setByte(std::size_t idx, std::uint8_t value); + + friend quint32 qHash(const HostAddress &); + +private: + // Binary representation of an IPv6 address + std::array< std::uint8_t, 16 > m_byteRepresentation; }; Q_DECLARE_TYPEINFO(HostAddress, Q_MOVABLE_TYPE); -quint32 qHash(const HostAddress &); - #endif diff --git a/src/ServerAddress.cpp b/src/ServerAddress.cpp index 048c6f9a57f..a67ee71828d 100644 --- a/src/ServerAddress.cpp +++ b/src/ServerAddress.cpp @@ -5,9 +5,6 @@ #include "ServerAddress.h" -ServerAddress::ServerAddress() : port(0) { -} - ServerAddress::ServerAddress(HostAddress host_, unsigned short port_) : host(host_), port(port_) { } diff --git a/src/ServerAddress.h b/src/ServerAddress.h index 23b10812f1e..e0424d96d7b 100644 --- a/src/ServerAddress.h +++ b/src/ServerAddress.h @@ -14,13 +14,13 @@ /// address consisting of a HostAddress /// and a port. struct ServerAddress { - HostAddress host; - unsigned short port; + HostAddress host = {}; + unsigned short port = 0; /// Construct a default ServerAddress. /// The default ServerAddress value is considered /// invalid per the |isValid| method. - ServerAddress(); + ServerAddress() = default; /// Construct a ServerAddress pointing to |host_| and |port_|. ServerAddress(HostAddress host_, unsigned short port_); diff --git a/src/murmur/DBus.cpp b/src/murmur/DBus.cpp index cecc80aa358..aaa9fe66ed0 100644 --- a/src/murmur/DBus.cpp +++ b/src/murmur/DBus.cpp @@ -766,7 +766,7 @@ GroupInfo::GroupInfo(const Group *g) : inherited(false) { } BanInfo::BanInfo(const Ban &b) { - address = ntohl(b.haAddress.hash[3]); + address = ntohl(b.haAddress.toIPv4()); bits = b.iMask; } diff --git a/src/murmur/MumbleServerIce.cpp b/src/murmur/MumbleServerIce.cpp index fcec475dc7f..b2a6f8696d2 100644 --- a/src/murmur/MumbleServerIce.cpp +++ b/src/murmur/MumbleServerIce.cpp @@ -132,9 +132,9 @@ static void userToUser(const ::User *p, ::MumbleServer::User &mp) { #endif ::MumbleServer::NetAddress addr(16, 0); - const Q_IPV6ADDR &a = u->haAddress.qip6; - for (int i = 0; i < 16; ++i) - addr[i] = a[i]; + for (unsigned int i = 0; i < 16; ++i) { + addr[i] = u->haAddress.getByteRepresentation()[i]; + } mp.address = addr; } @@ -172,9 +172,9 @@ static void groupToGroup(const ::Group *g, ::MumbleServer::Group &mg) { static void banToBan(const ::Ban &b, ::MumbleServer::Ban &mb) { ::MumbleServer::NetAddress addr(16, 0); - const Q_IPV6ADDR &a = b.haAddress.qip6; - for (int i = 0; i < 16; ++i) - addr[i] = a[i]; + for (unsigned int i = 0; i < 16; ++i) { + addr[i] = b.haAddress.getByteRepresentation()[i]; + } mb.address = addr; mb.bits = b.iMask; @@ -186,12 +186,13 @@ static void banToBan(const ::Ban &b, ::MumbleServer::Ban &mb) { } static void banToBan(const ::MumbleServer::Ban &mb, ::Ban &b) { - if (mb.address.size() != 16) - for (int i = 0; i < 16; ++i) - b.haAddress.qip6[i] = 0; - else - for (int i = 0; i < 16; ++i) - b.haAddress.qip6[i] = mb.address[i]; + if (mb.address.size() != 16) { + b.haAddress.reset(); + } else { + for (unsigned int i = 0; i < 16; ++i) { + b.haAddress.setByte(i, mb.address[i]); + } + } b.iMask = mb.bits; b.qsUsername = u8(mb.name); b.qsHash = u8(mb.hash); diff --git a/src/murmur/Server.cpp b/src/murmur/Server.cpp index 55682804a9f..795b30beae9 100644 --- a/src/murmur/Server.cpp +++ b/src/murmur/Server.cpp @@ -1064,7 +1064,8 @@ void Server::sendMessage(ServerUser &u, const unsigned char *data, int len, QByt cmsg->cmsg_len = CMSG_LEN(sizeof(struct in6_pktinfo)); struct in6_pktinfo *pktinfo = reinterpret_cast< struct in6_pktinfo * >(CMSG_DATA(cmsg)); memset(pktinfo, 0, sizeof(*pktinfo)); - memcpy(&pktinfo->ipi6_addr.s6_addr[0], &tcpha.qip6.c[0], sizeof(pktinfo->ipi6_addr.s6_addr)); + memcpy(&pktinfo->ipi6_addr.s6_addr[0], tcpha.getByteRepresentation().data(), + sizeof(pktinfo->ipi6_addr.s6_addr)); } else { cmsg->cmsg_level = IPPROTO_IP; cmsg->cmsg_type = IP_PKTINFO; @@ -1073,7 +1074,7 @@ void Server::sendMessage(ServerUser &u, const unsigned char *data, int len, QByt memset(pktinfo, 0, sizeof(*pktinfo)); if (tcpha.isV6()) return; - pktinfo->ipi_spec_dst.s_addr = tcpha.hash[3]; + pktinfo->ipi_spec_dst.s_addr = tcpha.toIPv4(); } From ded91ed2c8d771d627d0c5d7c04bfcc79932af11 Mon Sep 17 00:00:00 2001 From: Robert Adam Date: Fri, 5 Jan 2024 09:02:37 +0100 Subject: [PATCH 11/13] FIX(client): Migration of GKey shortcuts The migration path was implemented in 0e17c5394c5597b746c6076d16c732e2a4a04e7f but the QUuid object created for the GKey keyboard shortcuts had an error in the constructor arguments (wrong pairing of bytes) which would lead to some bytes being discarded and thus to a different (invalid) QUuid. This has been fixed. --- src/mumble/GlobalShortcut_win.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/mumble/GlobalShortcut_win.cpp b/src/mumble/GlobalShortcut_win.cpp index dcd7f4bc547..36353ed9e77 100644 --- a/src/mumble/GlobalShortcut_win.cpp +++ b/src/mumble/GlobalShortcut_win.cpp @@ -212,7 +212,7 @@ QList< Shortcut > GlobalShortcutWin::migrateSettings(const QList< Shortcut > &ol constexpr QUuid KEYBOARD_UUID(0x6F1D2B61, 0xD5A0, 0x11CF, 0xBF, 0xC7, 0x44, 0x45, 0x53, 0x54, 0x00, 0x00); constexpr QUuid MOUSE_UUID(0x6F1D2B60, 0xD5A0, 0x11CF, 0xBF, 0xC7, 0x44, 0x45, 0x53, 0x54, 0x00, 0x00); constexpr QUuid XINPUT_UUID(0xCA3937E3, 0x640C, 0x4D9E, 0x9E, 0xF3, 0x90, 0x3F, 0x8B, 0x4F, 0xBC, 0xAB); - constexpr QUuid GKEY_KEYBOARD_UUID(0x153E64E6, 0x98C8, 0x4E, 0x03, 0x80EF, 0x5F, 0xFD, 0x33, 0xD2, 0x5B, 0x8A); + constexpr QUuid GKEY_KEYBOARD_UUID(0x153E64E6, 0x98C8, 0x4E03, 0x80, 0xEF, 0x5F, 0xFD, 0x33, 0xD2, 0x5B, 0x8A); constexpr QUuid GKEY_MOUSE_UUID(0xC41E60AF, 0x9022, 0x46CF, 0xBC, 0x39, 0x37, 0x98, 0x10, 0x82, 0xD7, 0x16); QList< Shortcut > newShortcuts; From b5a67c05fb54e030ddadf6219e350fb2ac9eb7f6 Mon Sep 17 00:00:00 2001 From: Robert Adam Date: Sun, 7 Jan 2024 17:08:57 +0100 Subject: [PATCH 12/13] REFAC: Fix tons of warnings and non-portable code In various places we relied on compiler extensions such as variable-length arrays on the stack or using non-standard escape sequences. In order to make our code as portable as possible, these parts of the code have been refactored to only use standard C++. Furthermore, the new warning settings triggered a bunch of new warnings all over the place that have been addressed by this commit. --- src/Channel.cpp | 10 +- src/Channel.h | 10 +- src/ChannelListenerManager.cpp | 26 +-- src/ChannelListenerManager.h | 32 +-- src/Connection.cpp | 12 +- src/EnvUtils.cpp | 2 +- src/EnvUtils.h | 2 +- src/LogEmitter.cpp | 5 +- src/MumbleConstants.h | 6 +- src/MumbleProtocol.cpp | 51 ++--- src/MumbleProtocol.h | 8 +- src/OSInfo.cpp | 175 ++++------------- src/PacketDataStream.h | 25 +-- src/ProcessResolver.cpp | 10 +- src/ProtoUtils.cpp | 2 +- src/ProtoUtils.h | 2 +- src/QtUtils.cpp | 4 +- src/QtUtils.h | 8 +- src/SSLLocks.cpp | 6 +- src/Utils.h | 7 +- src/Version.cpp | 8 +- src/Version.h | 6 +- src/VolumeAdjustment.cpp | 8 +- src/crypto/CryptStateOCB2.cpp | 14 +- src/crypto/CryptographicHash.cpp | 2 +- src/crypto/CryptographicRandom.cpp | 5 +- src/mumble/ACLEditor.cpp | 38 ++-- src/mumble/ACLEditor.h | 6 +- src/mumble/ALSAAudio.cpp | 35 ++-- src/mumble/API.h | 16 +- src/mumble/API_v_1_x_x.cpp | 66 ++++--- src/mumble/ASIOInput.cpp | 17 +- src/mumble/Audio.cpp | 12 +- src/mumble/Audio.h | 3 +- src/mumble/AudioConfigDialog.cpp | 48 ++--- src/mumble/AudioInput.cpp | 61 +++--- src/mumble/AudioInput.h | 5 +- src/mumble/AudioOutput.cpp | 52 ++--- src/mumble/AudioOutputCache.cpp | 4 +- src/mumble/AudioOutputSample.cpp | 15 +- src/mumble/AudioOutputSpeech.cpp | 54 ++--- src/mumble/AudioStats.cpp | 74 +++---- src/mumble/AudioWizard.cpp | 16 +- src/mumble/BanEditor.cpp | 7 +- src/mumble/CMakeLists.txt | 8 +- src/mumble/ClientUser.cpp | 2 +- src/mumble/ConnectDialog.cpp | 14 +- src/mumble/CoreAudio.mm | 14 +- src/mumble/CustomElements.cpp | 11 +- src/mumble/Database.cpp | 4 +- src/mumble/Database.h | 5 +- src/mumble/DeveloperConsole.h | 2 +- src/mumble/EnumStringConversions.cpp | 2 +- src/mumble/EnumStringConversions.h | 2 +- src/mumble/Global.cpp | 5 - src/mumble/Global.h | 4 +- src/mumble/GlobalShortcut.cpp | 14 +- src/mumble/GlobalShortcut.h | 2 +- src/mumble/GlobalShortcutButtons.cpp | 10 +- src/mumble/GlobalShortcut_macx.mm | 15 +- src/mumble/GlobalShortcut_unix.cpp | 4 +- src/mumble/GlobalShortcut_win.cpp | 18 +- src/mumble/JSONSerialization.h | 2 +- src/mumble/JackAudio.cpp | 52 ++--- src/mumble/LCD.cpp | 4 +- src/mumble/ListenerVolumeSlider.cpp | 2 +- src/mumble/ListenerVolumeSlider.h | 2 +- src/mumble/Log.cpp | 4 +- src/mumble/Log.h | 2 +- src/mumble/MainWindow.cpp | 24 +-- src/mumble/MainWindow.h | 2 +- src/mumble/ManualPlugin.cpp | 2 +- src/mumble/ManualPlugin.h | 2 +- src/mumble/Markdown.cpp | 2 +- src/mumble/Markdown.h | 2 +- src/mumble/Messages.cpp | 32 +-- src/mumble/OSS.cpp | 41 ++-- src/mumble/Overlay.h | 2 +- src/mumble/OverlayClient.cpp | 77 ++++---- src/mumble/OverlayClient.h | 2 +- src/mumble/OverlayEditor.cpp | 11 +- src/mumble/OverlayEditorScene.cpp | 40 ++-- src/mumble/OverlayPositionableItem.cpp | 6 +- src/mumble/OverlayPositionableItem.h | 2 +- src/mumble/OverlayText.cpp | 20 +- src/mumble/OverlayUser.cpp | 43 ++-- src/mumble/OverlayUserGroup.cpp | 26 +-- src/mumble/OverlayUserGroup.h | 2 +- src/mumble/Overlay_macx.mm | 2 +- src/mumble/Overlay_win.cpp | 5 +- src/mumble/PAAudio.cpp | 20 +- src/mumble/PipeWire.cpp | 16 +- src/mumble/Plugin.cpp | 4 +- src/mumble/PluginInstaller.h | 4 +- src/mumble/PluginManager.cpp | 23 ++- src/mumble/PluginManifest.cpp | 5 +- src/mumble/PluginManifest.h | 6 +- src/mumble/PluginUpdater.h | 4 +- src/mumble/PositionalAudioViewer.cpp | 26 +-- src/mumble/PositionalAudioViewer.h | 4 +- src/mumble/PulseAudio.cpp | 68 ++++--- src/mumble/QtWidgetUtils.cpp | 8 +- src/mumble/QtWidgetUtils.h | 4 +- src/mumble/RichTextEditor.cpp | 19 +- src/mumble/Screen.cpp | 4 +- src/mumble/Screen.h | 4 +- src/mumble/SearchDialog.cpp | 20 +- src/mumble/SearchDialog.h | 12 +- src/mumble/ServerHandler.cpp | 30 +-- src/mumble/ServerHandler.h | 8 +- src/mumble/ServerInformation.cpp | 13 +- src/mumble/ServerInformation.h | 4 +- src/mumble/Settings.cpp | 21 +- src/mumble/Settings.h | 4 +- src/mumble/SettingsKeys.h | 2 +- src/mumble/TalkingUI.cpp | 64 +++--- src/mumble/TalkingUI.h | 12 +- src/mumble/TalkingUIContainer.cpp | 4 +- src/mumble/TalkingUIEntry.cpp | 10 +- src/mumble/TalkingUIEntry.h | 2 +- src/mumble/TalkingUISelection.cpp | 4 +- src/mumble/TalkingUISelection.h | 8 +- src/mumble/TextToSpeech_macx.mm | 4 +- src/mumble/ThemeInfo.h | 4 +- src/mumble/Translations.cpp | 4 +- src/mumble/Translations.h | 4 +- src/mumble/UserInformation.cpp | 16 +- src/mumble/UserListModel.cpp | 4 +- src/mumble/UserListModel.h | 4 +- src/mumble/UserLocalNicknameDialog.h | 2 +- src/mumble/UserModel.cpp | 28 +-- src/mumble/UserModel.h | 14 +- src/mumble/UserView.cpp | 3 +- src/mumble/VoiceRecorder.cpp | 11 +- src/mumble/VoiceRecorderDialog.cpp | 2 +- src/mumble/WASAPI.cpp | 12 +- src/mumble/Zeroconf.cpp | 2 +- src/mumble/main.cpp | 7 +- src/mumble/os_macx.mm | 4 +- src/mumble/os_win.cpp | 41 ++-- src/mumble/widgets/RichTextItemDelegate.cpp | 7 +- src/mumble/widgets/RichTextItemDelegate.h | 4 +- .../widgets/SearchDialogItemDelegate.cpp | 16 +- src/mumble/widgets/SearchDialogItemDelegate.h | 4 +- src/murmur/DBus.cpp | 35 ++-- src/murmur/DBus.h | 32 +-- src/murmur/Messages.cpp | 133 ++++++------- src/murmur/Meta.cpp | 36 ++-- src/murmur/Meta.h | 14 +- src/murmur/MumbleServerIce.cpp | 129 ++++++------ src/murmur/MumbleServerIce.h | 2 +- src/murmur/RPC.cpp | 8 +- src/murmur/Register.cpp | 8 +- src/murmur/Server.cpp | 184 +++++++++++------- src/murmur/Server.h | 18 +- src/murmur/ServerDB.cpp | 30 +-- src/murmur/ServerDB.h | 2 +- src/murmur/ServerUser.cpp | 4 +- src/murmur/TracyConstants.h | 2 +- src/murmur/Tray.h | 2 +- src/tests/Emit.cpp | 4 +- .../TestAudioReceiverBuffer.cpp | 8 +- src/tests/TestCrypt/TestCrypt.cpp | 69 ++++--- .../TestCryptographicRandom.cpp | 16 +- .../TestMumbleProtocol/TestMumbleProtocol.cpp | 30 ++- .../TestPacketDataStream.cpp | 2 +- src/tests/TestVersion/TestVersion.cpp | 2 +- 167 files changed, 1522 insertions(+), 1406 deletions(-) diff --git a/src/Channel.cpp b/src/Channel.cpp index e6ea22d5e1c..a14c62f492b 100644 --- a/src/Channel.cpp +++ b/src/Channel.cpp @@ -17,11 +17,11 @@ # include "Database.h" # include "ServerHandler.h" -QHash< int, Channel * > Channel::c_qhChannels; +QHash< unsigned int, Channel * > Channel::c_qhChannels; QReadWriteLock Channel::c_qrwlChannels; #endif -Channel::Channel(int id, const QString &name, QObject *p) : QObject(p) { +Channel::Channel(unsigned int id, const QString &name, QObject *p) : QObject(p) { iId = id; iPosition = 0; qsName = name; @@ -59,12 +59,12 @@ Channel::~Channel() { } #ifdef MUMBLE -Channel *Channel::get(int id) { +Channel *Channel::get(unsigned int id) { QReadLocker lock(&c_qrwlChannels); return c_qhChannels.value(id); } -Channel *Channel::add(int id, const QString &name) { +Channel *Channel::add(unsigned int id, const QString &name) { QWriteLocker lock(&c_qrwlChannels); if (c_qhChannels.contains(id)) @@ -272,7 +272,7 @@ void Channel::removeUser(User *p) { Channel::operator QString() const { return QString::fromLatin1("%1[%2:%3%4]") - .arg(qsName, QString::number(iId), QString::number(cParent ? cParent->iId : -1), + .arg(qsName, QString::number(iId), QString::number(cParent ? static_cast< int >(cParent->iId) : -1), bTemporary ? QLatin1String("*") : QLatin1String("")); } diff --git a/src/Channel.h b/src/Channel.h index b599eb4cdcb..04549d37879 100644 --- a/src/Channel.h +++ b/src/Channel.h @@ -34,7 +34,7 @@ class Channel : public QObject { public: static constexpr int ROOT_ID = 0; - int iId; + unsigned int iId; int iPosition; bool bTemporary; Channel *cParent; @@ -67,7 +67,7 @@ class Channel : public QObject { /// setting. unsigned int uiMaxUsers; - Channel(int id, const QString &name, QObject *p = nullptr); + Channel(unsigned int id, const QString &name, QObject *p = nullptr); ~Channel(); #ifdef MUMBLE @@ -79,11 +79,11 @@ class Channel : public QObject { void clearFilterMode(); bool isFiltered() const; - static QHash< int, Channel * > c_qhChannels; + static QHash< unsigned int, Channel * > c_qhChannels; static QReadWriteLock c_qrwlChannels; - static Channel *get(int); - static Channel *add(int, const QString &); + static Channel *get(unsigned int); + static Channel *add(unsigned int, const QString &); static void remove(Channel *); void addClientUser(ClientUser *p); diff --git a/src/ChannelListenerManager.cpp b/src/ChannelListenerManager.cpp index cf562da2457..b922924ec2f 100644 --- a/src/ChannelListenerManager.cpp +++ b/src/ChannelListenerManager.cpp @@ -12,7 +12,7 @@ std::size_t qHash(const ChannelListener &listener) { return std::hash< ChannelListener >()(listener); -}; +} bool operator==(const ChannelListener &lhs, const ChannelListener &rhs) { return lhs.channelID == rhs.channelID && lhs.userSession == rhs.userSession; @@ -23,21 +23,21 @@ ChannelListenerManager::ChannelListenerManager() m_listenerVolumeAdjustments() { } -void ChannelListenerManager::addListener(unsigned int userSession, int channelID) { +void ChannelListenerManager::addListener(unsigned int userSession, unsigned int channelID) { QWriteLocker lock(&m_listenerLock); m_listeningUsers[userSession] << channelID; m_listenedChannels[channelID] << userSession; } -void ChannelListenerManager::removeListener(unsigned int userSession, int channelID) { +void ChannelListenerManager::removeListener(unsigned int userSession, unsigned int channelID) { QWriteLocker lock(&m_listenerLock); m_listeningUsers[userSession].remove(channelID); m_listenedChannels[channelID].remove(userSession); } -bool ChannelListenerManager::isListening(unsigned int userSession, int channelID) const { +bool ChannelListenerManager::isListening(unsigned int userSession, unsigned int channelID) const { QReadLocker lock(&m_listenerLock); return m_listenedChannels[channelID].contains(userSession); @@ -49,25 +49,25 @@ bool ChannelListenerManager::isListeningToAny(unsigned int userSession) const { return !m_listeningUsers[userSession].isEmpty(); } -bool ChannelListenerManager::isListenedByAny(int channelID) const { +bool ChannelListenerManager::isListenedByAny(unsigned int channelID) const { QReadLocker lock(&m_listenerLock); return !m_listenedChannels[channelID].isEmpty(); } -const QSet< unsigned int > ChannelListenerManager::getListenersForChannel(int channelID) const { +const QSet< unsigned int > ChannelListenerManager::getListenersForChannel(unsigned int channelID) const { QReadLocker lock(&m_listenerLock); return m_listenedChannels[channelID]; } -const QSet< int > ChannelListenerManager::getListenedChannelsForUser(unsigned int userSession) const { +const QSet< unsigned int > ChannelListenerManager::getListenedChannelsForUser(unsigned int userSession) const { QReadLocker lock(&m_listenerLock); return m_listeningUsers[userSession]; } -int ChannelListenerManager::getListenerCountForChannel(int channelID) const { +int ChannelListenerManager::getListenerCountForChannel(unsigned int channelID) const { QReadLocker lock(&m_listenerLock); return m_listenedChannels[channelID].size(); @@ -79,7 +79,7 @@ int ChannelListenerManager::getListenedChannelCountForUser(unsigned int userSess return m_listeningUsers[userSession].size(); } -void ChannelListenerManager::setListenerVolumeAdjustment(unsigned int userSession, int channelID, +void ChannelListenerManager::setListenerVolumeAdjustment(unsigned int userSession, unsigned int channelID, const VolumeAdjustment &volumeAdjustment) { float oldValue = 1.0f; { @@ -103,7 +103,7 @@ void ChannelListenerManager::setListenerVolumeAdjustment(unsigned int userSessio } const VolumeAdjustment &ChannelListenerManager::getListenerVolumeAdjustment(unsigned int userSession, - int channelID) const { + unsigned int channelID) const { static VolumeAdjustment fallbackObj = VolumeAdjustment::fromFactor(1.0f); QReadLocker lock(&m_volumeLock); @@ -121,14 +121,14 @@ const VolumeAdjustment &ChannelListenerManager::getListenerVolumeAdjustment(unsi } } -std::unordered_map< int, VolumeAdjustment > +std::unordered_map< unsigned int, VolumeAdjustment > ChannelListenerManager::getAllListenerVolumeAdjustments(unsigned int userSession) const { QReadLocker lock1(&m_volumeLock); QReadLocker lock2(&m_listenerLock); - std::unordered_map< int, VolumeAdjustment > adjustments; + std::unordered_map< unsigned int, VolumeAdjustment > adjustments; - for (int channelID : m_listeningUsers.value(userSession)) { + for (unsigned int channelID : m_listeningUsers.value(userSession)) { ChannelListener listener = {}; listener.channelID = channelID; listener.userSession = userSession; diff --git a/src/ChannelListenerManager.h b/src/ChannelListenerManager.h index b7072708d55..5e65be7e626 100644 --- a/src/ChannelListenerManager.h +++ b/src/ChannelListenerManager.h @@ -22,13 +22,13 @@ struct ChannelListener { /// The session ID of the owning user unsigned int userSession; /// The ID of the channel this listener is placed in - int channelID; + unsigned int channelID; }; // Make ChannelListener hashable and comparable template<> struct std::hash< ChannelListener > { std::size_t operator()(const ChannelListener &val) const { - return std::hash< unsigned int >()(val.userSession) ^ (std::hash< int >()(val.channelID) << 2); + return std::hash< unsigned int >()(val.userSession) ^ (std::hash< unsigned int >()(val.channelID) << 2); } }; std::size_t qHash(const ChannelListener &listener); @@ -47,9 +47,9 @@ class ChannelListenerManager : public QObject { /// A lock for guarding m_listeningUsers as well as m_listenedChannels mutable QReadWriteLock m_listenerLock; /// A map between a user's session and a list of IDs of all channels the user is listening to - QHash< unsigned int, QSet< int > > m_listeningUsers; + QHash< unsigned int, QSet< unsigned int > > m_listeningUsers; /// A map between a channel's ID and a list of all user-sessions of users listening to that channel - QHash< int, QSet< unsigned int > > m_listenedChannels; + QHash< unsigned int, QSet< unsigned int > > m_listenedChannels; /// A lock for guarding m_listenerVolumeAdjustments mutable QReadWriteLock m_volumeLock; /// A map between channel IDs and local volume adjustments to be made for ChannelListeners @@ -64,18 +64,18 @@ class ChannelListenerManager : public QObject { /// /// @param userSession The session ID of the user /// @param channelID The ID of the channel - void addListener(unsigned int userSession, int channelID); + void addListener(unsigned int userSession, unsigned int channelID); /// Removes a listener from the channel. /// /// @param userSession The session ID of the user /// @param channelID The ID of the channel - void removeListener(unsigned int userSession, int channelID); + void removeListener(unsigned int userSession, unsigned int channelID); /// @param userSession The session ID of the user /// @param channelID The ID of the channel /// @returns Whether the given user is listening to the given channel - bool isListening(unsigned int userSession, int channelID) const; + bool isListening(unsigned int userSession, unsigned int channelID) const; /// @param userSession The session ID of the user /// @returns Whether this user is listening to any channel via the ChannelListener feature @@ -83,19 +83,19 @@ class ChannelListenerManager : public QObject { /// @param channelID The ID of the channel /// @returns Whether any user listens to this channel via the ChannelListener feature - bool isListenedByAny(int channelID) const; + bool isListenedByAny(unsigned int channelID) const; /// @param channelID The ID of the channel /// @returns A set of user sessions of users listening to the given channel - const QSet< unsigned int > getListenersForChannel(int channelID) const; + const QSet< unsigned int > getListenersForChannel(unsigned int channelID) const; /// @param userSession The session ID of the user /// @returns A set of channel IDs of channels the given user is listening to - const QSet< int > getListenedChannelsForUser(unsigned int userSession) const; + const QSet< unsigned int > getListenedChannelsForUser(unsigned int userSession) const; /// @param channelID The ID of the channel /// @returns The amount of users that are listening to the given channel - int getListenerCountForChannel(int channelID) const; + int getListenerCountForChannel(unsigned int channelID) const; /// @param userSession The session ID of the user /// @returns The amount of channels the given user is listening to @@ -106,21 +106,23 @@ class ChannelListenerManager : public QObject { /// @param userSession The session ID of the user /// @param channelID The ID of the channel /// @param volumeAdjustment The volume adjustment to apply - void setListenerVolumeAdjustment(unsigned int userSession, int channelID, const VolumeAdjustment &volumeAdjustment); + void setListenerVolumeAdjustment(unsigned int userSession, unsigned int channelID, + const VolumeAdjustment &volumeAdjustment); /// @param userSession The session ID of the user /// @param channelID The ID of the channel /// @returns The volume adjustment for the listener of the given user in the given channel. - const VolumeAdjustment &getListenerVolumeAdjustment(unsigned int userSession, int channelID) const; + const VolumeAdjustment &getListenerVolumeAdjustment(unsigned int userSession, unsigned int channelID) const; /// @param userSession The session ID of the user whose listener's volume adjustments to obtain /// @returns A map between channel IDs and the currently set volume adjustment - std::unordered_map< int, VolumeAdjustment > getAllListenerVolumeAdjustments(unsigned int userSession) const; + std::unordered_map< unsigned int, VolumeAdjustment > + getAllListenerVolumeAdjustments(unsigned int userSession) const; /// Clears all ChannelListeners and volume adjustments void clear(); signals: - void localVolumeAdjustmentsChanged(int channelID, float newAdjustment, float oldAdjustment); + void localVolumeAdjustmentsChanged(unsigned int channelID, float newAdjustment, float oldAdjustment); }; #endif // MUMBLE_CHANNELLISTENERMANAGER_H_ diff --git a/src/Connection.cpp b/src/Connection.cpp index d80fe5c727e..5e0811bb58f 100644 --- a/src/Connection.cpp +++ b/src/Connection.cpp @@ -121,7 +121,7 @@ void Connection::socketRead() { qtsSocket->read(reinterpret_cast< char * >(a_ucBuffer), 6); m_type = static_cast< Mumble::Protocol::TCPMessageType >(qFromBigEndian< quint16 >(&a_ucBuffer[0])); - iPacketLength = qFromBigEndian< quint32 >(&a_ucBuffer[2]); + iPacketLength = qFromBigEndian< int >(&a_ucBuffer[2]); iAvailable -= 6; } @@ -161,19 +161,19 @@ void Connection::socketDisconnected() { void Connection::messageToNetwork(const ::google::protobuf::Message &msg, Mumble::Protocol::TCPMessageType msgType, QByteArray &cache) { #if GOOGLE_PROTOBUF_VERSION >= 3004000 - int len = msg.ByteSizeLong(); + std::size_t len = msg.ByteSizeLong(); #else // ByteSize() has been deprecated as of protobuf v3.4 - int len = msg.ByteSize(); + std::size_t len = msg.ByteSize(); #endif if (len > 0x7fffff) return; - cache.resize(len + 6); + cache.resize(static_cast< int >(len + 6)); unsigned char *uc = reinterpret_cast< unsigned char * >(cache.data()); qToBigEndian< quint16 >(static_cast< quint16 >(msgType), &uc[0]); - qToBigEndian< quint32 >(len, &uc[2]); + qToBigEndian< quint32 >(static_cast< unsigned int >(len), &uc[2]); - msg.SerializeToArray(uc + 6, len); + msg.SerializeToArray(uc + 6, static_cast< int >(len)); } void Connection::sendMessage(const ::google::protobuf::Message &msg, Mumble::Protocol::TCPMessageType msgType, diff --git a/src/EnvUtils.cpp b/src/EnvUtils.cpp index cf2f7857afe..e49ddc00052 100644 --- a/src/EnvUtils.cpp +++ b/src/EnvUtils.cpp @@ -61,4 +61,4 @@ bool waylandIsUsed() { return getenv(QStringLiteral("WAYLAND_DISPLAY")) != ""; } -}; // namespace EnvUtils +} // namespace EnvUtils diff --git a/src/EnvUtils.h b/src/EnvUtils.h index 7389eccedc7..ba322e8dbda 100644 --- a/src/EnvUtils.h +++ b/src/EnvUtils.h @@ -24,6 +24,6 @@ bool setenv(QString name, QString value); bool waylandIsUsed(); -}; // namespace EnvUtils +} // namespace EnvUtils #endif diff --git a/src/LogEmitter.cpp b/src/LogEmitter.cpp index 55f0a7d7882..522e7800bc1 100644 --- a/src/LogEmitter.cpp +++ b/src/LogEmitter.cpp @@ -5,8 +5,9 @@ #include "LogEmitter.h" -LogEmitter::LogEmitter(QObject *p) : QObject(p){}; +LogEmitter::LogEmitter(QObject *p) : QObject(p) { +} void LogEmitter::addLogEntry(const QString &msg) { emit newLogEntry(msg); -}; +} diff --git a/src/MumbleConstants.h b/src/MumbleConstants.h index 619545684da..d42421a750a 100644 --- a/src/MumbleConstants.h +++ b/src/MumbleConstants.h @@ -13,8 +13,8 @@ namespace Plugins { constexpr int MAX_DATA_LENGTH = 1000; constexpr int MAX_DATA_ID_LENGTH = 100; - }; // namespace PluginMessage -}; // namespace Plugins -}; // namespace Mumble + } // namespace PluginMessage +} // namespace Plugins +} // namespace Mumble #endif // MUMBLE_MUMBLECONSTANTS_H_ diff --git a/src/MumbleProtocol.cpp b/src/MumbleProtocol.cpp index fedeaa9d837..32194f2250b 100644 --- a/src/MumbleProtocol.cpp +++ b/src/MumbleProtocol.cpp @@ -39,7 +39,7 @@ namespace Protocol { if (!useCachedSize) { serializedSize = getProtobufSize(message); } else { - serializedSize = message.GetCachedSize(); + serializedSize = static_cast< std::size_t >(message.GetCachedSize()); } assert(serializedSize + offset <= maxAllowedSize); @@ -54,7 +54,7 @@ namespace Protocol { buffer.resize(serializedSize + offset); - message.SerializePartialToArray(buffer.data() + offset, serializedSize); + message.SerializePartialToArray(buffer.data() + offset, static_cast< int >(serializedSize)); return serializedSize; } @@ -135,11 +135,11 @@ namespace Protocol { } // The audio format (aka: package type) has to be written to the 3 most significant bits of the header byte assert(type < (1 << 3)); - type = type << 5; + type = static_cast< decltype(type) >(type << 5); m_byteBuffer[0] = type; - PacketDataStream stream(m_byteBuffer.data() + 1, m_byteBuffer.size() - 1); + PacketDataStream stream(m_byteBuffer.data() + 1, static_cast< unsigned int >(m_byteBuffer.size() - 1)); if (this->getRole() == Role::Server) { stream << data.senderSession; @@ -155,14 +155,16 @@ namespace Protocol { stream << static_cast< int >(data.isLastFrame ? data.payload.size() | (1 << 13) : data.payload.size()); // After the size has been encoded, we write the actual Opus frame to the message - stream.append(reinterpret_cast< const char * >(data.payload.data()), data.payload.size()); + stream.append(reinterpret_cast< const char * >(data.payload.data()), + static_cast< unsigned int >(data.payload.size())); break; } case AudioCodec::CELT_Alpha: case AudioCodec::CELT_Beta: case AudioCodec::Speex: { // Simply append the provided payload - stream.append(reinterpret_cast< const char * >(data.payload.data()), data.payload.size()); + stream.append(reinterpret_cast< const char * >(data.payload.data()), + static_cast< unsigned int >(data.payload.size())); break; } } @@ -199,7 +201,9 @@ namespace Protocol { template< Role role > void UDPAudioEncoder< role >::addPositionalData_legacy(const AudioData &data) { if (data.containsPositionalData) { - PacketDataStream stream(m_byteBuffer.data() + m_staticPartSize, m_byteBuffer.size() - m_staticPartSize); + assert(m_byteBuffer.size() >= m_staticPartSize); + PacketDataStream stream(m_byteBuffer.data() + m_staticPartSize, + static_cast< unsigned int >(m_byteBuffer.size() - m_staticPartSize)); // Positional data simply gets attached to the stream after the audio payload assert(data.position.size() == 3); @@ -295,7 +299,7 @@ namespace Protocol { } } - gsl::span< const byte > buffer = getPreEncodedContext(data.targetOrContext); + gsl::span< const byte > buffer = getPreEncodedContext(static_cast< byte >(data.targetOrContext)); if (!buffer.empty()) { // Use pre-encoded snippet offset += writeSnippet(buffer, m_byteBuffer, offset, MAX_UDP_PACKET_SIZE); @@ -320,7 +324,7 @@ namespace Protocol { if (data.containsPositionalData) { m_audioMessage.Clear(); - for (int i = 0; i < 3; ++i) { + for (unsigned int i = 0; i < 3; ++i) { m_audioMessage.add_positional_data(data.position[i]); } @@ -363,9 +367,10 @@ namespace Protocol { // Store the pre-encoded packet // The max-size is the size of the used field (float) plus 1 byte overhead for encoding the field type and // number - bool successful = - encodeProtobuf(m_audioMessage, m_preEncodedVolumeAdjustment[dbAdjustment - preEncodedDBAdjustmentBegin], - 0, sizeof(float) + 1, false); + bool successful = encodeProtobuf( + m_audioMessage, + m_preEncodedVolumeAdjustment[static_cast< std::size_t >(dbAdjustment - preEncodedDBAdjustmentBegin)], 0, + sizeof(float) + 1, false); (void) successful; assert(successful); } @@ -385,7 +390,7 @@ namespace Protocol { template< Role role > gsl::span< const byte > UDPAudioEncoder< role >::getPreEncodedVolumeAdjustment(const VolumeAdjustment &adjustment) const { - int index = (adjustment.dbAdjustment - preEncodedDBAdjustmentBegin); + int index = static_cast< int >(adjustment.dbAdjustment - preEncodedDBAdjustmentBegin); if (adjustment.dbAdjustment == VolumeAdjustment::INVALID_DB_ADJUSTMENT || index < 0 || static_cast< std::size_t >(index) >= m_preEncodedVolumeAdjustment.size()) { @@ -393,7 +398,7 @@ namespace Protocol { return {}; } - const std::vector< byte > &data = m_preEncodedVolumeAdjustment[index]; + const std::vector< byte > &data = m_preEncodedVolumeAdjustment[static_cast< std::size_t >(index)]; return gsl::span< const byte >(data.data(), data.size()); } @@ -605,7 +610,7 @@ namespace Protocol { return false; } - PacketDataStream stream(data.data(), data.size()); + PacketDataStream stream(data.data(), static_cast< unsigned int >(data.size())); if (data.size() <= sizeof(std::uint64_t) + 1) { // Regular connectivity ping (contains a single varint which may be up to a full 64bit number plus @@ -677,7 +682,7 @@ namespace Protocol { return false; } - if (!m_pingMessage.ParseFromArray(data.data(), data.size())) { + if (!m_pingMessage.ParseFromArray(data.data(), static_cast< int >(data.size()))) { // Invalid format return false; } @@ -715,7 +720,7 @@ namespace Protocol { m_audioData.targetOrContext = data[0] & 0x1f; m_audioData.usedCodec = codec; - PacketDataStream stream(data.data() + 1, data.size() - 1); + PacketDataStream stream(data.data() + 1, static_cast< unsigned int >(data.size() - 1)); if (this->getRole() == Role::Client) { // When the client receives audio packets from the server, there will be an extra field containing the @@ -767,7 +772,7 @@ namespace Protocol { // We don't include the size/header-field in the actual payload payloadBegin = stream.dataPtr(); - stream.skip(payloadSize); + stream.skip(static_cast< unsigned int >(payloadSize)); break; } @@ -782,7 +787,7 @@ namespace Protocol { // If there are further bytes after the audio payload, this means that there is positional data attached to // the packet. m_audioData.containsPositionalData = true; - for (int i = 0; i < 3; ++i) { + for (unsigned int i = 0; i < 3; ++i) { stream >> m_audioData.position[i]; } } else if (stream.left() > 0) { @@ -799,7 +804,7 @@ namespace Protocol { m_messageType = UDPMessageType::Audio; m_audioData = {}; - if (!m_audioMessage.ParseFromArray(data.data(), data.size())) { + if (!m_audioMessage.ParseFromArray(data.data(), static_cast< int >(data.size()))) { // Invalid format return false; } @@ -825,8 +830,8 @@ namespace Protocol { // We always expect a 3D position, if positional data is present return false; } - for (int i = 0; i < 3; ++i) { - m_audioData.position[i] = m_audioMessage.positional_data(i); + for (unsigned int i = 0; i < 3; ++i) { + m_audioData.position[i] = m_audioMessage.positional_data(static_cast< int >(i)); } m_audioData.containsPositionalData = true; @@ -883,4 +888,4 @@ namespace Protocol { #undef PROCESS_CLASS } // namespace Protocol -}; // namespace Mumble +} // namespace Mumble diff --git a/src/MumbleProtocol.h b/src/MumbleProtocol.h index 267148195bb..5732d6a5c3b 100644 --- a/src/MumbleProtocol.h +++ b/src/MumbleProtocol.h @@ -91,7 +91,7 @@ namespace Protocol { namespace ReservedTargetIDs { constexpr unsigned int REGULAR_SPEECH = 0; constexpr unsigned int SERVER_LOOPBACK = 31; - }; // namespace ReservedTargetIDs + } // namespace ReservedTargetIDs using audio_context_t = byte; namespace AudioContext { @@ -103,7 +103,7 @@ namespace Protocol { constexpr audio_context_t BEGIN = NORMAL; constexpr audio_context_t END = LISTEN + 1; - }; // namespace AudioContext + } // namespace AudioContext enum class Role { Server, Client }; @@ -273,8 +273,8 @@ namespace Protocol { bool decodeAudio_protobuf(const gsl::span< const byte > data); }; -}; // namespace Protocol -}; // namespace Mumble +} // namespace Protocol +} // namespace Mumble /** * This is merely a dummy-function (never used) that is required as a scope for dummy-switch statements on our message diff --git a/src/OSInfo.cpp b/src/OSInfo.cpp index a5efedf44df..037fa6ae666 100644 --- a/src/OSInfo.cpp +++ b/src/OSInfo.cpp @@ -7,6 +7,7 @@ #if defined(Q_OS_WIN) # include "win.h" +# include "versionhelpers.h" #endif #include "OSInfo.h" @@ -130,7 +131,7 @@ QString OSInfo::getArchitecture(const bool build) { QString OSInfo::getMacHash(const QList< QHostAddress > &qlBind) { QString first, second, third; - foreach (const QNetworkInterface &qni, QNetworkInterface::allInterfaces()) { + for (const QNetworkInterface &qni : QNetworkInterface::allInterfaces()) { if (!qni.isValid()) continue; if (qni.flags() & QNetworkInterface::IsLoopBack) @@ -150,7 +151,7 @@ QString OSInfo::getMacHash(const QList< QHostAddress > &qlBind) { if (second.isEmpty() || second > hash) second = hash; - foreach (const QNetworkAddressEntry &qnae, qni.addressEntries()) { + for (const QNetworkAddressEntry &qnae : qni.addressEntries()) { const QHostAddress &qha = qnae.ip(); if (qlBind.isEmpty() || qlBind.contains(qha)) { if (first.isEmpty() || first > hash) @@ -193,135 +194,46 @@ QString OSInfo::getOSDisplayableVersion(const bool appendArch) { #if defined(Q_OS_WIN) QString os = win10DisplayableVersion(); if (os.isEmpty()) { - OSVERSIONINFOEXW ovi; - memset(&ovi, 0, sizeof(ovi)); - ovi.dwOSVersionInfoSize = sizeof(ovi); - if (!GetVersionEx(reinterpret_cast< OSVERSIONINFOW * >(&ovi))) { - return QString(); - } - - if (ovi.dwMajorVersion == 10) { - if (ovi.wProductType == VER_NT_WORKSTATION) { + if (IsWindows10OrGreater()) { + if (!IsWindowsServer()) { os = QLatin1String("Windows 10"); } else { os = QLatin1String("Windows 10 Server"); } - } else if (ovi.dwMajorVersion == 6) { - if (ovi.dwMinorVersion == 0) { - if (ovi.wProductType == VER_NT_WORKSTATION) { - os = QLatin1String("Windows Vista"); - } else { - os = QLatin1String("Windows Server 2008"); - } - } else if (ovi.dwMinorVersion == 1) { - if (ovi.wProductType == VER_NT_WORKSTATION) { - os = QLatin1String("Windows 7"); - } else { - os = QLatin1String("Windows Server 2008 R2"); - } - } else if (ovi.dwMinorVersion == 2) { - if (ovi.wProductType == VER_NT_WORKSTATION) { - os = QLatin1String("Windows 8"); - } else { - os = QLatin1String("Windows Server 2012"); - } - } else if (ovi.dwMinorVersion == 3) { - if (ovi.wProductType == VER_NT_WORKSTATION) { - os = QLatin1String("Windows 8.1"); - } else { - os = QLatin1String("Windows Server 2012 R2"); - } - } else if (ovi.dwMinorVersion == 4) { - if (ovi.wProductType == VER_NT_WORKSTATION) { - os = QLatin1String("Windows 10"); - } else { - os = QLatin1String("Windows 10 Server"); - } + } else if (IsWindows8Point1OrGreater()) { + if (!IsWindowsServer()) { + os = QLatin1String("Windows 8.1"); + } else { + os = QLatin1String("Windows 8.1 Server"); } + } else if (IsWindows8OrGreater()) { + if (!IsWindowsServer()) { + os = QLatin1String("Windows 8"); + } else { + os = QLatin1String("Windows 8 Server"); + } + } else if (IsWindows7OrGreater()) { + if (!IsWindowsServer()) { + os = QLatin1String("Windows 7"); + } else { + os = QLatin1String("Windows 7 Server"); + } + } else if (IsWindowsVistaOrGreater()) { + if (!IsWindowsServer()) { + os = QLatin1String("Windows Vista"); + } else { + os = QLatin1String("Windows Vista Server"); + } + } else if (IsWindowsXPOrGreater()) { + if (!IsWindowsServer()) { + os = QLatin1String("Windows XP"); + } else { + os = QLatin1String("Windows XP Server"); + } + } else { + os = QLatin1String("Ancient Windows version"); } - typedef BOOL(WINAPI * PGPI)(DWORD, DWORD, DWORD, DWORD, PDWORD); - PGPI pGetProductInfo = (PGPI) GetProcAddress(GetModuleHandle(TEXT("kernel32.dll")), "GetProductInfo"); - if (!pGetProductInfo) { - return QString(); - } - - DWORD dwType = 0; - if (!pGetProductInfo(ovi.dwMajorVersion, ovi.dwMinorVersion, 0, 0, &dwType)) { - return QString(); - } - - switch (dwType) { - case PRODUCT_ULTIMATE: - os.append(QLatin1String(" Ultimate Edition")); - break; - case PRODUCT_PROFESSIONAL: - os.append(QLatin1String(" Professional")); - break; - case PRODUCT_HOME_PREMIUM: - os.append(QLatin1String(" Home Premium Edition")); - break; - case PRODUCT_HOME_BASIC: - os.append(QLatin1String(" Home Basic Edition")); - break; - case PRODUCT_ENTERPRISE: - os.append(QLatin1String(" Enterprise Edition")); - break; - case PRODUCT_BUSINESS: - os.append(QLatin1String(" Business Edition")); - break; - case PRODUCT_STARTER: - os.append(QLatin1String(" Starter Edition")); - break; - case PRODUCT_CLUSTER_SERVER: - os.append(QLatin1String(" Cluster Server Edition")); - break; - case PRODUCT_DATACENTER_SERVER: - os.append(QLatin1String(" Datacenter Edition")); - break; - case PRODUCT_DATACENTER_SERVER_CORE: - os.append(QLatin1String(" Datacenter Edition (core installation)")); - break; - case PRODUCT_ENTERPRISE_SERVER: - os.append(QLatin1String(" Enterprise Edition")); - break; - case PRODUCT_ENTERPRISE_SERVER_CORE: - os.append(QLatin1String(" Enterprise Edition (core installation)")); - break; - case PRODUCT_ENTERPRISE_SERVER_IA64: - os.append(QLatin1String(" Enterprise Edition for Itanium-based Systems")); - break; - case PRODUCT_SMALLBUSINESS_SERVER: - os.append(QLatin1String(" Small Business Server")); - break; - case PRODUCT_SMALLBUSINESS_SERVER_PREMIUM: - os.append(QLatin1String(" Small Business Server Premium Edition")); - break; - case PRODUCT_STANDARD_SERVER: - os.append(QLatin1String(" Standard Edition")); - break; - case PRODUCT_STANDARD_SERVER_CORE: - os.append(QLatin1String(" Standard Edition (core installation)")); - break; - case PRODUCT_WEB_SERVER: - os.append(QLatin1String(" Web Server Edition")); - break; - } - - // Service Packs (may be empty) - static_assert(sizeof(TCHAR) == sizeof(wchar_t), "Expected Unicode TCHAR."); - auto tmp = QString::fromWCharArray(ovi.szCSDVersion); - if (!tmp.isEmpty()) { - os.append(QLatin1String(" ")); - os.append(tmp); - } - - tmp = QString::asprintf(" - %lu.%lu.%lu", static_cast< unsigned long >(ovi.dwMajorVersion), - static_cast< unsigned long >(ovi.dwMinorVersion), - static_cast< unsigned long >(ovi.dwBuildNumber)); - - os.append(tmp); - return os; } #elif defined(Q_OS_MACOS) @@ -337,20 +249,7 @@ QString OSInfo::getOSDisplayableVersion(const bool appendArch) { } QString OSInfo::getOSVersion() { -#if defined(Q_OS_WIN) - OSVERSIONINFOEXW ovi; - memset(&ovi, 0, sizeof(ovi)); - - ovi.dwOSVersionInfoSize = sizeof(ovi); - if (!GetVersionEx(reinterpret_cast< OSVERSIONINFOW * >(&ovi))) { - return QString(); - } - - return QString::asprintf("%lu.%lu.%lu.%lu", static_cast< unsigned long >(ovi.dwMajorVersion), - static_cast< unsigned long >(ovi.dwMinorVersion), - static_cast< unsigned long >(ovi.dwBuildNumber), - (ovi.wProductType == VER_NT_WORKSTATION) ? 1UL : 0UL); -#elif defined(Q_OS_MACOS) +#if defined(Q_OS_MACOS) SInt32 major, minor, bugfix; OSErr err = Gestalt(gestaltSystemVersionMajor, &major); if (err == noErr) diff --git a/src/PacketDataStream.h b/src/PacketDataStream.h index e559a5f9c16..03b97d6b542 100644 --- a/src/PacketDataStream.h +++ b/src/PacketDataStream.h @@ -54,7 +54,7 @@ class PacketDataStream { memcpy(&data[offset], d, len); offset += len; } else { - int l = left(); + unsigned int l = left(); memset(&data[offset], 0, l); offset += l; overshoot += len - l; @@ -99,7 +99,7 @@ class PacketDataStream { QByteArray dataBlock(quint32 len) { if (len <= left()) { - QByteArray a(charPtr(), len); + QByteArray a(charPtr(), static_cast< int >(len)); offset += len; return a; } else { @@ -109,7 +109,7 @@ class PacketDataStream { } protected: - void setup(unsigned char *d, int msize) { + void setup(unsigned char *d, unsigned int msize) { data = d; offset = 0; overshoot = 0; @@ -118,23 +118,24 @@ class PacketDataStream { } public: - PacketDataStream(const unsigned char *d, int msize) { setup(const_cast< unsigned char * >(d), msize); }; + PacketDataStream(const unsigned char *d, unsigned int msize) { setup(const_cast< unsigned char * >(d), msize); }; - PacketDataStream(const char *d, int msize) { + PacketDataStream(const char *d, unsigned int msize) { setup(const_cast< unsigned char * >(reinterpret_cast< const unsigned char * >(d)), msize); }; - PacketDataStream(char *d, int msize) { setup(reinterpret_cast< unsigned char * >(d), msize); }; + PacketDataStream(char *d, unsigned int msize) { setup(reinterpret_cast< unsigned char * >(d), msize); }; - PacketDataStream(unsigned char *d, int msize) { setup(d, msize); }; + PacketDataStream(unsigned char *d, unsigned int msize) { setup(d, msize); }; PacketDataStream(const QByteArray &qba) { - setup(const_cast< unsigned char * >(reinterpret_cast< const unsigned char * >(qba.constData())), qba.size()); + setup(const_cast< unsigned char * >(reinterpret_cast< const unsigned char * >(qba.constData())), + static_cast< unsigned int >(qba.size())); } PacketDataStream(QByteArray &qba) { unsigned char *ptr = reinterpret_cast< unsigned char * >(qba.data()); - setup(ptr, qba.capacity()); + setup(ptr, static_cast< unsigned int >(qba.capacity())); } PacketDataStream &operator<<(const quint64 value) { @@ -236,7 +237,7 @@ class PacketDataStream { PacketDataStream &operator<<(const QByteArray &a) { *this << a.size(); - append(a.constData(), a.size()); + append(a.constData(), static_cast< unsigned int >(a.size())); return *this; } @@ -247,7 +248,7 @@ class PacketDataStream { len = left(); ok = false; } - a = QByteArray(reinterpret_cast< const char * >(&data[offset]), len); + a = QByteArray(reinterpret_cast< const char * >(&data[offset]), static_cast< int >(len)); offset += len; return *this; } @@ -262,7 +263,7 @@ class PacketDataStream { len = left(); ok = false; } - s = QString::fromUtf8(reinterpret_cast< const char * >(&data[offset]), len); + s = QString::fromUtf8(reinterpret_cast< const char * >(&data[offset]), static_cast< int >(len)); offset += len; return *this; } diff --git a/src/ProcessResolver.cpp b/src/ProcessResolver.cpp index 92f1739f858..e97e3886496 100644 --- a/src/ProcessResolver.cpp +++ b/src/ProcessResolver.cpp @@ -181,13 +181,13 @@ void ProcessResolver::doResolve() { void ProcessResolver::doResolve() { pid_t pids[2048]; - int bytes = proc_listpids(PROC_ALL_PIDS, 0, pids, sizeof(pids)); - int n_proc = bytes / sizeof(pids[0]); - for (int i = 0; i < n_proc; i++) { + unsigned int bytes = static_cast< unsigned int >(proc_listpids(PROC_ALL_PIDS, 0, pids, sizeof(pids))); + unsigned int n_proc = static_cast< unsigned int >(bytes / sizeof(pids[0])); + for (unsigned int i = 0; i < n_proc; i++) { struct proc_bsdinfo proc; int st = proc_pidinfo(pids[i], PROC_PIDTBSDINFO, 0, &proc, PROC_PIDTBSDINFO_SIZE); if (st == PROC_PIDTBSDINFO_SIZE) { - addEntry(pids[i], proc.pbi_name, m_processMap); + addEntry(static_cast< std::uint64_t >(pids[i]), proc.pbi_name, m_processMap); } } } @@ -208,7 +208,7 @@ void ProcessResolver::doResolve() { } for (int i = 0; i < n_procs; ++i) { - addEntry(procs_info[i].ki_pid, procs_info[i].ki_comm, m_processMap); + addEntry(static_cast< uint64_t >(procs_info[i].ki_pid), procs_info[i].ki_comm, m_processMap); } free(procs_info); diff --git a/src/ProtoUtils.cpp b/src/ProtoUtils.cpp index 891be6bc0b8..1e5c94135b2 100644 --- a/src/ProtoUtils.cpp +++ b/src/ProtoUtils.cpp @@ -37,4 +37,4 @@ void setSuggestedVersion(MumbleProto::SuggestConfig &msg, const ::Version::full_ msg.set_version_v1(::Version::toLegacyVersion(version)); } -}; // namespace MumbleProto +} // namespace MumbleProto diff --git a/src/ProtoUtils.h b/src/ProtoUtils.h index 45e4b7da582..6e08cf05538 100644 --- a/src/ProtoUtils.h +++ b/src/ProtoUtils.h @@ -17,6 +17,6 @@ void setVersion(MumbleProto::Version &msg, const ::Version::full_t version); ::Version::full_t getSuggestedVersion(const MumbleProto::SuggestConfig &msg); void setSuggestedVersion(MumbleProto::SuggestConfig &msg, const ::Version::full_t version); -}; // namespace MumbleProto +} // namespace MumbleProto #endif // MUMBLE_PROTOUTILS_H_ diff --git a/src/QtUtils.cpp b/src/QtUtils.cpp index 1f0a8c097c4..fb08cce6687 100644 --- a/src/QtUtils.cpp +++ b/src/QtUtils.cpp @@ -24,5 +24,5 @@ namespace QtUtils { } -}; // namespace QtUtils -}; // namespace Mumble +} // namespace QtUtils +} // namespace Mumble diff --git a/src/QtUtils.h b/src/QtUtils.h index 8534cf966b4..6fb0bd52216 100644 --- a/src/QtUtils.h +++ b/src/QtUtils.h @@ -34,8 +34,8 @@ namespace QtUtils { */ QString decode_first_utf8_qssl_string(const QStringList &list); -}; // namespace QtUtils -}; // namespace Mumble +} // namespace QtUtils +} // namespace Mumble template< typename T > using qt_unique_ptr = std::unique_ptr< T, decltype(&Mumble::QtUtils::deleteQObject) >; @@ -57,7 +57,7 @@ inline QString u8(const ::std::wstring &str) { inline ::std::string u8(const QString &str) { const QByteArray &qba = str.toUtf8(); - return ::std::string(qba.constData(), qba.length()); + return ::std::string(qba.constData(), static_cast< std::size_t >(qba.length())); } inline QByteArray blob(const ::std::string &str) { @@ -65,7 +65,7 @@ inline QByteArray blob(const ::std::string &str) { } inline ::std::string blob(const QByteArray &str) { - return ::std::string(str.constData(), str.length()); + return ::std::string(str.constData(), static_cast< std::size_t >(str.length())); } inline QByteArray sha1(const QByteArray &blob) { diff --git a/src/SSLLocks.cpp b/src/SSLLocks.cpp index b2f14c670ff..0bd6924b973 100644 --- a/src/SSLLocks.cpp +++ b/src/SSLLocks.cpp @@ -47,9 +47,9 @@ unsigned long id_callback() { } void SSLLocks::initialize() { - int nlocks = CRYPTO_num_locks(); + unsigned int nlocks = CRYPTO_num_locks(); - locks = reinterpret_cast< QMutex ** >(calloc(nlocks, sizeof(QMutex *))); + locks = reinterpret_cast< QMutex ** >(calloc(nlocks, sizeof(void *))); if (!locks) { qFatal("SSLLocks: unable to allocate locks array"); @@ -60,7 +60,7 @@ void SSLLocks::initialize() { exit(1); } - for (int i = 0; i < nlocks; i++) { + for (unsigned int i = 0; i < nlocks; i++) { locks[i] = new QMutex; } diff --git a/src/Utils.h b/src/Utils.h index 8da6b0457f3..9b389ff1ac0 100644 --- a/src/Utils.h +++ b/src/Utils.h @@ -11,18 +11,13 @@ #include -#define iroundf(x) (static_cast< int >(x)) - -#ifdef Q_OS_WIN -# define STACKVAR(type, varname, count) type *varname = reinterpret_cast< type * >(_alloca(sizeof(type) * (count))) -#else +#ifndef Q_OS_WIN # ifdef WId typedef WId HWND; # endif # define __cdecl # define INVALID_SOCKET -1 # define SOCKET_ERROR -1 -# define STACKVAR(type, varname, count) type varname[count] # define CopyMemory(dst, ptr, len) memcpy(dst, ptr, len) # define ZeroMemory(ptr, len) memset(ptr, 0, len) #endif diff --git a/src/Version.cpp b/src/Version.cpp index d2cd86f11e3..19cfee97697 100644 --- a/src/Version.cpp +++ b/src/Version.cpp @@ -72,13 +72,13 @@ bool getComponents(Version::component_t &major, Version::component_t &minor, Ver QRegExp rx(QLatin1String("(\\d+)\\.(\\d+)\\.(\\d+)(?:\\.(\\d+))?")); if (rx.exactMatch(version)) { - major = rx.cap(1).toInt(); - minor = rx.cap(2).toInt(); - patch = rx.cap(3).toInt(); + major = static_cast< Version::component_t >(rx.cap(1).toInt()); + minor = static_cast< Version::component_t >(rx.cap(2).toInt()); + patch = static_cast< Version::component_t >(rx.cap(3).toInt()); return true; } return false; } -}; // namespace Version +} // namespace Version diff --git a/src/Version.h b/src/Version.h index 6c2d1795601..716b2afbe46 100644 --- a/src/Version.h +++ b/src/Version.h @@ -92,7 +92,9 @@ constexpr void getComponents(Version::component_t &major, Version::component_t & // constexpr Version::full_t fromLegacyVersion(std::uint32_t version) { - return fromComponents((version & 0xFFFF0000) >> 16, (version & 0xFF00) >> 8, version & 0xFF); + return fromComponents(static_cast< component_t >((version & 0xFFFF0000) >> 16), + static_cast< component_t >((version & 0xFF00) >> 8), + static_cast< component_t >(version & 0xFF)); } constexpr std::uint32_t toLegacyVersion(Version::full_t version) { @@ -108,6 +110,6 @@ constexpr std::uint32_t toLegacyVersion(Version::full_t version) { static_cast< std::uint32_t >(std::numeric_limits< std::uint8_t >::max()))); } -}; // namespace Version +} // namespace Version #endif diff --git a/src/VolumeAdjustment.cpp b/src/VolumeAdjustment.cpp index 4cac66f22f9..08c611a30c3 100644 --- a/src/VolumeAdjustment.cpp +++ b/src/VolumeAdjustment.cpp @@ -8,7 +8,7 @@ #include #include -constexpr float DB_THRESHOLD = 0.1; +constexpr float DB_THRESHOLD = 0.1f; VolumeAdjustment::VolumeAdjustment(float factor, int dbAdjustment) : factor(factor), dbAdjustment(dbAdjustment) { assert(dbAdjustment == INVALID_DB_ADJUSTMENT @@ -20,7 +20,7 @@ VolumeAdjustment::VolumeAdjustment(float factor, int dbAdjustment) : factor(fact // If dB is the dB-representation of a loudness change factor f, we have // dB = log2(f) * 6 <=> f = 2^{dB/6} // (+6dB equals a doubling in loudness) - || DB_THRESHOLD >= std::abs(dbAdjustment - VolumeAdjustment::toDBAdjustment(factor))); + || DB_THRESHOLD >= std::abs(static_cast< float >(dbAdjustment) - VolumeAdjustment::toDBAdjustment(factor))); } // Decibel formula: +6db = *2 @@ -40,9 +40,9 @@ VolumeAdjustment VolumeAdjustment::fromFactor(float factor) { if (factor > 0) { float dB = VolumeAdjustment::toDBAdjustment(factor); - if (std::abs(dB - static_cast< int >(dB)) < DB_THRESHOLD) { + if (std::abs(dB - static_cast< float >(static_cast< int >(dB))) < DB_THRESHOLD) { // Close-enough - return VolumeAdjustment(factor, std::round(dB)); + return VolumeAdjustment(factor, static_cast< int >(std::round(dB))); } else { return VolumeAdjustment(factor, INVALID_DB_ADJUSTMENT); } diff --git a/src/crypto/CryptStateOCB2.cpp b/src/crypto/CryptStateOCB2.cpp index 773d3603761..e5866b01cba 100644 --- a/src/crypto/CryptStateOCB2.cpp +++ b/src/crypto/CryptStateOCB2.cpp @@ -209,8 +209,18 @@ bool CryptStateOCB2::decrypt(const unsigned char *source, unsigned char *dst, un memcpy(decrypt_iv, saveiv, AES_BLOCK_SIZE); uiGood++; - uiLate += late; - uiLost += lost; + // uiLate += late, but we have to make sure we don't cause wrap-arounds on the unsigned lhs + if (late > 0) { + uiLate += static_cast< unsigned int >(late); + } else if (static_cast< int >(uiLate) > std::abs(late)) { + uiLate -= static_cast< unsigned int >(std::abs(late)); + } + // uiLost += lost, but we have to make sure we don't cause wrap-arounds on the unsigned lhs + if (lost > 0) { + uiLost += static_cast< unsigned int >(lost); + } else if (static_cast< int >(uiLost) > std::abs(lost)) { + uiLost -= static_cast< unsigned int >(std::abs(lost)); + } tLastGood.restart(); return true; diff --git a/src/crypto/CryptographicHash.cpp b/src/crypto/CryptographicHash.cpp index f67fcde54e3..a1721671e73 100644 --- a/src/crypto/CryptographicHash.cpp +++ b/src/crypto/CryptographicHash.cpp @@ -78,7 +78,7 @@ void CryptographicHashPrivate::addData(const QByteArray &buf) { return; } - int err = EVP_DigestUpdate(m_mdctx, buf.constData(), buf.size()); + int err = EVP_DigestUpdate(m_mdctx, buf.constData(), static_cast< std::size_t >(buf.size())); if (err != 1) { cleanupMdctx(); } diff --git a/src/crypto/CryptographicRandom.cpp b/src/crypto/CryptographicRandom.cpp index 31ed0d24e2a..c3283666d98 100644 --- a/src/crypto/CryptographicRandom.cpp +++ b/src/crypto/CryptographicRandom.cpp @@ -36,7 +36,10 @@ uint32_t CryptographicRandom::uint32() { unsigned char buf[4]; CryptographicRandom::fillBuffer(buf, sizeof(buf)); - ret = (buf[0]) | (buf[1] << 8) | (buf[2] << 16) | (buf[3] << 24); + ret = buf[0]; + ret |= static_cast< decltype(ret) >(buf[1] << 8); + ret |= static_cast< decltype(ret) >(buf[2] << 16); + ret |= static_cast< decltype(ret) >(buf[3] << 24); return ret; } diff --git a/src/mumble/ACLEditor.cpp b/src/mumble/ACLEditor.cpp index a9837730037..36fc841e9f7 100644 --- a/src/mumble/ACLEditor.cpp +++ b/src/mumble/ACLEditor.cpp @@ -22,11 +22,13 @@ #include "Global.h" +#include + ACLGroup::ACLGroup(const QString &name) : Group(nullptr, name) { bInherited = false; } -ACLEditor::ACLEditor(int channelparentid, QWidget *p) : QDialog(p) { +ACLEditor::ACLEditor(unsigned int channelparentid, QWidget *p) : QDialog(p) { // Simple constructor for add channel menu bAddChannelMode = true; iChannel = channelparentid; @@ -76,7 +78,7 @@ ACLEditor::ACLEditor(int channelparentid, QWidget *p) : QDialog(p) { adjustSize(); } -ACLEditor::ACLEditor(int channelid, const MumbleProto::ACL &mea, QWidget *p) : QDialog(p) { +ACLEditor::ACLEditor(unsigned int channelid, const MumbleProto::ACL &mea, QWidget *p) : QDialog(p) { QLabel *l; bAddChannelMode = false; @@ -111,8 +113,8 @@ ACLEditor::ACLEditor(int channelid, const MumbleProto::ACL &mea, QWidget *p) : Q qcbChannelTemporary->hide(); - iId = mea.channel_id(); - setWindowTitle(tr("Mumble - Edit %1").arg(Channel::get(iId)->qsName)); + iId = static_cast< int >(mea.channel_id()); + setWindowTitle(tr("Mumble - Edit %1").arg(Channel::get(static_cast< unsigned int >(iId))->qsName)); qlChannelID->setText(tr("ID: %1").arg(iId)); @@ -127,7 +129,7 @@ ACLEditor::ACLEditor(int channelid, const MumbleProto::ACL &mea, QWidget *p) : Q if (Global::get().sh->m_version >= Version::fromComponents(1, 3, 0)) { qsbChannelMaxUsers->setRange(0, INT_MAX); - qsbChannelMaxUsers->setValue(pChannel->uiMaxUsers); + qsbChannelMaxUsers->setValue(static_cast< int >(pChannel->uiMaxUsers)); qsbChannelMaxUsers->setSpecialValueText(tr("Default server value")); } else { qlChannelMaxUsers->hide(); @@ -219,7 +221,7 @@ ACLEditor::ACLEditor(int channelid, const MumbleProto::ACL &mea, QWidget *p) : Q acl->bInherited = as.inherited(); acl->iUserId = -1; if (as.has_user_id()) - acl->iUserId = as.user_id(); + acl->iUserId = static_cast< int >(as.user_id()); else acl->qsGroup = u8(as.group()); acl->pAllow = static_cast< ChanACL::Permissions >(as.grant()); @@ -236,11 +238,11 @@ ACLEditor::ACLEditor(int channelid, const MumbleProto::ACL &mea, QWidget *p) : Q gp->bInherited = gs.inherited(); gp->bInheritable = gs.inheritable(); for (int j = 0; j < gs.add_size(); ++j) - gp->qsAdd.insert(gs.add(j)); + gp->qsAdd.insert(static_cast< int >(gs.add(j))); for (int j = 0; j < gs.remove_size(); ++j) - gp->qsRemove.insert(gs.remove(j)); + gp->qsRemove.insert(static_cast< int >(gs.remove(j))); for (int j = 0; j < gs.inherited_members_size(); ++j) - gp->qsTemporary.insert(gs.inherited_members(j)); + gp->qsTemporary.insert(static_cast< int >(gs.inherited_members(j))); qlGroups << gp; } @@ -301,8 +303,9 @@ void ACLEditor::accept() { // Update channel state if (bAddChannelMode) { Global::get().sh->createChannel(iChannel, qleChannelName->text(), rteChannelDescription->text(), - qsbChannelPosition->value(), qcbChannelTemporary->isChecked(), - qsbChannelMaxUsers->value()); + static_cast< unsigned int >(qsbChannelPosition->value()), + qcbChannelTemporary->isChecked(), + static_cast< unsigned int >(qsbChannelMaxUsers->value())); } else { bool needs_update = false; @@ -325,7 +328,8 @@ void ACLEditor::accept() { needs_update = true; } if (pChannel->uiMaxUsers != static_cast< unsigned int >(qsbChannelMaxUsers->value())) { - mpcs.set_max_users(qsbChannelMaxUsers->value()); + assert(qsbChannelMaxUsers->value() >= 0); + mpcs.set_max_users(static_cast< unsigned int >(qsbChannelMaxUsers->value())); needs_update = true; } if (needs_update) @@ -342,8 +346,8 @@ void ACLEditor::accept() { MumbleProto::ACL_ChanACL *mpa = msg.add_acls(); mpa->set_apply_here(acl->bApplyHere); mpa->set_apply_subs(acl->bApplySubs); - if (acl->iUserId != -1) - mpa->set_user_id(acl->iUserId); + if (acl->iUserId >= 0) + mpa->set_user_id(static_cast< unsigned int >(acl->iUserId)); else mpa->set_group(u8(acl->qsGroup)); mpa->set_grant(acl->pAllow); @@ -360,10 +364,10 @@ void ACLEditor::accept() { mpg->set_inheritable(gp->bInheritable); foreach (int pid, gp->qsAdd) if (pid >= 0) - mpg->add_add(pid); + mpg->add_add(static_cast< unsigned int >(pid)); foreach (int pid, gp->qsRemove) if (pid >= 0) - mpg->add_remove(pid); + mpg->add_remove(static_cast< unsigned int >(pid)); } Global::get().sh->sendMessage(msg); } @@ -401,7 +405,7 @@ void ACLEditor::returnQuery(const MumbleProto::QueryUsers &mqu) { return; for (int i = 0; i < mqu.names_size(); ++i) { - int pid = mqu.ids(i); + int pid = static_cast< int >(mqu.ids(i)); QString name = u8(mqu.names(i)); QString lname = name.toLower(); qhIDCache.insert(lname, pid); diff --git a/src/mumble/ACLEditor.h b/src/mumble/ACLEditor.h index 81e53600b72..2efa80bd188 100644 --- a/src/mumble/ACLEditor.h +++ b/src/mumble/ACLEditor.h @@ -46,7 +46,7 @@ class ACLEditor : public QDialog, public Ui::ACLEditor { ChanACL *pcaPassword; int numInheritACL; - int iChannel; + unsigned int iChannel; bool bAddChannelMode; const QString userName(int id); @@ -62,8 +62,8 @@ class ACLEditor : public QDialog, public Ui::ACLEditor { void fillWidgetFromSet(QListWidget *, const QSet< int > &); public: - ACLEditor(int parentchannelid, QWidget *p = nullptr); - ACLEditor(int channelid, const MumbleProto::ACL &mea, QWidget *p = nullptr); + ACLEditor(unsigned int parentchannelid, QWidget *p = nullptr); + ACLEditor(unsigned int channelid, const MumbleProto::ACL &mea, QWidget *p = nullptr); ~ACLEditor(); void returnQuery(const MumbleProto::QueryUsers &mqu); public slots: diff --git a/src/mumble/ALSAAudio.cpp b/src/mumble/ALSAAudio.cpp index 3d512f10fc2..88a61ef003c 100644 --- a/src/mumble/ALSAAudio.cpp +++ b/src/mumble/ALSAAudio.cpp @@ -367,7 +367,8 @@ void ALSAAudioInput::run() { eMicFormat = SampleShort; initializeMixer(); - char inbuff[wantPeriod * iChannels * sizeof(short)]; + static std::vector< char > inbuff; + inbuff.resize(wantPeriod * iChannels * sizeof(short)); qml.unlock(); @@ -378,7 +379,7 @@ void ALSAAudioInput::run() { snd_pcm_status_dump(status, log); snd_pcm_status_free(status); #endif - readblapp = snd_pcm_readi(capture_handle, inbuff, static_cast< int >(wantPeriod)); + readblapp = snd_pcm_readi(capture_handle, inbuff.data(), static_cast< snd_pcm_uframes_t >(wantPeriod)); if (readblapp == -ESTRPIPE) { qWarning("ALSAAudioInput: PCM suspended, trying to resume"); while (bRunning && snd_pcm_resume(capture_handle) == -EAGAIN) @@ -392,7 +393,7 @@ void ALSAAudioInput::run() { err = snd_pcm_prepare(capture_handle); qWarning("ALSAAudioInput: %s: %s", snd_strerror(static_cast< int >(readblapp)), snd_strerror(err)); } else if (wantPeriod == static_cast< unsigned int >(readblapp)) { - addMic(inbuff, static_cast< int >(readblapp)); + addMic(inbuff.data(), static_cast< unsigned int >(readblapp)); } } @@ -452,7 +453,7 @@ void ALSAAudioOutput::run() { unsigned int iOutputSize = (iFrameSize * rrate) / SAMPLE_RATE; snd_pcm_uframes_t period_size = iOutputSize; - snd_pcm_uframes_t buffer_size = iOutputSize * (Global::get().s.iOutputDelay + 1); + snd_pcm_uframes_t buffer_size = iOutputSize * static_cast< unsigned int >(Global::get().s.iOutputDelay + 1); int dir = 1; ALSA_ERRBAIL(snd_pcm_hw_params_set_period_size_near(pcm_handle, hw_params, &period_size, &dir)); @@ -483,8 +484,10 @@ void ALSAAudioOutput::run() { const unsigned int buffsize = static_cast< unsigned int >(period_size * iChannels); - float zerobuff[buffsize]; - float outbuff[buffsize]; + static std::vector< float > zerobuff; + zerobuff.resize(buffsize); + static std::vector< float > outbuff; + outbuff.resize(buffsize); for (unsigned int i = 0; i < buffsize; i++) zerobuff[i] = 0; @@ -492,7 +495,7 @@ void ALSAAudioOutput::run() { // Fill buffer if (bOk && pcm_handle) for (unsigned int i = 0; i < buffer_size / period_size; i++) - snd_pcm_writei(pcm_handle, zerobuff, period_size); + snd_pcm_writei(pcm_handle, zerobuff.data(), period_size); if (!bOk) { Global::get().mw->msgBox( @@ -518,25 +521,25 @@ void ALSAAudioOutput::run() { initializeMixer(chanmasks); count = snd_pcm_poll_descriptors_count(pcm_handle); - snd_pcm_poll_descriptors(pcm_handle, fds, count); + snd_pcm_poll_descriptors(pcm_handle, fds, static_cast< unsigned int >(count)); qml.unlock(); while (bRunning && bOk) { - poll(fds, count, 20); + poll(fds, static_cast< nfds_t >(count), 20); unsigned short revents; - snd_pcm_poll_descriptors_revents(pcm_handle, fds, count, &revents); + snd_pcm_poll_descriptors_revents(pcm_handle, fds, static_cast< unsigned int >(count), &revents); if (revents & POLLERR) { snd_pcm_prepare(pcm_handle); } else if (revents & POLLOUT) { snd_pcm_sframes_t avail{}; ALSA_ERRCHECK(avail = snd_pcm_avail_update(pcm_handle)); while (avail >= static_cast< int >(period_size)) { - stillRun = mix(outbuff, static_cast< int >(period_size)); + stillRun = mix(outbuff.data(), static_cast< unsigned int >(period_size)); if (stillRun) { snd_pcm_sframes_t w = 0; - ALSA_ERRCHECK(w = snd_pcm_writei(pcm_handle, outbuff, period_size)); + ALSA_ERRCHECK(w = snd_pcm_writei(pcm_handle, outbuff.data(), period_size)); if (w < 0) { avail = w; break; @@ -550,13 +553,13 @@ void ALSAAudioOutput::run() { snd_pcm_drain(pcm_handle); ALSA_ERRCHECK(snd_pcm_prepare(pcm_handle)); for (unsigned int i = 0; i < buffer_size / period_size; ++i) - ALSA_ERRCHECK(snd_pcm_writei(pcm_handle, zerobuff, period_size)); + ALSA_ERRCHECK(snd_pcm_writei(pcm_handle, zerobuff.data(), period_size)); } if (!stillRun) { snd_pcm_drain(pcm_handle); - while (bRunning && !mix(outbuff, static_cast< unsigned int >(period_size))) { + while (bRunning && !mix(outbuff.data(), static_cast< unsigned int >(period_size))) { this->msleep(10); } @@ -567,9 +570,9 @@ void ALSAAudioOutput::run() { // Fill one frame for (unsigned int i = 0; i < (buffer_size / period_size) - 1; i++) - snd_pcm_writei(pcm_handle, zerobuff, period_size); + snd_pcm_writei(pcm_handle, zerobuff.data(), period_size); - snd_pcm_writei(pcm_handle, outbuff, period_size); + snd_pcm_writei(pcm_handle, outbuff.data(), period_size); } } } diff --git a/src/mumble/API.h b/src/mumble/API.h index 63c3d2a5b33..1a054a730c3 100644 --- a/src/mumble/API.h +++ b/src/mumble/API.h @@ -67,8 +67,8 @@ struct MumbleAPICurator { /// This class is a singleton as a way to be able to write C function wrappers for the member functions /// that are needed for passing to the plugins. class MumbleAPI : public QObject { - Q_OBJECT; - Q_DISABLE_COPY(MumbleAPI); + Q_OBJECT + Q_DISABLE_COPY(MumbleAPI) public: static MumbleAPI &get(); @@ -197,15 +197,15 @@ class PluginData { /// @returns A reference to the PluginData singleton static PluginData &get(); }; // class PluginData -}; // namespace API +} // namespace API // Declare the meta-types that we require in order for the API to work -Q_DECLARE_METATYPE(mumble_settings_key_t); -Q_DECLARE_METATYPE(mumble_settings_key_t *); -Q_DECLARE_METATYPE(mumble_transmission_mode_t); -Q_DECLARE_METATYPE(mumble_transmission_mode_t *); -Q_DECLARE_METATYPE(std::shared_ptr< API::api_promise_t >); +Q_DECLARE_METATYPE(mumble_settings_key_t) +Q_DECLARE_METATYPE(mumble_settings_key_t *) +Q_DECLARE_METATYPE(mumble_transmission_mode_t) +Q_DECLARE_METATYPE(mumble_transmission_mode_t *) +Q_DECLARE_METATYPE(std::shared_ptr< API::api_promise_t >) ////////////////////////////////////////////////////////////// ///////////// SYNCHRONIZATION STRATEGY /////////////////////// diff --git a/src/mumble/API_v_1_x_x.cpp b/src/mumble/API_v_1_x_x.cpp index ca92cd87c0a..06d732495d7 100644 --- a/src/mumble/API_v_1_x_x.cpp +++ b/src/mumble/API_v_1_x_x.cpp @@ -32,6 +32,7 @@ #include #include +#include #include #include @@ -141,7 +142,7 @@ MumbleAPI::MumbleAPI() { REGISTER_METATYPE(mumble_transmission_mode_t); REGISTER_METATYPE(mumble_userid_t); REGISTER_METATYPE(mumble_userid_t); - REGISTER_METATYPE(size_t); + REGISTER_METATYPE(std::size_t); REGISTER_METATYPE(uint8_t); // Define additional types that can't be defined using macro REGISTER_METATYPE @@ -300,7 +301,7 @@ void MumbleAPI::getUserName_v_1_0_x(mumble_plugin_id_t callerID, mumble_connecti if (user) { // +1 for NULL terminator - size_t size = user->qsName.toUtf8().size() + 1; + std::size_t size = static_cast< std::size_t >(user->qsName.toUtf8().size() + 1); char *nameArray = reinterpret_cast< char * >(malloc(size * sizeof(char))); @@ -340,11 +341,11 @@ void MumbleAPI::getChannelName_v_1_0_x(mumble_plugin_id_t callerID, mumble_conne VERIFY_CONNECTION(connection); ENSURE_CONNECTION_SYNCHRONIZED(connection); - const Channel *channel = Channel::get(channelID); + const Channel *channel = Channel::get(static_cast< unsigned int >(channelID)); if (channel) { // +1 for NULL terminator - size_t size = channel->qsName.toUtf8().size() + 1; + std::size_t size = static_cast< std::size_t >(channel->qsName.toUtf8().size() + 1); char *nameArray = reinterpret_cast< char * >(malloc(size * sizeof(char))); @@ -362,13 +363,13 @@ void MumbleAPI::getChannelName_v_1_0_x(mumble_plugin_id_t callerID, mumble_conne } void MumbleAPI::getAllUsers_v_1_0_x(mumble_plugin_id_t callerID, mumble_connection_t connection, - mumble_userid_t **users, size_t *userCount, + mumble_userid_t **users, std::size_t *userCount, std::shared_ptr< api_promise_t > promise) { if (QThread::currentThread() != thread()) { // Invoke in main thread QMetaObject::invokeMethod(this, "getAllUsers_v_1_0_x", Qt::QueuedConnection, Q_ARG(mumble_plugin_id_t, callerID), Q_ARG(mumble_connection_t, connection), - Q_ARG(mumble_userid_t **, users), Q_ARG(size_t *, userCount), + Q_ARG(mumble_userid_t **, users), Q_ARG(std::size_t *, userCount), Q_ARG(std::shared_ptr< api_promise_t >, promise)); return; @@ -386,7 +387,7 @@ void MumbleAPI::getAllUsers_v_1_0_x(mumble_plugin_id_t callerID, mumble_connecti QReadLocker userLock(&ClientUser::c_qrwlUsers); - size_t amount = ClientUser::c_qmUsers.size(); + std::size_t amount = static_cast< std::size_t >(ClientUser::c_qmUsers.size()); auto it = ClientUser::c_qmUsers.constBegin(); @@ -409,13 +410,13 @@ void MumbleAPI::getAllUsers_v_1_0_x(mumble_plugin_id_t callerID, mumble_connecti } void MumbleAPI::getAllChannels_v_1_0_x(mumble_plugin_id_t callerID, mumble_connection_t connection, - mumble_channelid_t **channels, size_t *channelCount, + mumble_channelid_t **channels, std::size_t *channelCount, std::shared_ptr< api_promise_t > promise) { if (QThread::currentThread() != thread()) { // Invoke in main thread QMetaObject::invokeMethod(this, "getAllChannels_v_1_0_x", Qt::QueuedConnection, Q_ARG(mumble_plugin_id_t, callerID), Q_ARG(mumble_connection_t, connection), - Q_ARG(mumble_channelid_t **, channels), Q_ARG(size_t *, channelCount), + Q_ARG(mumble_channelid_t **, channels), Q_ARG(std::size_t *, channelCount), Q_ARG(std::shared_ptr< api_promise_t >, promise)); return; @@ -433,7 +434,7 @@ void MumbleAPI::getAllChannels_v_1_0_x(mumble_plugin_id_t callerID, mumble_conne QReadLocker channelLock(&Channel::c_qrwlChannels); - size_t amount = Channel::c_qhChannels.size(); + std::size_t amount = static_cast< std::size_t >(Channel::c_qhChannels.size()); auto it = Channel::c_qhChannels.constBegin(); @@ -442,7 +443,7 @@ void MumbleAPI::getAllChannels_v_1_0_x(mumble_plugin_id_t callerID, mumble_conne unsigned int index = 0; while (it != Channel::c_qhChannels.constEnd()) { - channelIDs[index] = it.key(); + channelIDs[index] = static_cast< mumble_channelid_t >(it.key()); it++; index++; @@ -486,7 +487,7 @@ void MumbleAPI::getChannelOfUser_v_1_0_x(mumble_plugin_id_t callerID, mumble_con } if (user->cChannel) { - *channelID = user->cChannel->iId; + *channelID = static_cast< mumble_channelid_t >(user->cChannel->iId); EXIT_WITH(MUMBLE_STATUS_OK); } else { @@ -495,14 +496,14 @@ void MumbleAPI::getChannelOfUser_v_1_0_x(mumble_plugin_id_t callerID, mumble_con } void MumbleAPI::getUsersInChannel_v_1_0_x(mumble_plugin_id_t callerID, mumble_connection_t connection, - mumble_channelid_t channelID, mumble_userid_t **users, size_t *userCount, + mumble_channelid_t channelID, mumble_userid_t **users, std::size_t *userCount, std::shared_ptr< api_promise_t > promise) { if (QThread::currentThread() != thread()) { // Invoke in main thread QMetaObject::invokeMethod(this, "getUsersInChannel_v_1_0_x", Qt::QueuedConnection, Q_ARG(mumble_plugin_id_t, callerID), Q_ARG(mumble_connection_t, connection), Q_ARG(mumble_channelid_t, channelID), Q_ARG(mumble_userid_t **, users), - Q_ARG(size_t *, userCount), Q_ARG(std::shared_ptr< api_promise_t >, promise)); + Q_ARG(std::size_t *, userCount), Q_ARG(std::shared_ptr< api_promise_t >, promise)); return; } @@ -517,13 +518,13 @@ void MumbleAPI::getUsersInChannel_v_1_0_x(mumble_plugin_id_t callerID, mumble_co VERIFY_CONNECTION(connection); ENSURE_CONNECTION_SYNCHRONIZED(connection); - const Channel *channel = Channel::get(channelID); + const Channel *channel = Channel::get(static_cast< unsigned int >(channelID)); if (!channel) { EXIT_WITH(MUMBLE_EC_CHANNEL_NOT_FOUND); } - size_t amount = channel->qlUsers.size(); + std::size_t amount = static_cast< std::size_t >(channel->qlUsers.size()); mumble_userid_t *userIDs = reinterpret_cast< mumble_userid_t * >(malloc(sizeof(mumble_userid_t) * amount)); @@ -687,7 +688,7 @@ void MumbleAPI::getUserHash_v_1_0_x(mumble_plugin_id_t callerID, mumble_connecti // The user's hash is already in hexadecimal representation, so we don't have to worry about null-bytes in it // +1 for NULL terminator - size_t size = user->qsHash.toUtf8().size() + 1; + std::size_t size = static_cast< std::size_t >(user->qsHash.toUtf8().size() + 1); char *hashArray = reinterpret_cast< char * >(malloc(size * sizeof(char))); @@ -726,7 +727,7 @@ void MumbleAPI::getServerHash_v_1_0_x(mumble_plugin_id_t callerID, mumble_connec QString strHash = QString::fromLatin1(hashHex); // +1 for NULL terminator - size_t size = strHash.toUtf8().size() + 1; + std::size_t size = static_cast< std::size_t >(strHash.toUtf8().size() + 1); char *hashArray = reinterpret_cast< char * >(malloc(size * sizeof(char))); @@ -758,7 +759,7 @@ void MumbleAPI::requestLocalUserTransmissionMode_v_1_0_x(mumble_plugin_id_t call VERIFY_PLUGIN_ID(callerID); - Settings::AudioTransmit mode; + Settings::AudioTransmit mode = Settings::PushToTalk; bool identifiedTransmissionMode = false; switch (transmissionMode) { @@ -828,7 +829,7 @@ void MumbleAPI::getUserComment_v_1_0_x(mumble_plugin_id_t callerID, mumble_conne } // +1 for NULL terminator - size_t size = user->qsComment.toUtf8().size() + 1; + std::size_t size = static_cast< std::size_t >(user->qsComment.toUtf8().size() + 1); char *nameArray = reinterpret_cast< char * >(malloc(size * sizeof(char))); @@ -864,7 +865,7 @@ void MumbleAPI::getChannelDescription_v_1_0_x(mumble_plugin_id_t callerID, mumbl VERIFY_CONNECTION(connection); ENSURE_CONNECTION_SYNCHRONIZED(connection); - Channel *channel = Channel::get(channelID); + Channel *channel = Channel::get(static_cast< unsigned int >(channelID)); if (!channel) { EXIT_WITH(MUMBLE_EC_CHANNEL_NOT_FOUND); @@ -880,7 +881,7 @@ void MumbleAPI::getChannelDescription_v_1_0_x(mumble_plugin_id_t callerID, mumbl } // +1 for NULL terminator - size_t size = channel->qsDesc.toUtf8().size() + 1; + std::size_t size = static_cast< std::size_t >(channel->qsDesc.toUtf8().size() + 1); char *nameArray = reinterpret_cast< char * >(malloc(size * sizeof(char))); @@ -922,7 +923,7 @@ void MumbleAPI::requestUserMove_v_1_0_x(mumble_plugin_id_t callerID, mumble_conn EXIT_WITH(MUMBLE_EC_USER_NOT_FOUND); } - const Channel *channel = Channel::get(channelID); + const Channel *channel = Channel::get(static_cast< unsigned int >(channelID)); if (!channel) { EXIT_WITH(MUMBLE_EC_CHANNEL_NOT_FOUND); @@ -935,7 +936,7 @@ void MumbleAPI::requestUserMove_v_1_0_x(mumble_plugin_id_t callerID, mumble_conn passwordList << QString::fromUtf8(password); } - Global::get().sh->joinChannel(user->uiSession, channel->iId, passwordList); + Global::get().sh->joinChannel(user->uiSession, static_cast< unsigned int >(channel->iId), passwordList); } EXIT_WITH(MUMBLE_STATUS_OK); @@ -1163,7 +1164,7 @@ void MumbleAPI::findChannelByName_v_1_0_x(mumble_plugin_id_t callerID, mumble_co auto it = Channel::c_qhChannels.constBegin(); while (it != Channel::c_qhChannels.constEnd()) { if (it.value()->qsName == qsChannelName) { - *channelID = it.key(); + *channelID = static_cast< mumble_channelid_t >(it.key()); EXIT_WITH(MUMBLE_STATUS_OK); } @@ -1349,7 +1350,7 @@ void MumbleAPI::getMumbleSetting_string_v_1_0_x(mumble_plugin_id_t callerID, mum const QString stringValue = value.toString(); // +1 for NULL terminator - size_t size = stringValue.toUtf8().size() + 1; + std::size_t size = static_cast< std::size_t >(stringValue.toUtf8().size() + 1); char *valueArray = reinterpret_cast< char * >(malloc(size * sizeof(char))); @@ -1519,14 +1520,15 @@ void MumbleAPI::setMumbleSetting_string_v_1_0_x(mumble_plugin_id_t callerID, mum #undef IS_NOT_TYPE void MumbleAPI::sendData_v_1_0_x(mumble_plugin_id_t callerID, mumble_connection_t connection, - const mumble_userid_t *users, size_t userCount, const uint8_t *data, size_t dataLength, - const char *dataID, std::shared_ptr< api_promise_t > promise) { + const mumble_userid_t *users, std::size_t userCount, const uint8_t *data, + std::size_t dataLength, const char *dataID, std::shared_ptr< api_promise_t > promise) { if (QThread::currentThread() != thread()) { // Invoke in main thread QMetaObject::invokeMethod(this, "sendData_v_1_0_x", Qt::QueuedConnection, Q_ARG(mumble_plugin_id_t, callerID), Q_ARG(mumble_connection_t, connection), Q_ARG(const mumble_userid_t *, users), - Q_ARG(size_t, userCount), Q_ARG(const uint8_t *, data), Q_ARG(size_t, dataLength), - Q_ARG(const char *, dataID), Q_ARG(std::shared_ptr< api_promise_t >, promise)); + Q_ARG(std::size_t, userCount), Q_ARG(const uint8_t *, data), + Q_ARG(std::size_t, dataLength), Q_ARG(const char *, dataID), + Q_ARG(std::shared_ptr< api_promise_t >, promise)); return; } @@ -1551,7 +1553,7 @@ void MumbleAPI::sendData_v_1_0_x(mumble_plugin_id_t callerID, mumble_connection_ MumbleProto::PluginDataTransmission mpdt; mpdt.set_sendersession(Global::get().uiSession); - for (size_t i = 0; i < userCount; i++) { + for (std::size_t i = 0; i < userCount; i++) { const ClientUser *user = ClientUser::get(users[i]); if (user) { @@ -2156,7 +2158,7 @@ PluginData &PluginData::get() { return *instance; } -}; // namespace API +} // namespace API #undef EXIT_WITH #undef VERIFY_PLUGIN_ID diff --git a/src/mumble/ASIOInput.cpp b/src/mumble/ASIOInput.cpp index 52f03dad124..3916f563d31 100644 --- a/src/mumble/ASIOInput.cpp +++ b/src/mumble/ASIOInput.cpp @@ -158,7 +158,7 @@ ASIOConfig::ASIOConfig(Settings &st) : ConfigWidget(st) { DWORD idx = 0; DWORD keynamelen = keynamebufsize; while (RegEnumKeyEx(hkDevs, idx++, keyname, &keynamelen, nullptr, nullptr, nullptr, &ft) == ERROR_SUCCESS) { - QString name = QString::fromUtf16(reinterpret_cast< ushort * >(keyname), keynamelen); + QString deviceName = QString::fromUtf16(reinterpret_cast< ushort * >(keyname), keynamelen); HKEY hk; if (RegOpenKeyEx(hkDevs, keyname, 0, KEY_READ, &hk) == ERROR_SUCCESS) { DWORD dtype = REG_SZ; @@ -172,7 +172,7 @@ ASIOConfig::ASIOConfig(Settings &st) : ConfigWidget(st) { QString::fromUtf16(reinterpret_cast< ushort * >(wclsid), datasize / 2).toLower().trimmed(); CLSID clsid; if (!blacklist.contains(qsCls) && !FAILED(CLSIDFromString(wclsid, &clsid))) { - ASIODev ad(name, qsCls); + ASIODev ad(std::move(deviceName), qsCls); qlDevs << ad; } } @@ -507,7 +507,7 @@ ASIOInput::ASIOInput() { iEchoChannels = iNumSpeaker; iMicChannels = iNumMic; - iEchoFreq = iMicFreq = iroundf(srate); + iEchoFreq = iMicFreq = static_cast< int >(srate); initializeMixer(); @@ -596,15 +596,16 @@ void ASIOInput::addBuffer(ASIOSampleType sampType, int interleave, void *src, fl } void ASIOInput::bufferReady(long buffindex) { - STACKVAR(float, buffer, lBufSize *qMax(iNumMic, iNumSpeaker)); + static std::vector< float > buffer; + buffer.resize(lBufSize * qMax(iNumMic, iNumSpeaker)); for (int c = 0; c < iNumSpeaker; ++c) - addBuffer(aciInfo[iNumMic + c].type, iNumSpeaker, abiInfo[iNumMic + c].buffers[buffindex], buffer + c); - addEcho(buffer, lBufSize); + addBuffer(aciInfo[iNumMic + c].type, iNumSpeaker, abiInfo[iNumMic + c].buffers[buffindex], buffer.data() + c); + addEcho(buffer.data(), lBufSize); for (int c = 0; c < iNumMic; ++c) - addBuffer(aciInfo[c].type, iNumMic, abiInfo[c].buffers[buffindex], buffer + c); - addMic(buffer, lBufSize); + addBuffer(aciInfo[c].type, iNumMic, abiInfo[c].buffers[buffindex], buffer.data() + c); + addMic(buffer.data(), lBufSize); } void ASIOInput::bufferSwitch(long index, ASIOBool processNow) { diff --git a/src/mumble/Audio.cpp b/src/mumble/Audio.cpp index ae0bd735266..9faa8057ad2 100644 --- a/src/mumble/Audio.cpp +++ b/src/mumble/Audio.cpp @@ -43,16 +43,16 @@ void LoopUser::addFrame(const Mumble::Protocol::AudioData &audioData) { QMutexLocker l(&qmLock); bool restart = (qetLastFetch.elapsed() > 100); - double time = qetTicker.elapsed(); + long time = qetTicker.elapsed(); - double r; + float r; if (restart) - r = 0.0; + r = 0; else - r = DOUBLE_RAND * Global::get().s.dMaxPacketDelay; + r = static_cast< float >(DOUBLE_RAND * Global::get().s.dMaxPacketDelay); - float virtualArrivalTime = time + r; + float virtualArrivalTime = static_cast< float >(time) + r; // Insert default-constructed AudioPacket object and only then fill its data in-place. This is necessary to // avoid any moving around of the payload vector which would mess up our pointers in the AudioData object. m_packets[virtualArrivalTime] = AudioPacket{}; @@ -87,7 +87,7 @@ void LoopUser::fetchFrames() { return; } - double cmp = qetTicker.elapsed(); + float cmp = static_cast< float >(qetTicker.elapsed()); auto it = m_packets.begin(); while (it != m_packets.end()) { diff --git a/src/mumble/Audio.h b/src/mumble/Audio.h index 11598eeda5c..22c8b254aa1 100644 --- a/src/mumble/Audio.h +++ b/src/mumble/Audio.h @@ -25,7 +25,8 @@ // A Wikipedia article claims the average distance between ears is 15.2 cm for men // (0.44 ms) and 14.4 cm for women (0.42 ms). We decided to set the delay to 0.43 ms. // The delay is calculated from the distance and the speed of sound. -constexpr float INTERAURAL_DELAY = 0.00043 / (1 / static_cast< float >(SAMPLE_RATE)); +constexpr unsigned int INTERAURAL_DELAY = + static_cast< unsigned int >(0.00043f / (1 / static_cast< float >(SAMPLE_RATE))); typedef QPair< QString, QVariant > audioDevice; diff --git a/src/mumble/AudioConfigDialog.cpp b/src/mumble/AudioConfigDialog.cpp index 5e0cce88488..a5fa2037985 100644 --- a/src/mumble/AudioConfigDialog.cpp +++ b/src/mumble/AudioConfigDialog.cpp @@ -15,6 +15,8 @@ #include +#include + const QString AudioOutputDialog::name = QLatin1String("AudioOutputWidget"); const QString AudioInputDialog::name = QLatin1String("AudioInputWidget"); @@ -134,10 +136,10 @@ void AudioInputDialog::load(const Settings &r) { loadComboBox(qcbTransmit, r.atTransmit); loadSlider(qsTransmitHold, r.iVoiceHold); - loadSlider(qsTransmitMin, iroundf(r.fVADmin * 32767.0f + 0.5f)); - loadSlider(qsTransmitMax, iroundf(r.fVADmax * 32767.0f + 0.5f)); + loadSlider(qsTransmitMin, static_cast< int >(r.fVADmin * 32767.0f + 0.5f)); + loadSlider(qsTransmitMax, static_cast< int >(r.fVADmax * 32767.0f + 0.5f)); loadSlider(qsFrames, (r.iFramesPerPacket == 1) ? 1 : (r.iFramesPerPacket / 2 + 1)); - loadSlider(qsDoublePush, iroundf(static_cast< float >(r.uiDoublePush) / 1000.f + 0.5f)); + loadSlider(qsDoublePush, static_cast< int >(static_cast< float >(r.uiDoublePush) / 1000.f + 0.5f)); loadSlider(qsPTTHold, static_cast< int >(r.pttHold)); if (r.vsVAD == Settings::Amplitude) @@ -206,7 +208,7 @@ void AudioInputDialog::load(const Settings &r) { loadSlider(qsAmp, 20000 - r.iMinLoudness); // Idle auto actions - qsbIdle->setValue(r.iIdleTime / 60); + qsbIdle->setValue(static_cast< int >(r.iIdleTime) / 60); loadComboBox(qcbIdleAction, r.iaeIdleAction); loadCheckBox(qcbUndoIdleAction, r.bUndoIdleActionUponActivity); @@ -261,12 +263,12 @@ void AudioInputDialog::save() const { s.vsVAD = qrbSNR->isChecked() ? Settings::SignalToNoise : Settings::Amplitude; s.iFramesPerPacket = qsFrames->value(); s.iFramesPerPacket = (s.iFramesPerPacket == 1) ? 1 : ((s.iFramesPerPacket - 1) * 2); - s.uiDoublePush = qsDoublePush->value() * 1000; - s.pttHold = qsPTTHold->value(); + s.uiDoublePush = static_cast< unsigned int >(qsDoublePush->value() * 1000); + s.pttHold = static_cast< quint64 >(qsPTTHold->value()); s.atTransmit = static_cast< Settings::AudioTransmit >(qcbTransmit->currentIndex()); // Idle auto actions - s.iIdleTime = qsbIdle->value() * 60; + s.iIdleTime = static_cast< unsigned int >(qsbIdle->value() * 60); s.iaeIdleAction = static_cast< Settings::IdleAction >(qcbIdleAction->currentIndex()); s.bUndoIdleActionUponActivity = qcbUndoIdleAction->isChecked(); @@ -537,14 +539,14 @@ void AudioInputDialog::updateEchoEnableState() { qcbEcho->setItemData(0, tr("Disable echo cancellation."), Qt::ToolTipRole); int i = 0; - for (EchoCancelOptionID ecoid : air->echoOptions) { - if (air->canEcho(ecoid, outputInterface)) { + for (EchoCancelOptionID echoid : air->echoOptions) { + if (air->canEcho(echoid, outputInterface)) { ++i; hasUsableEchoOption = true; - const EchoCancelOption &echoOption = EchoCancelOption::getOptions()[static_cast< int >(ecoid)]; - qcbEcho->insertItem(i, echoOption.description, static_cast< int >(ecoid)); + const EchoCancelOption &echoOption = EchoCancelOption::getOptions()[static_cast< std::size_t >(echoid)]; + qcbEcho->insertItem(i, echoOption.description, static_cast< int >(echoid)); qcbEcho->setItemData(i, echoOption.explanation, Qt::ToolTipRole); - if (s.echoOption == ecoid) { + if (s.echoOption == echoid) { qcbEcho->setCurrentIndex(i); } } @@ -578,9 +580,9 @@ void AudioInputDialog::on_Tick_timeout() { abSpeech->iAbove = qsTransmitMax->value(); if (qrbAmplitude->isChecked()) { - abSpeech->iValue = iroundf((32767.f / 96.0f) * (96.0f + ai->dPeakCleanMic) + 0.5f); + abSpeech->iValue = static_cast< int >((32767.f / 96.0f) * (96.0f + ai->dPeakCleanMic) + 0.5f); } else { - abSpeech->iValue = iroundf(ai->fSpeechProb * 32767.0f + 0.5f); + abSpeech->iValue = static_cast< int >(ai->fSpeechProb * 32767.0f + 0.5f); } abSpeech->update(); } @@ -713,8 +715,8 @@ void AudioOutputDialog::load(const Settings &r) { loadCheckBox(qcbExclusive, r.bExclusiveOutput); loadSlider(qsDelay, r.iOutputDelay); - loadSlider(qsVolume, iroundf(r.fVolume * 100.0f + 0.5f)); - loadSlider(qsOtherVolume, iroundf((1.0f - r.fOtherVolume) * 100.0f + 0.5f)); + loadSlider(qsVolume, static_cast< int >(r.fVolume * 100.0f + 0.5f)); + loadSlider(qsOtherVolume, static_cast< int >((1.0f - r.fOtherVolume) * 100.0f + 0.5f)); loadCheckBox(qcbAttenuateOthersOnTalk, r.bAttenuateOthersOnTalk); loadCheckBox(qcbAttenuateOthers, r.bAttenuateOthers); loadCheckBox(qcbAttenuateUsersOnPrioritySpeak, r.bAttenuateUsersOnPrioritySpeak); @@ -730,11 +732,11 @@ void AudioOutputDialog::load(const Settings &r) { loadSlider(qsJitter, r.iJitterBufferSize); loadComboBox(qcbLoopback, r.lmLoopMode); loadSlider(qsPacketDelay, static_cast< int >(r.dMaxPacketDelay)); - loadSlider(qsPacketLoss, iroundf(r.dPacketLoss * 100.0f + 0.5f)); + loadSlider(qsPacketLoss, static_cast< int >(r.dPacketLoss * 100.0f + 0.5f)); qsbMinimumDistance->setValue(r.fAudioMinDistance); qsbMaximumDistance->setValue(r.fAudioMaxDistance); - qsbMinimumVolume->setValue(r.fAudioMaxDistVolume * 100); - qsbBloom->setValue(r.fAudioBloom * 100); + qsbMinimumVolume->setValue(static_cast< int >(r.fAudioMaxDistVolume * 100)); + qsbBloom->setValue(static_cast< int >(r.fAudioBloom * 100)); loadCheckBox(qcbHeadphones, r.bPositionalHeadphone); loadCheckBox(qcbPositional, r.bPositionalAudio); @@ -858,7 +860,7 @@ void AudioOutputDialog::on_qcbLoopback_currentIndexChanged(int v) { void AudioOutputDialog::on_qsMinDistance_valueChanged(int value) { QSignalBlocker blocker(qsbMinimumDistance); - qsbMinimumDistance->setValue(value / 10.0f); + qsbMinimumDistance->setValue(value / 10.0); // Ensure that max distance is always a least 1m larger than min distance qsbMaximumDistance->setValue(std::max(qsbMaximumDistance->value(), (value / 10.0) + 1)); @@ -866,7 +868,7 @@ void AudioOutputDialog::on_qsMinDistance_valueChanged(int value) { void AudioOutputDialog::on_qsbMinimumDistance_valueChanged(double value) { QSignalBlocker blocker(qsMinDistance); - qsMinDistance->setValue(value * 10); + qsMinDistance->setValue(static_cast< int >(value * 10)); // Ensure that max distance is always a least 1m larger than min distance qsMaxDistance->setValue(std::max(qsMaxDistance->value(), static_cast< int >(value * 10) + 10)); @@ -874,14 +876,14 @@ void AudioOutputDialog::on_qsbMinimumDistance_valueChanged(double value) { void AudioOutputDialog::on_qsMaxDistance_valueChanged(int value) { QSignalBlocker blocker(qsbMaximumDistance); - qsbMaximumDistance->setValue(value / 10.0f); + qsbMaximumDistance->setValue(value / 10.0); // Ensure that min distance is always a least 1m less than max distance qsbMinimumDistance->setValue(std::min(qsbMinimumDistance->value(), (value / 10.0) - 1)); } void AudioOutputDialog::on_qsbMaximumDistance_valueChanged(double value) { QSignalBlocker blocker(qsMaxDistance); - qsMaxDistance->setValue(value * 10); + qsMaxDistance->setValue(static_cast< int >(value * 10)); // Ensure that min distance is always a least 1m less than max distance qsMinDistance->setValue(std::min(qsMinDistance->value(), static_cast< int >(value * 10) - 10)); diff --git a/src/mumble/AudioInput.cpp b/src/mumble/AudioInput.cpp index 39bfbaae5a3..c1ffba53e8d 100644 --- a/src/mumble/AudioInput.cpp +++ b/src/mumble/AudioInput.cpp @@ -213,7 +213,8 @@ bool AudioInputRegistrar::isMicrophoneAccessDeniedByOS() { return false; } -AudioInput::AudioInput() : opusBuffer(Global::get().s.iFramesPerPacket * (SAMPLE_RATE / 100)) { +AudioInput::AudioInput() + : opusBuffer(static_cast< std::size_t >(Global::get().s.iFramesPerPacket * (SAMPLE_RATE / 100))) { bDebugDumpInput = Global::get().bDebugDumpInput; resync.bDebugPrintQueue = Global::get().bDebugPrintQueue; if (bDebugDumpInput) { @@ -319,7 +320,7 @@ AudioInput::~AudioInput() { bool AudioInput::isTransmitting() const { return bPreviousVoice; -}; +} #define IN_MIXER_FLOAT(channels) \ static void inMixerFloat##channels(float *RESTRICT buffer, const void *RESTRICT ipt, unsigned int nsamp, \ @@ -356,7 +357,8 @@ static void inMixerFloatMask(float *RESTRICT buffer, const void *RESTRICT ipt, u const float *RESTRICT input = reinterpret_cast< const float * >(ipt); unsigned int chancount = 0; - STACKVAR(unsigned int, chanindex, N); + static std::vector< unsigned int > chanindex; + chanindex.resize(N); for (unsigned int j = 0; j < N; ++j) { if ((mask & (1ULL << j)) == 0) { continue; @@ -380,7 +382,8 @@ static void inMixerShortMask(float *RESTRICT buffer, const void *RESTRICT ipt, u const short *RESTRICT input = reinterpret_cast< const short * >(ipt); unsigned int chancount = 0; - STACKVAR(unsigned int, chanindex, N); + static std::vector< unsigned int > chanindex; + chanindex.resize(N); for (unsigned int j = 0; j < N; ++j) { if ((mask & (1ULL << j)) == 0) { continue; @@ -536,9 +539,10 @@ void AudioInput::initializeMixer() { imfMic = chooseMixer(iMicChannels, eMicFormat, uiMicChannelMask); imfEcho = chooseMixer(iEchoChannels, eEchoFormat, uiEchoChannelMask); - iMicSampleSize = static_cast< int >(iMicChannels * ((eMicFormat == SampleFloat) ? sizeof(float) : sizeof(short))); + iMicSampleSize = + static_cast< unsigned int >(iMicChannels * ((eMicFormat == SampleFloat) ? sizeof(float) : sizeof(short))); iEchoSampleSize = - static_cast< int >(iEchoChannels * ((eEchoFormat == SampleFloat) ? sizeof(float) : sizeof(short))); + static_cast< unsigned int >(iEchoChannels * ((eEchoFormat == SampleFloat) ? sizeof(float) : sizeof(short))); bResetProcessor = true; @@ -653,7 +657,7 @@ void AudioInput::addEcho(const void *data, unsigned int nsamp) { // float -> 16bit PCM const float mul = 32768.f; - for (int j = 0; j < iEchoFrameSize; ++j) { + for (unsigned int j = 0; j < iEchoFrameSize; ++j) { outbuff[j] = static_cast< short >(qBound(-32768.f, (ptr[j] * mul), 32767.f)); } @@ -762,7 +766,7 @@ void AudioInput::resetAudioProcessor() { speex_preprocess_ctl(sppPreprocess, SPEEX_PREPROCESS_SET_AGC_TARGET, &iArg); float v = 30000.0f / static_cast< float >(Global::get().s.iMinLoudness); - iArg = iroundf(floorf(20.0f * log10f(v))); + iArg = static_cast< int >(floorf(20.0f * log10f(v))); speex_preprocess_ctl(sppPreprocess, SPEEX_PREPROCESS_SET_AGC_MAX_GAIN, &iArg); iArg = -60; @@ -775,8 +779,9 @@ void AudioInput::resetAudioProcessor() { if (iEchoChannels > 0) { int filterSize = iFrameSize * (10 + resync.getNominalLag()); - sesEcho = speex_echo_state_init_mc(iFrameSize, filterSize, 1, bEchoMulti ? iEchoChannels : 1); - iArg = iSampleRate; + sesEcho = + speex_echo_state_init_mc(iFrameSize, filterSize, 1, bEchoMulti ? static_cast< int >(iEchoChannels) : 1); + iArg = iSampleRate; speex_echo_ctl(sesEcho, SPEEX_ECHO_SET_SAMPLING_RATE, &iArg); speex_preprocess_ctl(sppPreprocess, SPEEX_PREPROCESS_SET_ECHO_STATE, sesEcho); @@ -859,7 +864,6 @@ int AudioInput::encodeOpusFrame(short *source, int size, EncodingOutputBuffer &b void AudioInput::encodeAudioFrame(AudioChunk chunk) { int iArg; - int i; float sum; short max; @@ -872,14 +876,14 @@ void AudioInput::encodeAudioFrame(AudioChunk chunk) { // if the value of Global::get().iTarget changes during the execution of this function, // it won't cause any inconsistencies and the change is reflected once this // function is called again. - int voiceTargetID = Global::get().iTarget; + std::int32_t voiceTargetID = Global::get().iTarget; if (!bRunning) return; sum = 1.0f; max = 1; - for (i = 0; i < iFrameSize; i++) { + for (unsigned int i = 0; i < iFrameSize; i++) { sum += static_cast< float >(chunk.mic[i] * chunk.mic[i]); max = std::max(static_cast< short >(abs(chunk.mic[i])), max); } @@ -888,7 +892,7 @@ void AudioInput::encodeAudioFrame(AudioChunk chunk) { if (chunk.speaker && (iEchoChannels > 0)) { sum = 1.0f; - for (i = 0; i < iEchoFrameSize; ++i) { + for (unsigned int i = 0; i < iEchoFrameSize; ++i) { sum += static_cast< float >(chunk.speaker[i] * chunk.speaker[i]); } dPeakSpeaker = qMax(20.0f * log10f(sqrtf(sum / static_cast< float >(iFrameSize)) / 32768.0f), -96.0f); @@ -918,13 +922,13 @@ void AudioInput::encodeAudioFrame(AudioChunk chunk) { // At the time of writing this code, RNNoise only supports a sample rate of 48000 Hz. if (noiseCancel == Settings::NoiseCancelRNN || noiseCancel == Settings::NoiseCancelBoth) { float denoiseFrames[480]; - for (int i = 0; i < 480; i++) { + for (unsigned int i = 0; i < 480; i++) { denoiseFrames[i] = psSource[i]; } rnnoise_process_frame(denoiseState, denoiseFrames, denoiseFrames); - for (int i = 0; i < 480; i++) { + for (unsigned int i = 0; i < 480; i++) { psSource[i] = clampFloatSample(denoiseFrames[i]); } } @@ -933,7 +937,7 @@ void AudioInput::encodeAudioFrame(AudioChunk chunk) { speex_preprocess_run(sppPreprocess, psSource); sum = 1.0f; - for (i = 0; i < iFrameSize; i++) + for (unsigned int i = 0; i < iFrameSize; i++) sum += static_cast< float >(psSource[i] * psSource[i]); float micLevel = sqrtf(sum / static_cast< float >(iFrameSize)); dPeakSignal = qMax(20.0f * log10f(micLevel / 32768.0f), -96.0f); @@ -941,9 +945,11 @@ void AudioInput::encodeAudioFrame(AudioChunk chunk) { if (bDebugDumpInput) { outMic.write(reinterpret_cast< const char * >(chunk.mic), iFrameSize * sizeof(short)); if (chunk.speaker) { - outSpeaker.write(reinterpret_cast< const char * >(chunk.speaker), iEchoFrameSize * sizeof(short)); + outSpeaker.write(reinterpret_cast< const char * >(chunk.speaker), + static_cast< std::streamsize >(iEchoFrameSize * sizeof(short))); } - outProcessed.write(reinterpret_cast< const char * >(psSource), iFrameSize * sizeof(short)); + outProcessed.write(reinterpret_cast< const char * >(psSource), + static_cast< std::streamsize >(iFrameSize * sizeof(short))); } spx_int32_t prob = 0; @@ -1013,7 +1019,7 @@ void AudioInput::encodeAudioFrame(AudioChunk chunk) { if (p) { if (!bIsSpeech) p->setTalking(Settings::Passive); - else if (voiceTargetID == 0) + else if (voiceTargetID == Mumble::Protocol::ReservedTargetIDs::REGULAR_SPEECH) p->setTalking(Settings::Talking); else p->setTalking(Settings::Shouting); @@ -1118,7 +1124,7 @@ void AudioInput::encodeAudioFrame(AudioChunk chunk) { // a codec configuration switch by suddenly using a wildly different // framecount per packet. const int missingFrames = iAudioFrames - iBufferedFrames; - opusBuffer.insert(opusBuffer.end(), iFrameSize * missingFrames, 0); + opusBuffer.insert(opusBuffer.end(), static_cast< std::size_t >(iFrameSize * missingFrames), 0); iBufferedFrames += missingFrames; iFrameCounter += missingFrames; } @@ -1150,18 +1156,18 @@ void AudioInput::encodeAudioFrame(AudioChunk chunk) { static void sendAudioFrame(gsl::span< const Mumble::Protocol::byte > encodedPacket) { ServerHandlerPtr sh = Global::get().sh; if (sh) { - sh->sendMessage(encodedPacket.data(), encodedPacket.size()); + sh->sendMessage(encodedPacket.data(), static_cast< int >(encodedPacket.size())); } } -void AudioInput::flushCheck(const QByteArray &frame, bool terminator, int voiceTargetID) { +void AudioInput::flushCheck(const QByteArray &frame, bool terminator, std::int32_t voiceTargetID) { qlFrames << frame; if (!terminator && iBufferedFrames < iAudioFrames) return; Mumble::Protocol::AudioData audioData; - audioData.targetOrContext = voiceTargetID; + audioData.targetOrContext = static_cast< std::uint32_t >(voiceTargetID); audioData.isLastFrame = terminator; if (terminator && Global::get().iPrevTarget > 0) { @@ -1171,7 +1177,7 @@ void AudioInput::flushCheck(const QByteArray &frame, bool terminator, int voiceT // is reset to 0 by now. In order to send the last whisper frame correctly, we have to use // Global::get().iPrevTarget which is set to whatever Global::get().iTarget has been before its last change. - audioData.targetOrContext = Global::get().iPrevTarget; + audioData.targetOrContext = static_cast< std::uint32_t >(Global::get().iPrevTarget); // We reset Global::get().iPrevTarget as it has fulfilled its purpose for this whisper-action. It'll be set // accordingly once the client whispers for the next time. @@ -1186,7 +1192,7 @@ void AudioInput::flushCheck(const QByteArray &frame, bool terminator, int voiceT int frames = iBufferedFrames; iBufferedFrames = 0; - audioData.frameNumber = iFrameCounter - frames; + audioData.frameNumber = static_cast< std::size_t >(iFrameCounter - frames); if (Global::get().s.bTransmitPosition && Global::get().pluginManager && !Global::get().bCenterPosition && Global::get().pluginManager->fetchPositionalData()) { @@ -1204,7 +1210,8 @@ void AudioInput::flushCheck(const QByteArray &frame, bool terminator, int voiceT assert(qlFrames.size() == 1); audioData.payload = gsl::span< const Mumble::Protocol::byte >( - reinterpret_cast< const Mumble::Protocol::byte * >(qlFrames[0].constData()), qlFrames[0].size()); + reinterpret_cast< const Mumble::Protocol::byte * >(qlFrames[0].constData()), + static_cast< std::size_t >(qlFrames[0].size())); { ServerHandlerPtr sh = Global::get().sh; diff --git a/src/mumble/AudioInput.h b/src/mumble/AudioInput.h index a3bb4cd0751..2904e3f8a89 100644 --- a/src/mumble/AudioInput.h +++ b/src/mumble/AudioInput.h @@ -13,6 +13,7 @@ #include #include +#include #include #include #include @@ -208,7 +209,7 @@ class AudioInput : public QThread { unsigned int iMicFreq, iEchoFreq; unsigned int iMicLength, iEchoLength; unsigned int iMicSampleSize, iEchoSampleSize; - int iEchoMCLength, iEchoFrameSize; + unsigned int iEchoMCLength, iEchoFrameSize; quint64 uiMicChannelMask, uiEchoChannelMask; bool bEchoMulti; @@ -258,7 +259,7 @@ class AudioInput : public QThread { int iBufferedFrames; QList< QByteArray > qlFrames; - void flushCheck(const QByteArray &, bool terminator, int voiceTargetID); + void flushCheck(const QByteArray &, bool terminator, std::int32_t voiceTargetID); void initializeMixer(); diff --git a/src/mumble/AudioOutput.cpp b/src/mumble/AudioOutput.cpp index d8e80e9073a..f67514a6122 100644 --- a/src/mumble/AudioOutput.cpp +++ b/src/mumble/AudioOutput.cpp @@ -19,6 +19,7 @@ #include "VoiceRecorder.h" #include "Global.h" +#include #include // Remember that we cannot use static member classes that are not pointers, as the constructor @@ -402,14 +403,15 @@ void AudioOutput::initializeMixer(const unsigned int *chanmasks, bool forceheadp fSpeakers[3 * i + 2] /= d; } float *spf = &fStereoPanningFactor[2 * i]; - spf[0] = (1.0 - fSpeakers[i * 3 + 0]) / 2.0; - spf[1] = (1.0 + fSpeakers[i * 3 + 0]) / 2.0; + spf[0] = (1.0f - fSpeakers[i * 3 + 0]) / 2.0f; + spf[1] = (1.0f + fSpeakers[i * 3 + 0]) / 2.0f; } } else if (iChannels == 1) { fStereoPanningFactor[0] = 0.5; fStereoPanningFactor[1] = 0.5; } - iSampleSize = static_cast< int >(iChannels * ((eSampleFormat == SampleFloat) ? sizeof(float) : sizeof(short))); + iSampleSize = + static_cast< unsigned int >(iChannels * ((eSampleFormat == SampleFloat) ? sizeof(float) : sizeof(short))); qWarning("AudioOutput: Initialized %d channel %d hz mixer", iChannels, iMixerFreq); if (Global::get().s.bPositionalAudio && iChannels == 1) { @@ -467,14 +469,17 @@ bool AudioOutput::mix(void *outbuff, unsigned int frameCount) { // If the audio backend uses a float-array we can sample and mix the audio sources directly into the output. // Otherwise we'll have to use an intermediate buffer which we will convert to an array of shorts later - STACKVAR(float, fOutput, iChannels *frameCount); - float *output = (eSampleFormat == SampleFloat) ? reinterpret_cast< float * >(outbuff) : fOutput; + static std::vector< float > fOutput; + fOutput.resize(iChannels * frameCount); + float *output = (eSampleFormat == SampleFloat) ? reinterpret_cast< float * >(outbuff) : fOutput.data(); memset(output, 0, sizeof(float) * frameCount * iChannels); if (!qlMix.isEmpty()) { // There are audio sources available -> mix those sources together and feed them into the audio backend - STACKVAR(float, speaker, iChannels * 3); - STACKVAR(float, svol, iChannels); + static std::vector< float > speaker; + speaker.resize(iChannels * 3); + static std::vector< float > svol; + svol.resize(iChannels); bool validListener = false; @@ -601,7 +606,9 @@ bool AudioOutput::mix(void *outbuff, unsigned int frameCount) { // As the events may cause the output PCM to change, the connection has to be direct in any case const int channels = (speech && speech->bStereo) ? 2 : 1; // If user != nullptr, then the current audio is considered speech - emit audioSourceFetched(pfBuffer, frameCount, channels, SAMPLE_RATE, static_cast< bool >(user), user); + assert(channels >= 0); + emit audioSourceFetched(pfBuffer, frameCount, static_cast< unsigned int >(channels), SAMPLE_RATE, + static_cast< bool >(user), user); // If recording is enabled add the current audio source to the recording buffer if (recorder) { @@ -610,7 +617,7 @@ bool AudioOutput::mix(void *outbuff, unsigned int frameCount) { // Mix down stereo to mono. TODO: stereo record support // frame: for a stereo stream, the [LR] pair inside ...[LR]LRLRLR.... is a frame for (unsigned int i = 0; i < frameCount; ++i) { - recbuff[i] += (pfBuffer[2 * i] / 2.0 + pfBuffer[2 * i + 1] / 2.0) * volumeAdjustment; + recbuff[i] += (pfBuffer[2 * i] / 2.0f + pfBuffer[2 * i + 1] / 2.0f) * volumeAdjustment; } } else { for (unsigned int i = 0; i < frameCount; ++i) { @@ -619,7 +626,7 @@ bool AudioOutput::mix(void *outbuff, unsigned int frameCount) { } if (!recorder->isInMixDownMode()) { - recorder->addBuffer(speech->p, recbuff, frameCount); + recorder->addBuffer(speech->p, recbuff, static_cast< int >(frameCount)); recbuff = boost::shared_array< float >(new float[frameCount]); memset(recbuff.get(), 0, sizeof(float) * frameCount); } @@ -634,10 +641,8 @@ bool AudioOutput::mix(void *outbuff, unsigned int frameCount) { if (validListener && ((buffer->fPos[0] != 0.0f) || (buffer->fPos[1] != 0.0f) || (buffer->fPos[2] != 0.0f))) { // Add position to position map - AudioOutputSpeech *speech = qobject_cast< AudioOutputSpeech * >(buffer); #ifdef USE_MANUAL_PLUGIN - if (speech) { - const ClientUser *user = speech->p; + if (user) { // The coordinates in the plane are actually given by x and z instead of x and y (y is up) positions.insert(user->uiSession, { buffer->fPos[0], buffer->fPos[2] }); } @@ -708,24 +713,25 @@ bool AudioOutput::mix(void *outbuff, unsigned int frameCount) { // newly calculated offset for this chunk. This prevents clicking / buzzing when the // audio source or camera is moving, because abruptly changing offsets (and thus // abruptly changing the playback position) will create a clicking noise. - const int offset = - INTERAURAL_DELAY * (1.0 + dot) / 2.0; // Normalize dot to range [0,1] instead [-1,1] - const int oldOffset = buffer->piOffset[s]; - const float incOffset = (offset - oldOffset) / static_cast< float >(frameCount); - buffer->piOffset[s] = offset; + // Normalize dot to range [0,1] instead [-1,1] + const int offset = static_cast< int >(INTERAURAL_DELAY * (1.0f + dot) / 2.0f); + const int oldOffset = static_cast< int >(buffer->piOffset[s]); + const float incOffset = static_cast< float >(offset - oldOffset) / static_cast< float >(frameCount); + buffer->piOffset[s] = static_cast< unsigned int >(offset); /* qWarning("%d: Pos %f %f %f : Dot %f Len %f ChannelVol %f", s, speaker[s*3+0], speaker[s*3+1], speaker[s*3+2], dot, len, channelVol); */ if ((old >= 0.00000001f) || (channelVol >= 0.00000001f)) { for (unsigned int i = 0; i < frameCount; ++i) { - unsigned int currentOffset = oldOffset + incOffset * i; + unsigned int currentOffset = static_cast< unsigned int >( + static_cast< float >(oldOffset) + incOffset * static_cast< float >(i)); if (speech && speech->bStereo) { // Mix stereo user's stream into mono // frame: for a stereo stream, the [LR] pair inside ...[LR]LRLRLR.... is a frame - o[i * nchan] += - (pfBuffer[2 * i + currentOffset] / 2.0 + pfBuffer[2 * i + currentOffset + 1] / 2.0) - * (old + inc * static_cast< float >(i)); + o[i * nchan] += (pfBuffer[2 * i + currentOffset] / 2.0f + + pfBuffer[2 * i + currentOffset + 1] / 2.0f) + * (old + inc * static_cast< float >(i)); } else { o[i * nchan] += pfBuffer[i + currentOffset] * (old + inc * static_cast< float >(i)); } @@ -755,7 +761,7 @@ bool AudioOutput::mix(void *outbuff, unsigned int frameCount) { } if (recorder && recorder->isInMixDownMode()) { - recorder->addBuffer(nullptr, recbuff, frameCount); + recorder->addBuffer(nullptr, recbuff, static_cast< int >(frameCount)); } } diff --git a/src/mumble/AudioOutputCache.cpp b/src/mumble/AudioOutputCache.cpp index 9f987982259..b447edb19c7 100644 --- a/src/mumble/AudioOutputCache.cpp +++ b/src/mumble/AudioOutputCache.cpp @@ -51,7 +51,7 @@ void AudioOutputCache::loadFrom(const Mumble::Protocol::AudioData &audioData) { // Then copy remaining fields (that we care about) m_isLastFrame = audioData.isLastFrame; m_volumeAdjustment = audioData.volumeAdjustment.factor; - m_audioContext = audioData.targetOrContext; + m_audioContext = static_cast< Mumble::Protocol::audio_context_t >(audioData.targetOrContext); // And finally copy positional data, if available if (audioData.containsPositionalData) { @@ -60,7 +60,7 @@ void AudioOutputCache::loadFrom(const Mumble::Protocol::AudioData &audioData) { assert(m_position.size() == 3); assert(audioData.position.size() == 3); - for (int i = 0; i < 3; ++i) { + for (unsigned int i = 0; i < 3; ++i) { m_position[i] = audioData.position[i]; } } else { diff --git a/src/mumble/AudioOutputSample.cpp b/src/mumble/AudioOutputSample.cpp index 50d15749784..4bcdf0914bf 100644 --- a/src/mumble/AudioOutputSample.cpp +++ b/src/mumble/AudioOutputSample.cpp @@ -150,7 +150,8 @@ AudioOutputSample::AudioOutputSample(SoundFile *psndfile, float volume, bool loo // If the frequencies don't match initialize the resampler if (sfHandle->samplerate() != static_cast< int >(freq)) { - srs = speex_resampler_init(bStereo ? 2 : 1, sfHandle->samplerate(), iOutSampleRate, 3, &err); + srs = speex_resampler_init(bStereo ? 2 : 1, static_cast< unsigned int >(sfHandle->samplerate()), iOutSampleRate, + 3, &err); if (err != RESAMPLER_ERR_SUCCESS) { qWarning() << "Initialize " << sfHandle->samplerate() << " to " << iOutSampleRate << " resampler failed!"; srs = nullptr; @@ -233,15 +234,17 @@ bool AudioOutputSample::prepareSampleBuffer(unsigned int frameCount) { // Check if we can satisfy request with current buffer // Maximum interaural delay is accounted for to prevent audio glitches - if (iBufferFilled >= sampleCount + INTERAURAL_DELAY) + if (static_cast< float >(iBufferFilled) >= static_cast< float >(sampleCount) + INTERAURAL_DELAY) return true; // Calculate the required buffersize to hold the results unsigned int iInputFrames = static_cast< unsigned int >( - ceilf(static_cast< float >(frameCount * sfHandle->samplerate()) / static_cast< float >(iOutSampleRate))); + ceilf(static_cast< float >(frameCount * static_cast< unsigned int >(sfHandle->samplerate())) + / static_cast< float >(iOutSampleRate))); unsigned int iInputSamples = iInputFrames * channels; - STACKVAR(float, fOut, iInputSamples); + static std::vector< float > fOut; + fOut.resize(iInputSamples); bool eof = false; sf_count_t read; @@ -249,13 +252,13 @@ bool AudioOutputSample::prepareSampleBuffer(unsigned int frameCount) { resizeBuffer(iBufferFilled + sampleCount + INTERAURAL_DELAY); // If we need to resample, write to the buffer on stack - float *pOut = (srs) ? fOut : pfBuffer + iBufferFilled; + float *pOut = (srs) ? fOut.data() : pfBuffer + iBufferFilled; // Try to read all samples needed to satisfy this request if ((read = sfHandle->read(pOut, iInputSamples)) < iInputSamples) { if (sfHandle->error() != SF_ERR_NO_ERROR || !bLoop) { // We reached the eof or encountered an error, stuff with zeroes - memset(pOut, 0, sizeof(float) * (iInputSamples - read)); + memset(pOut, 0, sizeof(float) * static_cast< std::size_t >(iInputSamples - read)); read = iInputSamples; eof = true; } else { diff --git a/src/mumble/AudioOutputSpeech.cpp b/src/mumble/AudioOutputSpeech.cpp index 50da1178a22..7a168e1f4f2 100644 --- a/src/mumble/AudioOutputSpeech.cpp +++ b/src/mumble/AudioOutputSpeech.cpp @@ -42,7 +42,7 @@ std::size_t AudioOutputSpeech::storeAudioOutputCache(const Mumble::Protocol::Aud // Write audio data to that free (currently unused) chunk it->loadFrom(audioData); - return std::distance(s_audioCaches.begin(), it); + return static_cast< std::size_t >(std::distance(s_audioCaches.begin(), it)); } else { // The list of audio chunks is full -> extend it AudioOutputCache chunk; @@ -81,7 +81,7 @@ AudioOutputSpeech::AudioOutputSpeech(ClientUser *user, unsigned int freq, Mumble // Always pretend Stereo mode is true by default. since opus will convert mono stream to stereo stream. // https://tools.ietf.org/html/rfc6716#section-2.1.2 bStereo = true; - opusState = opus_decoder_create(iSampleRate, bStereo ? 2 : 1, nullptr); + opusState = opus_decoder_create(static_cast< int >(iSampleRate), bStereo ? 2 : 1, nullptr); opus_decoder_ctl(opusState, OPUS_SET_PHASE_INVERSION_DISABLED(1)); // Disable phase inversion for better mono downmix. @@ -130,8 +130,8 @@ AudioOutputSpeech::AudioOutputSpeech(ClientUser *user, unsigned int freq, Mumble m_audioContext = Mumble::Protocol::AudioContext::INVALID; - jbJitter = jitter_buffer_init(iFrameSize); - int margin = Global::get().s.iJitterBufferSize * iFrameSize; + jbJitter = jitter_buffer_init(static_cast< int >(iFrameSize)); + int margin = Global::get().s.iJitterBufferSize * static_cast< int >(iFrameSize); jitter_buffer_ctl(jbJitter, JITTER_BUFFER_SET_MARGIN, &margin); // We are configuring our Jitter buffer to use a custom deleter function. This prevents the buffer from @@ -183,12 +183,13 @@ void AudioOutputSpeech::addFrameToBuffer(const Mumble::Protocol::AudioData &audi assert(m_codec == Mumble::Protocol::AudioCodec::Opus); assert(audioData.usedCodec == m_codec); - samples = opus_decoder_get_nb_samples(opusState, audioData.payload.data(), - audioData.payload.size()); // this function return samples per channel - samples *= 2; // since we assume all input stream is stereo. + samples = opus_decoder_get_nb_samples( + opusState, audioData.payload.data(), + static_cast< int >(audioData.payload.size())); // this function return samples per channel + samples *= 2; // since we assume all input stream is stereo. // We can't handle frames which are not a multiple of our configured framesize. - if (samples % iFrameSize != 0) { + if (static_cast< unsigned int >(samples) % iFrameSize != 0) { qWarning("AudioOutputSpeech: Dropping Opus audio packet, because its sample count (%d) is not a " "multiple of our frame size (%d)", samples, iFrameSize); @@ -210,8 +211,8 @@ void AudioOutputSpeech::addFrameToBuffer(const Mumble::Protocol::AudioData &audi JitterBufferPacket jbp; jbp.data = reinterpret_cast< char * >(storageIndex) + 1; jbp.len = 0; - jbp.span = samples; - jbp.timestamp = iFrameSize * audioData.frameNumber; + jbp.span = static_cast< unsigned int >(samples); + jbp.timestamp = static_cast< unsigned int >(iFrameSize * audioData.frameNumber); jitter_buffer_put(jbJitter, &jbp); } @@ -240,7 +241,7 @@ bool AudioOutputSpeech::prepareSampleBuffer(unsigned int frameCount) { bool nextalive = bLastAlive; while (iBufferFilled < sampleCount + INTERAURAL_DELAY) { - int decodedSamples = iFrameSize; + int decodedSamples = static_cast< int >(iFrameSize); resizeBuffer(iBufferFilled + iOutputSize + INTERAURAL_DELAY); // TODO: allocating memory in the audio callback will crash mumble in some cases. // we need to initialize the buffer with an appropriate size when initializing @@ -260,7 +261,7 @@ bool AudioOutputSpeech::prepareSampleBuffer(unsigned int frameCount) { jitter_buffer_ctl(jbJitter, JITTER_BUFFER_GET_AVAILABLE_COUNT, &avail); if (p && (ts == 0)) { - int want = iroundf(p->fAverageAvailable); + int want = static_cast< int >(p->fAverageAvailable); if (avail < want) { ++iMissCount; if (iMissCount < 20) { @@ -276,7 +277,7 @@ bool AudioOutputSpeech::prepareSampleBuffer(unsigned int frameCount) { JitterBufferPacket jbp; spx_int32_t startofs = 0; - if (jitter_buffer_get(jbJitter, &jbp, iFrameSize, &startofs) == JITTER_BUFFER_OK) { + if (jitter_buffer_get(jbJitter, &jbp, static_cast< int >(iFrameSize), &startofs) == JITTER_BUFFER_OK) { std::lock_guard< std::mutex > audioChunkLock(s_audioCachesMutex); iMissCount = 0; @@ -295,13 +296,13 @@ bool AudioOutputSpeech::prepareSampleBuffer(unsigned int frameCount) { // Copy audio data into qlFrames qlFrames << QByteArray(reinterpret_cast< const char * >(cache.getAudioData().data()), - cache.getAudioData().size()); + static_cast< int >(cache.getAudioData().size())); if (cache.containsPositionalInformation()) { assert(cache.getPositionalInformation().size() == 3); assert(fPos.size() == 3); - for (int i = 0; i < 3; ++i) { + for (unsigned int i = 0; i < 3; ++i) { fPos[i] = cache.getPositionalInformation()[i]; } } else { @@ -313,7 +314,7 @@ bool AudioOutputSpeech::prepareSampleBuffer(unsigned int frameCount) { if (p) { float a = static_cast< float >(avail); - if (avail >= p->fAverageAvailable) + if (static_cast< float >(avail) >= p->fAverageAvailable) p->fAverageAvailable = a; else p->fAverageAvailable *= 0.99f; @@ -345,7 +346,7 @@ bool AudioOutputSpeech::prepareSampleBuffer(unsigned int frameCount) { // packet normally in order to be able to play it. decodedSamples = opus_decode_float( opusState, qba.isEmpty() ? nullptr : reinterpret_cast< const unsigned char * >(qba.constData()), - qba.size(), pOut, iAudioBufferSize, 0); + qba.size(), pOut, static_cast< int >(iAudioBufferSize), 0); } else { // If the packet is non-empty, but the associated user is locally muted, // we don't have to decode the packet. Instead it is enough to know how many @@ -356,10 +357,10 @@ bool AudioOutputSpeech::prepareSampleBuffer(unsigned int frameCount) { // The returned sample count we get from the Opus functions refer to samples per channel. // Thus in order to get the total amount, we have to multiply by the channel count. - decodedSamples *= channels; + decodedSamples *= static_cast< int >(channels); if (decodedSamples < 0) { - decodedSamples = iFrameSize; + decodedSamples = static_cast< int >(iFrameSize); memset(pOut, 0, iFrameSize * sizeof(float)); } @@ -397,11 +398,11 @@ bool AudioOutputSpeech::prepareSampleBuffer(unsigned int frameCount) { } } else { assert(m_codec == Mumble::Protocol::AudioCodec::Opus); - decodedSamples = opus_decode_float(opusState, nullptr, 0, pOut, iFrameSize, 0); - decodedSamples *= channels; + decodedSamples = opus_decode_float(opusState, nullptr, 0, pOut, static_cast< int >(iFrameSize), 0); + decodedSamples *= static_cast< int >(channels); if (decodedSamples < 0) { - decodedSamples = iFrameSize; + decodedSamples = static_cast< int >(iFrameSize); memset(pOut, 0, iFrameSize * sizeof(float)); } } @@ -418,7 +419,7 @@ bool AudioOutputSpeech::prepareSampleBuffer(unsigned int frameCount) { } } - for (int i = decodedSamples / iFrameSize; i > 0; --i) { + for (unsigned int i = static_cast< unsigned int >(decodedSamples) / iFrameSize; i > 0; --i) { jitter_buffer_tick(jbJitter); } } @@ -428,12 +429,13 @@ bool AudioOutputSpeech::prepareSampleBuffer(unsigned int frameCount) { // NOTE: If Opus is used, then in this case no samples have actually been decoded and thus // we don't discard previously done work (in form of decoding the audio stream) by overwriting // it with zeros. - memset(pOut, 0, decodedSamples * sizeof(float)); + memset(pOut, 0, static_cast< unsigned int >(decodedSamples) * sizeof(float)); } - spx_uint32_t inlen = decodedSamples / channels; // per channel + spx_uint32_t inlen = static_cast< unsigned int >(decodedSamples) / channels; // per channel spx_uint32_t outlen = static_cast< unsigned int >( - ceilf(static_cast< float >(decodedSamples / channels * iMixerFreq) / static_cast< float >(iSampleRate))); + ceilf(static_cast< float >(static_cast< unsigned int >(decodedSamples) / channels * iMixerFreq) + / static_cast< float >(iSampleRate))); if (srs && bLastAlive) { if (channels == 1) { speex_resampler_process_float(srs, 0, fResamplerBuffer, &inlen, pfBuffer + iBufferFilled, &outlen); diff --git a/src/mumble/AudioStats.cpp b/src/mumble/AudioStats.cpp index a0d7be9b0e2..499b99655c4 100644 --- a/src/mumble/AudioStats.cpp +++ b/src/mumble/AudioStats.cpp @@ -55,12 +55,12 @@ void AudioBar::paintEvent(QPaintEvent *) { float scale = static_cast< float >(width()) / static_cast< float >(iMax - iMin); int h = height(); - int val = iroundf(static_cast< float >(iValue) * scale + 0.5f); - int below = iroundf(static_cast< float >(iBelow) * scale + 0.5f); - int above = iroundf(static_cast< float >(iAbove) * scale + 0.5f); - int max = iroundf(static_cast< float >(iMax) * scale + 0.5f); - int min = iroundf(static_cast< float >(iMin) * scale + 0.5f); - int peak = iroundf(static_cast< float >(iPeak) * scale + 0.5f); + int val = static_cast< int >(static_cast< float >(iValue) * scale + 0.5f); + int below = static_cast< int >(static_cast< float >(iBelow) * scale + 0.5f); + int above = static_cast< int >(static_cast< float >(iAbove) * scale + 0.5f); + int max = static_cast< int >(static_cast< float >(iMax) * scale + 0.5f); + int min = static_cast< int >(static_cast< float >(iMin) * scale + 0.5f); + int peak = static_cast< int >(static_cast< float >(iPeak) * scale + 0.5f); if (Global::get().s.bHighContrast) { // Draw monochrome representation @@ -153,22 +153,24 @@ void AudioEchoWidget::paintEvent(QPaintEvent *) { spx_int32_t sz; speex_echo_ctl(ai->sesEcho, SPEEX_ECHO_GET_IMPULSE_RESPONSE_SIZE, &sz); - STACKVAR(spx_int32_t, w, sz); - STACKVAR(float, W, sz); + static std::vector< spx_int32_t > w; + w.resize(static_cast< std::size_t >(sz)); + static std::vector< float > W; + W.resize(static_cast< std::size_t >(sz)); - speex_echo_ctl(ai->sesEcho, SPEEX_ECHO_GET_IMPULSE_RESPONSE, w); + speex_echo_ctl(ai->sesEcho, SPEEX_ECHO_GET_IMPULSE_RESPONSE, w.data()); ai->qmSpeex.unlock(); - int N = 160; - int n = 2 * N; - int M = sz / n; + constexpr unsigned int N = 160; + constexpr unsigned int n = 2 * N; + const unsigned int M = static_cast< unsigned int >(sz) / n; drft_lookup d; mumble_drft_init(&d, n); - for (int j = 0; j < M; j++) { - for (int i = 0; i < n; i++) + for (unsigned int j = 0; j < M; j++) { + for (unsigned int i = 0; i < n; i++) W[j * n + i] = static_cast< float >(w[j * n + i]) / static_cast< float >(n); mumble_drft_forward(&d, &W[j * n]); } @@ -178,8 +180,8 @@ void AudioEchoWidget::paintEvent(QPaintEvent *) { float xscale = 1.0f / static_cast< float >(N); float yscale = 1.0f / static_cast< float >(M); - for (int j = 0; j < M; j++) { - for (int i = 1; i < N; i++) { + for (unsigned int j = 0; j < M; j++) { + for (unsigned int i = 1; i < N; i++) { float xa = static_cast< float >(i) * xscale; float ya = static_cast< float >(j) * yscale; @@ -195,7 +197,7 @@ void AudioEchoWidget::paintEvent(QPaintEvent *) { QPolygonF poly; xscale = 1.0f / (2.0f * static_cast< float >(n)); yscale = 1.0f / (200.0f * 32767.0f); - for (int i = 0; i < 2 * n; i++) { + for (unsigned int i = 0; i < 2 * n; i++) { poly << QPointF(static_cast< float >(i) * xscale, 0.5f + static_cast< float >(w[i]) * yscale); } @@ -224,11 +226,13 @@ void AudioNoiseWidget::paintEvent(QPaintEvent *) { spx_int32_t ps_size = 0; speex_preprocess_ctl(ai->sppPreprocess, SPEEX_PREPROCESS_GET_PSD_SIZE, &ps_size); - STACKVAR(spx_int32_t, noise, ps_size); - STACKVAR(spx_int32_t, ps, ps_size); + static std::vector< spx_int32_t > noise; + noise.resize(static_cast< std::size_t >(ps_size)); + static std::vector< spx_int32_t > ps; + ps.resize(static_cast< std::size_t >(ps_size)); - speex_preprocess_ctl(ai->sppPreprocess, SPEEX_PREPROCESS_GET_PSD, ps); - speex_preprocess_ctl(ai->sppPreprocess, SPEEX_PREPROCESS_GET_NOISE_PSD, noise); + speex_preprocess_ctl(ai->sppPreprocess, SPEEX_PREPROCESS_GET_PSD, ps.data()); + speex_preprocess_ctl(ai->sppPreprocess, SPEEX_PREPROCESS_GET_NOISE_PSD, noise.data()); ai->qmSpeex.unlock(); @@ -239,7 +243,7 @@ void AudioNoiseWidget::paintEvent(QPaintEvent *) { poly << QPointF(0.0f, height() - 1); float fftmul = 1.0 / (32768.0); - for (int i = 0; i < ps_size; i++) { + for (unsigned int i = 0; i < static_cast< unsigned int >(ps_size); i++) { qreal xp, yp; xp = i * sx; yp = sqrtf(sqrtf(static_cast< float >(noise[i]))) - 1.0f; @@ -258,7 +262,7 @@ void AudioNoiseWidget::paintEvent(QPaintEvent *) { poly.clear(); - for (int i = 0; i < ps_size; i++) { + for (unsigned int i = 0; i < static_cast< unsigned int >(ps_size); i++) { qreal xp, yp; xp = i * sx; yp = sqrtf(sqrtf(static_cast< float >(ps[i]))) - 1.0f; @@ -335,19 +339,21 @@ void AudioStats::on_Tick_timeout() { spx_int32_t ps_size = 0; speex_preprocess_ctl(ai->sppPreprocess, SPEEX_PREPROCESS_GET_PSD_SIZE, &ps_size); - STACKVAR(spx_int32_t, noise, ps_size); - STACKVAR(spx_int32_t, ps, ps_size); + static std::vector< spx_int32_t > noise; + noise.resize(static_cast< std::size_t >(ps_size)); + static std::vector< spx_int32_t > ps; + ps.resize(static_cast< std::size_t >(ps_size)); - speex_preprocess_ctl(ai->sppPreprocess, SPEEX_PREPROCESS_GET_PSD, ps); - speex_preprocess_ctl(ai->sppPreprocess, SPEEX_PREPROCESS_GET_NOISE_PSD, noise); + speex_preprocess_ctl(ai->sppPreprocess, SPEEX_PREPROCESS_GET_PSD, ps.data()); + speex_preprocess_ctl(ai->sppPreprocess, SPEEX_PREPROCESS_GET_NOISE_PSD, noise.data()); float s = 0.0f; float n = 0.0001f; - int start = (ps_size * 300) / SAMPLE_RATE; - int stop = (ps_size * 2000) / SAMPLE_RATE; + unsigned int start = static_cast< unsigned int >(ps_size * 300) / SAMPLE_RATE; + unsigned int stop = static_cast< unsigned int >(ps_size * 2000) / SAMPLE_RATE; - for (int i = start; i < stop; i++) { + for (unsigned int i = start; i < stop; i++) { s += sqrtf(static_cast< float >(ps[i])); n += sqrtf(static_cast< float >(noise[i])); } @@ -380,13 +386,13 @@ void AudioStats::on_Tick_timeout() { FORMAT_TO_TXT("%04llu ms", Global::get().uiDoublePush / 1000); qlDoublePush->setText(txt); - abSpeech->iBelow = iroundf(Global::get().s.fVADmin * 32767.0f + 0.5f); - abSpeech->iAbove = iroundf(Global::get().s.fVADmax * 32767.0f + 0.5f); + abSpeech->iBelow = static_cast< int >(Global::get().s.fVADmin * 32767.0f + 0.5f); + abSpeech->iAbove = static_cast< int >(Global::get().s.fVADmax * 32767.0f + 0.5f); if (Global::get().s.vsVAD == Settings::Amplitude) { - abSpeech->iValue = iroundf((32767.f / 96.0f) * (96.0f + ai->dPeakCleanMic) + 0.5f); + abSpeech->iValue = static_cast< int >((32767.f / 96.0f) * (96.0f + ai->dPeakCleanMic) + 0.5f); } else { - abSpeech->iValue = iroundf(ai->fSpeechProb * 32767.0f + 0.5f); + abSpeech->iValue = static_cast< int >(ai->fSpeechProb * 32767.0f + 0.5f); } abSpeech->update(); diff --git a/src/mumble/AudioWizard.cpp b/src/mumble/AudioWizard.cpp index 4f4ba080252..57befa31355 100644 --- a/src/mumble/AudioWizard.cpp +++ b/src/mumble/AudioWizard.cpp @@ -144,7 +144,7 @@ AudioWizard::AudioWizard(QWidget *p) : QWizard(p) { abVAD->qcInside = Qt::yellow; abVAD->qcAbove = Qt::green; - qsVAD->setValue(iroundf(Global::get().s.fVADmax * 32767.f + 0.5f)); + qsVAD->setValue(static_cast< int >(Global::get().s.fVADmax * 32767.f + 0.5f)); // Positional qcbHeadphone->setChecked(Global::get().s.bPositionalHeadphone); @@ -423,7 +423,7 @@ void AudioWizard::accept() { Settings::MessageLog mlReplace = qrbNotificationTTS->isChecked() ? Settings::LogSoundfile : Settings::LogTTS; for (int i = Log::firstMsgType; i <= Log::lastMsgType; ++i) { - if (Global::get().s.qmMessages[i] & mlReplace) + if (Global::get().s.qmMessages[i] & static_cast< unsigned int >(mlReplace)) Global::get().s.qmMessages[i] ^= Settings::LogSoundfile | Settings::LogTTS; } @@ -468,13 +468,13 @@ void AudioWizard::on_Ticker_timeout() { abAmplify->iPeak = iMaxPeak; abAmplify->update(); - abVAD->iBelow = iroundf(Global::get().s.fVADmin * 32767.0f + 0.5f); - abVAD->iAbove = iroundf(Global::get().s.fVADmax * 32767.0f + 0.5f); + abVAD->iBelow = static_cast< int >(Global::get().s.fVADmin * 32767.0f + 0.5f); + abVAD->iAbove = static_cast< int >(Global::get().s.fVADmax * 32767.0f + 0.5f); if (Global::get().s.vsVAD == Settings::Amplitude) { - abVAD->iValue = iroundf((32767.f / 96.0f) * (96.0f + ai->dPeakCleanMic) + 0.5f); + abVAD->iValue = static_cast< int >((32767.f / 96.0f) * (96.0f + ai->dPeakCleanMic) + 0.5f); } else { - abVAD->iValue = iroundf(ai->fSpeechProb * 32767.0f + 0.5f); + abVAD->iValue = static_cast< int >(ai->fSpeechProb * 32767.0f + 0.5f); } abVAD->update(); @@ -513,7 +513,7 @@ void AudioWizard::on_Ticker_timeout() { // qgsScene->addLine(QLineF(0,-1,0,1), pen); // qgsScene->addLine(QLineF(-1,0,1,0), pen); - const float speakerScale = 0.9; + const float speakerScale = 0.9f; const float speakerRadius = baseRadius * speakerScale; // nspeaker is in format [x1,y1,z1, x2,y2,z2, ...] @@ -540,7 +540,7 @@ void AudioWizard::on_Ticker_timeout() { } } - const float sourceScale = 0.9; + const float sourceScale = 0.9f; const float sourceRadius = baseRadius * sourceScale; qgiSource = qgsScene->addEllipse(QRectF(-sourceRadius, -sourceRadius, 2 * sourceRadius, 2 * sourceRadius), diff --git a/src/mumble/BanEditor.cpp b/src/mumble/BanEditor.cpp index baa1c833ed9..05a6a9641e1 100644 --- a/src/mumble/BanEditor.cpp +++ b/src/mumble/BanEditor.cpp @@ -11,6 +11,8 @@ #include "ServerHandler.h" #include "Global.h" +#include + BanEditor::BanEditor(const MumbleProto::BanList &msg, QWidget *p) : QDialog(p), maskDefaultValue(32) { setupUi(this); @@ -31,7 +33,7 @@ BanEditor::BanEditor(const MumbleProto::BanList &msg, QWidget *p) : QDialog(p), const MumbleProto::BanList_BanEntry &be = msg.bans(i); Ban b; b.haAddress = be.address(); - b.iMask = be.mask(); + b.iMask = static_cast< int >(be.mask()); b.qsUsername = u8(be.name()); b.qsHash = u8(be.hash()); b.qsReason = u8(be.reason()); @@ -53,7 +55,8 @@ void BanEditor::accept() { foreach (const Ban &b, qlBans) { MumbleProto::BanList_BanEntry *be = msg.add_bans(); be->set_address(b.haAddress.toStdString()); - be->set_mask(b.iMask); + assert(b.iMask >= 0); + be->set_mask(static_cast< unsigned int >(b.iMask)); be->set_name(u8(b.qsUsername)); be->set_hash(u8(b.qsHash)); be->set_reason(u8(b.qsReason)); diff --git a/src/mumble/CMakeLists.txt b/src/mumble/CMakeLists.txt index 195b3e125a8..8d72d88e0ba 100644 --- a/src/mumble/CMakeLists.txt +++ b/src/mumble/CMakeLists.txt @@ -317,12 +317,14 @@ set(MUMBLE_SOURCES "${SHARED_SOURCE_DIR}/User.cpp" "${SHARED_SOURCE_DIR}/User.h" - "${3RDPARTY_DIR}/smallft/smallft.cpp" - "mumble.qrc" "${CMAKE_SOURCE_DIR}/themes/DefaultTheme.qrc" ) +add_library(smallft STATIC "${3RDPARTY_DIR}/smallft/smallft.cpp") +target_include_directories(smallft PUBLIC "${3RDPARTY_DIR}/smallft") +target_disable_warnings(smallft) + add_custom_command( OUTPUT "${CMAKE_BINARY_DIR}/mumble_flags.qrc" COMMAND ${PYTHON_INTERPRETER} @@ -332,6 +334,7 @@ add_custom_command( list(APPEND MUMBLE_SOURCES "${CMAKE_BINARY_DIR}/mumble_flags.qrc") add_library(mumble_client_object_lib OBJECT ${MUMBLE_SOURCES}) +target_link_libraries(mumble_client_object_lib PUBLIC smallft) if(WIN32 AND NOT CMAKE_BUILD_TYPE STREQUAL "Debug") # We don't want the console to appear in release builds. @@ -416,7 +419,6 @@ target_include_directories(mumble_client_object_lib ${CMAKE_CURRENT_SOURCE_DIR} # This is required for includes in current folder to be found by files from the shared directory. "widgets" ${SHARED_SOURCE_DIR} - "${3RDPARTY_DIR}/smallft" "${PLUGINS_DIR}" ) diff --git a/src/mumble/ClientUser.cpp b/src/mumble/ClientUser.cpp index 3966adab78e..de107921b2c 100644 --- a/src/mumble/ClientUser.cpp +++ b/src/mumble/ClientUser.cpp @@ -316,7 +316,7 @@ bool ClientUser::isActive() { if (!tLastTalkStateChange.isStarted()) return false; - return tLastTalkStateChange.elapsed() < Global::get().s.os.uiActiveTime * 1000000U; + return tLastTalkStateChange.elapsed() < static_cast< unsigned int >(Global::get().s.os.uiActiveTime) * 1000000U; } /* From Channel.h diff --git a/src/mumble/ConnectDialog.cpp b/src/mumble/ConnectDialog.cpp index bb89f8b5003..8da030018b2 100644 --- a/src/mumble/ConnectDialog.cpp +++ b/src/mumble/ConnectDialog.cpp @@ -1467,7 +1467,8 @@ void ConnectDialog::fillList() { while (!ql.isEmpty()) { #if QT_VERSION >= QT_VERSION_CHECK(5, 10, 0) - ServerItem *si = static_cast< ServerItem * >(ql.takeAt(QRandomGenerator::global()->generate() % ql.count())); + ServerItem *si = static_cast< ServerItem * >( + ql.takeAt(static_cast< int >(QRandomGenerator::global()->generate()) % ql.count())); #else // Qt 5.10 introduces the QRandomGenerator class and in Qt 5.15 qrand got deprecated in its favor ServerItem *si = static_cast< ServerItem * >(ql.takeAt(qrand() % ql.count())); @@ -1790,11 +1791,11 @@ bool ConnectDialog::writePing(const QHostAddress &host, unsigned short port, Ver gsl::span< const Mumble::Protocol::byte > encodedPacket = m_udpPingEncoder.encodePingPacket(pingData); if (bIPv4 && host.protocol() == QAbstractSocket::IPv4Protocol) { - qusSocket4->writeDatagram(reinterpret_cast< const char * >(encodedPacket.data()), encodedPacket.size(), host, - port); + qusSocket4->writeDatagram(reinterpret_cast< const char * >(encodedPacket.data()), + static_cast< qint64 >(encodedPacket.size()), host, port); } else if (bIPv6 && host.protocol() == QAbstractSocket::IPv6Protocol) { - qusSocket6->writeDatagram(reinterpret_cast< const char * >(encodedPacket.data()), encodedPacket.size(), host, - port); + qusSocket6->writeDatagram(reinterpret_cast< const char * >(encodedPacket.data()), + static_cast< qint64 >(encodedPacket.size()), host, port); } else { return false; } @@ -1811,7 +1812,8 @@ void ConnectDialog::udpReply() { gsl::span< Mumble::Protocol::byte > buffer = m_udpDecoder.getBuffer(); - std::size_t len = sock->readDatagram(reinterpret_cast< char * >(buffer.data()), buffer.size(), &host, &port); + std::size_t len = static_cast< std::size_t >(sock->readDatagram( + reinterpret_cast< char * >(buffer.data()), static_cast< int >(buffer.size()), &host, &port)); // Pings are special in that they can be decoded in the new or the old format, if the protocol version is set to // the old format (which UNKNOWN does). Thus by setting the version to UNKNOWN, we effectively enable to decode diff --git a/src/mumble/CoreAudio.mm b/src/mumble/CoreAudio.mm index b935e35f07b..733b1c00933 100644 --- a/src/mumble/CoreAudio.mm +++ b/src/mumble/CoreAudio.mm @@ -72,7 +72,7 @@ QString GetDeviceStringProperty(AudioObjectID device_id, AudioObjectPropertySele device_id, &property_address, 0, nullptr, &size, &property_value); if (result != noErr) { - throw CoreAudioException(QString("Unable to get string property %1 of %2.").arg(property_selector, device_id)); + throw CoreAudioException(QString("Unable to get string property %1 of %2.").arg(property_selector).arg(static_cast(device_id))); } char buf[4096]; @@ -89,7 +89,7 @@ UInt32 GetDeviceUint32Property(AudioObjectID device_id, AudioObjectPropertySelec UInt32 size = sizeof(property_value); OSStatus result = AudioObjectGetPropertyData(device_id, &property_address, 0, nullptr, &size, &property_value); if (result != noErr) { - throw CoreAudioException(QString("Unable to get uint32 property %1 of %2.").arg(property_selector, device_id)); + throw CoreAudioException(QString("Unable to get uint32 property %1 of %2.").arg(property_selector).arg(static_cast(device_id))); } return property_value; @@ -103,7 +103,7 @@ UInt32 GetDevicePropertySize(AudioObjectID device_id, AudioObjectPropertySelecto UInt32 size = 0; OSStatus result = AudioObjectGetPropertyDataSize(device_id, &property_address, 0, nullptr, &size); if (result != noErr) { - throw CoreAudioException(QString("Unable to get property size of %1 of %2.").arg(property_selector, device_id)); + throw CoreAudioException(QString("Unable to get property size of %1 of %2.").arg(property_selector).arg(static_cast(device_id))); } return size; } @@ -710,7 +710,7 @@ static void LogAUStreamDescription(AudioUnit au) { qWarning("CoreAudioInput: BufferFrameSizeRange = (%.2f, %.2f)", range.mMinimum, range.mMaximum); - actualBufferLength = iMicLength; + actualBufferLength = static_cast(iMicLength); val = iMicLength; propertyAddress.mSelector = kAudioDevicePropertyBufferFrameSize; err = AudioObjectSetPropertyData(inputDevId, &propertyAddress, 0, nullptr, sizeof(UInt32), &val); @@ -836,7 +836,7 @@ static void LogAUStreamDescription(AudioUnit au) { buflist.mNumberBuffers = 1; AudioBuffer *b = buflist.mBuffers; b->mNumberChannels = iMicChannels; - b->mDataByteSize = iMicSampleSize * actualBufferLength; + b->mDataByteSize = iMicSampleSize * static_cast(actualBufferLength); b->mData = calloc(1, b->mDataByteSize); // Start! @@ -1003,7 +1003,7 @@ static void LogAUStreamDescription(AudioUnit au) { #endif iMixerFreq = static_cast< unsigned int >(fmt.mSampleRate); - iChannels = static_cast< int >(fmt.mChannelsPerFrame); + iChannels = static_cast< unsigned int >(fmt.mChannelsPerFrame); if (fmt.mFormatFlags & kAudioFormatFlagIsFloat) { eSampleFormat = SampleFloat; @@ -1064,7 +1064,7 @@ static void LogAUStreamDescription(AudioUnit au) { if (err != noErr) { qWarning("CoreAudioOutput: Unable to query for allowed buffer size ranges."); } else { - setBufferSize(range.mMaximum); + setBufferSize(static_cast(range.mMaximum)); qWarning("CoreAudioOutput: BufferFrameSizeRange = (%.2f, %.2f)", range.mMinimum, range.mMaximum); } diff --git a/src/mumble/CustomElements.cpp b/src/mumble/CustomElements.cpp index f92d53153d0..8b4df6bf293 100644 --- a/src/mumble/CustomElements.cpp +++ b/src/mumble/CustomElements.cpp @@ -88,7 +88,7 @@ void ChatbarTextEdit::contextMenuEvent(QContextMenuEvent *qcme) { QMenu *menu = createStandardContextMenu(); QAction *action = new QAction(tr("Paste and &Send") + QLatin1Char('\t'), menu); - action->setShortcut(Qt::CTRL + Qt::Key_Shift + Qt::Key_V); + action->setShortcut(static_cast< int >(Qt::CTRL) | Qt::Key_Shift | Qt::Key_V); action->setEnabled(!QApplication::clipboard()->text().isEmpty()); connect(action, SIGNAL(triggered()), this, SLOT(pasteAndSend_triggered())); if (menu->actions().count() > 6) @@ -138,7 +138,7 @@ QSize ChatbarTextEdit::minimumSizeHint() const { QSize ChatbarTextEdit::sizeHint() const { QSize sh = QTextEdit::sizeHint(); const int minHeight = minimumSizeHint().height(); - const int documentHeight = document()->documentLayout()->documentSize().height(); + const int documentHeight = static_cast< int >(document()->documentLayout()->documentSize().height()); sh.setHeight(std::max(minHeight, documentHeight)); const_cast< ChatbarTextEdit * >(this)->setMaximumHeight(sh.height()); return sh; @@ -218,7 +218,7 @@ bool ChatbarTextEdit::sendImagesFromMimeData(const QMimeData *source) { } bool ChatbarTextEdit::emitPastedImage(QImage image) { - QString processedImage = Log::imageToImg(image, Global::get().uiImageLength); + QString processedImage = Log::imageToImg(image, static_cast< int >(Global::get().uiImageLength)); if (processedImage.length() > 0) { QString imgHtml = QLatin1String("
") + processedImage; emit pastedImage(imgHtml); @@ -413,8 +413,9 @@ bool DockTitleBar::eventFilter(QObject *, QEvent *evt) { case QEvent::MouseButtonRelease: { newsize = 0; QPoint p = qdw->mapFromGlobal(QCursor::pos()); - if ((p.x() >= iroundf(static_cast< float >(qdw->width()) * 0.1f + 0.5f)) - && (p.x() < iroundf(static_cast< float >(qdw->width()) * 0.9f + 0.5f)) && (p.y() >= 0) && (p.y() < 15)) + if ((p.x() >= static_cast< int >(static_cast< float >(qdw->width()) * 0.1f + 0.5f)) + && (p.x() < static_cast< int >(static_cast< float >(qdw->width()) * 0.9f + 0.5f)) && (p.y() >= 0) + && (p.y() < 15)) newsize = 15; if (newsize > 0 && !qtTick->isActive()) qtTick->start(500); diff --git a/src/mumble/Database.cpp b/src/mumble/Database.cpp index 43881c45b93..0768182b26d 100644 --- a/src/mumble/Database.cpp +++ b/src/mumble/Database.cpp @@ -399,7 +399,7 @@ void Database::setLocalMuted(const QString &hash, bool muted) { execQueryAndLogFailure(query); } -ChannelFilterMode Database::getChannelFilterMode(const QByteArray &server_cert_digest, const int channel_id) { +ChannelFilterMode Database::getChannelFilterMode(const QByteArray &server_cert_digest, const unsigned int channel_id) { QSqlQuery query(db); query.prepare(QLatin1String( @@ -415,7 +415,7 @@ ChannelFilterMode Database::getChannelFilterMode(const QByteArray &server_cert_d return ChannelFilterMode::NORMAL; } -void Database::setChannelFilterMode(const QByteArray &server_cert_digest, const int channel_id, +void Database::setChannelFilterMode(const QByteArray &server_cert_digest, const unsigned int channel_id, const ChannelFilterMode filterMode) { QSqlQuery query(db); diff --git a/src/mumble/Database.h b/src/mumble/Database.h index 421c8d01b64..c5643deeb3f 100644 --- a/src/mumble/Database.h +++ b/src/mumble/Database.h @@ -55,8 +55,9 @@ class Database : public QObject { QString getUserLocalNickname(const QString &hash); void setUserLocalNickname(const QString &hash, const QString &nickname); - ChannelFilterMode getChannelFilterMode(const QByteArray &server_cert_digest, int channel_id); - void setChannelFilterMode(const QByteArray &server_cert_digest, int channel_id, ChannelFilterMode filterMode); + ChannelFilterMode getChannelFilterMode(const QByteArray &server_cert_digest, unsigned int channel_id); + void setChannelFilterMode(const QByteArray &server_cert_digest, unsigned int channel_id, + ChannelFilterMode filterMode); QMap< UnresolvedServerAddress, unsigned int > getPingCache(); void setPingCache(const QMap< UnresolvedServerAddress, unsigned int > &cache); diff --git a/src/mumble/DeveloperConsole.h b/src/mumble/DeveloperConsole.h index 90a53201d23..135a6b5ce50 100644 --- a/src/mumble/DeveloperConsole.h +++ b/src/mumble/DeveloperConsole.h @@ -14,7 +14,7 @@ class DeveloperConsole : public QObject { private: Q_OBJECT - Q_DISABLE_COPY(DeveloperConsole); + Q_DISABLE_COPY(DeveloperConsole) protected: QPointer< QMainWindow > m_window; diff --git a/src/mumble/EnumStringConversions.cpp b/src/mumble/EnumStringConversions.cpp index 48ffdcb62ba..48e3b8b1fec 100644 --- a/src/mumble/EnumStringConversions.cpp +++ b/src/mumble/EnumStringConversions.cpp @@ -247,7 +247,7 @@ namespace details { PROCESS_ALL_ENUMS -}; +} #undef PROCESS #undef AFTER_CODE diff --git a/src/mumble/EnumStringConversions.h b/src/mumble/EnumStringConversions.h index 9508ebf482b..75e4926fb27 100644 --- a/src/mumble/EnumStringConversions.h +++ b/src/mumble/EnumStringConversions.h @@ -62,7 +62,7 @@ void stringToEnum(const std::string &str, OverlaySettings::OverlayShow &e); void stringToEnum(const std::string &str, OverlaySettings::OverlaySort &e); void stringToEnum(const std::string &str, OverlaySettings::OverlayExclusionMode &e); -}; // namespace details +} // namespace details template< typename T > T stringToEnum(const std::string &str) { static_assert(std::is_enum< T >::value, "Only enums can be converted to strings with this function"); diff --git a/src/mumble/Global.cpp b/src/mumble/Global.cpp index 5193320d7ea..06cab015838 100644 --- a/src/mumble/Global.cpp +++ b/src/mumble/Global.cpp @@ -138,11 +138,6 @@ Global::Global(const QString &qsConfigPath) { channelListenerManager = std::make_unique< ChannelListenerManager >(); -#if defined(Q_OS_WIN) - QString appdata; - wchar_t appData[MAX_PATH]; -#endif - if (qsConfigPath.isEmpty()) { qdBasePath.setPath(QStandardPaths::writableLocation(QStandardPaths::AppDataLocation)); diff --git a/src/mumble/Global.h b/src/mumble/Global.h index 4fb6a85c88b..c129d26e214 100644 --- a/src/mumble/Global.h +++ b/src/mumble/Global.h @@ -74,11 +74,11 @@ struct Global Q_DECL_FINAL { Timer tDoublePush; quint64 uiDoublePush; /// Holds the current VoiceTarget ID to send audio to - int iTarget; + std::int32_t iTarget; /// Holds the value of iTarget before its last change until the current /// audio-stream ends (and it has a value > 0). See the comment in /// AudioInput::flushCheck for further details on this. - int iPrevTarget; + std::int32_t iPrevTarget; bool bPushToMute; bool bCenterPosition; bool bPosTest; diff --git a/src/mumble/GlobalShortcut.cpp b/src/mumble/GlobalShortcut.cpp index 3a70a0bb942..7acf806648c 100644 --- a/src/mumble/GlobalShortcut.cpp +++ b/src/mumble/GlobalShortcut.cpp @@ -74,7 +74,7 @@ ShortcutActionWidget::ShortcutActionWidget(QWidget *p) : MUComboBox(p) { model()->sort(0); } -void ShortcutActionWidget::setIndex(int idx) { +void ShortcutActionWidget::setIndex(unsigned int idx) { setCurrentIndex(findData(idx)); } @@ -128,14 +128,14 @@ void ChannelSelectWidget::setCurrentChannel(const ChannelTarget &target) { } ChannelTarget ChannelSelectWidget::currentChannel() const { - return itemData(currentIndex()).toInt(); + return itemData(currentIndex()).toUInt(); } void iterateChannelChildren(QTreeWidgetItem *root, Channel *chan, QMap< int, QTreeWidgetItem * > &map) { foreach (Channel *c, chan->qlChannels) { QTreeWidgetItem *sub = new QTreeWidgetItem(root, QStringList(c->qsName)); sub->setData(0, Qt::UserRole, c->iId); - map.insert(c->iId, sub); + map.insert(static_cast< int >(c->iId), sub); iterateChannelChildren(sub, c, map); } } @@ -254,7 +254,7 @@ ShortcutTargetDialog::ShortcutTargetDialog(const ShortcutTarget &st, QWidget *pw QTreeWidgetItem *qtwi; if (Global::get().uiSession) { - qtwi = qmTree.value(ClientUser::get(Global::get().uiSession)->cChannel->iId); + qtwi = qmTree.value(static_cast< int >(ClientUser::get(Global::get().uiSession)->cChannel->iId)); if (qtwi) qtwChannels->scrollToItem(qtwi); } @@ -408,7 +408,7 @@ QString ShortcutTargetWidget::targetString(const ShortcutTarget &st) { return tr("Subchannel #%1").arg(SHORTCUT_TARGET_CURRENT - st.iChannel); } } else { - Channel *c = Channel::get(st.iChannel); + Channel *c = Channel::get(static_cast< unsigned int >(st.iChannel)); if (c) return c->qsName; else @@ -457,9 +457,9 @@ ShortcutDelegate::ShortcutDelegate(QObject *p) : QStyledItemDelegate(p) { factory->registerEditor(QVariant::List, new QStandardItemEditorCreator< GlobalShortcutButtons >()); factory->registerEditor(QVariant::UInt, new QStandardItemEditorCreator< ShortcutActionWidget >()); factory->registerEditor(QVariant::Int, new QStandardItemEditorCreator< ShortcutToggleWidget >()); - factory->registerEditor(static_cast< QVariant::Type >(QVariant::fromValue(ShortcutTarget()).userType()), + factory->registerEditor(static_cast< int >(QVariant::fromValue(ShortcutTarget()).userType()), new QStandardItemEditorCreator< ShortcutTargetWidget >()); - factory->registerEditor(static_cast< QVariant::Type >(QVariant::fromValue(ChannelTarget()).userType()), + factory->registerEditor(static_cast< int >(QVariant::fromValue(ChannelTarget()).userType()), new QStandardItemEditorCreator< ChannelSelectWidget >()); factory->registerEditor(QVariant::String, new QStandardItemEditorCreator< QLineEdit >()); factory->registerEditor(QVariant::Invalid, new QStandardItemEditorCreator< QWidget >()); diff --git a/src/mumble/GlobalShortcut.h b/src/mumble/GlobalShortcut.h index c372f3f2c3e..64b9dbfc32c 100644 --- a/src/mumble/GlobalShortcut.h +++ b/src/mumble/GlobalShortcut.h @@ -59,7 +59,7 @@ class ShortcutActionWidget : public MUComboBox { public: ShortcutActionWidget(QWidget *p = nullptr); unsigned int index() const; - void setIndex(int); + void setIndex(unsigned int); }; class ShortcutToggleWidget : public MUComboBox { diff --git a/src/mumble/GlobalShortcutButtons.cpp b/src/mumble/GlobalShortcutButtons.cpp index 6d6df0c5c57..7debe51a114 100644 --- a/src/mumble/GlobalShortcutButtons.cpp +++ b/src/mumble/GlobalShortcutButtons.cpp @@ -31,11 +31,11 @@ QList< QVariant > GlobalShortcutButtons::buttons() { QList< QVariant > buttons; - const auto rootItem = m_ui->buttonTree->invisibleRootItem(); - for (auto i = 0; i < rootItem->childCount(); ++i) { - const auto buttonItem = rootItem->child(i); - for (auto i = 0; i < buttonItem->childCount(); ++i) { - buttons.append(buttonItem->child(i)->data(0, Qt::UserRole)); + const QTreeWidgetItem *rootItem = m_ui->buttonTree->invisibleRootItem(); + for (int i = 0; i < rootItem->childCount(); ++i) { + const QTreeWidgetItem *buttonItem = rootItem->child(i); + for (int k = 0; k < buttonItem->childCount(); ++k) { + buttons.append(buttonItem->child(k)->data(0, Qt::UserRole)); } } diff --git a/src/mumble/GlobalShortcut_macx.mm b/src/mumble/GlobalShortcut_macx.mm index c95bed50a2e..ea5c95494dd 100644 --- a/src/mumble/GlobalShortcut_macx.mm +++ b/src/mumble/GlobalShortcut_macx.mm @@ -54,8 +54,8 @@ if (Global::get().ocIntercept) { int64_t dx = CGEventGetIntegerValueField(event, kCGMouseEventDeltaX); int64_t dy = CGEventGetIntegerValueField(event, kCGMouseEventDeltaY); - Global::get().ocIntercept->iMouseX = qBound(0, Global::get().ocIntercept->iMouseX + static_cast(dx), Global::get().ocIntercept->uiWidth - 1); - Global::get().ocIntercept->iMouseY = qBound(0, Global::get().ocIntercept->iMouseY + static_cast(dy), Global::get().ocIntercept->uiHeight - 1); + Global::get().ocIntercept->iMouseX = qBound(0, Global::get().ocIntercept->iMouseX + static_cast(dx), Global::get().ocIntercept->iWidth - 1); + Global::get().ocIntercept->iMouseY = qBound(0, Global::get().ocIntercept->iMouseY + static_cast(dy), Global::get().ocIntercept->iHeight - 1); QMetaObject::invokeMethod(Global::get().ocIntercept, "updateMouse", Qt::QueuedConnection); forward = true; } @@ -292,7 +292,7 @@ if (sel) { NSPoint p; p.x = (CGFloat) Global::get().ocIntercept->iMouseX; - p.y = (CGFloat) (Global::get().ocIntercept->uiHeight - Global::get().ocIntercept->iMouseY); + p.y = (CGFloat) (Global::get().ocIntercept->iHeight - Global::get().ocIntercept->iMouseY); NSEvent *mouseEvent = [NSEvent mouseEventWithType:[event type] location:p modifierFlags:[event modifierFlags] timestamp:[event timestamp] windowNumber:0 context:nil eventNumber:[event eventNumber] clickCount:[event clickCount] pressure:[event pressure]]; @@ -392,7 +392,8 @@ QString GlobalShortcutMac::translateKeyName(const unsigned int keycode) const { UInt32 junk = 0; UniCharCount len = 64; - UniChar unicodeString[len]; + std::vector unicodeString; + unicodeString.resize(static_cast(len)); if (! kbdLayout) return QString(); @@ -400,7 +401,7 @@ OSStatus err = UCKeyTranslate(kbdLayout, static_cast(keycode), kUCKeyActionDisplay, 0, LMGetKbdType(), kUCKeyTranslateNoDeadKeysBit, &junk, - len, &len, unicodeString); + len, &len, unicodeString.data()); if (err != noErr) return QString(); @@ -412,7 +413,7 @@ return QLatin1String("Enter"); case '\b': return QLatin1String("Backspace"); - case '\e': + case 27: return QLatin1String("Escape"); case ' ': return QLatin1String("Space"); @@ -432,7 +433,7 @@ } } - return QString(reinterpret_cast(unicodeString), len).toUpper(); + return QString(reinterpret_cast(unicodeString.data()), static_cast(len)).toUpper(); } GlobalShortcutMac::ButtonInfo GlobalShortcutMac::buttonInfo(const QVariant &v) { diff --git a/src/mumble/GlobalShortcut_unix.cpp b/src/mumble/GlobalShortcut_unix.cpp index 8dbb55ad4a1..6d0646d4ae9 100644 --- a/src/mumble/GlobalShortcut_unix.cpp +++ b/src/mumble/GlobalShortcut_unix.cpp @@ -198,8 +198,8 @@ void GlobalShortcutX::run() { } } for (int i = 8; i <= 12; ++i) { - bool oldstate = (mask[idx] & (1 << i)) != 0; - bool newstate = (mask[next] & (1 << i)) != 0; + bool oldstate = (mask[idx] & static_cast< unsigned int >(1 << i)) != 0; + bool newstate = (mask[next] & static_cast< unsigned int >(1 << i)) != 0; if (oldstate != newstate) { handleButton(0x110 + i, newstate); } diff --git a/src/mumble/GlobalShortcut_win.cpp b/src/mumble/GlobalShortcut_win.cpp index 36353ed9e77..aab7949f266 100644 --- a/src/mumble/GlobalShortcut_win.cpp +++ b/src/mumble/GlobalShortcut_win.cpp @@ -6,6 +6,14 @@ // For detailed info about RAWKEYBOARD handling: // https://blog.molecular-matters.com/2011/09/05/properly-handling-keyboard-input +#ifdef _MSVC_LANG +# pragma warning(push) +// SPSCQueue does some funky alignment tricks which trigger the C4316 +// warning about potential misalignment on the heap. +// We just have to trust the SPSCQueue implementation here. +# pragma warning(disable : 4316) +#endif + #include "GlobalShortcut_win.h" #include "Global.h" @@ -489,7 +497,7 @@ void GlobalShortcutWin::processMsgHid(MsgHid &msg) { #endif auto data = reinterpret_cast< PHIDP_PREPARSED_DATA >(&device.data[0]); - ULONG nUsages = device.buttons.size(); + ULONG nUsages = static_cast< ULONG >(device.buttons.size()); std::vector< USAGE > usages(nUsages); if (HidP_GetUsages(HidP_Input, HID_USAGE_PAGE_BUTTON, 0, &usages[0], &nUsages, data, &msg.reports[0], msg.reportSize) @@ -623,12 +631,12 @@ GlobalShortcutWin::DeviceMap::iterator GlobalShortcutWin::addDevice(const HANDLE std::wstring_convert< std::codecvt_utf8_utf16< wchar_t > > conv; - if (HidD_GetManufacturerString(handle, &name[0], sizeof(wchar_t) * name.size())) { + if (HidD_GetManufacturerString(handle, &name[0], static_cast< ULONG >(sizeof(wchar_t) * name.size()))) { nameStream << ' ' << conv.to_bytes(name); name.clear(); } - if (HidD_GetProductString(handle, &name[0], sizeof(wchar_t) * name.size())) { + if (HidD_GetProductString(handle, &name[0], static_cast< ULONG >(sizeof(wchar_t) * name.size()))) { nameStream << ' ' << conv.to_bytes(name); } @@ -881,3 +889,7 @@ GlobalShortcutWin::ButtonInfo GlobalShortcutWin::buttonInfo(const QVariant &butt return info; } + +#ifdef _MSVC_LANG +# pragma warning(pop) +#endif diff --git a/src/mumble/JSONSerialization.h b/src/mumble/JSONSerialization.h index e830abeeba6..e329d343dd4 100644 --- a/src/mumble/JSONSerialization.h +++ b/src/mumble/JSONSerialization.h @@ -113,7 +113,7 @@ template<> inline QString from_string< QString >(const std::string &str) { return QString::fromStdString(str); } -}; // namespace details +} // namespace details diff --git a/src/mumble/JackAudio.cpp b/src/mumble/JackAudio.cpp index 5079f10da21..c0276f083a2 100644 --- a/src/mumble/JackAudio.cpp +++ b/src/mumble/JackAudio.cpp @@ -600,17 +600,17 @@ void JackAudioSystem::ringbufferWriteAdvance(jack_ringbuffer_t *buffer, const si } int JackAudioSystem::processCallback(jack_nframes_t frames, void *) { - auto const jai = dynamic_cast< JackAudioInput * >(Global::get().ai.get()); - auto const jao = dynamic_cast< JackAudioOutput * >(Global::get().ao.get()); + auto const input = dynamic_cast< JackAudioInput * >(Global::get().ai.get()); + auto const output = dynamic_cast< JackAudioOutput * >(Global::get().ao.get()); - const bool input = (jai && jai->isReady()); - const bool output = (jao && jao->isReady()); + const bool canInput = (input && input->isReady()); + const bool canOutput = (output && output->isReady()); - if (input && !jai->process(frames)) { + if (canInput && !input->process(frames)) { return 1; } - if (output && !jao->process(frames)) { + if (canOutput && !output->process(frames)) { return 1; } @@ -618,29 +618,29 @@ int JackAudioSystem::processCallback(jack_nframes_t frames, void *) { } int JackAudioSystem::sampleRateCallback(jack_nframes_t, void *) { - auto const jai = dynamic_cast< JackAudioInput * >(Global::get().ai.get()); - auto const jao = dynamic_cast< JackAudioOutput * >(Global::get().ao.get()); + auto const input = dynamic_cast< JackAudioInput * >(Global::get().ai.get()); + auto const output = dynamic_cast< JackAudioOutput * >(Global::get().ao.get()); - if (jai) { - jai->activate(); + if (input) { + input->activate(); } - if (jao) { - jao->activate(); + if (output) { + output->activate(); } return 0; } int JackAudioSystem::bufferSizeCallback(jack_nframes_t frames, void *) { - auto const jai = dynamic_cast< JackAudioInput * >(Global::get().ai.get()); - auto const jao = dynamic_cast< JackAudioOutput * >(Global::get().ao.get()); + auto const input = dynamic_cast< JackAudioInput * >(Global::get().ai.get()); + auto const output = dynamic_cast< JackAudioOutput * >(Global::get().ao.get()); - if (jai && !jai->allocBuffer(frames)) { + if (input && !input->allocBuffer(frames)) { return 1; } - if (jao && !jao->allocBuffer(frames)) { + if (output && !output->allocBuffer(frames)) { return 1; } @@ -837,7 +837,7 @@ void JackAudioInput::run() { while (const auto bytes = qMin(jas->ringbufferReadSpace(buffer), bufferSize)) { jas->ringbufferRead(buffer, bytes, sampleBuffer.get()); - addMic(sampleBuffer.get(), bytes / sizeof(jack_default_audio_sample_t)); + addMic(sampleBuffer.get(), static_cast< unsigned int >(bytes / sizeof(jack_default_audio_sample_t))); } qmWait.unlock(); @@ -1015,18 +1015,19 @@ bool JackAudioOutput::process(const jack_nframes_t frames) { qsSleep.release(1); for (decltype(iChannels) currentChannel = 0; currentChannel < iChannels; ++currentChannel) { - auto outputBuffer = jas->getPortBuffer(ports[currentChannel], frames); + auto outputBuffer = jas->getPortBuffer(ports[static_cast< int >(currentChannel)], frames); if (!outputBuffer) { return false; } - outputBuffers.replace(currentChannel, reinterpret_cast< jack_default_audio_sample_t * >(outputBuffer)); + outputBuffers.replace(static_cast< int >(currentChannel), + reinterpret_cast< jack_default_audio_sample_t * >(outputBuffer)); } const auto avail = jas->ringbufferReadSpace(buffer); if (avail == 0) { for (decltype(iChannels) currentChannel = 0; currentChannel < iChannels; ++currentChannel) { - memset(outputBuffers[currentChannel], 0, frames * sizeof(jack_default_audio_sample_t)); + memset(outputBuffers[static_cast< int >(currentChannel)], 0, frames * sizeof(jack_default_audio_sample_t)); } return true; @@ -1037,7 +1038,7 @@ bool JackAudioOutput::process(const jack_nframes_t frames) { if (iChannels == 1) { jas->ringbufferRead(buffer, avail, reinterpret_cast< char * >(outputBuffers[0])); if (avail < needed) { - memset(reinterpret_cast< char * >(&(outputBuffers[avail])), 0, needed - avail); + memset(reinterpret_cast< char * >(&(outputBuffers[static_cast< int >(avail)])), 0, needed - avail); } return true; @@ -1047,12 +1048,14 @@ bool JackAudioOutput::process(const jack_nframes_t frames) { for (auto currentSample = decltype(samples){ 0 }; currentSample < samples; ++currentSample) { jas->ringbufferRead( buffer, sizeof(jack_default_audio_sample_t), - reinterpret_cast< char * >(&outputBuffers[currentSample % iChannels][currentSample / iChannels])); + reinterpret_cast< char * >( + &outputBuffers[static_cast< int >(currentSample % iChannels)][currentSample / iChannels])); } if ((samples / iChannels) < frames) { for (decltype(iChannels) currentChannel = 0; currentChannel < iChannels; ++currentChannel) { - memset(&outputBuffers[currentChannel][avail / samples], 0, (needed - avail) / iChannels); + memset(&outputBuffers[static_cast< int >(currentChannel)][avail / samples], 0, + (needed - avail) / iChannels); } } @@ -1088,7 +1091,8 @@ void JackAudioOutput::run() { auto bOk = true; size_t writtenFrames = 0; - auto wanted = qMin(writeVector->len / iSampleSize, static_cast< size_t >(iFrameSize)); + unsigned int wanted = + qMin(static_cast< unsigned int >(writeVector->len) / iSampleSize, static_cast< unsigned int >(iFrameSize)); if (wanted > 0) { bOk = mix(writeVector->buf, wanted); writtenFrames += bOk ? wanted : 0; diff --git a/src/mumble/LCD.cpp b/src/mumble/LCD.cpp index 4d30a49ee1b..de57d589e20 100644 --- a/src/mumble/LCD.cpp +++ b/src/mumble/LCD.cpp @@ -210,7 +210,7 @@ void LCD::initBuffers() { foreach (LCDDevice *d, devmgr.qlDevices) { QSize size = d->size(); if (!qhImageBuffers.contains(size)) { - size_t buflen = (size.width() * size.height()) / 8; + size_t buflen = static_cast< std::size_t >(size.width() * size.height()) / 8; qhImageBuffers[size] = new unsigned char[buflen]; qhImages[size] = new QImage(qhImageBuffers[size], size.width(), size.height(), QImage::Format_MonoLSB); } @@ -429,5 +429,5 @@ LCDDevice::~LCDDevice() { /* --- */ uint qHash(const QSize &size) { - return ((size.width() & 0xffff) << 16) | (size.height() & 0xffff); + return static_cast< uint >((size.width() & 0xffff) << 16) | (size.height() & 0xffff); } diff --git a/src/mumble/ListenerVolumeSlider.cpp b/src/mumble/ListenerVolumeSlider.cpp index 6db5a8fdd3e..40179fb64d6 100644 --- a/src/mumble/ListenerVolumeSlider.cpp +++ b/src/mumble/ListenerVolumeSlider.cpp @@ -54,7 +54,7 @@ void ListenerVolumeSlider::on_VolumeSlider_changeCompleted() { // Timer values: 0, 50, 150, 350, 750, 1000 (ms) m_resetTimer.stop(); - m_sendTimer.start(m_currentSendDelay); + m_sendTimer.start(static_cast< int >(m_currentSendDelay)); m_currentSendDelay = std::min(1000u, (m_currentSendDelay + 25) * 2); } else { diff --git a/src/mumble/ListenerVolumeSlider.h b/src/mumble/ListenerVolumeSlider.h index 08c651a80c7..646e9adb0ba 100644 --- a/src/mumble/ListenerVolumeSlider.h +++ b/src/mumble/ListenerVolumeSlider.h @@ -29,7 +29,7 @@ class ListenerVolumeSlider : public VolumeSliderWidgetAction { QTimer m_sendTimer; QTimer m_resetTimer; unsigned int m_currentSendDelay; - int m_cachedChannelID; + unsigned int m_cachedChannelID; VolumeAdjustment m_cachedAdjustment; void sendToServer(); diff --git a/src/mumble/Log.cpp b/src/mumble/Log.cpp index 9d3074b807f..0f1229764aa 100644 --- a/src/mumble/Log.cpp +++ b/src/mumble/Log.cpp @@ -280,7 +280,7 @@ void LogConfig::save() const { } if (i->checkState(ColStaticSound) == Qt::Checked) v |= Settings::LogSoundfile; - s.qmMessages[mt] = v; + s.qmMessages[mt] = static_cast< unsigned int >(v); s.qmMessageSounds[mt] = i->text(ColStaticSoundPath); } s.iMaxLogBlocks = qsbMaxBlocks->value(); @@ -667,7 +667,7 @@ QString Log::validHtml(const QString &html, QTextCursor *tc) { } } - int messageSize = s.width() * s.height(); + int messageSize = static_cast< int >(s.width() * s.height()); int allowedSize = 2048 * 2048; if (messageSize > allowedSize) { diff --git a/src/mumble/Log.h b/src/mumble/Log.h index 76e7edf9b53..ec1fff086c1 100644 --- a/src/mumble/Log.h +++ b/src/mumble/Log.h @@ -192,6 +192,6 @@ class LogDocumentResourceAddedEvent : public QEvent { LogDocumentResourceAddedEvent(); }; -Q_DECLARE_METATYPE(Log::MsgType); +Q_DECLARE_METATYPE(Log::MsgType) #endif diff --git a/src/mumble/MainWindow.cpp b/src/mumble/MainWindow.cpp index 7951a78820e..8d15e81a7e5 100644 --- a/src/mumble/MainWindow.cpp +++ b/src/mumble/MainWindow.cpp @@ -943,7 +943,7 @@ bool MainWindow::handleSpecialContextMenu(const QUrl &url, const QPoint &pos_, b // plain integers in the host field as IP addresses QByteArray qbaServerDigest = QByteArray::fromBase64(url.path().remove(0, 1).toLatin1()); QString id = url.host().split(".").value(1, "-1"); - cuContextUser = ClientUser::get(id.toInt(&ok, 10)); + cuContextUser = ClientUser::get(id.toUInt(&ok, 10)); ServerHandlerPtr sh = Global::get().sh; ok = ok && sh && (qbaServerDigest == sh->qbaDigest); } @@ -965,7 +965,7 @@ bool MainWindow::handleSpecialContextMenu(const QUrl &url, const QPoint &pos_, b bool ok; QByteArray qbaServerDigest = QByteArray::fromBase64(url.path().remove(0, 1).toLatin1()); QString id = url.host().split(".").value(1, "-1"); - cContextChannel = Channel::get(id.toInt(&ok, 10)); + cContextChannel = Channel::get(id.toUInt(&ok, 10)); ServerHandlerPtr sh = Global::get().sh; ok = ok && sh && (qbaServerDigest == sh->qbaDigest); if (ok) { @@ -1227,7 +1227,7 @@ void MainWindow::openUrl(const QUrl &url) { std::swap(newSettings, Global::get().s); Global::get().l->log(Log::Warning, tr("Settings merged from file.")); - } catch (const std::exception &e) { + } catch (const std::exception &) { Global::get().l->log(Log::Warning, tr("Invalid settings file encountered.")); } @@ -2393,7 +2393,7 @@ void MainWindow::on_qaChannelRemove_triggered() { if (!c) return; - int id = c->iId; + unsigned int id = c->iId; ret = QMessageBox::question( this, QLatin1String("Mumble"), @@ -2413,7 +2413,7 @@ void MainWindow::on_qaChannelACL_triggered() { Channel *c = getContextMenuChannel(); if (!c) c = Channel::get(Channel::ROOT_ID); - int id = c->iId; + unsigned int id = c->iId; if (!c->qbaDescHash.isEmpty() && c->qsDesc.isEmpty()) { c->qsDesc = QString::fromUtf8(Global::get().db->blob(c->qbaDescHash)); @@ -2467,7 +2467,7 @@ void MainWindow::on_qaChannelSendMessage_triggered() { if (!c) return; - int id = c->iId; + unsigned int id = c->iId; ::TextMessage *texm = new ::TextMessage(this, tr("Sending message to channel %1").arg(c->qsName), true); int res = texm->exec(); @@ -2879,7 +2879,7 @@ Channel *MainWindow::mapChannel(int idx) const { break; } } else { - c = Channel::get(idx); + c = Channel::get(static_cast< unsigned int >(idx)); } return c; } @@ -2903,7 +2903,7 @@ void MainWindow::updateTarget() { Channel *c = pmModel->getSelectedChannel(); if (c) { nt.bUsers = false; - nt.iChannel = c->iId; + nt.iChannel = static_cast< int >(c->iId); nt.bLinks = st.bLinks; nt.bChildren = st.bChildren; @@ -2931,7 +2931,7 @@ void MainWindow::updateTarget() { if (c) { nt.bLinks = st.bLinks; nt.bChildren = st.bChildren; - nt.iChannel = c->iId; + nt.iChannel = static_cast< int >(c->iId); nt.qsGroup = st.qsGroup; ql << nt; } @@ -2964,7 +2964,7 @@ void MainWindow::updateTarget() { // Sets up a VoiceTarget (which is identified by the targetID idx) on the server for the given set // of ShortcutTargets MumbleProto::VoiceTarget mpvt; - mpvt.set_id(idx); + mpvt.set_id(static_cast< unsigned int >(idx)); foreach (const ShortcutTarget &st, ql) { MumbleProto::VoiceTarget_Target *t = mpvt.add_targets(); @@ -2974,7 +2974,7 @@ void MainWindow::updateTarget() { foreach (unsigned int uisession, st.qlSessions) t->add_session(uisession); } else { - t->set_channel_id(st.iChannel); + t->set_channel_id(static_cast< unsigned int >(st.iChannel)); if (st.bChildren) t->set_children(true); if (st.bLinks) @@ -3007,7 +3007,7 @@ void MainWindow::updateTarget() { qmTargets.erase(mi); mpvt.Clear(); - mpvt.set_id(oldidx); + mpvt.set_id(static_cast< unsigned int >(oldidx)); Global::get().sh->sendMessage(mpvt); break; diff --git a/src/mumble/MainWindow.h b/src/mumble/MainWindow.h index 08280ce1e5e..ed7e87d9012 100644 --- a/src/mumble/MainWindow.h +++ b/src/mumble/MainWindow.h @@ -41,7 +41,7 @@ class PTTButtonWidget; namespace Search { class SearchDialog; -}; +} class MenuLabel; class ListenerVolumeSlider; diff --git a/src/mumble/ManualPlugin.cpp b/src/mumble/ManualPlugin.cpp index bf7260aa635..4e42c515f32 100644 --- a/src/mumble/ManualPlugin.cpp +++ b/src/mumble/ManualPlugin.cpp @@ -263,7 +263,7 @@ void Manual::on_speakerPositionUpdate(QHash< unsigned int, Position2D > position while (remainingIt.hasNext()) { remainingIt.next(); - const float speakerRadius = 1.2; + const float speakerRadius = 1.2f; QGraphicsItem *speakerItem = m_qgsScene->addEllipse(-speakerRadius, -speakerRadius, 2 * speakerRadius, 2 * speakerRadius, QPen(), QBrush(Qt::red)); diff --git a/src/mumble/ManualPlugin.h b/src/mumble/ManualPlugin.h index 3058bd51587..932549e077e 100644 --- a/src/mumble/ManualPlugin.h +++ b/src/mumble/ManualPlugin.h @@ -25,7 +25,7 @@ struct Position2D { // We need this typedef in order to be able to pass this hash as an argument // to QMetaObject::invokeMethod using PositionMap = QHash< unsigned int, Position2D >; -Q_DECLARE_METATYPE(PositionMap); +Q_DECLARE_METATYPE(PositionMap) /// A struct holding information about a stale entry in the diff --git a/src/mumble/Markdown.cpp b/src/mumble/Markdown.cpp index 1c7b2c81b67..03c87c68102 100644 --- a/src/mumble/Markdown.cpp +++ b/src/mumble/Markdown.cpp @@ -404,4 +404,4 @@ QString markdownToHTML(const QString &markdownInput) { return htmlString; } -}; // namespace Markdown +} // namespace Markdown diff --git a/src/mumble/Markdown.h b/src/mumble/Markdown.h index cf39b0bab15..294bce0863c 100644 --- a/src/mumble/Markdown.h +++ b/src/mumble/Markdown.h @@ -15,6 +15,6 @@ namespace Markdown { /// @param markdownInput A reference to the input string /// @returns The processed HTML string QString markdownToHTML(const QString &markdownInput); -}; // namespace Markdown +} // namespace Markdown #endif // MUMBLE_MUMBLE_MARKDOWN_H_ diff --git a/src/mumble/Messages.cpp b/src/mumble/Messages.cpp index 6ff53a926ec..96ae313ecd2 100644 --- a/src/mumble/Messages.cpp +++ b/src/mumble/Messages.cpp @@ -149,7 +149,7 @@ void MainWindow::msgServerSync(const MumbleProto::ServerSync &msg) { } iTargetCounter = 100; - AudioInput::setMaxBandwidth(msg.max_bandwidth()); + AudioInput::setMaxBandwidth(static_cast< int >(msg.max_bandwidth())); findDesiredChannel(); @@ -200,7 +200,7 @@ void MainWindow::msgServerConfig(const MumbleProto::ServerConfig &msg) { } } if (msg.has_max_bandwidth()) - AudioInput::setMaxBandwidth(msg.max_bandwidth()); + AudioInput::setMaxBandwidth(static_cast< int >(msg.max_bandwidth())); if (msg.has_allow_html()) Global::get().bAllowHTML = msg.allow_html(); if (msg.has_message_length()) @@ -264,7 +264,7 @@ void MainWindow::msgPermissionDenied(const MumbleProto::PermissionDenied &msg) { Global::get().s.bTTS = true; quint32 oflags = Global::get().s.qmMessages.value(Log::PermissionDenied); Global::get().s.qmMessages[Log::PermissionDenied] = - (oflags | Settings::LogTTS) & (~Settings::LogSoundfile); + (oflags | Settings::LogTTS) & static_cast< unsigned int >(~Settings::LogSoundfile); Global::get().l->log(Log::PermissionDenied, QString::fromUtf8(Global::get().ccHappyEaster + 39) .arg(Global::get().s.qsUsername.toHtmlEscaped())); Global::get().s.qmMessages[Log::PermissionDenied] = oflags; @@ -376,7 +376,7 @@ void MainWindow::msgUserState(const MumbleProto::UserState &msg) { } if (msg.has_user_id()) { - pmModel->setUserId(pDst, msg.user_id()); + pmModel->setUserId(pDst, static_cast< int >(msg.user_id())); } if (channel) { @@ -501,14 +501,14 @@ void MainWindow::msgUserState(const MumbleProto::UserState &msg) { } } for (int i = 0; i < msg.listening_volume_adjustment_size(); i++) { - int channelID = msg.listening_volume_adjustment(i).listening_channel(); - float adjustment = msg.listening_volume_adjustment(i).volume_adjustment(); + unsigned int channelID = msg.listening_volume_adjustment(i).listening_channel(); + float adjustment = msg.listening_volume_adjustment(i).volume_adjustment(); - const Channel *channel = Channel::get(channelID); - if (channel && pSelf && pSelf->uiSession == pDst->uiSession) { - Global::get().channelListenerManager->setListenerVolumeAdjustment(pDst->uiSession, channel->iId, + const Channel *listenedChannel = Channel::get(channelID); + if (listenedChannel && pSelf && pSelf->uiSession == pDst->uiSession) { + Global::get().channelListenerManager->setListenerVolumeAdjustment(pDst->uiSession, listenedChannel->iId, VolumeAdjustment::fromFactor(adjustment)); - } else if (!channel) { + } else if (!listenedChannel) { qWarning("msgUserState(): Invalid channel ID encountered in volume adjustment"); } } @@ -982,7 +982,7 @@ void MainWindow::msgChannelRemove(const MumbleProto::ChannelRemove &msg) { if (Global::get().mw->m_searchDialog) { QMetaObject::invokeMethod(Global::get().mw->m_searchDialog, "on_channelRemoved", Qt::QueuedConnection, - Q_ARG(int, c->iId)); + Q_ARG(unsigned int, c->iId)); } if (!pmModel->removeChannel(c, true)) { @@ -1200,7 +1200,7 @@ void MainWindow::msgPermissionQuery(const MumbleProto::PermissionQuery &msg) { c->uiPermissions = 0; // We always need the permissions of the current focus channel - if (current && current->iId != static_cast< int >(msg.channel_id())) { + if (current && current->iId != msg.channel_id()) { Global::get().sh->requestChannelPermissions(current->iId); current->uiPermissions = ChanACL::All; @@ -1293,14 +1293,14 @@ void MainWindow::msgPluginDataTransmission(const MumbleProto::PluginDataTransmis return; } - const ClientUser *sender = ClientUser::get(msg.sendersession()); - const std::string &data = msg.data(); + const ClientUser *sender = ClientUser::get(msg.sendersession()); + const std::string &msgData = msg.data(); if (sender) { static_assert(sizeof(unsigned char) == sizeof(uint8_t), "Unsigned char does not have expected 8bit size"); // As long as above assertion is true, we are only casting away the sign, which is fine - Global::get().pluginManager->on_receiveData(sender, reinterpret_cast< const uint8_t * >(data.c_str()), - data.size(), msg.dataid().c_str()); + Global::get().pluginManager->on_receiveData(sender, reinterpret_cast< const uint8_t * >(msgData.c_str()), + msgData.size(), msg.dataid().c_str()); } } diff --git a/src/mumble/OSS.cpp b/src/mumble/OSS.cpp index c1a0f4a0123..593ab57e3c3 100644 --- a/src/mumble/OSS.cpp +++ b/src/mumble/OSS.cpp @@ -220,30 +220,30 @@ void OSSInput::run() { qWarning("OSSInput: Failed to set mono mode"); return; } - iMicChannels = ival; + iMicChannels = static_cast< unsigned int >(ival); ival = SAMPLE_RATE; if (ioctl(fd, SNDCTL_DSP_SPEED, &ival) == -1) { qWarning("OSSInput: Failed to set speed"); return; } - iMicFreq = ival; + iMicFreq = static_cast< unsigned int >(ival); qWarning("OSSInput: Starting audio capture from %s", device.constData()); eMicFormat = SampleShort; initializeMixer(); + std::vector< short > buffer; + buffer.resize(iMicLength); while (bRunning) { - short buffer[iMicLength]; - - int len = static_cast< int >(iMicLength * iMicChannels * sizeof(short)); - ssize_t l = read(fd, buffer, len); - if (l != len) { + std::size_t len = iMicLength * iMicChannels * sizeof(short); + ssize_t l = read(fd, buffer.data(), len); + if (l != static_cast< ssize_t >(len)) { qWarning("OSSInput: Read %zd", l); break; } - addMic(buffer, iMicLength); + addMic(buffer.data(), iMicLength); } qWarning("OSSInput: Releasing."); @@ -296,19 +296,19 @@ void OSSOutput::run() { iChannels = 2; - ival = iChannels; + ival = static_cast< int >(iChannels); if ((ioctl(fd, SNDCTL_DSP_CHANNELS, &ival) == -1) && (ival == static_cast< int >(iChannels))) { qWarning("OSSOutput: Failed to set channels"); return; } - iChannels = ival; + iChannels = static_cast< unsigned int >(ival); ival = SAMPLE_RATE; if (ioctl(fd, SNDCTL_DSP_SPEED, &ival) == -1) { qWarning("OSSOutput: Failed to set speed"); return; } - iMixerFreq = ival; + iMixerFreq = static_cast< unsigned int >(ival); const unsigned int chanmasks[32] = { SPEAKER_FRONT_LEFT, SPEAKER_FRONT_RIGHT, SPEAKER_FRONT_CENTER, SPEAKER_LOW_FREQUENCY, SPEAKER_BACK_LEFT, SPEAKER_BACK_RIGHT, @@ -318,26 +318,27 @@ void OSSOutput::run() { initializeMixer(chanmasks); - int iOutputBlock = (iFrameSize * iMixerFreq) / SAMPLE_RATE; + unsigned int iOutputBlock = (iFrameSize * iMixerFreq) / SAMPLE_RATE; qWarning("OSSOutput: Starting audio playback to %s", device.constData()); - ssize_t blocklen = iOutputBlock * iChannels * sizeof(short); - short mbuffer[iOutputBlock * iChannels]; + std::size_t blocklen = iOutputBlock * iChannels * sizeof(short); + static std::vector< short > mbuffer; + mbuffer.resize(iOutputBlock * iChannels); while (bRunning) { - bool stillRun = mix(mbuffer, iOutputBlock); + bool stillRun = mix(mbuffer.data(), iOutputBlock); if (stillRun) { - ssize_t l = write(fd, mbuffer, blocklen); - if (l != blocklen) { + ssize_t l = write(fd, mbuffer.data(), blocklen); + if (l != static_cast< ssize_t >(blocklen)) { qWarning("OSSOutput: Write %zd != %zd", l, blocklen); break; } } else { - while (!mix(mbuffer, iOutputBlock) && bRunning) + while (!mix(mbuffer.data(), iOutputBlock) && bRunning) this->msleep(20); - ssize_t l = write(fd, mbuffer, blocklen); - if (l != blocklen) { + ssize_t l = write(fd, mbuffer.data(), blocklen); + if (l != static_cast< ssize_t >(blocklen)) { qWarning("OSSOutput: Write %zd != %zd", l, blocklen); break; } diff --git a/src/mumble/Overlay.h b/src/mumble/Overlay.h index da5a5694b36..03184fa1a87 100644 --- a/src/mumble/Overlay.h +++ b/src/mumble/Overlay.h @@ -43,7 +43,7 @@ struct OverlayAppInfo { class OverlayGroup : public QGraphicsItem { private: - Q_DISABLE_COPY(OverlayGroup); + Q_DISABLE_COPY(OverlayGroup) public: enum { Type = UserType + 5 }; diff --git a/src/mumble/OverlayClient.cpp b/src/mumble/OverlayClient.cpp index af38371ee41..e7a8805014c 100644 --- a/src/mumble/OverlayClient.cpp +++ b/src/mumble/OverlayClient.cpp @@ -37,7 +37,7 @@ OverlayClient::OverlayClient(QLocalSocket *socket, QObject *p) omMsg.omh.iLength = -1; smMem = nullptr; - uiWidth = uiHeight = 0; + iWidth = iHeight = 0; uiPid = ~0ULL; @@ -98,7 +98,8 @@ bool OverlayClient::eventFilter(QObject *o, QEvent *e) { void OverlayClient::updateFPS() { if (Global::get().s.os.bFps) { const BasepointPixmap &pm = - OverlayTextLine(QString(QLatin1String("%1")).arg(iroundf(framesPerSecond + 0.5f)), Global::get().s.os.qfFps) + OverlayTextLine(QString(QLatin1String("%1")).arg(static_cast< int >(framesPerSecond + 0.5f)), + Global::get().s.os.qfFps) .createPixmap(Global::get().s.os.qcFps); qgpiFPS->setVisible(true); qgpiFPS->setPixmap(pm); @@ -228,8 +229,8 @@ void OverlayClient::showGui() { qgpw->setOpacity(0.90f); qgpw->setWidget(w); if (w == Global::get().mw) { - qgpw->setPos(uiWidth / 10, uiHeight / 10); - qgpw->resize((uiWidth * 8) / 10, (uiHeight * 8) / 10); + qgpw->setPos(static_cast< float >(iWidth) / 10, static_cast< float >(iHeight) / 10); + qgpw->resize(static_cast< float >(iWidth * 8) / 10, static_cast< float >(iHeight * 8) / 10); } qgs.addItem(qgpw); @@ -245,8 +246,8 @@ void OverlayClient::showGui() { qApp->sendEvent(&qgs, &activateEvent); QPoint p = QCursor::pos(); - iMouseX = qBound< int >(0, p.x(), uiWidth - 1); - iMouseY = qBound< int >(0, p.y(), uiHeight - 1); + iMouseX = qBound< int >(0, p.x(), static_cast< int >(iWidth) - 1); + iMouseY = qBound< int >(0, p.y(), static_cast< int >(iHeight) - 1); qgpiCursor->setPos(iMouseX, iMouseY); @@ -276,7 +277,7 @@ void OverlayClient::showGui() { om.omh.uiType = OVERLAY_MSGTYPE_INTERACTIVE; om.omh.iLength = sizeof(struct OverlayMsgInteractive); om.omin.state = true; - qlsSocket->write(om.headerbuffer, sizeof(OverlayMsgHeader) + om.omh.iLength); + qlsSocket->write(om.headerbuffer, static_cast< int >(sizeof(OverlayMsgHeader)) + om.omh.iLength); Global::get().o->updateOverlay(); } @@ -338,7 +339,7 @@ void OverlayClient::hideGui() { om.omh.uiType = OVERLAY_MSGTYPE_INTERACTIVE; om.omh.iLength = sizeof(struct OverlayMsgInteractive); om.omin.state = false; - qlsSocket->write(om.headerbuffer, sizeof(OverlayMsgHeader) + om.omh.iLength); + qlsSocket->write(om.headerbuffer, static_cast< int >(sizeof(OverlayMsgHeader)) + om.omh.iLength); Global::get().o->updateOverlay(); @@ -358,15 +359,15 @@ void OverlayClient::readyReadMsgInit(unsigned int length) { OverlayMsgInit *omi = &omMsg.omi; - uiWidth = omi->uiWidth; - uiHeight = omi->uiHeight; - qrLast = QRect(); + iWidth = static_cast< int >(omi->uiWidth); + iHeight = static_cast< int >(omi->uiHeight); + qrLast = QRect(); delete smMem; - smMem = new SharedMemory2(this, uiWidth * uiHeight * 4); + smMem = new SharedMemory2(this, static_cast< unsigned int >(iWidth * iHeight * 4)); if (!smMem->data()) { - qWarning() << "OverlayClient: Failed to create shared memory" << uiWidth << uiHeight; + qWarning() << "OverlayClient: Failed to create shared memory" << iWidth << iHeight; delete smMem; smMem = nullptr; return; @@ -379,8 +380,8 @@ void OverlayClient::readyReadMsgInit(unsigned int length) { om.omh.uiType = OVERLAY_MSGTYPE_SHMEM; om.omh.iLength = key.length(); Q_ASSERT(sizeof(om.oms.a_cName) >= static_cast< size_t >(key.length())); // Name should be auto-generated and short - memcpy(om.oms.a_cName, key.constData(), key.length()); - qlsSocket->write(om.headerbuffer, sizeof(OverlayMsgHeader) + om.omh.iLength); + memcpy(om.oms.a_cName, key.constData(), static_cast< std::size_t >(key.length())); + qlsSocket->write(om.headerbuffer, static_cast< int >(sizeof(OverlayMsgHeader)) + om.omh.iLength); setupRender(); @@ -463,7 +464,7 @@ void OverlayClient::readyRead() { } void OverlayClient::reset() { - if (!uiWidth || !uiHeight || !smMem) + if (!iWidth || !iHeight || !smMem) return; qgpiLogo.reset(); @@ -486,14 +487,14 @@ void OverlayClient::setupScene(bool show) { QImageReader qir(QLatin1String("skin:mumble.svg")); QSize sz = qir.size(); - sz.scale(uiWidth, uiHeight, Qt::KeepAspectRatio); + sz.scale(static_cast< int >(iWidth), static_cast< int >(iHeight), Qt::KeepAspectRatio); qir.setScaledSize(sz); qgpiLogo->setPixmap(QPixmap::fromImage(qir.read())); QRectF qrf = qgpiLogo->boundingRect(); - qgpiLogo->setPos(iroundf((uiWidth - qrf.width()) / 2.0f + 0.5f), - iroundf((uiHeight - qrf.height()) / 2.0f + 0.5f)); + qgpiLogo->setPos(static_cast< int >((iWidth - qrf.width()) / 2.0f + 0.5f), + static_cast< int >((iHeight - qrf.height()) / 2.0f + 0.5f)); } qgpiCursor->show(); @@ -520,10 +521,10 @@ void OverlayClient::setupScene(bool show) { } void OverlayClient::setupRender() { - qgs.setSceneRect(0, 0, uiWidth, uiHeight); + qgs.setSceneRect(0, 0, iWidth, iHeight); qgv.setScene(nullptr); - qgv.setGeometry(-2, -2, uiWidth + 2, uiHeight + 2); - qgv.viewport()->setGeometry(0, 0, uiWidth, uiHeight); + qgv.setGeometry(-2, -2, static_cast< int >(iWidth) + 2, static_cast< int >(iHeight) + 2); + qgv.viewport()->setGeometry(0, 0, static_cast< int >(iWidth), static_cast< int >(iHeight)); qgv.setScene(&qgs); smMem->erase(); @@ -534,15 +535,15 @@ void OverlayClient::setupRender() { om.omh.iLength = sizeof(OverlayMsgBlit); om.omb.x = 0; om.omb.y = 0; - om.omb.w = uiWidth; - om.omb.h = uiHeight; + om.omb.w = static_cast< unsigned int >(iWidth); + om.omb.h = static_cast< unsigned int >(iHeight); qlsSocket->write(om.headerbuffer, sizeof(OverlayMsgHeader) + sizeof(OverlayMsgBlit)); reset(); } bool OverlayClient::update() { - if (!uiWidth || !uiHeight || !smMem) + if (!iWidth || !iHeight || !smMem) return true; ougUsers.updateUsers(); @@ -569,7 +570,7 @@ void OverlayClient::render() { const QList< QRectF > region = qlDirty; qlDirty.clear(); - if (!uiWidth || !uiHeight || !smMem) + if (!iWidth || !iHeight || !smMem) return; QRect active; @@ -582,7 +583,7 @@ void OverlayClient::render() { QRect dirty = dirtyf.toAlignedRect(); - dirty = dirty.intersected(QRect(0, 0, uiWidth, uiHeight)); + dirty = dirty.intersected(QRect(0, 0, iWidth, iHeight)); if ((dirty.width() <= 0) || (dirty.height() <= 0)) return; @@ -590,7 +591,7 @@ void OverlayClient::render() { QRect target = dirty; target.moveTo(0, 0); - QImage img(reinterpret_cast< unsigned char * >(smMem->data()), uiWidth, uiHeight, + QImage img(reinterpret_cast< unsigned char * >(smMem->data()), iWidth, iHeight, QImage::Format_ARGB32_Premultiplied); QImage qi(target.size(), QImage::Format_ARGB32_Premultiplied); qi.fill(0); @@ -613,20 +614,20 @@ void OverlayClient::render() { om.omh.uiMagic = OVERLAY_MAGIC_NUMBER; om.omh.uiType = OVERLAY_MSGTYPE_BLIT; om.omh.iLength = sizeof(OverlayMsgBlit); - om.omb.x = dirty.x(); - om.omb.y = dirty.y(); - om.omb.w = dirty.width(); - om.omb.h = dirty.height(); + om.omb.x = static_cast< unsigned int >(dirty.x()); + om.omb.y = static_cast< unsigned int >(dirty.y()); + om.omb.w = static_cast< unsigned int >(dirty.width()); + om.omb.h = static_cast< unsigned int >(dirty.height()); qlsSocket->write(om.headerbuffer, sizeof(OverlayMsgHeader) + sizeof(OverlayMsgBlit)); } if (qgpiCursor->isVisible()) { - active = QRect(0, 0, uiWidth, uiHeight); + active = QRect(0, 0, iWidth, iHeight); } else { active = qgs.itemsBoundingRect().toAlignedRect(); if (active.isEmpty()) active = QRect(0, 0, 0, 0); - active = active.intersected(QRect(0, 0, uiWidth, uiHeight)); + active = active.intersected(QRect(0, 0, iWidth, iHeight)); } if (active != qrLast) { @@ -636,10 +637,10 @@ void OverlayClient::render() { om.omh.uiMagic = OVERLAY_MAGIC_NUMBER; om.omh.uiType = OVERLAY_MSGTYPE_ACTIVE; om.omh.iLength = sizeof(OverlayMsgActive); - om.oma.x = qrLast.x(); - om.oma.y = qrLast.y(); - om.oma.w = qrLast.width(); - om.oma.h = qrLast.height(); + om.oma.x = static_cast< unsigned int >(qrLast.x()); + om.oma.y = static_cast< unsigned int >(qrLast.y()); + om.oma.w = static_cast< unsigned int >(qrLast.width()); + om.oma.h = static_cast< unsigned int >(qrLast.height()); qlsSocket->write(om.headerbuffer, sizeof(OverlayMsgHeader) + sizeof(OverlayMsgActive)); } diff --git a/src/mumble/OverlayClient.h b/src/mumble/OverlayClient.h index fa7cab5ad01..a6504506f43 100644 --- a/src/mumble/OverlayClient.h +++ b/src/mumble/OverlayClient.h @@ -73,7 +73,7 @@ protected slots: public: QGraphicsView qgv; - unsigned int uiWidth, uiHeight; + int iWidth, iHeight; int iMouseX, iMouseY; OverlayClient(QLocalSocket *, QObject *); diff --git a/src/mumble/OverlayEditor.cpp b/src/mumble/OverlayEditor.cpp index 7e52d2bca07..4a7098e5ca5 100644 --- a/src/mumble/OverlayEditor.cpp +++ b/src/mumble/OverlayEditor.cpp @@ -32,10 +32,11 @@ OverlayEditor::OverlayEditor(QWidget *p, QGraphicsItem *qgi, OverlaySettings *os if (qgpw) { qgpw->setFlag(QGraphicsItem::ItemIgnoresParentOpacity); if (Global::get().ocIntercept) { - qgpw->setPos(iroundf(static_cast< float >(Global::get().ocIntercept->uiWidth) / 16.0f + 0.5f), - iroundf(static_cast< float >(Global::get().ocIntercept->uiHeight) / 16.0f + 0.5f)); - qgpw->resize(iroundf(static_cast< float >(Global::get().ocIntercept->uiWidth) * 14.0f / 16.0f + 0.5f), - iroundf(static_cast< float >(Global::get().ocIntercept->uiHeight) * 14.0f / 16.0f + 0.5f)); + qgpw->setPos(static_cast< int >(static_cast< float >(Global::get().ocIntercept->iWidth) / 16.0f + 0.5f), + static_cast< int >(static_cast< float >(Global::get().ocIntercept->iHeight) / 16.0f + 0.5f)); + qgpw->resize( + static_cast< int >(static_cast< float >(Global::get().ocIntercept->iWidth) * 14.0f / 16.0f + 0.5f), + static_cast< int >(static_cast< float >(Global::get().ocIntercept->iHeight) * 14.0f / 16.0f + 0.5f)); } } @@ -159,6 +160,6 @@ void OverlayEditor::on_qcbBox_clicked() { } void OverlayEditor::on_qsZoom_valueChanged(int zoom) { - oes.uiZoom = zoom; + oes.uiZoom = static_cast< unsigned int >(zoom); oes.resync(); } diff --git a/src/mumble/OverlayEditorScene.cpp b/src/mumble/OverlayEditorScene.cpp index bae8d5e4ef7..833dd39f02b 100644 --- a/src/mumble/OverlayEditorScene.cpp +++ b/src/mumble/OverlayEditorScene.cpp @@ -29,7 +29,7 @@ OverlayEditorScene::OverlayEditorScene(const OverlaySettings &srcos, QObject *p) uiZoom = 2; if (Global::get().ocIntercept) - uiSize = Global::get().ocIntercept->uiHeight; + uiSize = static_cast< unsigned int >(Global::get().ocIntercept->iHeight); else uiSize = 1080.f; @@ -75,13 +75,12 @@ OverlayEditorScene::OverlayEditorScene(const OverlaySettings &srcos, QObject *p) resync(); } -#define SCALESIZE(var) \ - iroundf(uiSize *uiZoom *os.qrf##var.width() + 0.5f), iroundf(uiSize *uiZoom *os.qrf##var.height() + 0.5f) - void OverlayEditorScene::updateMuted() { + const unsigned int scaleFactor = uiSize * uiZoom; QImageReader qir(QLatin1String("skin:muted_self.svg")); QSize sz = qir.size(); - sz.scale(SCALESIZE(MutedDeafened), Qt::KeepAspectRatio); + sz.scale(static_cast< int >(scaleFactor * os.qrfMutedDeafened.width() + 0.5f), + static_cast< int >(scaleFactor * os.qrfMutedDeafened.height() + 0.5f), Qt::KeepAspectRatio); qir.setScaledSize(sz); qgpiMuted->setPixmap(QPixmap::fromImage(qir.read())); @@ -116,8 +115,11 @@ void OverlayEditorScene::updateUserName() { break; } - const QPixmap &pm = - OverlayTextLine(qsName, os.qfUserName).createPixmap(SCALESIZE(UserName), os.qcUserName[tsColor]); + const unsigned int scaleFactor = uiSize * uiZoom; + const QPixmap &pm = OverlayTextLine(qsName, os.qfUserName) + .createPixmap(static_cast< unsigned int >(scaleFactor * os.qrfUserName.width() + 0.5f), + static_cast< unsigned int >(scaleFactor * os.qrfUserName.height() + 0.5f), + os.qcUserName[tsColor]); qgpiName->setPixmap(pm); moveUserName(); @@ -131,8 +133,11 @@ void OverlayEditorScene::moveUserName() { } void OverlayEditorScene::updateChannel() { + const unsigned int scaleFactor = uiSize * uiZoom; const QPixmap &pm = - OverlayTextLine(Overlay::tr("Channel"), os.qfChannel).createPixmap(SCALESIZE(Channel), os.qcChannel); + OverlayTextLine(Overlay::tr("Channel"), os.qfChannel) + .createPixmap(static_cast< unsigned int >(scaleFactor * os.qrfChannel.width() + 0.5f), + static_cast< unsigned int >(scaleFactor * os.qrfChannel.height() + 0.5f), os.qcChannel); qgpiChannel->setPixmap(pm); moveChannel(); @@ -146,10 +151,13 @@ void OverlayEditorScene::moveChannel() { } void OverlayEditorScene::updateAvatar() { + const unsigned int scaleFactor = uiSize * uiZoom; + QImage img; QImageReader qir(QLatin1String("skin:default_avatar.svg")); QSize sz = qir.size(); - sz.scale(SCALESIZE(Avatar), Qt::KeepAspectRatio); + sz.scale(static_cast< int >(scaleFactor * os.qrfAvatar.width() + 0.5f), + static_cast< int >(scaleFactor * os.qrfAvatar.height() + 0.5f), Qt::KeepAspectRatio); qir.setScaledSize(sz); img = qir.read(); qgpiAvatar->setPixmap(QPixmap::fromImage(img)); @@ -230,11 +238,11 @@ void OverlayEditorScene::drawBackground(QPainter *p, const QRectF &rect) { QRectF upscaled = OverlayUser::scaledRect(rect, 128.f / static_cast< float >(uiSize * uiZoom)); { - int min = iroundf(upscaled.left()); - int max = iroundf(ceil(upscaled.right())); + int min = static_cast< int >(upscaled.left()); + int max = static_cast< int >(ceil(upscaled.right())); for (int i = min; i <= max; ++i) { - qreal v = (i / 128) * static_cast< qreal >(uiSize * uiZoom); + qreal v = (static_cast< qreal >(i) / 128) * static_cast< qreal >(uiSize * uiZoom); if (i != 0) p->setPen(QPen(QColor(128, 128, 128, 255), 0.0f)); @@ -246,11 +254,11 @@ void OverlayEditorScene::drawBackground(QPainter *p, const QRectF &rect) { } { - int min = iroundf(upscaled.top()); - int max = iroundf(ceil(upscaled.bottom())); + int min = static_cast< int >(upscaled.top()); + int max = static_cast< int >(ceil(upscaled.bottom())); for (int i = min; i <= max; ++i) { - qreal v = (i / 128) * static_cast< qreal >(uiSize * uiZoom); + qreal v = (static_cast< qreal >(i) / 128) * static_cast< qreal >(uiSize * uiZoom); if (i != 0) p->setPen(QPen(QColor(128, 128, 128, 255), 0.0f)); @@ -865,5 +873,3 @@ Qt::WindowFrameSection OverlayEditorScene::rectSection(const QRectF &qrf, const return Qt::NoSection; } - -#undef SCALESIZE diff --git a/src/mumble/OverlayPositionableItem.cpp b/src/mumble/OverlayPositionableItem.cpp index cc39c7cfd0e..038e7a79b64 100644 --- a/src/mumble/OverlayPositionableItem.cpp +++ b/src/mumble/OverlayPositionableItem.cpp @@ -62,7 +62,8 @@ void OverlayPositionableItem::onMove() { void OverlayPositionableItem::updateRender() { const QRectF &sr = scene()->sceneRect(); // Translate the 0..1 float position to the real scene coordinates (relative to absolute position) - QPoint absPos(iroundf(sr.width() * m_position->x() + 0.5f), iroundf(sr.height() * m_position->y() + 0.5f)); + QPoint absPos(static_cast< int >(sr.width() * m_position->x() + 0.5f), + static_cast< int >(sr.height() * m_position->y() + 0.5f)); if (m_isPositionEditable) { if (!m_qgeiHandle) { @@ -73,7 +74,8 @@ void OverlayPositionableItem::updateRender() { QRectF br = boundingRect(); // Limit the position by the elements width (to make sure it is right-/bottom-bound rather than outside of the scene - QPoint maxPos(iroundf(sr.width() - br.width() + 0.5f), iroundf(sr.height() - br.height() + 0.5f)); + QPoint maxPos(static_cast< int >(sr.width() - br.width() + 0.5f), + static_cast< int >(sr.height() - br.height() + 0.5f)); int basex = qBound< int >(0, absPos.x(), maxPos.x()); int basey = qBound< int >(0, absPos.y(), maxPos.y()); setPos(basex, basey); diff --git a/src/mumble/OverlayPositionableItem.h b/src/mumble/OverlayPositionableItem.h index 62edcd36fbc..c9956079a69 100644 --- a/src/mumble/OverlayPositionableItem.h +++ b/src/mumble/OverlayPositionableItem.h @@ -11,7 +11,7 @@ class OverlayPositionableItem : public QObject, public QGraphicsPixmapItem { Q_OBJECT - Q_DISABLE_COPY(OverlayPositionableItem); + Q_DISABLE_COPY(OverlayPositionableItem) public: OverlayPositionableItem(QRectF *posPtr, const bool isPositionable = false); diff --git a/src/mumble/OverlayText.cpp b/src/mumble/OverlayText.cpp index d9edc3dd0d9..700858649da 100644 --- a/src/mumble/OverlayText.cpp +++ b/src/mumble/OverlayText.cpp @@ -55,8 +55,8 @@ BasepointPixmap OverlayTextLine::render(int w, int h, const QColor &col, const Q imgp.setPen(Qt::NoPen); imgp.drawPath(qpp); - img.iAscent = iroundf(fAscent + 0.5f); - img.iDescent = iroundf(fDescent + 0.5f); + img.iAscent = static_cast< int >(fAscent + 0.5f); + img.iDescent = static_cast< int >(fDescent + 0.5f); return img; } @@ -89,8 +89,9 @@ BasepointPixmap OverlayTextLine::createPixmap(QColor col) { qr = qpp.controlPointRect(); - return render(iroundf(qr.right() + 2.0f * fEdge + 0.5f), iroundf(qr.bottom() + 2.0f * fEdge + 0.5f), col, - QPoint(iroundf(fXCorrection + 0.5f), iroundf(fYCorrection + fAscent + 0.5f))); + return render(static_cast< int >(qr.right() + 2.0f * fEdge + 0.5f), + static_cast< int >(qr.bottom() + 2.0f * fEdge + 0.5f), col, + QPoint(static_cast< int >(fXCorrection + 0.5f), static_cast< int >(fYCorrection + fAscent + 0.5f))); } BasepointPixmap OverlayTextLine::createPixmap(unsigned int maxwidth, unsigned int height, QColor col) { @@ -158,7 +159,7 @@ BasepointPixmap OverlayTextLine::createPixmap(unsigned int maxwidth, unsigned in // eliding by previously calculated width if ((bb.width() * scale) + twice_edge > maxwidth) { - int eliding_width = iroundf((static_cast< float >(maxwidth) / scale) - twice_edge + 0.5f); + int eliding_width = static_cast< int >((static_cast< float >(maxwidth) / scale) - twice_edge + 0.5f); QString str = fm.elidedText(qsText, Qt::ElideRight, eliding_width); // use ellipsis as shortest possible string @@ -190,14 +191,15 @@ BasepointPixmap OverlayTextLine::createPixmap(unsigned int maxwidth, unsigned in } qpp = correction.map(qpp); - iCurWidth = iroundf(bb.width() * scale + 0.5f); - iCurHeight = height; + iCurWidth = static_cast< int >(bb.width() * scale + 0.5f); + iCurHeight = static_cast< int >(height); } QRectF qr = qpp.controlPointRect(); - return render(iroundf(qr.width() + twice_edge + 0.5f), iroundf(fAscent + fDescent + twice_edge + 0.5f), col, - QPoint(0, iroundf(fAscent + fEdge + 0.5f))); + return render(static_cast< int >(qr.width() + twice_edge + 0.5f), + static_cast< int >(fAscent + fDescent + twice_edge + 0.5f), col, + QPoint(0, static_cast< int >(fAscent + fEdge + 0.5f))); } void OverlayTextLine::setFont(const QFont &font) { diff --git a/src/mumble/OverlayUser.cpp b/src/mumble/OverlayUser.cpp index f9d15cc39c3..f3462027feb 100644 --- a/src/mumble/OverlayUser.cpp +++ b/src/mumble/OverlayUser.cpp @@ -58,16 +58,21 @@ void OverlayUser::setup() { qgpiBox->hide(); } -#undef SCALESIZE -#define SCALESIZE(var) \ - iroundf(uiSize * os->fZoom * os->qrf##var.width() + 0.5f), \ - iroundf(uiSize * os->fZoom * os->qrf##var.height() + 0.5f) +template< typename T > int roundToInt(T value) { + return static_cast< int >(value + 0.5f); +} + +template< typename T > unsigned int roundToUInt(T value) { + return static_cast< unsigned int >(value + 0.5f); +} void OverlayUser::updateLayout() { QPixmap pm; + const double scaleFactor = uiSize * os->fZoom; + if (scene()) - uiSize = iroundf(scene()->sceneRect().height() + 0.5); + uiSize = static_cast< unsigned int >(scene()->sceneRect().height() + 0.5); prepareGeometryChange(); @@ -80,7 +85,8 @@ void OverlayUser::updateLayout() { { QImageReader qir(QLatin1String("skin:muted_self.svg")); QSize sz = qir.size(); - sz.scale(SCALESIZE(MutedDeafened), Qt::KeepAspectRatio); + sz.scale(roundToInt(os->qrfMutedDeafened.width() * scaleFactor), + roundToInt(os->qrfMutedDeafened.height() * scaleFactor), Qt::KeepAspectRatio); qir.setScaledSize(sz); qgpiMuted->setPixmap(QPixmap::fromImage(qir.read())); } @@ -88,7 +94,8 @@ void OverlayUser::updateLayout() { { QImageReader qir(QLatin1String("skin:deafened_self.svg")); QSize sz = qir.size(); - sz.scale(SCALESIZE(MutedDeafened), Qt::KeepAspectRatio); + sz.scale(roundToInt(os->qrfMutedDeafened.width() * scaleFactor), + roundToInt(os->qrfMutedDeafened.height() * scaleFactor), Qt::KeepAspectRatio); qir.setScaledSize(sz); qgpiDeafened->setPixmap(QPixmap::fromImage(qir.read())); } @@ -155,13 +162,16 @@ void OverlayUser::updateLayout() { } void OverlayUser::updateUser() { + const double scaleFactor = uiSize * os->fZoom; + if (os->bUserName && (qgpiName[0]->pixmap().isNull() || (cuUser && (qsName != cuUser->qsName)))) { if (cuUser) qsName = cuUser->qsName; OverlayTextLine tl(qsName, os->qfUserName); - for (int i = 0; i < 4; ++i) { - const QPixmap &pm = tl.createPixmap(SCALESIZE(UserName), os->qcUserName[i]); + for (unsigned int i = 0; i < 4; ++i) { + const QPixmap &pm = tl.createPixmap(roundToUInt(os->qrfUserName.width() * scaleFactor), + roundToUInt(os->qrfUserName.height() * scaleFactor), os->qcUserName[i]); qgpiName[i]->setPixmap(pm); if (i == 0) @@ -176,8 +186,9 @@ void OverlayUser::updateUser() { if (cuUser) qsChannelName = cuUser->cChannel->qsName; - const QPixmap &pm = - OverlayTextLine(qsChannelName, os->qfChannel).createPixmap(SCALESIZE(Channel), os->qcChannel); + const QPixmap &pm = OverlayTextLine(qsChannelName, os->qfChannel) + .createPixmap(roundToUInt(os->qrfChannel.width() * scaleFactor), + roundToUInt(os->qrfChannel.height() * scaleFactor), os->qcChannel); qgpiChannel->setPixmap(pm); qgpiChannel->setPos(alignedPosition(scaledRect(os->qrfChannel, uiSize * os->fZoom), qgpiChannel->boundingRect(), os->qaChannel)); @@ -194,7 +205,8 @@ void OverlayUser::updateUser() { } else if (qbaAvatar.isNull()) { QImageReader qir(QLatin1String("skin:default_avatar.svg")); QSize sz = qir.size(); - sz.scale(SCALESIZE(Avatar), Qt::KeepAspectRatio); + sz.scale(roundToInt(os->qrfAvatar.width() * scaleFactor), roundToInt(os->qrfAvatar.height() * scaleFactor), + Qt::KeepAspectRatio); qir.setScaledSize(sz); img = qir.read(); } else { @@ -203,7 +215,8 @@ void OverlayUser::updateUser() { QImageReader qir(&qb, cuUser->qbaTextureFormat); QSize sz = qir.size(); - sz.scale(SCALESIZE(Avatar), Qt::KeepAspectRatio); + sz.scale(roundToInt(os->qrfAvatar.width() * scaleFactor), roundToInt(os->qrfAvatar.height() * scaleFactor), + Qt::KeepAspectRatio); qir.setScaledSize(sz); img = qir.read(); } @@ -283,7 +296,5 @@ QPointF OverlayUser::alignedPosition(const QRectF &box, const QRectF &item, Qt:: else if (a & Qt::AlignVCenter) yofs += hdiff * 0.5f; - return QPointF(iroundf(xofs + 0.5f), iroundf(yofs + 0.5f)); + return QPointF(static_cast< int >(xofs + 0.5f), static_cast< int >(yofs + 0.5f)); } - -#undef SCALESIZE diff --git a/src/mumble/OverlayUserGroup.cpp b/src/mumble/OverlayUserGroup.cpp index 92764672542..b1af3355103 100644 --- a/src/mumble/OverlayUserGroup.cpp +++ b/src/mumble/OverlayUserGroup.cpp @@ -183,7 +183,7 @@ void OverlayUserGroup::contextMenuEvent(QGraphicsSceneContextMenuEvent *e) { os->osSort = OverlaySettings::LastStateChange; updateUsers(); } else { - for (int i = 1; i <= 5; ++i) { + for (unsigned int i = 1; i <= 5; ++i) { if (act == qaColumns[i]) { os->uiColumns = i; updateLayout(); @@ -245,7 +245,7 @@ void OverlayUserGroup::updateLayout() { void OverlayUserGroup::updateUsers() { const QRectF &sr = scene()->sceneRect(); - unsigned int uiHeight = iroundf(sr.height() + 0.5f); + unsigned int uiHeight = static_cast< unsigned int >(sr.height() + 0.5f); QList< QGraphicsItem * > items; foreach (QGraphicsItem *qgi, childItems()) @@ -338,15 +338,15 @@ void OverlayUserGroup::updateUsers() { QRectF childrenBounds = os->qrfAvatar | os->qrfChannel | os->qrfMutedDeafened | os->qrfUserName; - int pad = os->bBox ? iroundf(uiHeight * os->fZoom * (os->fBoxPad + os->fBoxPenWidth) + 0.5f) : 0; - int width = iroundf(childrenBounds.width() * uiHeight * os->fZoom + 0.5f) + 2 * pad; - int height = iroundf(childrenBounds.height() * uiHeight * os->fZoom + 0.5f) + 2 * pad; + int pad = os->bBox ? static_cast< int >(uiHeight * os->fZoom * (os->fBoxPad + os->fBoxPenWidth) + 0.5f) : 0; + int width = static_cast< int >(childrenBounds.width() * uiHeight * os->fZoom + 0.5f) + 2 * pad; + int height = static_cast< int >(childrenBounds.height() * uiHeight * os->fZoom + 0.5f) + 2 * pad; - int xOffset = -iroundf(childrenBounds.left() * uiHeight * os->fZoom + 0.5f) + pad; - int yOffset = -iroundf(childrenBounds.top() * uiHeight * os->fZoom + 0.5f) + pad; + int xOffset = -static_cast< int >(childrenBounds.left() * uiHeight * os->fZoom + 0.5f) + pad; + int yOffset = -static_cast< int >(childrenBounds.top() * uiHeight * os->fZoom + 0.5f) + pad; - unsigned int yPos = 0; - unsigned int xPos = 0; + int yPos = 0; + int xPos = 0; foreach (OverlayUser *ou, users) { if (!ou->parentItem()) @@ -356,7 +356,7 @@ void OverlayUserGroup::updateUsers() { ou->updateUser(); ou->show(); - if (xPos >= (os->uiColumns - 1)) { + if (static_cast< unsigned int >(xPos) >= (os->uiColumns - 1)) { xPos = 0; ++yPos; } else { @@ -366,8 +366,10 @@ void OverlayUserGroup::updateUsers() { QRectF br = boundingRect< OverlayUser >(); - int basex = qBound< int >(0, iroundf(sr.width() * os->fX + 0.5f), iroundf(sr.width() - br.width() + 0.5f)); - int basey = qBound< int >(0, iroundf(sr.height() * os->fY + 0.5f), iroundf(sr.height() - br.height() + 0.5f)); + int basex = qBound< int >(0, static_cast< int >(sr.width() * os->fX + 0.5f), + static_cast< int >(sr.width() - br.width() + 0.5f)); + int basey = qBound< int >(0, static_cast< int >(sr.height() * os->fY + 0.5f), + static_cast< int >(sr.height() - br.height() + 0.5f)); setPos(basex, basey); } diff --git a/src/mumble/OverlayUserGroup.h b/src/mumble/OverlayUserGroup.h index 11c3dc60774..3c154b02ac7 100644 --- a/src/mumble/OverlayUserGroup.h +++ b/src/mumble/OverlayUserGroup.h @@ -13,7 +13,7 @@ class OverlayUser; class OverlayUserGroup : public QObject, public OverlayGroup { private: Q_OBJECT - Q_DISABLE_COPY(OverlayUserGroup); + Q_DISABLE_COPY(OverlayUserGroup) public: enum { Type = UserType + 3 }; diff --git a/src/mumble/Overlay_macx.mm b/src/mumble/Overlay_macx.mm index 90c9d7003d8..0a2ae2b0fcd 100644 --- a/src/mumble/Overlay_macx.mm +++ b/src/mumble/Overlay_macx.mm @@ -271,7 +271,7 @@ static bool isInstallerNewer(QString path, NSUInteger curVer) { goto out; } - QXmlStreamReader reader(QByteArray::fromRawData(data, size)); + QXmlStreamReader reader(QByteArray::fromRawData(data, static_cast(size))); while (! reader.atEnd()) { QXmlStreamReader::TokenType tok = reader.readNext(); if (tok == QXmlStreamReader::StartElement) { diff --git a/src/mumble/Overlay_win.cpp b/src/mumble/Overlay_win.cpp index 0f67bd5b0fb..8b285f2c277 100644 --- a/src/mumble/Overlay_win.cpp +++ b/src/mumble/Overlay_win.cpp @@ -217,9 +217,8 @@ void OverlayPrivateWin::onHelperProcessStarted() { qFatal("OverlayPrivateWin: unknown QProcess found in onHelperProcessStarted()."); } - PROCESS_INFORMATION *pi = helper->pid(); - qWarning("OverlayPrivateWin: overlay helper process '%s' started with PID %llu.", qPrintable(path), - static_cast< unsigned long long >(pi->dwProcessId)); + std::uint64_t processID = helper->processId(); + qWarning("OverlayPrivateWin: overlay helper process '%s' started with PID %llu.", qPrintable(path), processID); } void OverlayPrivateWin::onHelperProcessError(QProcess::ProcessError processError) { diff --git a/src/mumble/PAAudio.cpp b/src/mumble/PAAudio.cpp index 70cc7c3c7d6..069aca9c0ef 100644 --- a/src/mumble/PAAudio.cpp +++ b/src/mumble/PAAudio.cpp @@ -332,29 +332,30 @@ bool PortAudioSystem::stopStream(PaStream *stream) { return true; } -int PortAudioSystem::streamCallback(const void *input, void *output, unsigned long frames, +int PortAudioSystem::streamCallback(const void *inBuffer, void *outBuffer, unsigned long frames, const PaStreamCallbackTimeInfo *, PaStreamCallbackFlags, void *isInput) { if (isInput) { - auto const pai = dynamic_cast< PortAudioInput * >(Global::get().ai.get()); - if (!pai) { + auto const input = dynamic_cast< PortAudioInput * >(Global::get().ai.get()); + if (!input) { return paAbort; } - pai->process(frames, input); + input->process(static_cast< unsigned int >(frames), inBuffer); } else { - auto const pao = dynamic_cast< PortAudioOutput * >(Global::get().ao.get()); - if (!pao) { + auto const output = dynamic_cast< PortAudioOutput * >(Global::get().ao.get()); + if (!output) { return paAbort; } - pao->process(frames, output); + output->process(static_cast< unsigned int >(frames), outBuffer); } return paContinue; } PortAudioInput::PortAudioInput() : stream(nullptr) { - iMicChannels = pas->openStream(&stream, Global::get().s.iPortAudioInput, iFrameSize, true); + iMicChannels = + static_cast< unsigned int >(pas->openStream(&stream, Global::get().s.iPortAudioInput, iFrameSize, true)); if (!iMicChannels) { qWarning("PortAudioInput: failed to open stream"); return; @@ -405,7 +406,8 @@ void PortAudioInput::run() { } PortAudioOutput::PortAudioOutput() : stream(nullptr) { - iChannels = pas->openStream(&stream, Global::get().s.iPortAudioOutput, iFrameSize, false); + iChannels = + static_cast< unsigned int >(pas->openStream(&stream, Global::get().s.iPortAudioOutput, iFrameSize, false)); if (!iChannels) { qWarning("PortAudioOutput: failed to open stream"); return; diff --git a/src/mumble/PipeWire.cpp b/src/mumble/PipeWire.cpp index c206ab5bbb3..d986083b04b 100644 --- a/src/mumble/PipeWire.cpp +++ b/src/mumble/PipeWire.cpp @@ -72,7 +72,7 @@ const QList< audioDevice > PipeWireInputRegistrar::getDeviceChoices() { } void PipeWireInputRegistrar::setDeviceChoice(const QVariant &choice, Settings &settings) { - settings.pipeWireInput = choice.toUInt(); + settings.pipeWireInput = static_cast< std::uint8_t >(choice.toUInt()); } bool PipeWireInputRegistrar::canEcho(EchoCancelOptionID, const QString &) const { @@ -101,7 +101,7 @@ const QList< audioDevice > PipeWireOutputRegistrar::getDeviceChoices() { } void PipeWireOutputRegistrar::setDeviceChoice(const QVariant &choice, Settings &settings) { - settings.pipeWireOutput = choice.toUInt(); + settings.pipeWireOutput = static_cast< std::uint8_t >(choice.toUInt()); } bool PipeWireOutputRegistrar::usesOutputDelay() const { @@ -321,7 +321,7 @@ PipeWireInput::PipeWireInput() { SPEAKER_FRONT_RIGHT, }; - if (!m_engine->connect(PW_DIRECTION_INPUT, CHANNELS, iMicChannels)) { + if (!m_engine->connect(PW_DIRECTION_INPUT, CHANNELS, static_cast< std::uint8_t >(iMicChannels))) { return; } @@ -349,7 +349,7 @@ void PipeWireInput::processCallback(void *param) { return; } - pwi->addMic(data.data, data.chunk->size / sizeof(float)); + pwi->addMic(data.data, static_cast< unsigned int >(data.chunk->size / sizeof(float))); pwi->m_engine->queueBuffer(buffer); } @@ -378,7 +378,7 @@ PipeWireOutput::PipeWireOutput() { constexpr uint32_t CHANNELS[]{ SPEAKER_FRONT_LEFT, SPEAKER_FRONT_RIGHT, SPEAKER_LOW_FREQUENCY, SPEAKER_FRONT_CENTER, SPEAKER_BACK_LEFT, SPEAKER_BACK_RIGHT, SPEAKER_SIDE_LEFT, SPEAKER_SIDE_RIGHT }; - if (!m_engine->connect(PW_DIRECTION_OUTPUT, CHANNELS, iChannels)) { + if (!m_engine->connect(PW_DIRECTION_OUTPUT, CHANNELS, static_cast< std::uint8_t >(iChannels))) { return; } @@ -412,11 +412,11 @@ void PipeWireOutput::processCallback(void *param) { } chunk->offset = 0; - chunk->stride = sizeof(float) * pwo->iChannels; + chunk->stride = static_cast< int >(sizeof(float) * pwo->iChannels); - const uint32_t frames = std::min(data.maxsize / chunk->stride, pwo->iFrameSize); + const uint32_t frames = std::min(data.maxsize / static_cast< std::uint32_t >(chunk->stride), pwo->iFrameSize); - chunk->size = frames * chunk->stride; + chunk->size = frames * static_cast< unsigned int >(chunk->stride); if (!pwo->mix(data.data, frames)) { // When the mixer has no data available to write, we still need to push silence. // This is to avoid an infinite loop when destroying the stream. diff --git a/src/mumble/Plugin.cpp b/src/mumble/Plugin.cpp index 3e5cc3a9fcf..d1e6ba27327 100644 --- a/src/mumble/Plugin.cpp +++ b/src/mumble/Plugin.cpp @@ -57,7 +57,7 @@ Plugin::~Plugin() { } QString Plugin::extractWrappedString(MumbleStringWrapper wrapper) const { - QString wrappedString = QString::fromUtf8(wrapper.data, wrapper.size); + QString wrappedString = QString::fromUtf8(wrapper.data, static_cast< int >(wrapper.size)); if (wrapper.needsReleasing) { releaseResource(static_cast< const void * >(wrapper.data)); @@ -694,7 +694,7 @@ void Plugin::onKeyEvent(mumble_keycode_t keyCode, bool wasPress) const { } if (m_pluginFnc.onKeyEvent) { - m_pluginFnc.onKeyEvent(keyCode, wasPress); + m_pluginFnc.onKeyEvent(static_cast< std::uint32_t >(keyCode), wasPress); } } diff --git a/src/mumble/PluginInstaller.h b/src/mumble/PluginInstaller.h index 88b362e1070..3f054cd8755 100644 --- a/src/mumble/PluginInstaller.h +++ b/src/mumble/PluginInstaller.h @@ -33,8 +33,8 @@ class PluginInstallException : public QException { /// directory on the FileSystem. class PluginInstaller : public QDialog, public Ui::PluginInstaller { private: - Q_OBJECT; - Q_DISABLE_COPY(PluginInstaller); + Q_OBJECT + Q_DISABLE_COPY(PluginInstaller) protected: /// The file the installer has been invoked on diff --git a/src/mumble/PluginManager.cpp b/src/mumble/PluginManager.cpp index dbdd1e7854b..5aff76270bf 100644 --- a/src/mumble/PluginManager.cpp +++ b/src/mumble/PluginManager.cpp @@ -157,7 +157,8 @@ bool PluginManager::eventFilter(QObject *target, QEvent *event) { // them. However we want to process each event only once. if (!kEvent->isAutoRepeat() && !processedEvents.contains(kEvent)) { // Fire event - emit keyEvent(kEvent->key(), kEvent->modifiers(), kEvent->type() == QEvent::KeyPress); + emit keyEvent(static_cast< unsigned int >(kEvent->key()), kEvent->modifiers(), + kEvent->type() == QEvent::KeyPress); processedEvents << kEvent; @@ -655,8 +656,9 @@ void PluginManager::on_channelEntered(const Channel *newChannel, const Channel * foreachPlugin([user, newChannel, prevChannel, connectionID](Plugin &plugin) { if (plugin.isLoaded()) { - plugin.onChannelEntered(connectionID, user->uiSession, prevChannel ? prevChannel->iId : -1, - newChannel->iId); + plugin.onChannelEntered(connectionID, user->uiSession, + prevChannel ? static_cast< int >(prevChannel->iId) : -1, + static_cast< int >(newChannel->iId)); } }); } @@ -670,7 +672,7 @@ void PluginManager::on_channelExited(const Channel *channel, const User *user) c foreachPlugin([user, channel, connectionID](Plugin &plugin) { if (plugin.isLoaded()) { - plugin.onChannelExited(connectionID, user->uiSession, channel->iId); + plugin.onChannelExited(connectionID, user->uiSession, static_cast< int >(channel->iId)); } }); } @@ -750,7 +752,8 @@ void PluginManager::on_audioInput(short *inputPCM, unsigned int sampleCount, uns foreachPlugin([inputPCM, sampleCount, channelCount, sampleRate, isSpeech](Plugin &plugin) { if (plugin.isLoaded()) { - plugin.onAudioInput(inputPCM, sampleCount, channelCount, sampleRate, isSpeech); + plugin.onAudioInput(inputPCM, sampleCount, static_cast< std::uint16_t >(channelCount), sampleRate, + isSpeech); } }); } @@ -767,8 +770,8 @@ void PluginManager::on_audioSourceFetched(float *outputPCM, unsigned int sampleC foreachPlugin([outputPCM, sampleCount, channelCount, sampleRate, isSpeech, user](Plugin &plugin) { if (plugin.isLoaded()) { - plugin.onAudioSourceFetched(outputPCM, sampleCount, channelCount, sampleRate, isSpeech, - user ? user->uiSession : -1); + plugin.onAudioSourceFetched(outputPCM, sampleCount, static_cast< std::uint16_t >(channelCount), sampleRate, + isSpeech, user ? user->uiSession : static_cast< unsigned int >(-1)); } }); } @@ -781,7 +784,8 @@ void PluginManager::on_audioOutputAboutToPlay(float *outputPCM, unsigned int sam #endif foreachPlugin([outputPCM, sampleCount, channelCount, sampleRate, modifiedAudio](Plugin &plugin) { if (plugin.isLoaded()) { - if (plugin.onAudioOutputAboutToPlay(outputPCM, sampleCount, channelCount, sampleRate)) { + if (plugin.onAudioOutputAboutToPlay(outputPCM, sampleCount, static_cast< std::uint16_t >(channelCount), + sampleRate)) { *modifiedAudio = true; } } @@ -929,7 +933,8 @@ void PluginManager::on_syncPositionalData() { if (m_sentData.context != m_positionalData.m_context) { m_sentData.context = m_positionalData.m_context; - mpus.set_plugin_context(m_sentData.context.toUtf8().constData(), m_sentData.context.size()); + mpus.set_plugin_context(m_sentData.context.toUtf8().constData(), + static_cast< std::size_t >(m_sentData.context.size())); } if (m_sentData.identity != m_positionalData.m_identity) { m_sentData.identity = m_positionalData.m_identity; diff --git a/src/mumble/PluginManifest.cpp b/src/mumble/PluginManifest.cpp index b651a278412..6c2782fa679 100644 --- a/src/mumble/PluginManifest.cpp +++ b/src/mumble/PluginManifest.cpp @@ -21,7 +21,7 @@ void PluginManifest::parse(std::istream &input) { Poco::AutoPtr< Poco::XML::Document > doc; try { doc = parser.parse(&source); - } catch (const Poco::XML::SAXParseException &e) { + } catch (const Poco::XML::SAXParseException &) { throw PluginManifestException("Plugin manifest uses malformed XML"); } @@ -70,7 +70,8 @@ void PluginManifest::parse_v1_0_0(Poco::AutoPtr< Poco::XML::Document > document) Poco::AutoPtr< Poco::XML::NodeList > pluginNodes = assets->getElementsByTagName("plugin"); for (std::size_t i = 0; i < pluginNodes->length(); ++i) { - Poco::XML::Element *current = dynamic_cast< Poco::XML::Element * >(pluginNodes->item(i)); + Poco::XML::Element *current = + dynamic_cast< Poco::XML::Element * >(pluginNodes->item(static_cast< unsigned long >(i))); if (!current) { throw PluginManifestException("Plugin manifest uses \"plugin\" node of unexpected type"); } diff --git a/src/mumble/PluginManifest.h b/src/mumble/PluginManifest.h index e1860349c8b..9d90c9874df 100644 --- a/src/mumble/PluginManifest.h +++ b/src/mumble/PluginManifest.h @@ -16,8 +16,8 @@ namespace Poco { namespace XML { class Document; -}; // namespace XML -}; // namespace Poco +} // namespace XML +} // namespace Poco struct PluginManifestException : std::runtime_error { PluginManifestException(const std::string &msg = "") : std::runtime_error(msg) {} @@ -39,7 +39,7 @@ template<> struct hash< PluginRuntimeSpec > { return std::hash< std::string >()(spec.os) ^ (std::hash< std::string >()(spec.architecture) << 1); } }; -}; // namespace std +} // namespace std class PluginManifest { public: diff --git a/src/mumble/PluginUpdater.h b/src/mumble/PluginUpdater.h index 42dbe179e7d..9c83d2961fe 100644 --- a/src/mumble/PluginUpdater.h +++ b/src/mumble/PluginUpdater.h @@ -40,8 +40,8 @@ struct UpdateEntry { /// a Dialog that can be used to prompt the user whether certain updates should be updated. class PluginUpdater : public QDialog, public Ui::PluginUpdater { private: - Q_OBJECT; - Q_DISABLE_COPY(PluginUpdater); + Q_OBJECT + Q_DISABLE_COPY(PluginUpdater) protected: /// An atomic flag indicating whether the plugin update has been interrupted. It is used diff --git a/src/mumble/PositionalAudioViewer.cpp b/src/mumble/PositionalAudioViewer.cpp index 9036f10548c..ef35c34526f 100644 --- a/src/mumble/PositionalAudioViewer.cpp +++ b/src/mumble/PositionalAudioViewer.cpp @@ -28,19 +28,19 @@ void PositionalAudioViewer::update() { pluginManager->fetchPositionalData(); - const PositionalData &data = pluginManager->getPositionalData(); + const PositionalData &posData = pluginManager->getPositionalData(); - updatePlayer(data); - updateCamera(data); + updatePlayer(posData); + updateCamera(posData); - m_ui->context->setPlainText(data.getContext()); - m_ui->identity->setPlainText(data.getPlayerIdentity()); + m_ui->context->setPlainText(posData.getContext()); + m_ui->identity->setPlainText(posData.getPlayerIdentity()); } -void PositionalAudioViewer::updatePlayer(const PositionalData &data) { - const Position3D pos = data.getPlayerPos(); - const Vector3D dir = data.getPlayerDir(); - const Vector3D axis = data.getPlayerAxis(); +void PositionalAudioViewer::updatePlayer(const PositionalData &posData) { + const Position3D pos = posData.getPlayerPos(); + const Vector3D dir = posData.getPlayerDir(); + const Vector3D axis = posData.getPlayerAxis(); m_ui->playerPosX->setValue(pos.x); m_ui->playerPosY->setValue(pos.y); @@ -55,10 +55,10 @@ void PositionalAudioViewer::updatePlayer(const PositionalData &data) { m_ui->playerAxisZ->setValue(axis.z); } -void PositionalAudioViewer::updateCamera(const PositionalData &data) { - const Position3D pos = data.getCameraPos(); - const Vector3D dir = data.getCameraDir(); - const Vector3D axis = data.getCameraAxis(); +void PositionalAudioViewer::updateCamera(const PositionalData &posData) { + const Position3D pos = posData.getCameraPos(); + const Vector3D dir = posData.getCameraDir(); + const Vector3D axis = posData.getCameraAxis(); m_ui->cameraPosX->setValue(pos.x); m_ui->cameraPosY->setValue(pos.y); diff --git a/src/mumble/PositionalAudioViewer.h b/src/mumble/PositionalAudioViewer.h index f6a4c465c02..4854a474496 100644 --- a/src/mumble/PositionalAudioViewer.h +++ b/src/mumble/PositionalAudioViewer.h @@ -15,7 +15,7 @@ namespace Ui { class PositionalAudioViewer; -}; +} class PositionalAudioViewer : public QDialog { public: @@ -31,7 +31,7 @@ class PositionalAudioViewer : public QDialog { std::unique_ptr< Ui::PositionalAudioViewer > m_ui; private: - Q_OBJECT; + Q_OBJECT }; #endif diff --git a/src/mumble/PulseAudio.cpp b/src/mumble/PulseAudio.cpp index d931890311f..b7ef8872cd6 100644 --- a/src/mumble/PulseAudio.cpp +++ b/src/mumble/PulseAudio.cpp @@ -10,6 +10,9 @@ #include "User.h" #include "Global.h" +#include +#include + #ifdef Q_CC_GNU # define RESOLVE(var) \ { \ @@ -250,10 +253,10 @@ void PulseAudioSystem::eventCallback(pa_mainloop_api *api, pa_defer_event *) { const pa_sample_spec *pss = m_pulseAudio.stream_get_sample_spec(pasOutput); const size_t sampleSize = (pss->format == PA_SAMPLE_FLOAT32NE) ? sizeof(float) : sizeof(short); const unsigned int iBlockLen = pao->iFrameSize * pss->channels * static_cast< unsigned int >(sampleSize); - buff.tlength = iBlockLen * (Global::get().s.iOutputDelay + 1); + buff.tlength = iBlockLen * static_cast< unsigned int >(Global::get().s.iOutputDelay + 1); buff.minreq = iBlockLen; - buff.maxlength = -1; - buff.prebuf = -1; + buff.maxlength = static_cast< decltype(buff.maxlength) >(-1); + buff.prebuf = static_cast< decltype(buff.prebuf) >(-1); buff.fragsize = iBlockLen; iDelayCache = Global::get().s.iOutputDelay; @@ -309,14 +312,15 @@ void PulseAudioSystem::eventCallback(pa_mainloop_api *api, pa_defer_event *) { } else if (do_start) { qWarning("PulseAudio: Starting input %s", qPrintable(idev)); pa_buffer_attr buff; - const pa_sample_spec *pss = m_pulseAudio.stream_get_sample_spec(pasInput); - const size_t sampleSize = (pss->format == PA_SAMPLE_FLOAT32NE) ? sizeof(float) : sizeof(short); - const unsigned int iBlockLen = pai->iFrameSize * pss->channels * static_cast< unsigned int >(sampleSize); - buff.tlength = iBlockLen; - buff.minreq = iBlockLen; - buff.maxlength = -1; - buff.prebuf = -1; - buff.fragsize = iBlockLen; + const pa_sample_spec *pss = m_pulseAudio.stream_get_sample_spec(pasInput); + const size_t sampleSize = (pss->format == PA_SAMPLE_FLOAT32NE) ? sizeof(float) : sizeof(short); + const unsigned int iBlockLen = + static_cast< unsigned int >(static_cast< unsigned int >(pai->iFrameSize) * pss->channels * sampleSize); + buff.tlength = iBlockLen; + buff.minreq = iBlockLen; + buff.maxlength = static_cast< decltype(buff.maxlength) >(-1); + buff.prebuf = static_cast< decltype(buff.prebuf) >(-1); + buff.fragsize = iBlockLen; qsInputCache = idev; @@ -374,14 +378,15 @@ void PulseAudioSystem::eventCallback(pa_mainloop_api *api, pa_defer_event *) { } else if (do_start) { qWarning("PulseAudio: Starting echo: %s", qPrintable(edev)); pa_buffer_attr buff; - const pa_sample_spec *pss = m_pulseAudio.stream_get_sample_spec(pasSpeaker); - const size_t sampleSize = (pss->format == PA_SAMPLE_FLOAT32NE) ? sizeof(float) : sizeof(short); - const unsigned int iBlockLen = pai->iFrameSize * pss->channels * static_cast< unsigned int >(sampleSize); - buff.tlength = iBlockLen; - buff.minreq = iBlockLen; - buff.maxlength = -1; - buff.prebuf = -1; - buff.fragsize = iBlockLen; + const pa_sample_spec *pss = m_pulseAudio.stream_get_sample_spec(pasSpeaker); + const size_t sampleSize = (pss->format == PA_SAMPLE_FLOAT32NE) ? sizeof(float) : sizeof(short); + const unsigned int iBlockLen = + static_cast< unsigned int >(static_cast< unsigned int >(pai->iFrameSize) * pss->channels * sampleSize); + buff.tlength = iBlockLen; + buff.minreq = iBlockLen; + buff.maxlength = static_cast< decltype(buff.maxlength) >(-1); + buff.prebuf = static_cast< decltype(buff.prebuf) >(-1); + buff.fragsize = iBlockLen; bEchoMultiCache = (Global::get().s.echoOption == EchoCancelOptionID::SPEEX_MULTICHANNEL); qsEchoCache = edev; @@ -464,7 +469,7 @@ void PulseAudioSystem::sink_info_callback(pa_context *, const pa_sink_info *i, i return; } - pas->iSinkId = i->index; + pas->iSinkId = static_cast< int >(i->index); } void PulseAudioSystem::write_stream_callback(pa_stream *s, void *userdata) { @@ -578,9 +583,10 @@ void PulseAudioSystem::write_callback(pa_stream *s, size_t bytes, void *userdata // effectively removing the audio output completely until Mumble is restarted. // See: https://github.com/mumble-voip/mumble/issues/4883 // See: https://gitlab.freedesktop.org/pulseaudio/pulseaudio/-/issues/1132 - unsigned char buffer[bytes]; - memset(buffer, 0, sizeof(buffer)); - pa.stream_write(s, buffer, sizeof(buffer), nullptr, 0, PA_SEEK_RELATIVE); + static std::vector< std::uint8_t > m_silenceBuffer; + m_silenceBuffer.resize(bytes); + + pa.stream_write(s, m_silenceBuffer.data(), bytes, nullptr, 0, PA_SEEK_RELATIVE); return; } @@ -595,7 +601,8 @@ void PulseAudioSystem::write_callback(pa_stream *s, size_t bytes, void *userdata pao->eSampleFormat = PulseAudioOutput::SampleShort; pao->iMixerFreq = pss->rate; pao->iChannels = pss->channels; - unsigned int chanmasks[pss->channels]; + static std::vector< unsigned int > chanmasks; + chanmasks.resize(pss->channels); for (int i = 0; i < pss->channels; ++i) { unsigned int cm = 0; switch (pcm->map[i]) { @@ -636,24 +643,23 @@ void PulseAudioSystem::write_callback(pa_stream *s, size_t bytes, void *userdata cm = 0; break; } - chanmasks[i] = cm; + chanmasks[static_cast< std::size_t >(i)] = cm; } - pao->initializeMixer(chanmasks); + pao->initializeMixer(chanmasks.data()); } const unsigned int iSampleSize = pao->iSampleSize; const unsigned int samples = static_cast< unsigned int >(bytes) / iSampleSize; bool oldAttenuation = pas->bAttenuating; - unsigned char buffer[bytes]; + static std::vector< unsigned char > buffer; + buffer.resize(bytes); // do we have some mixed output? - if (pao->mix(buffer, samples)) { + if (pao->mix(buffer.data(), samples)) { // attenuate if instructed to or it's in settings pas->bAttenuating = (Global::get().bAttenuateOthers || Global::get().s.bAttenuateOthers); } else { - memset(buffer, 0, bytes); - // attenuate if intructed to (self-activated) pas->bAttenuating = Global::get().bAttenuateOthers; } @@ -663,7 +669,7 @@ void PulseAudioSystem::write_callback(pa_stream *s, size_t bytes, void *userdata pas->setVolumes(); } - pa.stream_write(s, buffer, iSampleSize * samples, nullptr, 0, PA_SEEK_RELATIVE); + pa.stream_write(s, buffer.data(), iSampleSize * samples, nullptr, 0, PA_SEEK_RELATIVE); } void PulseAudioSystem::volume_sink_input_list_callback(pa_context *c, const pa_sink_input_info *i, int eol, diff --git a/src/mumble/QtWidgetUtils.cpp b/src/mumble/QtWidgetUtils.cpp index 490f52328fc..e6afab65423 100644 --- a/src/mumble/QtWidgetUtils.cpp +++ b/src/mumble/QtWidgetUtils.cpp @@ -41,9 +41,9 @@ namespace QtUtils { const QString elidedPostfix = "..."; QFontMetrics metric(doc.defaultFont()); #if QT_VERSION >= QT_VERSION_CHECK(5, 11, 0) - uint32_t postfixWidth = metric.horizontalAdvance(elidedPostfix); + uint32_t postfixWidth = static_cast< std::uint32_t >(metric.horizontalAdvance(elidedPostfix)); #else - uint32_t postfixWidth = metric.width(elidedPostfix); + uint32_t postfixWidth = static_cast< std::uint32_t >(metric.width(elidedPostfix)); #endif while (doc.size().width() > std::max(width - postfixWidth, static_cast< uint32_t >(0))) { @@ -55,5 +55,5 @@ namespace QtUtils { } } -}; // namespace QtUtils -}; // namespace Mumble +} // namespace QtUtils +} // namespace Mumble diff --git a/src/mumble/QtWidgetUtils.h b/src/mumble/QtWidgetUtils.h index 794793af5a6..6e022400931 100644 --- a/src/mumble/QtWidgetUtils.h +++ b/src/mumble/QtWidgetUtils.h @@ -28,7 +28,7 @@ namespace QtUtils { void elideText(QTextDocument &doc, uint32_t width); -}; // namespace QtUtils -}; // namespace Mumble +} // namespace QtUtils +} // namespace Mumble #endif // MUMBLE_MUMBLE_QTWIDGETUTILS_H_ diff --git a/src/mumble/RichTextEditor.cpp b/src/mumble/RichTextEditor.cpp index 8362fe5b440..b00bc5d3b23 100644 --- a/src/mumble/RichTextEditor.cpp +++ b/src/mumble/RichTextEditor.cpp @@ -34,9 +34,9 @@ static QString decodeMimeString(const QByteArray &src) { if (src.isEmpty()) return QString(); - if ((src.length() >= 4) && ((src.length() % sizeof(ushort)) == 0)) { + if ((src.length() >= 4) && ((static_cast< std::size_t >(src.length()) % sizeof(ushort)) == 0)) { const ushort *ptr = reinterpret_cast< const ushort * >(src.constData()); - int len = static_cast< int >(src.length() / sizeof(ushort)); + int len = static_cast< int >(static_cast< std::size_t >(src.length()) / sizeof(ushort)); if ((ptr[0] > 0) && (ptr[0] < 0x7f) && (ptr[1] > 0) && (ptr[1] < 0x7f)) { while (len && (ptr[len - 1] == 0)) --len; @@ -44,16 +44,25 @@ static QString decodeMimeString(const QByteArray &src) { } } +#ifdef _MSVC_LANG +# pragma warning(push) + // Disable warning about this if condition being constant + // TODO: Use if constexpr as soon as we have moved to C++17 (or higher) +# pragma warning(disable : 4127) +#endif if ((sizeof(wchar_t) != sizeof(ushort)) && (src.length() >= static_cast< int >(sizeof(wchar_t))) - && ((src.length() % sizeof(wchar_t)) == 0)) { + && ((static_cast< std::size_t >(src.length()) % sizeof(wchar_t)) == 0)) { const wchar_t *ptr = reinterpret_cast< const wchar_t * >(src.constData()); - int len = static_cast< int >(src.length() / sizeof(wchar_t)); + int len = static_cast< int >(static_cast< std::size_t >(src.length()) / sizeof(wchar_t)); if (*ptr < 0x7f) { while (len && (ptr[len - 1] == 0)) --len; return QString::fromWCharArray(ptr, len); } } +#ifdef _MSVC_LANG +# pragma warning(pop) +#endif const char *ptr = src.constData(); int len = src.length(); while (len && (ptr[len - 1] == 0)) @@ -283,7 +292,7 @@ void RichTextEditor::on_qteRichText_textChanged() { bool over = true; - unsigned int imagelength = plainText.length(); + unsigned int imagelength = static_cast< unsigned int >(plainText.length()); if (Global::get().uiMessageLength && imagelength <= Global::get().uiMessageLength) { diff --git a/src/mumble/Screen.cpp b/src/mumble/Screen.cpp index c930b6eaacc..1777f973b3e 100644 --- a/src/mumble/Screen.cpp +++ b/src/mumble/Screen.cpp @@ -63,5 +63,5 @@ namespace Screen { #endif } -}; // namespace Screen -}; // namespace Mumble +} // namespace Screen +} // namespace Mumble diff --git a/src/mumble/Screen.h b/src/mumble/Screen.h index 6365cb4bf68..3991ecd8a80 100644 --- a/src/mumble/Screen.h +++ b/src/mumble/Screen.h @@ -18,8 +18,8 @@ namespace Screen { QWindow *windowFromWidget(const QWidget &widget); QScreen *screenFromWidget(const QWidget &widget); QScreen *screenAt(const QPoint &point); -}; // namespace Screen +} // namespace Screen -}; // namespace Mumble +} // namespace Mumble #endif diff --git a/src/mumble/SearchDialog.cpp b/src/mumble/SearchDialog.cpp index dd1ac8a67c0..670e298b0d3 100644 --- a/src/mumble/SearchDialog.cpp +++ b/src/mumble/SearchDialog.cpp @@ -51,7 +51,7 @@ QString SearchDialog::toString(ChannelAction action) { } class SearchResultItem : public QTreeWidgetItem { - Q_DISABLE_COPY(SearchResultItem); + Q_DISABLE_COPY(SearchResultItem) public: template< typename parent_t > @@ -88,7 +88,7 @@ class SearchResultItem : public QTreeWidgetItem { }; class ChannelItem : public QTreeWidgetItem { - Q_DISABLE_COPY(ChannelItem); + Q_DISABLE_COPY(ChannelItem) public: template< typename parent_t > @@ -101,10 +101,10 @@ class ChannelItem : public QTreeWidgetItem { setTextAlignment(NAME_COLUMN, Qt::AlignLeft | Qt::AlignVCenter); } - int getChannelID() const { return m_chanID; } + unsigned int getChannelID() const { return m_chanID; } private: - int m_chanID; + unsigned int m_chanID; }; SearchDialog::SearchDialog(QWidget *parent) : QWidget(parent), m_itemDelegate(new SearchDialogItemDelegate()) { @@ -140,7 +140,7 @@ SearchDialog::SearchDialog(QWidget *parent) : QWidget(parent), m_itemDelegate(ne searchResultTree->header()->hide(); QFontMetrics metric(searchResultTree->font()); - searchResultTree->header()->resizeSection(0, metric.height() * 1.2); + searchResultTree->header()->resizeSection(0, static_cast< int >(metric.height() * 1.2)); searchResultTree->setIconSize(QSize(metric.ascent(), metric.ascent())); if (Global::get().mw) { @@ -228,7 +228,7 @@ void SearchDialog::on_searchResultTree_currentItemChanged(QTreeWidgetItem *c, QT Global::get().mw->pmModel->setSelectedUser(user->uiSession); } } else { - const Channel *channel = Channel::get(static_cast< int >(item.getID())); + const Channel *channel = Channel::get(item.getID()); if (channel) { // Only try to select the channel if it still exists @@ -377,7 +377,7 @@ void SearchDialog::search(const QString &searchTerm) { if (searchChannels) { QReadLocker userLock(&Channel::c_qrwlChannels); - QHash< int, Channel * >::const_iterator it = Channel::c_qhChannels.constBegin(); + QHash< unsigned int, Channel * >::const_iterator it = Channel::c_qhChannels.constBegin(); while (it != Channel::c_qhChannels.constEnd()) { const Channel *currentChannel = it.value(); @@ -419,7 +419,7 @@ void SearchDialog::on_clientDisconnected(unsigned int userSession) { removeSearchResult(userSession, true); } -void SearchDialog::on_channelRemoved(int channelID) { +void SearchDialog::on_channelRemoved(unsigned int channelID) { removeSearchResult(channelID, false); } @@ -505,7 +505,7 @@ void SearchDialog::keyPressEvent(QKeyEvent *event) { || event->key() == Qt::Key_PageDown) { QKeyEvent *copy = new QKeyEvent(event->type(), event->key(), event->modifiers(), event->nativeScanCode(), event->nativeVirtualKey(), event->nativeScanCode(), event->text(), - event->isAutoRepeat(), event->count()); + event->isAutoRepeat(), static_cast< ushort >(event->count())); m_relayedKeyEvents.insert(copy); @@ -597,4 +597,4 @@ bool SearchDialog::removeSearchResult(unsigned int id, bool isUser) { return false; } -}; // namespace Search +} // namespace Search diff --git a/src/mumble/SearchDialog.h b/src/mumble/SearchDialog.h index 7ddc7ce1825..ac7683cf670 100644 --- a/src/mumble/SearchDialog.h +++ b/src/mumble/SearchDialog.h @@ -86,8 +86,8 @@ using SearchResultMap = std::map< SearchResult, unsigned int, SearchResultSortCo * The search result class is the one that pops up when triggering the search functionality */ class SearchDialog : public QWidget, private Ui::SearchDialog { - Q_OBJECT; - Q_DISABLE_COPY(SearchDialog); + Q_OBJECT + Q_DISABLE_COPY(SearchDialog) public: SearchDialog(QWidget *parent = nullptr); @@ -123,7 +123,7 @@ public slots: void on_serverConnectionSynchronized(); void on_serverDisconnected(); void on_clientDisconnected(unsigned int userSession); - void on_channelRemoved(int channelID); + void on_channelRemoved(unsigned int channelID); private: MultiStyleWidgetWrapper m_searchFieldStyleWrapper; @@ -139,9 +139,9 @@ public slots: bool removeSearchResult(unsigned int id, bool isUser); }; -}; // namespace Search +} // namespace Search -Q_DECLARE_METATYPE(Search::SearchDialog::UserAction); -Q_DECLARE_METATYPE(Search::SearchDialog::ChannelAction); +Q_DECLARE_METATYPE(Search::SearchDialog::UserAction) +Q_DECLARE_METATYPE(Search::SearchDialog::ChannelAction) #endif // MUMBLE_MUMBLE_SEARCHDIALOG_H_ diff --git a/src/mumble/ServerHandler.cpp b/src/mumble/ServerHandler.cpp index 22e03cfd138..fe590960f65 100644 --- a/src/mumble/ServerHandler.cpp +++ b/src/mumble/ServerHandler.cpp @@ -290,7 +290,8 @@ void ServerHandler::handleVoicePacket(const Mumble::Protocol::AudioData &audioDa } void ServerHandler::sendMessage(const unsigned char *data, int len, bool force) { - STACKVAR(unsigned char, crypto, len + 4); + static std::vector< unsigned char > crypto; + crypto.resize(static_cast< std::size_t >(len + 4)); QMutexLocker qml(&qmUdp); @@ -309,15 +310,16 @@ void ServerHandler::sendMessage(const unsigned char *data, int len, bool force) *reinterpret_cast< quint16 * >(&uc[0]) = qToBigEndian(static_cast< quint16 >(Mumble::Protocol::TCPMessageType::UDPTunnel)); *reinterpret_cast< quint32 * >(&uc[2]) = qToBigEndian(static_cast< quint32 >(len)); - memcpy(uc + 6, data, len); + memcpy(uc + 6, data, static_cast< std::size_t >(len)); QApplication::postEvent(this, new ServerHandlerMessageEvent(qba, Mumble::Protocol::TCPMessageType::UDPTunnel, true)); } else { - if (!connection->csCrypt->encrypt(reinterpret_cast< const unsigned char * >(data), crypto, len)) { + if (!connection->csCrypt->encrypt(reinterpret_cast< const unsigned char * >(data), crypto.data(), + static_cast< unsigned int >(len))) { return; } - qusUdp->writeDatagram(reinterpret_cast< const char * >(crypto), len + 4, qhaRemote, usResolvedPort); + qusUdp->writeDatagram(reinterpret_cast< const char * >(crypto.data()), len + 4, qhaRemote, usResolvedPort); } } @@ -588,7 +590,7 @@ void ServerHandler::sendPingInternal() { m_udpPingEncoder.setProtocolVersion(m_version); gsl::span< const Mumble::Protocol::byte > encodedPacket = m_udpPingEncoder.encodePingPacket(pingData); - sendMessage(encodedPacket.data(), encodedPacket.size(), true); + sendMessage(encodedPacket.data(), static_cast< int >(encodedPacket.size()), true); } MumbleProto::Ping mpp; @@ -604,13 +606,13 @@ void ServerHandler::sendPingInternal() { mpp.set_udp_ping_avg(static_cast< float >(boost::accumulators::mean(accUDP))); mpp.set_udp_ping_var(static_cast< float >(boost::accumulators::variance(accUDP))); } - mpp.set_udp_packets(static_cast< int >(boost::accumulators::count(accUDP))); + mpp.set_udp_packets(static_cast< unsigned int >(boost::accumulators::count(accUDP))); if (boost::accumulators::count(accTCP)) { mpp.set_tcp_ping_avg(static_cast< float >(boost::accumulators::mean(accTCP))); mpp.set_tcp_ping_var(static_cast< float >(boost::accumulators::variance(accTCP))); } - mpp.set_tcp_packets(static_cast< int >(boost::accumulators::count(accTCP))); + mpp.set_tcp_packets(static_cast< unsigned int >(boost::accumulators::count(accTCP))); sendMessage(mpp); @@ -910,11 +912,11 @@ void ServerHandler::joinChannel(unsigned int uiSession, unsigned int channel, sendMessage(mpus); } -void ServerHandler::startListeningToChannel(int channel) { +void ServerHandler::startListeningToChannel(unsigned int channel) { startListeningToChannels({ channel }); } -void ServerHandler::startListeningToChannels(const QList< int > &channelIDs) { +void ServerHandler::startListeningToChannels(const QList< unsigned int > &channelIDs) { if (channelIDs.isEmpty()) { return; } @@ -922,7 +924,7 @@ void ServerHandler::startListeningToChannels(const QList< int > &channelIDs) { MumbleProto::UserState mpus; mpus.set_session(Global::get().uiSession); - foreach (int currentChannel, channelIDs) { + for (unsigned int currentChannel : channelIDs) { // The naming of the function is a bit unfortunate but what this does is to add // the channel ID to the message field listening_channel_add mpus.add_listening_channel_add(currentChannel); @@ -931,11 +933,11 @@ void ServerHandler::startListeningToChannels(const QList< int > &channelIDs) { sendMessage(mpus); } -void ServerHandler::stopListeningToChannel(int channel) { +void ServerHandler::stopListeningToChannel(unsigned int channel) { stopListeningToChannels({ channel }); } -void ServerHandler::stopListeningToChannels(const QList< int > &channelIDs) { +void ServerHandler::stopListeningToChannels(const QList< unsigned int > &channelIDs) { if (channelIDs.isEmpty()) { return; } @@ -943,7 +945,7 @@ void ServerHandler::stopListeningToChannels(const QList< int > &channelIDs) { MumbleProto::UserState mpus; mpus.set_session(Global::get().uiSession); - foreach (int currentChannel, channelIDs) { + for (unsigned int currentChannel : channelIDs) { // The naming of the function is a bit unfortunate but what this does is to add // the channel ID to the message field listening_channel_remove mpus.add_listening_channel_remove(currentChannel); @@ -958,7 +960,7 @@ void ServerHandler::createChannel(unsigned int parent_id, const QString &name, c mpcs.set_parent(parent_id); mpcs.set_name(u8(name)); mpcs.set_description(u8(description)); - mpcs.set_position(position); + mpcs.set_position(static_cast< int >(position)); mpcs.set_temporary(temporary); mpcs.set_max_users(maxUsers); sendMessage(mpcs); diff --git a/src/mumble/ServerHandler.h b/src/mumble/ServerHandler.h index 82f5dd3a08a..d64745f9c86 100644 --- a/src/mumble/ServerHandler.h +++ b/src/mumble/ServerHandler.h @@ -155,10 +155,10 @@ class ServerHandler : public QThread { void requestUserStats(unsigned int uiSession, bool statsOnly); void joinChannel(unsigned int uiSession, unsigned int channel); void joinChannel(unsigned int uiSession, unsigned int channel, const QStringList &temporaryAccessTokens); - void startListeningToChannel(int channel); - void startListeningToChannels(const QList< int > &channelIDs); - void stopListeningToChannel(int channel); - void stopListeningToChannels(const QList< int > &channelIDs); + void startListeningToChannel(unsigned int channel); + void startListeningToChannels(const QList< unsigned int > &channelIDs); + void stopListeningToChannel(unsigned int channel); + void stopListeningToChannels(const QList< unsigned int > &channelIDs); void createChannel(unsigned int parent_id, const QString &name, const QString &description, unsigned int position, bool temporary, unsigned int maxUsers); void requestBanList(); diff --git a/src/mumble/ServerInformation.cpp b/src/mumble/ServerInformation.cpp index 14ec4487dcc..822130c9d04 100644 --- a/src/mumble/ServerInformation.cpp +++ b/src/mumble/ServerInformation.cpp @@ -82,8 +82,8 @@ static const QString currentCodec() { void ServerInformation::updateAudioBandwidth() { // The bandwidths are in bit/s, so we divide by 1000 to get kBit/s - const float maxBandwidthAllowed = Global::get().iMaxBandwidth / 1000.0f; - const float currentBandwidth = Global::get().iAudioBandwidth / 1000.0f; + const float maxBandwidthAllowed = static_cast< float >(Global::get().iMaxBandwidth) / 1000.0f; + const float currentBandwidth = static_cast< float >(Global::get().iAudioBandwidth) / 1000.0f; audio_current->setText(QString::fromLatin1("%1 kBit/s").arg(currentBandwidth, 0, 'f', 1)); audio_allowed->setText(QString::fromLatin1("%1 kBit/s").arg(maxBandwidthAllowed, 0, 'f', 1)); @@ -117,8 +117,9 @@ void ServerInformation::updateConnectionDetails() { connection_udp_statisticsGroup->show(); // Actually fill in data - const float latency = boost::accumulators::mean(Global::get().sh->accUDP); - const float deviation = std::sqrt(boost::accumulators::variance(Global::get().sh->accUDP)); + const float latency = static_cast< float >(boost::accumulators::mean(Global::get().sh->accUDP)); + const float deviation = + static_cast< float >(std::sqrt(boost::accumulators::variance(Global::get().sh->accUDP))); connection_udp_encryption->setText("128 bit OCB-AES128"); connection_udp_latency->setText(latencyString.arg(latency, 0, 'f', 1).arg(deviation, 0, 'f', 1)); @@ -128,8 +129,8 @@ void ServerInformation::updateConnectionDetails() { // TCP - const float latency = boost::accumulators::mean(Global::get().sh->accTCP); - const float deviation = std::sqrt(boost::accumulators::variance(Global::get().sh->accTCP)); + const float latency = static_cast< float >(boost::accumulators::mean(Global::get().sh->accTCP)); + const float deviation = static_cast< float >(std::sqrt(boost::accumulators::variance(Global::get().sh->accTCP))); QSslCipher cipher = Global::get().sh->qscCipher; diff --git a/src/mumble/ServerInformation.h b/src/mumble/ServerInformation.h index 41dfd86ed19..b9cc27f7e31 100644 --- a/src/mumble/ServerInformation.h +++ b/src/mumble/ServerInformation.h @@ -13,8 +13,8 @@ class Connection; class ServerInformation : public QDialog, private Ui::ServerInformation { - Q_OBJECT; - Q_DISABLE_COPY(ServerInformation); + Q_OBJECT + Q_DISABLE_COPY(ServerInformation) public: ServerInformation(QWidget *parent = nullptr); diff --git a/src/mumble/Settings.cpp b/src/mumble/Settings.cpp index 99473cec26e..d935b7d2582 100644 --- a/src/mumble/Settings.cpp +++ b/src/mumble/Settings.cpp @@ -98,7 +98,7 @@ quint32 qHash(const ShortcutTarget &t) { foreach (unsigned int u, t.qlSessions) h ^= u; } else { - h ^= t.iChannel; + h ^= static_cast< unsigned int >(t.iChannel); if (t.bLinks) h ^= 0x80000000; if (t.bChildren) @@ -110,7 +110,7 @@ quint32 qHash(const ShortcutTarget &t) { } quint32 qHash(const QList< ShortcutTarget > &l) { - quint32 h = l.count(); + quint32 h = static_cast< quint32 >(l.count()); foreach (const ShortcutTarget &st, l) h ^= qHash(st); return h; @@ -219,7 +219,7 @@ void Settings::save() const { void Settings::load(const QString &path) { if (path.endsWith(QLatin1String(BACKUP_FILE_EXTENSION))) { // Trim away the backup extension - settingsLocation = path.left(path.size() - std::strlen(BACKUP_FILE_EXTENSION)); + settingsLocation = path.left(path.size() - static_cast< int >(std::strlen(BACKUP_FILE_EXTENSION))); } else { settingsLocation = path; } @@ -268,7 +268,7 @@ void Settings::load(const QString &path) { "If you experience repeated crashes with these settings, you might have to manually delete the " "settings files at
%1
and
%2
in order to reset all settings to their " "default value.") - .arg(path.left(path.size() - std::strlen(BACKUP_FILE_EXTENSION))) + .arg(path.left(path.size() - static_cast< int >(std::strlen(BACKUP_FILE_EXTENSION)))) .arg(path)); msgBox.setIcon(QMessageBox::Warning); msgBox.exec(); @@ -351,9 +351,9 @@ QDataStream &operator>>(QDataStream &qds, ShortcutTarget &st) { buf[i] = 0; } - int read = device->peek(buf, sizeof(buf)); + qint64 read = device->peek(buf, sizeof(buf)); - for (int i = 0; i < read; i++) { + for (unsigned int i = 0; i < read; i++) { if (buf[i] >= 31) { if (buf[i] == 'v') { qds >> versionString; @@ -713,8 +713,8 @@ void OverlaySettings::legacyLoad(QSettings *settings_ptr) { LOAD(uiColumns, "columns"); settings_ptr->beginReadArray(QLatin1String("states")); - for (int i = 0; i < 4; ++i) { - settings_ptr->setArrayIndex(i); + for (unsigned int i = 0; i < 4; ++i) { + settings_ptr->setArrayIndex(static_cast< int >(i)); LOAD(qcUserName[i], "color"); LOAD(fUser[i], "opacity"); } @@ -1150,8 +1150,9 @@ void Settings::legacyLoad(const QString &path) { if (iIdleTime == 5 * 60) { // New default iaeIdleAction = Settings::Nothing; } else { - iIdleTime = 60 * qRound(Global::get().s.iIdleTime / 60.); // Round to minutes - iaeIdleAction = Settings::Deafen; // Old behavior + iIdleTime = + static_cast< unsigned int >(60 * qRound(Global::get().s.iIdleTime / 60.)); // Round to minutes + iaeIdleAction = Settings::Deafen; // Old behavior } // Fallthrough #ifdef Q_OS_WIN diff --git a/src/mumble/Settings.h b/src/mumble/Settings.h index f07af40f419..09b37d69388 100644 --- a/src/mumble/Settings.h +++ b/src/mumble/Settings.h @@ -55,10 +55,10 @@ struct Shortcut { }; struct ChannelTarget { - int channelID = Channel::ROOT_ID; + unsigned int channelID = Channel::ROOT_ID; ChannelTarget() = default; - ChannelTarget(int id) : channelID(id) {} + ChannelTarget(unsigned int id) : channelID(id) {} friend bool operator==(const ChannelTarget &lhs, const ChannelTarget &rhs); friend bool operator<(const ChannelTarget &lhs, const ChannelTarget &rhs); diff --git a/src/mumble/SettingsKeys.h b/src/mumble/SettingsKeys.h index 33ced19a329..9fa29647d1f 100644 --- a/src/mumble/SettingsKeys.h +++ b/src/mumble/SettingsKeys.h @@ -343,6 +343,6 @@ const SettingsKey SETTINGS_VERSION_KEY = { "settings_version" }; const SettingsKey CERTIFICATE_KEY = { "certificate" }; const SettingsKey MUMBLE_QUIT_NORMALLY_KEY = { "mumble_has_quit_normally" }; -}; // namespace SettingsKeys +} // namespace SettingsKeys #endif // MUMBLE_MUMBLE_SETTINGSKEYS_H_ diff --git a/src/mumble/TalkingUI.cpp b/src/mumble/TalkingUI.cpp index b08e34da929..a39dd073f73 100644 --- a/src/mumble/TalkingUI.cpp +++ b/src/mumble/TalkingUI.cpp @@ -60,7 +60,7 @@ std::unique_ptr< TalkingUIContainer > TalkingUI::removeContainer(int associatedC if (index >= 0) { // Move the container out of the vector - container = std::move(m_containers[index]); + container = std::move(m_containers[static_cast< std::size_t >(index)]); m_containers.erase(m_containers.begin() + index); // If the container is currently selected, clear the selection @@ -143,8 +143,8 @@ void TalkingUI::addListener(const ClientUser *user, const Channel *channel) { // First make sure the channel exists addChannel(channel); - std::unique_ptr< TalkingUIContainer > &channelContainer = - m_containers[findContainer(channel->iId, ContainerType::CHANNEL)]; + std::unique_ptr< TalkingUIContainer > &channelContainer = m_containers[static_cast< std::size_t >( + findContainer(static_cast< int >(channel->iId), ContainerType::CHANNEL))]; std::unique_ptr< TalkingUIChannelListener > listenerEntry = std::make_unique< TalkingUIChannelListener >(*user, *channel); @@ -155,11 +155,12 @@ void TalkingUI::addListener(const ClientUser *user, const Channel *channel) { } } -TalkingUIChannelListener *TalkingUI::findListener(unsigned int userSession, int channelID) { - int channelIndex = findContainer(channelID, ContainerType::CHANNEL); +TalkingUIChannelListener *TalkingUI::findListener(unsigned int userSession, unsigned int channelID) { + int channelIndex = findContainer(static_cast< int >(channelID), ContainerType::CHANNEL); if (channelIndex >= 0) { - std::unique_ptr< TalkingUIContainer > &channelContainer = m_containers[channelIndex]; + std::unique_ptr< TalkingUIContainer > &channelContainer = + m_containers[static_cast< std::size_t >(channelIndex)]; TalkingUIEntry *entry = channelContainer->get(userSession, EntryType::LISTENER); @@ -171,7 +172,7 @@ TalkingUIChannelListener *TalkingUI::findListener(unsigned int userSession, int return nullptr; } -void TalkingUI::removeListener(unsigned int userSession, int channelID) { +void TalkingUI::removeListener(unsigned int userSession, unsigned int channelID) { TalkingUIChannelListener *listenerEntry = findListener(userSession, channelID); if (listenerEntry) { @@ -328,7 +329,7 @@ QString createChannelName(const Channel *chan, bool abbreviateName, int minPrefi } void TalkingUI::addChannel(const Channel *channel) { - if (findContainer(channel->iId, ContainerType::CHANNEL) < 0) { + if (findContainer(static_cast< int >(channel->iId), ContainerType::CHANNEL) < 0) { // Create a QGroupBox for this channel const QString channelName = createChannelName( channel, Global::get().s.bTalkingUI_AbbreviateChannelNames, Global::get().s.iTalkingUI_PrefixCharCount, @@ -380,12 +381,13 @@ TalkingUIUser *TalkingUI::findOrAddUser(const ClientUser *user) { // Create an entry for this user bool isSelf = Global::get().uiSession == user->uiSession; - int channelIndex = findContainer(user->cChannel->iId, ContainerType::CHANNEL); + int channelIndex = findContainer(static_cast< int >(user->cChannel->iId), ContainerType::CHANNEL); if (channelIndex < 0) { qCritical("TalkingUI::findOrAddUser User's channel does not exist!"); return nullptr; } - std::unique_ptr< TalkingUIContainer > &channelContainer = m_containers[channelIndex]; + std::unique_ptr< TalkingUIContainer > &channelContainer = + m_containers[static_cast< std::size_t >(channelIndex)]; if (!channelContainer) { qCritical("TalkingUI::findOrAddUser requesting unknown channel!"); return nullptr; @@ -395,7 +397,7 @@ TalkingUIUser *TalkingUI::findOrAddUser(const ClientUser *user) { TalkingUIUser *newUserEntry = userEntry.get(); // * 1000 as the setting is in seconds whereas the timer expects milliseconds - userEntry->setLifeTime(Global::get().s.iTalkingUI_SilentUserLifeTime * 1000); + userEntry->setLifeTime(static_cast< unsigned int >(Global::get().s.iTalkingUI_SilentUserLifeTime) * 1000); bool isLocalUserAndLocalUserAlwaysVisible = isSelf && Global::get().s.bTalkingUI_LocalUserStaysVisible; bool usersAlwaysVisible = Global::get().s.talkingUI_UsersAlwaysVisible; @@ -428,15 +430,15 @@ TalkingUIUser *TalkingUI::findOrAddUser(const ClientUser *user) { } } -void TalkingUI::moveUserToChannel(unsigned int userSession, int channelID) { - int targetChanIndex = findContainer(channelID, ContainerType::CHANNEL); +void TalkingUI::moveUserToChannel(unsigned int userSession, unsigned int channelID) { + int targetChanIndex = findContainer(static_cast< int >(channelID), ContainerType::CHANNEL); if (targetChanIndex < 0) { qCritical("TalkingUI::moveUserToChannel Can't find channel for speaker"); return; } - std::unique_ptr< TalkingUIContainer > &targetChannel = m_containers[targetChanIndex]; + std::unique_ptr< TalkingUIContainer > &targetChannel = m_containers[static_cast< std::size_t >(targetChanIndex)]; if (targetChannel->contains(userSession, EntryType::USER)) { // The given user is already in the target channel - nothing to do @@ -522,9 +524,9 @@ void TalkingUI::mousePressEvent(QMouseEvent *event) { case EntryType::LISTENER: TalkingUIChannelListener *listenerEntry = static_cast< TalkingUIChannelListener * >(currentEntry.get()); - setSelection(ListenerSelection(listenerEntry->getWidget(), - listenerEntry->getAssociatedUserSession(), - listenerEntry->getAssociatedChannelID())); + setSelection(ListenerSelection( + listenerEntry->getWidget(), listenerEntry->getAssociatedUserSession(), + static_cast< unsigned int >(listenerEntry->getAssociatedChannelID()))); break; } @@ -536,8 +538,8 @@ void TalkingUI::mousePressEvent(QMouseEvent *event) { if (!foundTarget) { // Select channel itself - setSelection( - ChannelSelection(currentContainer->getWidget(), currentContainer->getAssociatedChannelID())); + setSelection(ChannelSelection(currentContainer->getWidget(), + static_cast< unsigned int >(currentContainer->getAssociatedChannelID()))); foundTarget = true; } @@ -579,7 +581,7 @@ QSize TalkingUI::sizeHint() const { // Prefer to occupy at least 10% of the screen's size // This aims to be a good compromise between not being in the way and not // being too small to being handled properly. - int width = QGuiApplication::screens()[0]->availableSize().width() * 0.1; + int width = static_cast< int >(QGuiApplication::screens()[0]->availableSize().width() * 0.1); return { width, 0 }; } @@ -649,14 +651,16 @@ void TalkingUI::on_mainWindowSelectionChanged(const QModelIndex ¤t, const // if user != nullptr, the selection is actually a user, but UserModel::getChannel still returns // the channel of that user. However we only want to select the channel if the user has indeed // selected the channel and not just one of the users in it. - int index = findContainer(channel->iId, ContainerType::CHANNEL); + int index = findContainer(static_cast< int >(channel->iId), ContainerType::CHANNEL); if (index >= 0) { // Only select the channel if there is present in the TalkingUI - std::unique_ptr< TalkingUIContainer > &targetContainer = m_containers[index]; + std::unique_ptr< TalkingUIContainer > &targetContainer = + m_containers[static_cast< std::size_t >(index)]; setSelection( - ChannelSelection(targetContainer->getWidget(), targetContainer->getAssociatedChannelID())); + ChannelSelection(targetContainer->getWidget(), + static_cast< unsigned int >(targetContainer->getAssociatedChannelID()))); clearSelection = false; } @@ -696,10 +700,10 @@ void TalkingUI::on_serverSynchronized() { removeAllListeners(); if (Global::get().s.bTalkingUI_ShowLocalListeners) { if (self) { - const QSet< int > channels = + const QSet< unsigned int > channels = Global::get().channelListenerManager->getListenedChannelsForUser(self->uiSession); - for (int currentChannelID : channels) { + for (unsigned int currentChannelID : channels) { const Channel *channel = Channel::get(currentChannelID); if (channel) { @@ -757,7 +761,7 @@ void TalkingUI::on_settingsChanged() { TalkingUIChannel *channelContainer = static_cast< TalkingUIChannel * >(currentContainer.get()); - const Channel *channel = Channel::get(currentContainer->getAssociatedChannelID()); + const Channel *channel = Channel::get(static_cast< unsigned int >(currentContainer->getAssociatedChannelID())); if (channel) { // Update @@ -784,7 +788,7 @@ void TalkingUI::on_settingsChanged() { // The time that a silent user may stick around might have changed as well // * 1000 as the setting is in seconds whereas the timer expects milliseconds - userEntry->setLifeTime(silentUserLifeTime * 1000); + userEntry->setLifeTime(static_cast< unsigned int >(silentUserLifeTime) * 1000); userEntry->restrictLifetime(!usersAlwaysVisible); } } @@ -820,10 +824,10 @@ void TalkingUI::on_settingsChanged() { removeAllListeners(); if (Global::get().s.bTalkingUI_ShowLocalListeners) { if (self) { - const QSet< int > channels = + const QSet< unsigned int > channels = Global::get().channelListenerManager->getListenedChannelsForUser(self->uiSession); - for (int currentChannelID : channels) { + for (unsigned int currentChannelID : channels) { const Channel *channel = Channel::get(currentChannelID); if (channel) { @@ -868,7 +872,7 @@ void TalkingUI::on_channelListenerRemoved(const ClientUser *user, const Channel removeListener(user->uiSession, channel->iId); } -void TalkingUI::on_channelListenerLocalVolumeAdjustmentChanged(int channelID, float, float) { +void TalkingUI::on_channelListenerLocalVolumeAdjustmentChanged(unsigned int channelID, float, float) { TalkingUIChannelListener *listenerEntry = findListener(Global::get().uiSession, channelID); const Channel *channel = Channel::get(channelID); diff --git a/src/mumble/TalkingUI.h b/src/mumble/TalkingUI.h index efbc327d617..540fbf660f8 100644 --- a/src/mumble/TalkingUI.h +++ b/src/mumble/TalkingUI.h @@ -36,7 +36,7 @@ class TalkingUI : public QWidget { private: Q_OBJECT - Q_DISABLE_COPY(TalkingUI); + Q_DISABLE_COPY(TalkingUI) std::vector< std::unique_ptr< TalkingUIContainer > > m_containers; /// The Entry corresponding to the currently selected user @@ -56,8 +56,8 @@ class TalkingUI : public QWidget { void removeUser(unsigned int userSession); void addListener(const ClientUser *user, const Channel *channel); - TalkingUIChannelListener *findListener(unsigned int userSession, int channelID); - void removeListener(unsigned int userSession, int channelID); + TalkingUIChannelListener *findListener(unsigned int userSession, unsigned int channelID); + void removeListener(unsigned int userSession, unsigned int channelID); void removeAllListeners(); /// Sets up the UI components @@ -70,7 +70,6 @@ class TalkingUI : public QWidget { /// /// @param channel A pointer to the channel that shall be added void addChannel(const Channel *channel); - ; /// Adds an UI entry for the given User, if none exists yet. /// /// @param channel A pointer to the user that shall be added @@ -81,7 +80,7 @@ class TalkingUI : public QWidget { /// /// @paam userSession The session ID of the user /// @param channelID The channel ID of the channel - void moveUserToChannel(unsigned int userSession, int channelID); + void moveUserToChannel(unsigned int userSession, unsigned int channelID); /// Update (resize) the UI to its content void updateUI(); @@ -125,7 +124,8 @@ public slots: void on_userLocalVolumeAdjustmentsChanged(float newAdjustment, float oldAdjustment); void on_channelListenerAdded(const ClientUser *user, const Channel *channel); void on_channelListenerRemoved(const ClientUser *user, const Channel *channel); - void on_channelListenerLocalVolumeAdjustmentChanged(int channelID, float newAdjustment, float oldAdjustment); + void on_channelListenerLocalVolumeAdjustmentChanged(unsigned int channelID, float newAdjustment, + float oldAdjustment); }; #endif // MUMBLE_MUMBLE_TALKINGUI_H_ diff --git a/src/mumble/TalkingUIContainer.cpp b/src/mumble/TalkingUIContainer.cpp index 2bdd6623957..a2a3754cde5 100644 --- a/src/mumble/TalkingUIContainer.cpp +++ b/src/mumble/TalkingUIContainer.cpp @@ -58,7 +58,7 @@ std::unique_ptr< TalkingUIEntry > TalkingUIContainer::removeEntry(unsigned int a if (index >= 0) { // Move the entry out of the vector - entry = std::move(m_entries[index]); + entry = std::move(m_entries[static_cast< std::size_t >(index)]); m_entries.erase(m_entries.begin() + index); // reset container @@ -100,7 +100,7 @@ TalkingUIEntry *TalkingUIContainer::get(unsigned int associatedUserSession, Entr int index = find(associatedUserSession, type); if (index >= 0) { - return m_entries[index].get(); + return m_entries[static_cast< std::size_t >(index)].get(); } else { return nullptr; } diff --git a/src/mumble/TalkingUIEntry.cpp b/src/mumble/TalkingUIEntry.cpp index dff7ec9095f..6b4835f92c9 100644 --- a/src/mumble/TalkingUIEntry.cpp +++ b/src/mumble/TalkingUIEntry.cpp @@ -211,7 +211,7 @@ int TalkingUIUser::compare(const TalkingUIEntry &other) const { if (res == 0) { // Make sure that we only consider users the same, if they have the same ID and // not simply because they happen to have the same name - res = otherUser.getAssociatedUserSession() - getAssociatedUserSession(); + res = static_cast< int >(otherUser.getAssociatedUserSession()) - static_cast< int >(getAssociatedUserSession()); } return res; @@ -263,7 +263,7 @@ void TalkingUIUser::setDisplayString(const QString &displayString) { } void TalkingUIUser::setLifeTime(unsigned int time) { - m_timer.setInterval(time); + m_timer.setInterval(static_cast< int >(time)); } void TalkingUIUser::restrictLifetime(bool restrict) { @@ -316,8 +316,8 @@ void TalkingUIUser::setStatus(UserStatus status) { // Draw the icons to the Pixmap QPainter painter(&pixmap); - for (int i = 0; i < static_cast< int >(icons.size()); i++) { - painter.drawPixmap(i * m_iconSize, 0, + for (unsigned int i = 0; i < icons.size(); i++) { + painter.drawPixmap(static_cast< int >(i) * m_iconSize, 0, icons[i].get().pixmap(QSize(m_iconSize, m_iconSize), QIcon::Normal, QIcon::On)); } @@ -397,5 +397,5 @@ void TalkingUIChannelListener::setDisplayString(const QString &displayString) { } int TalkingUIChannelListener::getAssociatedChannelID() const { - return m_channelID; + return static_cast< int >(m_channelID); } diff --git a/src/mumble/TalkingUIEntry.h b/src/mumble/TalkingUIEntry.h index eeb2f9c8ea7..a0ac405c30d 100644 --- a/src/mumble/TalkingUIEntry.h +++ b/src/mumble/TalkingUIEntry.h @@ -128,7 +128,7 @@ class TalkingUIChannelListener : public TalkingUIEntry { QLabel *m_icon = nullptr; QLabel *m_nameLabel = nullptr; - int m_channelID; + unsigned int m_channelID; QString m_name; public: diff --git a/src/mumble/TalkingUISelection.cpp b/src/mumble/TalkingUISelection.cpp index 39a9787f119..1daa48593d9 100644 --- a/src/mumble/TalkingUISelection.cpp +++ b/src/mumble/TalkingUISelection.cpp @@ -64,7 +64,7 @@ std::unique_ptr< TalkingUISelection > UserSelection::cloneToHeap() const { -ChannelSelection::ChannelSelection(QWidget *widget, int channelID) +ChannelSelection::ChannelSelection(QWidget *widget, unsigned int channelID) : TalkingUISelection(widget), m_channelID(channelID) { } @@ -80,7 +80,7 @@ std::unique_ptr< TalkingUISelection > ChannelSelection::cloneToHeap() const { -ListenerSelection::ListenerSelection(QWidget *widget, unsigned int userSession, int channelID) +ListenerSelection::ListenerSelection(QWidget *widget, unsigned int userSession, unsigned int channelID) : TalkingUISelection(widget), m_userSession(userSession), m_channelID(channelID) { } diff --git a/src/mumble/TalkingUISelection.h b/src/mumble/TalkingUISelection.h index 743108a42b5..66574f2619a 100644 --- a/src/mumble/TalkingUISelection.h +++ b/src/mumble/TalkingUISelection.h @@ -64,10 +64,10 @@ class UserSelection : public TalkingUISelection { /// A class representing the selection of a channel in the TalkingUI class ChannelSelection : public TalkingUISelection { protected: - const int m_channelID; + const unsigned int m_channelID; public: - explicit ChannelSelection(QWidget *widget, int channelID); + explicit ChannelSelection(QWidget *widget, unsigned int channelID); explicit ChannelSelection(const ChannelSelection &) = default; virtual void syncToMainWindow() const override; @@ -78,10 +78,10 @@ class ChannelSelection : public TalkingUISelection { class ListenerSelection : public TalkingUISelection { protected: unsigned int m_userSession; - const int m_channelID; + const unsigned int m_channelID; public: - explicit ListenerSelection(QWidget *widget, unsigned int userSession, int channelID); + explicit ListenerSelection(QWidget *widget, unsigned int userSession, unsigned int channelID); explicit ListenerSelection(const ListenerSelection &) = default; virtual void syncToMainWindow() const override; diff --git a/src/mumble/TextToSpeech_macx.mm b/src/mumble/TextToSpeech_macx.mm index 1824bbbb155..33b02a43f6d 100644 --- a/src/mumble/TextToSpeech_macx.mm +++ b/src/mumble/TextToSpeech_macx.mm @@ -118,7 +118,7 @@ - (void)speechSynthesizer:(NSSpeechSynthesizer *)synthesizer didFinishSpeaking:( void TextToSpeechPrivate::say(const QString &text) { QByteArray byteArray = text.toUtf8(); - NSString *message = [[NSString alloc] initWithBytes:byteArray.constData() length:byteArray.size() encoding:NSUTF8StringEncoding]; + NSString *message = [[NSString alloc] initWithBytes:byteArray.constData() length:((NSUInteger) byteArray.size()) encoding:NSUTF8StringEncoding]; if (message == nil) { return; @@ -135,7 +135,7 @@ - (void)speechSynthesizer:(NSSpeechSynthesizer *)synthesizer didFinishSpeaking:( void TextToSpeechPrivate::setVolume(int volume) { // Check for setVolume: availability. It's only available on 10.5+. if ([[m_synthesizerHelper synthesizer] respondsToSelector:@selector(setVolume:)]) { - [[m_synthesizerHelper synthesizer] setVolume:volume / 100.0]; + [[m_synthesizerHelper synthesizer] setVolume:volume / 100.0f]; } } diff --git a/src/mumble/ThemeInfo.h b/src/mumble/ThemeInfo.h index 255e539d220..003bf8cc9dc 100644 --- a/src/mumble/ThemeInfo.h +++ b/src/mumble/ThemeInfo.h @@ -83,7 +83,7 @@ class ThemeInfo { QString defaultStyle; }; -Q_DECLARE_METATYPE(ThemeInfo); -Q_DECLARE_METATYPE(ThemeInfo::StyleInfo); +Q_DECLARE_METATYPE(ThemeInfo) +Q_DECLARE_METATYPE(ThemeInfo::StyleInfo) #endif // MUMBLE_MUMBLE_THEMEINFO_H_ diff --git a/src/mumble/Translations.cpp b/src/mumble/Translations.cpp index 53b87e15128..da8c2b1a4d8 100644 --- a/src/mumble/Translations.cpp +++ b/src/mumble/Translations.cpp @@ -140,5 +140,5 @@ namespace Translations { return guard; } -}; // namespace Translations -}; // namespace Mumble +} // namespace Translations +} // namespace Mumble diff --git a/src/mumble/Translations.h b/src/mumble/Translations.h index 8e585928554..cbfc36e8c10 100644 --- a/src/mumble/Translations.h +++ b/src/mumble/Translations.h @@ -42,7 +42,7 @@ namespace Translations { */ LifetimeGuard installTranslators(const QLocale &locale, QApplication &app, const QStringList &extraDirectories); -}; // namespace Translations -}; // namespace Mumble +} // namespace Translations +} // namespace Mumble #endif // MUMBLE_MUMBLE_TRANSLATIONS_H_ diff --git a/src/mumble/UserInformation.cpp b/src/mumble/UserInformation.cpp index 8b96096cba0..03f72b179fc 100644 --- a/src/mumble/UserInformation.cpp +++ b/src/mumble/UserInformation.cpp @@ -56,14 +56,14 @@ void UserInformation::on_qpbCertificate_clicked() { QString UserInformation::secsToString(unsigned int secs) { QStringList qsl; - int weeks = secs / (60 * 60 * 24 * 7); - secs = secs % (60 * 60 * 24 * 7); - int days = secs / (60 * 60 * 24); - secs = secs % (60 * 60 * 24); - int hours = secs / (60 * 60); - secs = secs % (60 * 60); - int minutes = secs / 60; - int seconds = secs % 60; + unsigned int weeks = secs / (60 * 60 * 24 * 7); + secs -= weeks * (60 * 60 * 24 * 7); + unsigned int days = secs / (60 * 60 * 24); + secs -= days * (60 * 60 * 24); + unsigned int hours = secs / (60 * 60); + secs -= hours * (60 * 60); + unsigned int minutes = secs / 60; + unsigned int seconds = secs - minutes * 60; if (weeks) qsl << tr("%1w").arg(weeks); diff --git a/src/mumble/UserListModel.cpp b/src/mumble/UserListModel.cpp index 8dd515d5417..532cd061636 100644 --- a/src/mumble/UserListModel.cpp +++ b/src/mumble/UserListModel.cpp @@ -191,7 +191,7 @@ void UserListModel::removeRowsInSelection(const QItemSelection &selection) { QModelIndexList indices = selection.indexes(); std::vector< int > rows; - rows.reserve(indices.size()); + rows.reserve(static_cast< std::size_t >(indices.size())); foreach (const QModelIndex &idx, indices) { if (idx.column() != COL_NICK) @@ -270,7 +270,7 @@ QVariant UserListModel::lastSeenToTodayDayCount(const std::string &lastSeenDate) return count; } -QString UserListModel::pathForChannelId(const int channelId) const { +QString UserListModel::pathForChannelId(const unsigned int channelId) const { QString path = m_channelIdToPathMap.value(channelId); if (path.isNull()) { path = QLatin1String("-"); diff --git a/src/mumble/UserListModel.h b/src/mumble/UserListModel.h index c9ba28c3d8f..6b3b59af6a8 100644 --- a/src/mumble/UserListModel.h +++ b/src/mumble/UserListModel.h @@ -61,7 +61,7 @@ class UserListModel : public QAbstractTableModel { /// @return QVariant() is returned for invalid strings. QVariant lastSeenToTodayDayCount(const std::string &lastSeenDate) const; /// Returns a textual representation of the channel hierarchy of the given channel - QString pathForChannelId(const int channelId) const; + QString pathForChannelId(unsigned int channelId) const; /// Converts a ISO formatted UTC time string to a QDateTime object. QDateTime isoUTCToDateTime(const std::string &isoTime) const; @@ -79,7 +79,7 @@ class UserListModel : public QAbstractTableModel { /// Cache for lastSeenToTodayDayCount mutable QHash< QString, QVariant > m_stringToLastSeenToTodayCount; /// Cache for pathForChannelId conversions - mutable QHash< int, QString > m_channelIdToPathMap; + mutable QHash< unsigned int, QString > m_channelIdToPathMap; }; #endif // MUMBLE_MUMBLE_USERLISTMODEL_H_ diff --git a/src/mumble/UserLocalNicknameDialog.h b/src/mumble/UserLocalNicknameDialog.h index 62ea6419a5d..1505bb85d29 100644 --- a/src/mumble/UserLocalNicknameDialog.h +++ b/src/mumble/UserLocalNicknameDialog.h @@ -18,7 +18,7 @@ class UserLocalNicknameDialog; class UserLocalNicknameDialog : public QDialog, private Ui::UserLocalNicknameDialog { Q_OBJECT - Q_DISABLE_COPY(UserLocalNicknameDialog); + Q_DISABLE_COPY(UserLocalNicknameDialog) /// The session ID for the user that the dialog is changing the nickname for. unsigned int m_clientSession; diff --git a/src/mumble/UserModel.cpp b/src/mumble/UserModel.cpp index 2b727946de8..2507c77f6a3 100644 --- a/src/mumble/UserModel.cpp +++ b/src/mumble/UserModel.cpp @@ -135,9 +135,9 @@ int ModelItem::rowOf(Channel *c) const { return -1; } -int ModelItem::rowOf(ClientUser *p, const bool isListener) const { +int ModelItem::rowOf(ClientUser *p, const bool lookForListener) const { for (int i = 0; i < qlChildren.count(); i++) - if (qlChildren.at(i)->isListener == isListener && qlChildren.at(i)->pUser == p) + if (qlChildren.at(i)->isListener == lookForListener && qlChildren.at(i)->pUser == p) return i; return -1; } @@ -176,7 +176,7 @@ int ModelItem::insertIndex(Channel *c) const { return qlpc.indexOf(c) + (bUsersTop ? ocount : 0); } -int ModelItem::insertIndex(ClientUser *p, bool isListener) const { +int ModelItem::insertIndex(ClientUser *p, bool userIsListener) const { QList< ClientUser * > qlclientuser; ModelItem *item; @@ -187,7 +187,7 @@ int ModelItem::insertIndex(ClientUser *p, bool isListener) const { if (item->pUser) { if (item->pUser != p) { // Make sure listeners and non-listeners are all grouped together and not mixed - if ((isListener && item->isListener) || (!isListener && !item->isListener)) { + if ((userIsListener && item->isListener) || (!userIsListener && !item->isListener)) { qlclientuser << item->pUser; } } @@ -206,7 +206,7 @@ int ModelItem::insertIndex(ClientUser *p, bool isListener) const { // Make sure that the a user is always added to other users either all above or all below // sub-channels) and also make sure that listeners are grouped together and directly above // normal users. - return qlclientuser.indexOf(p) + (bUsersTop ? 0 : ocount) + (isListener ? 0 : listenerCount); + return qlclientuser.indexOf(p) + (bUsersTop ? 0 : ocount) + (userIsListener ? 0 : listenerCount); } QString ModelItem::hash() const { @@ -679,7 +679,7 @@ QVariant UserModel::otherRoles(const QModelIndex &idx, int role) const { if (c->qsDesc.isEmpty()) { c->qsDesc = QString::fromUtf8(Global::get().db->blob(c->qbaDescHash)); if (c->qsDesc.isEmpty()) { - const_cast< UserModel * >(this)->iChannelDescription = c->iId; + const_cast< UserModel * >(this)->iChannelDescription = static_cast< int >(c->iId); MumbleProto::RequestBlob mprb; mprb.add_channel_description(c->iId); @@ -1245,7 +1245,7 @@ void UserModel::setComment(Channel *c, const QString &comment) { if (!comment.isEmpty()) { Global::get().db->setBlob(c->qbaDescHash, c->qsDesc.toUtf8()); - if (c->iId == iChannelDescription) { + if (c->iId == static_cast< unsigned int >(iChannelDescription)) { iChannelDescription = -1; item->bCommentSeen = false; if (bClicked) { @@ -1339,7 +1339,7 @@ void UserModel::repositionChannel(Channel *c, const int position) { } } -Channel *UserModel::addChannel(int id, Channel *p, const QString &name) { +Channel *UserModel::addChannel(unsigned int id, Channel *p, const QString &name) { Channel *c = Channel::add(id, name); if (!c) @@ -1430,7 +1430,7 @@ bool UserModel::isChannelListener(const QModelIndex &idx) const { return item->isListener; } -void UserModel::setSelectedChannelListener(unsigned int userSession, int channelID) { +void UserModel::setSelectedChannelListener(unsigned int userSession, unsigned int channelID) { QModelIndex idx = channelListenerIndex(ClientUser::get(userSession), Channel::get(channelID)); if (!idx.isValid()) { @@ -1667,7 +1667,7 @@ Channel *UserModel::getSelectedChannel() const { return nullptr; } -void UserModel::setSelectedChannel(int id) { +void UserModel::setSelectedChannel(unsigned int id) { QModelIndex idx = index(Channel::get(id)); if (!idx.isValid()) { @@ -1707,7 +1707,7 @@ void UserModel::userStateChanged() { updateOverlay(); } -void UserModel::on_channelListenerLocalVolumeAdjustmentChanged(int channelID, float oldValue, float newValue) { +void UserModel::on_channelListenerLocalVolumeAdjustmentChanged(unsigned int channelID, float oldValue, float newValue) { Q_UNUSED(oldValue); Q_UNUSED(newValue); @@ -1813,7 +1813,7 @@ bool UserModel::dropMimeData(const QMimeData *md, Qt::DropAction, int row, int c mpus.set_session(uiSession); mpus.set_channel_id(c->iId); Global::get().sh->sendMessage(mpus); - } else if (c->iId != iId) { + } else if (c->iId != static_cast< unsigned int >(iId)) { // Channel dropped somewhere (not on itself) int ret; switch (Global::get().s.ceChannelDrag) { @@ -1841,7 +1841,7 @@ bool UserModel::dropMimeData(const QMimeData *md, Qt::DropAction, int row, int c } long long inewpos = 0; - Channel *dropped = Channel::c_qhChannels.value(iId); + Channel *dropped = Channel::c_qhChannels.value(static_cast< unsigned int >(iId)); if (!dropped) return false; @@ -1952,7 +1952,7 @@ bool UserModel::dropMimeData(const QMimeData *md, Qt::DropAction, int row, int c } MumbleProto::ChannelState mpcs; - mpcs.set_channel_id(iId); + mpcs.set_channel_id(static_cast< unsigned int >(iId)); if (dropped->parent() != c) mpcs.set_parent(c->iId); mpcs.set_position(static_cast< int >(inewpos)); diff --git a/src/mumble/UserModel.h b/src/mumble/UserModel.h index 2a25ea70038..b645f29615f 100644 --- a/src/mumble/UserModel.h +++ b/src/mumble/UserModel.h @@ -133,14 +133,14 @@ class UserModel : public QAbstractItemModel { /// @param session The session ID of the respective User void setSelectedUser(unsigned int session); - Channel *addChannel(int id, Channel *p, const QString &name); + Channel *addChannel(unsigned int id, Channel *p, const QString &name); Channel *getChannel(const QModelIndex &idx) const; /// @returns A pointer to the currently selected Channel or nullptr if there is none Channel *getSelectedChannel() const; /// Sets the selection to the Channel with the given ID /// /// @param session The ID of the respective Channel - void setSelectedChannel(int id); + void setSelectedChannel(unsigned int id); /// Adds the guven user as a listener to the given channel /// @@ -161,7 +161,7 @@ class UserModel : public QAbstractItemModel { /// /// @param userSession The session ID of the respective User /// @param channelID The ID of the respective Channel - void setSelectedChannelListener(unsigned int userSession, int channelID); + void setSelectedChannelListener(unsigned int userSession, unsigned int channelID); Channel *getSubChannel(Channel *p, int idx) const; @@ -208,7 +208,7 @@ class UserModel : public QAbstractItemModel { public slots: /// Invalidates the model data of the ClientUser triggering this slot. void userStateChanged(); - void on_channelListenerLocalVolumeAdjustmentChanged(int channelID, float oldValue, float newValue); + void on_channelListenerLocalVolumeAdjustmentChanged(unsigned int channelID, float oldValue, float newValue); void ensureSelfVisible(); void recheckLinks(); void updateOverlay() const; @@ -225,15 +225,15 @@ public slots: /// A signal that emitted whenever a channel is added to the model. /// /// @param channelID The ID of the channel - void channelAdded(int channelID); + void channelAdded(unsigned int channelID); /// A signal that emitted whenever a channel is removed from the model. /// /// @param channelID The ID of the channel - void channelRemoved(int channelID); + void channelRemoved(unsigned int channelID); /// A signal that emitted whenever a channel is renamed. /// /// @param channelID The ID of the channel - void channelRenamed(int channelID); + void channelRenamed(unsigned int channelID); }; #endif diff --git a/src/mumble/UserView.cpp b/src/mumble/UserView.cpp index 65de065de8d..4551ea50e01 100644 --- a/src/mumble/UserView.cpp +++ b/src/mumble/UserView.cpp @@ -75,7 +75,8 @@ void UserDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, QRect textRect = style->subElementRect(QStyle::SE_ItemViewItemText, &o, o.widget); QString itemText = o.fontMetrics.elidedText(o.text, o.textElideMode, textRect.width()); painter->setFont(o.font); - style->drawItemText(painter, textRect, o.displayAlignment, o.palette, true, itemText, colorRole); + style->drawItemText(painter, textRect, static_cast< int >(o.displayAlignment), o.palette, true, itemText, + colorRole); // draw icons to original rect QRect ps = QRect(option.rect.right() - (ql.size() * m_iconTotalDimension), option.rect.y(), diff --git a/src/mumble/VoiceRecorder.cpp b/src/mumble/VoiceRecorder.cpp index 3e1c3b82c41..be563baa78b 100644 --- a/src/mumble/VoiceRecorder.cpp +++ b/src/mumble/VoiceRecorder.cpp @@ -157,7 +157,7 @@ QString VoiceRecorder::expandTemplateVariables(const QString &path, const QStrin int VoiceRecorder::indexForUser(const ClientUser *clientUser) const { Q_ASSERT(!m_config.mixDownMode || !clientUser); - return (m_config.mixDownMode) ? 0 : clientUser->uiSession; + return (m_config.mixDownMode) ? 0 : static_cast< int >(clientUser->uiSession); } SF_INFO VoiceRecorder::createSoundFileInfo() const { @@ -339,7 +339,8 @@ void VoiceRecorder::run() { return; } - const qint64 missingSamples = rb->absoluteStartSample - ri->lastWrittenAbsoluteSample; + const qint64 missingSamples = + static_cast< qint64 >(rb->absoluteStartSample) - static_cast< qint64 >(ri->lastWrittenAbsoluteSample); static const qint64 heuristicSilenceThreshold = m_config.sampleRate / 10; // 100ms if (missingSamples > heuristicSilenceThreshold) { @@ -359,7 +360,7 @@ void VoiceRecorder::run() { if (rest > 0) sf_write_float(ri->soundFile, buffer, rest); - ri->lastWrittenAbsoluteSample += silenceToWrite; + ri->lastWrittenAbsoluteSample += static_cast< quint64 >(silenceToWrite); if (requeue) { // Requeue the writing for this buffer to keep thread responsive @@ -371,7 +372,7 @@ void VoiceRecorder::run() { // Write the audio buffer and update the timestamp in |ri|. sf_write_float(ri->soundFile, rb->buffer.get(), rb->samples); - ri->lastWrittenAbsoluteSample += rb->samples; + ri->lastWrittenAbsoluteSample += static_cast< quint64 >(rb->samples); } m_sleepLock.unlock(); @@ -398,7 +399,7 @@ void VoiceRecorder::stop(bool force) { void VoiceRecorder::prepareBufferAdds() { // Should be ms accurat - m_absoluteSampleEstimation = (m_timestamp->elapsed() / 1000) * (m_config.sampleRate / 1000); + m_absoluteSampleEstimation = (m_timestamp->elapsed() / 1000) * (static_cast< quint64 >(m_config.sampleRate) / 1000); } void VoiceRecorder::addBuffer(const ClientUser *clientUser, boost::shared_array< float > buffer, int samples) { diff --git a/src/mumble/VoiceRecorderDialog.cpp b/src/mumble/VoiceRecorderDialog.cpp index fedaa9aacfe..138c664bd98 100644 --- a/src/mumble/VoiceRecorderDialog.cpp +++ b/src/mumble/VoiceRecorderDialog.cpp @@ -162,7 +162,7 @@ void VoiceRecorderDialog::on_qpbStart_clicked() { // Create the recorder VoiceRecorder::Config config; - config.sampleRate = ao->getMixerFreq(); + config.sampleRate = static_cast< int >(ao->getMixerFreq()); config.fileName = dir.absoluteFilePath(basename + QLatin1Char('.') + suffix); config.mixDownMode = qrbDownmix->isChecked(); config.recordingFormat = static_cast< VoiceRecorderFormat::Format >(ifm); diff --git a/src/mumble/WASAPI.cpp b/src/mumble/WASAPI.cpp index 2c3d4a860b4..c3961987bde 100644 --- a/src/mumble/WASAPI.cpp +++ b/src/mumble/WASAPI.cpp @@ -352,15 +352,16 @@ static IMMDevice *openNamedOrDefaultDevice(const QString &name, EDataFlow dataFl IMMDevice *pDevice = nullptr; // Try to find a device pointer for |name|. if (!name.isEmpty()) { - STACKVAR(wchar_t, devname, name.length() + 1); - int len = name.toWCharArray(devname); + static std::vector< wchar_t > devname; + devname.resize(name.length() + 1); + int len = name.toWCharArray(devname.data()); devname[len] = 0; - hr = pEnumerator->GetDevice(devname, &pDevice); + hr = pEnumerator->GetDevice(devname.data(), &pDevice); if (FAILED(hr)) { qWarning("WASAPI: Failed to open selected device %s %ls (df=%d, e=%d, hr=0x%08lx), falling back to default", - qPrintable(name), devname, dataFlow, role, hr); + qPrintable(name), devname.data(), dataFlow, role, hr); } else { - WASAPINotificationClient::get().enlistDeviceAsUsed(devname); + WASAPINotificationClient::get().enlistDeviceAsUsed(devname.data()); } } @@ -901,7 +902,6 @@ void WASAPIOutput::run() { HANDLE hMmThread; int ns = 0; unsigned int chanmasks[32]; - QMap< DWORD, float > qmVolumes; bool lastspoke = false; REFERENCE_TIME bufferDuration = (Global::get().s.iOutputDelay > 1) ? (Global::get().s.iOutputDelay + 1) * 100000 : 0; diff --git a/src/mumble/Zeroconf.cpp b/src/mumble/Zeroconf.cpp index 31bec87432c..27b0d2f5b5d 100644 --- a/src/mumble/Zeroconf.cpp +++ b/src/mumble/Zeroconf.cpp @@ -214,7 +214,7 @@ void Zeroconf::helperBrowserRecordsChanged(const QList< BonjourRecord > &records } void Zeroconf::helperResolverRecordResolved(const BonjourRecord record, const QString hostname, const int port) { - emit recordResolved(record, hostname, port); + emit recordResolved(record, hostname, static_cast< std::uint16_t >(port)); } void Zeroconf::helperBrowserError(const DNSServiceErrorType error) const { diff --git a/src/mumble/main.cpp b/src/mumble/main.cpp index 9daee17ef8f..417cc0f0c7d 100644 --- a/src/mumble/main.cpp +++ b/src/mumble/main.cpp @@ -467,7 +467,8 @@ int main(int argc, char **argv) { if (_wgetenv_s(&reqSize, nullptr, 0, L"PATH") != 0) { qWarning() << "Failed to get PATH. Not adding application directory to PATH. DBus bindings may not work."; } else if (reqSize > 0) { - STACKVAR(wchar_t, buff, reqSize + 1); + std::vector< wchar_t > buff; + buff.resize(reqSize + 1); if (_wgetenv_s(&reqSize, buff, reqSize, L"PATH") != 0) { qWarning() << "Failed to get PATH. Not adding application directory to PATH. DBus bindings may not work."; @@ -476,7 +477,9 @@ int main(int argc, char **argv) { QString::fromLatin1("%1;%2") .arg(QDir::toNativeSeparators(MumbleApplication::instance()->applicationVersionRootPath())) .arg(QString::fromWCharArray(buff)); - STACKVAR(wchar_t, buffout, path.length() + 1); + static std::vector< wchar_t > outBuffer; + outBuffer.resize(path.length() + 1); + wchar_t *buffout = outBuffer.data(); path.toWCharArray(buffout); if (_wputenv_s(L"PATH", buffout) != 0) { qWarning() << "Failed to set PATH. DBus bindings may not work."; diff --git a/src/mumble/os_macx.mm b/src/mumble/os_macx.mm index 7c0effabb3e..5d98e5c847b 100644 --- a/src/mumble/os_macx.mm +++ b/src/mumble/os_macx.mm @@ -139,7 +139,9 @@ void os_init() { if (home) { size_t len = strlen(home) + strlen(logpath) + 1; - STACKVAR(char, buff, len); + static std::vector buffer; + buffer.resize(len); + char *buff = buffer.data(); memset(buff, 0, len); strcat(buff, home); strcat(buff, logpath); diff --git a/src/mumble/os_win.cpp b/src/mumble/os_win.cpp index 1b0acf33499..573d389581e 100644 --- a/src/mumble/os_win.cpp +++ b/src/mumble/os_win.cpp @@ -10,8 +10,13 @@ # include "Utils.h" #endif -#include "Version.h" +// Must be included before other Windows stuff #include "win.h" + +#include "versionhelpers.h" + +#include "Version.h" + #include "Global.h" #include @@ -30,6 +35,8 @@ #include #include +#include + extern "C" { void __cpuid(int a[4], int b); void mumble_speex_init(); @@ -174,12 +181,13 @@ FARPROC WINAPI delayHook(unsigned dliNotify, PDelayLoadInfo pdli) { size_t buflen = length + 10; - STACKVAR(char, filename, buflen); - strcpy_s(filename, buflen, pdli->szDll); + std::vector< char > filename; + filename.resize(buflen); + strcpy_s(filename.data(), buflen, pdli->szDll); size_t offset = 0; - if (_stricmp(filename + length - 4, ".dll") == 0) + if (_stricmp(filename.data() + length - 4, ".dll") == 0) offset = length - 4; else offset = length; @@ -192,20 +200,20 @@ FARPROC WINAPI delayHook(unsigned dliNotify, PDelayLoadInfo pdli) { if (cpuinfo[3] & 0x04000000) { // And SSE3? if (cpuinfo[2] & 0x00000001) { - strcpy_s(filename + offset, 10, ".sse3.dll"); - hmod = LoadLibraryA(filename); + strcpy_s(filename.data() + offset, 10, ".sse3.dll"); + hmod = LoadLibraryA(filename.data()); if (hmod) return (FARPROC) hmod; } - strcpy_s(filename + offset, 10, ".sse2.dll"); - hmod = LoadLibraryA(filename); + strcpy_s(filename.data() + offset, 10, ".sse2.dll"); + hmod = LoadLibraryA(filename.data()); if (hmod) return (FARPROC) hmod; } - strcpy_s(filename + offset, 10, ".sse.dll"); - hmod = LoadLibraryA(filename); + strcpy_s(filename.data() + offset, 10, ".sse.dll"); + hmod = LoadLibraryA(filename.data()); if (hmod) return (FARPROC) hmod; } @@ -226,13 +234,8 @@ void os_init() { exit(0); } - OSVERSIONINFOEXW ovi; - memset(&ovi, 0, sizeof(ovi)); - - ovi.dwOSVersionInfoSize = sizeof(ovi); - GetVersionEx(reinterpret_cast< OSVERSIONINFOW * >(&ovi)); - bIsWin7 = (ovi.dwMajorVersion >= 7) || ((ovi.dwMajorVersion == 6) && (ovi.dwBuildNumber >= 7100)); - bIsVistaSP1 = (ovi.dwMajorVersion >= 7) || ((ovi.dwMajorVersion == 6) && (ovi.dwBuildNumber >= 6001)); + bIsWin7 = IsWindows7OrGreater(); + bIsVistaSP1 = IsWindowsVistaSP1OrGreater(); #if _MSC_VER == 1800 && defined(_M_X64) // Disable MSVC 2013's FMA-optimized math routines on Windows @@ -240,7 +243,7 @@ void os_init() { // There are various issues on OSes that do not support the newer // instructions. // See issue mumble-voip/mumble#1615. - if (ovi.dwMajorVersion < 5 || (ovi.dwMajorVersion == 6 && ovi.dwMinorVersion <= 1)) { + if (!IsWindows8OrGreater()) { _set_FMA3_enable(0); } #endif @@ -301,7 +304,7 @@ void os_init() { } DWORD WinVerifySslCert(const QByteArray &cert) { - DWORD errorStatus = -1; + DWORD errorStatus = std::numeric_limits< DWORD >::max(); PCCERT_CONTEXT certContext = CertCreateCertificateContext( X509_ASN_ENCODING, reinterpret_cast< const BYTE * >(cert.constData()), cert.size()); diff --git a/src/mumble/widgets/RichTextItemDelegate.cpp b/src/mumble/widgets/RichTextItemDelegate.cpp index db0f9fa8efe..dec42d2d45b 100644 --- a/src/mumble/widgets/RichTextItemDelegate.cpp +++ b/src/mumble/widgets/RichTextItemDelegate.cpp @@ -46,7 +46,7 @@ void RichTextItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem & doc.adjustSize(); if (doc.size().width() > option.rect.width()) { - Mumble::QtUtils::elideText(doc, option.rect.width()); + Mumble::QtUtils::elideText(doc, static_cast< std::uint32_t >(option.rect.width())); } // Painting item without text (this takes care of painting e.g. the highlighted for selected @@ -56,7 +56,8 @@ void RichTextItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem & // Figure out where to render the text in order to follow the requested alignment QRect textRect = style->subElementRect(QStyle::SE_ItemViewItemText, &option); - QSize documentSize(doc.size().width(), doc.size().height()); // Convert QSizeF to QSize + QSize documentSize(static_cast< int >(doc.size().width()), + static_cast< int >(doc.size().height())); // Convert QSizeF to QSize QRect layoutRect = QStyle::alignedRect(Qt::LayoutDirectionAuto, option.displayAlignment, documentSize, textRect); painter->save(); @@ -84,5 +85,5 @@ QSize RichTextItemDelegate::sizeHint(const QStyleOptionViewItem &inOption, const doc.setDefaultFont(option.font); doc.setDocumentMargin(1); - return QSize(doc.idealWidth(), doc.size().height()); + return QSize(static_cast< int >(doc.idealWidth()), static_cast< int >(doc.size().height())); } diff --git a/src/mumble/widgets/RichTextItemDelegate.h b/src/mumble/widgets/RichTextItemDelegate.h index 14155b9a791..02c58e40f25 100644 --- a/src/mumble/widgets/RichTextItemDelegate.h +++ b/src/mumble/widgets/RichTextItemDelegate.h @@ -18,8 +18,8 @@ class QModelIndex; * rich text support to the *View and *Widget objects (e.g. TreeWidget). */ class RichTextItemDelegate : public QStyledItemDelegate { - Q_OBJECT; - Q_DISABLE_COPY(RichTextItemDelegate); + Q_OBJECT + Q_DISABLE_COPY(RichTextItemDelegate) public: // inherit constructors diff --git a/src/mumble/widgets/SearchDialogItemDelegate.cpp b/src/mumble/widgets/SearchDialogItemDelegate.cpp index 7f99a45f2be..56e047c2ac5 100644 --- a/src/mumble/widgets/SearchDialogItemDelegate.cpp +++ b/src/mumble/widgets/SearchDialogItemDelegate.cpp @@ -33,10 +33,12 @@ void setupDocuments(QTextDocument &resultDoc, QTextDocument &channelTreeDoc, con // Render the channel tree with a smaller font QFont channelTreeFont(option.font); if (channelTreeFont.pointSize() >= 0) { - channelTreeFont.setPointSize(std::max(channelTreeFont.pointSize() * 0.8f, 1.0f)); + channelTreeFont.setPointSize( + static_cast< int >(std::max(static_cast< float >(channelTreeFont.pointSize()) * 0.8f, 1.0f))); } else { // Font size is specified in pixels - channelTreeFont.setPixelSize(std::max(channelTreeFont.pixelSize() * 0.8f, 1.0f)); + channelTreeFont.setPixelSize( + static_cast< int >(std::max(static_cast< float >(channelTreeFont.pixelSize()) * 0.8f, 1.0f))); } resultDoc.setDefaultTextOption(resultTextOption); @@ -79,12 +81,13 @@ void SearchDialogItemDelegate::paint(QPainter *painter, const QStyleOptionViewIt const QRect textRect = style->subElementRect(QStyle::SE_ItemViewItemText, &option); if (resultDoc.size().width() > textRect.width()) { - Mumble::QtUtils::elideText(resultDoc, textRect.width()); + Mumble::QtUtils::elideText(resultDoc, static_cast< unsigned int >(textRect.width())); } // Figure out where to render the text in order to follow the requested alignment - QSize contentSize(std::max(resultDoc.size().width(), channelTreeDoc.size().width() + CHANNEL_TREE_LEFT_INDENT), - resultDoc.size().height() + channelTreeDoc.size().height() + BOTTOM_MARGIN); + QSize contentSize(static_cast< int >( + std::max(resultDoc.size().width(), channelTreeDoc.size().width() + CHANNEL_TREE_LEFT_INDENT)), + static_cast< int >(resultDoc.size().height() + channelTreeDoc.size().height() + BOTTOM_MARGIN)); QRect contentLayoutRect = QStyle::alignedRect(Qt::LayoutDirectionAuto, option.displayAlignment, contentSize, textRect); @@ -137,7 +140,8 @@ QSize SearchDialogItemDelegate::sizeHint(const QStyleOptionViewItem &inOption, c std::max(static_cast< int >( std::max(resultDoc.size().width(), channelTreeDoc.size().width() + CHANNEL_TREE_LEFT_INDENT)), size.width()); - const int hintHeight = resultDoc.size().height() + channelTreeDoc.size().height() + BOTTOM_MARGIN; + const int hintHeight = + static_cast< int >(resultDoc.size().height() + channelTreeDoc.size().height() + BOTTOM_MARGIN); return { hintWidth, hintHeight }; } diff --git a/src/mumble/widgets/SearchDialogItemDelegate.h b/src/mumble/widgets/SearchDialogItemDelegate.h index a789af09f78..594339df612 100644 --- a/src/mumble/widgets/SearchDialogItemDelegate.h +++ b/src/mumble/widgets/SearchDialogItemDelegate.h @@ -15,8 +15,8 @@ class QModelIndex; class QObject; class SearchDialogItemDelegate : public QStyledItemDelegate { - Q_OBJECT; - Q_DISABLE_COPY(SearchDialogItemDelegate); + Q_OBJECT + Q_DISABLE_COPY(SearchDialogItemDelegate) public: constexpr static int CHANNEL_TREE_ROLE = Qt::UserRole + 1; diff --git a/src/murmur/DBus.cpp b/src/murmur/DBus.cpp index aaa9fe66ed0..4558c37cac3 100644 --- a/src/murmur/DBus.cpp +++ b/src/murmur/DBus.cpp @@ -381,7 +381,7 @@ void MurmurDBus::getPlayerState(unsigned int session, const QDBusMessage &msg, P void MurmurDBus::setPlayerState(const PlayerInfo &npi, const QDBusMessage &msg) { PLAYER_SETUP_VAR(npi.session); - CHANNEL_SETUP_VAR(npi.channel); + CHANNEL_SETUP_VAR(static_cast< unsigned int >(npi.channel)); PlayerInfo pi(pUser); server->setUserState(pUser, cChannel, npi.mute, npi.deaf, pUser->bPrioritySpeaker, npi.suppressed); @@ -394,13 +394,13 @@ void MurmurDBus::sendMessage(unsigned int session, const QString &text, const QD } void MurmurDBus::sendMessageChannel(int id, bool tree, const QString &text, const QDBusMessage &msg) { - CHANNEL_SETUP_VAR(id); + CHANNEL_SETUP_VAR(static_cast< unsigned int >(id)); server->sendTextMessage(cChannel, nullptr, tree, text); } void MurmurDBus::addChannel(const QString &name, int chanparent, const QDBusMessage &msg, int &newid) { - CHANNEL_SETUP_VAR(chanparent); + CHANNEL_SETUP_VAR(static_cast< unsigned int >(chanparent)); Channel *nc; @@ -410,7 +410,7 @@ void MurmurDBus::addChannel(const QString &name, int chanparent, const QDBusMess } server->updateChannel(nc); - newid = nc->iId; + newid = static_cast< int >(nc->iId); MumbleProto::ChannelState mpcs; mpcs.set_channel_id(nc->iId); @@ -420,7 +420,7 @@ void MurmurDBus::addChannel(const QString &name, int chanparent, const QDBusMess } void MurmurDBus::removeChannel(int id, const QDBusMessage &msg) { - CHANNEL_SETUP_VAR(id); + CHANNEL_SETUP_VAR(static_cast< unsigned int >(id)); if (!cChannel->cParent) { qdbc->send(msg.createErrorReply("net.sourceforge.mumble.Error.channel", "Invalid channel id")); return; @@ -431,17 +431,17 @@ void MurmurDBus::removeChannel(int id, const QDBusMessage &msg) { } void MurmurDBus::getChannelState(int id, const QDBusMessage &msg, ChannelInfo &state) { - CHANNEL_SETUP_VAR(id); + CHANNEL_SETUP_VAR(static_cast< unsigned int >(id)); state = ChannelInfo(cChannel); } void MurmurDBus::setChannelState(const ChannelInfo &nci, const QDBusMessage &msg) { - CHANNEL_SETUP_VAR(nci.id); - CHANNEL_SETUP_VAR2(cParent, nci.parent); + CHANNEL_SETUP_VAR(static_cast< unsigned int >(nci.id)); + CHANNEL_SETUP_VAR2(cParent, static_cast< unsigned int >(nci.parent)); QSet< Channel * > newset; foreach (int id, nci.links) { - CHANNEL_SETUP_VAR2(cLink, id); + CHANNEL_SETUP_VAR2(cLink, static_cast< unsigned int >(id)); newset << cLink; } @@ -453,7 +453,7 @@ void MurmurDBus::setChannelState(const ChannelInfo &nci, const QDBusMessage &msg void MurmurDBus::getACL(int id, const QDBusMessage &msg, QList< ACLInfo > &acls, QList< GroupInfo > &groups, bool &inherit) { - CHANNEL_SETUP_VAR(id); + CHANNEL_SETUP_VAR(static_cast< unsigned int >(id)); QStack< Channel * > chans; Channel *p; @@ -510,7 +510,7 @@ void MurmurDBus::getACL(int id, const QDBusMessage &msg, QList< ACLInfo > &acls, void MurmurDBus::setACL(int id, const QList< ACLInfo > &acls, const QList< GroupInfo > &groups, bool inherit, const QDBusMessage &msg) { - CHANNEL_SETUP_VAR(id); + CHANNEL_SETUP_VAR(static_cast< unsigned int >(id)); Group *g; ChanACL *a; @@ -716,7 +716,7 @@ void MurmurDBus::setAuthenticator(const QDBusObjectPath &path, bool reentrant, c } void MurmurDBus::setTemporaryGroups(int channel, int userid, const QStringList &groups, const QDBusMessage &msg) { - CHANNEL_SETUP_VAR(channel); + CHANNEL_SETUP_VAR(static_cast< unsigned int >(channel)); server->setTempGroups(userid, 0, cChannel, groups); } @@ -728,7 +728,7 @@ PlayerInfo::PlayerInfo(const User *p) { suppressed = p->bSuppress; selfMute = p->bSelfMute; selfDeaf = p->bSelfDeaf; - channel = p->cChannel->iId; + channel = static_cast< int >(p->cChannel->iId); } PlayerInfoExtended::PlayerInfoExtended(const User *p) : PlayerInfo(p) { @@ -741,11 +741,11 @@ PlayerInfoExtended::PlayerInfoExtended(const User *p) : PlayerInfo(p) { } ChannelInfo::ChannelInfo(const Channel *c) { - id = c->iId; + id = static_cast< int >(c->iId); name = c->qsName; - parent = c->cParent ? c->cParent->iId : -1; + parent = c->cParent ? static_cast< int >(c->cParent->iId) : -1; foreach (Channel *chn, c->qsPermLinks) - links << chn->iId; + links << static_cast< int >(chn->iId); } ACLInfo::ACLInfo(const ChanACL *acl) { @@ -913,7 +913,8 @@ void MetaDBus::getLog(int server_id, int min_offset, int max_offset, const QDBus MurmurDBus::qdbc->send(msg.createErrorReply("net.sourceforge.mumble.Error.server", "Invalid server id")); } else { entries.clear(); - QList< ServerDB::LogRecord > dblog = ServerDB::getLog(server_id, min_offset, max_offset); + QList< ServerDB::LogRecord > dblog = ServerDB::getLog(server_id, static_cast< unsigned int >(min_offset), + static_cast< unsigned int >(max_offset)); foreach (const ServerDB::LogRecord &e, dblog) { entries << LogEntry(e); } } } diff --git a/src/murmur/DBus.h b/src/murmur/DBus.h index 229b30823fd..eefa7d15c21 100644 --- a/src/murmur/DBus.h +++ b/src/murmur/DBus.h @@ -30,7 +30,7 @@ struct PlayerInfo { : session(0), mute(false), deaf(false), suppressed(false), selfMute(false), selfDeaf(false), channel(-1){}; PlayerInfo(const User *); }; -Q_DECLARE_METATYPE(PlayerInfo); +Q_DECLARE_METATYPE(PlayerInfo) struct PlayerInfoExtended : public PlayerInfo { int id; @@ -40,8 +40,8 @@ struct PlayerInfoExtended : public PlayerInfo { PlayerInfoExtended() : id(-1), onlinesecs(-1), bytespersec(-1){}; PlayerInfoExtended(const User *); }; -Q_DECLARE_METATYPE(PlayerInfoExtended); -Q_DECLARE_METATYPE(QList< PlayerInfoExtended >); +Q_DECLARE_METATYPE(PlayerInfoExtended) +Q_DECLARE_METATYPE(QList< PlayerInfoExtended >) struct ChannelInfo { int id; @@ -51,8 +51,8 @@ struct ChannelInfo { ChannelInfo() : id(-1), parent(-1){}; ChannelInfo(const Channel *c); }; -Q_DECLARE_METATYPE(ChannelInfo); -Q_DECLARE_METATYPE(QList< ChannelInfo >); +Q_DECLARE_METATYPE(ChannelInfo) +Q_DECLARE_METATYPE(QList< ChannelInfo >) struct GroupInfo { QString name; @@ -61,8 +61,8 @@ struct GroupInfo { GroupInfo() : inherited(false), inherit(false), inheritable(false){}; GroupInfo(const Group *g); }; -Q_DECLARE_METATYPE(GroupInfo); -Q_DECLARE_METATYPE(QList< GroupInfo >); +Q_DECLARE_METATYPE(GroupInfo) +Q_DECLARE_METATYPE(QList< GroupInfo >) struct ACLInfo { bool applyHere, applySubs, inherited; @@ -72,8 +72,8 @@ struct ACLInfo { ACLInfo() : applyHere(false), applySubs(false), inherited(false), playerid(-1), allow(0), deny(0){}; ACLInfo(const ChanACL *acl); }; -Q_DECLARE_METATYPE(ACLInfo); -Q_DECLARE_METATYPE(QList< ACLInfo >); +Q_DECLARE_METATYPE(ACLInfo) +Q_DECLARE_METATYPE(QList< ACLInfo >) struct BanInfo { unsigned int address; @@ -81,8 +81,8 @@ struct BanInfo { BanInfo() : address(0), bits(0){}; BanInfo(const Ban &); }; -Q_DECLARE_METATYPE(BanInfo); -Q_DECLARE_METATYPE(QList< BanInfo >); +Q_DECLARE_METATYPE(BanInfo) +Q_DECLARE_METATYPE(QList< BanInfo >) struct RegisteredPlayer { int id; @@ -91,8 +91,8 @@ struct RegisteredPlayer { QString pw; RegisteredPlayer(); }; -Q_DECLARE_METATYPE(RegisteredPlayer); -Q_DECLARE_METATYPE(QList< RegisteredPlayer >); +Q_DECLARE_METATYPE(RegisteredPlayer) +Q_DECLARE_METATYPE(QList< RegisteredPlayer >) struct LogEntry { unsigned int timestamp; @@ -100,8 +100,8 @@ struct LogEntry { LogEntry(); LogEntry(const ServerDB::LogRecord &); }; -Q_DECLARE_METATYPE(LogEntry); -Q_DECLARE_METATYPE(QList< LogEntry >); +Q_DECLARE_METATYPE(LogEntry) +Q_DECLARE_METATYPE(QList< LogEntry >) class MurmurDBus : public QDBusAbstractAdaptor { private: @@ -200,7 +200,7 @@ public slots: }; typedef QMap< QString, QString > ConfigMap; -Q_DECLARE_METATYPE(ConfigMap); +Q_DECLARE_METATYPE(ConfigMap) class MetaDBus : public QDBusAbstractAdaptor { private: diff --git a/src/murmur/Messages.cpp b/src/murmur/Messages.cpp index 6ebad11c172..5ba4895845a 100644 --- a/src/murmur/Messages.cpp +++ b/src/murmur/Messages.cpp @@ -54,7 +54,7 @@ #define PERM_DENIED(who, where, what) \ { \ MumbleProto::PermissionDenied mppd; \ - mppd.set_permission(static_cast< int >(what)); \ + mppd.set_permission(static_cast< unsigned int >(what)); \ mppd.set_channel_id(where->iId); \ mppd.set_session(who->uiSession); \ mppd.set_type(MumbleProto::PermissionDenied_DenyType_Permission); \ @@ -184,7 +184,7 @@ void Server::msgAuthenticate(ServerUser *uSource, MumbleProto::Authenticate &msg MumbleProto::ChannelState mpcs; for (Channel *chan : qhChannels) { - mpcs.set_channel_id(chan->iId); + mpcs.set_channel_id(static_cast< unsigned int >(chan->iId)); mpcs.set_can_enter(hasPermission(uSource, chan, ChanACL::Enter)); // As no ACLs have changed, we don't need to update the is_access_restricted message field @@ -216,8 +216,8 @@ void Server::msgAuthenticate(ServerUser *uSource, MumbleProto::Authenticate &msg // Fetch ID and stored username. // Since this may call DBus, which may recall our dbus messages, this function needs // to support re-entrancy, and also to support the fact that sessions may go away. - int id = authenticate(uSource->qsName, pw, uSource->uiSession, uSource->qslEmail, uSource->qsHash, - uSource->bVerified, uSource->peerCertificateChain()); + int id = authenticate(uSource->qsName, pw, static_cast< int >(uSource->uiSession), uSource->qslEmail, + uSource->qsHash, uSource->bVerified, uSource->peerCertificateChain()); uSource->iId = id >= 0 ? id : -1; @@ -282,7 +282,7 @@ void Server::msgAuthenticate(ServerUser *uSource, MumbleProto::Authenticate &msg } } - if ((id != 0) && (qhUsers.count() > iMaxUsers)) { + if ((id != 0) && (static_cast< unsigned int >(qhUsers.count()) > iMaxUsers)) { reason = QString::fromLatin1("Server is full (max %1 users)").arg(iMaxUsers); rtType = MumbleProto::Reject_RejectType_ServerFull; ok = false; @@ -294,8 +294,11 @@ void Server::msgAuthenticate(ServerUser *uSource, MumbleProto::Authenticate &msg ok = false; } - Channel *lc; - lc = qhChannels.value(readLastChannel(uSource->iId)); + Channel *lc = nullptr; + int lastChannelID = readLastChannel(uSource->iId); + if (lastChannelID >= 0) { + lc = qhChannels.value(static_cast< unsigned int >(lastChannelID)); + } if (!lc || !hasPermission(uSource, lc, ChanACL::Enter) || isChannelFull(lc, uSource)) { lc = qhChannels.value(iDefaultChan); @@ -437,7 +440,7 @@ void Server::msgAuthenticate(ServerUser *uSource, MumbleProto::Authenticate &msg mpus.set_session(uSource->uiSession); mpus.set_name(u8(uSource->qsName)); if (uSource->iId >= 0) { - mpus.set_user_id(uSource->iId); + mpus.set_user_id(static_cast< unsigned int >(uSource->iId)); hashAssign(uSource->qbaTexture, uSource->qbaTextureHash, getUserTexture(uSource->iId)); @@ -482,7 +485,7 @@ void Server::msgAuthenticate(ServerUser *uSource, MumbleProto::Authenticate &msg mpus.set_session(u->uiSession); mpus.set_name(u8(u->qsName)); if (u->iId >= 0) - mpus.set_user_id(u->iId); + mpus.set_user_id(static_cast< unsigned int >(u->iId)); if (uSource->m_version >= Version::fromComponents(1, 2, 2)) { if (!u->qbaTextureHash.isEmpty()) mpus.set_texture_hash(blob(u->qbaTextureHash)); @@ -518,7 +521,7 @@ void Server::msgAuthenticate(ServerUser *uSource, MumbleProto::Authenticate &msg mpus.set_hash(u8(u->qsHash)); - for (int channelID : m_channelListenerManager.getListenedChannelsForUser(u->uiSession)) { + for (unsigned int channelID : m_channelListenerManager.getListenedChannelsForUser(u->uiSession)) { mpus.add_listening_channel_add(channelID); if (broadcastListenerVolumeAdjustments) { @@ -532,12 +535,12 @@ void Server::msgAuthenticate(ServerUser *uSource, MumbleProto::Authenticate &msg sendMessage(uSource, mpus); } - // Send syncronisation packet + // Send synchronisation packet MumbleProto::ServerSync mpss; mpss.set_session(uSource->uiSession); if (!qsWelcomeText.isEmpty()) mpss.set_welcome_text(u8(qsWelcomeText)); - mpss.set_max_bandwidth(iMaxBandwidth); + mpss.set_max_bandwidth(static_cast< unsigned int >(iMaxBandwidth)); if (uSource->iId == 0) { mpss.set_permissions(ChanACL::All); @@ -553,7 +556,7 @@ void Server::msgAuthenticate(ServerUser *uSource, MumbleProto::Authenticate &msg // client may require its own session ID for processing the listeners properly. mpus.Clear(); mpus.set_session(uSource->uiSession); - for (int channelID : m_channelListenerManager.getListenedChannelsForUser(uSource->uiSession)) { + for (unsigned int channelID : m_channelListenerManager.getListenedChannelsForUser(uSource->uiSession)) { mpus.add_listening_channel_add(channelID); } @@ -564,7 +567,7 @@ void Server::msgAuthenticate(ServerUser *uSource, MumbleProto::Authenticate &msg sendExcept(uSource, mpus, Version::fromComponents(1, 2, 2), Version::CompareMode::AtLeast); } - std::unordered_map< int, VolumeAdjustment > volumeAdjustments = + std::unordered_map< unsigned int, VolumeAdjustment > volumeAdjustments = m_channelListenerManager.getAllListenerVolumeAdjustments(uSource->uiSession); for (auto it = volumeAdjustments.begin(); it != volumeAdjustments.end(); ++it) { MumbleProto::UserState::VolumeAdjustment *adjustment = mpus.add_listening_volume_adjustment(); @@ -584,9 +587,9 @@ void Server::msgAuthenticate(ServerUser *uSource, MumbleProto::Authenticate &msg MumbleProto::ServerConfig mpsc; mpsc.set_allow_html(bAllowHTML); - mpsc.set_message_length(iMaxTextMessageLength); - mpsc.set_image_message_length(iMaxImageMessageLength); - mpsc.set_max_users(iMaxUsers); + mpsc.set_message_length(static_cast< unsigned int >(iMaxTextMessageLength)); + mpsc.set_image_message_length(static_cast< unsigned int >(iMaxImageMessageLength)); + mpsc.set_max_users(static_cast< unsigned int >(iMaxUsers)); mpsc.set_recording_allowed(allowRecording); sendMessage(uSource, mpsc); @@ -663,7 +666,7 @@ void Server::msgBanList(ServerUser *uSource, MumbleProto::BanList &msg) { foreach (const Ban &b, qlBans) { MumbleProto::BanList_BanEntry *be = msg.add_bans(); be->set_address(b.haAddress.toStdString()); - be->set_mask(b.iMask); + be->set_mask(static_cast< unsigned int >(b.iMask)); be->set_name(u8(b.qsUsername)); be->set_hash(u8(b.qsHash)); be->set_reason(u8(b.qsReason)); @@ -684,7 +687,7 @@ void Server::msgBanList(ServerUser *uSource, MumbleProto::BanList &msg) { Ban b; b.haAddress = be.address(); - b.iMask = be.mask(); + b.iMask = static_cast< int >(be.mask()); b.qsUsername = u8(be.name()); b.qsHash = u8(be.hash()); b.qsReason = u8(be.reason()); @@ -1059,7 +1062,7 @@ void Server::msgUserState(ServerUser *uSource, MumbleProto::UserState &msg) { // Handle channel listening // Note that it is important to handle the listening channels after channel-joins - QSet< int > volumeAdjustedChannels; + QSet< unsigned int > volumeAdjustedChannels; for (int i = 0; i < msg.listening_volume_adjustment_size(); i++) { const MumbleProto::UserState::VolumeAdjustment &adjustment = msg.listening_volume_adjustment(i); @@ -1128,7 +1131,7 @@ void Server::msgUserState(ServerUser *uSource, MumbleProto::UserState &msg) { if (id > 0) { pDstServerUser->iId = id; setLastChannel(pDstServerUser); - msg.set_user_id(id); + msg.set_user_id(static_cast< unsigned int >(id)); bDstAclChanged = true; } else { // Registration failed @@ -1764,7 +1767,7 @@ void Server::msgACL(ServerUser *uSource, MumbleProto::ACL &msg) { Channel *p; ChanACL *acl; - QSet< int > qsId; + QSet< unsigned int > qsId; msg.clear_groups(); msg.clear_acls(); @@ -1790,8 +1793,8 @@ void Server::msgACL(ServerUser *uSource, MumbleProto::ACL &msg) { mpacl->set_apply_here(acl->bApplyHere); mpacl->set_apply_subs(acl->bApplySubs); if (acl->iUserId >= 0) { - mpacl->set_user_id(acl->iUserId); - qsId.insert(acl->iUserId); + mpacl->set_user_id(static_cast< unsigned int >(acl->iUserId)); + qsId.insert(static_cast< unsigned int >(acl->iUserId)); } else mpacl->set_group(u8(acl->qsGroup)); mpacl->set_grant(acl->pAllow); @@ -1813,18 +1816,18 @@ void Server::msgACL(ServerUser *uSource, MumbleProto::ACL &msg) { group->set_inherited(pg && pg->bInheritable); if (g) { foreach (int id, g->qsAdd) { - qsId.insert(id); - group->add_add(id); + qsId.insert(static_cast< unsigned int >(id)); + group->add_add(static_cast< unsigned int >(id)); } foreach (int id, g->qsRemove) { - qsId.insert(id); - group->add_remove(id); + qsId.insert(static_cast< unsigned int >(id)); + group->add_remove(static_cast< unsigned int >(id)); } } if (pg) { foreach (int id, pg->members()) { - qsId.insert(id); - group->add_inherited_members(id); + qsId.insert(static_cast< unsigned int >(id)); + group->add_inherited_members(static_cast< unsigned int >(id)); } } } @@ -1832,8 +1835,8 @@ void Server::msgACL(ServerUser *uSource, MumbleProto::ACL &msg) { sendMessage(uSource, msg); MumbleProto::QueryUsers mpqu; - foreach (int id, qsId) { - QString uname = getUserName(id); + foreach (unsigned int id, qsId) { + QString uname = getUserName(static_cast< int >(id)); if (!uname.isEmpty()) { mpqu.add_ids(id); mpqu.add_names(u8(uname)); @@ -1882,11 +1885,11 @@ void Server::msgACL(ServerUser *uSource, MumbleProto::ACL &msg) { g->bInherit = group.inherit(); g->bInheritable = group.inheritable(); for (int j = 0; j < group.add_size(); ++j) - if (!getUserName(group.add(j)).isEmpty()) - g->qsAdd << group.add(j); + if (!getUserName(static_cast< int >(group.add(j))).isEmpty()) + g->qsAdd << static_cast< int >(group.add(j)); for (int j = 0; j < group.remove_size(); ++j) - if (!getUserName(group.remove(j)).isEmpty()) - g->qsRemove << group.remove(j); + if (!getUserName(static_cast< int >(group.remove(j))).isEmpty()) + g->qsRemove << static_cast< int >(group.remove(j)); g->qsTemporary = hOldTemp.value(g->qsName); } @@ -1898,14 +1901,14 @@ void Server::msgACL(ServerUser *uSource, MumbleProto::ACL &msg) { // Add new ACLs for (int i = 0; i < msg.acls_size(); ++i) { const MumbleProto::ACL_ChanACL &mpacl = msg.acls(i); - if (mpacl.has_user_id() && getUserName(mpacl.user_id()).isEmpty()) + if (mpacl.has_user_id() && getUserName(static_cast< int >(mpacl.user_id())).isEmpty()) continue; a = new ChanACL(c); a->bApplyHere = mpacl.apply_here(); a->bApplySubs = mpacl.apply_subs(); if (mpacl.has_user_id()) - a->iUserId = mpacl.user_id(); + a->iUserId = static_cast< int >(mpacl.user_id()); else a->qsGroup = u8(mpacl.group()); a->pDeny = static_cast< ChanACL::Permissions >(mpacl.deny()) & ChanACL::All; @@ -1963,13 +1966,11 @@ void Server::msgQueryUsers(ServerUser *uSource, MumbleProto::QueryUsers &msg) { MumbleProto::QueryUsers reply; for (int i = 0; i < msg.ids_size(); ++i) { - int id = msg.ids(i); - if (id >= 0) { - const QString &name = getUserName(id); - if (!name.isEmpty()) { - reply.add_ids(id); - reply.add_names(u8(name)); - } + unsigned int id = msg.ids(i); + const QString &name = getUserName(static_cast< int >(id)); + if (!name.isEmpty()) { + reply.add_ids(id); + reply.add_names(u8(name)); } } @@ -1978,7 +1979,7 @@ void Server::msgQueryUsers(ServerUser *uSource, MumbleProto::QueryUsers &msg) { int id = getUserID(name); if (id >= 0) { name = getUserName(id); - reply.add_ids(id); + reply.add_ids(static_cast< unsigned int >(id)); reply.add_names(u8(name)); } } @@ -2050,7 +2051,7 @@ void Server::msgContextAction(ServerUser *uSource, MumbleProto::ContextAction &m if (session && !qhUsers.contains(session)) return; - if ((id >= 0) && !qhChannels.contains(id)) + if ((id >= 0) && !qhChannels.contains(static_cast< unsigned int >(id))) return; emit contextAction(uSource, u8(msg.action()), session, id); } @@ -2112,10 +2113,10 @@ void Server::msgUserList(ServerUser *uSource, MumbleProto::UserList &msg) { // Skip the SuperUser if (it->user_id > 0) { ::MumbleProto::UserList_User *user = msg.add_users(); - user->set_user_id(it->user_id); + user->set_user_id(static_cast< unsigned int >(it->user_id)); user->set_name(u8(it->name)); - if (it->last_channel) { - user->set_last_channel(*it->last_channel); + if (it->last_channel >= 0) { + user->set_last_channel(static_cast< unsigned int >(*it->last_channel)); } user->set_last_seen(u8(it->last_active.toString(Qt::ISODate))); } @@ -2126,13 +2127,13 @@ void Server::msgUserList(ServerUser *uSource, MumbleProto::UserList &msg) { for (int i = 0; i < msg.users_size(); ++i) { const MumbleProto::UserList_User &user = msg.users(i); - int id = user.user_id(); + unsigned int id = user.user_id(); if (id == 0) continue; if (!user.has_name()) { log(uSource, QString::fromLatin1("Unregistered user %1").arg(id)); - unregisterUser(id); + unregisterUser(static_cast< int >(id)); } else { const QString &name = u8(user.name()).trimmed(); if (validateUserName(name)) { @@ -2140,11 +2141,11 @@ void Server::msgUserList(ServerUser *uSource, MumbleProto::UserList &msg) { QMap< int, QString > info; info.insert(ServerDB::User_Name, name); - setInfo(id, info); + setInfo(static_cast< int >(id), info); MumbleProto::UserState mpus; foreach (ServerUser *serverUser, qhUsers) { - if (serverUser->iId == id) { + if (serverUser->iId == static_cast< int >(id)) { serverUser->qsName = name; mpus.set_session(serverUser->uiSession); break; @@ -2174,7 +2175,7 @@ void Server::msgVoiceTarget(ServerUser *uSource, MumbleProto::VoiceTarget &msg) MSG_SETUP_NO_UNIDLE(ServerUser::Authenticated); - int target = msg.id(); + int target = static_cast< int >(msg.id()); if ((target < 1) || (target >= 0x1f)) return; @@ -2198,7 +2199,7 @@ void Server::msgVoiceTarget(ServerUser *uSource, MumbleProto::VoiceTarget &msg) unsigned int id = t.channel_id(); if (qhChannels.contains(id)) { WhisperTarget::Channel wtc; - wtc.iId = id; + wtc.iId = static_cast< int >(id); wtc.bChildren = t.children(); wtc.bLinks = t.links(); if (t.has_group()) @@ -2310,10 +2311,10 @@ void Server::msgUserStats(ServerUser *uSource, MumbleProto::UserStats &msg) { } if (local) - msg.set_bandwidth(bwr.bandwidth()); - msg.set_onlinesecs(bwr.onlineSeconds()); + msg.set_bandwidth(static_cast< unsigned int >(bwr.bandwidth())); + msg.set_onlinesecs(static_cast< unsigned int >(bwr.onlineSeconds())); if (local) - msg.set_idlesecs(bwr.idleSeconds()); + msg.set_idlesecs(static_cast< unsigned int >(bwr.idleSeconds())); sendMessage(uSource, msg); } @@ -2330,8 +2331,8 @@ void Server::msgRequestBlob(ServerUser *uSource, MumbleProto::RequestBlob &msg) if (ndescriptions) { MumbleProto::ChannelState mpcs; for (int i = 0; i < ndescriptions; ++i) { - int id = msg.channel_description(i); - Channel *c = qhChannels.value(id); + unsigned int id = msg.channel_description(i); + Channel *c = qhChannels.value(id); if (c && !c->qsDesc.isEmpty()) { mpcs.set_channel_id(id); mpcs.set_description(u8(c->qsDesc)); @@ -2342,8 +2343,8 @@ void Server::msgRequestBlob(ServerUser *uSource, MumbleProto::RequestBlob &msg) if (ntextures || ncomments) { MumbleProto::UserState mpus; for (int i = 0; i < ntextures; ++i) { - int session = msg.session_texture(i); - ServerUser *su = qhUsers.value(session); + unsigned int session = msg.session_texture(i); + ServerUser *su = qhUsers.value(session); if (su && !su->qbaTexture.isEmpty()) { mpus.set_session(session); mpus.set_texture(blob(su->qbaTexture)); @@ -2353,8 +2354,8 @@ void Server::msgRequestBlob(ServerUser *uSource, MumbleProto::RequestBlob &msg) if (ntextures) mpus.clear_texture(); for (int i = 0; i < ncomments; ++i) { - int session = msg.session_comment(i); - ServerUser *su = qhUsers.value(session); + unsigned int session = msg.session_comment(i); + ServerUser *su = qhUsers.value(session); if (su && !su->qsComment.isEmpty()) { mpus.set_session(session); mpus.set_comment(u8(su->qsComment)); @@ -2403,7 +2404,7 @@ void Server::msgPluginDataTransmission(ServerUser *sender, MumbleProto::PluginDa // Copy needed data from message in order to be able to remove info about receivers from the message as this doesn't // matter for the client - size_t receiverAmount = msg.receiversessions_size(); + size_t receiverAmount = static_cast< std::size_t >(msg.receiversessions_size()); const ::google::protobuf::RepeatedField<::google::protobuf::uint32 > receiverSessions = msg.receiversessions(); msg.clear_receiversessions(); diff --git a/src/murmur/Meta.cpp b/src/murmur/Meta.cpp index 45bbc4ccab2..a27f2dce26e 100644 --- a/src/murmur/Meta.cpp +++ b/src/murmur/Meta.cpp @@ -136,8 +136,9 @@ MetaParams::~MetaParams() { * @param settings The QSettings object to read from. If null, the Meta's qsSettings will be used. * @return Setting if valid, default if not or setting not set. */ -template< class T > -T MetaParams::typeCheckedFromSettings(const QString &name, const T &defaultValue, QSettings *settings) { +template< class ValueType, class ReturnType > +ReturnType MetaParams::typeCheckedFromSettings(const QString &name, const ValueType &defaultValue, + QSettings *settings) { // Use qsSettings unless a specific QSettings instance // is requested. if (!settings) { @@ -146,16 +147,15 @@ T MetaParams::typeCheckedFromSettings(const QString &name, const T &defaultValue QVariant cfgVariable = settings->value(name, defaultValue); - if (!cfgVariable.convert( - QVariant(defaultValue) - .type())) { // Bit convoluted as canConvert() only does a static check without considering whether - // say a string like "blub" is actually a valid double (which convert does). + // Bit convoluted as canConvert() only does a static check without considering whether + // say a string like "blub" is actually a valid double (which convert does). + if (!cfgVariable.convert(static_cast< int >(QVariant(defaultValue).type()))) { qCritical() << "Configuration variable" << name << "is of invalid format. Set to default value of" << defaultValue << "."; - return defaultValue; + return static_cast< ReturnType >(defaultValue); } - return cfgVariable.value< T >(); + return cfgVariable.value< ReturnType >(); } void MetaParams::read(QString fname) { @@ -370,11 +370,11 @@ void MetaParams::read(QString fname) { qrUserName = QRegExp(typeCheckedFromSettings("username", qrUserName.pattern())); qrChannelName = QRegExp(typeCheckedFromSettings("channelname", qrChannelName.pattern())); - iMessageLimit = typeCheckedFromSettings("messagelimit", 1); - iMessageBurst = typeCheckedFromSettings("messageburst", 5); + iMessageLimit = typeCheckedFromSettings< unsigned int >("messagelimit", 1); + iMessageBurst = typeCheckedFromSettings< unsigned int >("messageburst", 5); - iPluginMessageLimit = typeCheckedFromSettings("pluginmessagelimit", 4); - iPluginMessageBurst = typeCheckedFromSettings("pluginmessageburst", 15); + iPluginMessageLimit = typeCheckedFromSettings< unsigned int >("pluginmessagelimit", 4); + iPluginMessageBurst = typeCheckedFromSettings< unsigned int >("pluginmessageburst", 15); broadcastListenerVolumeAdjustments = typeCheckedFromSettings("broadcastlistenervolumeadjustments", false); @@ -382,10 +382,10 @@ void MetaParams::read(QString fname) { if (bObfuscate) { qWarning("IP address obfuscation enabled."); #if QT_VERSION >= QT_VERSION_CHECK(5, 10, 0) - iObfuscate = QRandomGenerator::global()->generate(); + iObfuscate = static_cast< int >(QRandomGenerator::global()->generate()); #else // Qt 5.10 introduces the QRandomGenerator class and in Qt 5.15 qrand got deprecated in its favor - iObfuscate = qrand(); + iObfuscate = static_cast< int >(qrand()); #endif } bSendVersion = typeCheckedFromSettings("sendversion", bSendVersion); @@ -713,8 +713,8 @@ bool Meta::boot(int srvnum) { #ifdef Q_OS_UNIX unsigned int sockets = 19; // Base foreach (s, qhServers) { - sockets += 11; // Listen sockets, signal pipes etc. - sockets += s->iMaxUsers; // One per user + sockets += 11; // Listen sockets, signal pipes etc. + sockets += static_cast< unsigned int >(s->iMaxUsers); // One per user } struct rlimit r; @@ -778,7 +778,7 @@ bool Meta::banCheck(const QHostAddress &addr) { if (qhBans.contains(addr)) { Timer t = qhBans.value(addr); - if (t.elapsed() < (1000000ULL * mp.iBanTime)) + if (t.elapsed() < (1000000ULL * static_cast< unsigned long long >(mp.iBanTime))) return true; qhBans.remove(addr); } @@ -786,7 +786,7 @@ bool Meta::banCheck(const QHostAddress &addr) { QList< Timer > &ql = qhAttempts[addr]; ql.append(Timer()); - while (!ql.isEmpty() && (ql.at(0).elapsed() > (1000000ULL * mp.iBanTimeframe))) + while (!ql.isEmpty() && (ql.at(0).elapsed() > (1000000ULL * static_cast< unsigned long long >(mp.iBanTimeframe)))) ql.removeFirst(); if (ql.count() > mp.iBanTries) { diff --git a/src/murmur/Meta.h b/src/murmur/Meta.h index 4fc87f96eb4..47de6231838 100644 --- a/src/murmur/Meta.h +++ b/src/murmur/Meta.h @@ -34,11 +34,11 @@ class MetaParams { unsigned short usPort; int iTimeout; int iMaxBandwidth; - int iMaxUsers; - int iMaxUsersPerChannel; + unsigned int iMaxUsers; + unsigned int iMaxUsersPerChannel; int iMaxListenersPerChannel; int iMaxListenerProxiesPerUser; - int iDefaultChan; + unsigned int iDefaultChan; bool bRememberChan; int iRememberChanDuration; int iMaxTextMessageLength; @@ -168,14 +168,14 @@ class MetaParams { bool loadSSLSettings(); private: - template< class T > - T typeCheckedFromSettings(const QString &name, const T &variable, QSettings *settings = nullptr); + template< class ValueType, class ReturnType = ValueType > + ReturnType typeCheckedFromSettings(const QString &name, const ValueType &variable, QSettings *settings = nullptr); }; class Meta : public QObject { private: - Q_OBJECT; - Q_DISABLE_COPY(Meta); + Q_OBJECT + Q_DISABLE_COPY(Meta) public: static MetaParams mp; diff --git a/src/murmur/MumbleServerIce.cpp b/src/murmur/MumbleServerIce.cpp index b2a6f8696d2..19152640203 100644 --- a/src/murmur/MumbleServerIce.cpp +++ b/src/murmur/MumbleServerIce.cpp @@ -91,13 +91,13 @@ static std::string iceBase64(const std::string &s) { return std::string(ba64.data(), static_cast< size_t >(ba64.size())); } -static void logToLog(const ServerDB::LogRecord &r, ::MumbleServer::LogEntry &le) { - le.timestamp = r.first; - le.txt = iceString(r.second); +static void logToLog(const ServerDB::LogRecord &r, ::MumbleServer::LogEntry &entry) { + entry.timestamp = static_cast< int >(r.first); + entry.txt = iceString(r.second); } static void userToUser(const ::User *p, ::MumbleServer::User &mp) { - mp.session = p->uiSession; + mp.session = static_cast< int >(p->uiSession); mp.userid = p->iId; mp.name = iceString(p->qsName); mp.mute = p->bMute; @@ -107,14 +107,14 @@ static void userToUser(const ::User *p, ::MumbleServer::User &mp) { mp.prioritySpeaker = p->bPrioritySpeaker; mp.selfMute = p->bSelfMute; mp.selfDeaf = p->bSelfDeaf; - mp.channel = p->cChannel->iId; + mp.channel = static_cast< int >(p->cChannel->iId); mp.comment = iceString(p->qsComment); const ServerUser *u = static_cast< const ServerUser * >(p); mp.onlinesecs = u->bwr.onlineSeconds(); mp.bytespersec = u->bwr.bandwidth(); - mp.version2 = u->m_version; - mp.version = Version::toLegacyVersion(u->m_version); + mp.version2 = static_cast< long >(u->m_version); + mp.version = static_cast< int >(Version::toLegacyVersion(u->m_version)); mp.release = iceString(u->qsRelease); mp.os = iceString(u->qsOS); mp.osversion = iceString(u->qsOSVersion); @@ -140,14 +140,14 @@ static void userToUser(const ::User *p, ::MumbleServer::User &mp) { } static void channelToChannel(const ::Channel *c, ::MumbleServer::Channel &mc) { - mc.id = c->iId; + mc.id = static_cast< int >(c->iId); mc.name = iceString(c->qsName); - mc.parent = c->cParent ? c->cParent->iId : -1; + mc.parent = c->cParent ? static_cast< int >(c->cParent->iId) : -1; mc.description = iceString(c->qsDesc); mc.position = c->iPosition; mc.links.clear(); foreach (::Channel *chn, c->qsPermLinks) - mc.links.push_back(chn->iId); + mc.links.push_back(static_cast< int >(chn->iId)); mc.temporary = c->bTemporary; } @@ -157,8 +157,8 @@ static void ACLtoACL(const ::ChanACL *acl, ::MumbleServer::ACL &ma) { ma.inherited = false; ma.userid = acl->iUserId; ma.group = iceString(acl->qsGroup); - ma.allow = acl->pAllow; - ma.deny = acl->pDeny; + ma.allow = static_cast< int >(acl->pAllow); + ma.deny = static_cast< int >(acl->pDeny); } static void groupToGroup(const ::Group *g, ::MumbleServer::Group &mg) { @@ -181,8 +181,8 @@ static void banToBan(const ::Ban &b, ::MumbleServer::Ban &mb) { mb.name = iceString(b.qsUsername); mb.hash = iceString(b.qsHash); mb.reason = iceString(b.qsReason); - mb.start = b.qdtStart.toLocalTime().toTime_t(); - mb.duration = b.iDuration; + mb.start = static_cast< int >(b.qdtStart.toLocalTime().toTime_t()); + mb.duration = static_cast< int >(b.iDuration); } static void banToBan(const ::MumbleServer::Ban &mb, ::Ban &b) { @@ -198,7 +198,7 @@ static void banToBan(const ::MumbleServer::Ban &mb, ::Ban &b) { b.qsHash = u8(mb.hash); b.qsReason = u8(mb.reason); b.qdtStart = QDateTime::fromTime_t(static_cast< quint32 >(mb.start)).toUTC(); - b.iDuration = mb.duration; + b.iDuration = static_cast< unsigned int >(mb.duration); } static void infoToInfo(const QMap< int, QString > &info, ::MumbleServer::UserInfoMap &im) { @@ -217,13 +217,13 @@ static void textmessageToTextmessage(const ::TextMessage &tm, ::MumbleServer::Te tmdst.text = iceString(tm.qsText); foreach (unsigned int i, tm.qlSessions) - tmdst.sessions.push_back(i); + tmdst.sessions.push_back(static_cast< int >(i)); foreach (unsigned int i, tm.qlChannels) - tmdst.channels.push_back(i); + tmdst.channels.push_back(static_cast< int >(i)); foreach (unsigned int i, tm.qlTrees) - tmdst.trees.push_back(i); + tmdst.trees.push_back(static_cast< int >(i)); } class ServerLocator : public virtual Ice::ServantLocator { @@ -498,7 +498,7 @@ void MumbleServerIce::userConnected(const ::User *p) { void MumbleServerIce::userDisconnected(const ::User *p) { ::Server *s = qobject_cast<::Server * >(sender()); - qmServerContextCallbacks[s->iServerNum].remove(p->uiSession); + qmServerContextCallbacks[s->iServerNum].remove(static_cast< int >(p->uiSession)); const QList<::MumbleServer::ServerCallbackPrx > &qmList = qmServerCallbacks[s->iServerNum]; @@ -629,10 +629,10 @@ void MumbleServerIce::contextAction(const ::User *pSrc, const QString &action, u return; QMap< int, QMap< QString, ::MumbleServer::ServerContextCallbackPrx > > &qmServer = qmAll[s->iServerNum]; - if (!qmServer.contains(pSrc->uiSession)) + if (!qmServer.contains(static_cast< int >(pSrc->uiSession))) return; - QMap< QString, ::MumbleServer::ServerContextCallbackPrx > &qmUser = qmServer[pSrc->uiSession]; + QMap< QString, ::MumbleServer::ServerContextCallbackPrx > &qmUser = qmServer[static_cast< int >(pSrc->uiSession)]; if (!qmUser.contains(action)) return; @@ -642,13 +642,13 @@ void MumbleServerIce::contextAction(const ::User *pSrc, const QString &action, u userToUser(pSrc, mp); try { - prx->contextAction(iceString(action), mp, session, iChannel); + prx->contextAction(iceString(action), mp, static_cast< int >(session), iChannel); } catch (...) { s->log(QString("Ice ServerContextCallback %1 for session %2, action %3 failed") .arg(QString::fromStdString(communicator->proxyToString(prx))) .arg(pSrc->uiSession) .arg(action)); - removeServerContextCallback(s, pSrc->uiSession, action); + removeServerContextCallback(s, static_cast< int >(pSrc->uiSession), action); // Remove clientside entry MumbleProto::ContextActionModify mpcam; @@ -680,7 +680,7 @@ void MumbleServerIce::idToTextureSlot(QByteArray &qba, int id) { qba.resize(static_cast< int >(tex.size())); char *ptr = qba.data(); for (unsigned int i = 0; i < tex.size(); ++i) - ptr[i] = tex[i]; + ptr[i] = static_cast< char >(tex[i]); } catch (...) { badAuthenticator(server); } @@ -707,15 +707,15 @@ void MumbleServerIce::authenticateSlot(int &res, QString &uname, int sessionId, ::MumbleServer::GroupNameList groups; ::MumbleServer::CertificateList certs; - certs.resize(certlist.size()); + certs.resize(static_cast< std::size_t >(certlist.size())); for (int i = 0; i < certlist.size(); ++i) { ::MumbleServer::CertificateDer der; QByteArray qba = certlist.at(i).toDer(); - der.resize(qba.size()); + der.resize(static_cast< std::size_t >(qba.size())); const char *ptr = qba.constData(); for (int j = 0; j < qba.size(); ++j) - der[j] = ptr[j]; - certs[i] = der; + der[static_cast< std::size_t >(j)] = static_cast< unsigned char >(ptr[j]); + certs[static_cast< std::size_t >(i)] = der; } try { @@ -828,10 +828,10 @@ void MumbleServerIce::setTextureSlot(int &res, int id, const QByteArray &texture return; ::MumbleServer::Texture tex; - tex.resize(texture.size()); + tex.resize(static_cast< std::size_t >(texture.size())); const char *ptr = texture.constData(); - for (int i = 0; i < texture.size(); ++i) - tex[i] = ptr[i]; + for (unsigned int i = 0; i < static_cast< unsigned int >(texture.size()); ++i) + tex[i] = static_cast< unsigned char >(ptr[i]); try { res = prx->setTexture(id, tex); @@ -860,15 +860,15 @@ Ice::ObjectPtr ServerLocator::locate(const Ice::Current &, Ice::LocalObjectPtr & return; \ } -#define NEED_PLAYER \ - ServerUser *user = server->qhUsers.value(session); \ - if (!user) { \ - cb->ice_exception(::MumbleServer::InvalidSessionException()); \ - return; \ +#define NEED_PLAYER \ + ServerUser *user = server->qhUsers.value(static_cast< unsigned int >(session)); \ + if (!user) { \ + cb->ice_exception(::MumbleServer::InvalidSessionException()); \ + return; \ } #define NEED_CHANNEL_VAR(x, y) \ - x = server->qhChannels.value(y); \ + x = server->qhChannels.value(static_cast< unsigned int >(y)); \ if (!x) { \ cb->ice_exception(::MumbleServer::InvalidChannelException()); \ return; \ @@ -1032,11 +1032,12 @@ static void impl_Server_getLog(const ::MumbleServer::AMD_Server_getLogPtr cb, in ::MumbleServer::LogList ll; - QList< ServerDB::LogRecord > dblog = ServerDB::getLog(server_id, min, max); + QList< ServerDB::LogRecord > dblog = + ServerDB::getLog(server_id, static_cast< unsigned int >(min), static_cast< unsigned int >(max)); foreach (const ServerDB::LogRecord &e, dblog) { - ::MumbleServer::LogEntry le; - logToLog(e, le); - ll.push_back(le); + ::MumbleServer::LogEntry entry; + logToLog(e, entry); + ll.push_back(std::move(entry)); } cb->ice_response(ll); } @@ -1057,7 +1058,7 @@ static void impl_Server_getUsers(const ::MumbleServer::AMD_Server_getUsersPtr cb ::MumbleServer::User mp; if (static_cast< const ServerUser * >(p)->sState == ::ServerUser::Authenticated) { userToUser(p, mp); - pm[p->uiSession] = mp; + pm[static_cast< int >(p->uiSession)] = mp; } } cb->ice_response(pm); @@ -1070,7 +1071,7 @@ static void impl_Server_getChannels(const ::MumbleServer::AMD_Server_getChannels foreach (const ::Channel *c, server->qhChannels) { ::MumbleServer::Channel mc; channelToChannel(c, mc); - cm[c->iId] = mc; + cm[static_cast< int >(c->iId)] = mc; } cb->ice_response(cm); } @@ -1119,15 +1120,15 @@ static void impl_Server_getCertificateList(const ::MumbleServer::AMD_Server_getC const QList< QSslCertificate > &certlist = user->peerCertificateChain(); - certs.resize(certlist.size()); + certs.resize(static_cast< std::size_t >(certlist.size())); for (int i = 0; i < certlist.size(); ++i) { ::MumbleServer::CertificateDer der; QByteArray qba = certlist.at(i).toDer(); - der.resize(qba.size()); + der.resize(static_cast< std::size_t >(qba.size())); const char *ptr = qba.constData(); - for (int j = 0; j < qba.size(); ++j) - der[j] = ptr[j]; - certs[i] = der; + for (unsigned int j = 0; j < static_cast< unsigned int >(qba.size()); ++j) + der[j] = static_cast< unsigned char >(ptr[j]); + certs[static_cast< std::size_t >(i)] = der; } cb->ice_response(certs); } @@ -1168,7 +1169,7 @@ static void impl_Server_kickUser(const ::MumbleServer::AMD_Server_kickUserPtr cb NEED_PLAYER; MumbleProto::UserRemove mpur; - mpur.set_session(session); + mpur.set_session(static_cast< unsigned int >(session)); mpur.set_reason(reason); server->sendAll(mpur); user->disconnectSocket(); @@ -1199,7 +1200,7 @@ static void impl_Server_effectivePermissions(const ::MumbleServer::AMD_Server_ef NEED_SERVER; NEED_PLAYER; NEED_CHANNEL; - cb->ice_response(server->effectivePermissions(user, channel)); + cb->ice_response(static_cast< int >(server->effectivePermissions(user, channel))); } static void impl_Server_addContextCallback(const MumbleServer::AMD_Server_addContextCallbackPtr cb, int server_id, @@ -1239,7 +1240,7 @@ static void impl_Server_addContextCallback(const MumbleServer::AMD_Server_addCon MumbleProto::ContextActionModify mpcam; mpcam.set_action(action); mpcam.set_text(text); - mpcam.set_context(ctx); + mpcam.set_context(static_cast< unsigned int >(ctx)); mpcam.set_operation(MumbleProto::ContextActionModify_Operation_Add); server->sendMessage(user, mpcam); } @@ -1256,7 +1257,7 @@ static void impl_Server_removeContextCallback(const MumbleServer::AMD_Server_rem cbptr->ice_oneway()->ice_connectionCached(false)->ice_timeout(5000)); foreach (int session, qmPrx.keys()) { - ServerUser *user = server->qhUsers.value(session); + ServerUser *user = server->qhUsers.value(static_cast< unsigned int >(session)); const QMap< QString, ::MumbleServer::ServerContextCallbackPrx > &qm = qmPrx[session]; foreach (const QString &act, qm.keys(oneway)) { mi->removeServerContextCallback(server, session, act); @@ -1379,15 +1380,15 @@ static void impl_Server_addChannel(const ::MumbleServer::AMD_Server_addChannelPt nc = server->addChannel(p, qsName); server->updateChannel(nc); - int newid = nc->iId; + unsigned int newid = nc->iId; MumbleProto::ChannelState mpcs; mpcs.set_channel_id(newid); - mpcs.set_parent(parent); + mpcs.set_parent(static_cast< unsigned int >(parent)); mpcs.set_name(name); server->sendAll(mpcs); - cb->ice_response(newid); + cb->ice_response(static_cast< int >(newid)); } #define ACCESS_Server_getACL_READ @@ -1645,10 +1646,10 @@ static void impl_Server_getTexture(const ::MumbleServer::AMD_Server_getTexturePt const QByteArray &qba = server->getUserTexture(userid); ::MumbleServer::Texture tex; - tex.resize(qba.size()); + tex.resize(static_cast< std::size_t >(qba.size())); const char *ptr = qba.constData(); - for (int i = 0; i < qba.size(); ++i) - tex[i] = ptr[i]; + for (unsigned int i = 0; i < static_cast< unsigned int >(qba.size()); ++i) + tex[i] = static_cast< unsigned char >(ptr[i]); cb->ice_response(tex); } @@ -1665,12 +1666,12 @@ static void impl_Server_setTexture(const ::MumbleServer::AMD_Server_setTexturePt QByteArray qba(static_cast< int >(tex.size()), 0); char *ptr = qba.data(); for (unsigned int i = 0; i < tex.size(); ++i) - ptr[i] = tex[i]; + ptr[i] = static_cast< char >(tex[i]); if (!server->setTexture(userid, qba)) { cb->ice_exception(InvalidTextureException()); } else { - ServerUser *user = server->qhUsers.value(userid); + ServerUser *user = server->qhUsers.value(static_cast< unsigned int >(userid)); if (user) { MumbleProto::UserState mpus; mpus.set_session(user->uiSession); @@ -1778,8 +1779,8 @@ static void impl_Server_getListeningChannels(const ::MumbleServer::AMD_Server_ge NEED_PLAYER; ::MumbleServer::IntList channelIDs; - foreach (int currentChannelID, server->m_channelListenerManager.getListenedChannelsForUser(user->uiSession)) { - channelIDs.push_back(currentChannelID); + for (unsigned int currentChannelID : server->m_channelListenerManager.getListenedChannelsForUser(user->uiSession)) { + channelIDs.push_back(static_cast< int >(currentChannelID)); } cb->ice_response(channelIDs); @@ -1792,7 +1793,7 @@ static void impl_Server_getListeningUsers(const ::MumbleServer::AMD_Server_getLi ::MumbleServer::IntList userSessions; foreach (unsigned int currentSession, server->m_channelListenerManager.getListenersForChannel(channel->iId)) { - userSessions.push_back(currentSession); + userSessions.push_back(static_cast< int >(currentSession)); } cb->ice_response(userSessions); @@ -1802,7 +1803,7 @@ static void impl_Server_sendWelcomeMessage(const ::MumbleServer::AMD_Server_send ::MumbleServer::IdList receiverUserIDs) { NEED_SERVER; - for (unsigned int session : receiverUserIDs) { + for (int session : receiverUserIDs) { NEED_PLAYER; server->sendWelcomeMessageTo(user); diff --git a/src/murmur/MumbleServerIce.h b/src/murmur/MumbleServerIce.h index fdb8bd02435..a65376daf1b 100644 --- a/src/murmur/MumbleServerIce.h +++ b/src/murmur/MumbleServerIce.h @@ -29,7 +29,7 @@ struct TextMessage; class MumbleServerIce : public QObject { friend class MurmurLocker; - Q_OBJECT; + Q_OBJECT protected: int count; diff --git a/src/murmur/RPC.cpp b/src/murmur/RPC.cpp index debce6ccbac..82728630185 100644 --- a/src/murmur/RPC.cpp +++ b/src/murmur/RPC.cpp @@ -249,9 +249,11 @@ void Server::setTempGroups(int userid, int sessionId, Channel *cChannel, const Q } } - User *p = qhUsers.value(userid); - if (p) - clearACLCache(p); + if (userid >= 0) { + User *p = qhUsers.value(static_cast< unsigned int >(userid)); + if (p) + clearACLCache(p); + } } /** diff --git a/src/murmur/Register.cpp b/src/murmur/Register.cpp index 13ebbd7470f..f56fc7ef882 100644 --- a/src/murmur/Register.cpp +++ b/src/murmur/Register.cpp @@ -23,10 +23,10 @@ void Server::initRegister() { if (!qsRegName.isEmpty() && !qsRegPassword.isEmpty() && qurlRegWeb.isValid() && qsPassword.isEmpty() && bAllowPing) #if QT_VERSION >= QT_VERSION_CHECK(5, 10, 0) - qtTick.start((60 + (QRandomGenerator::global()->generate() % 120)) * 1000); + qtTick.start((60 + (static_cast< int >(QRandomGenerator::global()->generate()) % 120)) * 1000); #else // Qt 5.10 introduces the QRandomGenerator class and in Qt 5.15 qrand got deprecated in its favor - qtTick.start((60 + (qrand() % 120)) * 1000); + qtTick.start((60 + (static_cast< int >(qrand()) % 120)) * 1000); #endif else log("Registration needs nonempty 'registername', 'registerpassword' and 'registerurl', must have an empty " @@ -45,10 +45,10 @@ void Server::update() { qnamNetwork = new QNetworkAccessManager(this); #if QT_VERSION >= QT_VERSION_CHECK(5, 10, 0) - qtTick.start(1000 * (60 * 60 + (QRandomGenerator::global()->generate() % 300))); + qtTick.start(1000 * (60 * 60 + (static_cast< int >(QRandomGenerator::global()->generate()) % 300))); #else // Qt 5.10 introduces the QRandomGenerator class and in Qt 5.15 qrand got deprecated in its favor - qtTick.start(1000 * (60 * 60 + (qrand() % 300))); + qtTick.start(1000 * (60 * 60 + (static_cast< int >(qrand()) % 300))); #endif QDomDocument doc; diff --git a/src/murmur/Server.cpp b/src/murmur/Server.cpp index 795b30beae9..32b574f56fc 100644 --- a/src/murmur/Server.cpp +++ b/src/murmur/Server.cpp @@ -222,7 +222,7 @@ Server::Server(int snum, QObject *p) : QThread(p) { Qt::QueuedConnection); connect(this, SIGNAL(reqSync(unsigned int)), this, SLOT(doSync(unsigned int))); - for (int i = 1; i < iMaxUsers * 2; ++i) + for (unsigned int i = 1; i < iMaxUsers * 2; ++i) qqIds.enqueue(i); connect(qtTimeout, SIGNAL(timeout()), this, SLOT(checkTimeout())); @@ -392,12 +392,12 @@ void Server::readParams() { usPort = static_cast< unsigned short >(getConf("port", usPort).toUInt()); iTimeout = getConf("timeout", iTimeout).toInt(); iMaxBandwidth = getConf("bandwidth", iMaxBandwidth).toInt(); - iMaxUsers = getConf("users", iMaxUsers).toInt(); - iMaxUsersPerChannel = getConf("usersperchannel", iMaxUsersPerChannel).toInt(); + iMaxUsers = getConf("users", iMaxUsers).toUInt(); + iMaxUsersPerChannel = getConf("usersperchannel", iMaxUsersPerChannel).toUInt(); iMaxTextMessageLength = getConf("textmessagelength", iMaxTextMessageLength).toInt(); iMaxImageMessageLength = getConf("imagemessagelength", iMaxImageMessageLength).toInt(); bAllowHTML = getConf("allowhtml", bAllowHTML).toBool(); - iDefaultChan = getConf("defaultchannel", iDefaultChan).toInt(); + iDefaultChan = getConf("defaultchannel", iDefaultChan).toUInt(); bRememberChan = getConf("rememberchannel", bRememberChan).toBool(); iRememberChanDuration = getConf("rememberchannelduration", iRememberChanDuration).toInt(); qsWelcomeText = getConf("welcometext", qsWelcomeText).toString(); @@ -480,17 +480,17 @@ void Server::setLiveConf(const QString &key, const QString &value) { if (length != iMaxBandwidth) { iMaxBandwidth = length; MumbleProto::ServerConfig mpsc; - mpsc.set_max_bandwidth(length); + mpsc.set_max_bandwidth(static_cast< unsigned int >(length)); sendAll(mpsc); } } else if (key == "users") { - int newmax = i ? i : Meta::mp.iMaxUsers; + unsigned int newmax = i ? static_cast< unsigned int >(i) : Meta::mp.iMaxUsers; if (iMaxUsers == newmax) return; iMaxUsers = newmax; qqIds.clear(); - for (int id = 1; id < iMaxUsers * 2; ++id) + for (unsigned int id = 1; id < iMaxUsers * 2; ++id) if (!qhUsers.contains(id)) qqIds.enqueue(id); @@ -498,13 +498,13 @@ void Server::setLiveConf(const QString &key, const QString &value) { mpsc.set_max_users(iMaxUsers); sendAll(mpsc); } else if (key == "usersperchannel") - iMaxUsersPerChannel = i ? i : Meta::mp.iMaxUsersPerChannel; + iMaxUsersPerChannel = i ? static_cast< unsigned int >(i) : Meta::mp.iMaxUsersPerChannel; else if (key == "textmessagelength") { int length = i ? i : Meta::mp.iMaxTextMessageLength; if (length != iMaxTextMessageLength) { iMaxTextMessageLength = length; MumbleProto::ServerConfig mpsc; - mpsc.set_message_length(length); + mpsc.set_message_length(static_cast< unsigned int >(length)); sendAll(mpsc); } } else if (key == "imagemessagelength") { @@ -512,7 +512,7 @@ void Server::setLiveConf(const QString &key, const QString &value) { if (length != iMaxImageMessageLength) { iMaxImageMessageLength = length; MumbleProto::ServerConfig mpsc; - mpsc.set_image_message_length(length); + mpsc.set_image_message_length(static_cast< unsigned int >(length)); sendAll(mpsc); } } else if (key == "allowhtml") { @@ -524,7 +524,7 @@ void Server::setLiveConf(const QString &key, const QString &value) { sendAll(mpsc); } } else if (key == "defaultchannel") - iDefaultChan = i ? i : Meta::mp.iDefaultChan; + iDefaultChan = i ? static_cast< unsigned int >(i) : Meta::mp.iDefaultChan; else if (key == "rememberchannel") bRememberChan = !v.isNull() ? QVariant(v).toBool() : Meta::mp.bRememberChan; else if (key == "rememberchannelduration") { @@ -641,10 +641,11 @@ gsl::span< const Mumble::Protocol::byte > if (pingData.requestAdditionalInformation) { pingData.requestAdditionalInformation = false; - pingData.serverVersion = Version::get(); - pingData.userCount = qhUsers.size() - m_botCount; + pingData.serverVersion = Version::get(); + assert(qhUsers.size() >= static_cast< int >(m_botCount)); + pingData.userCount = static_cast< unsigned int >(qhUsers.size()) - m_botCount; pingData.maxUserCount = iMaxUsers; - pingData.maxBandwidthPerUser = iMaxBandwidth; + pingData.maxBandwidthPerUser = static_cast< unsigned int >(iMaxBandwidth); pingData.containsAdditionalInformation = true; } else if (expectExtended) { // Return zero-length span @@ -690,7 +691,7 @@ void Server::udpActivated(int socket) { msg.msg_controllen = sizeof(controldata); int &sock = socket; - len = static_cast< quint32 >(::recvmsg(sock, &msg, MSG_TRUNC)); + len = static_cast< qint32 >(::recvmsg(sock, &msg, MSG_TRUNC)); # else socklen_t fromlen = sizeof(from); int &sock = socket; @@ -698,13 +699,14 @@ void Server::udpActivated(int socket) { MSG_TRUNC, reinterpret_cast< struct sockaddr * >(&from), &fromlen)); # endif #else - int fromlen = sizeof(from); + int fromlen = static_cast< int >(sizeof(from)); SOCKET sock = static_cast< SOCKET >(socket); - len = ::recvfrom(sock, reinterpret_cast< char * >(m_udpDecoder.getBuffer().data()), m_udpDecoder.getBuffer().size(), - 0, reinterpret_cast< struct sockaddr * >(&from), &fromlen); + len = ::recvfrom(sock, reinterpret_cast< char * >(m_udpDecoder.getBuffer().data()), + static_cast< int >(m_udpDecoder.getBuffer().size()), 0, + reinterpret_cast< struct sockaddr * >(&from), &fromlen); #endif - gsl::span< Mumble::Protocol::byte > inputData(&m_udpDecoder.getBuffer()[0], len); + gsl::span< Mumble::Protocol::byte > inputData(&m_udpDecoder.getBuffer()[0], static_cast< std::size_t >(len)); if (bAllowPing && m_udpDecoder.decodePing(inputData) && m_udpDecoder.getMessageType() == Mumble::Protocol::UDPMessageType::Ping) { @@ -718,8 +720,14 @@ void Server::udpActivated(int socket) { iov[0].iov_base = const_cast< Mumble::Protocol::byte * >(encodedPing.data()); ::sendmsg(sock, &msg, 0); #else - ::sendto(sock, reinterpret_cast< const char * >(encodedPing.data()), encodedPing.size(), 0, - reinterpret_cast< struct sockaddr * >(&from), fromlen); +# ifdef Q_OS_WIN + using size_type = int; +# else + using size_type = std::size_t; +# endif + ::sendto(sock, reinterpret_cast< const char * >(encodedPing.data()), + static_cast< size_type >(encodedPing.size()), 0, reinterpret_cast< struct sockaddr * >(&from), + fromlen); #endif } } @@ -738,14 +746,15 @@ void Server::run() { unsigned char buffer[Mumble::Protocol::MAX_UDP_PACKET_SIZE]; sockaddr_storage from; - int nfds = qlUdpSocket.count(); + unsigned int nfds = static_cast< unsigned int >(qlUdpSocket.count()); #ifdef Q_OS_UNIX socklen_t fromlen; - STACKVAR(struct pollfd, fds, nfds + 1); + std::vector< struct pollfd > fds; + fds.resize(static_cast< std::size_t >(nfds + 1)); - for (int i = 0; i < nfds; ++i) { - fds[i].fd = qlUdpSocket.at(i); + for (unsigned int i = 0; i < nfds; ++i) { + fds[i].fd = qlUdpSocket.at(static_cast< int >(i)); fds[i].events = POLLIN; fds[i].revents = 0; } @@ -755,9 +764,11 @@ void Server::run() { fds[nfds].revents = 0; #else int fromlen; - STACKVAR(SOCKET, fds, nfds); - STACKVAR(HANDLE, events, nfds + 1); - for (int i = 0; i < nfds; ++i) { + std::vector< SOCKET > fds; + fds.resize(nfds); + std::vector< HANDLE > events; + events.resize(nfds + 1); + for (unsigned int i = 0; i < nfds; ++i) { fds[i] = qlUdpSocket.at(i); events[i] = CreateEvent(nullptr, FALSE, FALSE, nullptr); ::WSAEventSelect(fds[i], events[i], FD_READ); @@ -771,7 +782,7 @@ void Server::run() { FrameMarkNamed(TracyConstants::UDP_FRAME); #ifdef Q_OS_UNIX - int pret = poll(fds, nfds, -1); + int pret = poll(fds.data(), nfds, -1); if (pret <= 0) { if (errno == EINTR) continue; @@ -788,7 +799,7 @@ void Server::run() { break; } - for (int i = 0; i < nfds - 1; ++i) { + for (unsigned int i = 0; i < nfds - 1; ++i) { if (fds[i].revents) { if (fds[i].revents & (POLLHUP | POLLERR | POLLNVAL)) { qCritical("poll event failure"); @@ -798,9 +809,9 @@ void Server::run() { int sock = fds[i].fd; #else - for (int i = 0; i < 1; ++i) { + for (unsigned int i = 0; i < 1; ++i) { { - DWORD ret = WaitForMultipleObjects(nfds, events, FALSE, INFINITE); + DWORD ret = WaitForMultipleObjects(nfds, events.data(), FALSE, INFINITE); if (ret == (WAIT_OBJECT_0 + nfds - 1)) { break; } @@ -834,7 +845,7 @@ void Server::run() { msg.msg_control = controldata; msg.msg_controllen = sizeof(controldata); - len = static_cast< quint32 >(::recvmsg(sock, &msg, MSG_TRUNC)); + len = static_cast< qint32 >(::recvmsg(sock, &msg, MSG_TRUNC)); Q_UNUSED(fromlen); # else len = static_cast< qint32 >(::recvfrom(sock, encrypt, Mumble::Protocol::MAX_UDP_PACKET_SIZE, MSG_TRUNC, @@ -875,7 +886,9 @@ void Server::run() { m_udpDecoder.setProtocolVersion(Version::UNKNOWN); } // This may be a general ping requesting server details, unencrypted. - if (bAllowPing && m_udpDecoder.decodePing(gsl::span< Mumble::Protocol::byte >(encrypt, len)) + if (bAllowPing + && m_udpDecoder.decodePing( + gsl::span< Mumble::Protocol::byte >(encrypt, static_cast< std::size_t >(len))) && m_udpDecoder.getMessageType() == Mumble::Protocol::UDPMessageType::Ping) { ZoneScopedN(TracyConstants::PING_PROCESSING_ZONE); @@ -889,7 +902,13 @@ void Server::run() { iov[0].iov_len = encodedPing.size(); ::sendmsg(sock, &msg, 0); #else - ::sendto(sock, reinterpret_cast< const char * >(encodedPing.data()), encodedPing.size(), 0, +# ifdef Q_OS_WIN + using size_type = int; +# else + using size_type = std::size_t; +# endif + ::sendto(sock, reinterpret_cast< const char * >(encodedPing.data()), + static_cast< size_type >(encodedPing.size()), 0, reinterpret_cast< struct sockaddr * >(&from), fromlen); #endif } @@ -899,7 +918,7 @@ void Server::run() { if (u) { - if (!checkDecrypt(u, encrypt, buffer, len)) { + if (!checkDecrypt(u, encrypt, buffer, static_cast< unsigned int >(len))) { continue; } } else { @@ -907,7 +926,9 @@ void Server::run() { // Unknown peer foreach (ServerUser *usr, qhHostUsers.value(ha)) { - if (checkDecrypt(usr, encrypt, buffer, len)) { // checkDecrypt takes the User's qrwlCrypt lock. + if (checkDecrypt( + usr, encrypt, buffer, + static_cast< unsigned int >(len))) { // checkDecrypt takes the User's qrwlCrypt lock. // Every time we relock, reverify users' existence. // The main thread might delete the user while the lock isn't held. unsigned int uiSession = usr->uiSession; @@ -933,7 +954,7 @@ void Server::run() { } len -= 4; - if (m_udpDecoder.decode(gsl::span< Mumble::Protocol::byte >(buffer, len))) { + if (m_udpDecoder.decode(gsl::span< Mumble::Protocol::byte >(buffer, static_cast< std::size_t >(len)))) { switch (m_udpDecoder.getMessageType()) { case Mumble::Protocol::UDPMessageType::Audio: { Mumble::Protocol::AudioData audioData = m_udpDecoder.getAudioData(); @@ -965,7 +986,8 @@ void Server::run() { handlePing(m_udpDecoder, m_udpPingEncoder, false); QByteArray cache; - sendMessage(*u, encodedPing.data(), encodedPing.size(), cache, true); + sendMessage(*u, encodedPing.data(), static_cast< int >(encodedPing.size()), cache, + true); } break; } @@ -978,7 +1000,7 @@ void Server::run() { } } #ifdef Q_OS_WIN - for (int i = 0; i < nfds - 1; ++i) { + for (unsigned int i = 0; i < nfds - 1; ++i) { ::WSAEventSelect(fds[i], nullptr, 0); CloseHandle(events[i]); } @@ -1013,10 +1035,14 @@ void Server::sendMessage(ServerUser &u, const unsigned char *data, int len, QByt if ((u.aiUdpFlag.load() == 1 || force) && (u.sUdpSocket != INVALID_SOCKET)) { #endif #if defined(__LP64__) - STACKVAR(char, ebuffer, len + 4 + 16); - char *buffer = reinterpret_cast< char * >(((reinterpret_cast< quint64 >(ebuffer) + 8) & ~7) + 4); + static std::vector< char > ebuffer; + ebuffer.resize(static_cast< std::size_t >(len + 4 + 16)); + char *buffer = reinterpret_cast< char * >( + ((reinterpret_cast< quint64 >(ebuffer.data()) + 8) & static_cast< quint64 >(~7)) + 4); #else - STACKVAR(char, buffer, len + 4); + std::vector< char > bufVec; + bufVec.resize(len + 4); + char *buffer = bufVec.data(); #endif { QMutexLocker wl(&u.qmCrypt); @@ -1026,7 +1052,7 @@ void Server::sendMessage(ServerUser &u, const unsigned char *data, int len, QByt } if (!u.csCrypt->encrypt(reinterpret_cast< const unsigned char * >(data), - reinterpret_cast< unsigned char * >(buffer), len)) { + reinterpret_cast< unsigned char * >(buffer), static_cast< unsigned int >(len))) { return; } } @@ -1041,7 +1067,7 @@ void Server::sendMessage(ServerUser &u, const unsigned char *data, int len, QByt struct iovec iov[1]; iov[0].iov_base = buffer; - iov[0].iov_len = len + 4; + iov[0].iov_len = static_cast< unsigned int >(len + 4); uint8_t controldata[CMSG_SPACE(std::max(sizeof(struct in6_pktinfo), sizeof(struct in_pktinfo)))]; memset(controldata, 0, sizeof(controldata)); @@ -1080,7 +1106,13 @@ void Server::sendMessage(ServerUser &u, const unsigned char *data, int len, QByt ::sendmsg(u.sUdpSocket, &msg, 0); #else - ::sendto(u.sUdpSocket, buffer, len + 4, 0, reinterpret_cast< struct sockaddr * >(&u.saiUdpAddress), +# ifdef Q_OS_WIN + using size_type = int; +# else + using size_type = std::size_t; +# endif + ::sendto(u.sUdpSocket, buffer, static_cast< size_type >(len + 4), 0, + reinterpret_cast< struct sockaddr * >(&u.saiUdpAddress), (u.saiUdpAddress.ss_family == AF_INET6) ? sizeof(struct sockaddr_in6) : sizeof(struct sockaddr_in)); #endif #ifdef Q_OS_WIN @@ -1123,9 +1155,9 @@ void Server::processMsg(ServerUser *u, Mumble::Protocol::AudioData audioData, Au BandwidthRecord *bw = &u->bwr; // IP + UDP + Crypt + Data - const int packetsize = 20 + 8 + 4 + audioData.payload.size(); + const std::size_t packetsize = 20 + 8 + 4 + audioData.payload.size(); - if (!bw->addFrame(packetsize, iMaxBandwidth / 8)) { + if (!bw->addFrame(static_cast< int >(packetsize), iMaxBandwidth / 8)) { // Suppress packet. return; } @@ -1183,27 +1215,27 @@ void Server::processMsg(ServerUser *u, Mumble::Protocol::AudioData audioData, Au } } } - } else if (u->qmTargets.contains(audioData.targetOrContext)) { // Whisper/Shout + } else if (u->qmTargets.contains(static_cast< int >(audioData.targetOrContext))) { // Whisper/Shout QSet< ServerUser * > channel; QSet< ServerUser * > direct; QHash< ServerUser *, VolumeAdjustment > cachedListeners; - if (u->qmTargetCache.contains(audioData.targetOrContext)) { + if (u->qmTargetCache.contains(static_cast< int >(audioData.targetOrContext))) { ZoneScopedN(TracyConstants::AUDIO_WHISPER_CACHE_STORE); - const WhisperTargetCache &cache = u->qmTargetCache.value(audioData.targetOrContext); + const WhisperTargetCache &cache = u->qmTargetCache.value(static_cast< int >(audioData.targetOrContext)); channel = cache.channelTargets; direct = cache.directTargets; cachedListeners = cache.listeningTargets; } else { ZoneScopedN(TracyConstants::AUDIO_WHISPER_CACHE_CREATE); - const WhisperTarget &wt = u->qmTargets.value(audioData.targetOrContext); + const WhisperTarget &wt = u->qmTargets.value(static_cast< int >(audioData.targetOrContext)); if (!wt.qlChannels.isEmpty()) { QMutexLocker qml(&qmCache); foreach (const WhisperTarget::Channel &wtc, wt.qlChannels) { - Channel *wc = qhChannels.value(wtc.iId); + Channel *wc = qhChannels.value(static_cast< unsigned int >(wtc.iId)); if (wc) { bool link = wtc.bLinks && !wc->qhLinks.isEmpty(); bool dochildren = wtc.bChildren && !wc->qlChannels.isEmpty(); @@ -1270,12 +1302,13 @@ void Server::processMsg(ServerUser *u, Mumble::Protocol::AudioData audioData, Au } } - int uiSession = u->uiSession; + unsigned int uiSession = u->uiSession; qrwlVoiceThread.unlock(); qrwlVoiceThread.lockForWrite(); if (qhUsers.contains(uiSession)) - u->qmTargetCache.insert(audioData.targetOrContext, { channel, direct, cachedListeners }); + u->qmTargetCache.insert(static_cast< int >(audioData.targetOrContext), + { channel, direct, cachedListeners }); qrwlVoiceThread.unlock(); qrwlVoiceThread.lockForRead(); if (!qhUsers.contains(uiSession)) @@ -1353,7 +1386,8 @@ void Server::processMsg(ServerUser *u, Mumble::Protocol::AudioData audioData, Au // Send encoded packet to all receivers of this range for (auto it = currentRange.begin; it != currentRange.end; ++it) { - sendMessage(it->getReceiver(), encodedPacket.data(), encodedPacket.size(), tcpCache); + sendMessage(it->getReceiver(), encodedPacket.data(), static_cast< int >(encodedPacket.size()), + tcpCache); } // Find next range @@ -1404,7 +1438,7 @@ void Server::newClient() { } foreach (const Ban &ban, qlBans) { - if (ban.haAddress.match(ha, ban.iMask)) { + if (ban.haAddress.match(ha, static_cast< unsigned int >(ban.iMask))) { log(QString("Ignoring connection: %1, Reason: %2, Username: %3, Hash: %4 (Server ban)") .arg(addressToString(sock->peerAddress(), sock->peerPort()), ban.qsReason, ban.qsUsername, ban.qsHash)); @@ -1654,7 +1688,7 @@ void Server::connectionClosed(QAbstractSocket::SocketError err, const QString &r if (u->sState == ServerUser::Authenticated) { if (m_channelListenerManager.isListeningToAny(u->uiSession)) { - foreach (int channelID, m_channelListenerManager.getListenedChannelsForUser(u->uiSession)) { + for (unsigned int channelID : m_channelListenerManager.getListenedChannelsForUser(u->uiSession)) { // Remove the client from the list on the server m_channelListenerManager.removeListener(u->uiSession, channelID); } @@ -1693,7 +1727,7 @@ void Server::connectionClosed(QAbstractSocket::SocketError err, const QString &r QCoreApplication::instance()->postEvent(this, new ExecEvent(boost::bind(&Server::removeChannel, this, old->iId))); - if (u->uiSession > 0 && static_cast< int >(u->uiSession) < iMaxUsers * 2) + if (u->uiSession > 0 && u->uiSession < iMaxUsers * 2) qqIds.enqueue(u->uiSession); // Reinsert session id into pool if (u->sState == ServerUser::Authenticated) { @@ -1732,7 +1766,8 @@ void Server::message(Mumble::Protocol::TCPMessageType type, const QByteArray &qb m_tcpTunnelDecoder.setProtocolVersion(u->m_version); if (m_tcpTunnelDecoder.decode(gsl::span< const Mumble::Protocol::byte >( - reinterpret_cast< const Mumble::Protocol::byte * >(qbaMsg.constData()), qbaMsg.size()))) { + reinterpret_cast< const Mumble::Protocol::byte * >(qbaMsg.constData()), + static_cast< std::size_t >(qbaMsg.size())))) { if (m_tcpTunnelDecoder.getMessageType() == Mumble::Protocol::UDPMessageType::Audio) { Mumble::Protocol::AudioData audioData = m_tcpTunnelDecoder.getAudioData(); // Allow all voice packets through by default. @@ -1811,7 +1846,7 @@ void Server::tcpTransmitData(QByteArray a, unsigned int id) { *reinterpret_cast< quint16 * >(&uc[0]) = qToBigEndian(static_cast< quint16 >(Mumble::Protocol::TCPMessageType::UDPTunnel)); *reinterpret_cast< quint32 * >(&uc[2]) = qToBigEndian(static_cast< quint32 >(len)); - memcpy(uc + 6, a.constData(), len); + memcpy(uc + 6, a.constData(), static_cast< std::size_t >(len)); c->sendMessage(qba); c->forceFlush(); @@ -1855,7 +1890,7 @@ void Server::sendProtoExcept(ServerUser *u, const ::google::protobuf::Message &m } } -void Server::removeChannel(int id) { +void Server::removeChannel(unsigned int id) { Channel *c = qhChannels.value(id); if (c) removeChannel(c); @@ -1958,7 +1993,11 @@ bool Server::unregisterUser(int id) { clearACLCache(u); MumbleProto::UserState mpus; mpus.set_session(u->uiSession); - mpus.set_user_id(-1); + // NOTE: We are assuming that the integer representation on the receiving end's machine is the same as on + // our machine in order to guarantee that back-casting the unsigned ID to a signed one will give back the + // value of -1. This is not ideal, but given it has seemingly worked for this long, it is not likely to + // start breaking now. + mpus.set_user_id(static_cast< unsigned int >(-1)); sendAll(mpus); u->iId = -1; @@ -2033,14 +2072,14 @@ void Server::sendClientPermission(ServerUser *u, Channel *c, bool explicitlyRequ if (explicitlyRequested) { // Store the last channel the client showed explicit interest in - u->iLastPermissionCheck = c->iId; + u->iLastPermissionCheck = static_cast< int >(c->iId); } - if (explicitlyRequested || u->qmPermissionSent.value(c->iId) != perm) { + if (explicitlyRequested || u->qmPermissionSent.value(static_cast< int >(c->iId)) != perm) { // Send the permission info only if the client has explicitly asked for it // or if the permissions have changed since the last time the client has // been informed about permission for this channel. - u->qmPermissionSent.insert(c->iId, perm); + u->qmPermissionSent.insert(static_cast< int >(c->iId), perm); MumbleProto::PermissionQuery mppq; mppq.set_channel_id(c->iId); @@ -2059,10 +2098,9 @@ void Server::sendClientPermission(ServerUser *u, Channel *c, bool explicitlyRequ */ void Server::flushClientPermissionCache(ServerUser *u, MumbleProto::PermissionQuery &mppq) { - QMap< int, unsigned int >::const_iterator i; bool match = (u->qmPermissionSent.count() < 20); - for (i = u->qmPermissionSent.constBegin(); (match && (i != u->qmPermissionSent.constEnd())); ++i) { - Channel *c = qhChannels.value(i.key()); + for (auto i = u->qmPermissionSent.constBegin(); (match && (i != u->qmPermissionSent.constEnd())); ++i) { + Channel *c = qhChannels.value(static_cast< unsigned int >(i.key())); if (!c) { match = false; } else { @@ -2078,15 +2116,15 @@ void Server::flushClientPermissionCache(ServerUser *u, MumbleProto::PermissionQu u->qmPermissionSent.clear(); - Channel *c = qhChannels.value(u->iLastPermissionCheck); + Channel *c = qhChannels.value(static_cast< unsigned int >(u->iLastPermissionCheck)); if (!c) { c = u->cChannel; - u->iLastPermissionCheck = c->iId; + u->iLastPermissionCheck = static_cast< int >(c->iId); } ChanACL::hasPermission(u, c, ChanACL::Enter, &acCache); unsigned int perm = acCache.value(u)->value(c); - u->qmPermissionSent.insert(c->iId, perm); + u->qmPermissionSent.insert(static_cast< int >(c->iId), perm); mppq.Clear(); mppq.set_channel_id(c->iId); @@ -2362,7 +2400,7 @@ bool Server::isChannelFull(Channel *c, ServerUser *u) { return static_cast< unsigned int >(c->qlUsers.count()) >= c->uiMaxUsers; } if (iMaxUsersPerChannel) { - return c->qlUsers.count() >= iMaxUsersPerChannel; + return static_cast< unsigned int >(c->qlUsers.count()) >= iMaxUsersPerChannel; } return false; } diff --git a/src/murmur/Server.h b/src/murmur/Server.h index 7546d3c15e1..2cee156c8c9 100644 --- a/src/murmur/Server.h +++ b/src/murmur/Server.h @@ -65,7 +65,7 @@ struct TextMessage { class SslServer : public QTcpServer { private: - Q_OBJECT; + Q_OBJECT Q_DISABLE_COPY(SslServer) protected: QList< QSslSocket * > qlSockets; @@ -79,7 +79,7 @@ class SslServer : public QTcpServer { #define EXEC_QEVENT (QEvent::User + 959) class ExecEvent : public QEvent { - Q_DISABLE_COPY(ExecEvent); + Q_DISABLE_COPY(ExecEvent) protected: boost::function< void() > func; @@ -91,8 +91,8 @@ class ExecEvent : public QEvent { class Server : public QThread { private: - Q_OBJECT; - Q_DISABLE_COPY(Server); + Q_OBJECT + Q_DISABLE_COPY(Server) protected: bool bRunning; @@ -112,9 +112,9 @@ class Server : public QThread { unsigned short usPort; int iTimeout; int iMaxBandwidth; - int iMaxUsers; - int iMaxUsersPerChannel; - int iDefaultChan; + unsigned int iMaxUsers; + unsigned int iMaxUsersPerChannel; + unsigned int iDefaultChan; bool bRememberChan; int iRememberChanDuration; int iMaxTextMessageLength; @@ -242,7 +242,7 @@ public slots: public: int iServerNum; - QQueue< int > qqIds; + QQueue< unsigned int > qqIds; QList< SslServer * > qlServer; QTimer *qtTimeout; @@ -367,7 +367,7 @@ public slots: void log(const QString &) const; void log(ServerUser *u, const QString &) const; - void removeChannel(int id); + void removeChannel(unsigned int id); void removeChannel(Channel *c, Channel *dest = nullptr); void userEnterChannel(User *u, Channel *c, MumbleProto::UserState &mpus); bool unregisterUser(int id); diff --git a/src/murmur/ServerDB.cpp b/src/murmur/ServerDB.cpp index 29565a2ae91..ebe7c41032d 100644 --- a/src/murmur/ServerDB.cpp +++ b/src/murmur/ServerDB.cpp @@ -1823,9 +1823,9 @@ Channel *Server::addChannel(Channel *p, const QString &name, bool temporary, int SQLPREP("SELECT MAX(`channel_id`)+1 AS id FROM `%1channels` WHERE `server_id`=?"); query.addBindValue(iServerNum); SQLEXEC(); - int id = 0; + unsigned int id = 0; if (query.next()) - id = query.value(0).toInt(); + id = query.value(0).toUInt(); // Temporary channels might "complicate" this somewhat. while (qhChannels.contains(id)) @@ -2045,7 +2045,7 @@ void Server::updateChannel(const Channel *c) { void Server::readChannelPrivs(Channel *c) { TransactionHolder th; - int cid = c->iId; + unsigned int cid = c->iId; QSqlQuery &query = *th.qsqQuery; @@ -2114,8 +2114,8 @@ void Server::readChannels(Channel *p) { int parentid = -1; if (p) { - parentid = p->iId; - readChannelPrivs(qhChannels.value(parentid)); + parentid = static_cast< int >(p->iId); + readChannelPrivs(qhChannels.value(p->iId)); } { @@ -2133,7 +2133,7 @@ void Server::readChannels(Channel *p) { SQLEXEC(); while (query.next()) { - c = new Channel(query.value(0).toInt(), query.value(1).toString(), p); + c = new Channel(query.value(0).toUInt(), query.value(1).toString(), p); if (!p) c->setParent(this); qhChannels.insert(c->iId, c); @@ -2157,8 +2157,8 @@ void Server::readLinks() { SQLEXEC(); while (query.next()) { - int cid = query.value(0).toInt(); - int lid = query.value(1).toInt(); + unsigned int cid = query.value(0).toUInt(); + unsigned int lid = query.value(1).toUInt(); Channel *c = qhChannels.value(cid); Channel *l = qhChannels.value(lid); @@ -2207,7 +2207,7 @@ int Server::readLastChannel(int id) { SQLEXEC(); if (query.next()) { - int cid = query.value(0).toInt(); + unsigned int cid = query.value(0).toUInt(); if (!qhChannels.contains(cid)) { return -1; @@ -2216,7 +2216,7 @@ int Server::readLastChannel(int id) { int duration = Meta::mp.iRememberChanDuration; if (duration <= 0) { - return cid; + return static_cast< int >(cid); } if (query.value(1).isNull()) { @@ -2244,7 +2244,7 @@ int Server::readLastChannel(int id) { } if (last_disconnect.secsTo(QDateTime::currentDateTime()) <= duration) { - return cid; + return static_cast< int >(cid); } } return -1; @@ -2317,7 +2317,7 @@ void Server::getBans() { ban.qsReason = query.value(4).toString(); ban.qdtStart = query.value(5).toDateTime(); ban.qdtStart.setTimeSpec(Qt::UTC); - ban.iDuration = query.value(6).toInt(); + ban.iDuration = query.value(6).toUInt(); if (ban.isValid()) qlBans << ban; @@ -2430,9 +2430,9 @@ void Server::loadChannelListenersOf(const ServerUser &user) { SQLEXEC(); while (query.next()) { - int channelID = query.value(0).toInt(); - float volume = query.value(1).toFloat(); - bool enabled = query.value(2).toUInt() == 1; + unsigned int channelID = query.value(0).toUInt(); + float volume = query.value(1).toFloat(); + bool enabled = query.value(2).toUInt() == 1; if (enabled) { m_channelListenerManager.addListener(user.uiSession, channelID); diff --git a/src/murmur/ServerDB.h b/src/murmur/ServerDB.h index 5d1b25419fb..aa07c4b72da 100644 --- a/src/murmur/ServerDB.h +++ b/src/murmur/ServerDB.h @@ -18,7 +18,7 @@ class QSqlDatabase; class QSqlQuery; class ServerDB : public QObject { - Q_OBJECT; + Q_OBJECT public: /// A version number that allows us to keep track of changes we make to the DB architecture diff --git a/src/murmur/ServerUser.cpp b/src/murmur/ServerUser.cpp index 3b6b374ef5a..d5d2c5ababf 100644 --- a/src/murmur/ServerUser.cpp +++ b/src/murmur/ServerUser.cpp @@ -55,7 +55,7 @@ bool BandwidthRecord::addFrame(int size, int maxpersec) { return false; int nsum = iSum - a_iBW[iRecNum] + size; - int bw = static_cast< int >((nsum * 1000000LL) / elapsed); + int bw = static_cast< int >((static_cast< quint64 >(nsum) * 1000000ULL) / elapsed); if (bw > maxpersec) return false; @@ -114,7 +114,7 @@ int BandwidthRecord::bandwidth() const { if (elapsed < 250000ULL) return 0; - return static_cast< int >((sum * 1000000ULL) / elapsed); + return static_cast< int >((static_cast< quint64 >(sum) * 1000000ULL) / elapsed); } LeakyBucket::LeakyBucket(unsigned int tokensPerSec, unsigned int maxTokens) diff --git a/src/murmur/TracyConstants.h b/src/murmur/TracyConstants.h index 58d470746a1..0995a6285bc 100644 --- a/src/murmur/TracyConstants.h +++ b/src/murmur/TracyConstants.h @@ -20,6 +20,6 @@ static constexpr const char *AUDIO_ENCODE = "audio_encode"; static constexpr const char *AUDIO_UPDATE = "audio_update"; static constexpr const char *AUDIO_WHISPER_CACHE_STORE = "audio_whisper_cache_restore"; static constexpr const char *AUDIO_WHISPER_CACHE_CREATE = "audio_whisper_cache_create"; -}; // namespace TracyConstants +} // namespace TracyConstants #endif // MUMBLE_MURMUR_TRACYCONSTANTS_H_ diff --git a/src/murmur/Tray.h b/src/murmur/Tray.h index 5d6d2e40e64..4ffa8c07025 100644 --- a/src/murmur/Tray.h +++ b/src/murmur/Tray.h @@ -16,7 +16,7 @@ class QAction; class Tray : public QObject { private: Q_OBJECT - Q_DISABLE_COPY(Tray); + Q_DISABLE_COPY(Tray) protected: QSystemTrayIcon *qsti; diff --git a/src/tests/Emit.cpp b/src/tests/Emit.cpp index 06d261a18f0..35667d42f47 100644 --- a/src/tests/Emit.cpp +++ b/src/tests/Emit.cpp @@ -9,7 +9,7 @@ #include class Slotter : public QObject { - Q_OBJECT; + Q_OBJECT public: Slotter(QObject *p = nullptr) : QObject(p){}; @@ -18,7 +18,7 @@ public Q_SLOTS: }; class Emitter : public QObject { - Q_OBJECT; + Q_OBJECT public: Slotter *s; diff --git a/src/tests/TestAudioReceiverBuffer/TestAudioReceiverBuffer.cpp b/src/tests/TestAudioReceiverBuffer/TestAudioReceiverBuffer.cpp index fed889d07a5..d75719e9361 100644 --- a/src/tests/TestAudioReceiverBuffer/TestAudioReceiverBuffer.cpp +++ b/src/tests/TestAudioReceiverBuffer/TestAudioReceiverBuffer.cpp @@ -89,7 +89,7 @@ class PseudoEncoder { }; class TestAudioReceiverBuffer : public QObject { - Q_OBJECT; + Q_OBJECT private slots: void test_preconditions() { // Preconditions for these test to make any sense @@ -209,11 +209,11 @@ private slots: ServerUser &sender = contextUser2; buffer.addReceiver(sender, users[0], Mumble::Protocol::AudioContext::NORMAL, false, - VolumeAdjustment::fromFactor(1.22)); + VolumeAdjustment::fromFactor(1.22f)); buffer.addReceiver(sender, users[1], Mumble::Protocol::AudioContext::NORMAL, false, - VolumeAdjustment::fromFactor(1.22 + 0.6 * AudioReceiverBuffer::maxFactorDiff)); + VolumeAdjustment::fromFactor(1.22f + 0.6f * AudioReceiverBuffer::maxFactorDiff)); buffer.addReceiver(sender, users[2], Mumble::Protocol::AudioContext::NORMAL, false, - VolumeAdjustment::fromFactor(1.22 + 1.1 * AudioReceiverBuffer::maxFactorDiff)); + VolumeAdjustment::fromFactor(1.22f + 1.1f * AudioReceiverBuffer::maxFactorDiff)); buffer.addReceiver(sender, users[3], Mumble::Protocol::AudioContext::NORMAL, false, VolumeAdjustment::fromDBAdjustment(-60)); buffer.addReceiver(sender, users[4], Mumble::Protocol::AudioContext::NORMAL, false, diff --git a/src/tests/TestCrypt/TestCrypt.cpp b/src/tests/TestCrypt/TestCrypt.cpp index 1c768c06c19..8ff6f4b5c3b 100644 --- a/src/tests/TestCrypt/TestCrypt.cpp +++ b/src/tests/TestCrypt/TestCrypt.cpp @@ -163,7 +163,7 @@ void TestCrypt::testvectors() { unsigned char source[40]; unsigned char crypt[40]; - for (int i = 0; i < 40; i++) + for (unsigned char i = 0; i < 40; i++) source[i] = i; QVERIFY(cs.ocb_encrypt(source, crypt, 40, rawkey, tag)); const unsigned char longtag[AES_BLOCK_SIZE] = { 0x9D, 0xB0, 0xCD, 0xF8, 0x80, 0xF7, 0x3E, 0x3E, @@ -181,7 +181,7 @@ void TestCrypt::testvectors() { } void TestCrypt::authcrypt() { - for (int len = 0; len < 128; len++) { + for (unsigned int len = 0; len < 128; len++) { const unsigned char rawkey[AES_BLOCK_SIZE] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f }; const unsigned char nonce[AES_BLOCK_SIZE] = { 0xff, 0xee, 0xdd, 0xcc, 0xbb, 0xaa, 0x99, 0x88, @@ -191,22 +191,25 @@ void TestCrypt::authcrypt() { CryptStateOCB2 cs; cs.setKey(rawkey_str, nonce_str, nonce_str); - STACKVAR(unsigned char, src, len); - for (int i = 0; i < len; i++) - src[i] = (i + 1); + std::vector< unsigned char > src; + src.resize(len); + for (unsigned char i = 0; i < len; i++) + src[i] = static_cast< unsigned char >(i + 1); unsigned char enctag[AES_BLOCK_SIZE]; unsigned char dectag[AES_BLOCK_SIZE]; - STACKVAR(unsigned char, encrypted, len); - STACKVAR(unsigned char, decrypted, len); + std::vector< unsigned char > encrypted; + encrypted.resize(len); + std::vector< unsigned char > decrypted; + decrypted.resize(len); - QVERIFY(cs.ocb_encrypt(src, encrypted, len, nonce, enctag)); - QVERIFY(cs.ocb_decrypt(encrypted, decrypted, len, nonce, dectag)); + QVERIFY(cs.ocb_encrypt(src.data(), encrypted.data(), len, nonce, enctag)); + QVERIFY(cs.ocb_decrypt(encrypted.data(), decrypted.data(), len, nonce, dectag)); for (int i = 0; i < AES_BLOCK_SIZE; i++) QCOMPARE(enctag[i], dectag[i]); - for (int i = 0; i < len; i++) + for (unsigned int i = 0; i < len; i++) QCOMPARE(src[i], decrypted[i]); } } @@ -222,26 +225,28 @@ void TestCrypt::xexstarAttack() { CryptStateOCB2 cs; cs.setKey(rawkey_str, nonce_str, nonce_str); - STACKVAR(unsigned char, src, 2 * AES_BLOCK_SIZE); + std::vector< unsigned char > src; + src.resize(2 * AES_BLOCK_SIZE); // Set first block to `len(secondBlock)` - memset(src, 0, AES_BLOCK_SIZE); src[AES_BLOCK_SIZE - 1] = AES_BLOCK_SIZE * 8; // Set second block to arbitrary value - memset(src + AES_BLOCK_SIZE, 42, AES_BLOCK_SIZE); + memset(src.data() + AES_BLOCK_SIZE, 42, AES_BLOCK_SIZE); unsigned char enctag[AES_BLOCK_SIZE]; unsigned char dectag[AES_BLOCK_SIZE]; - STACKVAR(unsigned char, encrypted, 2 * AES_BLOCK_SIZE); - STACKVAR(unsigned char, decrypted, 2 * AES_BLOCK_SIZE); + std::vector< unsigned char > encrypted; + encrypted.resize(2 * AES_BLOCK_SIZE); + std::vector< unsigned char > decrypted; + decrypted.resize(2 * AES_BLOCK_SIZE); - const bool failed_encrypt = !cs.ocb_encrypt(src, encrypted, 2 * AES_BLOCK_SIZE, nonce, enctag, false); + const bool failed_encrypt = !cs.ocb_encrypt(src.data(), encrypted.data(), 2 * AES_BLOCK_SIZE, nonce, enctag, false); // Perform the attack encrypted[AES_BLOCK_SIZE - 1] ^= AES_BLOCK_SIZE * 8; - for (int i = 0; i < AES_BLOCK_SIZE; ++i) + for (unsigned int i = 0; i < AES_BLOCK_SIZE; ++i) enctag[i] = src[AES_BLOCK_SIZE + i] ^ encrypted[AES_BLOCK_SIZE + i]; - const bool failed_decrypt = !cs.ocb_decrypt(encrypted, decrypted, 1 * AES_BLOCK_SIZE, nonce, dectag); + const bool failed_decrypt = !cs.ocb_decrypt(encrypted.data(), decrypted.data(), 1 * AES_BLOCK_SIZE, nonce, dectag); // Verify forged tag (should match if attack is properly implemented) for (int i = 0; i < AES_BLOCK_SIZE; ++i) { @@ -256,8 +261,8 @@ void TestCrypt::xexstarAttack() { // since digital silence appears to produce them in mass. // So instead we now modify the packet in a way which should not affect the audio but will // prevent the attack. - QVERIFY(cs.ocb_encrypt(src, encrypted, 2 * AES_BLOCK_SIZE, nonce, enctag)); - QVERIFY(cs.ocb_decrypt(encrypted, decrypted, 2 * AES_BLOCK_SIZE, nonce, dectag)); + QVERIFY(cs.ocb_encrypt(src.data(), encrypted.data(), 2 * AES_BLOCK_SIZE, nonce, enctag)); + QVERIFY(cs.ocb_decrypt(encrypted.data(), decrypted.data(), 2 * AES_BLOCK_SIZE, nonce, dectag)); // Tags should match for (int i = 0; i < AES_BLOCK_SIZE; ++i) { @@ -280,18 +285,20 @@ void TestCrypt::tamper() { cs.setKey(rawkey_str, nonce_str, nonce_str); const unsigned char msg[] = "It was a funky funky town!"; - int len = sizeof(msg); - - STACKVAR(unsigned char, encrypted, len + 4); - STACKVAR(unsigned char, decrypted, len); - cs.encrypt(msg, encrypted, len); - - for (int i = 0; i < len * 8; i++) { - encrypted[i / 8] ^= 1 << (i % 8); - QVERIFY(!cs.decrypt(encrypted, decrypted, len + 4)); - encrypted[i / 8] ^= 1 << (i % 8); + unsigned int len = sizeof(msg); + + std::vector< unsigned char > encrypted; + encrypted.resize(len + 4); + std::vector< unsigned char > decrypted; + decrypted.resize(len); + cs.encrypt(msg, encrypted.data(), len); + + for (unsigned int i = 0; i < len * 8; i++) { + encrypted[i / 8] ^= static_cast< unsigned char >(1 << (i % 8)); + QVERIFY(!cs.decrypt(encrypted.data(), decrypted.data(), len + 4)); + encrypted[i / 8] ^= static_cast< unsigned char >(1 << (i % 8)); } - QVERIFY(cs.decrypt(encrypted, decrypted, len + 4)); + QVERIFY(cs.decrypt(encrypted.data(), decrypted.data(), len + 4)); } QTEST_MAIN(TestCrypt) diff --git a/src/tests/TestCryptographicRandom/TestCryptographicRandom.cpp b/src/tests/TestCryptographicRandom/TestCryptographicRandom.cpp index 722291f46e7..ad7b1927ba1 100644 --- a/src/tests/TestCryptographicRandom/TestCryptographicRandom.cpp +++ b/src/tests/TestCryptographicRandom/TestCryptographicRandom.cpp @@ -60,14 +60,14 @@ void TestCryptographicRandom::uint32() { for (int i = 0; i < 10; i++) { unsigned char *buf = reinterpret_cast< unsigned char * >(calloc(buflen, 1)); - int niter = buflen / sizeof(uint32_t); - for (int j = 0; j < niter; j++) { - int off = j * sizeof(uint32_t); - uint32_t val = CryptographicRandom::uint32(); - buf[off] = val & 0xff; - buf[off + 1] = (val >> 8) & 0xff; - buf[off + 2] = (val >> 16) & 0xff; - buf[off + 3] = (val >> 24) & 0xff; + unsigned int niter = buflen / sizeof(uint32_t); + for (unsigned int j = 0; j < niter; j++) { + unsigned int off = static_cast< unsigned int >(j * sizeof(uint32_t)); + uint32_t val = CryptographicRandom::uint32(); + buf[off] = static_cast< unsigned char >(val & 0xff); + buf[off + 1] = static_cast< unsigned char >((val >> 8) & 0xff); + buf[off + 2] = static_cast< unsigned char >((val >> 16) & 0xff); + buf[off + 3] = static_cast< unsigned char >((val >> 24) & 0xff); } QVERIFY(verifyEntropy(buf, buflen)); free(buf); diff --git a/src/tests/TestMumbleProtocol/TestMumbleProtocol.cpp b/src/tests/TestMumbleProtocol/TestMumbleProtocol.cpp index 1ae5eee45c3..9ca521486c5 100644 --- a/src/tests/TestMumbleProtocol/TestMumbleProtocol.cpp +++ b/src/tests/TestMumbleProtocol/TestMumbleProtocol.cpp @@ -77,8 +77,8 @@ namespace Protocol { using UDPAudioEncoder< role >::getPreEncodedVolumeAdjustment; }; -}; // namespace Protocol -}; // namespace Mumble +} // namespace Protocol +} // namespace Mumble template< Mumble::Protocol::Role encoderRole, Mumble::Protocol::Role decoderRole > void do_test_ping() { Mumble::Protocol::UDPPingEncoder< encoderRole > encoder; @@ -103,7 +103,16 @@ template< Mumble::Protocol::Role encoderRole, Mumble::Protocol::Role decoderRole QCOMPARE(decoder.getPingData(), data); // Extended ping (request) +#ifdef _MSVC_LANG +# pragma warning(push) + // Disable warning about this if condition being constant + // TODO: Use if constexpr as soon as we have moved to C++17 (or higher) +# pragma warning(disable : 4127) +#endif if (decoderRole == Mumble::Protocol::Role::Server) { +#ifdef _MSVC_LANG +# pragma warning(pop) +#endif QVERIFY(encoderRole == Mumble::Protocol::Role::Client); data.requestAdditionalInformation = true; @@ -169,7 +178,16 @@ template< Mumble::Protocol::Role encoderRole, Mumble::Protocol::Role decoderRole data.volumeAdjustment = VolumeAdjustment::fromFactor(1.4f); } +#ifdef _MSVC_LANG +# pragma warning(push) + // Disable warning about this if condition being constant + // TODO: Use if constexpr as soon as we have moved to C++17 (or higher) +# pragma warning(disable : 4127) +#endif if (decoderRole == Mumble::Protocol::Role::Client) { +#ifdef _MSVC_LANG +# pragma warning(pop) +#endif QVERIFY(encoder.getRole() == Mumble::Protocol::Role::Server); data.targetOrContext = Mumble::Protocol::AudioContext::SHOUT; @@ -223,7 +241,7 @@ template< Mumble::Protocol::Role encoderRole, Mumble::Protocol::Role decoderRole } class TestMumbleProtocol : public QObject { - Q_OBJECT; + Q_OBJECT private slots: void test_ping_client_to_server() { do_test_ping< Mumble::Protocol::Role::Client, Mumble::Protocol::Role::Server >(); @@ -287,16 +305,16 @@ private slots: QVERIFY2(!snippet.empty(), "Unable to find pre-encoded snippet for volume adjustment"); - msg.ParseFromArray(snippet.data(), snippet.size()); + msg.ParseFromArray(snippet.data(), static_cast< int >(snippet.size())); // This will perform a fuzzy-compare - QCOMPARE(msg.volume_adjustment(), std::pow(2.0f, currentAdjustment / 6.0f)); + QCOMPARE(msg.volume_adjustment(), std::pow(2.0f, static_cast< float >(currentAdjustment) / 6.0f)); } // Ensure that an unknown/unexpected volume adjustment yields an empty span QVERIFY(encoder.getPreEncodedVolumeAdjustment(VolumeAdjustment::fromDBAdjustment(MIN - 1)).empty()); // We only expect pre-encoded values for integer dB adjustments - QVERIFY(encoder.getPreEncodedVolumeAdjustment(VolumeAdjustment(std::pow(2.0f, (MAX + 0.5) / 6.0f))).empty()); + QVERIFY(encoder.getPreEncodedVolumeAdjustment(VolumeAdjustment(std::pow(2.0f, (MAX + 0.5f) / 6.0f))).empty()); } }; diff --git a/src/tests/TestPacketDataStream/TestPacketDataStream.cpp b/src/tests/TestPacketDataStream/TestPacketDataStream.cpp index 66593b16fd3..ff91ac4b777 100644 --- a/src/tests/TestPacketDataStream/TestPacketDataStream.cpp +++ b/src/tests/TestPacketDataStream/TestPacketDataStream.cpp @@ -26,7 +26,7 @@ private slots: void TestPacketDataStream::floating_data() { QTest::addColumn< double >("value"); for (int i = 1; i < 256; i++) { - double v = 1.0L / (1.0L * i); + double v = 1.0 / (1.0 * i); QTest::newRow("Positive") << v; QTest::newRow("Negative") << -v; } diff --git a/src/tests/TestVersion/TestVersion.cpp b/src/tests/TestVersion/TestVersion.cpp index 3aaa9c50a95..0890a828e03 100644 --- a/src/tests/TestVersion/TestVersion.cpp +++ b/src/tests/TestVersion/TestVersion.cpp @@ -11,7 +11,7 @@ #include class TestVersion : public QObject { - Q_OBJECT; + Q_OBJECT private slots: void legacy_encode() { From 6b4b50f8f2a29fc288ff76684dddb9588368660b Mon Sep 17 00:00:00 2001 From: Robert Adam Date: Sun, 7 Jan 2024 17:18:37 +0100 Subject: [PATCH 13/13] BUILD: Use LTO by default for everything but Debug builds Instead of relying on explicitly having to use the "Release" target, we now enable LTO for everything but the special "Debug" target. That is, we assume that every configuration other than "Debug" is likely meant as some sort of release build (potentially with external flags) and thus we want to make use of LTO. --- CMakeLists.txt | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index d4738dc686f..6a51c0ae204 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -161,7 +161,8 @@ add_compile_definitions(MUMBLE_TARGET_OS="${MUMBLE_TARGET_OS}") set(CMAKE_UNITY_BUILD_BATCH_SIZE 40) -set(CMAKE_INTERPROCEDURAL_OPTIMIZATION_RELEASE ${lto}) +set(CMAKE_INTERPROCEDURAL_OPTIMIZATION ${lto}) +set(CMAKE_INTERPROCEDURAL_OPTIMIZATION_DEBUG OFF) if(client OR server) add_subdirectory(src)