Krita is a free and open source cross-platform application that offers an end-to-end solution for creating digital art files from scratch built on the KDE and Qt frameworks.
C++
[android] Implement supporter benefits
Carsten Hartenfels966cf6913ef2
diff --git a/krita/CMakeLists.txt b/krita/CMakeLists.txtindex 31ca3eb09f..52f69ea327 100644--- a/krita/CMakeLists.txt+++ b/krita/CMakeLists.txt@@ -100,6 +100,13 @@ ecm_install_icons(ICONS"${CMAKE_CURRENT_SOURCE_DIR}/pics/mimetypes/1024-mimetypes-application-x-krita.png"DESTINATION ${KDE_INSTALL_ICONDIR} THEME hicolor)+# Android has a different splash screen.+if(ANDROID)+ set(krita_splash_qrc splash-android.qrc)+else()+ set(krita_splash_qrc splash.qrc)+endif()+# separate listing, both used by Krita and KritaSketchset(krita_QRCS${CMAKE_SOURCE_DIR}/krita/krita.qrc@@ -122,7 +129,7 @@ set(krita_QRCS${CMAKE_SOURCE_DIR}/krita/data/gamutmasks/gamutmasks.qrc${CMAKE_SOURCE_DIR}/plugins/paintops/defaultpresets/defaultpresets.qrc${CMAKE_SOURCE_DIR}/krita/pics/branding/${BRANDING}/branding.qrc- ${CMAKE_SOURCE_DIR}/krita/data/splash/splash.qrc+ ${CMAKE_SOURCE_DIR}/krita/data/splash/${krita_splash_qrc}${CMAKE_SOURCE_DIR}/krita/pics/sponsors/sponsors.qrcCACHE INTERNAL "krita_QRCS")@@ -214,7 +221,16 @@ else()install(TARGETS krita ${INSTALL_TARGETS_DEFAULT_ARGS})endif()install(FILES org.kde.krita.desktop DESTINATION ${KDE_INSTALL_APPDIR})-install(FILES krita.action kritamenu.action DESTINATION ${KDE_INSTALL_DATADIR}/krita/actions)++set(actions_files krita.action kritamenu.action)+if (ANDROID)+ # In-app-purchase-related actions are only relevant on Android. They+ # wouldn't show up in the menu anyway because the application doesn't+ # instantiate them, but they'd still appear in the keyboard shortcuts.+ list(APPEND actions_files kritamenu_android.action)+endif()+install(FILES ${actions_files} DESTINATION ${KDE_INSTALL_DATADIR}/krita/actions)+install(FILES org.kde.krita.appdata.xml DESTINATION ${KDE_INSTALL_METAINFODIR} )install(DIRECTORY DESTINATION ${KDE_INSTALL_DATADIR}/krita/shortcuts)diff --git a/krita/data/aboutdata/credits.txt b/krita/data/aboutdata/credits.txtindex 82ec941b42..24f623efc8 100644--- a/krita/data/aboutdata/credits.txt+++ b/krita/data/aboutdata/credits.txt@@ -1,10 +1,15 @@Peter Sikking:Project VisionRamon Miranda:Artist, Muses author, brush and preset creator-David Revoy:Brushes and Palettes+David Revoy:Brushes and Palettes; Kiki with piggy bank icon and Kiki raising hands icon, licensed under CC-BY-SA 4.0Ilya Portnov:MyPaint shade selectorMartin Renold:MyPaint shade selectorSaisho Kazuki:Japanese Animation templatePasquale D'Antuono:DonorDavid Gowers:Dither patterns+L.Sumireneko.M:Kiki with watering can icon, licensed under CC-BY-SA 4.0+Brian Wong:Chuffed Kiki icon, licensed under CC-BY-SA 4.0+MossGreenEddie:Stargazers banner and Cat with brush banner, licensed under CC-BY-SA 4.0+greenajd:Kiki winking banner, licensed under CC-BY-SA 4.0+mibambakso:Person with digital palette banner, licensed under CC-BY-SA 4.0diff --git a/krita/data/donation/CMakeLists.txt b/krita/data/donation/CMakeLists.txtindex 25c8328e40..e47e568f3c 100644--- a/krita/data/donation/CMakeLists.txt+++ b/krita/data/donation/CMakeLists.txt@@ -1,5 +1,9 @@install( FILESbanner.png+ welcomebanner1.jpg+ welcomebanner2.jpg+ welcomebanner3.jpg+ welcomebanner4.jpgDESTINATION ${KDE_INSTALL_DATADIR}/krita/donation/)diff --git a/krita/data/donation/welcomebanner1.jpg b/krita/data/donation/welcomebanner1.jpgnew file mode 100644index 0000000000..b649b7f765Binary files /dev/null and b/krita/data/donation/welcomebanner1.jpg differdiff --git a/krita/data/donation/welcomebanner2.jpg b/krita/data/donation/welcomebanner2.jpgnew file mode 100644index 0000000000..7be78928a6Binary files /dev/null and b/krita/data/donation/welcomebanner2.jpg differdiff --git a/krita/data/donation/welcomebanner3.jpg b/krita/data/donation/welcomebanner3.jpgnew file mode 100644index 0000000000..4eca9d1b93Binary files /dev/null and b/krita/data/donation/welcomebanner3.jpg differdiff --git a/krita/data/donation/welcomebanner4.jpg b/krita/data/donation/welcomebanner4.jpgnew file mode 100644index 0000000000..292b164f81Binary files /dev/null and b/krita/data/donation/welcomebanner4.jpg differdiff --git a/krita/data/splash/electrichearts_20250824A_kiki_HD.jpg b/krita/data/splash/electrichearts_20250824A_kiki_HD.jpgnew file mode 100644index 0000000000..86ba03f733Binary files /dev/null and b/krita/data/splash/electrichearts_20250824A_kiki_HD.jpg differdiff --git a/krita/data/splash/splash-android.qrc b/krita/data/splash/splash-android.qrcnew file mode 100644index 0000000000..d7147ad4ee--- /dev/null+++ b/krita/data/splash/splash-android.qrc@@ -0,0 +1,12 @@+<!DOCTYPE RCC>+<!--+ SPDX-FileCopyrightText: none+ SPDX-License-Identifier: CC0-1.0+-->+<RCC version="1.0">+ <qresource prefix="/splash">+ <file>banner.svg</file>+ <file alias="hd.jpg">electrichearts_20250824A_kiki_HD.jpg</file>+ </qresource>+</RCC>+diff --git a/krita/krita5.xmlgui b/krita/krita5.xmlguiindex cbf7da1757..d8cf6e7c69 100644--- a/krita/krita5.xmlgui+++ b/krita/krita5.xmlgui@@ -386,6 +386,9 @@ xsi:schemaLocation="http://www.kde.org/standards/kxmlgui/1.0 http://www.kde.org<Action name="options_configure"/><Action name="manage_bundles"/><Action name="manage_resources"/>+ <Action name="manage_supporter_bundles"/>+ <Action name="manage_donations"/>+ <Action name="manage_subscriptions"/><Separator/><Action name="options_configure_toolbars"/><Merge name="StandardToolBarMenuHandler" />diff --git a/krita/kritamenu_android.action b/krita/kritamenu_android.actionnew file mode 100644index 0000000000..cc3d3cea0b--- /dev/null+++ b/krita/kritamenu_android.action@@ -0,0 +1,46 @@+<?xml version="1.0" encoding="UTF-8"?>+<ActionCollection version="2" name="Supporter Benefits">+ <Actions category="Resources">+ <text>Resources</text>+ <Action name="manage_supporter_bundles">+ <icon></icon>+ <text>Get More Resources...</text>+ <whatsThis></whatsThis>+ <toolTip>Get More Resources</toolTip>+ <iconText>Get More Resources</iconText>+ <activationFlags>0</activationFlags>+ <activationConditions>0</activationConditions>+ <shortcut></shortcut>+ <isCheckable>false</isCheckable>+ <statusTip></statusTip>+ </Action>+ </Actions>+ <Actions category="Management">+ <text>Management</text>+ <Action name="manage_donations">+ <icon></icon>+ <text>Manage Supporter Benefits...</text>+ <whatsThis></whatsThis>+ <toolTip>Manage Supporter Benefits</toolTip>+ <iconText>Manage Supporter Benefits</iconText>+ <activationFlags>0</activationFlags>+ <activationConditions>0</activationConditions>+ <shortcut></shortcut>+ <isCheckable>false</isCheckable>+ <statusTip></statusTip>+ </Action>+ <Action name="manage_subscriptions">+ <icon></icon>+ <text>Manage Subscriptions...</text>+ <whatsThis></whatsThis>+ <toolTip>Manage Subscriptions</toolTip>+ <iconText>Manage Subscriptions</iconText>+ <activationFlags>0</activationFlags>+ <activationConditions>0</activationConditions>+ <shortcut></shortcut>+ <isCheckable>false</isCheckable>+ <statusTip></statusTip>+ </Action>+ </Actions>+</ActionCollection>+diff --git a/libs/ui/CMakeLists.txt b/libs/ui/CMakeLists.txtindex a2e8574429..2877e3f416 100644--- a/libs/ui/CMakeLists.txt+++ b/libs/ui/CMakeLists.txt@@ -503,6 +503,11 @@ if(WIN32)${kritaui_LIB_SRCS}dialogs/KisDlgCustomTabletResolution.cpp)+elseif(ANDROID)+ list(APPEND kritaui_LIB_SRCS+ dialogs/KisDonationManagementDialog.cpp+ widgets/KisDonationManagementWidget.cpp+ )endif()set(kritaui_LIB_SRCS@@ -661,6 +666,11 @@ if(WIN32)ki18n_wrap_ui(kritaui_LIB_SRCSdialogs/KisDlgCustomTabletResolution.ui)+elseif(ANDROID)+ ki18n_wrap_ui(kritaui_LIB_SRCS+ dialogs/KisDonationManagementDialog.ui+ widgets/KisDonationManagementWidget.ui+ )endif()if (KRITA_USE_SURFACE_COLOR_MANAGEMENT_API)diff --git a/libs/ui/KisAndroidDonations.cpp b/libs/ui/KisAndroidDonations.cppindex 610e55489a..13c4d7d08e 100644--- a/libs/ui/KisAndroidDonations.cpp+++ b/libs/ui/KisAndroidDonations.cpp@@ -4,11 +4,71 @@#include "KisAndroidDonations.h"#include "KisApplication.h"+#include "kis_splash_screen.h"+#include <QAndroidJniEnvironment>+#include <QImage>+#include <QTemporaryFile>#include <QtAndroid>// See DonationHelper.java for notes!+namespace+{+void cleanupProductIconData(void *info)+{+ uint32_t *data = static_cast<uint32_t *>(info);+ delete[] data;+}++QPixmap getProductIcon(const QAndroidJniObject &javaProduct)+{+ jint width = 256;+ jint height = 256;++ QAndroidJniObject pixelsArrayObject = javaProduct.callObjectMethod("getIconPixels", "(II)[I", width, height);+ if (!pixelsArrayObject.isValid()) {+ return QPixmap();+ }++ jintArray pixelsArray = static_cast<jintArray>(pixelsArrayObject.object());+ if (!pixelsArray) {+ return QPixmap();+ }++ QAndroidJniEnvironment env;+ jsize length = env->GetArrayLength(pixelsArray);+ if (length != jsize(width) * jsize(height)) {+ return QPixmap();+ }++ jint *pixels = env->GetIntArrayElements(pixelsArray, nullptr);+ if (!pixels) {+ return QPixmap();+ }++ uint32_t *data = new uint32_t[length];+ for (jsize i = 0; i < length; ++i) {+ data[i] = uint32_t(pixels[i]);+ }++ env->ReleaseIntArrayElements(pixelsArray, pixels, 0);++ QPixmap pixmap;+ if (!pixmap.convertFromImage(QImage(reinterpret_cast<uchar *>(data),+ int(width),+ int(height),+ qsizetype(width) * qsizetype(4),+ QImage::Format_ARGB32,+ cleanupProductIconData,+ data))) {+ return QPixmap();+ }++ return pixmap;+}+} // namespace+KisAndroidDonations *KisAndroidDonations::instance(){KisApplication *app = qobject_cast<KisApplication *>(KisApplication::instance());@@ -19,28 +79,133 @@ KisAndroidDonations *KisAndroidDonations::instance()}}-bool KisAndroidDonations::shouldShowDonationLink() const+void KisAndroidDonations::setLoaded(bool loaded)+{+ QAndroidJniObject::callStaticMethod<void>("org/krita/android/MainActivity", "setLoaded", "(Z)V", jboolean(loaded));+}++void KisAndroidDonations::setLoadingText(const QString &text){- // Normally, we'd want to show a donation link when the state is NoSupport.- // However, currently we only have the lifetime badge as a product and we- // don't want to continue offering that, so the link is disabled for now.- return false;+ QAndroidJniObject textObject = QAndroidJniObject::fromString(text);+ QAndroidJniObject::callStaticMethod<void>("org/krita/android/MainActivity",+ "setLoadingText",+ "(Ljava/lang/String;)V",+ textObject.object<jstring>());+}++void KisAndroidDonations::showDonationDialog(bool splash)+{+ QAndroidJniEnvironment env;+ jbyteArray splashBytes = nullptr;+ QString splashArtist;+ if (splash) {+ KisSplashScreen::Source source = KisSplashScreen::getImageSource();+ splashArtist = source.artistCredit;+ QFile f(source.resourcePath);+ if (f.open(QIODevice::ReadOnly)) {+ QByteArray buf = f.readAll();+ f.close();++ jsize length = buf.size();+ if (length > 0) {+ splashBytes = env->NewByteArray(length);+ env->SetByteArrayRegion(splashBytes, 0, length, reinterpret_cast<const jbyte *>(buf.constData()));+ }+ } else {+ qWarning("Failed to read splash screen image from '%s': %s",+ qUtf8Printable(source.resourcePath),+ qUtf8Printable(f.errorString()));+ }+ }+ QAndroidJniObject splashArtistObject = QAndroidJniObject::fromString(splashArtist);+ QAndroidJniObject splashVersionObject = QAndroidJniObject::fromString(qApp->applicationVersion());+ QAndroidJniObject::callStaticMethod<void>("org/krita/android/MainActivity",+ "showDonationDialog",+ "(Z[BLjava/lang/String;Ljava/lang/String;)V",+ jboolean(splash),+ splashBytes,+ splashArtistObject.object(),+ splashVersionObject.object());+ if (splashBytes) {+ env->DeleteLocalRef(splashBytes);+ }}bool KisAndroidDonations::shouldShowSupporterBadge() const{- return m_state == State::LifetimeSupporter;+ return m_state == State::Supporter && isProductOwned(QStringLiteral("thankyoukiki"));+}++void KisAndroidDonations::setShowDonationManagementDialogPending(bool pending)+{+ if (pending && !m_showDonationManagementDialogPending) {+ m_showDonationManagementDialogPending = true;+ Q_EMIT sigShowDonationManagementDialogRequested();+ } else if (!pending && m_showDonationManagementDialogPending) {+ m_showDonationManagementDialogPending = false;+ }+}++QVector<KisSupporterProduct> KisAndroidDonations::getCurrentProducts() const+{+ QVector<KisSupporterProduct> products;+ QAndroidJniObject currentProducts = QAndroidJniObject::callStaticObjectMethod("org/krita/android/DonationHelper",+ "getCurrentProducts",+ "()Ljava/util/List;");+ jint size = currentProducts.callMethod<jint>("size", "()I");+ products.reserve(size);+ for (jint i = 0; i < size; ++i) {+ QAndroidJniObject javaProduct = currentProducts.callObjectMethod("get", "(I)Ljava/lang/Object;", i);++ products.append(KisSupporterProduct{+ KisSupporterProductType(javaProduct.callMethod<jint>("getType", "()I")),+ KisSupporterProductAvailability(javaProduct.callMethod<jint>("getAvailability", "()I")),+ javaProduct.callObjectMethod("getId", "()Ljava/lang/String;").toString(),+ javaProduct.callObjectMethod("getTitle", "()Ljava/lang/String;").toString(),+ javaProduct.callObjectMethod("getDescription", "()Ljava/lang/String;").toString(),+ getProductIcon(javaProduct),+ javaProduct.callObjectMethod("getButtonText", "()Ljava/lang/String;").toString(),+ javaProduct.callObjectMethod("getOfferToken", "()Ljava/lang/String;").toString(),+ });+ }+ return products;+}++void KisAndroidDonations::startBillingFlowFor(const QString &productId, const QString &offerToken)+{+ QAndroidJniObject productIdObject = QAndroidJniObject::fromString(productId);+ QAndroidJniObject offerTokenObject = QAndroidJniObject::fromString(offerToken);+ QAndroidJniObject::callStaticMethod<void>("org/krita/android/DonationHelper",+ "startBillingFlowForProductId",+ "(Ljava/lang/String;Ljava/lang/String;)V",+ productIdObject.object<jstring>(),+ offerTokenObject.object<jstring>());}void KisAndroidDonations::slotStartDonationFlow(){- QAndroidJniObject::callStaticMethod<void>("org/krita/android/DonationHelper", "startBillingFlow", "()V");+ showDonationDialog(false);+}++void KisAndroidDonations::slotManageSubscriptions()+{+ QAndroidJniObject::callStaticMethod<void>("org/krita/android/MainActivity", "manageSubscriptions", "()V");}-void KisAndroidDonations::slotUpdateState(int state)+void KisAndroidDonations::slotManageSubscription(const QString &productId){- if (int(m_state) != state) {+ QAndroidJniObject productIdObject = QAndroidJniObject::fromString(productId);+ QAndroidJniObject::callStaticMethod<void>("org/krita/android/MainActivity",+ "manageSubscription",+ "(Ljava/lang/String;)V",+ productIdObject.object<jstring>());+}++void KisAndroidDonations::slotUpdateState(int state, long long ownedProductFlags)+{+ if (int(m_state) != state || m_ownedProductFlags != ownedProductFlags) {m_state = State(state);+ m_ownedProductFlags = ownedProductFlags;Q_EMIT sigStateChanged();}}@@ -49,7 +214,19 @@ KisAndroidDonations::KisAndroidDonations(QObject *parent): QObject(parent){// The state update can come from a different thread, so we'll use a queued connection.- connect(this, SIGNAL(sigStateUpdateReceived(int)), this, SLOT(slotUpdateState(int)), Qt::QueuedConnection);+ connect(this,+ &KisAndroidDonations::sigStateUpdateReceived,+ this,+ &KisAndroidDonations::slotUpdateState,+ Qt::QueuedConnection);+}++bool KisAndroidDonations::isProductOwned(const QString &productId) const+{+ QAndroidJniObject productIdObject = QAndroidJniObject::fromString(productId);+ return QAndroidJniObject::callStaticMethod<jboolean>("org/krita/android/DonationHelper",+ "isProductOwned",+ "(Ljava/lang/String;)B");}void KisAndroidDonations::syncState()@@ -59,13 +236,26 @@ void KisAndroidDonations::syncState()extern "C" JNIEXPORT void JNICALL Java_org_krita_android_JNIWrappers_donationStateUpdated(JNIEnv * /*env*/,jobject /*obj*/,- jint state)+ jint state,+ jlong ownedProductFlags)+{+ KisApplication *app = qobject_cast<KisApplication *>(KisApplication::instance());+ if (app) {+ KisAndroidDonations *androidDonations = app->androidDonations();+ if (androidDonations) {+ Q_EMIT androidDonations->sigStateUpdateReceived(state, ownedProductFlags);+ }+ }+}++extern "C" JNIEXPORT void JNICALL Java_org_krita_android_JNIWrappers_showDonationManagementDialog(JNIEnv * /*env*/,+ jobject /*obj*/){KisApplication *app = qobject_cast<KisApplication *>(KisApplication::instance());if (app) {KisAndroidDonations *androidDonations = app->androidDonations();if (androidDonations) {- Q_EMIT androidDonations->sigStateUpdateReceived(state);+ androidDonations->setShowDonationManagementDialogPending(true);}}}diff --git a/libs/ui/KisAndroidDonations.h b/libs/ui/KisAndroidDonations.hindex 8d7fd3c96f..397b11d1f3 100644--- a/libs/ui/KisAndroidDonations.h+++ b/libs/ui/KisAndroidDonations.h@@ -5,7 +5,9 @@#define __KISANDROIDDONATIONS_H_#include <QObject>+#include <QVector>+#include "KisSupporterProduct.h"#include "kritaui_export.h"// See DonationHelper.java for notes!@@ -29,31 +31,54 @@ public:Unavailable = 2,// User does not own any support products, but they could purchase one.NoSupport = 3,- // User purchased the (legacy) lifetime supporter badge.- LifetimeSupporter = 4,+ // User owns at least some kind of supporter product.+ Supporter = 4,};static KisAndroidDonations *instance();- bool shouldShowDonationLink() const;+ State state() const { return m_state; }+bool shouldShowSupporterBadge() const;+ bool isShowDonationManagementDialogPending() const+ {+ return m_showDonationManagementDialogPending;+ }++ void setShowDonationManagementDialogPending(bool pending);++ QVector<KisSupporterProduct> getCurrentProducts() const;++ void startBillingFlowFor(const QString &productId, const QString &offerToken);++ static void setLoaded(bool loaded);+ static void setLoadingText(const QString &text);+ static void showDonationDialog(bool splash);+public Q_SLOTS:void slotStartDonationFlow();+ void slotManageSubscriptions();+ void slotManageSubscription(const QString &productId);private Q_SLOTS:- void slotUpdateState(int state);+ void slotUpdateState(int state, long long ownedProductFlags);Q_SIGNALS:- void sigStateUpdateReceived(int state);+ void sigStateUpdateReceived(int state, long long ownedProductFlags);void sigStateChanged();+ void sigShowDonationManagementDialogRequested();private:explicit KisAndroidDonations(QObject *parent = nullptr);+ bool isProductOwned(const QString &productId) const;+void syncState();State m_state{State::Unknown};+ long long m_ownedProductFlags{0L};+ bool m_showDonationManagementDialogPending{false};};#endif // __KISANDROIDDONATIONS_Hdiff --git a/libs/ui/KisApplication.cpp b/libs/ui/KisApplication.cppindex 627046ddc6..b1dde6afd7 100644--- a/libs/ui/KisApplication.cpp+++ b/libs/ui/KisApplication.cpp@@ -496,6 +496,10 @@ void KisApplication::loadPlugins()bool KisApplication::start(const KisApplicationArguments &args){+#ifdef Q_OS_ANDROID+ KisAndroidDonations::showDonationDialog(true);+#endif+KisConfig cfg(false);#if defined(Q_OS_WIN)@@ -536,12 +540,14 @@ bool KisApplication::start(const KisApplicationArguments &args)// only show the mainWindow when no command-line mode option is passedbool showmainWindow = (!exportAs && !exportSequence); // would be !batchRun;+#ifndef Q_OS_ANDROIDconst bool showSplashScreen = !d->batchRun && qEnvironmentVariableIsEmpty("NOSPLASH");if (showSplashScreen && d->splashScreen) {d->splashScreen->show();d->splashScreen->repaint();processEvents();}+#endifKConfigGroup group(KSharedConfig::openConfig(), "theme");#ifndef Q_OS_HAIKU@@ -635,6 +641,9 @@ bool KisApplication::start(const KisApplicationArguments &args)}setSplashScreenLoadingText(QString()); // done loading, so clear out label+#ifdef Q_OS_ANDROID+ KisAndroidDonations::setLoaded(true);+#endifprocessEvents();//configure the unit manager@@ -879,10 +888,16 @@ void KisApplication::setSplashScreenLoadingText(const QString &textToLoad)d->splashScreen->setLoadingText(textToLoad);d->splashScreen->repaint();}+#ifdef Q_OS_ANDROID+ KisAndroidDonations::setLoadingText(textToLoad);+#endif}void KisApplication::hideSplashScreen(){+#ifdef Q_OS_ANDROID+ KisAndroidDonations::setLoaded(true);+#endifif (d->splashScreen) {// hide the splashscreen to see the dialogd->splashScreen->hide();@@ -1167,7 +1182,7 @@ void KisApplication::checkAutosaveFiles()if (autosaveFiles.size() > 0) {if (d->splashScreen) {// hide the splashscreen to see the dialog- d->splashScreen->hide();+ hideSplashScreen();}d->autosaveDialog = new KisAutoSaveRecoveryDialog(autosaveFiles, activeWindow());QDialog::DialogCode result = (QDialog::DialogCode) d->autosaveDialog->exec();diff --git a/libs/ui/KisMainWindow.cpp b/libs/ui/KisMainWindow.cppindex fcd9e943ca..7cf796a258 100644--- a/libs/ui/KisMainWindow.cpp+++ b/libs/ui/KisMainWindow.cpp@@ -99,6 +99,8 @@#include <KisPlaybackEngine.h>#ifdef Q_OS_ANDROID+#include "KisAndroidDonations.h"+#include "dialogs/KisDonationManagementDialog.h"#include <QtAndroid>#include <KisAndroidUtils.h>#endif@@ -254,7 +256,10 @@ public:KisAction *toggleDockers {nullptr};KisAction *resetConfigurations {nullptr};KisAction *toggleDockerTitleBars {nullptr};-#ifndef Q_OS_ANDROID+#ifdef Q_OS_ANDROID+ KisAction *showDonationManagementDialog {nullptr};+ KisAction *manageSubscriptions {nullptr};+#elseKisAction *toggleDetachCanvas {nullptr};KisAction *newWindow {nullptr};#endif@@ -1637,6 +1642,13 @@ void KisMainWindow::showEvent(QShowEvent *event)}#ifdef Q_OS_ANDROIDQ_EMIT sigFullscreenOnShow(true); // Android defaults to fullscreen.+ // The user can conceivably purchase a product from the splash screen while+ // Krita is still loading. In that case, the "pending" flag will be set. The+ // dialog in question will clear the flag.+ KisAndroidDonations *androidDonations = KisAndroidDonations::instance();+ if (androidDonations && androidDonations->isShowDonationManagementDialogPending()) {+ QTimer::singleShot(0, this, &KisMainWindow::slotShowDonationManagementDialog);+ }#endifreturn KXmlGuiWindow::showEvent(event);}@@ -1852,6 +1864,39 @@ void KisMainWindow::slotShowSessionManager() {KisPart::instance()->showSessionManager();}+#ifdef Q_OS_ANDROID+void KisMainWindow::slotShowDonationManagementDialog()+{+ // Don't show the donation management dialog on top of another dialog+ // that may have triggered a donation flow, such as the bundle manager.+ QWidget *win = qApp->activeWindow();+ if (win && !qobject_cast<KisMainWindow *>(win) && (win->isModal() || win->windowModality() != Qt::NonModal)) {+ return;+ }++ // We don't use `exec` here because the purchase stuff runs in Android's+ // event loop, so it's legitimately possible that we get hit by another+ // request to show the donation management dialog while it's already up+ // and it's more convenient for the dialog to handle the deduplication.+ QString objectName = QStringLiteral("kisdonationmanagementdialog");+ KisDonationManagementDialog *dlg = findChild<KisDonationManagementDialog *>(objectName, Qt::FindDirectChildrenOnly);+ if (dlg) {+ dlg->reshow();+ } else {+ dlg = new KisDonationManagementDialog(this);++ QAction *action = actionCollection()->action("manage_supporter_bundles");+ if (action) {+ connect(dlg, &KisDonationManagementDialog::sigShowSupporterBundles, action, &QAction::trigger);+ }++ dlg->setAttribute(Qt::WA_DeleteOnClose);+ dlg->setObjectName(objectName);+ dlg->show();+ }+}+#endif+KoCanvasResourceProvider *KisMainWindow::resourceManager() const{return d->viewManager->canvasResourceProvider()->resourceManager();@@ -3050,7 +3095,27 @@ void KisMainWindow::createActions()d->mdiPreviousWindow = actionManager->createAction("windows_previous");connect(d->mdiPreviousWindow, SIGNAL(triggered()), d->mdiArea, SLOT(activatePreviousSubWindow()));-#ifndef Q_OS_ANDROID+#ifdef Q_OS_ANDROID+ d->showDonationManagementDialog = actionManager->createAction("manage_donations");+ connect(d->showDonationManagementDialog,+ &QAction::triggered,+ this,+ &KisMainWindow::slotShowDonationManagementDialog);++ KisAndroidDonations *androidDonations = KisAndroidDonations::instance();+ if (androidDonations) {+ d->manageSubscriptions = actionManager->createAction("manage_subscriptions");+ connect(d->manageSubscriptions,+ &QAction::triggered,+ androidDonations,+ &KisAndroidDonations::slotManageSubscriptions);+ connect(androidDonations,+ &KisAndroidDonations::sigShowDonationManagementDialogRequested,+ this,+ &KisMainWindow::slotShowDonationManagementDialog,+ Qt::QueuedConnection);+ }+#elsed->newWindow = actionManager->createAction("view_newwindow");connect(d->newWindow, SIGNAL(triggered(bool)), this, SLOT(newWindow()));#endifdiff --git a/libs/ui/KisMainWindow.h b/libs/ui/KisMainWindow.hindex d2f9425020..c907d6a7ae 100644--- a/libs/ui/KisMainWindow.h+++ b/libs/ui/KisMainWindow.h@@ -260,6 +260,10 @@ public Q_SLOTS:void slotShowSessionManager();+#ifdef Q_OS_ANDROID+ void slotShowDonationManagementDialog();+#endif+/*** Update the option widgets to the argument ones, removing the currently set widgets.*/diff --git a/libs/ui/KisSupporterProduct.h b/libs/ui/KisSupporterProduct.hnew file mode 100644index 0000000000..8c544a3148--- /dev/null+++ b/libs/ui/KisSupporterProduct.h@@ -0,0 +1,36 @@+/*+ * SPDX-License-Identifier: GPL-3.0-or-later+ */+#ifndef __KISSUPPORTERPRODUCT_H_+#define __KISSUPPORTERPRODUCT_H_++#include <QPixmap>+#include <QString>++#include "kritaui_export.h"++// Keep in sync with KisSupporterProduct.java!++enum class KRITAUI_EXPORT KisSupporterProductType {+ OneTime,+ Subscription,+};++enum class KRITAUI_EXPORT KisSupporterProductAvailability {+ Missing,+ Available,+ Owned,+};++struct KRITAUI_EXPORT KisSupporterProduct {+ KisSupporterProductType type;+ KisSupporterProductAvailability availability;+ QString id;+ QString title;+ QString description;+ QPixmap icon;+ QString buttonText;+ QString offerToken;+};++#endifdiff --git a/libs/ui/KisWelcomePageWidget.cpp b/libs/ui/KisWelcomePageWidget.cppindex c066d502ce..3c44e7a832 100644--- a/libs/ui/KisWelcomePageWidget.cpp+++ b/libs/ui/KisWelcomePageWidget.cpp@@ -83,6 +83,11 @@#ifdef Q_OS_ANDROID#include "KisAndroidDonations.h"+#include <QFontMetrics>+#include <QPaintDevice>+#include <QPainter>+#include <QPainterPath>+#include <QRandomGenerator>#endif// Used for triggering a QAction::setChecked signal from a QLabel::linkActivated signal@@ -167,7 +172,6 @@ KisWelcomePageWidget::KisWelcomePageWidget(QWidget *parent)btnNewsOptions->setMenu(newsOptionsMenu);labelSupportText->setFont(largerFont());- donationLink->setFont(largerFont());connect(showNewsAction, SIGNAL(toggled(bool)), newsWidget, SLOT(setVisible(bool)));connect(showNewsAction, SIGNAL(toggled(bool)), labelNoFeed, SLOT(setHidden(bool)));@@ -180,7 +184,6 @@ KisWelcomePageWidget::KisWelcomePageWidget(QWidget *parent)connect(showNewsAction, SIGNAL(toggled(bool)), this, SLOT(slotToggleUpdateChecks(bool)));#endif- donationLink->hide();supporterBadge->hide();#ifdef Q_OS_ANDROIDinitDonations();@@ -395,11 +398,6 @@ void KisWelcomePageWidget::slotUpdateThemeColors()updateVersionUpdaterFrame(); // updater frame#endif-#ifdef Q_OS_ANDROID- donationLink->setText(- QStringLiteral("<a href=\"#\">%1</a>").arg(QString(i18n("Get your Krita Supporter Badge here!"))));-#endif-#ifdef Q_OS_MACOS// macOS store version should not contain external links containing donation buttons or formsif (KisMacosEntitlements().sandbox()) {@@ -408,7 +406,6 @@ void KisWelcomePageWidget::slotUpdateThemeColors()labelSupportText->hide();kritaWebsiteLink->hide();kritaWebsiteIcon->hide();- donationLink->hide();}#endif}@@ -479,7 +476,6 @@ void KisWelcomePageWidget::changeEvent(QEvent *event){if (event->type() == QEvent::FontChange) {labelSupportText->setFont(largerFont());- donationLink->setFont(largerFont());}}@@ -795,14 +791,158 @@ void KisWelcomePageWidget::initDonations()return;}- connect(donationLink, SIGNAL(linkActivated(QString)), androidDonations, SLOT(slotStartDonationFlow()));+ // Pick a random banner. Note that the second number is *exclusive*.+ int bannerIndex = QRandomGenerator::global()->bounded(1, 5);++ // Banners have space where we can place text, but this varies by banner.+ // These are the relative locations where that space is.+ qreal ry = 0.02; // Vertical offset, always the same.+ qreal rh = 1.0 - ry * 2.0; // Height, dito.+ qreal rwpad = 0.02; // Horizontal padding.+ qreal rx, rw; // Horizontal offset and width, vary by banner.+ switch (bannerIndex) {+ case 1: // Kiki winking on the left.+ case 3: // Stargazers on the left.+ rx = 0.4;+ rw = 1.0 - rx - rwpad;+ break;+ case 2: // Cat holding brush in its mouth on the right.+ case 4: // Person holding digital palette on the right.+ rx = rwpad;+ rw = 0.6 - rx;+ break;+ default: // Shouldn't happen, punt to using the entire width minus padding.+ qWarning("Unhandled banner index %d", bannerIndex);+ rx = rwpad;+ rw = 1.0 - rwpad * 2.0;+ break;+ }- QString bannerPath = QStandardPaths::locate(QStandardPaths::AppDataLocation, "share/krita/donation/banner.png");- QPixmap pixmap(bannerPath);- if (pixmap.isNull()) {- qWarning("KisWelcomePage::initDonations: failed to load banner from '%s'", qUtf8Printable(bannerPath));+ QString welcomeBannerPath =+ QStandardPaths::locate(QStandardPaths::AppDataLocation,+ QStringLiteral("share/krita/donation/welcomebanner%1.jpg").arg(bannerIndex));+ QPixmap welcomeBannerPixmap(welcomeBannerPath);++ if (welcomeBannerPixmap.isNull()) {+ qWarning("KisWelcomePage::initDonations: failed to load welcome banner from '%s'",+ qUtf8Printable(welcomeBannerPath));+ // Leave the button alone, it will just say "Support Krita!"} else {- supporterBadge->setPixmap(QPixmap(bannerPath));+ QVector<QString> headlines = {+ i18n("Become a Supporter!"),+ i18n("Support Krita!"),+ };+ QVector<QString> subtitles = {+ i18n("Supporters get brush packs and more."),+ i18n("Contributions keep development going."),+ };+ QString headline = headlines[QRandomGenerator::global()->bounded(headlines.size())];+ QString subtitle = subtitles[QRandomGenerator::global()->bounded(subtitles.size())];++ // We want some text on the banner, which unfortunately requires some+ // manual layout. We're going to write a top line in a larger font and+ // a bottom line in a smaller font. They're going to be separated by a+ // few pixels, centered horizontally and fit into predefined bounds on+ // the banner depending on which image we're using. The text will be+ // white with a black outline, so we'll use QPainterPath. Math time.+ QPainter painter(&welcomeBannerPixmap);+ painter.setRenderHint(QPainter::Antialiasing);+ painter.setRenderHint(QPainter::TextAntialiasing);++ QPen pen(Qt::black, 12.0, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin);+ QBrush brush(Qt::white);++ qreal verticalSeparation = 40.0;++ // Top line, the heading.+ QFont currentFont = font();+ currentFont.setPointSize(100);+ currentFont.setBold(false);+ QPainterPath topPath;+ topPath.addText(0, 0, currentFont, headline);+ QRectF topBounds = topPath.boundingRect();++ // Bottom line, smaller text for more words.+ currentFont.setPointSize(60);+ currentFont.setBold(true);+ QPainterPath bottomPath;+ bottomPath.addText(0, 0, currentFont, subtitle);+ QRectF bottomBounds = bottomPath.boundingRect();++ // Stick those two lines into a combined path, horizontally centered,+ // separated a bit so that the text doesn't get glued together.+ qreal maxWidth = qMax(topBounds.width(), bottomBounds.width());+ qreal topOffsetX = (maxWidth - topBounds.width()) / 2.0;+ qreal bottomOffsetX = (maxWidth - bottomBounds.width()) / 2.0;++ QTransform topTransform;+ topTransform.translate(topOffsetX - topBounds.left(), -topBounds.top());+ topPath = topTransform.map(topPath);+ topPath.setFillRule(Qt::WindingFill);++ QTransform bottomTransform;+ bottomTransform.translate(bottomOffsetX - bottomBounds.left(),+ topBounds.height() + verticalSeparation - bottomBounds.top());+ bottomPath = bottomTransform.map(bottomPath);+ bottomPath.setFillRule(Qt::WindingFill);++ QPainterPath combinedPath;+ combinedPath.addPath(topPath);+ combinedPath.addPath(bottomPath);++ // Determine the rectangle on the banner that we want to fit the text+ // into. Taking a detour through the paint device just in case high-DPI+ // scaling messes with the dimensions somehow.+ qreal w = painter.device()->width();+ qreal h = painter.device()->height();+ QRect rect(w * rx, h * ry, w * rw, h * rh);++ QRectF combinedBounds = combinedPath.boundingRect();+ qreal scaleX = rect.width() / combinedBounds.width();+ qreal scaleY = rect.height() / combinedBounds.height();+ qreal scale = qMin(scaleX, scaleY);+ qreal combinedOffsetX = (rect.width() - (combinedBounds.width() * scale)) / 2.0;+ qreal combinedOffsetY = (rect.height() - (combinedBounds.height() * scale)) / 2.0;++ QTransform combinedTransform;+ combinedTransform.translate(rect.left() + combinedOffsetX, rect.top() + combinedOffsetY);+ combinedTransform.scale(scale, scale);+ combinedTransform.translate(-combinedBounds.left(), -combinedBounds.top());+ combinedPath = combinedTransform.map(combinedPath);+ combinedPath.setFillRule(Qt::WindingFill);++ // And finally, draw the text onto the banner. First stroking the+ // outside, then filling the inside, otherwise there's weird effects+ // with strokes inside of letters overlapping with the fill.+ painter.setPen(pen);+ painter.setBrush(Qt::NoBrush);+ painter.drawPath(combinedPath);++ painter.setPen(Qt::NoPen);+ painter.setBrush(brush);+ painter.drawPath(combinedPath);++ QSize welcomeBannerSize = welcomeBannerPixmap.size().scaled(500, 100, Qt::KeepAspectRatio);+ bnAndroidSupport->setFlat(false);+ bnAndroidSupport->setText(QString());+ bnAndroidSupport->setContentsMargins(0, 0, 0, 0);+ bnAndroidSupport->setIcon(QIcon(welcomeBannerPixmap));+ bnAndroidSupport->setIconSize(welcomeBannerSize);+ bnAndroidSupport->setFixedSize(welcomeBannerSize);+ }++ connect(bnAndroidSupport, &QPushButton::clicked, androidDonations, &KisAndroidDonations::slotStartDonationFlow);+ connect(bnAndroidSupporterManage,+ &QPushButton::clicked,+ androidDonations,+ &KisAndroidDonations::sigShowDonationManagementDialogRequested);++ QString badgePath = QStandardPaths::locate(QStandardPaths::AppDataLocation, "share/krita/donation/banner.png");+ QPixmap badgePixmap(badgePath);+ if (badgePixmap.isNull()) {+ qWarning("KisWelcomePage::initDonations: failed to load badge from '%s'", qUtf8Printable(badgePath));+ } else {+ supporterBadge->setPixmap(badgePixmap);}connect(androidDonations, SIGNAL(sigStateChanged()), this, SLOT(slotUpdateDonationState()));@@ -811,18 +951,35 @@ void KisWelcomePageWidget::initDonations()void KisWelcomePageWidget::slotUpdateDonationState(){- bool linkVisible = false;bool badgeVisible = false;+ QWidget *pageVisible = pgSupportMessage;KisAndroidDonations *androidDonations = KisAndroidDonations::instance();if (androidDonations) {- linkVisible = androidDonations->shouldShowDonationLink();badgeVisible = androidDonations->shouldShowSupporterBadge();+ switch (androidDonations->state()) {+ case KisAndroidDonations::State::Supporter:+ pageVisible = pgAndroidSupporter;+ break;+ case KisAndroidDonations::State::NoSupport:+ pageVisible = nullptr;+ break;+ default:+ break;+ }} else {qWarning("KisWelcomePageWidget::slotUpdateDonationState: android donations is null");}- donationLink->setVisible(linkVisible);+ if(pageVisible) {+ stkSupport->setCurrentWidget(pageVisible);+ wdgAndroidSupportBanner->hide();+ stkSupport->show();+ } else {+ stkSupport->hide();+ wdgAndroidSupportBanner->show();+ }+supporterBadge->setVisible(badgeVisible);}#endifdiff --git a/libs/ui/dialogs/KisDonationManagementDialog.cpp b/libs/ui/dialogs/KisDonationManagementDialog.cppnew file mode 100644index 0000000000..2b8da81dc0--- /dev/null+++ b/libs/ui/dialogs/KisDonationManagementDialog.cpp@@ -0,0 +1,177 @@+/*+ * SPDX-License-Identifier: GPL-3.0-or-later+ */+#include "KisDonationManagementDialog.h"+#include "kis_assert.h"+#include <KisDonationManagementWidget.h>+#include <KisKineticScroller.h>+#include <QFrame>+#include <QLabel>++KisDonationManagementDialog::KisDonationManagementDialog(QWidget *parent)+ : QDialog(parent)+ , m_androidDonations(KisAndroidDonations::instance())+{+ KIS_SAFE_ASSERT_RECOVER_NOOP(m_androidDonations);+ setupUi(this);+ setWindowTitle(i18n("Supporter Benefits"));++ QScroller *scroller = KisKineticScroller::createPreconfiguredScroller(m_scrBenefitsList);+ if (scroller) {+ connect(scroller, &QScroller::stateChanged, this, [&](QScroller::State state) {+ KisKineticScroller::updateCursor(this, state);+ });+ }++ QPushButton *btnManageSubscriptions =+ m_buttons->addButton(i18n("Manage Subscriptions"), QDialogButtonBox::ActionRole);++ if (m_androidDonations) {+ // It is theoretically possible that the user purchases a product while+ // Krita is still loading, hence the existence of this "pending" flag,+ // in case the Qt UI isn't ready yet. This here is the dialog that's+ // pending to be shown, so its appearance clears that flag.+ m_androidDonations->setShowDonationManagementDialogPending(false);+ connect(m_androidDonations,+ &KisAndroidDonations::sigStateChanged,+ this,+ &KisDonationManagementDialog::slotUpdateCurrentProducts,+ Qt::QueuedConnection);+ connect(m_btnNoBenefitsSupport,+ &QPushButton::clicked,+ m_androidDonations,+ &KisAndroidDonations::slotStartDonationFlow);+ connect(btnManageSubscriptions,+ &QPushButton::clicked,+ m_androidDonations,+ &KisAndroidDonations::slotManageSubscriptions);+ } else {+ // Shouldn't happen, but just revert to a blank no benefits page.+ m_stack->setCurrentWidget(m_pgNoBenefits);+ m_btnNoBenefitsSupport->hide();+ }++ slotUpdateCurrentProducts();++ connect(m_buttons, &QDialogButtonBox::rejected, this, &KisDonationManagementDialog::reject);+}++void KisDonationManagementDialog::reshow()+{+ if (m_androidDonations) {+ m_androidDonations->setShowDonationManagementDialogPending(false);+ }+ slotUpdateCurrentProducts();+ slotShowOverview();+ activateWindow();+ raise();+}++void KisDonationManagementDialog::slotShowOverview()+{+ if (m_availableProducts.isEmpty() && m_ownedProducts.isEmpty()) {+ m_stack->setCurrentWidget(m_pgNoBenefits);+ } else {+ m_stack->setCurrentWidget(m_pgBenefitsList);+ }+}++void KisDonationManagementDialog::slotUpdateCurrentProducts()+{+ QVector<KisSupporterProduct> availableProducts;+ QVector<KisSupporterProduct> ownedProducts;+ if (m_androidDonations) {+ for (const KisSupporterProduct &product : m_androidDonations->getCurrentProducts()) {+ switch (product.availability) {+ case KisSupporterProductAvailability::Missing:+ break;+ case KisSupporterProductAvailability::Available:+ availableProducts.append(product);+ break;+ case KisSupporterProductAvailability::Owned:+ ownedProducts.append(product);+ break;+ }+ }+ }++ bool productsChanged = !isProductIdsEqual(m_availableProducts, availableProducts)+ || !isProductIdsEqual(m_ownedProducts, ownedProducts);+ if (productsChanged) {+ m_availableProducts = availableProducts;+ m_ownedProducts = ownedProducts;++ while (!m_lytScrBenefitsList->isEmpty()) {+ QLayoutItem *item = m_lytScrBenefitsList->takeAt(m_lytScrBenefitsList->count() - 1);+ QWidget *widget = item->widget();+ if (widget) {+ widget->deleteLater();+ }+ delete item;+ }++ addProductWidgets(+ i18np("You have %1 supporter benefit:", "You have %1 supporter benefits:", m_ownedProducts.size()),+ m_ownedProducts);++ if (!m_availableProducts.isEmpty() && !m_ownedProducts.isEmpty()) {+ addProductSeparator();+ m_lytScrBenefitsList->addSpacing(12);+ }++ addProductWidgets(i18np("There is %1 supporter benefit available:",+ "There are %1 supporter benefits available:",+ m_availableProducts.size()),+ m_availableProducts);++ m_lytScrBenefitsList->addStretch();+ slotShowOverview();+ }+}++void KisDonationManagementDialog::addProductWidgets(const QString &heading,+ const QVector<KisSupporterProduct> &products)+{+ int count = products.size();+ if (count != 0) {+ QLabel *label =+ new QLabel(QStringLiteral("<span style=\"font-size:large;\">%1</span>").arg(heading.toHtmlEscaped()));+ label->setWordWrap(true);+ m_lytScrBenefitsList->addWidget(label);++ for (int i = 0; i < count; ++i) {+ addProductSeparator();+ KisDonationManagementWidget *widget = new KisDonationManagementWidget(products[i]);+ m_lytScrBenefitsList->addWidget(widget);+ connect(widget,+ &KisDonationManagementWidget::sigShowSupporterBundles,+ this,+ &KisDonationManagementDialog::sigShowSupporterBundles);+ }+ }+}++void KisDonationManagementDialog::addProductSeparator()+{+ QFrame *separator = new QFrame;+ separator->setFrameShape(QFrame::HLine);+ separator->setFrameShadow(QFrame::Sunken);+ m_lytScrBenefitsList->addWidget(separator);+}++bool KisDonationManagementDialog::isProductIdsEqual(const QVector<KisSupporterProduct> &a,+ const QVector<KisSupporterProduct> &b)+{+ int count = a.size();+ if (b.size() != count) {+ return false;+ }++ for (int i = 0; i < count; ++i) {+ if (a[i].id != b[i].id) {+ return false;+ }+ }++ return true;+}diff --git a/libs/ui/dialogs/KisDonationManagementDialog.h b/libs/ui/dialogs/KisDonationManagementDialog.hnew file mode 100644index 0000000000..718ee0d951--- /dev/null+++ b/libs/ui/dialogs/KisDonationManagementDialog.h@@ -0,0 +1,42 @@+/*+ * SPDX-License-Identifier: GPL-3.0-or-later+ */+#ifndef __KISDONATIONMANAGEMENTDIALOG_H_+#define __KISDONATIONMANAGEMENTDIALOG_H_++#include <QDialog>+#include <QVector>++#include "kritaui_export.h"+#include "ui_KisDonationManagementDialog.h"+#include <KisAndroidDonations.h>+#include <KisSupporterProduct.h>++class KRITAUI_EXPORT KisDonationManagementDialog : public QDialog, public Ui::KisDonationManagementDialog+{+ Q_OBJECT+public:+ explicit KisDonationManagementDialog(QWidget *parent = nullptr);++ void reshow();++Q_SIGNALS:+ void sigShowSupporterBundles();++private Q_SLOTS:+ void slotShowOverview();+ void slotUpdateCurrentProducts();++private:+ void addProductWidgets(const QString &heading, const QVector<KisSupporterProduct> &products);++ void addProductSeparator();++ static bool isProductIdsEqual(const QVector<KisSupporterProduct> &a, const QVector<KisSupporterProduct> &b);++ KisAndroidDonations *m_androidDonations;+ QVector<KisSupporterProduct> m_availableProducts;+ QVector<KisSupporterProduct> m_ownedProducts;+};++#endifdiff --git a/libs/ui/dialogs/KisDonationManagementDialog.ui b/libs/ui/dialogs/KisDonationManagementDialog.uinew file mode 100644index 0000000000..8a17995a05--- /dev/null+++ b/libs/ui/dialogs/KisDonationManagementDialog.ui@@ -0,0 +1,136 @@+<?xml version="1.0" encoding="UTF-8"?>+<ui version="4.0">+ <class>KisDonationManagementDialog</class>+ <widget class="QDialog" name="KisDonationManagementDialog">+ <property name="geometry">+ <rect>+ <x>0</x>+ <y>0</y>+ <width>600</width>+ <height>480</height>+ </rect>+ </property>+ <property name="windowTitle">+ <string>StackedWidget</string>+ </property>+ <property name="modal">+ <bool>true</bool>+ </property>+ <layout class="QVBoxLayout" name="m_dlgLayout">+ <item>+ <widget class="QStackedWidget" name="m_stack">+ <widget class="QWidget" name="m_pgNoBenefits">+ <layout class="QVBoxLayout" name="m_pgNoBenefitsLayout">+ <property name="leftMargin">+ <number>0</number>+ </property>+ <property name="topMargin">+ <number>0</number>+ </property>+ <property name="rightMargin">+ <number>0</number>+ </property>+ <property name="bottomMargin">+ <number>0</number>+ </property>+ <item>+ <spacer name="m_spcNoBenefitsTop">+ <property name="orientation">+ <enum>Qt::Vertical</enum>+ </property>+ <property name="sizeHint" stdset="0">+ <size>+ <width>0</width>+ <height>0</height>+ </size>+ </property>+ </spacer>+ </item>+ <item>+ <widget class="QLabel" name="m_lblNoBenefits">+ <property name="text">+ <string>No supporter benefits available on this version of Krita.+You can still support Krita by donating.</string>+ </property>+ <property name="alignment">+ <set>Qt::AlignCenter</set>+ </property>+ </widget>+ </item>+ <item>+ <widget class="QPushButton" name="m_btnNoBenefitsSupport">+ <property name="text">+ <string>Donate</string>+ </property>+ </widget>+ </item>+ <item>+ <spacer name="m_spcNoBenefitsBottom">+ <property name="orientation">+ <enum>Qt::Vertical</enum>+ </property>+ <property name="sizeHint" stdset="0">+ <size>+ <width>0</width>+ <height>0</height>+ </size>+ </property>+ </spacer>+ </item>+ </layout>+ </widget>+ <widget class="QWidget" name="m_pgBenefitsList">+ <layout class="QVBoxLayout" name="m_pgBenefitsListLayout">+ <property name="leftMargin">+ <number>0</number>+ </property>+ <property name="topMargin">+ <number>0</number>+ </property>+ <property name="rightMargin">+ <number>0</number>+ </property>+ <property name="bottomMargin">+ <number>0</number>+ </property>+ <item>+ <widget class="QScrollArea" name="m_scrBenefitsList">+ <property name="widgetResizable">+ <bool>true</bool>+ </property>+ <widget class="QWidget" name="m_wdgBenefitsListContents">+ <property name="geometry">+ <rect>+ <x>0</x>+ <y>0</y>+ <width>98</width>+ <height>28</height>+ </rect>+ </property>+ <layout class="QVBoxLayout" name="m_lytScrBenefitsList"/>+ </widget>+ </widget>+ </item>+ </layout>+ </widget>+ </widget>+ </item>+ <item>+ <widget class="Line" name="line">+ <property name="orientation">+ <enum>Qt::Horizontal</enum>+ </property>+ </widget>+ </item>+ <item>+ <widget class="QDialogButtonBox" name="m_buttons">+ <property name="standardButtons">+ <set>QDialogButtonBox::Close</set>+ </property>+ </widget>+ </item>+ </layout>+ </widget>+ <resources/>+ <connections/>+</ui>diff --git a/libs/ui/forms/KisWelcomePage.ui b/libs/ui/forms/KisWelcomePage.uiindex 0f6dd53212..7d6bdb628a 100644--- a/libs/ui/forms/KisWelcomePage.ui+++ b/libs/ui/forms/KisWelcomePage.ui@@ -23,7 +23,7 @@<property name="autoFillBackground"><bool>false</bool></property>- <layout class="QVBoxLayout" name="verticalLayout_3">+ <layout class="QVBoxLayout" name="verticalLayout_3" stretch="1,0,0"><property name="leftMargin"><number>20</number></property>@@ -1522,19 +1522,6 @@ recently opened documents</string></layout></widget></item>- <item>- <widget class="QLabel" name="donationLink">- <property name="text">- <string notr="true">Supporter Link</string>- </property>- <property name="alignment">- <set>Qt::AlignCenter</set>- </property>- <property name="wordWrap">- <bool>true</bool>- </property>- </widget>- </item><item><layout class="QHBoxLayout" name="supporterBadgeLayout"><property name="spacing">@@ -1606,60 +1593,149 @@ recently opened documents</string></widget></item><item>- <layout class="QHBoxLayout" name="horizontalLayout_12">- <item>- <spacer name="horizontalSpacer_9">- <property name="orientation">- <enum>Qt::Horizontal</enum>+ <widget class="QStackedWidget" name="stkSupport">+ <widget class="QWidget" name="pgSupportMessage">+ <layout class="QVBoxLayout" name="lytPgSupportMessage">+ <property name="spacing">+ <number>0</number>+ </property>+ <property name="leftMargin">+ <number>0</number>+ </property>+ <property name="topMargin">+ <number>0</number></property>- <property name="sizeHint" stdset="0">- <size>- <width>40</width>- <height>20</height>- </size>+ <property name="rightMargin">+ <number>0</number></property>- </spacer>- </item>- <item>- <widget class="QLabel" name="labelSupportText">- <property name="sizePolicy">- <sizepolicy hsizetype="MinimumExpanding" vsizetype="Preferred">- <horstretch>1</horstretch>- <verstretch>0</verstretch>- </sizepolicy>+ <property name="bottomMargin">+ <number>0</number></property>- <property name="text">- <string><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd">+ <item>+ <widget class="QLabel" name="labelSupportText">+ <property name="sizePolicy">+ <sizepolicy hsizetype="MinimumExpanding" vsizetype="Preferred">+ <horstretch>1</horstretch>+ <verstretch>0</verstretch>+ </sizepolicy>+ </property>+ <property name="text">+ <string><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"><html><head><meta name="qrichtext" content="1" /><style type="text/css">p, li { white-space: pre-wrap; }</style></head><body><p style=" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Krita is an open source and community-driven tool for digital artists everywhere.<br />Progress is made possible thanks to ongoing support from our community of <a href="https://docs.krita.org/en/contributors_manual.html">contributors</a>, <a href="https://krita.org/en/sponsors/">sponsors</a>, and <a href="https://fund.krita.org/">development fund</a> members.</p></body></html></string>+ </property>+ <property name="alignment">+ <set>Qt::AlignCenter</set>+ </property>+ <property name="wordWrap">+ <bool>true</bool>+ </property>+ <property name="openExternalLinks">+ <bool>true</bool>+ </property>+ </widget>+ </item>+ </layout>+ </widget>+ <widget class="QWidget" name="pgAndroidSupporter">+ <layout class="QVBoxLayout" name="lytPgAndroidSupporter">+ <property name="leftMargin">+ <number>0</number></property>- <property name="alignment">- <set>Qt::AlignCenter</set>+ <property name="topMargin">+ <number>0</number></property>- <property name="wordWrap">- <bool>true</bool>+ <property name="rightMargin">+ <number>0</number></property>- <property name="openExternalLinks">- <bool>true</bool>+ <property name="bottomMargin">+ <number>0</number></property>- </widget>- </item>- <item>- <spacer name="horizontalSpacer_10">- <property name="orientation">- <enum>Qt::Horizontal</enum>- </property>- <property name="sizeHint" stdset="0">- <size>- <width>40</width>- <height>20</height>- </size>- </property>- </spacer>- </item>- </layout>+ <item>+ <widget class="QLabel" name="lblAndroidSupporter">+ <property name="text">+ <string>Krita is made possible thanks to ongoing support from people like you!</string>+ </property>+ <property name="alignment">+ <set>Qt::AlignCenter</set>+ </property>+ <property name="wordWrap">+ <bool>true</bool>+ </property>+ </widget>+ </item>+ <item>+ <widget class="QPushButton" name="bnAndroidSupporterManage">+ <property name="text">+ <string>Manage Supporter Benefits</string>+ </property>+ </widget>+ </item>+ </layout>+ </widget>+ </widget>+ </item>+ <item>+ <widget class="QWidget" name="wdgAndroidSupportBanner" native="true">+ <layout class="QHBoxLayout" name="lytWdgAndroidSupporterBanner" stretch="0,1,0">+ <property name="spacing">+ <number>0</number>+ </property>+ <property name="leftMargin">+ <number>0</number>+ </property>+ <property name="topMargin">+ <number>0</number>+ </property>+ <property name="rightMargin">+ <number>0</number>+ </property>+ <property name="bottomMargin">+ <number>0</number>+ </property>+ <item>+ <spacer name="spcWdgAndroidSupportBannerLeft">+ <property name="orientation">+ <enum>Qt::Horizontal</enum>+ </property>+ <property name="sizeHint" stdset="0">+ <size>+ <width>0</width>+ <height>0</height>+ </size>+ </property>+ </spacer>+ </item>+ <item>+ <widget class="QPushButton" name="bnAndroidSupport">+ <property name="cursor">+ <cursorShape>PointingHandCursor</cursorShape>+ </property>+ <property name="text">+ <string>Support Krita!</string>+ </property>+ <property name="flat">+ <bool>false</bool>+ </property>+ </widget>+ </item>+ <item>+ <spacer name="spcWdgAndroidSupportBannerRight">+ <property name="orientation">+ <enum>Qt::Horizontal</enum>+ </property>+ <property name="sizeHint" stdset="0">+ <size>+ <width>0</width>+ <height>0</height>+ </size>+ </property>+ </spacer>+ </item>+ </layout>+ </widget></item></layout></widget>diff --git a/libs/ui/kis_splash_screen.cpp b/libs/ui/kis_splash_screen.cppindex 3a5f8a2877..2bcfff5760 100644--- a/libs/ui/kis_splash_screen.cpp+++ b/libs/ui/kis_splash_screen.cpp@@ -106,19 +106,8 @@ void KisSplashScreen::updateSplashImage()const int marginTop = splashHeight * 0.05;const int marginRight = splashHeight * 0.1;- QString splashName = QStringLiteral(":/splash/0.png");- QString splashArtist = i18nc("Normal splash artist name", "Tyson Tan");- // TODO: Re-add the holiday splash...-#if 0- QDate currentDate = QDate::currentDate();- if (currentDate > QDate(currentDate.year(), 12, 4) ||- currentDate < QDate(currentDate.year(), 1, 9)) {- splashName = QStringLiteral(":/splash/1.png");- splashArtist = QStringLiteral("???");- }-#endif-- QPixmap img(splashName);+ Source source = getImageSource();+ QPixmap img(source.resourcePath);if (img.isNull() || img.height() == 0) return;@@ -152,11 +141,7 @@ void KisSplashScreen::updateSplashImage()m_loadingTextLabel->setFixedWidth(m_bannerSvg->geometry().right() - marginRight);// Place credits text on bottom right with similar margins.- if (splashArtist.isEmpty()) {- m_artCreditsLabel->setText(QString());- } else {- m_artCreditsLabel->setText(i18nc("splash image credit", "Artwork by: %1", splashArtist));- }+ m_artCreditsLabel->setText(source.artistCredit);m_artCreditsLabel->setFixedWidth(m_loadingTextLabel->width());m_artCreditsLabel->setFixedHeight(20);m_artCreditsLabel->move(m_loadingTextLabel->x(), height - marginTop - m_artCreditsLabel->height());@@ -283,6 +268,33 @@ void KisSplashScreen::setLoadingText(QString text)m_loadingTextLabel->setText(htmlText);}+KisSplashScreen::Source KisSplashScreen::getImageSource()+{+ QString artistCredit = i18nc("Normal splash artist name", "Tyson Tan");+ // Loading the ginormous 4K PNG splash image increases the startup time on+ // Android by several seconds and at the same time looks really bad when+ // scaled down to a dinky size. Instead of overengineering this into an+ // Enterprise Splash Screen Solution where we choose the image based on+ // screen size or something, we'll just use a HD JPEG instead. It's fine.+#ifdef Q_OS_ANDROID+ QString resourcePath = QStringLiteral(":/splash/hd.jpg");+#else+ QString resourcePath = QStringLiteral(":/splash/0.png");+ // TODO: Re-add the holiday splash...+#if 0+ QDate currentDate = QDate::currentDate();+ if (currentDate > QDate(currentDate.year(), 12, 4) ||+ currentDate < QDate(currentDate.year(), 1, 9)) {+ resourcePath = QStringLiteral(":/splash/1.png");+ artistCredit = QStringLiteral("???")};+ }+#endif+#endif+ if (!artistCredit.isEmpty()) {+ artistCredit = i18nc("splash image credit", "Artwork by: %1", artistCredit);+ }+ return Source{resourcePath, artistCredit};+}QString KisSplashScreen::colorString() constdiff --git a/libs/ui/kis_splash_screen.h b/libs/ui/kis_splash_screen.hindex 0786a2a12d..054db36ea7 100644--- a/libs/ui/kis_splash_screen.h+++ b/libs/ui/kis_splash_screen.h@@ -21,6 +21,11 @@ class KRITAUI_EXPORT KisSplashScreen : public QWidget, public Ui::WdgSplash{Q_OBJECTpublic:+ struct Source {+ QString resourcePath;+ QString artistCredit;+ };+explicit KisSplashScreen(bool themed = false, QWidget *parent = 0, Qt::WindowFlags f = Qt::WindowFlags());void repaint();@@ -31,6 +36,8 @@ public:void setLoadingText(QString text);+ static Source getImageSource();+private Q_SLOTS:void toggleShowAtStartup(bool toggle);diff --git a/libs/ui/widgets/KisDonationManagementWidget.cpp b/libs/ui/widgets/KisDonationManagementWidget.cppnew file mode 100644index 0000000000..4f5cfb8aed--- /dev/null+++ b/libs/ui/widgets/KisDonationManagementWidget.cpp@@ -0,0 +1,56 @@+/*+ * SPDX-License-Identifier: GPL-3.0-or-later+ */+#include "KisDonationManagementWidget.h"+#include <KisAndroidDonations.h>+#include <QPushButton>+#include <kis_assert.h>++KisDonationManagementWidget::KisDonationManagementWidget(const KisSupporterProduct &product, QWidget *parent)+ : QWidget(parent)+ , m_product(product)+{+ setupUi(this);++ if (m_product.icon.isNull()) {+ m_lblPreview->hide();+ } else {+ m_lblPreview->setPixmap(m_product.icon);+ }++ m_lblTitle->setText(QStringLiteral("<strong>%1</strong>").arg(m_product.title.toHtmlEscaped()));+ m_lblDescription->setText(m_product.description);++ if (m_product.availability == KisSupporterProductAvailability::Owned) {+ QPushButton *btnResources = new QPushButton(i18n("Download Resource Bundles"));+ m_lytDetails->addWidget(btnResources);+ connect(btnResources, &QPushButton::clicked, this, &KisDonationManagementWidget::sigShowSupporterBundles);++ if (m_product.type == KisSupporterProductType::Subscription) {+ QPushButton *btnManageSubscription = new QPushButton(i18n("Manage Subscription"));+ m_lytDetails->addWidget(btnManageSubscription);+ connect(btnManageSubscription,+ &QPushButton::clicked,+ this,+ &KisDonationManagementWidget::slotManageSubscription);+ }+ } else if (m_product.availability == KisSupporterProductAvailability::Available) {+ QPushButton *btnPurchase = new QPushButton(product.buttonText);+ m_lytDetails->addWidget(btnPurchase);+ connect(btnPurchase, &QPushButton::clicked, this, &KisDonationManagementWidget::slotPurchase);+ }+}++void KisDonationManagementWidget::slotManageSubscription()+{+ KisAndroidDonations *androidDonations = KisAndroidDonations::instance();+ KIS_SAFE_ASSERT_RECOVER_RETURN(androidDonations);+ androidDonations->slotManageSubscription(m_product.id);+}++void KisDonationManagementWidget::slotPurchase()+{+ KisAndroidDonations *androidDonations = KisAndroidDonations::instance();+ KIS_SAFE_ASSERT_RECOVER_RETURN(androidDonations);+ androidDonations->startBillingFlowFor(m_product.id, m_product.offerToken);+}diff --git a/libs/ui/widgets/KisDonationManagementWidget.h b/libs/ui/widgets/KisDonationManagementWidget.hnew file mode 100644index 0000000000..09645d18a0--- /dev/null+++ b/libs/ui/widgets/KisDonationManagementWidget.h@@ -0,0 +1,30 @@+/*+ * SPDX-License-Identifier: GPL-3.0-or-later+ */+#ifndef __KISDONATIONMANAGEMENTWIDGET_H_+#define __KISDONATIONMANAGEMENTWIDGET_H_++#include <QWidget>++#include "kritaui_export.h"+#include "ui_KisDonationManagementWidget.h"+#include <KisSupporterProduct.h>++class KisDonationManagementWidget : public QWidget, public Ui::KisDonationManagementWidget+{+ Q_OBJECT+public:+ explicit KisDonationManagementWidget(const KisSupporterProduct &product, QWidget *parent = nullptr);++Q_SIGNALS:+ void sigShowSupporterBundles();++private Q_SLOTS:+ void slotManageSubscription();+ void slotPurchase();++private:+ KisSupporterProduct m_product;+};++#endifdiff --git a/libs/ui/widgets/KisDonationManagementWidget.ui b/libs/ui/widgets/KisDonationManagementWidget.uinew file mode 100644index 0000000000..f893fa644c--- /dev/null+++ b/libs/ui/widgets/KisDonationManagementWidget.ui@@ -0,0 +1,115 @@+<?xml version="1.0" encoding="UTF-8"?>+<ui version="4.0">+ <class>KisDonationManagementWidget</class>+ <widget class="QWidget" name="KisDonationManagementWidget">+ <property name="geometry">+ <rect>+ <x>0</x>+ <y>0</y>+ <width>450</width>+ <height>148</height>+ </rect>+ </property>+ <property name="windowTitle">+ <string>Form</string>+ </property>+ <layout class="QHBoxLayout" name="m_lyt" stretch="0,1">+ <property name="spacing">+ <number>6</number>+ </property>+ <item>+ <layout class="QVBoxLayout" name="m_lytPreview">+ <property name="spacing">+ <number>0</number>+ </property>+ <item>+ <widget class="QLabel" name="m_lblPreview">+ <property name="sizePolicy">+ <sizepolicy hsizetype="Fixed" vsizetype="Fixed">+ <horstretch>0</horstretch>+ <verstretch>0</verstretch>+ </sizepolicy>+ </property>+ <property name="minimumSize">+ <size>+ <width>128</width>+ <height>128</height>+ </size>+ </property>+ <property name="maximumSize">+ <size>+ <width>128</width>+ <height>128</height>+ </size>+ </property>+ <property name="text">+ <string/>+ </property>+ <property name="scaledContents">+ <bool>true</bool>+ </property>+ <property name="alignment">+ <set>Qt::AlignHCenter|Qt::AlignTop</set>+ </property>+ </widget>+ </item>+ <item>+ <spacer name="m_spcPreview">+ <property name="orientation">+ <enum>Qt::Vertical</enum>+ </property>+ <property name="sizeHint" stdset="0">+ <size>+ <width>0</width>+ <height>0</height>+ </size>+ </property>+ </spacer>+ </item>+ </layout>+ </item>+ <item>+ <layout class="QVBoxLayout" name="m_lytDetails" stretch="0,0,0">+ <item>+ <widget class="QLabel" name="m_lblTitle">+ <property name="text">+ <string notr="true"><b>Title</b></string>+ </property>+ <property name="textFormat">+ <enum>Qt::RichText</enum>+ </property>+ </widget>+ </item>+ <item>+ <widget class="QLabel" name="m_lblDescription">+ <property name="text">+ <string notr="true">Description</string>+ </property>+ <property name="textFormat">+ <enum>Qt::RichText</enum>+ </property>+ <property name="wordWrap">+ <bool>true</bool>+ </property>+ </widget>+ </item>+ <item>+ <spacer name="m_spcDetails">+ <property name="orientation">+ <enum>Qt::Vertical</enum>+ </property>+ <property name="sizeHint" stdset="0">+ <size>+ <width>0</width>+ <height>0</height>+ </size>+ </property>+ </spacer>+ </item>+ </layout>+ </item>+ </layout>+ </widget>+ <resources/>+ <connections/>+</ui>diff --git a/packaging/android/apk/res/drawable/krita_blue_button.xml b/packaging/android/apk/res/drawable/krita_blue_button.xmlnew file mode 100644index 0000000000..dfeeb29b0a--- /dev/null+++ b/packaging/android/apk/res/drawable/krita_blue_button.xml@@ -0,0 +1,5 @@+<?xml version="1.0" encoding="utf-8"?>+<shape xmlns:android="http://schemas.android.com/apk/res/android">+ <solid android:color="#53728e" />+ <corners android:radius="4dp" />+</shape>\ No newline at end of filediff --git a/packaging/android/apk/res/drawable/krita_gray_button.xml b/packaging/android/apk/res/drawable/krita_gray_button.xmlnew file mode 100644index 0000000000..0ea7b85434--- /dev/null+++ b/packaging/android/apk/res/drawable/krita_gray_button.xml@@ -0,0 +1,5 @@+<?xml version="1.0" encoding="utf-8"?>+<shape xmlns:android="http://schemas.android.com/apk/res/android">+ <solid android:color="#424242" />+ <corners android:radius="4dp" />+</shape>\ No newline at end of filediff --git a/packaging/android/apk/res/drawable/krita_pink_button.xml b/packaging/android/apk/res/drawable/krita_pink_button.xmlnew file mode 100644index 0000000000..e719cf30f8--- /dev/null+++ b/packaging/android/apk/res/drawable/krita_pink_button.xml@@ -0,0 +1,5 @@+<?xml version="1.0" encoding="utf-8"?>+<shape xmlns:android="http://schemas.android.com/apk/res/android">+ <solid android:color="#fe4b9c" />+ <corners android:radius="4dp" />+</shape>\ No newline at end of filediff --git a/packaging/android/apk/res/drawable/product_donation.png b/packaging/android/apk/res/drawable/product_donation.pngnew file mode 100644index 0000000000..8523f26639Binary files /dev/null and b/packaging/android/apk/res/drawable/product_donation.png differdiff --git a/packaging/android/apk/res/drawable/product_fund.jpg b/packaging/android/apk/res/drawable/product_fund.jpgnew file mode 100644index 0000000000..52b1a1469cBinary files /dev/null and b/packaging/android/apk/res/drawable/product_fund.jpg differdiff --git a/packaging/android/apk/res/drawable/product_onetime.png b/packaging/android/apk/res/drawable/product_onetime.pngnew file mode 100644index 0000000000..e07767f684Binary files /dev/null and b/packaging/android/apk/res/drawable/product_onetime.png differdiff --git a/packaging/android/apk/res/drawable/product_subscription.png b/packaging/android/apk/res/drawable/product_subscription.pngnew file mode 100644index 0000000000..4565d987fcBinary files /dev/null and b/packaging/android/apk/res/drawable/product_subscription.png differdiff --git a/packaging/android/apk/res/layout/divider_layout.xml b/packaging/android/apk/res/layout/divider_layout.xmlnew file mode 100644index 0000000000..f9e100f39c--- /dev/null+++ b/packaging/android/apk/res/layout/divider_layout.xml@@ -0,0 +1,6 @@+<?xml version="1.0" encoding="utf-8"?>+<View xmlns:android="http://schemas.android.com/apk/res/android"+ android:id="@+id/topDivider"+ android:layout_width="match_parent"+ android:layout_height="1dp"+ android:background="?android:attr/listDivider" />\ No newline at end of filediff --git a/packaging/android/apk/res/layout/donation_dialog_layout.xml b/packaging/android/apk/res/layout/donation_dialog_layout.xmlnew file mode 100644index 0000000000..00b5e7c86b--- /dev/null+++ b/packaging/android/apk/res/layout/donation_dialog_layout.xml@@ -0,0 +1,156 @@+<?xml version="1.0" encoding="utf-8"?>+<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"+ android:layout_width="match_parent"+ android:layout_height="match_parent"+ android:orientation="vertical"+ android:background="#242424">++ <LinearLayout+ android:id="@+id/headerTextLayout"+ android:layout_width="match_parent"+ android:layout_height="wrap_content"+ android:orientation="horizontal"+ android:background="#242424">++ <Button+ android:id="@+id/backButton"+ android:gravity="center"+ android:layout_width="wrap_content"+ android:layout_height="match_parent"+ android:layout_weight="0"+ android:text="@string/donation_dialog_button_back"+ android:layout_margin="4dp"+ android:background="@drawable/krita_gray_button"+ android:textColor="#ffffff" />++ <TextView+ android:id="@+id/headerText"+ android:layout_width="0dp"+ android:layout_height="match_parent"+ android:layout_weight="1"+ android:gravity="center"+ android:paddingTop="8dp"+ android:paddingBottom="8dp"+ android:text="@string/donation_dialog_header_support"+ android:textAppearance="@android:style/TextAppearance.Material.Large"+ android:textColor="#ffffff" />+ </LinearLayout>++ <Button+ android:id="@+id/headerButton"+ android:layout_width="match_parent"+ android:layout_height="wrap_content"+ android:layout_margin="4dp"+ android:background="@drawable/krita_pink_button"+ android:text="@string/donation_dialog_header_button"+ android:textColor="#ffffff" />++ <View+ android:id="@+id/topDivider"+ android:layout_width="match_parent"+ android:layout_height="1dp"+ android:background="?android:attr/listDivider" />++ <FrameLayout+ android:id="@+id/splashLayout"+ android:layout_width="match_parent"+ android:layout_height="wrap_content">++ <ImageView+ android:id="@+id/splashImage"+ android:layout_width="match_parent"+ android:layout_height="wrap_content"+ android:adjustViewBounds="true"+ android:scaleType="fitCenter" />++ <TextView+ android:id="@+id/splashText"+ android:layout_width="match_parent"+ android:layout_height="match_parent"+ android:gravity="right|top"+ android:paddingTop="6dp"+ android:paddingRight="6dp"+ android:textColor="#ffffff"+ android:shadowColor="#000000"+ android:shadowDx="0"+ android:shadowDy="0"+ android:shadowRadius="4.0" />+ </FrameLayout>++ <ScrollView+ android:id="@+id/productScroll"+ android:layout_width="match_parent"+ android:layout_height="0dp"+ android:layout_weight="1"+ android:background="#242424">++ <LinearLayout+ android:id="@+id/productList"+ android:layout_width="match_parent"+ android:layout_height="wrap_content"+ android:orientation="vertical"+ android:background="#242424">++ </LinearLayout>+ </ScrollView>++ <TextView+ android:id="@+id/supporterText"+ android:layout_width="match_parent"+ android:layout_height="wrap_content"+ android:gravity="center"+ android:padding="8dp"+ android:text="@string/donation_dialog_supporter_text"+ android:textColor="#ffffff" />++ <View+ android:id="@+id/bottomDivider"+ android:layout_width="match_parent"+ android:layout_height="1dp"+ android:background="?android:attr/listDivider" />++ <ViewAnimator+ android:id="@+id/bottomViews"+ android:layout_width="match_parent"+ android:layout_height="wrap_content"+ android:background="#242424">++ <Button+ android:id="@+id/dismissButton"+ android:layout_width="match_parent"+ android:layout_height="match_parent"+ android:gravity="center"+ android:text="@string/donation_dialog_button_close"+ android:layout_margin="4dp"+ android:background="@drawable/krita_gray_button"+ android:textColor="#ffffff" />++ <LinearLayout+ android:id="@+id/loadingLayout"+ android:layout_width="match_parent"+ android:layout_height="wrap_content"+ android:orientation="horizontal"+ android:background="#242424">++ <ProgressBar+ android:id="@+id/loadingSpinner"+ style="?android:attr/progressBarStyle"+ android:layout_width="wrap_content"+ android:layout_height="wrap_content"+ android:layout_gravity="center"+ android:layout_weight="0" />++ <TextView+ android:id="@+id/loadingText"+ android:layout_width="wrap_content"+ android:layout_height="wrap_content"+ android:layout_gravity="center"+ android:layout_weight="1"+ android:gravity="center"+ android:text="@string/donation_dialog_loading"+ android:textColor="#ffffff" />++ </LinearLayout>+ </ViewAnimator>++</LinearLayout>\ No newline at end of filediff --git a/packaging/android/apk/res/layout/donation_item_layout.xml b/packaging/android/apk/res/layout/donation_item_layout.xmlnew file mode 100644index 0000000000..5e7d5bad64--- /dev/null+++ b/packaging/android/apk/res/layout/donation_item_layout.xml@@ -0,0 +1,52 @@+<?xml version="1.0" encoding="utf-8"?>+<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"+ xmlns:app="http://schemas.android.com/apk/res-auto"+ android:id="@+id/productLayout"+ style="@android:style/Theme.Material"+ android:layout_width="match_parent"+ android:layout_height="wrap_content"+ android:orientation="horizontal"+ android:padding="8dp"+ android:background="#242424">++ <ImageView+ android:id="@+id/leftImage"+ android:layout_width="100dp"+ android:layout_height="100dp"+ android:layout_gravity="center"+ android:layout_margin="8dp"+ android:scaleType="fitCenter" />++ <LinearLayout+ android:id="@+id/bodyLayout"+ android:layout_width="0dp"+ android:layout_height="wrap_content"+ android:layout_weight="1"+ android:orientation="vertical"+ android:background="#242424">++ <TextView+ android:id="@+id/productDescription"+ android:layout_width="match_parent"+ android:layout_height="wrap_content"+ android:textColor="#ffffff" />++ <Button+ android:id="@+id/productButton"+ android:layout_width="match_parent"+ android:layout_height="wrap_content"+ android:layout_margin="4dp"+ android:background="@drawable/krita_blue_button"+ android:textColor="#ffffff" />++ </LinearLayout>++ <ImageView+ android:id="@+id/rightImage"+ android:layout_width="100dp"+ android:layout_height="100dp"+ android:layout_gravity="center"+ android:layout_margin="8dp"+ android:scaleType="fitCenter" />++</LinearLayout>\ No newline at end of filediff --git a/packaging/android/apk/res/values/strings.xml b/packaging/android/apk/res/values/strings.xmlindex d20b472011..d1e1fa9675 100644--- a/packaging/android/apk/res/values/strings.xml+++ b/packaging/android/apk/res/values/strings.xml@@ -12,4 +12,25 @@<string name="cancelled">Cancelled</string><string name="save_notification_text">Saving Document</string><string name="cancel_save_notification">Cancel</string>+ <string name="donation_dialog_loading">Krita is loading…</string>+ <string name="donation_dialog_loaded">Krita is ready!</string>+ <string name="donation_dialog_button_back">Back</string>+ <string name="donation_dialog_button_close">Close</string>+ <string name="donation_dialog_header_support">Support Krita</string>+ <string name="donation_dialog_header_button">♥︎ Show Supporter Options</string>+ <string name="donation_dialog_supporter_text">Thank you for supporting Krita! Your contribution helps to keep its continued development going.</string>+ <string name="product_donations_description"><![CDATA[<h2>Donations</h2><p>Help Krita\'s continued development with a direct donation through PayPal, via credit or debit card and many other payment methods.</p>]]></string>+ <string name="product_donations_button">Donate</string>+ <string name="product_development_fund_description"><![CDATA[<h2>Development Fund</h2><p>Join Krita\'s development fund and help its continued development with a monthly contribution. Different tiers with benefits are available.</p>]]></string>+ <string name="product_development_fund_button">Join the Fund</string>+ <string name="product_button_subscribe">Subscribe</string>+ <string name="product_button_subscribe_for_month">Subscribe for %s/month</string>+ <string name="product_button_buy">Buy</string>+ <string name="product_button_buy_for">Buy for %s</string>+ <string name="product_supporter_badge_title">Supporter Badge</string>+ <string name="product_supporter_badge_description"><![CDATA[<p>A badge for early supporters of Krita on Android.</p>]]></string>+ <string name="product_subscription_title">Supporter Subscription</string>+ <string name="product_subscription_description"><![CDATA[<p>Support Krita\'s development with a monthly contribution. While subscribed, you get access to <strong>all</strong> supporter benefits as they are released. You currently receive %1$d resource bundles together containing over %2$d brushes, including the paid Digital Atelier bundle, with more planned in the future.</p>]]></string>+ <string name="product_onetime_title">Krita 5.3 Supporter Pack</string>+ <string name="product_onetime_description"><![CDATA[<p>In this pack you will receive %1$d resource bundles together containing over %2$d brushes, including the paid Digital Atelier bundle. This is a <strong>one-time purchase</strong>, you won\'t be entered into a subscription.</p>]]></string></resources>diff --git a/packaging/android/apk/res/values/styles.xml b/packaging/android/apk/res/values/styles.xmlindex 9e27558926..87f7a0b3bc 100644--- a/packaging/android/apk/res/values/styles.xml+++ b/packaging/android/apk/res/values/styles.xml@@ -1,7 +1,6 @@<?xml version="1.0" encoding="utf-8"?><resources>- <!-- TODO: use newer theme -->- <style name = "DefaultTheme" parent="android:Theme.Holo.Light">+ <style name="DefaultTheme" parent="android:Theme.Material"><item name="android:windowBackground">@android:color/black</item><!-- TODO: remove after updating to anroid-36 and uptating to Qt6 --><item name="android:windowOptOutEdgeToEdgeEnforcement">true</item>diff --git a/packaging/android/apk/src/org/krita/android/DonationDialog.java b/packaging/android/apk/src/org/krita/android/DonationDialog.javanew file mode 100644index 0000000000..9851be8154--- /dev/null+++ b/packaging/android/apk/src/org/krita/android/DonationDialog.java@@ -0,0 +1,302 @@+// SPDX-License-Identifier: GPL-3.0-or-later+package org.krita.android;++import android.app.Activity;+import android.app.AlertDialog;+import android.content.Context;+import android.content.SharedPreferences;+import android.graphics.Bitmap;+import android.graphics.drawable.Drawable;+import android.util.Log;+import android.view.View;+import android.widget.Button;+import android.widget.ImageView;+import android.widget.LinearLayout;+import android.widget.TextView;+import android.widget.ViewAnimator;++import com.android.billingclient.api.ProductDetails;++import org.krita.R;++import java.util.ArrayList;+import java.util.List;+import java.util.Objects;++public class DonationDialog {++ private static final String TAG = "krita.DonationDialog";+ private static final String PREF_LAST_TIMESTAMP = "donationdialogautotimestamp";+ private static final String PREF_LAST_SHOWN = "donationdialogautoshown";++ private static final long DAY_IN_SECONDS = 24L * 60L * 60L;+ // How many days to wait between automatically showing the support options on the splash screen.+ private static final long AUTO_SHOW_DELAY = 5L * DAY_IN_SECONDS;++ private static final int PAGE_SPLASH = 0;+ private static final int PAGE_PRODUCT_LIST = 1;+ private static final int PAGE_PURCHASE_CONFIRMATION = 2;++ private final Activity mActivity;+ private final View mView;+ private final AlertDialog mAlertDialog;+ private final boolean mSplash;+ private boolean mLoading;+ private boolean mAutoClose;+ private boolean mHaveSplashImage = false;+ private int mPage;+ private List<ProductDetails> mProductDetails = null;+ private boolean mAnyProductsOwned = false;+ private boolean mAutoShowSet = false;+ private boolean mShouldAutoShow = false;+ private boolean mFirstStartup = false;++ public DonationDialog(Activity activity, boolean splash) {+ mActivity = activity;+ mSplash = splash;+ mLoading = splash;+ mAutoClose = splash;+ mPage = splash ? PAGE_SPLASH : PAGE_PRODUCT_LIST;+ mView = activity.getLayoutInflater().inflate(R.layout.donation_dialog_layout, null);++ mAlertDialog = new AlertDialog.Builder(activity)+ .setView(mView)+ .create();++ getBackButton().setOnClickListener(v -> showSplashPage());+ getHeaderButton().setOnClickListener(v -> showProductListPage());+ getDismissButton().setOnClickListener(v -> mAlertDialog.dismiss());++ updateState();+ }++ public boolean isSplash() {+ return mSplash;+ }++ public AlertDialog getAlertDialog() {+ return mAlertDialog;+ }++ public Button getBackButton() {+ return mView.findViewById(R.id.backButton);+ }++ public Button getHeaderButton() {+ return mView.findViewById(R.id.headerButton);+ }++ public ImageView getSplashImage() {+ return mView.findViewById(R.id.splashImage);+ }++ public TextView getSplashText() {+ return mView.findViewById(R.id.splashText);+ }++ public ViewAnimator getBottomViews() {+ return mView.findViewById(R.id.bottomViews);+ }++ public Button getDismissButton() {+ return mView.findViewById(R.id.dismissButton);+ }++ public TextView getLoadingText() {+ return mView.findViewById(R.id.loadingText);+ }++ public void setLoading(boolean loading) {+ if (loading != mLoading) {+ mLoading = loading;+ updateState();+ if (!loading && mAutoClose) {+ mAlertDialog.dismiss();+ }+ }+ }++ public void showSplashPage() {+ if (mLoading && mSplash) {+ mAutoClose = true;+ mPage = PAGE_SPLASH;+ updateState();+ }+ }++ public void showProductListPage() {+ mAutoClose = false;+ mPage = PAGE_PRODUCT_LIST;+ updateState();+ }++ public void showPurchaseConfirmationPage() {+ mAutoClose = false;+ mPage = PAGE_PURCHASE_CONFIRMATION;+ updateState();+ }++ public void setLoadingText(String text) {+ getLoadingText().setText(text);+ }++ public void setSplashContents(Bitmap bitmap, String text) {+ mHaveSplashImage = bitmap != null;+ getSplashImage().setImageBitmap(bitmap);+ getSplashText().setText(text);+ updateState();+ }++ public void setProductDetails(List<ProductDetails> productDetails, boolean anyProductsOwned) {+ if (!Objects.equals(productDetails, mProductDetails) || anyProductsOwned != mAnyProductsOwned) {+ mProductDetails = productDetails;+ mAnyProductsOwned = anyProductsOwned;+ updateProducts();+ if (checkAutoShowProducts()) {+ mPage = PAGE_PRODUCT_LIST;+ mAutoClose = false;+ }+ updateState();+ }+ }++ private boolean checkAutoShowProducts() {+ if (mPage != PAGE_SPLASH) {+ Log.d(TAG, "checkAutoShowProducts: not on splash screen");+ return false;+ }++ if (mAnyProductsOwned) {+ Log.d(TAG, "checkAutoShowProducts: already owns a product");+ return false;+ }++ if (mProductDetails == null) {+ Log.d(TAG, "checkAutoShowProducts: no product details");+ return false;+ }++ if (mAutoShowSet) {+ Log.d(TAG, "checkAutoShowProducts: already set to " + mShouldAutoShow);+ return mShouldAutoShow;+ }++ SharedPreferences prefs = mActivity.getPreferences(Context.MODE_PRIVATE);+ long lastAutoShowTimestamp = prefs.getLong(PREF_LAST_TIMESTAMP, -1L);+ boolean lastShown = prefs.getBoolean(PREF_LAST_SHOWN, false);+ mFirstStartup = lastAutoShowTimestamp == -1;+ long currentTimestamp = System.currentTimeMillis() / 1000L;++ // Automatically show the supporter page on the splash screen if enough time has elapsed+ // since the last time it has shown. However, we never automatically show it on first+ // startup and also never show it two times in a row.+ mShouldAutoShow = !mFirstStartup && !lastShown && lastAutoShowTimestamp + AUTO_SHOW_DELAY <= currentTimestamp;+ mAutoShowSet = true;++ Log.d(TAG, "checkAutoShowProducts lastAutoShowTimestamp=" + lastAutoShowTimestamp+ + " lastShown=" + lastShown + " firstStartup=" + mFirstStartup+ + " currentTimestamp=" + currentTimestamp + " shouldAutoShow=" + mShouldAutoShow);++ SharedPreferences.Editor editor = prefs.edit();+ if (mFirstStartup) {+ editor.putLong(PREF_LAST_TIMESTAMP, 0L);+ } else if (mShouldAutoShow) {+ editor.putLong(PREF_LAST_TIMESTAMP, currentTimestamp);+ }+ editor.putBoolean(PREF_LAST_SHOWN, mShouldAutoShow);+ editor.apply();++ return mShouldAutoShow;+ }++ private void updateProducts() {+ List<DonationProductView> products = new ArrayList<>();+ if (mProductDetails != null) {+ for (DonationProduct donationProduct : DonationProduct.getAvailableProducts()) {+ addProduct(products, donationProduct);+ }+ }++ // If no products are available (e.g. because the user doesn't have a phone with Google+ // services on it or this is a Krita Next build), we show donation options instead.+ if (products.isEmpty()) {+ Log.d(TAG, "No products, adding fallback");+ products.addAll(DonationProductView.getFallbackProducts(mActivity));+ }++ LinearLayout productList = mView.findViewById(R.id.productList);+ productList.removeAllViews();+ for (int i = 0, count = products.size(); i < count; ++i) {+ if (i != 0) {+ productList.addView(mActivity.getLayoutInflater().inflate(R.layout.divider_layout, null));+ }+ productList.addView(products.get(i).getView());+ }+ }++ private void addProduct(List<DonationProductView> products, DonationProduct donationProduct) {+ String productId = donationProduct.getId();+ DonationOffer offer = searchOfferById(productId);+ if (offer == null) {+ Log.d(TAG, "Did not find offer for product " + productId);+ } else {+ Log.d(TAG, "Adding offer " + productId + ": " + offer);+ boolean left = products.size() % 2 == 0;+ String description = String.format(+ "<h2>%s</h2>%s", donationProduct.getTitle(), donationProduct.getDescription());+ String buttonText = offer.getButtonText();+ View.OnClickListener onClick = (View v) -> {+ DonationHelper donationHelper = DonationHelper.getInstance();+ donationHelper.startBillingFlowWith(offer.getProductDetails(), offer.getOfferToken());+ };+ Drawable icon = donationProduct.getIcon();+ products.add(new DonationProductView(+ mActivity, left ? icon : null, left ? null : icon, description,+ buttonText, onClick));+ }+ }++ private DonationOffer searchOfferById(String productId) {+ return mProductDetails.stream()+ .filter(pd -> productId.equals(pd.getProductId()))+ .findAny()+ .map(productDetails -> DonationOffer.fromProductDetails(mActivity, productDetails))+ .orElse(null);+ }++ private void updateState() {+ // Adjust which elements are visible depending on whether this+ // is the splash screen or summoned by the user. If this is+ // the splash screen, it may show or hide some elements+ // depending on if the application is still starting up or not.+ Button headerButton = getHeaderButton();+ boolean showHeaderButton = mPage == PAGE_SPLASH && mProductDetails != null+ && !mAnyProductsOwned && !mFirstStartup;+ headerButton.setEnabled(showHeaderButton);+ setViewGone(headerButton, !showHeaderButton);++ getDismissButton().setEnabled(!mLoading);+ mAlertDialog.setCancelable(!mLoading);++ setViewGone(mView.findViewById(R.id.headerTextLayout), mPage == PAGE_SPLASH);+ setViewGone(mView.findViewById(R.id.backButton), !mLoading || !mSplash);+ setViewGone(mView.findViewById(R.id.topDivider), mPage == PAGE_SPLASH);+ setViewGone(mView.findViewById(R.id.splashLayout), mPage != PAGE_SPLASH || !mHaveSplashImage);+ setViewGone(mView.findViewById(R.id.productScroll), mPage != PAGE_PRODUCT_LIST);+ setViewGone(mView.findViewById(R.id.supporterText), mPage != PAGE_PURCHASE_CONFIRMATION);++ ViewAnimator bottomViews = getBottomViews();+ int bottomDisplay = bottomViews.getDisplayedChild();+ if (mLoading && bottomDisplay != 1) {+ bottomViews.setDisplayedChild(1);+ } else if (!mLoading && bottomDisplay != 0) {+ bottomViews.setDisplayedChild(0);+ }+ }++ private static void setViewGone(View view, boolean gone) {+ if (view != null) {+ view.setVisibility(gone ? View.GONE : View.VISIBLE);+ }+ }+}diff --git a/packaging/android/apk/src/org/krita/android/DonationHelper.java b/packaging/android/apk/src/org/krita/android/DonationHelper.javaindex 1633b62f9a..dea6ae756d 100644--- a/packaging/android/apk/src/org/krita/android/DonationHelper.java+++ b/packaging/android/apk/src/org/krita/android/DonationHelper.java@@ -19,14 +19,8 @@ import com.android.billingclient.api.BillingFlowParams.ProductDetailsParams;import com.android.billingclient.api.BillingResult;import com.android.billingclient.api.PendingPurchasesParams;import com.android.billingclient.api.ProductDetails;-import com.android.billingclient.api.ProductDetailsResponseListener;import com.android.billingclient.api.Purchase;-import com.android.billingclient.api.PurchasesResponseListener;import com.android.billingclient.api.PurchasesUpdatedListener;-import com.android.billingclient.api.QueryProductDetailsParams;-import com.android.billingclient.api.QueryProductDetailsResult;-import com.android.billingclient.api.QueryPurchasesParams;-import com.android.billingclient.api.UnfetchedProduct;import org.krita.R;import org.qtproject.qt5.android.QtNative;@@ -34,31 +28,33 @@ import org.qtproject.qt5.android.QtNative;import java.util.ArrayList;import java.util.HashSet;import java.util.List;+import java.util.Map;+import java.util.Objects;+import java.util.Optional;import java.util.Set;+import java.util.function.Function;+import java.util.stream.Collectors;+import java.util.stream.Stream;// Note that for testing this stuff, your Google account needs to be added to// the "License Testers" in the Play Console and you need to test with a// "krita.org" package, not "krita.org.debug". To change the package name, edit// build.gradle and comment out the line `applicationIdSuffix ".debug"`.-@SuppressWarnings("unused")-public class DonationHelper implements PurchasesUpdatedListener, BillingClientStateListener, ProductDetailsResponseListener {+public class DonationHelper implements PurchasesUpdatedListener, BillingClientStateListener {private static final String TAG = "krita.DonationHelper";- private static final String PRODUCT_ID_LIFETIME_SUPPORTER = "thankyoukiki";- private static final List<String> ALL_PRODUCT_IDS = List.of(- PRODUCT_ID_LIFETIME_SUPPORTER);-// Keep this in sync with the enum clas State in KisAndroidDonations.h!private static final int STATE_UNKNOWN = 0;private static final int STATE_CHECKING = 1;private static final int STATE_UNAVAILABLE = 2;private static final int STATE_NOSUPPORT = 3;- private static final int STATE_LIFETIMESUPPORTER = 4;+ private static final int STATE_SUPPORTER = 4;private final BillingClient mBillingClient;private List<ProductDetails> mProductDetailsList;- private Set<String> mOwnedProductIds = new HashSet<String>();+ private final Set<String> mOwnedProductIds = new HashSet<>();+ private boolean mReady = false;private boolean mProductsQueryInProgress = false;private boolean mSync = false;@@ -66,13 +62,13 @@ public class DonationHelper implements PurchasesUpdatedListener, BillingClientStprivate DonationHelper() {mBillingClient = BillingClient.newBuilder(QtNative.getContext())- .setListener(this)- .enableAutoServiceReconnection()- .enablePendingPurchases(- PendingPurchasesParams.newBuilder()- .enableOneTimeProducts()- .build())- .build();+ .setListener(this)+ .enableAutoServiceReconnection()+ .enablePendingPurchases(+ PendingPurchasesParams.newBuilder()+ .enableOneTimeProducts()+ .build())+ .build();mBillingClient.startConnection(this);}@@ -84,6 +80,26 @@ public class DonationHelper implements PurchasesUpdatedListener, BillingClientStreturn sInstance;}+ public BillingClient getBillingClient() {+ return mBillingClient;+ }++ public synchronized boolean isReady() {+ return mReady && !mProductsQueryInProgress;+ }++ public synchronized boolean isAnyProductsOwned() {+ return !mOwnedProductIds.isEmpty();+ }++ public synchronized List<ProductDetails> getProductDetails() {+ if (mProductsQueryInProgress || mProductDetailsList == null || mProductDetailsList.isEmpty()) {+ return List.of();+ } else {+ return new ArrayList<>(mProductDetailsList);+ }+ }+@Overridepublic void onBillingSetupFinished(BillingResult billingResult) {Log.d(TAG, "Billing setup finished: " + billingResult);@@ -91,82 +107,21 @@ public class DonationHelper implements PurchasesUpdatedListener, BillingClientStrefreshPurchases();} else {Log.d(TAG, "Billing setup not successful, not refreshing purchases");+ mReady = true;sendDonationStateUpdate();}}private void refreshPurchases() {- try {- QueryPurchasesParams params = QueryPurchasesParams.newBuilder()- .setProductType(BillingClient.ProductType.INAPP)- .build();- Log.d(TAG, "Querying purchases");- mBillingClient.queryPurchasesAsync(params,- new PurchasesResponseListener() {- @Override- public void onQueryPurchasesResponse(BillingResult billingResult, List<Purchase> purchases) {- Log.d(TAG, "Badge check result: " + billingResult);- if (billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK) {- mOwnedProductIds.clear();- if (handlePurchases(purchases)) {- Log.d(TAG, "Badge purchased or pending");- } else {- Log.w(TAG, "No badge purchased");- }- }- sendDonationStateUpdate();- refreshProductDetails();- }- });- } catch (Exception e) {- Log.e(TAG, "Exception refreshing purchases", e);- sendDonationStateUpdate();- }- }-- private void refreshProductDetails() {+ mReady = false;mProductsQueryInProgress = true;- try {- List<QueryProductDetailsParams.Product> productList = new ArrayList<>();- // Querying for only owned products just produces an error, so filter those.- for (String productId : ALL_PRODUCT_IDS) {- if(mOwnedProductIds.contains(productId)) {- Log.d(TAG, "Not querying for owned product " + productId);- } else {- Log.d(TAG, "Querying for product " + productId);- productList.add(QueryProductDetailsParams.Product.newBuilder()- .setProductId(productId)- .setProductType(BillingClient.ProductType.INAPP)- .build());- }- }-- if (productList.isEmpty()) {- Log.d(TAG, "No products to query for");- mProductsQueryInProgress = false;- } else {- QueryProductDetailsParams params = QueryProductDetailsParams.newBuilder()- .setProductList(productList)- .build();- Log.d(TAG, "Query product details");- mBillingClient.queryProductDetailsAsync(params, this);- }- } catch (Exception e) {- Log.e(TAG, "Exception refreshing product details", e);- mProductsQueryInProgress = false;- }+ DonationQuery.execute(this);}- @Override- public void onProductDetailsResponse(BillingResult billingResult, QueryProductDetailsResult queryProductDetailsResult) {- Log.d(TAG, "onProductDetailsResponse: " + billingResult);+ public void handleFinishedQuery(DonationQuery query) {+ mProductDetailsList = query.getProductDetails();mProductsQueryInProgress = false;- if (billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK) {- mProductDetailsList = queryProductDetailsResult.getProductDetailsList();- Log.d(TAG, "Fetched: " + mProductDetailsList);- List<UnfetchedProduct> unfetchedProductList = queryProductDetailsResult.getUnfetchedProductList();- Log.d(TAG, "Unfetched: " + unfetchedProductList);- }+ mReady = true;sendDonationStateUpdate();}@@ -181,6 +136,7 @@ public class DonationHelper implements PurchasesUpdatedListener, BillingClientStswitch (billingResult.getResponseCode()) {case BillingClient.BillingResponseCode.OK:handlePurchases(purchases);+ MainActivity.showPurchaseConfirmation();break;case BillingClient.BillingResponseCode.ITEM_ALREADY_OWNED:refreshPurchases();@@ -194,55 +150,54 @@ public class DonationHelper implements PurchasesUpdatedListener, BillingClientSt}}- private boolean handlePurchases(List<Purchase> purchases) {- boolean handled = false;+ public void handlePurchases(List<Purchase> purchases) {if (purchases == null || purchases.isEmpty()) {Log.d(TAG, "No purchases to handle");} else {Log.d(TAG, "Handling purchases " + purchases);- for (Purchase purchase: purchases) {+ for (Purchase purchase : purchases) {try {- if (handlePurchase(purchase)) {- handled = true;- }+ handlePurchase(purchase);} catch (Exception e) {Log.e(TAG, "Error handling purchase " + purchase, e);}}}- return handled;}- private boolean handlePurchase(Purchase purchase) {- Set<String> productIds = new HashSet<String>(ALL_PRODUCT_IDS);+ private void handlePurchase(Purchase purchase) {+ Set<String> productIds = DonationProduct.getAllProductIdSet();productIds.retainAll(purchase.getProducts());- if(productIds.isEmpty()) {+ if (productIds.isEmpty()) {Log.w(TAG, "No products identified in " + purchase);- return false;+ return;}- switch(purchase.getPurchaseState()) {+ switch (purchase.getPurchaseState()) {case Purchase.PurchaseState.PURCHASED:Log.d(TAG, "Purchased " + productIds + " with " + purchase);addOwnedProductIds(productIds);acknowledgePurchase(purchase);- return true;+ break;case Purchase.PurchaseState.PENDING:// Pending means the payment is still processing and could// conceivably be declined in the future. We'll just treat this// as a successful purchase, it's not worth the extra code.Log.d(TAG, "Pending " + productIds + " with " + purchase);addOwnedProductIds(productIds);- return true;+ break;default:// Ostensibly there's only an UNSPECIFIED_STATE left.Log.d(TAG, "Unhandled " + productIds + " with " + purchase);- return false;+ break;}}private void addOwnedProductIds(Set<String> productIds) {mOwnedProductIds.addAll(productIds);+ if (mProductDetailsList != null) {+ mProductDetailsList.removeIf(productDetails -> mOwnedProductIds.contains(productDetails.getProductId()));+ }sendDonationStateUpdate();}@@ -285,28 +240,39 @@ public class DonationHelper implements PurchasesUpdatedListener, BillingClientSt}}- // Called from native code by KisAndroidDonations.- public static void startBillingFlow() {- Log.d(TAG, "startBillingFlow");- try {- getInstance().startBillingFlowInternal();- } catch (Exception e) {- Log.e(TAG, "Exception starting billing flow", e);- showToast(R.string.something_wrong);+ @SuppressWarnings("unused")+ public static boolean isProductOwned(String productId) {+ DonationHelper donationHelper = getInstance();+ synchronized (donationHelper) {+ return donationHelper.mOwnedProductIds.contains(productId);+ }+ }++ @SuppressWarnings("unused")+ public static void startBillingFlowForProductId(String productId, String offerToken) {+ DonationHelper donationHelper = getInstance();+ ProductDetails productDetails;+ synchronized (donationHelper) {+ productDetails = Optional.ofNullable(donationHelper.mProductDetailsList)+ .map(List::stream)+ .orElseGet(Stream::empty)+ .filter((ProductDetails pd) -> Objects.equals(pd.getProductId(), productId))+ .findFirst()+ .orElse(null);}+ donationHelper.startBillingFlowWith(productDetails, offerToken);}- private void startBillingFlowInternal() {- if (anyProductsAvailable()) {- List<ProductDetailsParams> productDetailsParamsList = new ArrayList<>();- for (ProductDetails details : mProductDetailsList) {- productDetailsParamsList.add(ProductDetailsParams.newBuilder()- .setProductDetails(details)- .build());+ public void startBillingFlowWith(ProductDetails productDetails, String offerToken) {+ if (anyProductsAvailable() && productDetails != null) {+ ProductDetailsParams.Builder builder = ProductDetailsParams.newBuilder()+ .setProductDetails(productDetails);+ if (offerToken != null && !offerToken.isEmpty()) {+ builder.setOfferToken(offerToken);}BillingFlowParams params = BillingFlowParams.newBuilder()- .setProductDetailsParamsList(productDetailsParamsList)+ .setProductDetailsParamsList(List.of(builder.build())).build();Log.d(TAG, "Launch billing flow");@@ -317,10 +283,11 @@ public class DonationHelper implements PurchasesUpdatedListener, BillingClientSt}}- boolean anyProductsAvailable() {+ public boolean anyProductsAvailable() {if (mProductDetailsList != null) {+ Set<String> allProductIds = DonationProduct.getAllProductIdSet();for (ProductDetails productDetails : mProductDetailsList) {- if (ALL_PRODUCT_IDS.contains(productDetails.getProductId())) {+ if (allProductIds.contains(productDetails.getProductId())) {return true;}}@@ -329,23 +296,43 @@ public class DonationHelper implements PurchasesUpdatedListener, BillingClientSt}private static void showToast(final int resourceId) {- try{- QtNative.activity().runOnUiThread(new Runnable() {- @Override- public void run() {- try {- Toast.makeText(QtNative.getContext(), resourceId, Toast.LENGTH_LONG).show();- } catch (Exception|UnsatisfiedLinkError e) {- Log.e(TAG, "Exception showing toast with resource id " + resourceId, e);- }+ try {+ QtNative.activity().runOnUiThread(() -> {+ try {+ Toast.makeText(QtNative.getContext(), resourceId, Toast.LENGTH_LONG).show();+ } catch (Exception | UnsatisfiedLinkError e) {+ Log.e(TAG, "Exception showing toast with resource id " + resourceId, e);}});- } catch (Exception|UnsatisfiedLinkError e) {+ } catch (Exception | UnsatisfiedLinkError e) {Log.e(TAG, "Exception dispatching toast with resource id " + resourceId, e);}}- // Called from native code by KisAndroidDonations.+ @SuppressWarnings("unused")+ public static List<KisSupporterProduct> getCurrentProducts() {+ return getInstance().getCurrentProductsInternal();+ }++ private synchronized List<KisSupporterProduct> getCurrentProductsInternal() {+ if (isReady()) {+ return DonationProduct.getKisSupporterProducts(+ QtNative.activity(), getAvailableProductsById(), mOwnedProductIds);+ } else {+ return List.of();+ }+ }++ private Map<String, ProductDetails> getAvailableProductsById() {+ if (mProductDetailsList == null) {+ return Map.of();+ } else {+ return mProductDetailsList.stream()+ .collect(Collectors.toMap(ProductDetails::getProductId, Function.identity()));+ }+ }++ @SuppressWarnings("unused")public static void syncState() {Log.d(TAG, "syncState");getInstance().syncStateInternal();@@ -368,20 +355,22 @@ public class DonationHelper implements PurchasesUpdatedListener, BillingClientStprivate synchronized void sendDonationStateUpdate() {int state = getState();if (mSync) {- Log.d(TAG, "Sending donation state " + state);+ long flags = DonationProduct.getOwnedProductFlags(mOwnedProductIds);+ Log.d(TAG, "Sending donation state " + state + " flags " + flags);try {- JNIWrappers.donationStateUpdated(state);- } catch (Exception|UnsatisfiedLinkError e) {- Log.e(TAG, "Exception sending donation state update with state " + state, e);+ JNIWrappers.donationStateUpdated(state, flags);+ } catch (Exception | UnsatisfiedLinkError e) {+ Log.e(TAG, "Exception sending donation state update with state " + state + " flags " + flags, e);}} else {Log.d(TAG, "Not synchronized, not sending donation state " + state);}+ MainActivity.updateDonationDialogProducts();}private int getState() {- if (mOwnedProductIds.contains(PRODUCT_ID_LIFETIME_SUPPORTER)) {- return STATE_LIFETIMESUPPORTER;+ if (isAnyProductsOwned()) {+ return STATE_SUPPORTER;} else if (anyProductsAvailable()) {return STATE_NOSUPPORT;} else if (mProductsQueryInProgress) {diff --git a/packaging/android/apk/src/org/krita/android/DonationOffer.java b/packaging/android/apk/src/org/krita/android/DonationOffer.javanew file mode 100644index 0000000000..f9d4598a8a--- /dev/null+++ b/packaging/android/apk/src/org/krita/android/DonationOffer.java@@ -0,0 +1,164 @@+// SPDX-License-Identifier: GPL-3.0-or-later+package org.krita.android;++import android.app.Activity;+import android.util.Log;++import com.android.billingclient.api.BillingClient;+import com.android.billingclient.api.ProductDetails;++import org.krita.R;++import java.util.Collection;+import java.util.Collections;+import java.util.Comparator;+import java.util.List;+import java.util.Objects;+import java.util.Optional;+import java.util.regex.Matcher;+import java.util.regex.Pattern;+import java.util.stream.Stream;++public final class DonationOffer {+ private static final String TAG = "krita.DonationOffer";+ private static final Pattern PRIORITY_TAG_PATTERN = Pattern.compile("\\Ap(-?[0-9]+)\\z");++ private final ProductDetails mProductDetails;+ private final String mOfferToken;+ private final String mButtonText;++ private DonationOffer(ProductDetails productDetails, String offerToken, String buttonText) {+ this.mProductDetails = productDetails;+ this.mOfferToken = offerToken;+ this.mButtonText = buttonText;+ }++ @Override+ public String toString() {+ return "DonationOffer{" ++ "mProductDetails=" + mProductDetails ++ ", mOfferToken='" + mOfferToken + '\'' ++ ", mButtonText='" + mButtonText + '\'' ++ '}';+ }++ public ProductDetails getProductDetails() {+ return mProductDetails;+ }++ public String getOfferToken() {+ return mOfferToken;+ }++ public String getButtonText() {+ return mButtonText;+ }++ public static DonationOffer fromProductDetails(Activity activity, ProductDetails productDetails) {+ if (productDetails == null) {+ return null;+ }++ if (BillingClient.ProductType.SUBS.equals(productDetails.getProductType())) {+ ProductDetails.SubscriptionOfferDetails offerDetails = Optional.ofNullable(productDetails.getSubscriptionOfferDetails())+ .map(Collection::stream)+ .orElseGet(Stream::empty)+ .min(Comparator.comparing(DonationOffer::getSubscriptionOfferPriority))+ .orElse(null);+ if (offerDetails == null) {+ Log.d(TAG, "No available offers for subscription product " + productDetails);+ return null;+ } else {+ Log.d(TAG, "Using subscription offer " + offerDetails);+ return new DonationOffer(+ productDetails, offerDetails.getOfferToken(),+ formatSubscriptionButtonText(activity, offerDetails));+ }+ } else {+ ProductDetails.OneTimePurchaseOfferDetails offerDetails = Optional.ofNullable(productDetails.getOneTimePurchaseOfferDetailsList())+ .map(Collection::stream)+ .orElseGet(Stream::empty)+ .filter(Objects::nonNull)+ .min(Comparator.comparing(DonationOffer::getOneTimePurchaseOfferPriority))+ .orElse(null);+ if (offerDetails == null) {+ Log.d(TAG, "No available offers for one-time product " + productDetails);+ return null;+ } else {+ Log.d(TAG, "Using subscription offer " + offerDetails);+ return new DonationOffer(+ productDetails, offerDetails.getOfferToken(),+ formatOneTimeButtonText(activity, offerDetails));+ }+ }+ }++ private static int getOneTimePurchaseOfferPriority(ProductDetails.OneTimePurchaseOfferDetails details) {+ return getOfferPriority(details.getOfferTags());+ }++ private static int getSubscriptionOfferPriority(ProductDetails.SubscriptionOfferDetails details) {+ return getOfferPriority(details.getOfferTags());+ }++ private static int getOfferPriority(List<String> offerTags) {+ // There's a litany of options you can set on products, with multiple plans, special offers+ // and all sorts of guff. We don't currently intend to use any of that, but we gotta pick a+ // single offer out of the list *somehow*. So it does this by checking the offer tags (which+ // can be configured in the Play Console), which is just a p followed by a number, which can+ // be negative. The offer with the lowest number wins, default priority is 1000.+ return Optional.of(offerTags)+ .orElseGet(Collections::emptyList)+ .stream()+ .map(PRIORITY_TAG_PATTERN::matcher)+ .filter(Matcher::find)+ .map(DonationOffer::parsePriorityTagMatch)+ .filter(Objects::nonNull)+ .sorted()+ .findFirst()+ .orElse(1000);+ }++ private static String formatOneTimeButtonText(+ Activity activity, ProductDetails.OneTimePurchaseOfferDetails offerDetails) {+ // Doesn't currently handle any discounts or anything, just shows the price.+ String price = offerDetails.getFormattedPrice().trim();+ if(!price.isEmpty()) {+ return activity.getString(R.string.product_button_buy_for, price);+ }+ // Fallback, just say "buy" with no pricing information.+ return activity.getString(R.string.product_button_buy);+ }++ private static String formatSubscriptionButtonText(+ Activity activity, ProductDetails.SubscriptionOfferDetails offerDetails) {+ // We currently only intend to have monthly subscriptions, so the code is only set up to say+ // "subscribe for price/month" on the button. It can't deal with multiple phases or other+ // cadences, so this code weeds those out so that the button just says "subscribe" instead.+ List<ProductDetails.PricingPhase> pricingPhases = offerDetails.getPricingPhases().getPricingPhaseList();+ if (pricingPhases.size() == 1) {+ ProductDetails.PricingPhase onlyPhase = pricingPhases.get(0);+ // Billing periods are in ISO8601 duration format, P1M is one month.+ if ("P1M".equals(onlyPhase.getBillingPeriod())) {+ String price = onlyPhase.getFormattedPrice().trim();+ if(!price.isEmpty()) {+ return activity.getString(R.string.product_button_subscribe_for_month, price);+ }+ }+ }+ // Fallback, just say "subscribe" with no pricing information.+ return activity.getString(R.string.product_button_subscribe);+ }++ private static Integer parsePriorityTagMatch(Matcher matcher) {+ String capture = matcher.group(1);+ if (capture != null) {+ try {+ return Integer.parseInt(capture, 10);+ } catch (NumberFormatException e) {+ Log.w(TAG, "Failed to parse tag priority", e);+ }+ }+ return null;+ }+}diff --git a/packaging/android/apk/src/org/krita/android/DonationProduct.java b/packaging/android/apk/src/org/krita/android/DonationProduct.javanew file mode 100644index 0000000000..ffe17c792e--- /dev/null+++ b/packaging/android/apk/src/org/krita/android/DonationProduct.java@@ -0,0 +1,190 @@+// SPDX-License-Identifier: GPL-3.0-or-later+package org.krita.android;++import android.app.Activity;+import android.graphics.drawable.Drawable;+import android.util.Log;++import com.android.billingclient.api.ProductDetails;++import org.krita.R;++import java.util.List;+import java.util.Map;+import java.util.Set;+import java.util.function.Predicate;+import java.util.stream.Collectors;++public final class DonationProduct {+ private static final String TAG = "krita.DonationProduct";++ private static List<DonationProduct> allProducts = null;++ private final long mFlag;+ private final String mId;+ private final String mTitle;+ private final String mDescription;+ private final Drawable mIcon;+ private final boolean mSubscription;+ private final boolean mAvailable;++ private DonationProduct(long flag, String id, String title, String description, Drawable icon, boolean subscription, boolean available) {+ mFlag = flag;+ mId = id;+ mTitle = title;+ mDescription = description;+ mIcon = icon;+ mSubscription = subscription;+ mAvailable = available;+ }++ public long getFlag() {+ return mFlag;+ }++ public String getId() {+ return mId;+ }++ public String getTitle() {+ return mTitle;+ }++ public String getDescription() {+ return mDescription;+ }++ public Drawable getIcon() {+ return mIcon;+ }++ public boolean isSubscription() {+ return mSubscription;+ }++ public boolean isAvailable() {+ return mAvailable;+ }++ public static void initAllProducts(Activity activity) {+ if (allProducts == null) {+ allProducts = List.of(+ new DonationProduct(+ 1L << 1L,+ "kritasupportersubscription1",+ activity.getString(R.string.product_subscription_title),+ activity.getString(R.string.product_subscription_description, 8, 150),+ activity.getDrawable(R.drawable.product_subscription),+ true,+ true),+ new DonationProduct(+ 1L << 2L,+ "krita5x3x0supporterbundle",+ activity.getString(R.string.product_onetime_title),+ activity.getString(R.string.product_onetime_description, 8, 150),+ activity.getDrawable(R.drawable.product_onetime),+ false,+ true),+ new DonationProduct(+ 1L,+ "thankyoukiki",+ activity.getString(R.string.product_supporter_badge_title),+ activity.getString(R.string.product_supporter_badge_description),+ null,+ false,+ false));+ }+ }++ public static long getOwnedProductFlags(Set<String> ownedProductIds) {+ return allProducts.stream()+ .filter((DonationProduct dp) -> ownedProductIds.contains(dp.getId()))+ .map(DonationProduct::getFlag)+ .reduce(0L, (Long a, Long b) -> a | b);+ }++ public static List<DonationProduct> getAvailableProducts() {+ return allProducts.stream()+ .filter(DonationProduct::isAvailable)+ .collect(Collectors.toList());+ }++ public static Set<String> getAllProductIdSet() {+ return allProducts.stream()+ .map(DonationProduct::getId)+ .collect(Collectors.toSet());+ }++ public static List<String> getAvailableOneTimeProductIds() {+ return allProducts.stream()+ .filter(DonationProduct::isAvailable)+ .filter(Predicate.not(DonationProduct::isSubscription))+ .map(DonationProduct::getId)+ .collect(Collectors.toList());+ }++ public static List<String> getAvailableSubscriptionProductIds() {+ return allProducts.stream()+ .filter(DonationProduct::isAvailable)+ .filter(DonationProduct::isSubscription)+ .map(DonationProduct::getId)+ .collect(Collectors.toList());+ }++ public static List<KisSupporterProduct> getKisSupporterProducts(+ Activity activity, Map<String, ProductDetails> availableProductDetailsById, Set<String> ownedProductIds) {+ return allProducts.stream()+ .map((DonationProduct p) -> {+ String buttonText = null;+ String offerToken = null;++ int availability = p.getKisSupporterProductAvailability(availableProductDetailsById, ownedProductIds);+ if (availability == KisSupporterProduct.AVAILABILITY_AVAILABLE) {+ DonationOffer offer;+ try {+ offer = DonationOffer.fromProductDetails(activity, availableProductDetailsById.get(p.getId()));+ } catch (Exception e) {+ Log.w(TAG, "Exception retrieving offer for " + p.getId(), e);+ offer = null;+ }++ if (offer == null) {+ Log.w(TAG, "No offer for available product " + p.getId());+ availability = KisSupporterProduct.AVAILABILITY_MISSING;+ } else {+ buttonText = offer.getButtonText();+ offerToken = offer.getOfferToken();+ }+ }++ return new KisSupporterProduct(+ p.getKisSupporterProductType(),+ availability,+ p.getId(),+ p.getTitle(),+ p.getDescription(),+ p.getIcon(),+ buttonText,+ offerToken);+ })+ .collect(Collectors.toList());+ }++ private int getKisSupporterProductType() {+ if (mSubscription) {+ return KisSupporterProduct.TYPE_SUBSCRIPTION;+ } else {+ return KisSupporterProduct.TYPE_ONE_TIME;+ }+ }++ private int getKisSupporterProductAvailability(Map<String, ProductDetails> availableProductsById, Set<String> ownedProductIds) {+ if (ownedProductIds != null && ownedProductIds.contains(mId)) {+ return KisSupporterProduct.AVAILABILITY_OWNED;+ } else if (mAvailable && availableProductsById.containsKey(mId)) {+ return KisSupporterProduct.AVAILABILITY_AVAILABLE;+ } else {+ return KisSupporterProduct.AVAILABILITY_MISSING;+ }+ }+}diff --git a/packaging/android/apk/src/org/krita/android/DonationProductView.java b/packaging/android/apk/src/org/krita/android/DonationProductView.javanew file mode 100644index 0000000000..9bc2e5ed42--- /dev/null+++ b/packaging/android/apk/src/org/krita/android/DonationProductView.java@@ -0,0 +1,107 @@+// SPDX-License-Identifier: GPL-3.0-or-later+package org.krita.android;++import android.app.Activity;+import android.content.Intent;+import android.graphics.drawable.BitmapDrawable;+import android.graphics.drawable.Drawable;+import android.net.Uri;+import android.text.Html;+import android.util.Log;+import android.view.View;+import android.widget.Button;+import android.widget.ImageView;+import android.widget.LinearLayout;+import android.widget.TextView;++import org.krita.R;++import java.util.List;+import java.util.Locale;++public class DonationProductView {+ private static final String TAG = "krita.DonationProduct";++ View mView;++ public DonationProductView(Activity activity, Drawable leftImageDrawable,+ Drawable rightImageDrawable, String description, String buttonText,+ View.OnClickListener onButtonClick) {+ mView = activity.getLayoutInflater().inflate(R.layout.donation_item_layout, null);++ LinearLayout productLayout = mView.findViewById(R.id.productLayout);++ ImageView leftImage = mView.findViewById(R.id.leftImage);+ if (leftImageDrawable == null) {+ productLayout.removeView(leftImage);+ } else {+ leftImage.setImageDrawable(makeSmoothDrawable(leftImageDrawable));+ leftImage.setOnClickListener(onButtonClick);+ }++ ImageView rightImage = mView.findViewById(R.id.rightImage);+ if (rightImageDrawable == null) {+ productLayout.removeView(rightImage);+ } else {+ rightImage.setImageDrawable(makeSmoothDrawable(rightImageDrawable));+ rightImage.setOnClickListener(onButtonClick);+ }++ TextView productDescription = mView.findViewById(R.id.productDescription);+ productDescription.setText(Html.fromHtml(description, Html.FROM_HTML_MODE_COMPACT));++ Button productButton = mView.findViewById(R.id.productButton);+ productButton.setText(buttonText);+ productButton.setOnClickListener(onButtonClick);+ }++ public View getView() {+ return mView;+ }++ public static List<DonationProductView> getFallbackProducts(Activity activity) {+ String lang = Locale.getDefault().toLanguageTag();+ return List.of(+ new DonationProductView(+ activity,+ activity.getDrawable(R.drawable.product_fund),+ null,+ activity.getString(R.string.product_development_fund_description),+ activity.getString(R.string.product_development_fund_button),+ openLinkOnClick(activity, "https://fund.krita.org/?lang=" + lang)),+ new DonationProductView(+ activity,+ null,+ activity.getDrawable(R.drawable.product_donation),+ activity.getString(R.string.product_donations_description),+ activity.getString(R.string.product_donations_button),+ openLinkOnClick(activity, "https://krita.org/en/donations?lang=" + lang)));+ }++ private static View.OnClickListener openLinkOnClick(Activity activity, String link) {+ Uri uri = Uri.parse(link);+ return (View view) -> {+ try {+ Log.d(TAG, "Opening link " + link);+ Intent intent = new Intent(Intent.ACTION_VIEW, uri);+ activity.startActivity(intent);+ } catch (Exception e) {+ Log.e(TAG, "Exception opening link " + link, e);+ }+ };+ }++ private static Drawable makeSmoothDrawable(Drawable drawable) {+ if (drawable instanceof BitmapDrawable) {+ try {+ BitmapDrawable bd = (BitmapDrawable) drawable.mutate();+ bd.setAntiAlias(true);+ bd.setFilterBitmap(true);+ return bd;+ } catch (Exception e) {+ Log.e(TAG, "Exception mutating drawable", e);+ }+ }+ return drawable;+ }+}diff --git a/packaging/android/apk/src/org/krita/android/DonationQuery.java b/packaging/android/apk/src/org/krita/android/DonationQuery.javanew file mode 100644index 0000000000..a804daa0eb--- /dev/null+++ b/packaging/android/apk/src/org/krita/android/DonationQuery.java@@ -0,0 +1,146 @@+// SPDX-License-Identifier: GPL-3.0-or-later+package org.krita.android;++import android.util.Log;++import com.android.billingclient.api.BillingClient;+import com.android.billingclient.api.ProductDetails;+import com.android.billingclient.api.Purchase;+import com.android.billingclient.api.QueryProductDetailsParams;+import com.android.billingclient.api.QueryPurchasesParams;++import java.util.ArrayList;+import java.util.HashSet;+import java.util.List;+import java.util.Set;++// Wrapper around the awful interface of the Android billing client. Some undocumented issues:+// * You can't query both one-time and subscription products in one query, it errors.+// * Querying for details about products that the user already owns also errors.+// * Can't query for subscriptions that contain dashes in their IDs, raises invalid ID errors.+// * Can't query for subscriptions that contain underscores in their IDs, just doesn't return them.+//+// Also, this class does all of its queries sequentially. That is intentional, I don't trust the+// billing client to actually be capable of performing two queries at once, considering the numerous+// undocumented failure modes it has. It's fine this way.+public class DonationQuery {++ private static final String TAG = "krita.DonationQuery";++ private final DonationHelper mDonationHelper;+ private final Set<String> mOwnedProductIds = new HashSet<>();+ private final List<ProductDetails> mProductDetails = new ArrayList<>();++ private DonationQuery(DonationHelper donationHelper) {+ mDonationHelper = donationHelper;+ }++ public List<ProductDetails> getProductDetails() {+ return mProductDetails;+ }++ public static void execute(DonationHelper donationHelper) {+ DonationQuery donationQuery = new DonationQuery(donationHelper);+ donationQuery.step1QueryOwnedOneTimeProducts();+ }++ // Part 1: Query for products the user has purchased. We must always do this because inquiring+ // about products that the user already owns raises an (undocumented) error. We also have to do+ // this in two queries, because the API doesn't allow both one-time products and subscriptions.++ private void step1QueryOwnedOneTimeProducts() {+ queryOwnedProducts(BillingClient.ProductType.INAPP, this::step2QueryOwnedSubscriptionProducts);+ }++ private void step2QueryOwnedSubscriptionProducts() {+ queryOwnedProducts(BillingClient.ProductType.SUBS, this::step3QueryOneTimeProductDetails);+ }++ private void queryOwnedProducts(String productType, Runnable next) {+ try {+ QueryPurchasesParams params = QueryPurchasesParams.newBuilder()+ .setProductType(productType)+ .build();+ Log.d(TAG, "Querying " + productType + " purchases");+ mDonationHelper.getBillingClient().queryPurchasesAsync(params, (billingResult, purchases) -> {+ Log.d(TAG, "Purchase query " + productType + " result: " + billingResult);+ if (billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK) {+ handlePurchases(purchases);+ }+ next.run();+ });+ } catch (Exception e) {+ Log.e(TAG, "Exception querying " + productType + " purchases", e);+ next.run();+ }+ }++ private void handlePurchases(List<Purchase> purchases) {+ mDonationHelper.handlePurchases(purchases);+ for (Purchase purchase : purchases) {+ mOwnedProductIds.addAll(purchase.getProducts());+ }+ }++ // Part 2: Query information about available products, avoiding the forbidden query of+ // already-owned ones. Even though the API seems to allow it, attempting to query both one-time+ // and subscription product raises an (undocumented) error.++ private void step3QueryOneTimeProductDetails() {+ queryProductDetails(+ BillingClient.ProductType.INAPP, DonationProduct.getAvailableOneTimeProductIds(),+ this::step4QuerySubscriptionProductDetails);+ }++ private void step4QuerySubscriptionProductDetails() {+ queryProductDetails(+ BillingClient.ProductType.SUBS, DonationProduct.getAvailableSubscriptionProductIds(),+ this::step5Finish);+ }++ private void queryProductDetails(String productType, List<String> productIds, Runnable next) {+ try {+ List<QueryProductDetailsParams.Product> productList = new ArrayList<>();+ for (String productId : productIds) {+ if (mOwnedProductIds.contains(productId)) {+ Log.d(TAG, "Not querying for owned " + productType + " product " + productId);+ } else {+ Log.d(TAG, "Querying for " + productType + " product " + productId);+ productList.add(QueryProductDetailsParams.Product.newBuilder()+ .setProductId(productId)+ .setProductType(productType)+ .build());+ }+ }++ if (productList.isEmpty()) {+ Log.d(TAG, "No " + productType + "products to query for");+ next.run();+ } else {+ QueryProductDetailsParams params = QueryProductDetailsParams.newBuilder()+ .setProductList(productList)+ .build();+ Log.d(TAG, "Querying " + productType + " product details");+ mDonationHelper.getBillingClient().queryProductDetailsAsync(params, (billingResult, queryProductDetailsResult) -> {+ Log.d(TAG, "Query " + productType + " product details result: " + billingResult);+ if (billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK) {+ List<ProductDetails> productDetails = queryProductDetailsResult.getProductDetailsList();+ mProductDetails.addAll(productDetails);+ Log.d(TAG, "Fetched " + productType + " products: " + productDetails);+ Log.d(TAG, "Unfetched " + productType + " products: " + queryProductDetailsResult.getUnfetchedProductList());+ }+ next.run();+ });+ }+ } catch (Exception e) {+ Log.e(TAG, "Exception querying " + productType + " product details", e);+ next.run();+ }+ }++ // Part 3: Report back.++ private void step5Finish() {+ mDonationHelper.handleFinishedQuery(this);+ }+}diff --git a/packaging/android/apk/src/org/krita/android/JNIWrappers.java b/packaging/android/apk/src/org/krita/android/JNIWrappers.javaindex 9ede96961e..b83a32e53c 100644--- a/packaging/android/apk/src/org/krita/android/JNIWrappers.java+++ b/packaging/android/apk/src/org/krita/android/JNIWrappers.java@@ -10,7 +10,8 @@ package org.krita.android;class JNIWrappers {public static native void saveState();public static native boolean hasMainWindowLoaded();- public static native void donationStateUpdated(int state);+ public static native void donationStateUpdated(int state, long ownedProductFlags);public static native void openFileFromIntent(String uri);+ public static native void showDonationManagementDialog();}diff --git a/packaging/android/apk/src/org/krita/android/KisSupporterProduct.java b/packaging/android/apk/src/org/krita/android/KisSupporterProduct.javanew file mode 100644index 0000000000..de2d21c877--- /dev/null+++ b/packaging/android/apk/src/org/krita/android/KisSupporterProduct.java@@ -0,0 +1,85 @@+// SPDX-License-Identifier: GPL-3.0-or-later+package org.krita.android;++import android.graphics.Bitmap;+import android.graphics.Canvas;+import android.graphics.drawable.Drawable;+import android.util.Log;++// Keep in sync with KisSupporterProduct.h!+public final class KisSupporterProduct {+ private static final String TAG = "krita.KisSupporterProduct";++ public static final int TYPE_ONE_TIME = 0;+ public static final int TYPE_SUBSCRIPTION = 1;+ public static final int AVAILABILITY_MISSING = 0;+ public static final int AVAILABILITY_AVAILABLE = 1;+ public static final int AVAILABILITY_OWNED = 2;++ private final int mType;+ private final int mAvailability;+ private final String mId;+ private final String mTitle;+ private final String mDescription;+ private final Drawable mIcon;+ private final String mButtonText;+ private final String mOfferToken;++ public KisSupporterProduct(+ int type, int availability, String id, String title, String description, Drawable icon,+ String buttonText, String offerToken) {+ mType = type;+ mAvailability = availability;+ mId = id;+ mTitle = title;+ mDescription = description;+ mIcon = icon;+ mButtonText = buttonText;+ mOfferToken = offerToken;+ }++ public int getType() {+ return mType;+ }++ public int getAvailability() {+ return mAvailability;+ }++ public String getId() {+ return mId;+ }++ public String getTitle() {+ return mTitle;+ }++ public String getDescription() {+ return mDescription;+ }++ public int[] getIconPixels(int width, int height) {+ if (width > 0 && height > 0 && mIcon != null) {+ try {+ Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);+ Canvas canvas = new Canvas(bitmap);+ mIcon.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());+ mIcon.draw(canvas);+ int[] pixels = new int[width * height];+ bitmap.getPixels(pixels, 0, width, 0, 0, width, height);+ return pixels;+ } catch (Exception e) {+ Log.w(TAG, "Exception getting icon pixels", e);+ }+ }+ return null;+ }++ public String getButtonText() {+ return mButtonText;+ }++ public String getOfferToken() {+ return mOfferToken;+ }+}diff --git a/packaging/android/apk/src/org/krita/android/MainActivity.java b/packaging/android/apk/src/org/krita/android/MainActivity.javaindex cd45bd7a9b..d3d9af21d2 100644--- a/packaging/android/apk/src/org/krita/android/MainActivity.java+++ b/packaging/android/apk/src/org/krita/android/MainActivity.java@@ -7,11 +7,16 @@package org.krita.android;+import android.annotation.SuppressLint;+import android.app.Activity;import android.app.ActivityManager;+import android.app.AlertDialog;import android.app.ApplicationExitInfo;import android.app.ForegroundServiceStartNotAllowedException;import android.app.ServiceStartNotAllowedException;import android.content.Intent;+import android.graphics.Bitmap;+import android.graphics.BitmapFactory;import android.net.Uri;import android.os.Build;import android.os.Bundle;@@ -20,25 +25,31 @@ import android.view.InputDevice;import android.view.KeyEvent;import android.view.MotionEvent;import android.view.ViewConfiguration;+import android.widget.Toast;import androidx.annotation.RequiresApi;import java.util.List;+import org.krita.R;+import org.libsdl.app.SDLAudioManager;import org.qtproject.qt5.android.QtNative;-import org.qtproject.qt5.android.QtInputEventDispatcher;import org.qtproject.qt5.android.bindings.QtActivity;-import org.libsdl.app.SDLAudioManager;+import java.util.function.BiConsumer;+import java.util.function.Consumer;public class MainActivity extends QtActivity {private static final String TAG = "krita.MainActivity";-+ private static boolean applicationLoaded = false;+ private static String applicationLoadingText = "";private boolean haveLibsLoaded = false;private boolean serviceStarted = false;+ private DonationDialog mDonationDialog = null;@Override+ @SuppressLint("MissingSuperCall")public void onCreate(Bundle savedInstanceState) {super.QT_ANDROID_DEFAULT_THEME = "DefaultTheme";@@ -60,6 +71,7 @@ public class MainActivity extends QtActivity {haveLibsLoaded = true;DonationHelper.getInstance();+ DonationProduct.initAllProducts(this);}@Override@@ -237,4 +249,204 @@ public class MainActivity extends QtActivity {}return false;}++ @SuppressWarnings("unused")+ public static void manageSubscriptions() {+ manageSubscription(null);+ }++ @SuppressWarnings("unused")+ public static void manageSubscription(String productId) {+ doWithMainActivity((MainActivity activity) -> {+ activity.runOnUiThread(() -> {+ try {+ String packageName = activity.getApplicationContext().getPackageName();+ String uri = "https://play.google.com/store/account/subscriptions?package=" + Uri.encode(packageName)+ + (productId == null ? "" : "&sku=" + Uri.encode(productId));+ activity.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(uri)));+ } catch (Exception e) {+ Log.e(TAG, "Failed to open subscription management", e);+ Toast.makeText(QtNative.getContext(), R.string.something_wrong, Toast.LENGTH_LONG).show();+ }+ });+ });+ }++ @SuppressWarnings("unused")+ public static void showDonationDialog(boolean splash, byte[] splashBytes, String splashArtist, String splashVersion) {+ Log.d(TAG, "showDonationDialog");+ try {+ Activity activity = QtNative.activity();+ if (activity instanceof MainActivity) {+ ((MainActivity) activity).showDonationDialogInternal(splash, splashBytes, splashArtist, splashVersion);+ } else {+ Log.e(TAG, "showDonationDialog: QtNative.activity() is not a Krita MainActivity");+ }+ } catch (Exception e) {+ Log.e(TAG, "Exception dispatching donation dialog", e);+ }+ }++ private void showDonationDialogInternal(boolean splash, byte[] splashBytes, String splashArtist, String splashVersion) {+ QtNative.activity().runOnUiThread(() -> {+ if (mDonationDialog == null) {+ try {+ mDonationDialog = new DonationDialog(MainActivity.this, splash);+ updateDonationDialog();+ AlertDialog alertDialog = mDonationDialog.getAlertDialog();+ alertDialog.setOnDismissListener(dialogInterface -> {+ if (mDonationDialog != null) {+ if (dialogInterface == mDonationDialog.getAlertDialog()) {+ Log.d(TAG, "Donation dialog dismissed, clearing");+ mDonationDialog = null;+ } else {+ Log.w(TAG, "Unknown donation dialog dismissed, not clearing it");+ }+ }+ });+ alertDialog.show();++ if (splash) {+ Bitmap bitmap = loadSplashImageBitmap(splashBytes);+ if (bitmap != null) {+ mDonationDialog.setSplashContents(bitmap, combineSplashText(splashArtist, splashVersion));+ }+ }++ updateDonationDialogProductsInternal(mDonationDialog);+ } catch (Exception e) {+ Log.e(TAG, "Exception showing donation dialog", e);+ }+ } else {+ Log.w(TAG, "Donation dialog requested while already shown");+ }+ });+ }++ private static Bitmap loadSplashImageBitmap(byte[] splashBytes) {+ if (splashBytes == null || splashBytes.length == 0) {+ Log.d(TAG, "No splash image data given");+ return null;+ }++ Bitmap bitmap;+ try {+ Log.d(TAG, "Loading splash image bitmap");+ bitmap = BitmapFactory.decodeByteArray(splashBytes, 0, splashBytes.length);+ } catch (Exception e) {+ Log.d(TAG, "Exception loading splash image bitmap", e);+ return null;+ }++ if (bitmap == null) {+ Log.w(TAG, "Null splash image bitmap loaded");+ return null;+ }++ Log.d(TAG, "Loaded splash image bitmap");+ return bitmap;+ }++ private static String combineSplashText(String splashArtist, String splashVersion) {+ boolean haveArtist = splashArtist != null && !splashArtist.isEmpty();+ boolean haveVersion = splashVersion != null && !splashVersion.isEmpty();+ if (haveArtist) {+ if (haveVersion) {+ return splashVersion + "\n" + splashArtist;+ } else {+ return splashArtist;+ }+ } else if (haveVersion) {+ return splashVersion;+ } else {+ return "";+ }+ }++ @SuppressWarnings("unused")+ public static void setLoaded(boolean loaded) {+ Log.d(TAG, "setLoaded " + loaded);+ applicationLoaded = loaded;+ updateDonationDialog();+ }++ @SuppressWarnings("unused")+ public static void setLoadingText(String loadingText) {+ Log.d(TAG, "setLoadingText " + loadingText);+ applicationLoadingText = loadingText;+ updateDonationDialog();+ }++ private static void updateDonationDialog() {+ doWithDonationDialog((MainActivity activity, DonationDialog dlg) -> {+ if (dlg.isSplash()) {+ dlg.setLoading(!applicationLoaded);+ dlg.setLoadingText(activity.getLoadingText());+ } else {+ dlg.showProductListPage();+ dlg.setLoading(false);+ }+ });+ }++ private String getLoadingText() {+ if (applicationLoaded) {+ return getString(R.string.donation_dialog_loaded);+ } else if (applicationLoadingText == null || applicationLoadingText.isEmpty()) {+ return getString(R.string.donation_dialog_loading);+ } else {+ return applicationLoadingText;+ }+ }++ public static void showPurchaseConfirmation() {+ JNIWrappers.showDonationManagementDialog();+ doWithDonationDialog((MainActivity activity, DonationDialog dlg) -> {+ dlg.showPurchaseConfirmationPage();+ });+ }++ public static void doWithDonationDialog(BiConsumer<MainActivity, DonationDialog> consumer) {+ doWithMainActivity((MainActivity activity) -> {+ activity.doWithDonationDialogInternal(consumer);+ });+ }++ private void doWithDonationDialogInternal(BiConsumer<MainActivity, DonationDialog> consumer) {+ if (mDonationDialog == null) {+ Log.d(TAG, "Donation dialog not set, not updating it");+ } else {+ QtNative.activity().runOnUiThread(() -> {+ if (mDonationDialog == null) {+ Log.d(TAG, "Donation dialog not set on UI thread, not updating it");+ } else {+ consumer.accept(this, mDonationDialog);+ }+ });+ }+ }++ public static void doWithMainActivity(Consumer<MainActivity> consumer) {+ try {+ Activity activity = QtNative.activity();+ if (activity instanceof MainActivity) {+ consumer.accept(((MainActivity) activity));+ } else {+ Log.e(TAG, "doWithMainActivity: QtNative.activity() is not a Krita MainActivity");+ }+ } catch (Exception e) {+ Log.e(TAG, "Exception in doWithMainActivity", e);+ }+ }++ public static void updateDonationDialogProducts() {+ doWithDonationDialog(MainActivity::updateDonationDialogProductsInternal);+ }++ private void updateDonationDialogProductsInternal(DonationDialog dlg) {+ DonationHelper donationHelper = DonationHelper.getInstance();+ dlg.setProductDetails(+ donationHelper.isReady() ? donationHelper.getProductDetails() : null,+ donationHelper.isAnyProductsOwned());+ }}diff --git a/plugins/extensions/resourcemanager/CMakeLists.txt b/plugins/extensions/resourcemanager/CMakeLists.txtindex 959d114eab..dbb55de07d 100644--- a/plugins/extensions/resourcemanager/CMakeLists.txt+++ b/plugins/extensions/resourcemanager/CMakeLists.txt@@ -31,6 +31,18 @@ ki18n_wrap_ui(kritaresourcemanager_SOURCESwdgtagpreview.ui)+if(ANDROID)+ list(APPEND kritaresourcemanager_SOURCES+ KisSupporterBundlesDialog.cpp+ KisSupporterBundlesFetcher.cpp+ KisSupporterBundleWidget.cpp+ )+ ki18n_wrap_ui(kritaresourcemanager_SOURCES+ KisSupporterBundlesDialog.ui+ KisSupporterBundleWidget.ui+ )+endif()+kis_add_library(kritaresourcemanager MODULE ${kritaresourcemanager_SOURCES})target_link_libraries(kritaresourcemanager kritawidgets kritaui kritalibpaintop kritaresources kritaresourcewidgets)install(TARGETS kritaresourcemanager DESTINATION ${KRITA_PLUGIN_INSTALL_DIR})diff --git a/plugins/extensions/resourcemanager/KisSupporterBundle.h b/plugins/extensions/resourcemanager/KisSupporterBundle.hnew file mode 100644index 0000000000..9d16e09036--- /dev/null+++ b/plugins/extensions/resourcemanager/KisSupporterBundle.h@@ -0,0 +1,26 @@+/*+ * SPDX-License-Identifier: GPL-3.0-or-later+ */+#ifndef __KISSUPPORTERBUNDLE_H_+#define __KISSUPPORTERBUNDLE_H_++#include <QHash>+#include <QPixmap>+#include <QSet>+#include <QString>++struct KisSupporterBundle {+ QString fileName;+ long long sizeInBytes;+ QString source;+ QString title;+ QString description;+ QString author;+ QString license;+ QString checksum;+ QPixmap thumbnail;+ QSet<QString> tags;+ QHash<QString, int> resourceCountByMediaType;+};++#endifdiff --git a/plugins/extensions/resourcemanager/KisSupporterBundleWidget.cpp b/plugins/extensions/resourcemanager/KisSupporterBundleWidget.cppnew file mode 100644index 0000000000..eeb41e77f4--- /dev/null+++ b/plugins/extensions/resourcemanager/KisSupporterBundleWidget.cpp@@ -0,0 +1,253 @@+/*+ * SPDX-License-Identifier: GPL-3.0-or-later+ */+#include "KisSupporterBundleWidget.h"+#include <KisAndroidDonations.h>+#include <KisNetworkAccessManager.h>+#include <KisStorageModel.h>+#include <QCoreApplication>+#include <QCryptographicHash>+#include <QMessageBox>+#include <QNetworkReply>+#include <QProgressDialog>+#include <QTimer>+#include <kis_assert.h>+#include <kis_debug.h>++KisSupporterBundleWidget::KisSupporterBundleWidget(KisSupporterBundlesFetcher *fetcher,+ const KisSupporterBundle &bundle,+ const QVector<KisSupporterProduct> &bundleProducts,+ QWidget *parent)+ : QWidget(parent)+ , m_fetcher(fetcher)+ , m_bundle(bundle)+{+ setupUi(this);++ QStringList contentList;+ addContentEntry(contentList, QStringLiteral("paintoppresets"), [](int count) {+ return i18np("%1 brush preset", "%1 brush presets", count);+ });+ addContentEntry(contentList, QStringLiteral("brushes"), [](int count) {+ return i18np("%1 brush tips", "%1 brush tips", count);+ });+ addContentEntry(contentList, QStringLiteral("patterns"), [](int count) {+ return i18np("%1 texture patterns", "%1 texture patterns", count);+ });+ addContentEntry(contentList, QStringLiteral("workspaces"), [](int count) {+ return i18np("%1 workspace layout", "%1 workspace layouts", count);+ });++ QStringList productList;+ for (const KisSupporterProduct &product : bundleProducts) {+ switch (product.availability) {+ case KisSupporterProductAvailability::Missing:+ // Product is neither available for purchase nor does the user own+ // it, so we'll pretend like it doesn't exist.+ break;+ case KisSupporterProductAvailability::Available:+ productList.append(product.title);+ break;+ case KisSupporterProductAvailability::Owned:+ if (product.type == KisSupporterProductType::Subscription) {+ productList.append(i18n("%1 (subscribed)").arg(product.title));+ } else {+ productList.append(i18n("%1 (owned)").arg(product.title));+ }+ m_productOwned = true;+ break;+ }+ }++ if (m_bundle.thumbnail.isNull()) {+ m_lblPreview->hide();+ } else {+ m_lblPreview->setPixmap(m_bundle.thumbnail);+ }++ QString author = m_bundle.author.toHtmlEscaped();+ if (!m_bundle.source.isEmpty()) {+ author = QStringLiteral("<a href=\"%1\">%2</a>").arg(m_bundle.source.toHtmlEscaped(), author);+ }+ m_lblTitle->setText(QStringLiteral("<strong>%1</strong> by %2").arg(m_bundle.title.toHtmlEscaped(), author));+ m_lblDescription->setText(m_bundle.description);++ // The margins on this stuff is ginormous by default, cut that down.+ QString productsText = QStringLiteral(+ "<style>\n"+ "ul { margin-top: 0px; margin-bottom: 4px; margin-left: -10px; }\n"+ "li { margin: 0px; padding: 0px; }\n"+ "</style>");+ if (!contentList.isEmpty()) {+ productsText.append(+ i18nc("in-app purchases, prefix for a list of what a bundle contains", "Contains:").toHtmlEscaped());+ productsText.append(QStringLiteral("<ul>"));+ for (const QString &content : contentList) {+ productsText.append(QStringLiteral("<li>%1</li>").arg(content.toHtmlEscaped()));+ }+ productsText.append(QStringLiteral("</ul>"));+ }++ if (productList.isEmpty()) {+ productsText.append(i18nc("in-app purchases, a bundle that the user can't acquire", "Not available."));+ } else {+ productsText.append(+ i18nc("in-app purchases, prefix for a list of which purchases make a bundle available", "Available with:")+ .toHtmlEscaped());+ productsText.append(QStringLiteral("<ul>"));+ for (const QString &product : productList) {+ productsText.append(QStringLiteral("<li>%1</li>").arg(product.toHtmlEscaped()));+ }+ productsText.append(QStringLiteral("</ul>"));+ }++ m_lblProducts->setText(productsText);++ KisStorageModel *storageModel = KisStorageModel::instance();+ m_canImport = storageModel->canImportStorage(m_bundle.fileName);+ if (!m_canImport) {+ m_stkDownload->setCurrentWidget(m_pgDone);+ } else if (m_productOwned) {+ m_stkDownload->setCurrentWidget(m_pgGet);+ } else {+ m_stkDownload->setCurrentWidget(m_pgSupport);+ }++ connect(m_btnGet, &QPushButton::clicked, this, &KisSupporterBundleWidget::slotStartDownload);++ KisAndroidDonations *androidDonations = KisAndroidDonations::instance();+ if (androidDonations) {+ connect(m_btnSupport, &QPushButton::clicked, androidDonations, &KisAndroidDonations::slotStartDonationFlow);+ } else {+ m_btnSupport->setEnabled(false);+ }+}++void KisSupporterBundleWidget::slotStartDownload()+{+ KIS_SAFE_ASSERT_RECOVER_RETURN(m_productOwned);+ KIS_SAFE_ASSERT_RECOVER_RETURN(m_fetcher);+ KIS_SAFE_ASSERT_RECOVER_RETURN(!m_progressDlg);++ m_progressDlg = new QProgressDialog(this);+ m_progressDlg->setAutoClose(false);+ m_progressDlg->setAutoReset(false);+ m_progressDlg->setModal(true);+ m_progressDlg->setMinimumDuration(0);+ m_progressDlg->setRange(0, 0);+ m_progressDlg->setLabelText(i18n("Downloading bundle…"));+ m_progressDlg->setWindowTitle(i18n("%1").arg(m_bundle.title));+ m_progressDlg->show();++ QNetworkReply *reply = m_fetcher->fetchBundle(m_bundle);+ connect(reply, &QNetworkReply::downloadProgress, this, &KisSupporterBundleWidget::slotUpdateDownloadProgress);+ connect(m_progressDlg, &QProgressDialog::canceled, reply, &QNetworkReply::abort);+ connect(reply, &QNetworkReply::finished, this, [=] {+ handleDownloadFinished(reply);+ reply->deleteLater();+ });+}++void KisSupporterBundleWidget::slotUpdateDownloadProgress(qint64 bytesReceived, qint64 bytesTotal)+{+ if (m_progressDlg) {+ if (bytesTotal <= 0) {+ m_progressDlg->setRange(0, 0);+ } else {+ m_progressDlg->setRange(0, 100);+ m_progressDlg->setValue(qRound(qreal(bytesTotal) / qreal(bytesReceived) * 100.0));+ }+ }+}++void KisSupporterBundleWidget::addContentEntry(QStringList &outContentList,+ const QString &key,+ const std::function<QString(int)> &formatFn) const+{+ int count = m_bundle.resourceCountByMediaType.value(key, 0);+ if (count > 0) {+ outContentList.append(formatFn(count));+ }+}++void KisSupporterBundleWidget::handleDownloadFinished(QNetworkReply *reply)+{+ if (reply->error() == QNetworkReply::OperationCanceledError) {+ showFinishedDownload(false, true, QString());+ return;+ }++ QString errorMessage;+ if (KisSupporterBundlesFetcher::hasNetworkReplyError(reply, errorMessage)) {+ showFinishedDownload(false, false, errorMessage);+ return;+ }++ slotUpdateDownloadProgress(1, 1);+ QCoreApplication::processEvents();++ QByteArray bytes = reply->readAll();+ long long sizeInBytes = bytes.size();+ if (sizeInBytes != m_bundle.sizeInBytes) {+ warnResources << "Bundle" << m_bundle.fileName << "size of" << sizeInBytes << "does not match expected"+ << m_bundle.sizeInBytes;+ showFinishedDownload(false, false, i18n("Invalid bundle size"));+ return;+ }++ QString hash = QCryptographicHash::hash(bytes, QCryptographicHash::Md5).toHex();+ if (hash != bundle().checksum) {+ warnResources << "Bundle" << m_bundle.fileName << "hash" << hash << "does not match expected"+ << m_bundle.checksum;+ showFinishedDownload(false, false, i18n("Invalid bundle checksum"));+ return;+ }++ m_progressDlg->setLabelText(i18n("Activating bundle…"));+ slotUpdateDownloadProgress(0, 0);+ QCoreApplication::processEvents();++ KisStorageModel *storageModel = KisStorageModel::instance();+ QGuiApplication::setOverrideCursor(Qt::WaitCursor);+ bool importOk = storageModel->importStorageData(m_bundle.fileName, KisStorageModel::None, bytes);+ QGuiApplication::restoreOverrideCursor();++ if (!importOk) {+ showFinishedDownload(false, false, i18n("Failed to import bundle"));+ return;+ }++ showFinishedDownload(true, false, QString());+}++void KisSupporterBundleWidget::showFinishedDownload(bool success, bool cancel, const QString &errorMessage)+{+ if (success) {+ m_btnGet->clearFocus(); // Prevent auto-scrolling to the next button.+ closeProgressDlg();+ m_canImport = false;+ m_stkDownload->setCurrentWidget(m_pgDone);+ } else if (cancel) {+ closeProgressDlg();+ m_btnGet->setEnabled(true);+ m_stkDownload->setCurrentWidget(m_pgGet);+ } else {+ // Delay this a bit to avoid excessively fast retries and to make it+ // clear to the user that a retry is actually happening. Otherwise the+ // download progress bar may flash so quickly that it seems like it's+ // not doing anything at all.+ QTimer::singleShot(1000, [=] {+ closeProgressDlg();+ QMessageBox::warning(this, i18n("Download failed"), i18n("Bundle download failed: %1").arg(errorMessage));+ m_stkDownload->setCurrentWidget(m_pgGet);+ });+ }+}++void KisSupporterBundleWidget::closeProgressDlg()+{+ if (m_progressDlg) {+ m_progressDlg->close();+ m_progressDlg = nullptr;+ }+}diff --git a/plugins/extensions/resourcemanager/KisSupporterBundleWidget.h b/plugins/extensions/resourcemanager/KisSupporterBundleWidget.hnew file mode 100644index 0000000000..8edf8d65b7--- /dev/null+++ b/plugins/extensions/resourcemanager/KisSupporterBundleWidget.h@@ -0,0 +1,63 @@+/*+ * SPDX-License-Identifier: GPL-3.0-or-later+ */+#ifndef __KISSUPPORTERBUNDLEWIDGET_H_+#define __KISSUPPORTERBUNDLEWIDGET_H_++#include <QPointer>+#include <QVector>+#include <QWidget>+#include <functional>++#include "KisSupporterBundle.h"+#include "KisSupporterBundlesFetcher.h"+#include "ui_KisSupporterBundleWidget.h"+#include <KisSupporterProduct.h>++class QNetworkReply;+class QProgressDialog;++class KisSupporterBundleWidget : public QWidget, public Ui::KisSupporterBundleWidget+{+ Q_OBJECT+public:+ explicit KisSupporterBundleWidget(KisSupporterBundlesFetcher *fetcher,+ const KisSupporterBundle &bundle,+ const QVector<KisSupporterProduct> &bundleProducts,+ QWidget *parent = nullptr);++ const KisSupporterBundle &bundle() const+ {+ return m_bundle;+ }++ bool isProductOwned() const+ {+ return m_productOwned;+ }++ bool canImport() const+ {+ return m_canImport;+ }++private Q_SLOTS:+ void slotStartDownload();+ void slotUpdateDownloadProgress(qint64 bytesReceived, qint64 bytesTotal);++private:+ void+ addContentEntry(QStringList &outContentList, const QString &key, const std::function<QString(int)> &formatFn) const;++ void handleDownloadFinished(QNetworkReply *reply);+ void showFinishedDownload(bool success, bool cancel, const QString &errorMessage);+ void closeProgressDlg();++ QPointer<KisSupporterBundlesFetcher> m_fetcher;+ QProgressDialog *m_progressDlg{nullptr};+ KisSupporterBundle m_bundle;+ bool m_productOwned{false};+ bool m_canImport;+};++#endifdiff --git a/plugins/extensions/resourcemanager/KisSupporterBundleWidget.ui b/plugins/extensions/resourcemanager/KisSupporterBundleWidget.uinew file mode 100644index 0000000000..debd1fbc5c--- /dev/null+++ b/plugins/extensions/resourcemanager/KisSupporterBundleWidget.ui@@ -0,0 +1,213 @@+<?xml version="1.0" encoding="UTF-8"?>+<ui version="4.0">+ <class>KisSupporterBundleWidget</class>+ <widget class="QWidget" name="KisSupporterBundleWidget">+ <property name="geometry">+ <rect>+ <x>0</x>+ <y>0</y>+ <width>450</width>+ <height>148</height>+ </rect>+ </property>+ <property name="windowTitle">+ <string>Form</string>+ </property>+ <layout class="QHBoxLayout" name="m_lyt" stretch="0,0">+ <property name="spacing">+ <number>6</number>+ </property>+ <item>+ <layout class="QVBoxLayout" name="m_lytPreview">+ <property name="spacing">+ <number>0</number>+ </property>+ <item>+ <widget class="QLabel" name="m_lblPreview">+ <property name="sizePolicy">+ <sizepolicy hsizetype="Fixed" vsizetype="Fixed">+ <horstretch>0</horstretch>+ <verstretch>0</verstretch>+ </sizepolicy>+ </property>+ <property name="minimumSize">+ <size>+ <width>128</width>+ <height>128</height>+ </size>+ </property>+ <property name="maximumSize">+ <size>+ <width>128</width>+ <height>128</height>+ </size>+ </property>+ <property name="text">+ <string/>+ </property>+ <property name="scaledContents">+ <bool>true</bool>+ </property>+ <property name="alignment">+ <set>Qt::AlignHCenter|Qt::AlignTop</set>+ </property>+ </widget>+ </item>+ <item>+ <spacer name="m_spcPreview">+ <property name="orientation">+ <enum>Qt::Vertical</enum>+ </property>+ <property name="sizeHint" stdset="0">+ <size>+ <width>0</width>+ <height>0</height>+ </size>+ </property>+ </spacer>+ </item>+ </layout>+ </item>+ <item>+ <layout class="QVBoxLayout" name="m_lytDetails" stretch="0,0,0,0,0">+ <item>+ <widget class="QLabel" name="m_lblTitle">+ <property name="text">+ <string notr="true"><b>Title</b></string>+ </property>+ <property name="textFormat">+ <enum>Qt::RichText</enum>+ </property>+ <property name="wordWrap">+ <bool>true</bool>+ </property>+ <property name="openExternalLinks">+ <bool>true</bool>+ </property>+ </widget>+ </item>+ <item>+ <widget class="QLabel" name="m_lblDescription">+ <property name="text">+ <string notr="true">Description</string>+ </property>+ <property name="textFormat">+ <enum>Qt::RichText</enum>+ </property>+ <property name="wordWrap">+ <bool>true</bool>+ </property>+ </widget>+ </item>+ <item>+ <widget class="QLabel" name="m_lblProducts">+ <property name="text">+ <string notr="true">Products</string>+ </property>+ <property name="textFormat">+ <enum>Qt::RichText</enum>+ </property>+ <property name="wordWrap">+ <bool>true</bool>+ </property>+ </widget>+ </item>+ <item>+ <spacer name="m_spcDetails">+ <property name="orientation">+ <enum>Qt::Vertical</enum>+ </property>+ <property name="sizeHint" stdset="0">+ <size>+ <width>0</width>+ <height>0</height>+ </size>+ </property>+ </spacer>+ </item>+ <item>+ <widget class="QStackedWidget" name="m_stkDownload">+ <widget class="QWidget" name="m_pgGet">+ <layout class="QVBoxLayout" name="m_lytPgGet">+ <property name="leftMargin">+ <number>0</number>+ </property>+ <property name="topMargin">+ <number>0</number>+ </property>+ <property name="rightMargin">+ <number>0</number>+ </property>+ <property name="bottomMargin">+ <number>0</number>+ </property>+ <item>+ <widget class="QPushButton" name="m_btnGet">+ <property name="text">+ <string>Download</string>+ </property>+ <property name="autoDefault">+ <bool>false</bool>+ </property>+ </widget>+ </item>+ </layout>+ </widget>+ <widget class="QWidget" name="m_pgSupport">+ <layout class="QVBoxLayout" name="m_lytPgSupport">+ <property name="leftMargin">+ <number>0</number>+ </property>+ <property name="topMargin">+ <number>0</number>+ </property>+ <property name="rightMargin">+ <number>0</number>+ </property>+ <property name="bottomMargin">+ <number>0</number>+ </property>+ <item>+ <widget class="QPushButton" name="m_btnSupport">+ <property name="text">+ <string>Support Krita</string>+ </property>+ </widget>+ </item>+ </layout>+ </widget>+ <widget class="QWidget" name="m_pgDone">+ <layout class="QVBoxLayout" name="m_lytPgDone">+ <property name="leftMargin">+ <number>0</number>+ </property>+ <property name="topMargin">+ <number>0</number>+ </property>+ <property name="rightMargin">+ <number>0</number>+ </property>+ <property name="bottomMargin">+ <number>0</number>+ </property>+ <item>+ <widget class="QLabel" name="label">+ <property name="text">+ <string>✔ Owned</string>+ </property>+ <property name="alignment">+ <set>Qt::AlignCenter</set>+ </property>+ </widget>+ </item>+ </layout>+ </widget>+ </widget>+ </item>+ </layout>+ </item>+ </layout>+ </widget>+ <resources/>+ <connections/>+</ui>diff --git a/plugins/extensions/resourcemanager/KisSupporterBundlesDialog.cpp b/plugins/extensions/resourcemanager/KisSupporterBundlesDialog.cppnew file mode 100644index 0000000000..e9671de125--- /dev/null+++ b/plugins/extensions/resourcemanager/KisSupporterBundlesDialog.cpp@@ -0,0 +1,206 @@+/*+ * SPDX-License-Identifier: GPL-3.0-or-later+ */++#include "KisSupporterBundlesDialog.h"+#include "KisSupporterBundleWidget.h"+#include "KisSupporterBundlesFetcher.h"+#include <KisAndroidDonations.h>+#include <KisKineticScroller.h>+#include <QFrame>+#include <QTimer>+#include <kis_assert.h>+#include <kis_debug.h>++KisSupporterBundlesDialog::KisSupporterBundlesDialog(QWidget *parent)+ : QDialog(parent)+ , m_fetcher(new KisSupporterBundlesFetcher(this))+{+ setupUi(this);+ setWindowTitle(i18n("Supporter Bundles"));++ QScroller *scroller = KisKineticScroller::createPreconfiguredScroller(m_scrBundles);+ if (scroller) {+ connect(scroller, &QScroller::stateChanged, this, [&](QScroller::State state) {+ KisKineticScroller::updateCursor(this, state);+ });+ }++ connect(m_fetcher,+ &KisSupporterBundlesFetcher::fetchIndexDone,+ this,+ &KisSupporterBundlesDialog::slotFetchIndexDone);+ connect(m_btnRetry, &QPushButton::clicked, this, &KisSupporterBundlesDialog::fetchBundles);+ connect(m_buttons, &QDialogButtonBox::rejected, this, &KisSupporterBundlesDialog::reject);++ fetchBundles();+}++void KisSupporterBundlesDialog::slotFetchIndexDone(bool success, const QString &errorMessage)+{+ m_btnRetry->setEnabled(!success);+ if (success) {+ slotResetBundleWidgets();+ m_stack->setCurrentIndex(PAGE_BUNDLES);++ KisAndroidDonations *androidDonations = KisAndroidDonations::instance();+ if (androidDonations) {+ connect(androidDonations,+ &KisAndroidDonations::sigStateChanged,+ this,+ &KisSupporterBundlesDialog::slotResetBundleWidgets);+ }++ } else {+ m_lblError->setText(i18n("<strong>Error:</strong> %1").arg(errorMessage.toHtmlEscaped()));+ // Delay this a bit to avoid excessively fast retries and to make it+ // clear to the user that a retry is actually happening. Otherwise the+ // loading page may flash so quickly that it seems like it's not doing+ // anything at all.+ QTimer::singleShot(1000, [this] {+ m_stack->setCurrentIndex(PAGE_ERROR);+ });+ }+}++void KisSupporterBundlesDialog::slotResetBundleWidgets()+{+ while (!m_lytWdgBundles->isEmpty()) {+ QLayoutItem *item = m_lytWdgBundles->takeAt(m_lytWdgBundles->count() - 1);+ QWidget *widget = item->widget();+ if (widget) {+ widget->deleteLater();+ }+ delete item;+ }++ QVector<KisSupporterProduct> currentProducts = getCurrentProducts();++ QVector<KisSupporterBundleWidget *> bundleWidgets;+ for (const KisSupporterBundle &bundle : m_fetcher->bundles()) {+ // Gather the products that this bundle is associated with.+ QVector<KisSupporterProduct> bundleProducts = getProductsForBundle(currentProducts, bundle);+ // Only show bundles that the user could actually acquire, there's no+ // point in dangling a bundle in front of their nose that they couldn't+ // purchase any product for.+ if (couldOwnAnyProduct(bundleProducts)) {+ KisSupporterBundleWidget *bundleWidget = new KisSupporterBundleWidget(m_fetcher, bundle, bundleProducts);+ bundleWidgets.append(bundleWidget);+ } else {+ dbgResources << "No products for bundle" << bundle.fileName;+ }+ }++ if (bundleWidgets.isEmpty()) {+ m_lytWdgBundles->addStretch();+ QLabel *label = new QLabel(i18n("No supporter bundles available."));+ label->setAlignment(Qt::AlignCenter);+ label->setWordWrap(true);+ m_lytWdgBundles->addWidget(label);+ m_lytWdgBundles->addStretch();+ } else {+ std::sort(bundleWidgets.begin(), bundleWidgets.end(), &KisSupporterBundlesDialog::bundleWidgetLessThan);++ // We've been asked to put this disclaimer here so that people don't+ // contact the authors and complain about paywalling or something.+ // Don't remove this message without discussing it with them.+ QLabel *purchaseNoteLabel =+ new QLabel(i18n("These bundles have been made available by their authors to help provide rewards for "+ "supporting Krita's development. They do not receive compensation for purchases and may "+ "make these bundles in other ways behind the links below."));+ purchaseNoteLabel->setTextFormat(Qt::PlainText);+ purchaseNoteLabel->setWordWrap(true);+ m_lytWdgBundles->addWidget(purchaseNoteLabel);++ for (KisSupporterBundleWidget *bundleWidget : bundleWidgets) {+ QFrame *separator = new QFrame;+ separator->setFrameShape(QFrame::HLine);+ separator->setFrameShadow(QFrame::Sunken);+ m_lytWdgBundles->addWidget(separator);+ m_lytWdgBundles->addWidget(bundleWidget);+ }+ m_lytWdgBundles->addStretch();+ }+}++void KisSupporterBundlesDialog::fetchBundles()+{+ if (!m_fetcher->isFetching()) {+ m_stack->setCurrentIndex(PAGE_FETCHING);+ m_btnRetry->setEnabled(false);+ m_fetcher->fetchIndex();+ }+}++QVector<KisSupporterProduct> KisSupporterBundlesDialog::getCurrentProducts() const+{+ KisAndroidDonations *androidDonations = KisAndroidDonations::instance();+ KIS_SAFE_ASSERT_RECOVER_RETURN_VALUE(androidDonations, QVector<KisSupporterProduct>());+ return androidDonations->getCurrentProducts();+}++QVector<KisSupporterProduct>+KisSupporterBundlesDialog::getProductsForBundle(const QVector<KisSupporterProduct> ¤tProducts,+ const KisSupporterBundle &bundle)+{+ const QString prefix = QStringLiteral("p:");+ QVector<KisSupporterProduct> bundleProducts;+ dbgResources << "Bundle" << bundle.fileName << "tags:" << bundle.tags;+ for (const QString &tag : bundle.tags) {+ if (tag.startsWith(prefix)) {+ const KisSupporterProduct *product = searchProductById(currentProducts, tag.mid(prefix.length()));+ if (product) {+ bundleProducts.append(*product);+ }+ }+ }+ return bundleProducts;+}++const KisSupporterProduct *+KisSupporterBundlesDialog::searchProductById(const QVector<KisSupporterProduct> ¤tProducts, const QString &id)+{+ for (const KisSupporterProduct &product : currentProducts) {+ if (product.id == id) {+ return &product;+ }+ }+ dbgResources << "No current product for id" << id;+ return nullptr;+}++bool KisSupporterBundlesDialog::couldOwnAnyProduct(const QVector<KisSupporterProduct> &bundleProducts)+{+ for (const KisSupporterProduct &product : bundleProducts) {+ switch (product.availability) {+ case KisSupporterProductAvailability::Missing:+ break;+ case KisSupporterProductAvailability::Available:+ case KisSupporterProductAvailability::Owned:+ return true;+ }+ }+ return false;+}++bool KisSupporterBundlesDialog::bundleWidgetLessThan(const KisSupporterBundleWidget *a,+ const KisSupporterBundleWidget *b)+{+ bool aOwned = a->isProductOwned();+ bool bOwned = b->isProductOwned();+ if (aOwned && !bOwned) {+ return true;+ } else if (!aOwned && bOwned) {+ return false;+ }++ bool aCanImport = a->canImport();+ bool bCanImport = b->canImport();+ if (aCanImport && !bCanImport) {+ return true;+ } else if (!aCanImport && bCanImport) {+ return false;+ }++ return a->bundle().title.compare(b->bundle().title, Qt::CaseInsensitive) < 0;+}diff --git a/plugins/extensions/resourcemanager/KisSupporterBundlesDialog.h b/plugins/extensions/resourcemanager/KisSupporterBundlesDialog.hnew file mode 100644index 0000000000..d1a91bcfdb--- /dev/null+++ b/plugins/extensions/resourcemanager/KisSupporterBundlesDialog.h@@ -0,0 +1,50 @@+/*+ * SPDX-License-Identifier: GPL-3.0-or-later+ */+#ifndef __KISSUPPORTERBUNDLESDIALOG_H_+#define __KISSUPPORTERBUNDLESDIALOG_H_++#include <QDialog>+#include <QSet>+#include <QVector>++#include "ui_KisSupporterBundlesDialog.h"+#include <KisSupporterProduct.h>++class KisSupporterBundlesFetcher;+class KisSupporterBundleWidget;+struct KisSupporterBundle;++class KisSupporterBundlesDialog : public QDialog, public Ui::KisSupporterBundlesDialog+{+ Q_OBJECT+public:+ explicit KisSupporterBundlesDialog(QWidget *parent = nullptr);++private Q_SLOTS:+ void slotFetchIndexDone(bool success, const QString &errorMessage);+ void slotResetBundleWidgets();++private:+ static constexpr int PAGE_FETCHING = 0;+ static constexpr int PAGE_ERROR = 1;+ static constexpr int PAGE_BUNDLES = 2;++ void fetchBundles();++ QVector<KisSupporterProduct> getCurrentProducts() const;++ static QVector<KisSupporterProduct> getProductsForBundle(const QVector<KisSupporterProduct> ¤tProducts,+ const KisSupporterBundle &bundle);++ static const KisSupporterProduct *searchProductById(const QVector<KisSupporterProduct> ¤tProducts,+ const QString &id);++ static bool couldOwnAnyProduct(const QVector<KisSupporterProduct> &bundleProducts);++ static bool bundleWidgetLessThan(const KisSupporterBundleWidget *a, const KisSupporterBundleWidget *b);++ KisSupporterBundlesFetcher *m_fetcher;+};++#endifdiff --git a/plugins/extensions/resourcemanager/KisSupporterBundlesDialog.ui b/plugins/extensions/resourcemanager/KisSupporterBundlesDialog.uinew file mode 100644index 0000000000..c34c028461--- /dev/null+++ b/plugins/extensions/resourcemanager/KisSupporterBundlesDialog.ui@@ -0,0 +1,154 @@+<?xml version="1.0" encoding="UTF-8"?>+<ui version="4.0">+ <class>KisSupporterBundlesDialog</class>+ <widget class="QDialog" name="KisSupporterBundlesDialog">+ <property name="geometry">+ <rect>+ <x>0</x>+ <y>0</y>+ <width>500</width>+ <height>480</height>+ </rect>+ </property>+ <property name="windowTitle">+ <string>Dialog</string>+ </property>+ <property name="modal">+ <bool>true</bool>+ </property>+ <layout class="QVBoxLayout" name="m_lyt">+ <item>+ <widget class="QStackedWidget" name="m_stack">+ <widget class="QWidget" name="m_wdgLoading">+ <layout class="QVBoxLayout" name="m_lytWdgLoading">+ <item>+ <spacer name="m_spcLoadingTop">+ <property name="orientation">+ <enum>Qt::Vertical</enum>+ </property>+ <property name="sizeHint" stdset="0">+ <size>+ <width>0</width>+ <height>0</height>+ </size>+ </property>+ </spacer>+ </item>+ <item>+ <widget class="QLabel" name="m_lblLoading">+ <property name="text">+ <string>Loading…</string>+ </property>+ <property name="alignment">+ <set>Qt::AlignCenter</set>+ </property>+ </widget>+ </item>+ <item>+ <widget class="QProgressBar" name="m_barLoading">+ <property name="maximum">+ <number>0</number>+ </property>+ <property name="value">+ <number>-1</number>+ </property>+ <property name="textVisible">+ <bool>false</bool>+ </property>+ <property name="format">+ <string notr="true"/>+ </property>+ </widget>+ </item>+ <item>+ <spacer name="m_spcLoadingBottom">+ <property name="orientation">+ <enum>Qt::Vertical</enum>+ </property>+ <property name="sizeHint" stdset="0">+ <size>+ <width>0</width>+ <height>0</height>+ </size>+ </property>+ </spacer>+ </item>+ </layout>+ </widget>+ <widget class="QWidget" name="m_wdgError">+ <layout class="QVBoxLayout" name="m_lytWdgError">+ <item>+ <spacer name="m_wdgErrorSpacerTop">+ <property name="orientation">+ <enum>Qt::Vertical</enum>+ </property>+ <property name="sizeHint" stdset="0">+ <size>+ <width>20</width>+ <height>40</height>+ </size>+ </property>+ </spacer>+ </item>+ <item>+ <widget class="QLabel" name="m_lblError">+ <property name="text">+ <string notr="true">Error message goes here.</string>+ </property>+ <property name="alignment">+ <set>Qt::AlignCenter</set>+ </property>+ </widget>+ </item>+ <item>+ <widget class="QPushButton" name="m_btnRetry">+ <property name="text">+ <string>Retry</string>+ </property>+ </widget>+ </item>+ <item>+ <spacer name="m_wdgErrorSpacerBottom">+ <property name="orientation">+ <enum>Qt::Vertical</enum>+ </property>+ <property name="sizeHint" stdset="0">+ <size>+ <width>20</width>+ <height>40</height>+ </size>+ </property>+ </spacer>+ </item>+ </layout>+ </widget>+ <widget class="QScrollArea" name="m_scrBundles">+ <property name="widgetResizable">+ <bool>true</bool>+ </property>+ <widget class="QWidget" name="m_wdgBundles">+ <property name="geometry">+ <rect>+ <x>0</x>+ <y>0</y>+ <width>98</width>+ <height>28</height>+ </rect>+ </property>+ <layout class="QVBoxLayout" name="m_lytWdgBundles"/>+ </widget>+ </widget>+ </widget>+ </item>+ <item>+ <widget class="QDialogButtonBox" name="m_buttons">+ <property name="standardButtons">+ <set>QDialogButtonBox::Close</set>+ </property>+ </widget>+ </item>+ </layout>+ </widget>+ <resources/>+ <connections/>+</ui>diff --git a/plugins/extensions/resourcemanager/KisSupporterBundlesFetcher.cpp b/plugins/extensions/resourcemanager/KisSupporterBundlesFetcher.cppnew file mode 100644index 0000000000..3d1664f306--- /dev/null+++ b/plugins/extensions/resourcemanager/KisSupporterBundlesFetcher.cpp@@ -0,0 +1,361 @@+/*+ * SPDX-License-Identifier: GPL-3.0-or-later+ */+#include "KisSupporterBundlesFetcher.h"+#include <KisNetworkAccessManager.h>+#include <QCryptographicHash>+#include <QDir>+#include <QFile>+#include <QHash>+#include <QNetworkReply>+#include <QRegularExpression>+#include <QSaveFile>+#include <QSqlDatabase>+#include <QSqlError>+#include <QSqlQuery>+#include <QStandardPaths>+#include <QtEndian>+#include <kis_assert.h>+#include <kis_debug.h>+#include <klocalizedstring.h>++KisSupporterBundlesFetcher::KisSupporterBundlesFetcher(QObject *parent)+ : QObject(parent)+{+ QDir cacheDir(QStandardPaths::writableLocation(QStandardPaths::CacheLocation));+ m_indexDbPath = cacheDir.filePath(QStringLiteral("kissupporterbundlesindex.db"));+ dbgResources << "Index db path:" << m_indexDbPath;+}++void KisSupporterBundlesFetcher::fetchIndex()+{+ KIS_SAFE_ASSERT_RECOVER_RETURN(!m_fetching);+ m_fetching = true;+ QNetworkReply *reply = fetch(QStringLiteral("check0.txt"));+ connect(reply, &QNetworkReply::finished, this, [=] {+ handleCheckTxtFetched(reply);+ reply->deleteLater();+ });+}++QNetworkReply *KisSupporterBundlesFetcher::fetchBundle(const KisSupporterBundle &bundle)+{+ return fetch(QStringLiteral("bundles/%1").arg(bundle.fileName));+}++bool KisSupporterBundlesFetcher::hasNetworkReplyError(QNetworkReply *reply, QString &outErrorMessage)+{+ if (reply->error() != QNetworkReply::NoError) {+ outErrorMessage = reply->errorString();+ return true;+ }++ int statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();+ if (statusCode < 200 || statusCode > 300) {+ outErrorMessage = i18n("Server responded with error %1.").arg(statusCode);+ return true;+ }++ return false;+}++void KisSupporterBundlesFetcher::handleCheckTxtFetched(QNetworkReply *reply)+{+ QString errorMessage;+ if (hasNetworkReplyError(reply, errorMessage)) {+ emitCheckTxtFetchFailed(errorMessage);+ return;+ }++ QString content = QString::fromUtf8(reply->readAll());++ // "Predefined failures" are for forward-compatibility for stuff like the+ // format changing and old versions of Krita becoming unsupported or the+ // service getting discontinued altogether.+ if (handleCheckTxtPredefinedFailure(content)) {+ return;+ }++ // The check0.txt is supposed to contain a version followed by an MD5 hash+ // digest. For forward-compatibility, we'll ignore anything else afterwards.+ QRegularExpression re(QStringLiteral("\\A\\s*([0-9]+)\\s+([0-9a-fA-F]+)\\b"));+ QRegularExpressionMatch match = re.match(content);+ if (!match.hasMatch()) {+ emitCheckTxtFetchFailed(i18n("Invalid checksums file."));+ return;+ }++ bool ok;+ unsigned int expectedVersion = match.captured(1).toUInt(&ok);+ dbgResources << "Expected version from fetched check0.txt:" << expectedVersion;+ if (!ok) {+ emitCheckTxtFetchFailed(i18n("Invalid checksums version."));+ return;+ }++ QString expectedHash = match.captured(2);+ dbgResources << "Expected hash from fetched check0.txt:" << expectedHash;++ if (checkExistingIndexDb(expectedVersion, expectedHash)) {+ readIndexDbBundles();+ } else {+ fetchIndexDb(expectedVersion, expectedHash);+ }+}++bool KisSupporterBundlesFetcher::handleCheckTxtPredefinedFailure(const QString &content)+{+ QRegularExpression re(QStringLiteral("\\A!failure=([a-zA-Z0-9]*)"), QRegularExpression::CaseInsensitiveOption);+ QRegularExpressionMatch match = re.match(content);+ if (!match.hasMatch()) {+ return false;+ }++ QString failureType = match.captured(1);+ QString errorMessage;+ if (failureType.compare(QStringLiteral("outdated"), Qt::CaseInsensitive) == 0) {+ errorMessage = i18n("You have to update Krita to use this service.");+ } else if (failureType.compare(QStringLiteral("region"), Qt::CaseInsensitive) == 0) {+ errorMessage = i18n("This service is not available in your region.");+ } else if (failureType.compare(QStringLiteral("unavailable"), Qt::CaseInsensitive) == 0) {+ errorMessage = i18n("This service is currently unavailable.");+ } else if (failureType.compare(QStringLiteral("discontinued"), Qt::CaseInsensitive) == 0) {+ errorMessage = i18n("This service has been discontinued.");+ } else {+ errorMessage = i18n("Unknown service error %1.").arg(failureType);+ }++ emitFailure(errorMessage);+ return true;+}++bool KisSupporterBundlesFetcher::checkExistingIndexDb(unsigned int expectedVersion, const QString &expectedHash)+{+ QFile file(m_indexDbPath);+ if (!file.open(QIODevice::ReadOnly)) {+ dbgResources << "Could not open existing index db";+ return false;+ }++ QByteArray bytes = file.readAll();+ unsigned int version;+ if (!readSqliteUserVersion(bytes, version)) {+ dbgResources << "Could not read existing version";+ return false;+ }++ if (version != expectedVersion) {+ dbgResources << "Existing version" << version << "!=" << expectedVersion;+ return false;+ }++ QString hash = QCryptographicHash::hash(bytes, QCryptographicHash::Md5).toHex();+ if (hash != expectedHash) {+ dbgResources << "Existing hash" << hash << "!=" << expectedHash;+ return false;+ }++ dbgResources << "Cached index database is valid";+ return true;+}++void KisSupporterBundlesFetcher::fetchIndexDb(unsigned int expectedVersion, const QString &expectedHash)+{+ QNetworkReply *reply = fetch(QStringLiteral("index0.db"));+ connect(reply, &QNetworkReply::finished, this, [=] {+ handleIndexDbFetched(reply, expectedVersion, expectedHash);+ reply->deleteLater();+ });+}++void KisSupporterBundlesFetcher::handleIndexDbFetched(QNetworkReply *reply,+ unsigned int expectedVersion,+ const QString &expectedHash)+{+ QString errorMessage;+ if (hasNetworkReplyError(reply, errorMessage)) {+ emitIndexDbFetchFailed(errorMessage);+ return;+ }++ QByteArray bytes = reply->readAll();+ unsigned int version;+ if (!readSqliteUserVersion(bytes, version)) {+ emitIndexDbFetchFailed(i18n("Not enough data."));+ return;+ }++ dbgResources << "got version:" << version;+ dbgResources << "expected:" << expectedVersion;+ if (version != expectedVersion) {+ emitIndexDbFetchFailed(i18n("Invalid version."));+ return;+ }++ QString hash = QCryptographicHash::hash(bytes, QCryptographicHash::Md5).toHex();+ dbgResources << "got hash:" << hash;+ dbgResources << "expected:" << expectedHash;+ if (hash != expectedHash) {+ emitIndexDbFetchFailed(i18n("Invalid checksum."));+ return;+ }++ QString dirName = QFileInfo(m_indexDbPath).path();+ if (!QDir().mkpath(dirName)) {+ emitIndexDbFetchFailed(i18n("Failed to create directory %1.").arg(dirName));+ return;+ }++ QSaveFile saveFile(m_indexDbPath);+ saveFile.setDirectWriteFallback(true);+ if (!saveFile.open(QIODevice::WriteOnly)) {+ emitIndexDbFetchFailed(i18n("Failed to open %1 for writing.").arg(m_indexDbPath));+ return;+ }++ qint64 written = saveFile.write(bytes);+ if (written != qint64(bytes.size()) || !saveFile.commit()) {+ emitIndexDbFetchFailed(i18n("Failed to write %1.").arg(m_indexDbPath));+ return;+ }++ readIndexDbBundles();+}++void KisSupporterBundlesFetcher::readIndexDbBundles()+{+ QString errorMessage;+ bool ok = doWithIndexDb(errorMessage, [this](QSqlDatabase &db, QString &outErrorMessage) {+ QSqlQuery query(db);++ QString selectBundlesSql = QStringLiteral(+ "select bundle_id, file_name, size_in_bytes, source, title,\n"+ " description, author, license, checksum, thumbnail\n"+ "from bundle");+ if (!query.exec(selectBundlesSql)) {+ outErrorMessage = query.lastError().text();+ return false;+ }++ QHash<long long, KisSupporterBundle> bundlesById;+ while (query.next()) {+ long long id = query.value(0).toLongLong();+ KisSupporterBundle bundle = {+ query.value(1).toString(),+ query.value(2).toLongLong(),+ query.value(3).toString(),+ query.value(4).toString(),+ query.value(5).toString(),+ query.value(6).toString(),+ query.value(7).toString(),+ query.value(8).toString(),+ QPixmap(),+ QSet<QString>(),+ QHash<QString, int>(),+ };+ bundle.thumbnail.loadFromData(query.value(9).toByteArray());+ bundlesById.insert(id, bundle);+ }++ QString selectTagsSql = QStringLiteral("select bundle_id, tag from bundle_tag");+ if (!query.exec(selectTagsSql)) {+ outErrorMessage = query.lastError().text();+ return false;+ }++ while (query.next()) {+ long long id = query.value(0).toLongLong();+ QHash<long long, KisSupporterBundle>::iterator it = bundlesById.find(id);+ if (it != bundlesById.end()) {+ it->tags.insert(query.value(1).toString());+ }+ }++ QString selectResourceCountsSql = QStringLiteral(+ "select bundle_id, media_type, amount\n"+ "from bundle_resource_count");+ if (query.exec(selectResourceCountsSql)) {+ while (query.next()) {+ long long id = query.value(0).toLongLong();+ QHash<long long, KisSupporterBundle>::iterator it = bundlesById.find(id);+ if (it != bundlesById.end()) {+ it->resourceCountByMediaType.insert(query.value(1).toString(), query.value(2).toInt());+ }+ }+ } else {+ warnResources << "Error querying bundle resource counts:" << query.lastError().text();+ // Not critical to have these counts, just keep going.+ }++ m_bundles = QVector<KisSupporterBundle>(bundlesById.begin(), bundlesById.end());+ dbgResources << "Loaded" << m_bundles.size() << "supporter bundle(s)";+ return true;+ });++ m_fetching = false;+ emit fetchIndexDone(ok, errorMessage);+}++QNetworkReply *KisSupporterBundlesFetcher::fetch(const QString &path)+{+ QUrl url(QString::fromUtf8(BASE_URL));+ url.setPath(url.path(QUrl::FullyDecoded) + path);++ QNetworkRequest req;+ req.setUrl(url);++ if (!m_nam) {+ m_nam = new KisNetworkAccessManager(this);+ }++ dbgResources << "Fetch" << url;+ return m_nam->get(req);+}++void KisSupporterBundlesFetcher::emitCheckTxtFetchFailed(const QString &errorMessage)+{+ emitFailure(i18n("Failed to retrieve bundle checksums: %1", errorMessage));+}++void KisSupporterBundlesFetcher::emitIndexDbFetchFailed(const QString &errorMessage)+{+ emitFailure(i18n("Failed to retrieve bundles: %1", errorMessage));+}++void KisSupporterBundlesFetcher::emitFailure(const QString &errorMessage)+{+ m_fetching = false;+ Q_EMIT fetchIndexDone(false, errorMessage);+}++bool KisSupporterBundlesFetcher::doWithIndexDb(QString &outErrorMessage,+ const std::function<bool(QSqlDatabase &, QString &)> &block)+{+ QString connectionName = QStringLiteral("KisSupporterBundlesFetcher");+ bool ok;+ {+ QSqlDatabase db = QSqlDatabase::addDatabase(QStringLiteral("QSQLITE"), connectionName);+ db.setDatabaseName(m_indexDbPath);+ if (db.open()) {+ ok = block(db, outErrorMessage);+ db.close();+ } else {+ ok = false;+ outErrorMessage = db.lastError().text();+ }+ }+ QSqlDatabase::removeDatabase(connectionName);+ return ok;+}++bool KisSupporterBundlesFetcher::readSqliteUserVersion(const QByteArray &bytes, unsigned int &outVersion)+{+ // The SQLite format stores its "user version" value at index 60 as a 32 bit+ // bigendian unsigned integer. See https://www.sqlite.org/fileformat.html+ if (bytes.size() < 64) {+ return false;+ } else {+ outVersion = qFromBigEndian<quint32>(bytes.constData() + 60);+ return true;+ }+}diff --git a/plugins/extensions/resourcemanager/KisSupporterBundlesFetcher.h b/plugins/extensions/resourcemanager/KisSupporterBundlesFetcher.hnew file mode 100644index 0000000000..6c7067caa5--- /dev/null+++ b/plugins/extensions/resourcemanager/KisSupporterBundlesFetcher.h@@ -0,0 +1,74 @@+/*+ * SPDX-License-Identifier: GPL-3.0-or-later+ */+#ifndef __KISSUPPORTERBUNDLESFETCHER_H_+#define __KISSUPPORTERBUNDLESFETCHER_H_++#include <QFileInfo>+#include <QObject>+#include <QUrl>+#include <QVector>+#include <functional>++#include "KisSupporterBundle.h"++class KisNetworkAccessManager;+class QNetworkReply;+class QSqlDatabase;++class KisSupporterBundlesFetcher : public QObject+{+ Q_OBJECT+public:+ explicit KisSupporterBundlesFetcher(QObject *parent = nullptr);++ bool isFetching() const+ {+ return m_fetching;+ }++ const QVector<KisSupporterBundle> &bundles() const+ {+ return m_bundles;+ }++ void fetchIndex();++ QNetworkReply *fetchBundle(const KisSupporterBundle &bundle);++ static bool hasNetworkReplyError(QNetworkReply *reply, QString &outErrorMessage);++Q_SIGNALS:+ void fetchIndexDone(bool success, const QString &errorMessage);++private:+ static constexpr char BASE_URL[] = "https://cdn.kde.org/krita/.android-supporters-extra/supporterbundles/";++ void handleCheckTxtFetched(QNetworkReply *reply);+ bool handleCheckTxtPredefinedFailure(const QString &content);++ bool checkExistingIndexDb(unsigned int expectedVersion, const QString &expectedHash);++ void fetchIndexDb(unsigned int expectedVersion, const QString &expectedHash);++ void handleIndexDbFetched(QNetworkReply *reply, unsigned int expectedVersion, const QString &expectedHash);++ void readIndexDbBundles();++ QNetworkReply *fetch(const QString &path);++ void emitCheckTxtFetchFailed(const QString &errorMessage);+ void emitIndexDbFetchFailed(const QString &errorMessage);+ void emitFailure(const QString &errorMessage);++ bool doWithIndexDb(QString &outErrorMessage, const std::function<bool(QSqlDatabase &, QString &)> &block);++ static bool readSqliteUserVersion(const QByteArray &bytes, unsigned int &outVersion);++ KisNetworkAccessManager *m_nam = nullptr;+ QString m_indexDbPath;+ QVector<KisSupporterBundle> m_bundles;+ bool m_fetching = false;+};++#endifdiff --git a/plugins/extensions/resourcemanager/dlg_bundle_manager.cpp b/plugins/extensions/resourcemanager/dlg_bundle_manager.cppindex 90b267263c..6ccdb9d660 100644--- a/plugins/extensions/resourcemanager/dlg_bundle_manager.cpp+++ b/plugins/extensions/resourcemanager/dlg_bundle_manager.cpp@@ -37,6 +37,10 @@#include <KisMainWindow.h>#include <KisPart.h>+#ifdef Q_OS_ANDROID+#include <KisSupporterBundlesDialog.h>+#endif+DlgBundleManager::ItemDelegate::ItemDelegate(QObject *parent, KisStorageFilterProxyModel* proxy): QStyledItemDelegate(parent), m_bundleManagerProxyModel(proxy)@@ -152,6 +156,12 @@ DlgBundleManager::DlgBundleManager(QWidget *parent)m_ui->bnEdit->setText(i18nc("In bundle manager; press button to edit existing bundle", "Edit Bundle"));connect(m_ui->bnEdit, SIGNAL(clicked(bool)), SLOT(editBundle()));+#ifdef Q_OS_ANDROID+ connect(m_ui->bnSupport, &QPushButton::clicked, this, &DlgBundleManager::slotShowSupporterBundlesDialog);+#else+ m_ui->bnSupport->hide();+#endif+setButtons(Close);m_proxyModel = new KisStorageFilterProxyModel(this);@@ -318,6 +328,14 @@ void DlgBundleManager::editBundle()}}+#ifdef Q_OS_ANDROID+void DlgBundleManager::slotShowSupporterBundlesDialog()+{+ QScopedPointer<KisSupporterBundlesDialog> dlg(new KisSupporterBundlesDialog(this));+ dlg->exec();+}+#endif+void DlgBundleManager::toggleBundle(){QModelIndex idx = m_ui->listView->currentIndex();diff --git a/plugins/extensions/resourcemanager/dlg_bundle_manager.h b/plugins/extensions/resourcemanager/dlg_bundle_manager.hindex 6c82afe2e2..d2350dbad3 100644--- a/plugins/extensions/resourcemanager/dlg_bundle_manager.h+++ b/plugins/extensions/resourcemanager/dlg_bundle_manager.h@@ -59,6 +59,9 @@ private Q_SLOTS:void createBundle();void toggleBundle();void editBundle();+#ifdef Q_OS_ANDROID+ void slotShowSupporterBundlesDialog();+#endifvoid slotModelAboutToBeReset();void slotModelReset();diff --git a/plugins/extensions/resourcemanager/resourcemanager.cpp b/plugins/extensions/resourcemanager/resourcemanager.cppindex 715d5d0234..ae7786fc38 100644--- a/plugins/extensions/resourcemanager/resourcemanager.cpp+++ b/plugins/extensions/resourcemanager/resourcemanager.cpp@@ -20,8 +20,11 @@#include "dlg_create_bundle.h"#include "DlgResourceManager.h"-class ResourceManager::Private {+#ifdef Q_OS_ANDROID+#include "KisSupporterBundlesDialog.h"+#endif+class ResourceManager::Private {public:Private()@@ -42,6 +45,12 @@ ResourceManager::ResourceManager(QObject *parent, const QVariantList &)action = new KisAction(i18n("Manage Resources..."), this);addAction("manage_resources", action);connect(action, SIGNAL(triggered()), this, SLOT(slotManageResources()));++#ifdef Q_OS_ANDROID+ action = new KisAction(i18n("Get More Resources..."), this);+ addAction("manage_supporter_bundles", action);+ connect(action, &QAction::triggered, this, &ResourceManager::slotManageSupporterBundles);+#endif}ResourceManager::~ResourceManager()@@ -60,4 +69,16 @@ void ResourceManager::slotManageResources()dlg.exec();}++#ifdef Q_OS_ANDROID+void ResourceManager::slotManageSupporterBundles()+{+ // Gotta summon it like this, doing it with exec() causes kinetic scrolling+ // to not work properly, requiring two fingers instead of one. No clue why.+ KisSupporterBundlesDialog *dlg = new KisSupporterBundlesDialog(qApp->activeWindow());+ dlg->setAttribute(Qt::WA_DeleteOnClose);+ dlg->show();+}+#endif+#include "resourcemanager.moc"diff --git a/plugins/extensions/resourcemanager/resourcemanager.h b/plugins/extensions/resourcemanager/resourcemanager.hindex 04776ba9f7..859069f27b 100644--- a/plugins/extensions/resourcemanager/resourcemanager.h+++ b/plugins/extensions/resourcemanager/resourcemanager.h@@ -28,6 +28,9 @@ public:private Q_SLOTS:void slotManageBundles();void slotManageResources();+#ifdef Q_OS_ANDROID+ void slotManageSupporterBundles();+#endifprivate:class Private;diff --git a/plugins/extensions/resourcemanager/wdgdlgbundlemanager.ui b/plugins/extensions/resourcemanager/wdgdlgbundlemanager.uiindex aa025b3158..dd1695c7d9 100644--- a/plugins/extensions/resourcemanager/wdgdlgbundlemanager.ui+++ b/plugins/extensions/resourcemanager/wdgdlgbundlemanager.ui@@ -67,21 +67,9 @@<verstretch>0</verstretch></sizepolicy></property>- <layout class="QGridLayout" name="gridLayout_5">- <property name="leftMargin">- <number>0</number>- </property>- <property name="topMargin">- <number>0</number>- </property>- <property name="rightMargin">- <number>0</number>- </property>- <property name="bottomMargin">- <number>0</number>- </property>- <item row="3" column="4">- <widget class="QPushButton" name="bnEdit">+ <layout class="QGridLayout" name="gridLayout">+ <item row="1" column="0">+ <widget class="QPushButton" name="bnAdd"><property name="sizePolicy"><sizepolicy hsizetype="Minimum" vsizetype="Minimum"><horstretch>0</horstretch>@@ -89,15 +77,18 @@</sizepolicy></property><property name="toolTip">- <string>Edit a resource library</string>+ <string>Import a resource library</string></property><property name="text"><string/></property>+ <property name="icon">+ <iconset theme="new"/>+ </property></widget></item>- <item row="3" column="1">- <widget class="QPushButton" name="bnNew">+ <item row="1" column="1">+ <widget class="QPushButton" name="bnToggle"><property name="sizePolicy"><sizepolicy hsizetype="Minimum" vsizetype="Minimum"><horstretch>0</horstretch>@@ -105,19 +96,18 @@</sizepolicy></property><property name="toolTip">- <string>Create a resource library</string>+ <string>Delete a resource library</string></property><property name="text"><string/></property><property name="icon">- <iconset theme="add">- <normaloff>.</normaloff>.</iconset>+ <iconset theme="delete"/></property></widget></item>- <item row="0" column="1">- <widget class="QPushButton" name="bnAdd">+ <item row="2" column="0">+ <widget class="QPushButton" name="bnNew"><property name="sizePolicy"><sizepolicy hsizetype="Minimum" vsizetype="Minimum"><horstretch>0</horstretch>@@ -125,19 +115,18 @@</sizepolicy></property><property name="toolTip">- <string>Import a resource library</string>+ <string>Create a resource library</string></property><property name="text"><string/></property><property name="icon">- <iconset theme="new">- <normaloff>.</normaloff>.</iconset>+ <iconset theme="add"/></property></widget></item>- <item row="0" column="4">- <widget class="QPushButton" name="bnToggle">+ <item row="2" column="1">+ <widget class="QPushButton" name="bnEdit"><property name="sizePolicy"><sizepolicy hsizetype="Minimum" vsizetype="Minimum"><horstretch>0</horstretch>@@ -145,14 +134,17 @@</sizepolicy></property><property name="toolTip">- <string>Delete a resource library</string>+ <string>Edit a resource library</string></property><property name="text"><string/></property>- <property name="icon">- <iconset theme="delete">- <normaloff>.</normaloff>.</iconset>+ </widget>+ </item>+ <item row="0" column="0" colspan="2">+ <widget class="QPushButton" name="bnSupport">+ <property name="text">+ <string>Get More Bundles</string></property></widget></item>