aboutsummaryrefslogtreecommitdiffstats
path: root/qt-ui/divepicturewidget.cpp
blob: ce997fea1a7c328c287568531b0c6b5436f9a600 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
#include "divepicturewidget.h"
#include "metrics.h"
#include "dive.h"
#include "divelist.h"
#include <unistd.h>
#include <QtConcurrentMap>
#include <QtConcurrentRun>
#include <QFuture>
#include <QDir>
#include <QCryptographicHash>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <mainwindow.h>
#include <qthelper.h>
#include <QStandardPaths>

void loadPicuture(struct picture *picture)
{
	ImageDownloader download(picture);
	download.load();
}

SHashedImage::SHashedImage(struct picture *picture) : QImage()
{
	QUrl url = QUrl::fromUserInput(QString(picture->filename));
	if(url.isLocalFile())
		load(url.toLocalFile());
	if (isNull()) {
		// Hash lookup.
		load(fileFromHash(picture->hash));
		if (!isNull()) {
			QtConcurrent::run(updateHash, picture);
		} else {
			QtConcurrent::run(loadPicuture, picture);
		}
	} else {
		QByteArray hash = hashFile(url.toLocalFile());
		free(picture->hash);
		picture->hash = strdup(hash.toHex().data());
	}
}

ImageDownloader::ImageDownloader(struct picture *pic)
{
	picture = pic;
}

void ImageDownloader::load(){
	QUrl url = QUrl::fromUserInput(QString(picture->filename));
	if (url.isValid()) {
		QEventLoop loop;
		QNetworkRequest request(url);
		connect(&manager, SIGNAL(finished(QNetworkReply *)), this, SLOT(saveImage(QNetworkReply *)));
		QNetworkReply *reply = manager.get(request);
		while (reply->isRunning()) {
			loop.processEvents();
			sleep(1);
		}
	}

}

void ImageDownloader::saveImage(QNetworkReply *reply)
{
	QByteArray imageData = reply->readAll();
	QCryptographicHash hash(QCryptographicHash::Sha1);
	hash.addData(imageData);
	QString path = QStandardPaths::standardLocations(QStandardPaths::CacheLocation).first();
	QDir dir(path);
	if (!dir.exists())
		dir.mkpath(path);
	QFile imageFile(path.append("/").append(hash.result().toHex()));
	if (imageFile.open(QIODevice::WriteOnly)) {
		QDataStream stream(&imageFile);
		stream.writeRawData(imageData.data(), imageData.length());
		imageFile.waitForBytesWritten(-1);
		imageFile.close();
		add_hash(imageFile.fileName(), hash.result());
		learnHash(picture, hash.result());
		DivePictureModel::instance()->updateDivePictures();
	}
	reply->manager()->deleteLater();
	reply->deleteLater();
}

DivePictureModel *DivePictureModel::instance()
{
	static DivePictureModel *self = new DivePictureModel();
	return self;
}

DivePictureModel::DivePictureModel() : numberOfPictures(0)
{
}

typedef struct picture *picturepointer;
typedef QPair<picturepointer, QImage> SPixmap;
typedef QList<struct picture *> SPictureList;

SPixmap scaleImages(picturepointer picture)
{
	static QHash <QString, QImage > cache;
	SPixmap ret;
	ret.first = picture;
	if (cache.contains(picture->filename) && !cache.value(picture->filename).isNull()) {
		ret.second = cache.value(picture->filename);
	} else {
		int dim = defaultIconMetrics().sz_pic;
		QImage p = SHashedImage(picture);
		if(!p.isNull())
			p = p.scaled(dim, dim, Qt::KeepAspectRatio);
			cache.insert(picture->filename, p);
		ret.second = p;
	}
	return ret;
}

void DivePictureModel::updateDivePicturesWhenDone(QList<QFuture<void> > futures)
{
	Q_FOREACH (QFuture<void> f, futures) {
		f.waitForFinished();
	}
	updateDivePictures();
}

void DivePictureModel::updateDivePictures()
{
	if (numberOfPictures != 0) {
		beginRemoveRows(QModelIndex(), 0, numberOfPictures - 1);
		numberOfPictures = 0;
		endRemoveRows();
	}

	// if the dive_table is empty, ignore the displayed_dive
	numberOfPictures = dive_table.nr == 0 ? 0 : dive_get_picture_count(&displayed_dive);
	if (numberOfPictures == 0) {
		return;
	}

	stringPixmapCache.clear();
	SPictureList pictures;
	FOR_EACH_PICTURE_NON_PTR(displayed_dive) {
		stringPixmapCache[QString(picture->filename)].offsetSeconds = picture->offset.seconds;
		pictures.push_back(picture);
	}

	QList<SPixmap> list = QtConcurrent::blockingMapped(pictures, scaleImages);
	Q_FOREACH (const SPixmap &pixmap, list)
		stringPixmapCache[pixmap.first->filename].image = pixmap.second;

	beginInsertRows(QModelIndex(), 0, numberOfPictures - 1);
	endInsertRows();
}

int DivePictureModel::columnCount(const QModelIndex &parent) const
{
	return 2;
}

QVariant DivePictureModel::data(const QModelIndex &index, int role) const
{
	QVariant ret;
	if (!index.isValid())
		return ret;

	QString key = stringPixmapCache.keys().at(index.row());
	if (index.column() == 0) {
		switch (role) {
		case Qt::ToolTipRole:
			ret = key;
			break;
		case Qt::DecorationRole:
			ret = stringPixmapCache[key].image;
			break;
		case Qt::DisplayRole:
			ret = QFileInfo(key).fileName();
			break;
		case Qt::DisplayPropertyRole:
			ret = QFileInfo(key).filePath();
		}
	} else if (index.column() == 1) {
		switch (role) {
		case Qt::UserRole:
			ret = QVariant::fromValue((int)stringPixmapCache[key].offsetSeconds);
		break;
		case Qt::DisplayRole:
			ret = key;
		}
	}
	return ret;
}

void DivePictureModel::removePicture(const QString &fileUrl)
{
	dive_remove_picture(fileUrl.toUtf8().data());
	copy_dive(current_dive, &displayed_dive);
	updateDivePictures();
	mark_divelist_changed(true);
}

int DivePictureModel::rowCount(const QModelIndex &parent) const
{
	return numberOfPictures;
}

DivePictureWidget::DivePictureWidget(QWidget *parent) : QListView(parent)
{
	connect(this, SIGNAL(doubleClicked(const QModelIndex &)), this, SLOT(doubleClicked(const QModelIndex &)));
}

void DivePictureWidget::doubleClicked(const QModelIndex &index)
{
	QString filePath = model()->data(index, Qt::DisplayPropertyRole).toString();
	emit photoDoubleClicked(localFilePath(filePath));
}