Corrected video recording resolution for front camera
[harmattan/cameraplus] / src / postcapturemodel.cpp
1 /*!
2  * This file is part of CameraPlus.
3  *
4  * Copyright (C) 2012-2013 Mohammed Sameer <msameer@foolab.org>
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
19  */
20
21 #include "postcapturemodel.h"
22 #include <QSparqlConnection>
23 #include <QSparqlQuery>
24 #include <QSparqlResult>
25 #include <QSparqlError>
26 #if defined(QT4)
27 #include <QDeclarativeInfo>
28 #elif defined(QT5)
29 #include <QQmlInfo>
30 #endif
31 #include <QDateTime>
32 #include <QDBusConnection>
33 #include <QStringList>
34 #include <QDBusMetaType>
35 #include <QDBusArgument>
36
37 #define DRIVER "QTRACKER_DIRECT"
38 #define QUERY "SELECT rdf:type(?urn) AS ?type nie:url(?urn) AS ?url nie:contentCreated(?urn) AS ?created nie:title(?urn) AS ?title nfo:fileName(?urn) AS ?filename nie:mimeType(?urn) AS ?mimetype tracker:available(?urn) AS ?available nfo:fileLastModified(?urn) as ?lastmod tracker:id(?urn) AS ?trackerid (EXISTS { ?urn nao:hasTag nao:predefined-tag-favorite }) AS ?favorite WHERE { ?urn nfo:equipment ?:equipment . {?urn a nfo:Video} UNION {?urn a nfo:Image}} ORDER BY DESC(?created)"
39
40 #define UPDATE_QUERY "SELECT rdf:type(?urn) AS ?type nie:url(?urn) AS ?url nie:contentCreated(?urn) AS ?created nie:title(?urn) AS ?title nfo:fileName(?urn) AS ?filename nie:mimeType(?urn) AS ?mimetype tracker:available(?urn) AS ?available nfo:fileLastModified(?urn) as ?lastmod tracker:id(?urn) AS ?trackerid (EXISTS { ?urn nao:hasTag nao:predefined-tag-favorite }) AS ?favorite WHERE {?urn a nfo:Visual . FILTER (tracker:id(?urn) IN (%1)) }"
41
42 #define TRACKER_SERVICE "org.freedesktop.Tracker1"
43 #define TRACKER_RESOURCE_PATH "/org/freedesktop/Tracker1/Resources"
44 #define TRACKER_RESOURCE_INTERFACE "org.freedesktop.Tracker1.Resources"
45 #define TRACKER_RESOURCE_SIGNAL "GraphUpdated"
46 #define PHOTO_CLASS "http://www.tracker-project.org/temp/nmm#Photo"
47 #define VIDEO_CLASS "http://www.tracker-project.org/temp/nmm#Video"
48 #define TRACKER_RESOURCE_SIGNAL_SIGNATURE "sa(iiii)a(iiii)"
49
50 class Quad {
51 public:
52   int graph;
53   int subject;
54   int predicate;
55   int object;
56 };
57
58 Q_DECLARE_METATYPE(Quad);
59 Q_DECLARE_METATYPE(QList<Quad>);
60
61 QDBusArgument& operator<<(QDBusArgument& argument, const Quad& t) {
62   argument.beginStructure();
63   argument << t.graph << t.subject << t.predicate << t.object;
64   argument.endStructure();
65   return argument;
66 }
67
68 const QDBusArgument& operator>>(const QDBusArgument& argument, Quad& t) {
69   argument.beginStructure();
70   argument >> t.graph >> t.subject >> t.predicate >> t.object;
71   argument.endStructure();
72   return argument;
73 }
74
75 PostCaptureModel::PostCaptureModel(QObject *parent) :
76   QAbstractListModel(parent),
77   m_connection(0),
78   m_connected(false) {
79
80   qDBusRegisterMetaType<Quad>();
81   qDBusRegisterMetaType<QList<Quad> >();
82
83   QHash<int, QByteArray> roles;
84   roles.insert(Item, "item");
85
86   setRoleNames(roles);
87 }
88
89 PostCaptureModel::~PostCaptureModel() {
90   qDeleteAll(m_items);
91   m_items.clear();
92
93   delete m_connection; m_connection = 0;
94 }
95
96 void PostCaptureModel::reload() {
97   delete m_connection; m_connection = 0;
98
99   if (!m_items.isEmpty()) {
100     beginRemoveRows(QModelIndex(), 0, m_items.size() - 1);
101     qDeleteAll(m_items);
102     m_items.clear();
103     endRemoveRows();
104   }
105
106   m_connection = new QSparqlConnection(DRIVER, QSparqlConnectionOptions(), this);
107   if (!m_connection->isValid()) {
108     emit error(tr("Failed to create SPARQL connection"));
109     return;
110   }
111
112   QString equipment = QString("urn:equipment:%1:%2:").arg(m_manufacturer).arg(m_model);
113
114   QSparqlQuery q(QUERY, QSparqlQuery::SelectStatement);
115   q.bindValue("equipment", equipment);
116   exec(q);
117
118   if (!m_connected) {
119     const char *slot = SLOT(graphUpdated(const QString&,
120                                          const QList<Quad>&,
121                                          const QList<Quad>&));
122     m_connected = QDBusConnection::sessionBus().connect(TRACKER_SERVICE, TRACKER_RESOURCE_PATH,
123                                                         TRACKER_RESOURCE_INTERFACE,
124                                                         TRACKER_RESOURCE_SIGNAL,
125                                                         TRACKER_RESOURCE_SIGNAL_SIGNATURE,
126                                                         this, slot);
127   }
128
129   if (!m_connected) {
130     qmlInfo(this) << "Failed to connect to tracker " << TRACKER_RESOURCE_SIGNAL;
131   }
132 }
133
134 void PostCaptureModel::exec(QSparqlQuery& query) {
135   if (!m_connection) {
136     qWarning() << "No connection to query";
137     return;
138   }
139
140   QSparqlResult *result = m_connection->exec(query);
141
142   if (result->hasError()) {
143     QSparqlError error = result->lastError();
144     qmlInfo(this) << "Error executing SPARQL query" << error.message();
145
146     delete result;
147
148     emit PostCaptureModel::error(tr("Failed to query tracker"));
149   }
150
151   if (result) {
152     QObject::connect(result, SIGNAL(dataReady(int)), this, SLOT(dataReady(int)));
153     QObject::connect(result, SIGNAL(finished()), result, SLOT(deleteLater()));
154   }
155 }
156
157 int PostCaptureModel::rowCount(const QModelIndex& parent) const {
158   if (parent.isValid()) {
159     return 0;
160   }
161
162   return m_items.size();
163 }
164
165 QVariant PostCaptureModel::data(const QModelIndex& index, int role) const {
166   if (!index.isValid() || index.row() < 0 || index.row() >= m_items.size()) {
167     return QVariant();
168   }
169
170   if (role == Item) {
171     return QVariant::fromValue(dynamic_cast<QObject *>(m_items[index.row()]));
172   }
173
174   return QVariant();
175 }
176
177 QString PostCaptureModel::manufacturer() const {
178   return m_manufacturer;
179 }
180
181 void PostCaptureModel::setManufacturer(const QString& manufacturer) {
182   if (m_manufacturer != manufacturer) {
183     m_manufacturer = manufacturer;
184     emit manufacturerChanged();
185   }
186 }
187
188 QString PostCaptureModel::model() const {
189   return m_model;
190 }
191
192 void PostCaptureModel::setModel(const QString& model) {
193   if (m_model != model) {
194     m_model = model;
195     emit modelChanged();
196   }
197 }
198
199 void PostCaptureModel::dataReady(int totalCount) {
200   Q_UNUSED(totalCount);
201
202   QSparqlResult *result = dynamic_cast<QSparqlResult *>(sender());
203   if (!result) {
204     return;
205   }
206
207   while (result->next()) {
208     addRow(new PostCaptureModelItem(result->current(), this));
209   }
210
211   result->previous();
212 }
213
214 void PostCaptureModel::addRow(PostCaptureModelItem *item) {
215   if (m_hash.contains(item->trackerId())) {
216     m_hash[item->trackerId()]->update(item);
217     delete item;
218     return;
219   }
220
221   beginInsertRows(QModelIndex(), m_items.size(), m_items.size());
222   m_items << item;
223   m_hash.insert(item->trackerId(), item);
224
225   endInsertRows();
226 }
227
228 void PostCaptureModel::remove(QObject *item) {
229   PostCaptureModelItem *i = dynamic_cast<PostCaptureModelItem *>(item);
230   if (!i) {
231     qmlInfo(this) << "Invalid item to remove";
232     return;
233   }
234
235   int index = m_items.indexOf(i);
236   if (index == -1) {
237     qmlInfo(this) << "Item" << i->trackerId() << "not found in model";
238     return;
239   }
240
241   beginRemoveRows(QModelIndex(), index, index);
242   m_items.takeAt(index);
243   m_hash.remove(i->trackerId());
244   endRemoveRows();
245
246   i->deleteLater();
247 }
248
249 void PostCaptureModel::graphUpdated(const QString& className, const QList<Quad>& deleted,
250                                     const QList<Quad>& inserted) {
251
252   // We will just assume tracker:available has changed and that's it.
253   // We are not really interested in the rest of properties.
254
255   if (!(className == QLatin1String(PHOTO_CLASS) || className == QLatin1String(VIDEO_CLASS))) {
256     return;
257   }
258
259   QList<int> items;
260
261   for (int x = 0; x < deleted.size(); x++) {
262     Quad q = deleted[x];
263     if (m_hash.contains(q.subject) && items.indexOf(q.subject) == -1) {
264       items << q.subject;
265     }
266   }
267
268   for (int x = 0; x < inserted.size(); x++) {
269     Quad q = inserted[x];
270     if (m_hash.contains(q.subject) && items.indexOf(q.subject) == -1) {
271       items << q.subject;
272     }
273   }
274
275   for (int x = 0; x < items.size(); x++) {
276     QString query = QString(UPDATE_QUERY).arg(items[x]);
277     QSparqlQuery q(query, QSparqlQuery::SelectStatement);
278
279     exec(q);
280   }
281 }
282
283 #if defined(QT5)
284 QHash<int, QByteArray> PostCaptureModel::roleNames() const {
285   return m_roles;
286 }
287
288 void PostCaptureModel::setRoleNames(const QHash<int, QByteArray>& roles) {
289   m_roles = roles;
290 }
291 #endif
292
293 PostCaptureModelItem::PostCaptureModelItem(const QSparqlResultRow& row, QObject *parent) :
294   QObject(parent) {
295
296   for (int x = 0; x < row.count(); x++) {
297     QSparqlBinding b = row.binding(x);
298     m_data.insert(b.name(), b.value());
299   }
300 }
301
302 QString PostCaptureModelItem::type() const {
303   return value("type").toString();
304 }
305
306 QUrl PostCaptureModelItem::url() const {
307   return value("url").toUrl();
308 }
309
310 QString PostCaptureModelItem::created() const {
311   return formatDateTime(value("created").toDateTime());
312 }
313
314 QString PostCaptureModelItem::title() const {
315   return value("title").toString();
316 }
317
318 QString PostCaptureModelItem::fileName() const {
319   return value("filename").toString();
320 }
321
322 QString PostCaptureModelItem::mimeType() const {
323   return value("mimetype").toString();
324 }
325
326 bool PostCaptureModelItem::available() const {
327   return value("available", false).toBool();
328 }
329
330 QString PostCaptureModelItem::lastModified() const {
331   return formatDateTime(value("lastmod").toDateTime());
332 }
333
334 unsigned PostCaptureModelItem::trackerId() const {
335   return value("trackerid").toUInt();
336 }
337
338 bool PostCaptureModelItem::favorite() const {
339   return value("favorite", false).toBool();
340 }
341
342 void PostCaptureModelItem::setFavorite(bool add) {
343   if (favorite() != add) {
344     m_data["favorite"] = add;
345
346     emit favoriteChanged();
347   }
348 }
349
350 QString PostCaptureModelItem::formatDateTime(const QDateTime& dt) const {
351   return dt.toString();
352 }
353
354 void PostCaptureModelItem::update(PostCaptureModelItem *other) {
355   // We will only update available, favorite and title:
356 #if 0
357   qDebug() << "i" << trackerId() << other->trackerId()  << "\n"
358            << "a" << available() << other->available() << "\n"
359            << "t" << title() << other->title() << "\n"
360            << "f" << favorite() << other->favorite();
361 #endif
362
363   if (available() != other->available()) {
364     m_data["available"] = other->available();
365     emit availableChanged();
366   }
367
368   if (title() != other->title()) {
369     m_data["title"] = other->title();
370     emit titleChanged();
371   }
372
373   if (favorite() != other->favorite()) {
374     m_data["favorite"] = other->favorite();
375     emit favoriteChanged();
376   }
377 }
378
379 QVariant PostCaptureModelItem::value(const QString& id, const QVariant& def) const {
380   return m_data.contains(id) ? m_data[id] : def;
381 }