Support Qt6, Min Qt5.8, Fix Win32, Fix Servatrice

Add lock around deleting arrows for commanding cards

Add support for Qt6 w/ Backwards Qt5

Handle Qt5/6 cross compilation better

Last cleanups

caps matter

Fix serv

Prevent crash on 6.3.0 Linux & bump to 5.8 min

Prevent out of bounds indexing

Delete shutdown timer if it exists

Fixup ticket comments, remove unneeded guards

Try to add support for missing OSes

Update .ci/release_template.md

Update PR based on comments

Update XML name after done and remove Hirsute

Address local game crash

Address comments from PR (again)
Tests don't work on mac, will see if a problem on other OSes

make soundengine more consistent across qt versions

disable tests on distros that are covered by others

Fix Oracle Crash due to bad memory access

Update Oracle to use new Qt6 way of adding translations

Add support for Qt5/Qt6 compiling of Cockatrice

Remove unneeded calls to QtMath/cmath/math.h

Update how we handle bitwise comparisons for enums with Tray Icon

Change header guards to not duplicate function

Leave comment & Fix Path for GHA Qt

Update common/server.h

Update cockatrice/src/window_main.cpp

Rollback change on cmake module path for NSIS

check docker image requirements

add size limit to ccache

put variables in quotes

properly set build type on mac

avoid names used in cmake

fix up cmake module path

cmake 3.10 does not recognize prepend

Support Tests in FindQtRuntime

set ccache size on non debug builds as well

immediately return when removing non existing client

handle incTxBytes with a signal instead

don't set common link libraries in cockatrice/CMakeLists.txt

add comments

set macos qt version to 6

Try upgrading XCode versions to latest they can be supported on

Ensure Qt gets linked

add tmate so i can see what's going on

Qt6 points two directories further down than Qt5 with regard to the top lib path, so we need to account for this

Establish Plugins directory for Qt6

Establish TLS plugins for Qt6 services

Minor change for release channel network manager

Let windows build in parallel cores

Wrong symbols

Qt6 patch up for signal

add missing qt6 package on deb builds

boolean expressions are hard

negative indexes should go to the end

Intentionally fail cache

move size checks to individual zone types

Hardcode libs needed for building on Windows, as the regex was annoying

Update wording

use the --parallel option in all builds

clean up the .ci scripts some more

tweak fedora build

add os parameter to compile.sh

I don't really like this but it seems the easiest way
I'd prefer if these types of quirks would live in the main configuration
file, the yml

fixup yml

readd appended cache key to vcpkg step

fix windows 32 quirk

the json hash is already added to the key as well

remove os parameter and clean up ci files

set name_build.sh to output relative paths

set backwards compatible version of xcode and qt on mac

set QTDIR for mac builds on qt5

has no effect for qt6

export BUILD_DIR to name_build.sh

merge mac build steps

merge homebrew steps, set package suffix

link qt5

remove brew link

set qtdir to qt5 only

compile.sh vars need to be empty not 0

fix sets manager search bar on qt 5.12/15

fix oracle subprocess errors being ignored on qt 5

clean up translation loading

move en@source translation file so it will not get included in packages
NOTE: this needs to be done at transifex as well!

Use generator platform over osname

Short circuit if not Win defined
This commit is contained in:
ZeldaZach 2022-03-27 19:59:37 -04:00 committed by ZeldaZach
parent accd5e4df7
commit b02adccf87
114 changed files with 1925 additions and 1603 deletions

View file

