summaryrefslogblamecommitdiffstats
path: root/src/sessionsiconholder.cpp
blob: b0feb668566b54e776412d8c9dda18fb0a4412f1 (plain) (tree)

























































































                                                                                           
/*
 * sessionsiconholder.cpp
 *
 *  Created on: Mar 7, 2014
 *      Author: nils
 */

#include <QHash>
#include <QtDebug>
#include <QFile>
#include <QIcon>
#include <QResource>
#include <QFileInfo>

#include "globals.h"
#include "sessionsiconholder.h"
#include "FileDownloader.h"

SessionsIconHolder::SessionsIconHolder() {
}

void SessionsIconHolder::afterDownload(QString& iconName, QByteArray downloadedData) {
	// save the data to disk
	QString filePath = "/tmp/vmchooser2/icons/" + iconName;
	QFile file(filePath);
	if (!file.open(QFile::WriteOnly)) {
		if (debugMode) {
			qDebug() << "Could not write file: " << filePath;
		}
		return;
	}
	file.write(downloadedData);

	if (file.write(downloadedData) != downloadedData.length()) {
		if (debugMode) {
			qDebug() << "Could not write file: " << filePath;
		}
		return;
	}

	file.close();
	QIcon icon(filePath);
	iconsURL.insert(iconName, icon);
	// TODO: trigger sessionstree to update the icons
}

QIcon SessionsIconHolder::getIconFromResource(const QString& name) {
	if (iconsResource.contains(name)) {
		return iconsResource[name];
	}

	QIcon icon;
	if (QResource(":" + name.toLower() + ".svg").isValid()) {
		icon = QIcon(":" + name.toLower() + ".svg");
	} else if (QResource(":" + name.toLower()).isValid()) {
		icon =  QIcon(":" + name.toLower());
	} else {
		icon = QIcon(":none");
	}

	iconsResource.insert(name, icon);
	return icon;
}

QIcon SessionsIconHolder::getIconFromFile(const QString& filename) {
	if (iconsFile.contains(filename)) {
		return iconsFile[filename];
	}

	QFile iconFile(filename);
	if (iconFile.exists()) {
		return QIcon(filename);
	}

	return QIcon(":none");
}

QIcon SessionsIconHolder::getIconFromURL(const QUrl& fileUrl) {
	QString iconName = QFileInfo(fileUrl.toLocalFile()).fileName();
	if (iconsURL.contains(iconName)) {
		return iconsURL[iconName];
	}

	FileDownloader fileDownloader(this);
	fileDownloader.connectSlot(this,
			SLOT(afterDownload(QString& iconName, QByteArray downloadedData)));
	fileDownloader.downloadFile(fileUrl);

	return QIcon(":none");
}