view src/gui/widgets/poster.cc @ 254:d14f8e0e40c3

[UNFINISHED] *: update anime button
author Paper <paper@paper.us.eu.org>
date Wed, 07 Feb 2024 07:57:37 -0500
parents 4d461ef7d424
children fe702c8f161f
line wrap: on
line source

#include "gui/widgets/poster.h"
#include "core/anime_db.h"
#include "core/http.h"
#include "core/session.h"
#include "core/strings.h"
#include "gui/widgets/clickable_label.h"

#include <QByteArray>
#include <QDebug>
#include <QDesktopServices>
#include <QFrame>
#include <QHBoxLayout>
#include <QLabel>
#include <QMessageBox>
#include <QPixmap>
#include <QThread>
#include <QUrl>

Poster::Poster(QWidget* parent) : QFrame(parent) {
	QHBoxLayout* layout = new QHBoxLayout(this);
	layout->setContentsMargins(1, 1, 1, 1);

	setCursor(Qt::PointingHandCursor);
	setFixedSize(150, 225);
	setFrameShape(QFrame::Box);
	setFrameShadow(QFrame::Plain);

	label = new ClickableLabel(this);
	label->setAlignment(Qt::AlignCenter);
	layout->addWidget(label);
}

Poster::Poster(const Anime::Anime& anime, QWidget* parent) : Poster(parent) {
	SetAnime(anime);
}

void Poster::SetAnime(const Anime::Anime& anime) {
	{
		HTTP::GetThread* thread = new HTTP::GetThread(anime.GetPosterUrl(), {}, this);

		connect(thread, &HTTP::GetThread::ReceivedData, this, &Poster::ImageDownloadFinished);
		connect(thread, &HTTP::GetThread::finished, thread, &HTTP::GetThread::deleteLater);

		thread->start();
	}

	service_url = Strings::ToQString(anime.GetServiceUrl());

	if (clickable) {
		label->disconnect();
		connect(label, &ClickableLabel::clicked, this,
				[this] { QDesktopServices::openUrl(service_url); });
	}
}

void Poster::SetClickable(bool enabled) {
	clickable = enabled;

	if (clickable && !service_url.isEmpty()) {
		setCursor(Qt::PointingHandCursor);
		label->disconnect();
		connect(label, &ClickableLabel::clicked, this,
				[this] { QDesktopServices::openUrl(service_url); });
	} else {
		setCursor(Qt::ArrowCursor);
		label->disconnect();
	}
}

void Poster::ImageDownloadFinished(const QByteArray& arr) {
	img.loadFromData(arr);
	RenderToLabel();
}

void Poster::RenderToLabel() {
	const QPixmap pixmap = QPixmap::fromImage(img);
	if (pixmap.isNull())
		return;
	label->setPixmap(pixmap.scaled(label->size(), Qt::KeepAspectRatioByExpanding, Qt::SmoothTransformation));
}

void Poster::resizeEvent(QResizeEvent*) {
	RenderToLabel();
}