view src/gui/widgets/poster.cpp @ 68:2417121d894e

*: normalize usage of layouts before, I used them two ways, once was by setting the layout later by using setLayout(QWidget), and the other was just using the constructor. I find the constructor to be easier to read, so I chose that one.
author Paper <mrpapersonic@gmail.com>
date Mon, 02 Oct 2023 21:33:25 -0400
parents 442065432549
children d3e9310598b1
line wrap: on
line source

#include "gui/widgets/poster.h"
#include "gui/widgets/clickable_label.h"
#include "core/anime_db.h"
#include "core/strings.h"
#include "core/session.h"
#include <QFrame>
#include <QMessageBox>
#include <QLabel>
#include <QHBoxLayout>
#include <QByteArray>
#include <QDesktopServices>
#include <QUrl>
#include <QDebug>
#include <QPixmap>
#include <curl/curl.h>

static size_t WriteCallback(void* contents, size_t size, size_t nmemb, void* userdata) {
	reinterpret_cast<QByteArray*>(userdata)->append(reinterpret_cast<char*>(contents), size * nmemb);
	return size * nmemb;
}

static QByteArray SendRequest(std::string url) {
	QByteArray userdata;
	CURL* curl = curl_easy_init();
	if (curl) {
		curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
		curl_easy_setopt(curl, CURLOPT_WRITEDATA, &userdata);
		curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, &WriteCallback);
		/* Use system certs... useful on Windows. */
		curl_easy_setopt(curl, CURLOPT_SSL_OPTIONS, CURLSSLOPT_NATIVE_CA);
		CURLcode res = curl_easy_perform(curl);
		session.IncrementRequests();
		curl_easy_cleanup(curl);
		if (res != CURLE_OK) {
			QMessageBox box(QMessageBox::Icon::Critical, "",
			                QString("curl_easy_perform(curl) failed!: ") + QString(curl_easy_strerror(res)));
			box.exec();
		}
	}
	return userdata;
}

Poster::Poster(int id, 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);
	
	const Anime::Anime& anime = Anime::db.items[id];
	QByteArray ret = SendRequest(anime.GetPosterUrl());

	img.loadFromData(ret);
	QPixmap pixmap = QPixmap::fromImage(img);

	label = new ClickableLabel(this);
	label->setAlignment(Qt::AlignCenter);
	connect(label, &ClickableLabel::clicked, this, [anime]{
		QDesktopServices::openUrl(Strings::ToQString(anime.GetServiceUrl()));
	});
	layout->addWidget(label);
}

void Poster::resizeEvent(QResizeEvent*) {
	QPixmap pixmap = QPixmap::fromImage(img).scaled(label->size(), Qt::KeepAspectRatioByExpanding, Qt::SmoothTransformation);
	label->setPixmap(pixmap);
}

#include "gui/widgets/moc_poster.cpp"