@ -138,7 +138,7 @@ IF(UPDATE_TRANSLATIONS)
FILE(GLOB_RECURSE translate_cockatrice_SRCS ${CMAKE_SOURCE_DIR}/cockatrice/src/*.cpp ${CMAKE_SOURCE_DIR}/cockatrice/src/*.h)
FILE(GLOB_RECURSE translate_common_SRCS ${CMAKE_SOURCE_DIR}/common/*.cpp ${CMAKE_SOURCE_DIR}/common/*.h)
SET(translate_SRCS ${translate_cockatrice_SRCS} ${translate_common_SRCS})
SET(cockatrice_TS "${CMAKE_CURRENT_SOURCE_DIR}/translations/cockatrice_en@source.ts")
SET(cockatrice_TS "${CMAKE_CURRENT_SOURCE_DIR}/cockatrice_en@source.ts")
ELSE()
FILE(GLOB cockatrice_TS "${CMAKE_CURRENT_SOURCE_DIR}/translations/*.ts")
ENDIF(UPDATE_TRANSLATIONS)
@ -153,30 +153,11 @@ if(APPLE)
set(cockatrice_SOURCES ${cockatrice_SOURCES} ${CMAKE_CURRENT_SOURCE_DIR}/resources/appicon.icns)
ENDIF(APPLE)
# Qt5
find_package(Qt5 COMPONENTS Concurrent Multimedia Network PrintSupport Svg WebSockets Widgets REQUIRED)
set(COCKATRICE_QT_MODULES Qt5::Concurrent Qt5::Multimedia Qt5::Network Qt5::PrintSupport Qt5::Svg Qt5::Widgets Qt5::WebSockets)
# Qt5LinguistTools
find_package(Qt5LinguistTools)
if(Qt5LinguistTools_FOUND)
list(APPEND COCKATRICE_LIBS Qt5::LinguistTools)
if(NOT Qt5_LRELEASE_EXECUTABLE)
MESSAGE(WARNING "Qt's lrelease not found.")
endif()
if(UPDATE_TRANSLATIONS)
if(NOT Qt5_LUPDATE_EXECUTABLE)
MESSAGE(WARNING "Qt's lupdate not found.")
endif()
QT5_CREATE_TRANSLATION(cockatrice_QM ${translate_SRCS} ${cockatrice_TS})
else()
QT5_ADD_TRANSLATION(cockatrice_QM ${cockatrice_TS})
endif()
endif()
QT5_ADD_RESOURCES(cockatrice_RESOURCES_RCC ${cockatrice_RESOURCES})
IF(Qt6_FOUND)
Qt6_ADD_RESOURCES(cockatrice_RESOURCES_RCC ${cockatrice_RESOURCES})
ELSEIF(Qt5_FOUND)
Qt5_ADD_RESOURCES(cockatrice_RESOURCES_RCC ${cockatrice_RESOURCES})
ENDIF()
# Declare path variables
set(ICONDIR share/icons CACHE STRING "icon dir")
@ -188,10 +169,38 @@ INCLUDE_DIRECTORIES(${PROTOBUF_INCLUDE_DIR})
INCLUDE_DIRECTORIES(${CMAKE_BINARY_DIR}/common)
INCLUDE_DIRECTORIES(${CMAKE_CURRENT_BINARY_DIR})
# Build cockatrice binary and link it
ADD_EXECUTABLE(cockatrice WIN32 MACOSX_BUNDLE ${cockatrice_SOURCES} ${cockatrice_QM} ${cockatrice_RESOURCES_RCC} ${cockatrice_MOC_SRCS})
set(COCKATRICE_MAC_QM_INSTALL_DIR "cockatrice.app/Contents/Resources/translations")
set(COCKATRICE_UNIX_QM_INSTALL_DIR "share/cockatrice/translations")
set(COCKATRICE_WIN32_QM_INSTALL_DIR "translations")
TARGET_LINK_LIBRARIES(cockatrice cockatrice_common ${COCKATRICE_QT_MODULES})
if(Qt6_FOUND)
qt6_add_executable(cockatrice WIN32 MACOSX_BUNDLE ${cockatrice_SOURCES} ${cockatrice_RESOURCES_RCC} ${cockatrice_MOC_SRCS} MANUAL_FINALIZATION)
elseif(Qt5_FOUND)
# Qt5 Translations need to be linked at executable creation time
if(Qt5LinguistTools_FOUND)
if(UPDATE_TRANSLATIONS)
qt5_create_translation(cockatrice_QM ${translate_SRCS} ${cockatrice_TS})
else()
qt5_add_translation(cockatrice_QM ${cockatrice_TS})
endif()
endif()
add_executable(cockatrice WIN32 MACOSX_BUNDLE ${cockatrice_SOURCES} ${cockatrice_QM} ${cockatrice_RESOURCES_RCC} ${cockatrice_MOC_SRCS})
if(UNIX)
if(APPLE)
install(FILES ${cockatrice_QM} DESTINATION ${COCKATRICE_MAC_QM_INSTALL_DIR})
else()
install(FILES ${cockatrice_QM} DESTINATION ${COCKATRICE_UNIX_QM_INSTALL_DIR})
endif()
elseif(WIN32)
install(FILES ${cockatrice_QM} DESTINATION ${COCKATRICE_WIN32_QM_INSTALL_DIR})
endif()
endif()
if(Qt5_FOUND)
target_link_libraries(cockatrice cockatrice_common ${COCKATRICE_QT_MODULES})
else()
target_link_libraries(cockatrice PUBLIC cockatrice_common ${COCKATRICE_QT_MODULES})
endif()
if(UNIX)
if(APPLE)
@ -205,27 +214,23 @@ if(UNIX)
set_target_properties(cockatrice PROPERTIES MACOSX_BUNDLE_INFO_PLIST ${CMAKE_SOURCE_DIR}/cmake/Info.plist)
INSTALL(TARGETS cockatrice BUNDLE DESTINATION ./)
INSTALL(FILES ${cockatrice_QM} DESTINATION ./cockatrice.app/Contents/Resources/translations)
else()
# Assume linux
INSTALL(TARGETS cockatrice RUNTIME DESTINATION bin/)
INSTALL(FILES ${CMAKE_CURRENT_SOURCE_DIR}/resources/cockatrice.png DESTINATION ${ICONDIR}/hicolor/48x48/apps)
INSTALL(FILES ${CMAKE_CURRENT_SOURCE_DIR}/resources/cockatrice.svg DESTINATION ${ICONDIR}/hicolor/scalable/apps)
INSTALL(FILES ${CMAKE_CURRENT_SOURCE_DIR}/cockatrice.desktop DESTINATION ${DESKTOPDIR})
INSTALL(FILES ${cockatrice_QM} DESTINATION share/cockatrice/translations)
endif()
elseif(WIN32)
INSTALL(TARGETS cockatrice RUNTIME DESTINATION ./)
INSTALL(FILES ${cockatrice_QM} DESTINATION ./translations)
endif()
if(APPLE)
# these needs to be relative to CMAKE_INSTALL_PREFIX
set(plugin_dest_dir cockatrice.app/Contents/Plugins)
set(qtconf_dest_dir cockatrice.app/Contents/Resources)
get_filename_component(QT_LIBRARY_DIR "${QT_LIBRARY_DIR}/.." ABSOLUTE)
# qt5 plugins: audio, iconengines, imageformats, platforms, printsupport
# Qt plugins: audio (Qt5), iconengines, imageformats, platforms, printsupport (Qt5), styles, tls (Qt6)
install(DIRECTORY "${QT_PLUGINS_DIR}/" DESTINATION ${plugin_dest_dir} COMPONENT Runtime
FILES_MATCHING
PATTERN "*.dSYM" EXCLUDE
@ -236,6 +241,7 @@ if(APPLE)
PATTERN "platforms/*.dylib"
PATTERN "printsupport/*.dylib"
PATTERN "styles/*.dylib"
PATTERN "tls/*.dylib"
)
install(CODE "
@ -261,9 +267,32 @@ if(WIN32)
install(DIRECTORY "${CMAKE_BINARY_DIR}/${PROJECT_NAME}/${CMAKE_BUILD_TYPE}/" DESTINATION ./ FILES_MATCHING PATTERN "*.dll")
# qt5 plugins: audio, iconengines, imageformats, platforms, printsupport
install(DIRECTORY "${QT_PLUGINS_DIR}/" DESTINATION ${plugin_dest_dir} COMPONENT Runtime
FILES_MATCHING REGEX "(audio|iconengines|imageformats|platforms|printsupport|styles)/.*[^d]\\.dll")
# Qt plugins: audio (Qt5), iconengines, imageformats, platforms, printsupport (Qt5), styles, tls (Qt6)
install(DIRECTORY "${QT_PLUGINS_DIR}/" DESTINATION ${plugin_dest_dir} COMPONENT Runtime FILES_MATCHING
PATTERN "audio/qtaudio_wasapi.dll"
PATTERN "audio/qtaudio_windows.dll"
PATTERN "iconengines/qsvgicon.dll"
PATTERN "imageformats/qgif.dll"
PATTERN "imageformats/qicns.dll"
PATTERN "imageformats/qico.dll"
PATTERN "imageformats/qjpeg.dll"
PATTERN "imageformats/qsvg.dll"
PATTERN "imageformats/qtga.dll"
PATTERN "imageformats/qtiff.dll"
PATTERN "imageformats/qwbmp.dll"
PATTERN "imageformats/qwebp.dll"
PATTERN "platforms/qdirect2d.dll"
PATTERN "platforms/qminimal.dll"
PATTERN "platforms/qoffscreen.dll"
PATTERN "platforms/qwindows.dll"
PATTERN "printsupport/windowsprintersupport.dll"
PATTERN "styles/qcertonlybackend.dll"
PATTERN "styles/qopensslbackend.dll"
PATTERN "styles/qschannelbackend.dll"
PATTERN "styles/qwindowsvistastyle.dll"
PATTERN "tls/qcertonlybackend.dll"
PATTERN "tls/qopensslbackend.dll"
PATTERN "tls/qschannelbackend.dll")
install(CODE "
file(WRITE \"\${CMAKE_INSTALL_PREFIX}/${qtconf_dest_dir}/qt.conf\" \"[Paths]
@ -284,3 +313,26 @@ Data = Resources\")
install(FILES ${WIN32SSLRUNTIME_LIBRARIES} DESTINATION ./)
endif()
endif()
if(Qt6LinguistTools_FOUND)
#Qt6 Translations happen after the executable is built up
if(UPDATE_TRANSLATIONS)
qt6_add_translations(cockatrice TS_FILES ${cockatrice_TS} SOURCES ${translate_SRCS} QM_FILES_OUTPUT_VARIABLE cockatrice_QM)
else()
qt6_add_translations(cockatrice TS_FILES ${cockatrice_TS} QM_FILES_OUTPUT_VARIABLE cockatrice_QM)
endif()
if(UNIX)
if(APPLE)
install(FILES ${cockatrice_QM} DESTINATION ${COCKATRICE_MAC_QM_INSTALL_DIR})
else()
install(FILES ${cockatrice_QM} DESTINATION ${COCKATRICE_UNIX_QM_INSTALL_DIR})
endif()
elseif(WIN32)
install(FILES ${cockatrice_QM} DESTINATION ${COCKATRICE_WIN32_QM_INSTALL_DIR})
endif()
endif()
if(Qt6_FOUND)
qt6_finalize_target(cockatrice)
endif()

View file

@ -48,6 +48,7 @@ AbstractClient::AbstractClient(QObject *parent)
qRegisterMetaType<QList<ServerInfo_User>>("QList<ServerInfo_User>");
qRegisterMetaType<Event_ReplayAdded>("Event_ReplayAdded");
qRegisterMetaType<QList<QString>>("missingFeatures");
qRegisterMetaType<PendingCommand *>("pendingCommand");
FeatureSet features;
features.initalizeFeatureList(clientFeatures);

View file

@ -16,7 +16,7 @@
#include <QGraphicsScene>
#include <QGraphicsSceneMouseEvent>
#include <QPainter>
#include <cmath>
#include <QtMath>
ArrowItem::ArrowItem(Player *_player, int _id, ArrowTarget *_startItem, ArrowTarget *_targetItem, const QColor &_color)
: QGraphicsItem(), player(_player), id(_id), startItem(_startItem), targetItem(_targetItem), color(_color),
@ -71,7 +71,7 @@ void ArrowItem::updatePath(const QPointF &endPoint)
const double arrowWidth = 15.0;
const double headWidth = 40.0;
const double headLength =
headWidth / pow(2, 0.5); // aka headWidth / sqrt (2) but this produces a compile error with MSVC++
headWidth / qPow(2, 0.5); // aka headWidth / sqrt (2) but this produces a compile error with MSVC++
const double phi = 15;
if (!startItem)
@ -86,7 +86,7 @@ void ArrowItem::updatePath(const QPointF &endPoint)
if (lineLength < 30)
path = QPainterPath();
else {
QPointF c(lineLength / 2, tan(phi * M_PI / 180) * lineLength);
QPointF c(lineLength / 2, qTan(phi * M_PI / 180) * lineLength);
QPainterPath centerLine;
centerLine.moveTo(0, 0);
@ -97,22 +97,22 @@ void ArrowItem::updatePath(const QPointF &endPoint)
QLineF testLine(arrowBodyEndPoint, centerLine.pointAtPercent(percentage + 0.001));
qreal alpha = testLine.angle() - 90;
QPointF endPoint1 =
arrowBodyEndPoint + arrowWidth / 2 * QPointF(cos(alpha * M_PI / 180), -sin(alpha * M_PI / 180));
arrowBodyEndPoint + arrowWidth / 2 * QPointF(qCos(alpha * M_PI / 180), -qSin(alpha * M_PI / 180));
QPointF endPoint2 =
arrowBodyEndPoint + arrowWidth / 2 * QPointF(-cos(alpha * M_PI / 180), sin(alpha * M_PI / 180));
arrowBodyEndPoint + arrowWidth / 2 * QPointF(-qCos(alpha * M_PI / 180), qSin(alpha * M_PI / 180));
QPointF point1 =
endPoint1 + (headWidth - arrowWidth) / 2 * QPointF(cos(alpha * M_PI / 180), -sin(alpha * M_PI / 180));
endPoint1 + (headWidth - arrowWidth) / 2 * QPointF(qCos(alpha * M_PI / 180), -qSin(alpha * M_PI / 180));
QPointF point2 =
endPoint2 + (headWidth - arrowWidth) / 2 * QPointF(-cos(alpha * M_PI / 180), sin(alpha * M_PI / 180));
endPoint2 + (headWidth - arrowWidth) / 2 * QPointF(-qCos(alpha * M_PI / 180), qSin(alpha * M_PI / 180));
path = QPainterPath(-arrowWidth / 2 * QPointF(cos((phi - 90) * M_PI / 180), sin((phi - 90) * M_PI / 180)));
path = QPainterPath(-arrowWidth / 2 * QPointF(qCos((phi - 90) * M_PI / 180), qSin((phi - 90) * M_PI / 180)));
path.quadTo(c, endPoint1);
path.lineTo(point1);
path.lineTo(QPointF(lineLength, 0));
path.lineTo(point2);
path.lineTo(endPoint2);
path.quadTo(c, arrowWidth / 2 * QPointF(cos((phi - 90) * M_PI / 180), sin((phi - 90) * M_PI / 180)));
path.lineTo(-arrowWidth / 2 * QPointF(cos((phi - 90) * M_PI / 180), sin((phi - 90) * M_PI / 180)));
path.quadTo(c, arrowWidth / 2 * QPointF(qCos((phi - 90) * M_PI / 180), qSin((phi - 90) * M_PI / 180)));
path.lineTo(-arrowWidth / 2 * QPointF(qCos((phi - 90) * M_PI / 180), qSin((phi - 90) * M_PI / 180)));
}
setPos(startPoint);

View file

@ -23,7 +23,7 @@ bool CockatriceXml3Parser::getCanParseFile(const QString &fileName, QIODevice &d
QXmlStreamReader xml(&device);
while (!xml.atEnd()) {
if (xml.readNext() == QXmlStreamReader::StartElement) {
if (xml.name() == COCKATRICE_XML3_TAGNAME) {
if (xml.name().toString() == COCKATRICE_XML3_TAGNAME) {
int version = xml.attributes().value("version").toString().toInt();
if (version == COCKATRICE_XML3_TAGVER) {
return true;
@ -52,12 +52,13 @@ void CockatriceXml3Parser::parseFile(QIODevice &device)
break;
}
if (xml.name() == "sets") {
auto name = xml.name().toString();
if (name == "sets") {
loadSetsFromXml(xml);
} else if (xml.name() == "cards") {
} else if (name == "cards") {
loadCardsFromXml(xml);
} else if (xml.name() != "") {
qDebug() << "[CockatriceXml3Parser] Unknown item" << xml.name() << ", trying to continue anyway";
} else if (!name.isEmpty()) {
qDebug() << "[CockatriceXml3Parser] Unknown item" << name << ", trying to continue anyway";
xml.skipCurrentElement();
}
}
@ -72,26 +73,27 @@ void CockatriceXml3Parser::loadSetsFromXml(QXmlStreamReader &xml)
break;
}
if (xml.name() == "set") {
auto name = xml.name().toString();
if (name == "set") {
QString shortName, longName, setType;
QDate releaseDate;
while (!xml.atEnd()) {
if (xml.readNext() == QXmlStreamReader::EndElement) {
break;
}
name = xml.name().toString();
if (xml.name() == "name") {
if (name == "name") {
shortName = xml.readElementText(QXmlStreamReader::IncludeChildElements);
} else if (xml.name() == "longname") {
} else if (name == "longname") {
longName = xml.readElementText(QXmlStreamReader::IncludeChildElements);
} else if (xml.name() == "settype") {
} else if (name == "settype") {
setType = xml.readElementText(QXmlStreamReader::IncludeChildElements);
} else if (xml.name() == "releasedate") {
} else if (name == "releasedate") {
releaseDate =
QDate::fromString(xml.readElementText(QXmlStreamReader::IncludeChildElements), Qt::ISODate);
} else if (xml.name() != "") {
qDebug() << "[CockatriceXml3Parser] Unknown set property" << xml.name()
<< ", trying to continue anyway";
} else if (!name.isEmpty()) {
qDebug() << "[CockatriceXml3Parser] Unknown set property" << name << ", trying to continue anyway";
xml.skipCurrentElement();
}
}
@ -146,7 +148,8 @@ void CockatriceXml3Parser::loadCardsFromXml(QXmlStreamReader &xml)
break;
}
if (xml.name() == "card") {
auto xmlName = xml.name().toString();
if (xmlName == "card") {
QString name = QString("");
QString text = QString("");
QVariantHash properties = QVariantHash();
@ -162,37 +165,39 @@ void CockatriceXml3Parser::loadCardsFromXml(QXmlStreamReader &xml)
if (xml.readNext() == QXmlStreamReader::EndElement) {
break;
}
xmlName = xml.name().toString();
// variable - assigned properties
if (xml.name() == "name") {
if (xmlName == "name") {
name = xml.readElementText(QXmlStreamReader::IncludeChildElements);
} else if (xml.name() == "text") {
} else if (xmlName == "text") {
text = xml.readElementText(QXmlStreamReader::IncludeChildElements);
} else if (xml.name() == "color") {
} else if (xmlName == "color") {
colors.append(xml.readElementText(QXmlStreamReader::IncludeChildElements));
} else if (xml.name() == "token") {
} else if (xmlName == "token") {
isToken = static_cast<bool>(xml.readElementText(QXmlStreamReader::IncludeChildElements).toInt());
// generic properties
} else if (xml.name() == "manacost") {
} else if (xmlName == "manacost") {
properties.insert("manacost", xml.readElementText(QXmlStreamReader::IncludeChildElements));
} else if (xml.name() == "cmc") {
} else if (xmlName == "cmc") {
properties.insert("cmc", xml.readElementText(QXmlStreamReader::IncludeChildElements));
} else if (xml.name() == "type") {
} else if (xmlName == "type") {
QString type = xml.readElementText(QXmlStreamReader::IncludeChildElements);
properties.insert("type", type);
properties.insert("maintype", getMainCardType(type));
} else if (xml.name() == "pt") {
} else if (xmlName == "pt") {
properties.insert("pt", xml.readElementText(QXmlStreamReader::IncludeChildElements));
} else if (xml.name() == "loyalty") {
} else if (xmlName == "loyalty") {
properties.insert("loyalty", xml.readElementText(QXmlStreamReader::IncludeChildElements));
// positioning info
} else if (xml.name() == "tablerow") {
} else if (xmlName == "tablerow") {
tableRow = xml.readElementText(QXmlStreamReader::IncludeChildElements).toInt();
} else if (xml.name() == "cipt") {
} else if (xmlName == "cipt") {
cipt = (xml.readElementText(QXmlStreamReader::IncludeChildElements) == "1");
} else if (xml.name() == "upsidedown") {
} else if (xmlName == "upsidedown") {
upsideDown = (xml.readElementText(QXmlStreamReader::IncludeChildElements) == "1");
// sets
} else if (xml.name() == "set") {
} else if (xmlName == "set") {
// NOTE: attributes must be read before readElementText()
QXmlStreamAttributes attrs = xml.attributes();
QString setName = xml.readElementText(QXmlStreamReader::IncludeChildElements);
@ -217,8 +222,8 @@ void CockatriceXml3Parser::loadCardsFromXml(QXmlStreamReader &xml)
setInfo.setProperty("rarity", attrs.value("rarity").toString());
}
sets.insert(setName, setInfo);
// relatd cards
} else if (xml.name() == "related" || xml.name() == "reverse-related") {
// related cards
} else if (xmlName == "related" || xmlName == "reverse-related") {
bool attach = false;
bool exclude = false;
bool variable = false;
@ -249,13 +254,13 @@ void CockatriceXml3Parser::loadCardsFromXml(QXmlStreamReader &xml)
}
auto *relation = new CardRelation(cardName, attach, exclude, variable, count);
if (xml.name() == "reverse-related") {
if (xmlName == "reverse-related") {
reverseRelatedCards << relation;
} else {
relatedCards << relation;
}
} else if (xml.name() != "") {
qDebug() << "[CockatriceXml3Parser] Unknown card property" << xml.name()
} else if (!xmlName.isEmpty()) {
qDebug() << "[CockatriceXml3Parser] Unknown card property" << xmlName
<< ", trying to continue anyway";
xml.skipCurrentElement();
}

View file

@ -23,7 +23,7 @@ bool CockatriceXml4Parser::getCanParseFile(const QString &fileName, QIODevice &d
QXmlStreamReader xml(&device);
while (!xml.atEnd()) {
if (xml.readNext() == QXmlStreamReader::StartElement) {
if (xml.name() == COCKATRICE_XML4_TAGNAME) {
if (xml.name().toString() == COCKATRICE_XML4_TAGNAME) {
int version = xml.attributes().value("version").toString().toInt();
if (version == COCKATRICE_XML4_TAGVER) {
return true;
@ -52,12 +52,13 @@ void CockatriceXml4Parser::parseFile(QIODevice &device)
break;
}
if (xml.name() == "sets") {
auto xmlName = xml.name().toString();
if (xmlName == "sets") {
loadSetsFromXml(xml);
} else if (xml.name() == "cards") {
} else if (xmlName == "cards") {
loadCardsFromXml(xml);
} else if (xml.name() != "") {
qDebug() << "[CockatriceXml4Parser] Unknown item" << xml.name() << ", trying to continue anyway";
} else if (!xmlName.isEmpty()) {
qDebug() << "[CockatriceXml4Parser] Unknown item" << xmlName << ", trying to continue anyway";
xml.skipCurrentElement();
}
}
@ -72,25 +73,27 @@ void CockatriceXml4Parser::loadSetsFromXml(QXmlStreamReader &xml)
break;
}
if (xml.name() == "set") {
auto xmlName = xml.name().toString();
if (xmlName == "set") {
QString shortName, longName, setType;
QDate releaseDate;
while (!xml.atEnd()) {
if (xml.readNext() == QXmlStreamReader::EndElement) {
break;
}
xmlName = xml.name().toString();
if (xml.name() == "name") {
if (xmlName == "name") {
shortName = xml.readElementText(QXmlStreamReader::IncludeChildElements);
} else if (xml.name() == "longname") {
} else if (xmlName == "longname") {
longName = xml.readElementText(QXmlStreamReader::IncludeChildElements);
} else if (xml.name() == "settype") {
} else if (xmlName == "settype") {
setType = xml.readElementText(QXmlStreamReader::IncludeChildElements);
} else if (xml.name() == "releasedate") {
} else if (xmlName == "releasedate") {
releaseDate =
QDate::fromString(xml.readElementText(QXmlStreamReader::IncludeChildElements), Qt::ISODate);
} else if (xml.name() != "") {
qDebug() << "[CockatriceXml4Parser] Unknown set property" << xml.name()
} else if (!xmlName.isEmpty()) {
qDebug() << "[CockatriceXml4Parser] Unknown set property" << xmlName
<< ", trying to continue anyway";
xml.skipCurrentElement();
}
@ -109,8 +112,9 @@ QVariantHash CockatriceXml4Parser::loadCardPropertiesFromXml(QXmlStreamReader &x
break;
}
if (xml.name() != "") {
properties.insert(xml.name().toString(), xml.readElementText(QXmlStreamReader::IncludeChildElements));
auto xmlName = xml.name().toString();
if (!xmlName.isEmpty()) {
properties.insert(xmlName, xml.readElementText(QXmlStreamReader::IncludeChildElements));
}
}
return properties;
@ -123,7 +127,9 @@ void CockatriceXml4Parser::loadCardsFromXml(QXmlStreamReader &xml)
break;
}
if (xml.name() == "card") {
auto xmlName = xml.name().toString();
if (xmlName == "card") {
QString name = QString("");
QString text = QString("");
QVariantHash properties = QVariantHash();
@ -138,25 +144,28 @@ void CockatriceXml4Parser::loadCardsFromXml(QXmlStreamReader &xml)
if (xml.readNext() == QXmlStreamReader::EndElement) {
break;
}
xmlName = xml.name().toString();
// variable - assigned properties
if (xml.name() == "name") {
if (xmlName == "name") {
name = xml.readElementText(QXmlStreamReader::IncludeChildElements);
} else if (xml.name() == "text") {
} else if (xmlName == "text") {
text = xml.readElementText(QXmlStreamReader::IncludeChildElements);
} else if (xml.name() == "token") {
} else if (xmlName == "token") {
isToken = static_cast<bool>(xml.readElementText(QXmlStreamReader::IncludeChildElements).toInt());
// generic properties
} else if (xml.name() == "prop") {
} else if (xmlName == "prop") {
properties = loadCardPropertiesFromXml(xml);
// positioning info
} else if (xml.name() == "tablerow") {
} else if (xmlName == "tablerow") {
tableRow = xml.readElementText(QXmlStreamReader::IncludeChildElements).toInt();
} else if (xml.name() == "cipt") {
} else if (xmlName == "cipt") {
cipt = (xml.readElementText(QXmlStreamReader::IncludeChildElements) == "1");
} else if (xml.name() == "upsidedown") {
} else if (xmlName == "upsidedown") {
upsideDown = (xml.readElementText(QXmlStreamReader::IncludeChildElements) == "1");
// sets
} else if (xml.name() == "set") {
} else if (xmlName == "set") {
// NOTE: attributes but be read before readElementText()
QXmlStreamAttributes attrs = xml.attributes();
QString setName = xml.readElementText(QXmlStreamReader::IncludeChildElements);
@ -171,8 +180,8 @@ void CockatriceXml4Parser::loadCardsFromXml(QXmlStreamReader &xml)
}
sets.insert(setName, setInfo);
}
// relatd cards
} else if (xml.name() == "related" || xml.name() == "reverse-related") {
// related cards
} else if (xmlName == "related" || xmlName == "reverse-related") {
bool attach = false;
bool exclude = false;
bool variable = false;
@ -203,13 +212,13 @@ void CockatriceXml4Parser::loadCardsFromXml(QXmlStreamReader &xml)
}
auto *relation = new CardRelation(cardName, attach, exclude, variable, count);
if (xml.name() == "reverse-related") {
if (xmlName == "reverse-related") {
reverseRelatedCards << relation;
} else {
relatedCards << relation;
}
} else if (xml.name() != "") {
qDebug() << "[CockatriceXml4Parser] Unknown card property" << xml.name()
} else if (!xmlName.isEmpty()) {
qDebug() << "[CockatriceXml4Parser] Unknown card property" << xmlName
<< ", trying to continue anyway";
xml.skipCurrentElement();
}

View file

@ -6,13 +6,9 @@
#include "main.h"
#include <QApplication>
#include <utility>
#if (QT_VERSION >= QT_VERSION_CHECK(5, 13, 0))
#include <QScreen>
#else
#include <QDesktopWidget>
#endif
#include <QVBoxLayout>
#include <utility>
CardInfoWidget::CardInfoWidget(const QString &cardName, QWidget *parent, Qt::WindowFlags flags)
: QFrame(parent, flags), aspectRatio((qreal)CARD_HEIGHT / (qreal)CARD_WIDTH), info(nullptr)
@ -34,12 +30,7 @@ CardInfoWidget::CardInfoWidget(const QString &cardName, QWidget *parent, Qt::Win
setFrameStyle(QFrame::Panel | QFrame::Raised);
#if (QT_VERSION >= QT_VERSION_CHECK(5, 13, 0))
int pixmapHeight = qApp->primaryScreen()->geometry().height() / 3;
#else
QDesktopWidget desktopWidget;
int pixmapHeight = desktopWidget.screenGeometry().height() / 3;
#endif
int pixmapHeight = QGuiApplication::primaryScreen()->geometry().height() / 3;
int pixmapWidth = static_cast<int>(pixmapHeight / aspectRatio);
pic->setFixedWidth(pixmapWidth);
pic->setFixedHeight(pixmapHeight);

View file

@ -2,6 +2,7 @@
#define CARDITEM_H
#include "abstractcarditem.h"
#include "server_card.h"
class CardDatabase;
class CardDragItem;

View file

@ -321,7 +321,7 @@ void ChatView::checkTag(QTextCursor &cursor, QString &message)
void ChatView::checkMention(QTextCursor &cursor, QString &message, const QString &userName, UserLevelFlags userLevel)
{
const QRegExp notALetterOrNumber = QRegExp("[^a-zA-Z0-9]");
const static auto notALetterOrNumber = QRegularExpression("[^a-zA-Z0-9]");
int firstSpace = message.indexOf(' ');
QString fullMentionUpToSpaceOrEnd = (firstSpace == -1) ? message.mid(1) : message.mid(1, firstSpace - 1);
@ -510,7 +510,11 @@ void ChatView::redactMessages(const QString &userName, int amount)
}
}
#if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
void ChatView::enterEvent(QEnterEvent * /*event*/)
#else
void ChatView::enterEvent(QEvent * /*event*/)
#endif
{
setMouseTracking(true);
}
@ -566,7 +570,11 @@ void ChatView::mousePressEvent(QMouseEvent *event)
switch (hoveredItemType) {
case HoveredCard: {
if ((event->button() == Qt::MiddleButton) || (event->button() == Qt::LeftButton))
#if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
emit showCardInfoPopup(event->globalPosition().toPoint(), hoveredContent);
#else
emit showCardInfoPopup(event->globalPos(), hoveredContent);
#endif
break;
}
case HoveredUser: {
@ -576,7 +584,11 @@ void ChatView::mousePressEvent(QMouseEvent *event)
switch (event->button()) {
case Qt::RightButton: {
UserLevelFlags userLevel(hoveredContent.left(delimiterIndex).toInt());
#if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
userContextMenu->showContextMenu(event->globalPosition().toPoint(), userName, userLevel, this);
#else
userContextMenu->showContextMenu(event->globalPos(), userName, userLevel, this);
#endif
break;
}
case Qt::LeftButton: {

View file

@ -103,7 +103,11 @@ public:
void redactMessages(const QString &userName, int amount);
protected:
#if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
void enterEvent(QEnterEvent *event);
#else
void enterEvent(QEvent *event);
#endif
void leaveEvent(QEvent *event);
void mouseMoveEvent(QMouseEvent *event);
void mousePressEvent(QMouseEvent *event);

View file

@ -6,6 +6,7 @@
#include <QDebug>
#include <QFile>
#include <QRegularExpression>
#include <QStringList>
const QStringList DeckLoader::fileNameFilters = QStringList()
@ -208,7 +209,7 @@ void DeckLoader::saveToStream_DeckHeader(QTextStream &out)
}
if (!getComments().isEmpty()) {
QStringList commentRows = getComments().split(QRegExp("\n|\r\n|\r"));
QStringList commentRows = getComments().split(QRegularExpression("\n|\r\n|\r"));
foreach (QString row, commentRows) {
out << "// " << row << "\n";
}

View file

@ -9,8 +9,8 @@
#include <QApplication>
#include <QGraphicsSceneMouseEvent>
#include <QMouseEvent>
#include <QtMath>
#include <algorithm>
#include <math.h>
DeckViewCardDragItem::DeckViewCardDragItem(DeckViewCard *_item,
const QPointF &_hotSpot,
@ -238,11 +238,9 @@ int DeckViewCardContainer::getCardTypeTextWidth() const
QFontMetrics fm(f);
int maxCardTypeWidth = 0;
QMapIterator<QString, DeckViewCard *> i(cardsByType);
while (i.hasNext()) {
int cardTypeWidth = fm.size(Qt::TextSingleLine, i.next().key()).width();
if (cardTypeWidth > maxCardTypeWidth)
maxCardTypeWidth = cardTypeWidth;
for (const auto &key : cardsByType.keys()) {
int cardTypeWidth = fm.size(Qt::TextSingleLine, key).width();
maxCardTypeWidth = qMax(maxCardTypeWidth, cardTypeWidth);
}
return maxCardTypeWidth + 15;
@ -440,7 +438,7 @@ void DeckViewScene::rearrangeItems()
const int maxRows = rowsAndColsList[maxIndex1][maxIndex2].first;
const int maxCardCount = cardCountList[maxIndex1][maxIndex2];
rowsAndColsList[maxIndex1][maxIndex2] =
QPair<int, int>(maxRows + 1, (int)ceil((qreal)maxCardCount / (qreal)(maxRows + 1)));
QPair<int, int>(maxRows + 1, (int)qCeil((qreal)maxCardCount / (qreal)(maxRows + 1)));
}
totalHeight = -spacing;

View file

@ -162,8 +162,7 @@ DlgConnect::DlgConnect(QWidget *parent) : QDialog(parent)
previousHostButton->setChecked(true);
connect(previousHosts, SIGNAL(currentIndexChanged(const QString &)), this,
SLOT(updateDisplayInfo(const QString &)));
connect(previousHosts, SIGNAL(currentTextChanged(const QString &)), this, SLOT(updateDisplayInfo(const QString &)));
playernameEdit->setFocus();
}

View file

@ -121,7 +121,12 @@ WndSets::WndSets(QWidget *parent) : QMainWindow(parent)
connect(disableSomeButton, SIGNAL(clicked()), this, SLOT(actDisableSome()));
connect(view->selectionModel(), SIGNAL(selectionChanged(const QItemSelection &, const QItemSelection &)), this,
SLOT(actToggleButtons(const QItemSelection &, const QItemSelection &)));
#if (QT_VERSION >= QT_VERSION_CHECK(5, 12, 0))
connect(searchField, SIGNAL(textChanged(const QString &)), displayModel,
SLOT(setFilterRegularExpression(const QString &)));
#else
connect(searchField, SIGNAL(textChanged(const QString &)), displayModel, SLOT(setFilterRegExp(const QString &)));
#endif
connect(view->header(), SIGNAL(sortIndicatorChanged(int, Qt::SortOrder)), this, SLOT(actDisableSortButtons(int)));
connect(searchField, SIGNAL(textChanged(const QString &)), this, SLOT(actDisableResetButton(const QString &)));
@ -139,7 +144,6 @@ WndSets::WndSets(QWidget *parent) : QMainWindow(parent)
tr("How to use custom card art") + "</a>"));
QGridLayout *hintsGrid = new QGridLayout;
hintsGrid->setMargin(2);
hintsGrid->addWidget(labNotes, 0, 0);
hintsGroupBox = new QGroupBox(tr("Hints"));
hintsGroupBox->setLayout(hintsGrid);

View file

@ -17,7 +17,6 @@
#include <QComboBox>
#include <QDebug>
#include <QDesktopServices>
#include <QDesktopWidget>
#include <QDialogButtonBox>
#include <QFileDialog>
#include <QGridLayout>
@ -44,18 +43,22 @@
GeneralSettingsPage::GeneralSettingsPage()
{
SettingsCache &settings = SettingsCache::instance();
QString setLanguage = settings.getLang();
QStringList qmFiles = findQmFiles();
for (int i = 0; i < qmFiles.size(); i++) {
QString langName = languageName(qmFiles[i]);
languageBox.addItem(langName, qmFiles[i]);
if ((qmFiles[i] == setLanguage) ||
(setLanguage.isEmpty() && langName == QCoreApplication::translate("i18n", DEFAULT_LANG_NAME)))
languageBox.setCurrentIndex(i);
QStringList languageCodes = findQmFiles();
for (const QString &code : languageCodes) {
QString langName = languageName(code);
languageBox.addItem(langName, code);
}
QString setLanguage = QCoreApplication::translate("i18n", DEFAULT_LANG_NAME);
int index = languageBox.findText(setLanguage, Qt::MatchExactly);
if (index == -1) {
qWarning() << "could not find language" << setLanguage;
} else {
languageBox.setCurrentIndex(index);
}
// updates
SettingsCache &settings = SettingsCache::instance();
QList<ReleaseChannel *> channels = settings.getUpdateReleaseChannels();
foreach (ReleaseChannel *chan, channels) {
updateReleaseChannelBox.insertItem(chan->getIndex(), tr(chan->getName().toUtf8()));
@ -186,15 +189,20 @@ QStringList GeneralSettingsPage::findQmFiles()
{
QDir dir(translationPath);
QStringList fileNames = dir.entryList(QStringList(translationPrefix + "_*.qm"), QDir::Files, QDir::Name);
fileNames.replaceInStrings(QRegExp(translationPrefix + "_(.*)\\.qm"), "\\1");
fileNames.removeOne("en@source");
fileNames.replaceInStrings(QRegularExpression(translationPrefix + "_(.*)\\.qm"), "\\1");
return fileNames;
}
QString GeneralSettingsPage::languageName(const QString &qmFile)
QString GeneralSettingsPage::languageName(const QString &lang)
{
QTranslator qTranslator;
qTranslator.load(translationPrefix + "_" + qmFile + ".qm", translationPath);
QString appNameHint = translationPrefix + "_" + lang;
bool appTranslationLoaded = qTranslator.load(appNameHint, translationPath);
if (!appTranslationLoaded) {
qDebug() << "Unable to load" << translationPrefix << "translation" << appNameHint << "at" << translationPath;
}
return qTranslator.translate("i18n", DEFAULT_LANG_NAME);
}
@ -1235,11 +1243,7 @@ void ShortcutSettingsPage::retranslateUi()
DlgSettings::DlgSettings(QWidget *parent) : QDialog(parent)
{
#if (QT_VERSION >= QT_VERSION_CHECK(5, 13, 0))
auto rec = qApp->primaryScreen()->availableGeometry();
#else
auto rec = QApplication::desktop()->availableGeometry();
#endif
auto rec = QGuiApplication::primaryScreen()->availableGeometry();
this->setMinimumSize(qMin(700, rec.width()), qMin(700, rec.height()));
connect(&SettingsCache::instance(), SIGNAL(langChanged()), this, SLOT(updateLanguage()));

View file

@ -49,7 +49,7 @@ private slots:
private:
QStringList findQmFiles();
QString languageName(const QString &qmFile);
QString languageName(const QString &lang);
QLineEdit *deckPathEdit;
QLineEdit *replaysPathEdit;
QLineEdit *picsPathEdit;

View file

@ -4,7 +4,6 @@
#include <QByteArray>
#include <QString>
#include <cmath>
#include <functional>
peg::parser search(R"(

View file

@ -13,7 +13,7 @@
#include <QGraphicsSceneMouseEvent>
#include <QGraphicsView>
#include <QSet>
#include <math.h>
#include <QtMath>
GameScene::GameScene(PhasesToolbar *_phasesToolbar, QObject *parent)
: QGraphicsScene(parent), phasesToolbar(_phasesToolbar), viewSize(QSize()), playerRotation(0)
@ -97,7 +97,7 @@ void GameScene::rearrange()
const int playersCount = playersPlaying.size();
const int columns = playersCount < SettingsCache::instance().getMinPlayersForMultiColumnLayout() ? 1 : 2;
const int rows = ceil((qreal)playersCount / columns);
const int rows = qCeil((qreal)playersCount / columns);
qreal sceneHeight = 0, sceneWidth = -playerAreaSpacing;
QList<int> columnWidth;

View file

@ -93,11 +93,7 @@ QVariant GamesModel::data(const QModelIndex &index, int role) const
case CREATED: {
switch (role) {
case Qt::DisplayRole: {
#if (QT_VERSION >= QT_VERSION_CHECK(5, 8, 0))
QDateTime then = QDateTime::fromSecsSinceEpoch(gameentry.start_time(), Qt::UTC);
#else
QDateTime then = QDateTime::fromTime_t(gameentry.start_time(), Qt::UTC);
#endif
int secs = then.secsTo(QDateTime::currentDateTimeUtc());
return getGameCreatedString(secs);
}

View file

@ -24,8 +24,10 @@ void HandZone::updateBg()
void HandZone::addCardImpl(CardItem *card, int x, int /*y*/)
{
if (x == -1)
// if x is negative set it to add at end
if (x < 0 || x >= cards.size()) {
x = cards.size();
}
cards.insert(x, card);
if (!cards.getContentsKnown()) {

View file

@ -12,8 +12,9 @@ LocalServer::LocalServer(QObject *parent) : Server(parent)
LocalServer::~LocalServer()
{
// LocalServer is single threaded so it doesn't need locks on this
while (!clients.isEmpty())
clients.first()->prepareDestroy();
for (auto *client : clients) {
client->prepareDestroy();
}
prepareDestroy();
}

View file

@ -27,6 +27,7 @@ protected:
public:
LocalServer_DatabaseInterface(LocalServer *_localServer);
~LocalServer_DatabaseInterface() = default;
AuthenticationResult checkUserPassword(Server_ProtocolHandler *handler,
const QString &user,
const QString &password,

View file

@ -67,11 +67,29 @@ void installNewTranslator()
{
QString lang = SettingsCache::instance().getLang();
qtTranslator->load("qt_" + lang, QLibraryInfo::location(QLibraryInfo::TranslationsPath));
QString qtNameHint = "qt_" + lang;
#if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
QString qtTranslationPath = QLibraryInfo::path(QLibraryInfo::TranslationsPath);
#else
QString qtTranslationPath = QLibraryInfo::location(QLibraryInfo::TranslationsPath);
#endif
bool qtTranslationLoaded = qtTranslator->load(qtNameHint, qtTranslationPath);
if (!qtTranslationLoaded) {
qDebug() << "Unable to load qt translation" << qtNameHint << "at" << qtTranslationPath;
} else {
qDebug() << "Loaded qt translation" << qtNameHint << "at" << qtTranslationPath;
}
qApp->installTranslator(qtTranslator);
translator->load(translationPrefix + "_" + lang, translationPath);
QString appNameHint = translationPrefix + "_" + lang;
bool appTranslationLoaded = qtTranslator->load(appNameHint, translationPath);
if (!appTranslationLoaded) {
qDebug() << "Unable to load" << translationPrefix << "translation" << appNameHint << "at" << translationPath;
} else {
qDebug() << "Loaded" << translationPrefix << "translation" << appNameHint << "at" << translationPath;
}
qApp->installTranslator(translator);
qDebug() << "Language changed:" << lang;
}
QString const generateClientID()
@ -165,7 +183,9 @@ int main(int argc, char *argv[])
ui.show();
qDebug("main(): ui.show() finished");
#if (QT_VERSION < QT_VERSION_CHECK(6, 0, 0))
app.setAttribute(Qt::AA_UseHighDpiPixmaps);
#endif
app.exec();
qDebug("Event loop finished, terminating...");

View file

@ -44,6 +44,10 @@ void PileZone::paint(QPainter *painter, const QStyleOptionGraphicsItem * /*optio
void PileZone::addCardImpl(CardItem *card, int x, int /*y*/)
{
connect(card, SIGNAL(sigPixmapUpdated()), this, SLOT(callUpdate()));
// if x is negative set it to add at end
if (x < 0 || x >= cards.size()) {
x = cards.size();
}
cards.insert(x, card);
card->setPos(0, 0);
if (!contentsKnown()) {

View file

@ -99,7 +99,7 @@ QMap<QString, QPixmap> CountryPixmapGenerator::pmCache;
QPixmap UserLevelPixmapGenerator::generatePixmap(int height, UserLevelFlags userLevel, bool isBuddy, QString privLevel)
{
QString key = QString::number(height * 10000) + ":" + (int)userLevel + ":" + (int)isBuddy + ":" + privLevel;
QString key = QString::number(height * 10000) + ":" + (short)userLevel + ":" + (short)isBuddy + ":" + privLevel;
if (pmCache.contains(key))
return pmCache.value(key);

View file

@ -66,6 +66,7 @@
#include <QDebug>
#include <QMenu>
#include <QMetaType>
#include <QPainter>
#include <QRegularExpression>
#include <QRegularExpressionMatch>
@ -3066,7 +3067,11 @@ void Player::actSetPT()
const auto oldpt = parsePT(card->getPT());
int ptIter = 0;
for (const auto &item : ptList) {
#if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
if (item.typeId() == QMetaType::Type::Int) {
#else
if (item.type() == QVariant::Int) {
#endif
int oldItem = ptIter < oldpt.size() ? oldpt.at(ptIter).toInt() : 0;
newpt += '/' + QString::number(oldItem + item.toInt());
} else {

View file

@ -28,7 +28,11 @@ bool PlayerListItemDelegate::editorEvent(QEvent *event,
if ((event->type() == QEvent::MouseButtonPress) && index.isValid()) {
QMouseEvent *const mouseEvent = static_cast<QMouseEvent *>(event);
if (mouseEvent->button() == Qt::RightButton) {
#if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
static_cast<PlayerListWidget *>(parent())->showContextMenu(mouseEvent->globalPosition().toPoint(), index);
#else
static_cast<PlayerListWidget *>(parent())->showContextMenu(mouseEvent->globalPos(), index);
#endif
return true;
}
}

View file

@ -23,10 +23,9 @@
int ReleaseChannel::sharedIndex = 0;
ReleaseChannel::ReleaseChannel() : response(nullptr), lastRelease(nullptr)
ReleaseChannel::ReleaseChannel() : netMan(new QNetworkAccessManager(this)), response(nullptr), lastRelease(nullptr)
{
index = sharedIndex++;
netMan = new QNetworkAccessManager(this);
}
ReleaseChannel::~ReleaseChannel()

View file

@ -78,7 +78,7 @@ class ReleaseChannel : public QObject
{
Q_OBJECT
public:
ReleaseChannel();
explicit ReleaseChannel();
~ReleaseChannel() override;
protected:
@ -117,7 +117,7 @@ class StableReleaseChannel : public ReleaseChannel
{
Q_OBJECT
public:
StableReleaseChannel() = default;
explicit StableReleaseChannel() = default;
~StableReleaseChannel() override = default;
QString getManualDownloadUrl() const override;

View file

@ -41,8 +41,13 @@ RemoteClient::RemoteClient(QObject *parent)
socket->setSocketOption(QAbstractSocket::LowDelayOption, 1);
connect(socket, SIGNAL(connected()), this, SLOT(slotConnected()));
connect(socket, SIGNAL(readyRead()), this, SLOT(readData()));
#if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
connect(socket, &QTcpSocket::errorOccurred, this, &RemoteClient::slotSocketError);
#else
connect(socket, SIGNAL(error(QAbstractSocket::SocketError)), this,
SLOT(slotSocketError(QAbstractSocket::SocketError)));
#endif
websocket = new QWebSocket(QString(), QWebSocketProtocol::VersionLatest, this);
connect(websocket, &QWebSocket::binaryMessageReceived, this, &RemoteClient::websocketMessageReceived);

View file

@ -221,7 +221,7 @@ void RemoteDeckList_TreeModel::addFileToTree(const ServerInfo_DeckStorage_TreeIt
{
const ServerInfo_DeckStorage_File &fileInfo = file.file();
QDateTime time;
time.setTime_t(fileInfo.creation_time());
time.setSecsSinceEpoch(fileInfo.creation_time());
beginInsertRows(nodeToIndex(parent), parent->size(), parent->size());
parent->append(new FileNode(QString::fromStdString(file.name()), file.id(), time, parent));

View file

@ -111,7 +111,7 @@ QVariant RemoteReplayList_TreeModel::data(const QModelIndex &index, int role) co
return playerList.join(", ");
}
case 4:
return QDateTime::fromTime_t(matchInfo.time_started());
return QDateTime::fromSecsSinceEpoch(matchInfo.time_started());
case 5:
return matchInfo.length();
default:

View file

@ -62,7 +62,11 @@ void ReplayTimelineWidget::paintEvent(QPaintEvent * /* event */)
void ReplayTimelineWidget::mousePressEvent(QMouseEvent *event)
{
#if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
int newTime = static_cast<int>((qint64)maxTime * (qint64)event->position().x() / width());
#else
int newTime = static_cast<int>((qint64)maxTime * (qint64)event->x() / width());
#endif
newTime -= newTime % 200; // Time should always be a multiple of 200
if (newTime < currentTime) {
currentTime = 0;

View file

@ -1,5 +1,7 @@
#include "setsmodel.h"
#include <QSortFilterProxyModel>
SetsModel::SetsModel(CardDatabase *_db, QObject *parent) : QAbstractTableModel(parent), sets(_db->getSetList())
{
sets.sortByKey();
@ -274,9 +276,15 @@ bool SetsDisplayModel::filterAcceptsRow(int sourceRow, const QModelIndex &source
auto nameIndex = sourceModel()->index(sourceRow, SetsModel::LongNameCol, sourceParent);
auto shortNameIndex = sourceModel()->index(sourceRow, SetsModel::ShortNameCol, sourceParent);
return (sourceModel()->data(typeIndex).toString().contains(filterRegExp()) ||
sourceModel()->data(nameIndex).toString().contains(filterRegExp()) ||
sourceModel()->data(shortNameIndex).toString().contains(filterRegExp()));
#if (QT_VERSION >= QT_VERSION_CHECK(5, 12, 0))
const auto filter = filterRegularExpression();
#else
const auto filter = filterRegExp();
#endif
return (sourceModel()->data(typeIndex).toString().contains(filter) ||
sourceModel()->data(nameIndex).toString().contains(filter) ||
sourceModel()->data(shortNameIndex).toString().contains(filter));
}
bool SetsDisplayModel::lessThan(const QModelIndex &left, const QModelIndex &right) const

View file

@ -18,7 +18,7 @@ QString SettingsCache::getDataPath()
if (isPortableBuild)
return qApp->applicationDirPath() + "/data";
else
return QStandardPaths::writableLocation(QStandardPaths::DataLocation);
return QStandardPaths::writableLocation(QStandardPaths::AppDataLocation);
}
QString SettingsCache::getSettingsPath()

View file

@ -2,21 +2,15 @@
#include "settingscache.h"
#include <QApplication>
#include <QAudioOutput>
#include <QBuffer>
#include <QDebug>
#include <QFileInfo>
#include <QLibraryInfo>
#include <QStandardPaths>
#include <QDir>
#include <QMediaPlayer>
#define DEFAULT_THEME_NAME "Default"
#define TEST_SOUND_FILENAME "player_join"
SoundEngine::SoundEngine(QObject *parent) : QObject(parent), player(0)
{
inputBuffer = new QBuffer(this);
ensureThemeDirectoryExists();
connect(&SettingsCache::instance(), SIGNAL(soundThemeChanged()), this, SLOT(themeChangedSlot()));
connect(&SettingsCache::instance(), SIGNAL(soundEnabledChanged()), this, SLOT(soundEnabledChanged()));
@ -31,8 +25,6 @@ SoundEngine::~SoundEngine()
player->deleteLater();
player = 0;
}
inputBuffer->deleteLater();
}
void SoundEngine::soundEnabledChanged()
@ -40,14 +32,11 @@ void SoundEngine::soundEnabledChanged()
if (SettingsCache::instance().getSoundEnabled()) {
qDebug("SoundEngine: enabling sound");
if (!player) {
QAudioFormat format;
format.setSampleRate(44100);
format.setChannelCount(1);
format.setSampleSize(16);
format.setCodec("audio/pcm");
format.setByteOrder(QAudioFormat::LittleEndian);
format.setSampleType(QAudioFormat::SignedInt);
player = new QAudioOutput(format, this);
player = new QMediaPlayer;
#if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
auto qAudioOutput = new QAudioOutput;
player->setAudioOutput(qAudioOutput);
#endif
}
} else {
qDebug("SoundEngine: disabling sound");
@ -61,25 +50,35 @@ void SoundEngine::soundEnabledChanged()
void SoundEngine::playSound(QString fileName)
{
if (!player)
if (!player) {
return;
}
// still playing the previous sound?
if (player->state() == QAudio::ActiveState)
#if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
if (player->playbackState() == QMediaPlayer::PlaybackState::PlayingState) {
#else
if (player->state() == QMediaPlayer::PlayingState) {
#endif
return;
}
if (!audioData.contains(fileName))
if (!audioData.contains(fileName)) {
return;
}
qDebug() << "playing" << fileName;
inputBuffer->close();
inputBuffer->setData(audioData[fileName]);
inputBuffer->open(QIODevice::ReadOnly);
player->setVolume(SettingsCache::instance().getMasterVolume() / 100.0);
#if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
player->audioOutput()->setVolume(SettingsCache::instance().getMasterVolume());
player->stop();
player->start(inputBuffer);
player->setSource(QUrl::fromLocalFile(audioData[fileName]));
#else
player->setVolume(SettingsCache::instance().getMasterVolume());
player->stop();
player->setMedia(QUrl::fromLocalFile(audioData[fileName]));
#endif
player->play();
}
void SoundEngine::testSound()
@ -105,7 +104,7 @@ QStringMap &SoundEngine::getAvailableThemes()
dir.setPath(SettingsCache::instance().getDataPath() + "/sounds");
foreach (QString themeName, dir.entryList(QDir::AllDirs | QDir::NoDotAndDotDot, QDir::Name)) {
for (const QString &themeName : dir.entryList(QDir::AllDirs | QDir::NoDotAndDotDot, QDir::Name)) {
if (!availableThemes.contains(themeName))
availableThemes.insert(themeName, dir.absoluteFilePath(themeName));
}
@ -121,7 +120,7 @@ QStringMap &SoundEngine::getAvailableThemes()
#endif
);
foreach (QString themeName, dir.entryList(QDir::AllDirs | QDir::NoDotAndDotDot, QDir::Name)) {
for (const QString &themeName : dir.entryList(QDir::AllDirs | QDir::NoDotAndDotDot, QDir::Name)) {
if (!availableThemes.contains(themeName))
availableThemes.insert(themeName, dir.absoluteFilePath(themeName));
}
@ -181,10 +180,7 @@ void SoundEngine::themeChangedSlot()
continue;
QFile file(dir.filePath(fileNames[i] + ".wav"));
file.open(QIODevice::ReadOnly);
// 44 = length of wav header
audioData.insert(fileNames[i], file.readAll().mid(44));
file.close();
audioData.insert(fileNames[i], file.fileName());
}
soundEnabledChanged();

View file

@ -1,8 +1,8 @@
#ifndef SOUNDENGINE_H
#define SOUNDENGINE_H
#include <QDir>
#include <QMap>
#include <QMediaPlayer>
#include <QObject>
#include <QString>
@ -21,10 +21,9 @@ public:
QStringMap &getAvailableThemes();
private:
QMap<QString, QByteArray> audioData;
QBuffer *inputBuffer;
QAudioOutput *player;
QStringMap availableThemes;
QMap<QString, QString> audioData;
QMediaPlayer *player;
protected:
void ensureThemeDirectoryExists();

View file

@ -114,7 +114,7 @@ void SpoilerBackgroundUpdater::actCheckIfSpoilerSeasonEnabled()
emit spoilerCheckerDone();
} else {
if (trayIcon) {
trayIcon->showMessage(tr("Spoilers download failed"), tr("Error") + " " + errorCode);
trayIcon->showMessage(tr("Spoilers download failed"), tr("Error") + " " + (short)errorCode);
}
qDebug() << "Spoiler download failed with reason" << errorCode;
@ -159,7 +159,7 @@ bool SpoilerBackgroundUpdater::saveDownloadedFile(QByteArray data)
// Data written, so reload the card database
qDebug() << "Spoiler Service Data Written";
QtConcurrent::run(db, &CardDatabase::loadCardDatabases);
const auto reloadOk = QtConcurrent::run([] { db->loadCardDatabases(); });
// If the user has notifications enabled, let them know
// when the database was last updated

View file

@ -26,8 +26,10 @@ void StackZone::updateBg()
void StackZone::addCardImpl(CardItem *card, int x, int /*y*/)
{
if (x == -1)
// if x is negative set it to add at end
if (x < 0 || x >= cards.size()) {
x = cards.size();
}
cards.insert(x, card);
if (!cards.getContentsKnown()) {

View file

@ -4,7 +4,8 @@
#include <QApplication>
#include <QDebug>
#include <QDesktopWidget>
#include <QScreen>
Tab::Tab(TabSupervisor *_tabSupervisor, QWidget *parent)
: QMainWindow(parent), tabSupervisor(_tabSupervisor), contentsChanged(false), infoPopup(0)
{
@ -20,7 +21,8 @@ void Tab::showCardInfoPopup(const QPoint &pos, const QString &cardName)
infoPopup = new CardInfoWidget(
cardName, 0, Qt::Widget | Qt::FramelessWindowHint | Qt::X11BypassWindowManagerHint | Qt::WindowStaysOnTopHint);
infoPopup->setAttribute(Qt::WA_TransparentForMouseEvents);
QRect screenRect = qApp->desktop()->screenGeometry(this);
auto screenRect = qApp->primaryScreen()->geometry();
infoPopup->move(qMax(screenRect.left(), qMin(pos.x() - infoPopup->width() / 2,
screenRect.left() + screenRect.width() - infoPopup->width())),
qMax(screenRect.top(), qMin(pos.y() - infoPopup->height() / 2,

View file

@ -52,7 +52,7 @@ TabRoom::TabRoom(TabSupervisor *_tabSupervisor,
SIGNAL(openMessageDialog(const QString &, bool)));
chatView = new ChatView(tabSupervisor, tabSupervisor, nullptr, true, this);
connect(chatView, SIGNAL(showMentionPopup(QString &)), this, SLOT(actShowMentionPopup(QString &)));
connect(chatView, SIGNAL(showMentionPopup(const QString &)), this, SLOT(actShowMentionPopup(const QString &)));
connect(chatView, SIGNAL(messageClickedSignal()), this, SLOT(focusTab()));
connect(chatView, SIGNAL(openMessageDialog(QString, bool)), this, SIGNAL(openMessageDialog(QString, bool)));
connect(chatView, SIGNAL(showCardInfoPopup(QPoint, QString)), this, SLOT(showCardInfoPopup(QPoint, QString)));
@ -160,7 +160,7 @@ void TabRoom::focusTab()
emit maximizeClient();
}
void TabRoom::actShowMentionPopup(QString &sender)
void TabRoom::actShowMentionPopup(const QString &sender)
{
this->actShowPopup(sender + tr(" mentioned you."));
}

View file

@ -75,7 +75,7 @@ private slots:
void actOpenChatSettings();
void addMentionTag(QString mentionTag);
void focusTab();
void actShowMentionPopup(QString &sender);
void actShowMentionPopup(const QString &sender);
void actShowPopup(const QString &message);
void actCompleterChanged();

View file

@ -58,7 +58,11 @@ QSize CloseButton::sizeHint() const
return QSize(width, height);
}
#if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
void CloseButton::enterEvent(QEnterEvent *event)
#else
void CloseButton::enterEvent(QEvent *event)
#endif
{
update();
QAbstractButton::enterEvent(event);
@ -74,7 +78,7 @@ void CloseButton::paintEvent(QPaintEvent * /*event*/)
{
QPainter p(this);
QStyleOption opt;
opt.init(this);
opt.initFrom(this);
opt.state |= QStyle::State_AutoRaise;
if (isEnabled() && underMouse() && !isChecked() && !isDown())
opt.state |= QStyle::State_Raised;

View file

@ -52,7 +52,11 @@ public:
}
protected:
#if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
void enterEvent(QEnterEvent *event);
#else
void enterEvent(QEvent *event);
#endif
void leaveEvent(QEvent *event);
void paintEvent(QPaintEvent *event);
};

View file

@ -8,6 +8,7 @@
#include <QNetworkReply>
#include <QNetworkRequest>
#include <QRegExp>
#include <QRegularExpression>
#include <QUrlQuery>
TappedOutInterface::TappedOutInterface(CardDatabase &_cardDatabase, QObject *parent)
@ -53,7 +54,7 @@ void TappedOutInterface::queryFinished(QNetworkReply *reply)
int captures = rx2.captureCount();
for (int i = 1; i <= captures; i++) {
errorMessage += QString("\n") + rx2.cap(i).remove(QRegExp("<[^>]*>")).simplified();
errorMessage += QString("\n") + rx2.cap(i).remove(QRegularExpression("<[^>]*>")).simplified();
}
}

View file

@ -36,7 +36,9 @@ TipsOfTheDay::TipsOfTheDay(QString xmlPath, QObject *parent) : QAbstractListMode
break;
}
if (reader.name() == "tip") {
auto readerName = reader.name().toString();
if (readerName == "tip") {
QString title, content, imagePath;
QDate date;
reader.readNext();
@ -45,16 +47,18 @@ TipsOfTheDay::TipsOfTheDay(QString xmlPath, QObject *parent) : QAbstractListMode
break;
}
if (reader.name() == "title") {
readerName = reader.name().toString();
if (readerName == "title") {
title = reader.readElementText();
} else if (reader.name() == "text") {
} else if (readerName == "text") {
content = reader.readElementText();
} else if (reader.name() == "image") {
} else if (readerName == "image") {
imagePath = "theme:tips/images/" + reader.readElementText();
} else if (reader.name() == "date") {
} else if (readerName == "date") {
date = QDate::fromString(reader.readElementText(), Qt::ISODate);
} else {
// unkown element, do nothing
// unknown element, do nothing
}
}
tipList->append(TipOfTheDay(title, content, imagePath, date));

View file

@ -137,7 +137,7 @@ QString UserInfoBox::getAgeString(int ageSeconds)
if (ageSeconds == 0)
return accountAgeString;
auto date = QDateTime::fromTime_t(QDateTime::currentSecsSinceEpoch() - ageSeconds).date();
auto date = QDateTime::fromSecsSinceEpoch(QDateTime::currentSecsSinceEpoch() - ageSeconds).date();
if (!date.isValid())
return accountAgeString;

View file

@ -296,7 +296,11 @@ bool UserListItemDelegate::editorEvent(QEvent *event,
if ((event->type() == QEvent::MouseButtonPress) && index.isValid()) {
QMouseEvent *const mouseEvent = static_cast<QMouseEvent *>(event);
if (mouseEvent->button() == Qt::RightButton) {
#if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
static_cast<UserList *>(parent())->showContextMenu(mouseEvent->globalPosition().toPoint(), index);
#else
static_cast<UserList *>(parent())->showContextMenu(mouseEvent->globalPos(), index);
#endif
return true;
}
}

View file

@ -101,8 +101,8 @@ void MainWindow::processConnectionClosedEvent(const Event_ConnectionClosed &even
case Event_ConnectionClosed::BANNED: {
reasonStr = tr("Banned by moderator");
if (event.has_end_time())
reasonStr.append("\n" +
tr("Expected end time: %1").arg(QDateTime::fromTime_t(event.end_time()).toString()));
reasonStr.append(
"\n" + tr("Expected end time: %1").arg(QDateTime::fromSecsSinceEpoch(event.end_time()).toString()));
else
reasonStr.append("\n" + tr("This ban lasts indefinitely."));
if (event.has_reason_str())
@ -393,7 +393,7 @@ void MainWindow::loginError(Response::ResponseCode r,
case Response::RespUserIsBanned: {
QString bannedStr;
if (endTime)
bannedStr = tr("You are banned until %1.").arg(QDateTime::fromTime_t(endTime).toString());
bannedStr = tr("You are banned until %1.").arg(QDateTime::fromSecsSinceEpoch(endTime).toString());
else
bannedStr = tr("You are banned indefinitely.");
if (!reasonStr.isEmpty())
@ -530,7 +530,7 @@ void MainWindow::registerError(Response::ResponseCode r, QString reasonStr, quin
case Response::RespUserIsBanned: {
QString bannedStr;
if (endTime)
bannedStr = tr("You are banned until %1.").arg(QDateTime::fromTime_t(endTime).toString());
bannedStr = tr("You are banned until %1.").arg(QDateTime::fromSecsSinceEpoch(endTime).toString());
else
bannedStr = tr("You are banned indefinitely.");
if (!reasonStr.isEmpty())
@ -865,13 +865,13 @@ void MainWindow::startupConfigCheck()
if (SettingsCache::instance().getNotifyAboutNewVersion()) {
alertForcedOracleRun(VERSION_STRING, true);
} else {
QtConcurrent::run(db, &CardDatabase::loadCardDatabases);
const auto reloadOk0 = QtConcurrent::run([] { db->loadCardDatabases(); });
}
SettingsCache::instance().setClientVersion(VERSION_STRING);
} else {
// previous config from this version found
qDebug() << "Startup: found config with current version";
QtConcurrent::run(db, &CardDatabase::loadCardDatabases);
const auto reloadOk1 = QtConcurrent::run([] { db->loadCardDatabases(); });
// Run the tips dialog only on subsequent startups.
// On the first run after an install/update the startup is already crowded enough
@ -932,9 +932,9 @@ void MainWindow::createTrayIcon()
void MainWindow::iconActivated(QSystemTrayIcon::ActivationReason reason)
{
if (reason == QSystemTrayIcon::DoubleClick) {
if (windowState() != Qt::WindowMinimized && windowState() != Qt::WindowMinimized + Qt::WindowMaximized)
if ((windowState() & Qt::WindowMinimized) == 0) {
showMinimized();
else {
} else {
showNormal();
QApplication::setActiveWindow(this);
}
@ -1058,7 +1058,7 @@ void MainWindow::cardDatabaseNewSetsFound(int numUnknownSets, QStringList unknow
if (msgBox.clickedButton() == yesButton) {
db->enableAllUnknownSets();
QtConcurrent::run(db, &CardDatabase::loadCardDatabases);
const auto reloadOk1 = QtConcurrent::run([] { db->loadCardDatabases(); });
} else if (msgBox.clickedButton() == noButton) {
db->markAllSetsAsKnown();
} else if (msgBox.clickedButton() == settingsButton) {
@ -1086,8 +1086,9 @@ void MainWindow::actCheckCardUpdates()
}
cardUpdateProcess = new QProcess(this);
connect(cardUpdateProcess, SIGNAL(error(QProcess::ProcessError)), this,
SLOT(cardUpdateError(QProcess::ProcessError)));
connect(cardUpdateProcess, &QProcess::errorOccurred, this, &MainWindow::cardUpdateError);
connect(cardUpdateProcess, SIGNAL(finished(int, QProcess::ExitStatus)), this,
SLOT(cardUpdateFinished(int, QProcess::ExitStatus)));
@ -1148,7 +1149,7 @@ void MainWindow::exitCardDatabaseUpdate()
cardUpdateProcess->deleteLater();
cardUpdateProcess = nullptr;
QtConcurrent::run(db, &CardDatabase::loadCardDatabases);
const auto reloadOk1 = QtConcurrent::run([] { db->loadCardDatabases(); });
}
void MainWindow::cardUpdateError(QProcess::ProcessError err)
@ -1278,7 +1279,7 @@ void MainWindow::actAddCustomSet()
QMessageBox::information(
this, tr("Load sets/cards"),
tr("The new sets/cards have been added successfully.\nCockatrice will now reload the card database."));
QtConcurrent::run(db, &CardDatabase::loadCardDatabases);
const auto reloadOk1 = QtConcurrent::run([] { db->loadCardDatabases(); });
} else {
QMessageBox::warning(this, tr("Load sets/cards"), tr("Sets/cards failed to import."));
}

View file

@ -14,7 +14,7 @@
#include <QDebug>
#include <QGraphicsSceneWheelEvent>
#include <QPainter>
#include <math.h>
#include <QtMath>
ZoneViewZone::ZoneViewZone(Player *_p,
CardZone *_origZone,
@ -103,17 +103,17 @@ void ZoneViewZone::reorganizeCards()
for (int i = 0; i < cardCount; ++i)
cards[i]->setId(i);
int cols = floor(sqrt((double)cardCount / 2));
int cols = qFloor(qSqrt((double)cardCount / 2));
if (cols > 7)
cols = 7;
int rows = ceil((double)cardCount / cols);
int rows = qCeil((double)cardCount / cols);
if (rows < 1)
rows = 1;
if (minRows == 0)
minRows = rows;
else if (rows < minRows) {
rows = minRows;
cols = ceil((double)cardCount / minRows);
cols = qCeil((double)cardCount / minRows);
}
if (cols < 2)
cols = 2;
@ -193,6 +193,10 @@ void ZoneViewZone::setPileView(int _pileView)
void ZoneViewZone::addCardImpl(CardItem *card, int x, int /*y*/)
{
// if x is negative set it to add at end
if (x < 0 || x >= cards.size()) {
x = cards.size();
}
cards.insert(x, card);
card->setParentItem(this);
card->update();