mirror of
https://github.com/YACReader/yacreader
synced 2025-07-14 02:54:46 -04:00
Refactoring: fix mixed indentation and add curly braces in comic.cpp
This commit is contained in:
47
YACReaderLibrary/db/comic_item.cpp
Normal file
47
YACReaderLibrary/db/comic_item.cpp
Normal file
@ -0,0 +1,47 @@
|
||||
|
||||
#include <QStringList>
|
||||
|
||||
#include "comic_item.h"
|
||||
|
||||
//! [0]
|
||||
ComicItem::ComicItem(const QList<QVariant> &data)
|
||||
|
||||
{
|
||||
itemData = data;
|
||||
}
|
||||
//! [0]
|
||||
|
||||
//! [1]
|
||||
ComicItem::~ComicItem()
|
||||
{
|
||||
|
||||
}
|
||||
//! [1]
|
||||
|
||||
|
||||
//! [5]
|
||||
int ComicItem::columnCount() const
|
||||
{
|
||||
return itemData.count();
|
||||
}
|
||||
//! [5]
|
||||
|
||||
//! [6]
|
||||
QVariant ComicItem::data(int column) const
|
||||
{
|
||||
return itemData.value(column);
|
||||
}
|
||||
//! [6]
|
||||
|
||||
void ComicItem::setData(int column,const QVariant & value)
|
||||
{
|
||||
itemData[column] = value;
|
||||
}
|
||||
|
||||
//! [8]
|
||||
int ComicItem::row() const
|
||||
{
|
||||
|
||||
return 0;
|
||||
}
|
||||
//! [8]
|
27
YACReaderLibrary/db/comic_item.h
Normal file
27
YACReaderLibrary/db/comic_item.h
Normal file
@ -0,0 +1,27 @@
|
||||
#ifndef TABLEITEM_H
|
||||
#define TABLEITEM_H
|
||||
|
||||
#include <QList>
|
||||
#include <QVariant>
|
||||
|
||||
//! [0]
|
||||
class ComicItem : public QObject
|
||||
{
|
||||
Q_OBJECT
|
||||
public:
|
||||
ComicItem(const QList<QVariant> &data);
|
||||
~ComicItem();
|
||||
int columnCount() const;
|
||||
QVariant data(int column) const;
|
||||
void setData(int column,const QVariant & value);
|
||||
int row() const;
|
||||
//unsigned long long int id; //TODO sustituir por una clase adecuada
|
||||
//Comic comic;
|
||||
private:
|
||||
QList<QVariant> itemData;
|
||||
|
||||
|
||||
};
|
||||
//! [0]
|
||||
|
||||
#endif
|
1187
YACReaderLibrary/db/comic_model.cpp
Normal file
1187
YACReaderLibrary/db/comic_model.cpp
Normal file
File diff suppressed because it is too large
Load Diff
168
YACReaderLibrary/db/comic_model.h
Normal file
168
YACReaderLibrary/db/comic_model.h
Normal file
@ -0,0 +1,168 @@
|
||||
#ifndef TABLEMODEL_H
|
||||
#define TABLEMODEL_H
|
||||
|
||||
#include <QAbstractItemModel>
|
||||
#include <QModelIndex>
|
||||
#include <QVariant>
|
||||
#include <QSqlQuery>
|
||||
#include <QSqlDatabase>
|
||||
|
||||
#include "yacreader_global_gui.h"
|
||||
|
||||
class ComicDB;
|
||||
|
||||
class ComicItem;
|
||||
|
||||
using namespace YACReader;
|
||||
|
||||
//! [0]
|
||||
class ComicModel : public QAbstractItemModel
|
||||
{
|
||||
Q_OBJECT
|
||||
|
||||
public:
|
||||
ComicModel(QObject *parent = 0);
|
||||
ComicModel( QSqlQuery &sqlquery, QObject *parent = 0);
|
||||
~ComicModel();
|
||||
|
||||
QVariant data(const QModelIndex &index, int role) const;
|
||||
Qt::ItemFlags flags(const QModelIndex &index) const;
|
||||
QVariant headerData(int section, Qt::Orientation orientation,
|
||||
int role = Qt::DisplayRole) const;
|
||||
QModelIndex index(int row, int column,
|
||||
const QModelIndex &parent = QModelIndex()) const;
|
||||
QModelIndex parent(const QModelIndex &index) const;
|
||||
int rowCount(const QModelIndex &parent = QModelIndex()) const;
|
||||
int columnCount(const QModelIndex &parent = QModelIndex()) const;
|
||||
bool canDropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent) const;
|
||||
bool dropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent);
|
||||
bool canBeResorted();
|
||||
QMimeData * mimeData(const QModelIndexList &indexes) const;
|
||||
QStringList mimeTypes() const;
|
||||
|
||||
void setupFolderModelData(unsigned long long int parentFolder,const QString & databasePath);
|
||||
void setupLabelModelData(unsigned long long int parentLabel, const QString & databasePath);
|
||||
void setupReadingListModelData(unsigned long long int parentReadingList, const QString & databasePath);
|
||||
void setupFavoritesModelData(const QString & databasePath);
|
||||
void setupReadingModelData(const QString & databasePath);
|
||||
//configures the model for showing the comics matching the filter criteria.
|
||||
void setupModelData(const SearchModifiers modifier, const QString & filter, const QString & databasePath);
|
||||
|
||||
//Métodos de conveniencia
|
||||
QStringList getPaths(const QString & _source);
|
||||
QString getComicPath(QModelIndex mi);
|
||||
QString getCurrentPath(){return QString(_databasePath).remove("/.yacreaderlibrary");}
|
||||
ComicDB getComic(const QModelIndex & mi); //--> para la edición
|
||||
//ComicDB getComic(int row);
|
||||
QVector<YACReaderComicReadStatus> getReadList();
|
||||
QVector<YACReaderComicReadStatus> setAllComicsRead(YACReaderComicReadStatus readStatus);
|
||||
QList<ComicDB> getComics(QList<QModelIndex> list); //--> recupera la información común a los comics seleccionados
|
||||
QList<ComicDB> getAllComics();
|
||||
QModelIndex getIndexFromId(quint64 id);
|
||||
QList<QModelIndex> getIndexesFromIds(const QList<qulonglong> &comicIds);
|
||||
//setcomicInfo(QModelIndex & mi); --> inserta en la base datos
|
||||
//setComicInfoForAllComics(); --> inserta la información común a todos los cómics de una sola vez.
|
||||
//setComicInfoForSelectedComis(QList<QModelIndex> list); -->inserta la información común para los comics seleccionados
|
||||
QVector<YACReaderComicReadStatus> setComicsRead(QList<QModelIndex> list,YACReaderComicReadStatus read);
|
||||
qint64 asignNumbers(QList<QModelIndex> list,int startingNumber);
|
||||
void remove(ComicDB * comic, int row);
|
||||
void removeInTransaction(int row);
|
||||
void reload(const ComicDB & comic);
|
||||
void resetComicRating(const QModelIndex & mi);
|
||||
|
||||
|
||||
void addComicsToFavorites(const QList<QModelIndex> &comicsList);
|
||||
void addComicsToLabel(const QList<QModelIndex> &comicsList, qulonglong labelId);
|
||||
void addComicsToReadingList(const QList<QModelIndex> &comicsList, qulonglong readingListId);
|
||||
|
||||
void deleteComicsFromFavorites(const QList<QModelIndex> &comicsList);
|
||||
void deleteComicsFromLabel(const QList<QModelIndex> &comicsList, qulonglong labelId);
|
||||
void deleteComicsFromReadingList(const QList<QModelIndex> &comicsList, qulonglong readingListId);
|
||||
|
||||
void deleteComicsFromModel(const QList<QModelIndex> &comicsList);
|
||||
|
||||
bool isFavorite(const QModelIndex &index);
|
||||
|
||||
QHash<int, QByteArray> roleNames() const;
|
||||
|
||||
enum Columns {
|
||||
Number = 0,
|
||||
Title = 1,
|
||||
FileName = 2,
|
||||
NumPages = 3,
|
||||
Id = 4,
|
||||
Parent_Id = 5,
|
||||
Path = 6,
|
||||
Hash = 7,
|
||||
ReadColumn = 8,
|
||||
IsBis = 9,
|
||||
CurrentPage = 10,
|
||||
Rating = 11,
|
||||
HasBeenOpened = 12
|
||||
};
|
||||
|
||||
enum Roles {
|
||||
NumberRole = Qt::UserRole + 1,
|
||||
TitleRole,
|
||||
FileNameRole,
|
||||
NumPagesRole,
|
||||
IdRole,
|
||||
Parent_IdRole,
|
||||
PathRole,
|
||||
HashRole,
|
||||
ReadColumnRole,
|
||||
IsBisRole,
|
||||
CurrentPageRole,
|
||||
RatingRole,
|
||||
HasBeenOpenedRole,
|
||||
CoverPathRole
|
||||
|
||||
};
|
||||
|
||||
enum Mode {
|
||||
Folder,
|
||||
Favorites,
|
||||
Reading,
|
||||
Label,
|
||||
ReadingList
|
||||
};
|
||||
|
||||
|
||||
|
||||
public slots:
|
||||
void remove(int row);
|
||||
void startTransaction();
|
||||
void finishTransaction();
|
||||
void updateRating(int rating, QModelIndex mi);
|
||||
|
||||
void addComicsToFavorites(const QList<qulonglong> &comicIds);
|
||||
void addComicsToLabel(const QList<qulonglong> &comicIds, qulonglong labelId);
|
||||
void addComicsToReadingList(const QList<qulonglong> &comicIds, qulonglong readingListId);
|
||||
|
||||
protected:
|
||||
|
||||
private:
|
||||
void setupModelData( QSqlQuery &sqlquery);
|
||||
void setupModelDataForList(QSqlQuery &sqlquery);
|
||||
ComicDB _getComic(const QModelIndex & mi);
|
||||
QList<ComicItem *> _data;
|
||||
|
||||
QString _databasePath;
|
||||
|
||||
QSqlDatabase dbTransaction;
|
||||
|
||||
bool enableResorting;
|
||||
Mode mode;
|
||||
qulonglong sourceId;
|
||||
|
||||
signals:
|
||||
void beforeReset();
|
||||
void reset();
|
||||
void isEmpty();
|
||||
void searchNumResults(int);
|
||||
void resortedIndexes(QList<int>);
|
||||
void newSelectedIndex(const QModelIndex &);
|
||||
};
|
||||
//! [0]
|
||||
|
||||
#endif
|
790
YACReaderLibrary/db/data_base_management.cpp
Normal file
790
YACReaderLibrary/db/data_base_management.cpp
Normal file
@ -0,0 +1,790 @@
|
||||
#include "data_base_management.h"
|
||||
|
||||
#include <QtCore>
|
||||
#include "library_creator.h"
|
||||
#include "check_new_version.h"
|
||||
|
||||
|
||||
static QString fields = "title ,"
|
||||
|
||||
"coverPage,"
|
||||
"numPages,"
|
||||
|
||||
"number,"
|
||||
"isBis,"
|
||||
"count,"
|
||||
|
||||
"volume,"
|
||||
"storyArc,"
|
||||
"arcNumber,"
|
||||
"arcCount,"
|
||||
|
||||
"genere,"
|
||||
|
||||
"writer,"
|
||||
"penciller,"
|
||||
"inker,"
|
||||
"colorist,"
|
||||
"letterer,"
|
||||
"coverArtist,"
|
||||
|
||||
"date,"
|
||||
"publisher,"
|
||||
"format,"
|
||||
"color,"
|
||||
"ageRating,"
|
||||
|
||||
"synopsis,"
|
||||
"characters,"
|
||||
"notes,"
|
||||
|
||||
"comicVineID,"
|
||||
|
||||
"hash"
|
||||
;
|
||||
|
||||
DataBaseManagement::DataBaseManagement()
|
||||
:QObject(),dataBasesList()
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
/*TreeModel * DataBaseManagement::newTreeModel(QString path)
|
||||
{
|
||||
//la consulta se ejecuta...
|
||||
QSqlQuery selectQuery(loadDatabase(path));
|
||||
selectQuery.setForwardOnly(true);
|
||||
selectQuery.exec("select * from folder order by parentId,name");
|
||||
//selectQuery.finish();
|
||||
return new TreeModel(selectQuery);
|
||||
}*/
|
||||
|
||||
QSqlDatabase DataBaseManagement::createDatabase(QString name, QString path)
|
||||
{
|
||||
return createDatabase(QDir::cleanPath(path) + "/" + name + ".ydb");
|
||||
}
|
||||
|
||||
QSqlDatabase DataBaseManagement::createDatabase(QString dest)
|
||||
{
|
||||
QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE",dest);
|
||||
db.setDatabaseName(dest);
|
||||
if (!db.open())
|
||||
qDebug() << db.lastError();
|
||||
else {
|
||||
qDebug() << db.tables();
|
||||
}
|
||||
|
||||
{
|
||||
QSqlQuery pragma("PRAGMA foreign_keys = ON",db);
|
||||
//pragma.finish();
|
||||
DataBaseManagement::createTables(db);
|
||||
|
||||
QSqlQuery query("INSERT INTO folder (parentId, name, path) "
|
||||
"VALUES (1,'root', '/')",db);
|
||||
}
|
||||
//query.finish();
|
||||
//db.close();
|
||||
|
||||
return db;
|
||||
}
|
||||
|
||||
QSqlDatabase DataBaseManagement::loadDatabase(QString path)
|
||||
{
|
||||
//TODO check path
|
||||
QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE",path);
|
||||
db.setDatabaseName(path+"/library.ydb");
|
||||
if (!db.open()) {
|
||||
//se devuelve una base de datos vacía e inválida
|
||||
|
||||
return QSqlDatabase();
|
||||
}
|
||||
QSqlQuery pragma("PRAGMA foreign_keys = ON",db);
|
||||
//pragma.finish();
|
||||
//devuelve la base de datos
|
||||
return db;
|
||||
}
|
||||
|
||||
QSqlDatabase DataBaseManagement::loadDatabaseFromFile(QString filePath)
|
||||
{
|
||||
//TODO check path
|
||||
QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE",filePath);
|
||||
db.setDatabaseName(filePath);
|
||||
if (!db.open()) {
|
||||
//se devuelve una base de datos vacía e inválida
|
||||
|
||||
return QSqlDatabase();
|
||||
}
|
||||
{
|
||||
QSqlQuery pragma("PRAGMA foreign_keys = ON",db);
|
||||
}
|
||||
//pragma.finish();
|
||||
//devuelve la base de datos
|
||||
return db;
|
||||
}
|
||||
|
||||
bool DataBaseManagement::createTables(QSqlDatabase & database)
|
||||
{
|
||||
bool success = true;
|
||||
|
||||
//FOLDER (representa una carpeta en disco)
|
||||
{
|
||||
QSqlQuery queryFolder(database);
|
||||
queryFolder.prepare("CREATE TABLE folder ("
|
||||
"id INTEGER PRIMARY KEY,"
|
||||
"parentId INTEGER NOT NULL,"
|
||||
"name TEXT NOT NULL,"
|
||||
"path TEXT NOT NULL,"
|
||||
//new 7.1 fields
|
||||
"finished BOOLEAN DEFAULT 0," //reading
|
||||
"completed BOOLEAN DEFAULT 1," //collecting
|
||||
//--
|
||||
"FOREIGN KEY(parentId) REFERENCES folder(id) ON DELETE CASCADE)");
|
||||
success = success && queryFolder.exec();
|
||||
|
||||
//COMIC INFO (representa la información de un cómic, cada cómic tendrá un idéntificador único formado por un hash sha1'de los primeros 512kb' + su tamaño en bytes)
|
||||
QSqlQuery queryComicInfo(database);
|
||||
queryComicInfo.prepare("CREATE TABLE comic_info ("
|
||||
"id INTEGER PRIMARY KEY,"
|
||||
"title TEXT,"
|
||||
|
||||
"coverPage INTEGER DEFAULT 1,"
|
||||
"numPages INTEGER,"
|
||||
|
||||
"number INTEGER,"
|
||||
"isBis BOOLEAN,"
|
||||
"count INTEGER,"
|
||||
|
||||
"volume TEXT,"
|
||||
"storyArc TEXT,"
|
||||
"arcNumber INTEGER,"
|
||||
"arcCount INTEGER,"
|
||||
|
||||
"genere TEXT,"
|
||||
|
||||
"writer TEXT,"
|
||||
"penciller TEXT,"
|
||||
"inker TEXT,"
|
||||
"colorist TEXT,"
|
||||
"letterer TEXT,"
|
||||
"coverArtist TEXT,"
|
||||
|
||||
"date TEXT," //dd/mm/yyyy --> se mostrará en 3 campos diferentes
|
||||
"publisher TEXT,"
|
||||
"format TEXT,"
|
||||
"color BOOLEAN,"
|
||||
"ageRating BOOLEAN,"
|
||||
|
||||
"synopsis TEXT,"
|
||||
"characters TEXT,"
|
||||
"notes TEXT,"
|
||||
|
||||
"hash TEXT UNIQUE NOT NULL,"
|
||||
"edited BOOLEAN DEFAULT 0,"
|
||||
"read BOOLEAN DEFAULT 0,"
|
||||
//new 7.0 fields
|
||||
|
||||
"hasBeenOpened BOOLEAN DEFAULT 0,"
|
||||
"rating INTEGER DEFAULT 0,"
|
||||
"currentPage INTEGER DEFAULT 1, "
|
||||
"bookmark1 INTEGER DEFAULT -1, "
|
||||
"bookmark2 INTEGER DEFAULT -1, "
|
||||
"bookmark3 INTEGER DEFAULT -1, "
|
||||
"brightness INTEGER DEFAULT -1, "
|
||||
"contrast INTEGER DEFAULT -1, "
|
||||
"gamma INTEGER DEFAULT -1, "
|
||||
//new 7.1 fields
|
||||
"comicVineID TEXT"
|
||||
|
||||
")");
|
||||
success = success && queryComicInfo.exec();
|
||||
//queryComicInfo.finish();
|
||||
|
||||
//COMIC (representa un cómic en disco, contiene el nombre de fichero)
|
||||
QSqlQuery queryComic(database);
|
||||
queryComic.prepare("CREATE TABLE comic (id INTEGER PRIMARY KEY, parentId INTEGER NOT NULL, comicInfoId INTEGER NOT NULL, fileName TEXT NOT NULL, path TEXT, FOREIGN KEY(parentId) REFERENCES folder(id) ON DELETE CASCADE, FOREIGN KEY(comicInfoId) REFERENCES comic_info(id))");
|
||||
success = success && queryComic.exec();
|
||||
//queryComic.finish();
|
||||
//DB INFO
|
||||
QSqlQuery queryDBInfo(database);
|
||||
queryDBInfo.prepare("CREATE TABLE db_info (version TEXT NOT NULL)");
|
||||
success = success && queryDBInfo.exec();
|
||||
//queryDBInfo.finish();
|
||||
|
||||
QSqlQuery query("INSERT INTO db_info (version) "
|
||||
"VALUES ('" VERSION "')",database);
|
||||
//query.finish();
|
||||
|
||||
//8.0> tables
|
||||
success = success && DataBaseManagement::createV8Tables(database);
|
||||
|
||||
}
|
||||
|
||||
return success;
|
||||
}
|
||||
|
||||
bool DataBaseManagement::createV8Tables(QSqlDatabase &database)
|
||||
{
|
||||
bool success = true;
|
||||
{
|
||||
//8.0> tables
|
||||
//LABEL
|
||||
QSqlQuery queryLabel(database);
|
||||
success = success && queryLabel.exec("CREATE TABLE label (id INTEGER PRIMARY KEY, "
|
||||
"name TEXT NOT NULL, "
|
||||
"color TEXT NOT NULL, "
|
||||
"ordering INTEGER NOT NULL); "); //order depends on the color
|
||||
|
||||
QSqlQuery queryIndexLabel(database);
|
||||
success = success && queryIndexLabel.exec("CREATE INDEX label_ordering_index ON label (ordering)");
|
||||
|
||||
//COMIC LABEL
|
||||
QSqlQuery queryComicLabel(database);
|
||||
success = success && queryComicLabel.exec("CREATE TABLE comic_label ("
|
||||
"comic_id INTEGER, "
|
||||
"label_id INTEGER, "
|
||||
"ordering INTEGER, " //TODO order????
|
||||
"FOREIGN KEY(label_id) REFERENCES label(id) ON DELETE CASCADE, "
|
||||
"FOREIGN KEY(comic_id) REFERENCES comic(id) ON DELETE CASCADE, "
|
||||
"PRIMARY KEY(label_id, comic_id))");
|
||||
|
||||
QSqlQuery queryIndexComicLabel(database);
|
||||
success = success && queryIndexComicLabel.exec("CREATE INDEX comic_label_ordering_index ON label (ordering)");
|
||||
|
||||
//READING LIST
|
||||
QSqlQuery queryReadingList(database);
|
||||
success = success && queryReadingList.exec("CREATE TABLE reading_list ("
|
||||
"id INTEGER PRIMARY KEY, "
|
||||
"parentId INTEGER, "
|
||||
"ordering INTEGER DEFAULT 0, " //only use it if the parentId is NULL
|
||||
"name TEXT NOT NULL, "
|
||||
"finished BOOLEAN DEFAULT 0, "
|
||||
"completed BOOLEAN DEFAULT 1, "
|
||||
"FOREIGN KEY(parentId) REFERENCES reading_list(id) ON DELETE CASCADE)");
|
||||
|
||||
QSqlQuery queryIndexReadingList(database);
|
||||
success = success && queryIndexReadingList.exec("CREATE INDEX reading_list_ordering_index ON label (ordering)");
|
||||
|
||||
//COMIC READING LIST
|
||||
QSqlQuery queryComicReadingList(database);
|
||||
success = success && queryComicReadingList.exec("CREATE TABLE comic_reading_list ("
|
||||
"reading_list_id INTEGER, "
|
||||
"comic_id INTEGER, "
|
||||
"ordering INTEGER, "
|
||||
"FOREIGN KEY(reading_list_id) REFERENCES reading_list(id) ON DELETE CASCADE, "
|
||||
"FOREIGN KEY(comic_id) REFERENCES comic(id) ON DELETE CASCADE, "
|
||||
"PRIMARY KEY(reading_list_id, comic_id))");
|
||||
|
||||
QSqlQuery queryIndexComicReadingList(database);
|
||||
success = success && queryIndexComicReadingList.exec("CREATE INDEX comic_reading_list_ordering_index ON label (ordering)");
|
||||
|
||||
//DEFAULT READING LISTS
|
||||
QSqlQuery queryDefaultReadingList(database);
|
||||
success = success && queryDefaultReadingList.exec("CREATE TABLE default_reading_list ("
|
||||
"id INTEGER PRIMARY KEY, "
|
||||
"name TEXT NOT NULL"
|
||||
//TODO icon????
|
||||
")");
|
||||
|
||||
//COMIC DEFAULT READING LISTS
|
||||
QSqlQuery queryComicDefaultReadingList(database);
|
||||
success = success && queryComicDefaultReadingList.exec("CREATE TABLE comic_default_reading_list ("
|
||||
"comic_id INTEGER, "
|
||||
"default_reading_list_id INTEGER, "
|
||||
"ordering INTEGER, " //order????
|
||||
"FOREIGN KEY(default_reading_list_id) REFERENCES default_reading_list(id) ON DELETE CASCADE, "
|
||||
"FOREIGN KEY(comic_id) REFERENCES comic(id) ON DELETE CASCADE,"
|
||||
"PRIMARY KEY(default_reading_list_id, comic_id))");
|
||||
|
||||
QSqlQuery queryIndexComicDefaultReadingList(database);
|
||||
success = success && queryIndexComicDefaultReadingList.exec("CREATE INDEX comic_default_reading_list_ordering_index ON label (ordering)");
|
||||
|
||||
//INSERT DEFAULT READING LISTS
|
||||
QSqlQuery queryInsertDefaultReadingList(database);
|
||||
//if(!queryInsertDefaultReadingList.prepare())
|
||||
|
||||
//1 Favorites
|
||||
//queryInsertDefaultReadingList.bindValue(":name", "Favorites");
|
||||
success = success && queryInsertDefaultReadingList.exec("INSERT INTO default_reading_list (name) VALUES (\"Favorites\")");
|
||||
|
||||
//Reading doesn't need its onw list
|
||||
|
||||
}
|
||||
return success;
|
||||
}
|
||||
|
||||
void DataBaseManagement::exportComicsInfo(QString source, QString dest)
|
||||
{
|
||||
//QSqlDatabase sourceDB = loadDatabase(source);
|
||||
QSqlDatabase destDB = loadDatabaseFromFile(dest);
|
||||
//sourceDB.open();
|
||||
{
|
||||
QSqlQuery attach(destDB);
|
||||
attach.prepare("ATTACH DATABASE '"+QDir().toNativeSeparators(dest) +"' AS dest;");
|
||||
//attach.bindValue(":dest",QDir().toNativeSeparators(dest));
|
||||
attach.exec();
|
||||
//attach.finish();
|
||||
|
||||
QSqlQuery attach2(destDB);
|
||||
attach2.prepare("ATTACH DATABASE '"+QDir().toNativeSeparators(source) +"' AS source;");
|
||||
attach2.exec();
|
||||
//attach2.finish();
|
||||
|
||||
//sourceDB.close();
|
||||
QSqlQuery queryDBInfo(destDB);
|
||||
queryDBInfo.prepare("CREATE TABLE dest.db_info (version TEXT NOT NULL)");
|
||||
queryDBInfo.exec();
|
||||
//queryDBInfo.finish();
|
||||
|
||||
/*QSqlQuery queryComicsInfo(sourceDB);
|
||||
queryComicsInfo.prepare("CREATE TABLE dest.comic_info (id INTEGER PRIMARY KEY, hash TEXT NOT NULL, edited BOOLEAN DEFAULT FALSE, title TEXT, read BOOLEAN)");
|
||||
queryComicsInfo.exec();*/
|
||||
|
||||
QSqlQuery query("INSERT INTO dest.db_info (version) "
|
||||
"VALUES ('" VERSION "')",destDB);
|
||||
//query.finish();
|
||||
|
||||
QSqlQuery exportData(destDB);
|
||||
exportData.prepare("create table dest.comic_info as select " + fields +
|
||||
" from source.comic_info where source.comic_info.edited = 1");
|
||||
exportData.exec();
|
||||
//exportData.finish();
|
||||
}
|
||||
|
||||
//sourceDB.close();
|
||||
destDB.close();
|
||||
QSqlDatabase::removeDatabase(dest);
|
||||
|
||||
}
|
||||
|
||||
bool DataBaseManagement::importComicsInfo(QString source, QString dest)
|
||||
{
|
||||
QString error;
|
||||
QString driver;
|
||||
QStringList hashes;
|
||||
|
||||
bool b = false;
|
||||
|
||||
QSqlDatabase sourceDB = loadDatabaseFromFile(source);
|
||||
QSqlDatabase destDB = loadDatabaseFromFile(dest);
|
||||
|
||||
{
|
||||
QSqlQuery pragma("PRAGMA synchronous=OFF",destDB);
|
||||
|
||||
|
||||
QSqlQuery newInfo(sourceDB);
|
||||
newInfo.prepare("SELECT * FROM comic_info");
|
||||
newInfo.exec();
|
||||
destDB.transaction();
|
||||
int cp;
|
||||
while (newInfo.next()) //cada tupla deberá ser insertada o actualizada
|
||||
{
|
||||
QSqlQuery update(destDB);
|
||||
update.prepare("UPDATE comic_info SET "
|
||||
"title = :title,"
|
||||
|
||||
"coverPage = :coverPage,"
|
||||
"numPages = :numPages,"
|
||||
|
||||
"number = :number,"
|
||||
"isBis = :isBis,"
|
||||
"count = :count,"
|
||||
|
||||
"volume = :volume,"
|
||||
"storyArc = :storyArc,"
|
||||
"arcNumber = :arcNumber,"
|
||||
"arcCount = :arcCount,"
|
||||
|
||||
"genere = :genere,"
|
||||
|
||||
"writer = :writer,"
|
||||
"penciller = :penciller,"
|
||||
"inker = :inker,"
|
||||
"colorist = :colorist,"
|
||||
"letterer = :letterer,"
|
||||
"coverArtist = :coverArtist,"
|
||||
|
||||
"date = :date,"
|
||||
"publisher = :publisher,"
|
||||
"format = :format,"
|
||||
"color = :color,"
|
||||
"ageRating = :ageRating,"
|
||||
|
||||
"synopsis = :synopsis,"
|
||||
"characters = :characters,"
|
||||
"notes = :notes,"
|
||||
|
||||
"edited = :edited,"
|
||||
|
||||
"comicVineID = :comicVineID"
|
||||
|
||||
" WHERE hash = :hash ");
|
||||
|
||||
QSqlQuery insert(destDB);
|
||||
insert.prepare("INSERT INTO comic_info "
|
||||
"(title,"
|
||||
"coverPage,"
|
||||
"numPages,"
|
||||
"number,"
|
||||
"isBis,"
|
||||
"count,"
|
||||
"volume,"
|
||||
"storyArc,"
|
||||
"arcNumber,"
|
||||
"arcCount,"
|
||||
"genere,"
|
||||
"writer,"
|
||||
"penciller,"
|
||||
"inker,"
|
||||
"colorist,"
|
||||
"letterer,"
|
||||
"coverArtist,"
|
||||
"date,"
|
||||
"publisher,"
|
||||
"format,"
|
||||
"color,"
|
||||
"ageRating,"
|
||||
"synopsis,"
|
||||
"characters,"
|
||||
"notes,"
|
||||
"read,"
|
||||
"edited,"
|
||||
"comicVineID,"
|
||||
"hash)"
|
||||
|
||||
"VALUES (:title,"
|
||||
":coverPage,"
|
||||
":numPages,"
|
||||
":number,"
|
||||
":isBis,"
|
||||
":count,"
|
||||
|
||||
":volume,"
|
||||
":storyArc,"
|
||||
":arcNumber,"
|
||||
":arcCount,"
|
||||
|
||||
":genere,"
|
||||
|
||||
":writer,"
|
||||
":penciller,"
|
||||
":inker,"
|
||||
":colorist,"
|
||||
":letterer,"
|
||||
":coverArtist,"
|
||||
|
||||
":date,"
|
||||
":publisher,"
|
||||
":format,"
|
||||
":color,"
|
||||
":ageRating,"
|
||||
|
||||
":synopsis,"
|
||||
":characters,"
|
||||
":notes,"
|
||||
|
||||
":read,"
|
||||
":edited,"
|
||||
":comicVineID,"
|
||||
|
||||
":hash )");
|
||||
|
||||
QSqlRecord record = newInfo.record();
|
||||
cp = record.value("coverPage").toInt();
|
||||
if(cp>1)
|
||||
{
|
||||
QSqlQuery checkCoverPage(destDB);
|
||||
checkCoverPage.prepare("SELECT coverPage FROM comic_info where hash = :hash");
|
||||
checkCoverPage.bindValue(":hash",record.value("hash").toString());
|
||||
checkCoverPage.exec();
|
||||
bool extract = false;
|
||||
if(checkCoverPage.next())
|
||||
{
|
||||
extract = checkCoverPage.record().value("coverPage").toInt() != cp;
|
||||
}
|
||||
if(extract)
|
||||
hashes.append(record.value("hash").toString());
|
||||
}
|
||||
|
||||
bindValuesFromRecord(record,update);
|
||||
|
||||
update.bindValue(":edited",1);
|
||||
|
||||
|
||||
update.exec();
|
||||
|
||||
if(update.numRowsAffected() == 0)
|
||||
{
|
||||
|
||||
bindValuesFromRecord(record,insert);
|
||||
insert.bindValue(":edited",1);
|
||||
insert.bindValue(":read",0);
|
||||
|
||||
insert.exec();
|
||||
|
||||
QString error1 = insert.lastError().databaseText();
|
||||
QString error2 = insert.lastError().driverText();
|
||||
|
||||
//QMessageBox::critical(NULL,"db",error1);
|
||||
//QMessageBox::critical(NULL,"driver",error2);
|
||||
}
|
||||
//update.finish();
|
||||
//insert.finish();
|
||||
}
|
||||
}
|
||||
|
||||
destDB.commit();
|
||||
QString hash;
|
||||
foreach(hash, hashes)
|
||||
{
|
||||
QSqlQuery getComic(destDB);
|
||||
getComic.prepare("SELECT c.path,ci.coverPage FROM comic c INNER JOIN comic_info ci ON (c.comicInfoId = ci.id) where ci.hash = :hash");
|
||||
getComic.bindValue(":hash",hash);
|
||||
getComic.exec();
|
||||
if(getComic.next())
|
||||
{
|
||||
QString basePath = QString(dest).remove("/.yacreaderlibrary/library.ydb");
|
||||
QString path = basePath + getComic.record().value("path").toString();
|
||||
int coverPage = getComic.record().value("coverPage").toInt();
|
||||
ThumbnailCreator tc(path,basePath+"/.yacreaderlibrary/covers/"+hash+".jpg",coverPage);
|
||||
tc.create();
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
destDB.close();
|
||||
sourceDB.close();
|
||||
QSqlDatabase::removeDatabase(source);
|
||||
QSqlDatabase::removeDatabase(dest);
|
||||
return b;
|
||||
|
||||
}
|
||||
//TODO fix these bindings
|
||||
void DataBaseManagement::bindValuesFromRecord(const QSqlRecord & record, QSqlQuery & query)
|
||||
{
|
||||
bindString("title",record,query);
|
||||
|
||||
bindInt("coverPage",record,query);
|
||||
bindInt("numPages",record,query);
|
||||
|
||||
bindInt("number",record,query);
|
||||
bindInt("isBis",record,query);
|
||||
bindInt("count",record,query);
|
||||
|
||||
bindString("volume",record,query);
|
||||
bindString("storyArc",record,query);
|
||||
bindInt("arcNumber",record,query);
|
||||
bindInt("arcCount",record,query);
|
||||
|
||||
bindString("genere",record,query);
|
||||
|
||||
bindString("writer",record,query);
|
||||
bindString("penciller",record,query);
|
||||
bindString("inker",record,query);
|
||||
bindString("colorist",record,query);
|
||||
bindString("letterer",record,query);
|
||||
bindString("coverArtist",record,query);
|
||||
|
||||
bindString("date",record,query);
|
||||
bindString("publisher",record,query);
|
||||
bindString("format",record,query);
|
||||
bindInt("color",record,query);
|
||||
bindString("ageRating",record,query);
|
||||
|
||||
bindString("synopsis",record,query);
|
||||
bindString("characters",record,query);
|
||||
bindString("notes",record,query);
|
||||
|
||||
bindString("comicVineID",record,query);
|
||||
|
||||
bindString("hash",record,query);
|
||||
}
|
||||
|
||||
bool DataBaseManagement::addColumns(const QString &tableName, const QStringList &columnDefs, const QSqlDatabase &db)
|
||||
{
|
||||
QString sql = "ALTER TABLE %1 ADD COLUMN %2";
|
||||
bool returnValue = true;
|
||||
|
||||
foreach(QString columnDef, columnDefs)
|
||||
{
|
||||
QSqlQuery alterTable(db);
|
||||
alterTable.prepare(sql.arg(tableName).arg(columnDef));
|
||||
//alterTableComicInfo.bindValue(":column_def",columnDef);
|
||||
alterTable.exec();
|
||||
returnValue = returnValue && (alterTable.numRowsAffected() > 0);
|
||||
}
|
||||
|
||||
return returnValue;
|
||||
}
|
||||
|
||||
void DataBaseManagement::bindString(const QString & name, const QSqlRecord & record, QSqlQuery & query)
|
||||
{
|
||||
if(!record.value(name).isNull())
|
||||
{
|
||||
query.bindValue(":"+name,record.value(name).toString());
|
||||
}
|
||||
}
|
||||
void DataBaseManagement::bindInt(const QString & name, const QSqlRecord & record, QSqlQuery & query)
|
||||
{
|
||||
if(!record.value(name).isNull())
|
||||
{
|
||||
query.bindValue(":"+name,record.value(name).toInt());
|
||||
}
|
||||
}
|
||||
|
||||
QString DataBaseManagement::checkValidDB(const QString & fullPath)
|
||||
{
|
||||
QSqlDatabase db = loadDatabaseFromFile(fullPath);
|
||||
QString versionString = "";
|
||||
if(db.isValid() && db.isOpen())
|
||||
{
|
||||
QSqlQuery version(db);
|
||||
version.prepare("SELECT * FROM db_info");
|
||||
version.exec();
|
||||
|
||||
if(version.next())
|
||||
versionString = version.record().value("version").toString();
|
||||
}
|
||||
|
||||
db.close();
|
||||
QSqlDatabase::removeDatabase(fullPath);
|
||||
return versionString;
|
||||
}
|
||||
|
||||
int DataBaseManagement::compareVersions(const QString & v1, const QString v2)
|
||||
{
|
||||
QStringList v1l = v1.split('.');
|
||||
QStringList v2l = v2.split('.');
|
||||
QList<int> v1il;
|
||||
QList<int> v2il;
|
||||
|
||||
foreach(QString s, v1l)
|
||||
v1il.append(s.toInt());
|
||||
|
||||
foreach(QString s,v2l)
|
||||
v2il.append(s.toInt());
|
||||
|
||||
for(int i=0;i<qMin(v1il.length(),v2il.length());i++)
|
||||
{
|
||||
if(v1il[i]<v2il[i])
|
||||
return -1;
|
||||
if(v1il[i]>v2il[i])
|
||||
return 1;
|
||||
}
|
||||
|
||||
if(v1il.length() < v2il.length())
|
||||
return -1;
|
||||
if(v1il.length() == v2il.length())
|
||||
return 0;
|
||||
if(v1il.length() > v2il.length())
|
||||
return 1;
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
bool DataBaseManagement::updateToCurrentVersion(const QString & fullPath)
|
||||
{
|
||||
bool pre7 = false;
|
||||
bool pre7_1 = false;
|
||||
bool pre8 = false;
|
||||
|
||||
if(compareVersions(DataBaseManagement::checkValidDB(fullPath),"7.0.0")<0)
|
||||
pre7 = true;
|
||||
if(compareVersions(DataBaseManagement::checkValidDB(fullPath),"7.0.3")<0)
|
||||
pre7_1 = true;
|
||||
if(compareVersions(DataBaseManagement::checkValidDB(fullPath),"8.0.0")<0)
|
||||
pre8 = true;
|
||||
|
||||
QSqlDatabase db = loadDatabaseFromFile(fullPath);
|
||||
bool returnValue = false;
|
||||
if(db.isValid() && db.isOpen())
|
||||
{
|
||||
QSqlQuery updateVersion(db);
|
||||
updateVersion.prepare("UPDATE db_info SET "
|
||||
"version = :version");
|
||||
updateVersion.bindValue(":version",VERSION);
|
||||
updateVersion.exec();
|
||||
|
||||
if(updateVersion.numRowsAffected() > 0)
|
||||
returnValue = true;
|
||||
|
||||
if(pre7) //TODO: execute only if previous version was < 7.0
|
||||
{
|
||||
//new 7.0 fields
|
||||
QStringList columnDefs;
|
||||
columnDefs << "hasBeenOpened BOOLEAN DEFAULT 0"
|
||||
<< "rating INTEGER DEFAULT 0"
|
||||
<< "currentPage INTEGER DEFAULT 1"
|
||||
<< "bookmark1 INTEGER DEFAULT -1"
|
||||
<< "bookmark2 INTEGER DEFAULT -1"
|
||||
<< "bookmark3 INTEGER DEFAULT -1"
|
||||
<< "brightness INTEGER DEFAULT -1"
|
||||
<< "contrast INTEGER DEFAULT -1"
|
||||
<< "gamma INTEGER DEFAULT -1";
|
||||
|
||||
returnValue = returnValue && addColumns("comic_info", columnDefs, db);
|
||||
}
|
||||
//TODO update hasBeenOpened value
|
||||
|
||||
if(pre7_1)
|
||||
{
|
||||
{
|
||||
QStringList columnDefs;
|
||||
columnDefs << "finished BOOLEAN DEFAULT 0"
|
||||
<< "completed BOOLEAN DEFAULT 1";
|
||||
returnValue = returnValue && addColumns("folder", columnDefs, db);
|
||||
}
|
||||
|
||||
{//comic_info
|
||||
QStringList columnDefs;
|
||||
columnDefs << "comicVineID TEXT DEFAULT NULL";
|
||||
returnValue = returnValue && addColumns("comic_info", columnDefs, db);
|
||||
}
|
||||
}
|
||||
|
||||
if(pre8)
|
||||
{
|
||||
returnValue = returnValue && createV8Tables(db);
|
||||
}
|
||||
}
|
||||
|
||||
db.close();
|
||||
QSqlDatabase::removeDatabase(fullPath);
|
||||
return returnValue;
|
||||
}
|
||||
|
||||
//COMICS_INFO_EXPORTER
|
||||
ComicsInfoExporter::ComicsInfoExporter()
|
||||
:QThread()
|
||||
{
|
||||
}
|
||||
|
||||
void ComicsInfoExporter::exportComicsInfo(QSqlDatabase & source, QSqlDatabase & dest)
|
||||
{
|
||||
Q_UNUSED(source)
|
||||
Q_UNUSED(dest)
|
||||
//TODO check this method
|
||||
}
|
||||
|
||||
void ComicsInfoExporter::run()
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
|
||||
//COMICS_INFO_IMPORTER
|
||||
ComicsInfoImporter::ComicsInfoImporter()
|
||||
:QThread()
|
||||
{
|
||||
}
|
||||
|
||||
void ComicsInfoImporter::importComicsInfo(QSqlDatabase & source, QSqlDatabase & dest)
|
||||
{
|
||||
Q_UNUSED(source)
|
||||
Q_UNUSED(dest)
|
||||
//TODO check this method
|
||||
}
|
||||
|
||||
void ComicsInfoImporter::run()
|
||||
{
|
||||
|
||||
}
|
62
YACReaderLibrary/db/data_base_management.h
Normal file
62
YACReaderLibrary/db/data_base_management.h
Normal file
@ -0,0 +1,62 @@
|
||||
#ifndef __DATA_BASE_MANAGEMENT_H
|
||||
#define __DATA_BASE_MANAGEMENT_H
|
||||
|
||||
#include <QtCore>
|
||||
#include <QtSql>
|
||||
#include <QSqlDatabase>
|
||||
|
||||
#include "folder_model.h"
|
||||
|
||||
class ComicsInfoExporter : public QThread
|
||||
{
|
||||
Q_OBJECT
|
||||
public:
|
||||
ComicsInfoExporter();
|
||||
void exportComicsInfo(QSqlDatabase & source, QSqlDatabase & dest);
|
||||
private:
|
||||
void run();
|
||||
};
|
||||
|
||||
class ComicsInfoImporter : public QThread
|
||||
{
|
||||
Q_OBJECT
|
||||
public:
|
||||
ComicsInfoImporter();
|
||||
void importComicsInfo(QSqlDatabase & source, QSqlDatabase & dest);
|
||||
private:
|
||||
void run();
|
||||
|
||||
};
|
||||
|
||||
class DataBaseManagement : public QObject
|
||||
{
|
||||
Q_OBJECT
|
||||
private:
|
||||
QList<QString> dataBasesList;
|
||||
static void bindString(const QString & name, const QSqlRecord & record, QSqlQuery & query);
|
||||
static void bindInt(const QString & name, const QSqlRecord & record, QSqlQuery & query);
|
||||
static void bindValuesFromRecord(const QSqlRecord & record, QSqlQuery & query);
|
||||
|
||||
static bool addColumns(const QString & tableName, const QStringList & columnDefs, const QSqlDatabase & db);
|
||||
|
||||
public:
|
||||
DataBaseManagement();
|
||||
//TreeModel * newTreeModel(QString path);
|
||||
//crea una base de datos y todas sus tablas
|
||||
static QSqlDatabase createDatabase(QString name, QString path);
|
||||
static QSqlDatabase createDatabase(QString dest);
|
||||
//carga una base de datos desde la ruta path
|
||||
static QSqlDatabase loadDatabase(QString path);
|
||||
static QSqlDatabase loadDatabaseFromFile(QString path);
|
||||
static bool createTables(QSqlDatabase & database);
|
||||
static bool createV8Tables(QSqlDatabase & database);
|
||||
|
||||
static void exportComicsInfo(QString source, QString dest);
|
||||
static bool importComicsInfo(QString source, QString dest);
|
||||
|
||||
static QString checkValidDB(const QString & fullPath); //retorna "" si la DB es inválida ó la versión si es válida.
|
||||
static int compareVersions(const QString & v1, const QString v2); //retorna <0 si v1 < v2, 0 si v1 = v2 y >0 si v1 > v2
|
||||
static bool updateToCurrentVersion(const QString & path);
|
||||
};
|
||||
|
||||
#endif
|
103
YACReaderLibrary/db/folder_item.cpp
Normal file
103
YACReaderLibrary/db/folder_item.cpp
Normal file
@ -0,0 +1,103 @@
|
||||
#include <QStringList>
|
||||
|
||||
#include "folder_item.h"
|
||||
#include "qnaturalsorting.h"
|
||||
|
||||
FolderItem::FolderItem(const QList<QVariant> &data, FolderItem *parent)
|
||||
{
|
||||
parentItem = parent;
|
||||
itemData = data;
|
||||
}
|
||||
|
||||
FolderItem::~FolderItem()
|
||||
{
|
||||
qDeleteAll(childItems);
|
||||
}
|
||||
|
||||
void FolderItem::appendChild(FolderItem *item)
|
||||
{
|
||||
item->parentItem = this;
|
||||
|
||||
if(childItems.isEmpty())
|
||||
childItems.append(item);
|
||||
else
|
||||
{
|
||||
FolderItem * last = childItems.back();
|
||||
QString nameLast = last->data(1).toString(); //TODO usar info name si est<73> disponible, sino el nombre del fichero.....
|
||||
QString nameCurrent = item->data(1).toString();
|
||||
QList<FolderItem *>::iterator i;
|
||||
i = childItems.end();
|
||||
i--;
|
||||
while (naturalSortLessThanCI(nameCurrent,nameLast) && i != childItems.begin())
|
||||
{
|
||||
i--;
|
||||
nameLast = (*i)->data(1).toString();
|
||||
}
|
||||
if(!naturalSortLessThanCI(nameCurrent,nameLast)) //si se ha encontrado un elemento menor que current, se inserta justo despu<70>s
|
||||
childItems.insert(++i,item);
|
||||
else
|
||||
childItems.insert(i,item);
|
||||
|
||||
}
|
||||
|
||||
//childItems.append(item);
|
||||
}
|
||||
|
||||
FolderItem *FolderItem::child(int row)
|
||||
{
|
||||
return childItems.value(row);
|
||||
}
|
||||
|
||||
int FolderItem::childCount() const
|
||||
{
|
||||
return childItems.count();
|
||||
}
|
||||
|
||||
int FolderItem::columnCount() const
|
||||
{
|
||||
return itemData.count();
|
||||
}
|
||||
|
||||
QVariant FolderItem::data(int column) const
|
||||
{
|
||||
return itemData.value(column);
|
||||
}
|
||||
|
||||
void FolderItem::setData(int column, const QVariant & value)
|
||||
{
|
||||
itemData[column] = value;
|
||||
}
|
||||
|
||||
void FolderItem::removeChild(int childIndex)
|
||||
{
|
||||
childItems.removeAt(childIndex);
|
||||
}
|
||||
|
||||
void FolderItem::clearChildren()
|
||||
{
|
||||
qDeleteAll(childItems);
|
||||
childItems.clear();
|
||||
}
|
||||
|
||||
QList<FolderItem *> FolderItem::children()
|
||||
{
|
||||
return childItems;
|
||||
}
|
||||
|
||||
FolderItem *FolderItem::parent()
|
||||
{
|
||||
return parentItem;
|
||||
}
|
||||
|
||||
int FolderItem::row() const
|
||||
{
|
||||
if (parentItem)
|
||||
return parentItem->childItems.indexOf(const_cast<FolderItem*>(this));
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
QList<QVariant> FolderItem::getData() const
|
||||
{
|
||||
return itemData;
|
||||
}
|
77
YACReaderLibrary/db/folder_item.h
Normal file
77
YACReaderLibrary/db/folder_item.h
Normal file
@ -0,0 +1,77 @@
|
||||
/****************************************************************************
|
||||
**
|
||||
** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
|
||||
** All rights reserved.
|
||||
** Contact: Nokia Corporation (qt-info@nokia.com)
|
||||
**
|
||||
** This file is part of the examples of the Qt Toolkit.
|
||||
**
|
||||
** $QT_BEGIN_LICENSE:BSD$
|
||||
** You may use this file under the terms of the BSD license as follows:
|
||||
**
|
||||
** "Redistribution and use in source and binary forms, with or without
|
||||
** modification, are permitted provided that the following conditions are
|
||||
** met:
|
||||
** * Redistributions of source code must retain the above copyright
|
||||
** notice, this list of conditions and the following disclaimer.
|
||||
** * Redistributions in binary form must reproduce the above copyright
|
||||
** notice, this list of conditions and the following disclaimer in
|
||||
** the documentation and/or other materials provided with the
|
||||
** distribution.
|
||||
** * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor
|
||||
** the names of its contributors may be used to endorse or promote
|
||||
** products derived from this software without specific prior written
|
||||
** permission.
|
||||
**
|
||||
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
|
||||
** $QT_END_LICENSE$
|
||||
**
|
||||
****************************************************************************/
|
||||
|
||||
#ifndef TREEITEM_H
|
||||
#define TREEITEM_H
|
||||
|
||||
#include <QList>
|
||||
#include <QVariant>
|
||||
#include <QModelIndex>
|
||||
|
||||
class FolderItem
|
||||
{
|
||||
public:
|
||||
FolderItem(const QList<QVariant> &data, FolderItem *parent = 0);
|
||||
~FolderItem();
|
||||
|
||||
void appendChild(FolderItem *child);
|
||||
|
||||
FolderItem *child(int row);
|
||||
int childCount() const;
|
||||
int columnCount() const;
|
||||
QVariant data(int column) const;
|
||||
QList<QVariant> getData() const;
|
||||
int row() const;
|
||||
FolderItem *parent();
|
||||
FolderItem *parentItem;
|
||||
unsigned long long int id;
|
||||
QList<QString> comicNames;
|
||||
FolderItem * originalItem;
|
||||
void setData(int column, const QVariant &value);
|
||||
void removeChild(int childIndex);
|
||||
void clearChildren();
|
||||
QList<FolderItem*> children();
|
||||
private:
|
||||
QList<FolderItem*> childItems;
|
||||
QList<QVariant> itemData;
|
||||
};
|
||||
//! [0]
|
||||
|
||||
#endif
|
786
YACReaderLibrary/db/folder_model.cpp
Normal file
786
YACReaderLibrary/db/folder_model.cpp
Normal file
@ -0,0 +1,786 @@
|
||||
/****************************************************************************
|
||||
**
|
||||
** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
|
||||
** All rights reserved.
|
||||
** Contact: Nokia Corporation (qt-info@nokia.com)
|
||||
**
|
||||
** This file is part of the examples of the Qt Toolkit.
|
||||
**
|
||||
** $QT_BEGIN_LICENSE:BSD$
|
||||
** You may use this file under the terms of the BSD license as follows:
|
||||
**
|
||||
** "Redistribution and use in source and binary forms, with or without
|
||||
** modification, are permitted provided that the following conditions are
|
||||
** met:
|
||||
** * Redistributions of source code must retain the above copyright
|
||||
** notice, this list of conditions and the following disclaimer.
|
||||
** * Redistributions in binary form must reproduce the above copyright
|
||||
** notice, this list of conditions and the following disclaimer in
|
||||
** the documentation and/or other materials provided with the
|
||||
** distribution.
|
||||
** * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor
|
||||
** the names of its contributors may be used to endorse or promote
|
||||
** products derived from this software without specific prior written
|
||||
** permission.
|
||||
**
|
||||
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
|
||||
** $QT_END_LICENSE$
|
||||
**
|
||||
****************************************************************************/
|
||||
|
||||
/*
|
||||
treemodel.cpp
|
||||
|
||||
Provides a simple tree model to show how to create and use hierarchical
|
||||
models.
|
||||
*/
|
||||
|
||||
#include <QtGui>
|
||||
|
||||
|
||||
#include "folder_item.h"
|
||||
#include "folder_model.h"
|
||||
#include "data_base_management.h"
|
||||
#include "folder.h"
|
||||
#include "db_helper.h"
|
||||
#include "qnaturalsorting.h"
|
||||
#include "yacreader_global_gui.h"
|
||||
#include "QsLog.h"
|
||||
|
||||
#ifdef Q_OS_MAC
|
||||
#include <QFileIconProvider>
|
||||
QIcon finishedFolderIcon;
|
||||
void drawMacOSXFinishedFolderIcon()
|
||||
{
|
||||
QIcon ico = QFileIconProvider().icon(QFileIconProvider::Folder);
|
||||
QPixmap pixNormalOff = ico.pixmap(16,16, QIcon::Normal, QIcon::Off);
|
||||
QPixmap pixNormalOn = ico.pixmap(16,16, QIcon::Normal, QIcon::On);
|
||||
QPixmap pixSelectedOff = ico.pixmap(16,16, QIcon::Selected, QIcon::Off);
|
||||
QPixmap pixSelectedOn = ico.pixmap(16,16, QIcon::Selected, QIcon::On);
|
||||
QPixmap tick(":/images/folder_finished_macosx.png");
|
||||
|
||||
|
||||
{
|
||||
QPainter p(&pixNormalOff);
|
||||
p.drawPixmap(4,7,tick);
|
||||
}
|
||||
finishedFolderIcon.addPixmap(pixNormalOff, QIcon::Normal, QIcon::Off);
|
||||
|
||||
{
|
||||
QPainter p(&pixNormalOn);
|
||||
p.drawPixmap(4,7,tick);
|
||||
}
|
||||
finishedFolderIcon.addPixmap(pixNormalOn, QIcon::Normal, QIcon::On);
|
||||
|
||||
{
|
||||
QPainter p(&pixSelectedOff);
|
||||
p.drawPixmap(4,7,tick);
|
||||
}
|
||||
finishedFolderIcon.addPixmap(pixSelectedOff, QIcon::Selected, QIcon::Off);
|
||||
|
||||
{
|
||||
QPainter p(&pixSelectedOn);
|
||||
p.drawPixmap(4,7,tick);
|
||||
}
|
||||
finishedFolderIcon.addPixmap(pixSelectedOn, QIcon::Selected, QIcon::On);
|
||||
}
|
||||
#endif
|
||||
|
||||
#define ROOT 1
|
||||
|
||||
FolderModel::FolderModel(QObject *parent)
|
||||
: QAbstractItemModel(parent),rootItem(0)
|
||||
{
|
||||
connect(this,SIGNAL(beforeReset()),this,SIGNAL(modelAboutToBeReset()));
|
||||
connect(this,SIGNAL(reset()),this,SIGNAL(modelReset()));
|
||||
}
|
||||
|
||||
//! [0]
|
||||
FolderModel::FolderModel( QSqlQuery &sqlquery, QObject *parent)
|
||||
: QAbstractItemModel(parent),rootItem(0)
|
||||
{
|
||||
//lo m<>s probable es que el nodo ra<72>z no necesite tener informaci<63>n
|
||||
QList<QVariant> rootData;
|
||||
rootData << "root"; //id 0, padre 0, title "root" (el id, y el id del padre van a ir en la clase TreeItem)
|
||||
rootItem = new FolderItem(rootData);
|
||||
rootItem->id = ROOT;
|
||||
rootItem->parentItem = 0;
|
||||
setupModelData(sqlquery, rootItem);
|
||||
//sqlquery.finish();
|
||||
}
|
||||
//! [0]
|
||||
|
||||
//! [1]
|
||||
FolderModel::~FolderModel()
|
||||
{
|
||||
if(rootItem != 0)
|
||||
delete rootItem;
|
||||
}
|
||||
//! [1]
|
||||
|
||||
//! [2]
|
||||
int FolderModel::columnCount(const QModelIndex &parent) const
|
||||
{
|
||||
if (parent.isValid())
|
||||
return static_cast<FolderItem*>(parent.internalPointer())->columnCount();
|
||||
else
|
||||
return rootItem->columnCount();
|
||||
}
|
||||
//! [2]
|
||||
|
||||
//! [3]
|
||||
QVariant FolderModel::data(const QModelIndex &index, int role) const
|
||||
{
|
||||
if (!index.isValid())
|
||||
return QVariant();
|
||||
|
||||
FolderItem *item = static_cast<FolderItem*>(index.internalPointer());
|
||||
|
||||
if (role == Qt::DecorationRole)
|
||||
|
||||
#ifdef Q_OS_MAC
|
||||
if(item->data(FolderModel::Finished).toBool()){
|
||||
if(finishedFolderIcon.isNull()){
|
||||
drawMacOSXFinishedFolderIcon();
|
||||
}
|
||||
|
||||
return QVariant(finishedFolderIcon);
|
||||
}
|
||||
else {
|
||||
return QVariant(QFileIconProvider().icon(QFileIconProvider::Folder));
|
||||
}
|
||||
#else
|
||||
if(item->data(FolderModel::Finished).toBool())
|
||||
return QVariant(YACReader::noHighlightedIcon(":/images/sidebar/folder_finished.png"));
|
||||
else
|
||||
return QVariant(YACReader::noHighlightedIcon(":/images/sidebar/folder.png"));
|
||||
#endif
|
||||
|
||||
if(role == FolderModel::CompletedRole)
|
||||
return item->data(FolderModel::Completed);
|
||||
|
||||
if(role == FolderModel::FinishedRole)
|
||||
return item->data(FolderModel::Finished);
|
||||
|
||||
if (role != Qt::DisplayRole)
|
||||
return QVariant();
|
||||
|
||||
|
||||
|
||||
return item->data(index.column());
|
||||
}
|
||||
//! [3]
|
||||
|
||||
//! [4]
|
||||
Qt::ItemFlags FolderModel::flags(const QModelIndex &index) const
|
||||
{
|
||||
if (!index.isValid())
|
||||
return 0;
|
||||
|
||||
return Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsDropEnabled | Qt::ItemIsDragEnabled;
|
||||
}
|
||||
//! [4]
|
||||
|
||||
//! [5]
|
||||
QVariant FolderModel::headerData(int section, Qt::Orientation orientation,
|
||||
int role) const
|
||||
{
|
||||
if (orientation == Qt::Horizontal && role == Qt::DisplayRole)
|
||||
return rootItem->data(section);
|
||||
|
||||
return QVariant();
|
||||
}
|
||||
//! [5]
|
||||
|
||||
//! [6]
|
||||
QModelIndex FolderModel::index(int row, int column, const QModelIndex &parent)
|
||||
const
|
||||
{
|
||||
if (!hasIndex(row, column, parent))
|
||||
return QModelIndex();
|
||||
|
||||
FolderItem *parentItem;
|
||||
|
||||
if (!parent.isValid())
|
||||
parentItem = rootItem;
|
||||
else
|
||||
parentItem = static_cast<FolderItem*>(parent.internalPointer());
|
||||
|
||||
FolderItem *childItem = parentItem->child(row);
|
||||
if (childItem)
|
||||
return createIndex(row, column, childItem);
|
||||
else
|
||||
return QModelIndex();
|
||||
}
|
||||
//! [6]
|
||||
|
||||
//! [7]
|
||||
QModelIndex FolderModel::parent(const QModelIndex &index) const
|
||||
{
|
||||
if (!index.isValid())
|
||||
return QModelIndex();
|
||||
|
||||
FolderItem *childItem = static_cast<FolderItem*>(index.internalPointer());
|
||||
FolderItem *parentItem = childItem->parent();
|
||||
|
||||
if (parentItem == rootItem)
|
||||
return QModelIndex();
|
||||
|
||||
return createIndex(parentItem->row(), 0, parentItem);
|
||||
}
|
||||
//! [7]
|
||||
|
||||
/*
|
||||
QModelIndex FolderModel::indexFromItem(FolderItem * item,int column)
|
||||
{
|
||||
//if(item->parent() != 0)
|
||||
// return index(item->row(),column,parent(indexFromItem(item->parent(),column-1)));
|
||||
//else
|
||||
// return index(item->row(),0,QModelIndex());
|
||||
return createIndex(item->row(), column, item);
|
||||
}*/
|
||||
|
||||
|
||||
//! [8]
|
||||
int FolderModel::rowCount(const QModelIndex &parent) const
|
||||
{
|
||||
FolderItem *parentItem;
|
||||
if (parent.column() > 0)
|
||||
return 0;
|
||||
|
||||
if (!parent.isValid())
|
||||
parentItem = rootItem;
|
||||
else
|
||||
parentItem = static_cast<FolderItem*>(parent.internalPointer());
|
||||
|
||||
return parentItem->childCount();
|
||||
}
|
||||
//! [8]
|
||||
|
||||
void FolderModel::setupModelData(QString path)
|
||||
{
|
||||
beginResetModel();
|
||||
if(rootItem != 0)
|
||||
delete rootItem; //TODO comprobar que se libera bien la memoria
|
||||
|
||||
rootItem = 0;
|
||||
|
||||
//inicializar el nodo ra<72>z
|
||||
QList<QVariant> rootData;
|
||||
rootData << "root"; //id 0, padre 0, title "root" (el id, y el id del padre van a ir en la clase TreeItem)
|
||||
rootItem = new FolderItem(rootData);
|
||||
rootItem->id = ROOT;
|
||||
rootItem->parentItem = 0;
|
||||
|
||||
//cargar la base de datos
|
||||
_databasePath = path;
|
||||
QSqlDatabase db = DataBaseManagement::loadDatabase(path);
|
||||
//crear la consulta
|
||||
{
|
||||
QSqlQuery selectQuery("select * from folder where id <> 1 order by parentId,name",db);
|
||||
|
||||
setupModelData(selectQuery,rootItem);
|
||||
}
|
||||
//selectQuery.finish();
|
||||
db.close();
|
||||
QSqlDatabase::removeDatabase(path);
|
||||
endResetModel();
|
||||
|
||||
}
|
||||
|
||||
|
||||
void FolderModel::setupModelData(QSqlQuery &sqlquery, FolderItem *parent)
|
||||
{
|
||||
//64 bits para la primary key, es decir la misma precisi<73>n que soporta sqlit 2^64
|
||||
//el diccionario permitir<69> encontrar cualquier nodo del <20>rbol r<>pidamente, de forma que a<>adir un hijo a un padre sea O(1)
|
||||
items.clear();
|
||||
//se a<>ade el nodo 0
|
||||
items.insert(parent->id,parent);
|
||||
|
||||
while (sqlquery.next()) {
|
||||
QList<QVariant> data;
|
||||
QSqlRecord record = sqlquery.record();
|
||||
|
||||
data << record.value("name").toString();
|
||||
data << record.value("path").toString();
|
||||
data << record.value("finished").toBool();
|
||||
data << record.value("completed").toBool();
|
||||
FolderItem * item = new FolderItem(data);
|
||||
|
||||
item->id = record.value("id").toULongLong();
|
||||
//la inserci<63>n de hijos se hace de forma ordenada
|
||||
FolderItem * parent = items.value(record.value("parentId").toULongLong());
|
||||
//if(parent !=0) //TODO if parent==0 the parent of item was removed from the DB and delete on cascade didn't work, ERROR.
|
||||
parent->appendChild(item);
|
||||
//se a<>ade el item al map, de forma que se pueda encontrar como padre en siguientes iteraciones
|
||||
items.insert(item->id,item);
|
||||
}
|
||||
}
|
||||
|
||||
void FolderModel::updateFolderModelData(QSqlQuery &sqlquery, FolderItem *parent)
|
||||
{
|
||||
Q_UNUSED(parent);
|
||||
|
||||
while (sqlquery.next()) {
|
||||
QLOG_DEBUG () << "habia next";
|
||||
QList<QVariant> data;
|
||||
QSqlRecord record = sqlquery.record();
|
||||
|
||||
data << record.value("name").toString();
|
||||
data << record.value("path").toString();
|
||||
data << record.value("finished").toBool();
|
||||
data << record.value("completed").toBool();
|
||||
FolderItem * item = new FolderItem(data);
|
||||
|
||||
item->id = record.value("id").toULongLong();
|
||||
//la inserci<63>n de hijos se hace de forma ordenada
|
||||
FolderItem * parent = items.value(record.value("parentId").toULongLong());
|
||||
if(parent !=0) //TODO if parent==0 the parent of item was removed from the DB and delete on cascade didn't work, ERROR.
|
||||
parent->appendChild(item);
|
||||
//se a<>ade el item al map, de forma que se pueda encontrar como padre en siguientes iteraciones
|
||||
items.insert(item->id,item);
|
||||
}
|
||||
}
|
||||
|
||||
QString FolderModel::getDatabase()
|
||||
{
|
||||
return _databasePath;
|
||||
}
|
||||
|
||||
QString FolderModel::getFolderPath(const QModelIndex &folder)
|
||||
{
|
||||
if(!folder.isValid()) //root folder
|
||||
return "/";
|
||||
return static_cast<FolderItem*>(folder.internalPointer())->data(FolderModel::Path).toString();
|
||||
}
|
||||
|
||||
/*
|
||||
void FolderModel::resetFilter()
|
||||
{
|
||||
beginResetModel();
|
||||
filter = "";
|
||||
includeComics = false;
|
||||
//TODO hay que liberar la memoria reservada para el filtrado
|
||||
//items.clear();
|
||||
filteredItems.clear();
|
||||
FolderItem * root = rootItem;
|
||||
rootItem = rootBeforeFilter; //TODO si no se aplica el filtro previamente, esto invalidar<61>a en modelo
|
||||
if(root !=0)
|
||||
delete root;
|
||||
|
||||
rootBeforeFilter = 0;
|
||||
filterEnabled = false;
|
||||
endResetModel();
|
||||
|
||||
|
||||
}*/
|
||||
|
||||
void FolderModel::updateFolderCompletedStatus(const QModelIndexList &list, bool status)
|
||||
{
|
||||
QSqlDatabase db = DataBaseManagement::loadDatabase(_databasePath);
|
||||
db.transaction();
|
||||
foreach (QModelIndex mi, list)
|
||||
{
|
||||
FolderItem * item = static_cast<FolderItem*>(mi.internalPointer());
|
||||
item->setData(FolderModel::Completed,status);
|
||||
|
||||
Folder f = DBHelper::loadFolder(item->id,db);
|
||||
f.setCompleted(status);
|
||||
DBHelper::update(f,db);
|
||||
}
|
||||
db.commit();
|
||||
db.close();
|
||||
QSqlDatabase::removeDatabase(_databasePath);
|
||||
|
||||
emit dataChanged(index(list.first().row(),FolderModel::Name),index(list.last().row(),FolderModel::Completed));
|
||||
}
|
||||
|
||||
void FolderModel::updateFolderFinishedStatus(const QModelIndexList &list, bool status)
|
||||
{
|
||||
QSqlDatabase db = DataBaseManagement::loadDatabase(_databasePath);
|
||||
db.transaction();
|
||||
foreach (QModelIndex mi, list)
|
||||
{
|
||||
FolderItem * item = static_cast<FolderItem*>(mi.internalPointer());
|
||||
item->setData(FolderModel::Finished,status);
|
||||
|
||||
Folder f = DBHelper::loadFolder(item->id,db);
|
||||
f.setFinished(status);
|
||||
DBHelper::update(f,db);
|
||||
}
|
||||
db.commit();
|
||||
db.close();
|
||||
QSqlDatabase::removeDatabase(_databasePath);
|
||||
|
||||
emit dataChanged(index(list.first().row(),FolderModel::Name),index(list.last().row(),FolderModel::Completed));
|
||||
}
|
||||
|
||||
QStringList FolderModel::getSubfoldersNames(const QModelIndex &mi)
|
||||
{
|
||||
QStringList result;
|
||||
qulonglong id = 1;
|
||||
if(mi.isValid()){
|
||||
FolderItem * item = static_cast<FolderItem*>(mi.internalPointer());
|
||||
id = item->id;
|
||||
}
|
||||
|
||||
QSqlDatabase db = DataBaseManagement::loadDatabase(_databasePath);
|
||||
db.transaction();
|
||||
|
||||
result = DBHelper::loadSubfoldersNames(id,db);
|
||||
|
||||
db.commit();
|
||||
db.close();
|
||||
QSqlDatabase::removeDatabase(_databasePath);
|
||||
|
||||
//TODO sort result))
|
||||
qSort(result.begin(),result.end(),naturalSortLessThanCI);
|
||||
return result;
|
||||
}
|
||||
|
||||
void FolderModel::fetchMoreFromDB(const QModelIndex &parent)
|
||||
{
|
||||
FolderItem * item;
|
||||
if(parent.isValid())
|
||||
item = static_cast<FolderItem*>(parent.internalPointer());
|
||||
else
|
||||
item = rootItem;
|
||||
|
||||
//Remove all children
|
||||
if(item->childCount() > 0)
|
||||
{
|
||||
beginRemoveRows(parent, 0, item->childCount()-1);
|
||||
item->clearChildren();
|
||||
endRemoveRows();
|
||||
}
|
||||
|
||||
QSqlDatabase db = DataBaseManagement::loadDatabase(_databasePath);
|
||||
|
||||
QList<FolderItem *> items;
|
||||
QList<FolderItem *> nextLevelItems;
|
||||
|
||||
QSqlQuery selectQuery(db);
|
||||
selectQuery.prepare("select * from folder where id <> 1 and parentId = :parentId order by parentId,name");
|
||||
|
||||
items << item;
|
||||
bool firstLevelUpdated = false;
|
||||
while(items.size() > 0)
|
||||
{
|
||||
nextLevelItems.clear();
|
||||
foreach(FolderItem * item, items)
|
||||
{
|
||||
QLOG_DEBUG() << "ID " << item->id;
|
||||
selectQuery.bindValue(":parentId", item->id);
|
||||
|
||||
selectQuery.exec();
|
||||
|
||||
if(!firstLevelUpdated)
|
||||
{
|
||||
//NO size support
|
||||
int numResults = 0;
|
||||
while(selectQuery.next())
|
||||
numResults++;
|
||||
|
||||
if(!selectQuery.seek(-1))
|
||||
selectQuery.exec();
|
||||
//END no size support
|
||||
|
||||
beginInsertRows(parent, 0, numResults-1);
|
||||
}
|
||||
|
||||
updateFolderModelData(selectQuery,item);
|
||||
|
||||
if(!firstLevelUpdated)
|
||||
{
|
||||
endInsertRows();
|
||||
firstLevelUpdated = true;
|
||||
}
|
||||
|
||||
nextLevelItems << item->children();
|
||||
|
||||
}
|
||||
|
||||
items.clear();
|
||||
items = nextLevelItems;
|
||||
}
|
||||
|
||||
QLOG_DEBUG() << "item->childCount()-1" << item->childCount()-1;
|
||||
|
||||
|
||||
db.close();
|
||||
QSqlDatabase::removeDatabase(_databasePath);
|
||||
}
|
||||
|
||||
QModelIndex FolderModel::addFolderAtParent(const QString &folderName, const QModelIndex &parent)
|
||||
{
|
||||
FolderItem * parentItem;
|
||||
|
||||
if(parent.isValid())
|
||||
parentItem = static_cast<FolderItem*>(parent.internalPointer());
|
||||
else
|
||||
parentItem = rootItem;
|
||||
|
||||
Folder newFolder;
|
||||
newFolder.name = folderName;
|
||||
newFolder.parentId = parentItem->id;
|
||||
newFolder.path = parentItem->data(1).toString() + "/" + folderName;
|
||||
|
||||
QSqlDatabase db = DataBaseManagement::loadDatabase(_databasePath);
|
||||
newFolder.id = DBHelper::insert(&newFolder, db);
|
||||
QSqlDatabase::removeDatabase(_databasePath);
|
||||
|
||||
int destRow = 0;
|
||||
|
||||
QList<QVariant> data;
|
||||
data << newFolder.name;
|
||||
data << newFolder.path;
|
||||
data << false; //finished
|
||||
data << true; //completed
|
||||
|
||||
FolderItem * item = new FolderItem(data);
|
||||
item->id = newFolder.id;
|
||||
|
||||
beginInsertRows(parent,0,0); //TODO calculate the destRow before inserting the new child
|
||||
|
||||
parentItem->appendChild(item);
|
||||
destRow = parentItem->children().indexOf(item); //TODO optimize this, appendChild should return the index of the new item
|
||||
items.insert(item->id,item);
|
||||
|
||||
endInsertRows();
|
||||
|
||||
return index(destRow,0,parent);
|
||||
}
|
||||
|
||||
void FolderModel::deleteFolder(const QModelIndex &mi)
|
||||
{
|
||||
beginRemoveRows(mi.parent(),mi.row(),mi.row());
|
||||
|
||||
FolderItem * item = static_cast<FolderItem*>(mi.internalPointer());
|
||||
|
||||
FolderItem * parent = item->parent();
|
||||
parent->removeChild(mi.row());
|
||||
|
||||
Folder f;
|
||||
f.setId(item->id);
|
||||
|
||||
QSqlDatabase db = DataBaseManagement::loadDatabase(_databasePath);
|
||||
DBHelper::removeFromDB(&f,db);
|
||||
QSqlDatabase::removeDatabase(_databasePath);
|
||||
|
||||
endRemoveRows();
|
||||
}
|
||||
|
||||
|
||||
//PROXY
|
||||
|
||||
FolderModelProxy::FolderModelProxy(QObject *parent)
|
||||
:QSortFilterProxyModel(parent),rootItem(0),filterEnabled(false),filter(""),includeComics(true)
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
FolderModelProxy::~FolderModelProxy()
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
bool FolderModelProxy::filterAcceptsRow(int source_row, const QModelIndex &source_parent) const
|
||||
{
|
||||
if(!filterEnabled)
|
||||
return true;
|
||||
|
||||
FolderItem * parent = static_cast<FolderItem *>(source_parent.internalPointer());
|
||||
|
||||
if(parent == 0)
|
||||
parent = static_cast<FolderModel *>(sourceModel())->rootItem;
|
||||
|
||||
FolderItem * item = parent->children().at(source_row);
|
||||
|
||||
return filteredItems.contains(item->id);
|
||||
}
|
||||
|
||||
void FolderModelProxy::setFilter(const YACReader::SearchModifiers modifier, QString filter, bool includeComics)
|
||||
{
|
||||
clear();
|
||||
this->filter = filter;
|
||||
this->includeComics = includeComics;
|
||||
this->modifier = modifier;
|
||||
filterEnabled = true;
|
||||
setupFilteredModelData();
|
||||
}
|
||||
|
||||
void FolderModelProxy::setupFilteredModelData()
|
||||
{
|
||||
beginResetModel();
|
||||
|
||||
//TODO hay que liberar memoria de anteriores filtrados
|
||||
|
||||
//inicializar el nodo ra<72>z
|
||||
|
||||
if(rootItem != 0)
|
||||
delete rootItem; //TODO comprobar que se libera bien la memoria
|
||||
|
||||
rootItem = 0;
|
||||
|
||||
//inicializar el nodo ra<72>z
|
||||
QList<QVariant> rootData;
|
||||
rootData << "root";
|
||||
rootItem = new FolderItem(rootData);
|
||||
rootItem->id = ROOT;
|
||||
rootItem->parentItem = 0;
|
||||
|
||||
FolderModel * model = static_cast<FolderModel *>(sourceModel());
|
||||
|
||||
//cargar la base de datos
|
||||
QSqlDatabase db = DataBaseManagement::loadDatabase(model->_databasePath);
|
||||
//crear la consulta
|
||||
{
|
||||
QSqlQuery selectQuery(db); //TODO check
|
||||
if(!includeComics)
|
||||
{
|
||||
selectQuery.prepare("select * from folder where id <> 1 and upper(name) like upper(:filter) order by parentId,name ");
|
||||
selectQuery.bindValue(":filter", "%%"+filter+"%%");
|
||||
}
|
||||
else
|
||||
{
|
||||
switch(modifier)
|
||||
{
|
||||
case YACReader::NoModifiers:
|
||||
selectQuery.prepare("SELECT DISTINCT f.id, f.parentId, f.name, f.path, f.finished, f.completed "
|
||||
"FROM folder f LEFT JOIN comic c ON (f.id = c.parentId) "
|
||||
"WHERE f.id <> 1 AND ((UPPER(c.fileName) like UPPER(:filter)) OR (UPPER(f.name) like UPPER(:filter2))) ORDER BY f.parentId,f.name");
|
||||
selectQuery.bindValue(":filter", "%%"+filter+"%%");
|
||||
selectQuery.bindValue(":filter2", "%%"+filter+"%%");
|
||||
break;
|
||||
|
||||
case YACReader::OnlyRead:
|
||||
selectQuery.prepare("SELECT DISTINCT f.id, f.parentId, f.name, f.path, f.finished, f.completed "
|
||||
"FROM folder f LEFT JOIN (comic c INNER JOIN comic_info ci ON (c.comicInfoId = ci.id)) ON (f.id = c.parentId) "
|
||||
"WHERE f.id <> 1 AND ((UPPER(c.fileName) like UPPER(:filter)) OR (UPPER(f.name) like UPPER(:filter2))) AND ci.read = 1 ORDER BY f.parentId,f.name;");
|
||||
selectQuery.bindValue(":filter", "%%"+filter+"%%");
|
||||
selectQuery.bindValue(":filter2", "%%"+filter+"%%");
|
||||
break;
|
||||
|
||||
case YACReader::OnlyUnread:
|
||||
selectQuery.prepare("SELECT DISTINCT f.id, f.parentId, f.name, f.path, f.finished, f.completed "
|
||||
"FROM folder f LEFT JOIN (comic c INNER JOIN comic_info ci ON (c.comicInfoId = ci.id)) ON (f.id = c.parentId) "
|
||||
"WHERE f.id <> 1 AND ((UPPER(c.fileName) like UPPER(:filter)) OR (UPPER(f.name) like UPPER(:filter2))) AND ci.read = 0 ORDER BY f.parentId,f.name;");
|
||||
selectQuery.bindValue(":filter", "%%"+filter+"%%");
|
||||
selectQuery.bindValue(":filter2", "%%"+filter+"%%");
|
||||
break;
|
||||
|
||||
default:
|
||||
QLOG_ERROR() << "not implemented";
|
||||
break;
|
||||
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
selectQuery.exec();
|
||||
|
||||
setupFilteredModelData(selectQuery,rootItem);
|
||||
}
|
||||
//selectQuery.finish();
|
||||
db.close();
|
||||
QSqlDatabase::removeDatabase(model->_databasePath);
|
||||
|
||||
endResetModel();
|
||||
}
|
||||
|
||||
void FolderModelProxy::clear()
|
||||
{
|
||||
filterEnabled = false;
|
||||
|
||||
filteredItems.clear();
|
||||
|
||||
QSortFilterProxyModel::clear();
|
||||
}
|
||||
|
||||
void FolderModelProxy::setupFilteredModelData(QSqlQuery &sqlquery, FolderItem *parent)
|
||||
{
|
||||
FolderModel * model = static_cast<FolderModel *>(sourceModel());
|
||||
|
||||
//64 bits para la primary key, es decir la misma precisi<73>n que soporta sqlit 2^64
|
||||
filteredItems.clear();
|
||||
|
||||
//se a<>ade el nodo 0 al modelo que representa el arbol de elementos que cumplen con el filtro
|
||||
filteredItems.insert(parent->id,parent);
|
||||
|
||||
while (sqlquery.next()) { //se procesan todos los folders que cumplen con el filtro
|
||||
//datos de la base de datos
|
||||
QList<QVariant> data;
|
||||
QSqlRecord record = sqlquery.record();
|
||||
|
||||
data << record.value("name").toString();
|
||||
data << record.value("path").toString();
|
||||
data << record.value("finished").toBool();
|
||||
data << record.value("completed").toBool();
|
||||
|
||||
FolderItem * item = new FolderItem(data);
|
||||
item->id = sqlquery.value(0).toULongLong();
|
||||
|
||||
//id del padre
|
||||
quint64 parentId = record.value("parentId").toULongLong();
|
||||
|
||||
//se a<>ade el item al map, de forma que se pueda encontrar como padre en siguientes iteraciones
|
||||
if(!filteredItems.contains(item->id))
|
||||
filteredItems.insert(item->id,item);
|
||||
|
||||
//es necesario conocer las coordenadas de origen para poder realizar scroll autom<6F>tico en la vista
|
||||
item->originalItem = model->items.value(item->id);
|
||||
|
||||
//si el padre ya existe en el modelo, el item se a<>ade como hijo
|
||||
if(filteredItems.contains(parentId))
|
||||
filteredItems.value(parentId)->appendChild(item);
|
||||
else//si el padre a<>n no se ha a<>adido, hay que a<>adirlo a <20>l y todos los padres hasta el nodo ra<72>z
|
||||
{
|
||||
//comprobamos con esta variable si el <20>ltimo de los padres (antes del nodo ra<72>z) ya exist<73>a en el modelo
|
||||
bool parentPreviousInserted = false;
|
||||
|
||||
//mientras no se alcance el nodo ra<72>z se procesan todos los padres (de abajo a arriba)
|
||||
while(parentId != ROOT )
|
||||
{
|
||||
//el padre no estaba en el modelo filtrado, as<61> que se rescata del modelo original
|
||||
FolderItem * parentItem = model->items.value(parentId);
|
||||
//se debe crear un nuevo nodo (para no compartir los hijos con el nodo original)
|
||||
FolderItem * newparentItem = new FolderItem(parentItem->getData()); //padre que se a<>adir<69> a la estructura de directorios filtrados
|
||||
newparentItem->id = parentId;
|
||||
|
||||
newparentItem->originalItem = parentItem;
|
||||
|
||||
//si el modelo contiene al padre, se a<>ade el item actual como hijo
|
||||
if(filteredItems.contains(parentId))
|
||||
{
|
||||
filteredItems.value(parentId)->appendChild(item);
|
||||
parentPreviousInserted = true;
|
||||
}
|
||||
//sino se registra el nodo para poder encontrarlo con posterioridad y se a<>ade el item actual como hijo
|
||||
else
|
||||
{
|
||||
newparentItem->appendChild(item);
|
||||
filteredItems.insert(newparentItem->id,newparentItem);
|
||||
parentPreviousInserted = false;
|
||||
}
|
||||
|
||||
//variables de control del bucle, se avanza hacia el nodo padre
|
||||
item = newparentItem;
|
||||
parentId = parentItem->parentItem->id;
|
||||
}
|
||||
|
||||
//si el nodo es hijo de 1 y no hab<61>a sido previamente insertado como hijo, se a<>ade como tal
|
||||
if(!parentPreviousInserted)
|
||||
filteredItems.value(ROOT)->appendChild(item);
|
||||
}
|
||||
}
|
||||
}
|
151
YACReaderLibrary/db/folder_model.h
Normal file
151
YACReaderLibrary/db/folder_model.h
Normal file
@ -0,0 +1,151 @@
|
||||
/****************************************************************************
|
||||
**
|
||||
** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
|
||||
** All rights reserved.
|
||||
** Contact: Nokia Corporation (qt-info@nokia.com)
|
||||
**
|
||||
** This file is part of the examples of the Qt Toolkit.
|
||||
**
|
||||
** $QT_BEGIN_LICENSE:BSD$
|
||||
** You may use this file under the terms of the BSD license as follows:
|
||||
**
|
||||
** "Redistribution and use in source and binary forms, with or without
|
||||
** modification, are permitted provided that the following conditions are
|
||||
** met:
|
||||
** * Redistributions of source code must retain the above copyright
|
||||
** notice, this list of conditions and the following disclaimer.
|
||||
** * Redistributions in binary form must reproduce the above copyright
|
||||
** notice, this list of conditions and the following disclaimer in
|
||||
** the documentation and/or other materials provided with the
|
||||
** distribution.
|
||||
** * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor
|
||||
** the names of its contributors may be used to endorse or promote
|
||||
** products derived from this software without specific prior written
|
||||
** permission.
|
||||
**
|
||||
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
|
||||
** $QT_END_LICENSE$
|
||||
**
|
||||
****************************************************************************/
|
||||
|
||||
#ifndef TREEMODEL_H
|
||||
#define TREEMODEL_H
|
||||
|
||||
#include <QAbstractItemModel>
|
||||
#include <QSortFilterProxyModel>
|
||||
#include <QModelIndex>
|
||||
#include <QVariant>
|
||||
#include <QSqlQuery>
|
||||
#include <QSqlDatabase>
|
||||
|
||||
#include "yacreader_global.h"
|
||||
|
||||
class FolderItem;
|
||||
|
||||
class FolderModelProxy : public QSortFilterProxyModel
|
||||
{
|
||||
Q_OBJECT
|
||||
public:
|
||||
explicit FolderModelProxy(QObject *parent = 0);
|
||||
~FolderModelProxy();
|
||||
|
||||
void setFilter(const YACReader::SearchModifiers modifier, QString filter, bool includeComics);
|
||||
void setupFilteredModelData( QSqlQuery &sqlquery, FolderItem *parent);
|
||||
void setupFilteredModelData();
|
||||
void clear();
|
||||
|
||||
bool filterAcceptsRow(int source_row, const QModelIndex &source_parent) const;
|
||||
|
||||
protected:
|
||||
FolderItem *rootItem;
|
||||
QMap<unsigned long long int, FolderItem *> filteredItems; //relación entre folders
|
||||
|
||||
bool includeComics;
|
||||
QString filter;
|
||||
bool filterEnabled;
|
||||
|
||||
YACReader::SearchModifiers modifier;
|
||||
};
|
||||
|
||||
class FolderModel : public QAbstractItemModel
|
||||
{
|
||||
|
||||
Q_OBJECT
|
||||
|
||||
friend class FolderModelProxy;
|
||||
|
||||
public:
|
||||
FolderModel(QObject *parent = 0);
|
||||
FolderModel( QSqlQuery &sqlquery, QObject *parent = 0);
|
||||
~FolderModel();
|
||||
|
||||
//QAbstractItemModel methods
|
||||
QVariant data(const QModelIndex &index, int role) const;
|
||||
Qt::ItemFlags flags(const QModelIndex &index) const;
|
||||
QVariant headerData(int section, Qt::Orientation orientation,
|
||||
int role = Qt::DisplayRole) const;
|
||||
QModelIndex index(int row, int column,
|
||||
const QModelIndex &parent = QModelIndex()) const;
|
||||
QModelIndex parent(const QModelIndex &index) const;
|
||||
int rowCount(const QModelIndex &parent = QModelIndex()) const;
|
||||
int columnCount(const QModelIndex &parent = QModelIndex()) const;
|
||||
|
||||
//Convenience methods
|
||||
void setupModelData(QString path);
|
||||
QString getDatabase();
|
||||
QString getFolderPath(const QModelIndex &folder);
|
||||
//QModelIndex indexFromItem(FolderItem * item, int column);
|
||||
|
||||
|
||||
//bool isFilterEnabled(){return filterEnabled;};
|
||||
|
||||
void updateFolderCompletedStatus(const QModelIndexList & list, bool status);
|
||||
void updateFolderFinishedStatus(const QModelIndexList & list, bool status);
|
||||
|
||||
QStringList getSubfoldersNames(const QModelIndex & mi);
|
||||
|
||||
void fetchMoreFromDB(const QModelIndex & parent);
|
||||
|
||||
QModelIndex addFolderAtParent(const QString & folderName, const QModelIndex & parent);
|
||||
|
||||
enum Columns {
|
||||
Name = 0,
|
||||
Path = 1,
|
||||
Finished = 2,
|
||||
Completed = 3
|
||||
};//id INTEGER PRIMARY KEY, parentId INTEGER NOT NULL, name TEXT NOT NULL, path TEXT NOT NULL
|
||||
|
||||
enum Roles {
|
||||
FinishedRole = Qt::UserRole + 1,
|
||||
CompletedRole
|
||||
};
|
||||
|
||||
public slots:
|
||||
void deleteFolder(const QModelIndex & mi);
|
||||
|
||||
private:
|
||||
void setupModelData( QSqlQuery &sqlquery, FolderItem *parent);
|
||||
void updateFolderModelData( QSqlQuery &sqlquery, FolderItem *parent);
|
||||
|
||||
FolderItem *rootItem; //el árbol
|
||||
QMap<unsigned long long int, FolderItem *> items; //relación entre folders
|
||||
|
||||
QString _databasePath;
|
||||
|
||||
signals:
|
||||
void beforeReset();
|
||||
void reset();
|
||||
};
|
||||
//! [0]
|
||||
|
||||
#endif
|
276
YACReaderLibrary/db/reading_list_item.cpp
Normal file
276
YACReaderLibrary/db/reading_list_item.cpp
Normal file
@ -0,0 +1,276 @@
|
||||
#include "reading_list_item.h"
|
||||
#include "qnaturalsorting.h"
|
||||
|
||||
#include <QFileIconProvider>
|
||||
|
||||
#include "QsLog.h"
|
||||
|
||||
ListItem::ListItem(const QList<QVariant> &data)
|
||||
:itemData(data)
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
int ListItem::columnCount()
|
||||
{
|
||||
return itemData.count();
|
||||
}
|
||||
|
||||
QVariant ListItem::data(int column) const
|
||||
{
|
||||
return itemData.at(column);
|
||||
}
|
||||
|
||||
qulonglong ListItem::getId() const
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
//------------------------------------------------------
|
||||
|
||||
SpecialListItem::SpecialListItem(const QList<QVariant> &data)
|
||||
:ListItem(data)
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
QIcon SpecialListItem::getIcon() const
|
||||
{
|
||||
if(itemData.count()>Id)
|
||||
{
|
||||
QString id = itemData.at(Id).toString();
|
||||
return YACReader::noHighlightedIcon(QString(":/images/lists/default_%1.png").arg(id));
|
||||
}
|
||||
|
||||
QLOG_WARN() << "Icon for SpecialListItem not available";
|
||||
|
||||
return QIcon();
|
||||
}
|
||||
|
||||
ReadingListModel::TypeSpecialList SpecialListItem::getType() const
|
||||
{
|
||||
if(itemData.count()>Id)
|
||||
{
|
||||
int id = itemData.at(Id).toInt();
|
||||
return (ReadingListModel::TypeSpecialList)id;
|
||||
}
|
||||
|
||||
QLOG_WARN() << "TypeSpecialList not available";
|
||||
|
||||
return (ReadingListModel::TypeSpecialList)0;
|
||||
}
|
||||
|
||||
//------------------------------------------------------
|
||||
|
||||
LabelItem::LabelItem(const QList<QVariant> &data)
|
||||
:ListItem(data)
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
QIcon LabelItem::getIcon() const
|
||||
{
|
||||
if(itemData.count()>Color)
|
||||
{
|
||||
QString color = itemData.at(Color).toString();
|
||||
return YACReader::noHighlightedIcon(QString(":/images/lists/label_%1.png").arg(color).toLower());
|
||||
}
|
||||
|
||||
QLOG_WARN() << "Icon for label item not available";
|
||||
|
||||
return QIcon();
|
||||
}
|
||||
|
||||
YACReader::LabelColors LabelItem::colorid() const
|
||||
{
|
||||
if(itemData.count()>Ordering)
|
||||
{
|
||||
return YACReader::LabelColors(itemData.at(Ordering).toInt());
|
||||
}
|
||||
|
||||
QLOG_WARN() << "Label color for label item not available";
|
||||
|
||||
return (YACReader::LabelColors)0;
|
||||
}
|
||||
|
||||
QString LabelItem::name() const
|
||||
{
|
||||
if(itemData.count()>Name)
|
||||
{
|
||||
return itemData.at(Name).toString();
|
||||
}
|
||||
|
||||
QLOG_WARN() << "Name for label item not available";
|
||||
|
||||
return "";
|
||||
}
|
||||
|
||||
void LabelItem::setName(const QString &name)
|
||||
{
|
||||
if(itemData.count()>Name)
|
||||
{
|
||||
itemData[Name] = name;
|
||||
}
|
||||
}
|
||||
|
||||
qulonglong LabelItem::getId() const
|
||||
{
|
||||
if(itemData.count()>Id)
|
||||
{
|
||||
return YACReader::LabelColors(itemData.at(Id).toULongLong());
|
||||
}
|
||||
|
||||
QLOG_WARN() << "Id for Label item not available";
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
//------------------------------------------------------
|
||||
|
||||
ReadingListItem::ReadingListItem(const QList<QVariant> &data, ReadingListItem *p)
|
||||
:ListItem(data), parent(p)
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
QIcon ReadingListItem::getIcon() const
|
||||
{
|
||||
if(parent->getId() == 0)
|
||||
return YACReader::noHighlightedIcon(":/images/lists/list.png"); //top level list
|
||||
else
|
||||
#ifdef Q_OS_MAC
|
||||
return QFileIconProvider().icon(QFileIconProvider::Folder);
|
||||
#else
|
||||
return YACReader::noHighlightedIcon(":/images/sidebar/folder.png"); //sublist
|
||||
#endif
|
||||
}
|
||||
|
||||
int ReadingListItem::childCount() const
|
||||
{
|
||||
return childItems.count();
|
||||
}
|
||||
|
||||
ReadingListItem *ReadingListItem::child(int row)
|
||||
{
|
||||
return childItems.at(row);
|
||||
}
|
||||
|
||||
//items are sorted by order
|
||||
void ReadingListItem::appendChild(ReadingListItem *item)
|
||||
{
|
||||
item->parent = this;
|
||||
|
||||
if(childItems.isEmpty())
|
||||
childItems.append(item);
|
||||
else
|
||||
{
|
||||
if(item->parent->getId()==0) //sort by name, top level child
|
||||
{
|
||||
int i= 0;
|
||||
while(i<childItems.length() && naturalSortLessThanCI(childItems.at(i)->name(),item->name()))
|
||||
i++;
|
||||
childItems.insert(i,item);
|
||||
}
|
||||
else
|
||||
{
|
||||
int i= 0;
|
||||
while(i<childItems.length() && (childItems.at(i)->getOrdering()<item->getOrdering()))
|
||||
i++;
|
||||
childItems.insert(i,item);
|
||||
}
|
||||
|
||||
/*ReadingListItem * last = childItems.back();
|
||||
QString nameLast = last->data(1).toString(); //TODO usar info name si est<73> disponible, sino el nombre del fichero.....
|
||||
QString nameCurrent = item->data(1).toString();
|
||||
QList<FolderItem *>::iterator i;
|
||||
i = childItems.end();
|
||||
i--;
|
||||
while (naturalSortLessThanCI(nameCurrent,nameLast) && i != childItems.begin())
|
||||
{
|
||||
i--;
|
||||
nameLast = (*i)->data(1).toString();
|
||||
}
|
||||
if(!naturalSortLessThanCI(nameCurrent,nameLast)) //si se ha encontrado un elemento menor que current, se inserta justo despu<70>s
|
||||
childItems.insert(++i,item);
|
||||
else
|
||||
childItems.insert(i,item);*/
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
void ReadingListItem::appendChild(ReadingListItem *item, int pos)
|
||||
{
|
||||
childItems.insert(pos, item);
|
||||
}
|
||||
|
||||
void ReadingListItem::removeChild(ReadingListItem *item)
|
||||
{
|
||||
childItems.removeOne(item);
|
||||
}
|
||||
|
||||
qulonglong ReadingListItem::getId() const
|
||||
{
|
||||
if(itemData.count()>Id)
|
||||
return itemData.at(Id).toULongLong();
|
||||
|
||||
QLOG_WARN() << "Name for reading list item not available";
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
QString ReadingListItem::name() const
|
||||
{
|
||||
if(itemData.count()>Name)
|
||||
return itemData.at(Name).toString();
|
||||
|
||||
QLOG_WARN() << "Name for reading list item not available";
|
||||
|
||||
return "";
|
||||
}
|
||||
|
||||
void ReadingListItem::setName(const QString &name)
|
||||
{
|
||||
if(itemData.count()>Name)
|
||||
itemData[Name] = name;
|
||||
}
|
||||
|
||||
int ReadingListItem::getOrdering() const
|
||||
{
|
||||
if(itemData.count()>Ordering)
|
||||
return itemData[Ordering].toInt();
|
||||
|
||||
QLOG_WARN() << "Ordering for Item not available";
|
||||
return 0;
|
||||
}
|
||||
|
||||
void ReadingListItem::setOrdering(const int ordering)
|
||||
{
|
||||
if(itemData.count()>Ordering)
|
||||
itemData[Ordering] = ordering;
|
||||
}
|
||||
|
||||
QList<ReadingListItem *> ReadingListItem::children()
|
||||
{
|
||||
return childItems;
|
||||
}
|
||||
|
||||
int ReadingListItem::row() const
|
||||
{
|
||||
if (parent)
|
||||
return parent->childItems.indexOf(const_cast<ReadingListItem*>(this));
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
|
||||
ReadingListSeparatorItem::ReadingListSeparatorItem()
|
||||
:ListItem(QList<QVariant>())
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
QIcon ReadingListSeparatorItem::getIcon() const
|
||||
{
|
||||
return QIcon();
|
||||
}
|
104
YACReaderLibrary/db/reading_list_item.h
Normal file
104
YACReaderLibrary/db/reading_list_item.h
Normal file
@ -0,0 +1,104 @@
|
||||
#ifndef READING_LIST_ITEM_H
|
||||
#define READING_LIST_ITEM_H
|
||||
|
||||
#include <QIcon>
|
||||
#include <QVariant>
|
||||
|
||||
#include "yacreader_global_gui.h"
|
||||
#include "reading_list_model.h"
|
||||
//TODO add propper constructors, using QList<QVariant> is not safe
|
||||
|
||||
class ListItem
|
||||
{
|
||||
public:
|
||||
ListItem(const QList<QVariant> &data);
|
||||
int columnCount();
|
||||
virtual QIcon getIcon() const = 0;
|
||||
QVariant data(int column) const;
|
||||
virtual qulonglong getId() const;
|
||||
QList<QVariant> itemData;
|
||||
virtual ~ListItem() {}
|
||||
};
|
||||
|
||||
//------------------------------------------------------
|
||||
|
||||
class SpecialListItem : public ListItem
|
||||
{
|
||||
public:
|
||||
SpecialListItem(const QList<QVariant> &data);
|
||||
QIcon getIcon() const;
|
||||
ReadingListModel::TypeSpecialList getType() const;
|
||||
private:
|
||||
enum DataIndexes {
|
||||
Name,
|
||||
Id
|
||||
};
|
||||
|
||||
};
|
||||
|
||||
//------------------------------------------------------
|
||||
|
||||
class LabelItem : public ListItem
|
||||
{
|
||||
public:
|
||||
LabelItem(const QList<QVariant> &data);
|
||||
QIcon getIcon() const;
|
||||
YACReader::LabelColors colorid() const;
|
||||
QString name() const;
|
||||
void setName(const QString & name);
|
||||
qulonglong getId() const;
|
||||
|
||||
|
||||
private:
|
||||
enum DataIndexes {
|
||||
Name,
|
||||
Color,
|
||||
Id,
|
||||
Ordering
|
||||
};
|
||||
};
|
||||
|
||||
//------------------------------------------------------
|
||||
|
||||
class ReadingListItem : public ListItem
|
||||
{
|
||||
public:
|
||||
ReadingListItem(const QList<QVariant> &data, ReadingListItem * parent = 0);
|
||||
QIcon getIcon() const;
|
||||
ReadingListItem * parent;
|
||||
int childCount() const;
|
||||
int row() const;
|
||||
ReadingListItem * child(int row);
|
||||
void appendChild(ReadingListItem *item);
|
||||
void appendChild(ReadingListItem *item, int pos);
|
||||
void removeChild(ReadingListItem *item);
|
||||
qulonglong getId() const;
|
||||
QString name() const;
|
||||
void setName(const QString & name);
|
||||
int getOrdering() const;
|
||||
void setOrdering(const int ordering);
|
||||
QList<ReadingListItem*> children();
|
||||
|
||||
private:
|
||||
QList<ReadingListItem*> childItems;
|
||||
|
||||
enum DataIndexes {
|
||||
Name,
|
||||
Id,
|
||||
Finished,
|
||||
Completed,
|
||||
Ordering
|
||||
};
|
||||
|
||||
};
|
||||
|
||||
//------------------------------------------------------
|
||||
|
||||
class ReadingListSeparatorItem : public ListItem
|
||||
{
|
||||
public:
|
||||
ReadingListSeparatorItem();
|
||||
QIcon getIcon() const;
|
||||
};
|
||||
|
||||
#endif // READING_LIST_ITEM_H
|
792
YACReaderLibrary/db/reading_list_model.cpp
Normal file
792
YACReaderLibrary/db/reading_list_model.cpp
Normal file
@ -0,0 +1,792 @@
|
||||
#include "reading_list_model.h"
|
||||
|
||||
#include "reading_list_item.h"
|
||||
|
||||
#include "data_base_management.h"
|
||||
#include "qnaturalsorting.h"
|
||||
#include "db_helper.h"
|
||||
|
||||
#include "QsLog.h"
|
||||
|
||||
#include <typeinfo>
|
||||
|
||||
ReadingListModel::ReadingListModel(QObject *parent) :
|
||||
QAbstractItemModel(parent),rootItem(0)
|
||||
{
|
||||
separator1 = new ReadingListSeparatorItem;
|
||||
separator2 = new ReadingListSeparatorItem;
|
||||
}
|
||||
|
||||
int ReadingListModel::rowCount(const QModelIndex &parent) const
|
||||
{
|
||||
if(!parent.isValid()) //TOP
|
||||
{
|
||||
int separatorsCount = 2;//labels.isEmpty()?1:2;
|
||||
return specialLists.count() + labels.count() + rootItem->childCount() + separatorsCount;
|
||||
}
|
||||
else
|
||||
{
|
||||
ListItem * item = static_cast<ListItem*>(parent.internalPointer());
|
||||
|
||||
if(typeid(*item) == typeid(ReadingListItem))
|
||||
{
|
||||
ReadingListItem * item = static_cast<ReadingListItem*>(parent.internalPointer());
|
||||
return item->childCount();
|
||||
}
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
int ReadingListModel::columnCount(const QModelIndex &parent) const
|
||||
{
|
||||
if(parent.isValid())
|
||||
{
|
||||
ListItem * item = static_cast<ListItem*>(parent.internalPointer());
|
||||
if(typeid(*item) == typeid(ReadingListSeparatorItem))
|
||||
return 0;
|
||||
}
|
||||
return 1;
|
||||
/*if (parent.isValid())
|
||||
return static_cast<ListItem*>(parent.internalPointer())->columnCount();
|
||||
else
|
||||
return rootItem->columnCount();*/
|
||||
}
|
||||
|
||||
QVariant ReadingListModel::data(const QModelIndex &index, int role) const
|
||||
{
|
||||
if(!index.isValid())
|
||||
return QVariant();
|
||||
|
||||
ListItem * item = static_cast<ListItem*>(index.internalPointer());
|
||||
|
||||
if (role == ReadingListModel::TypeListsRole)
|
||||
{
|
||||
if(typeid(*item) == typeid(SpecialListItem))
|
||||
return QVariant(ReadingListModel::SpecialList);
|
||||
|
||||
if(typeid(*item) == typeid(LabelItem))
|
||||
return QVariant(ReadingListModel::Label);
|
||||
|
||||
if(typeid(*item) == typeid(ReadingListItem))
|
||||
return QVariant(ReadingListModel::ReadingList);
|
||||
|
||||
if(typeid(*item) == typeid(ReadingListSeparatorItem))
|
||||
return QVariant(ReadingListModel::Separator);
|
||||
}
|
||||
|
||||
if (role == ReadingListModel::LabelColorRole && typeid(*item) == typeid(LabelItem) )
|
||||
{
|
||||
LabelItem * labelItem = static_cast<LabelItem*>(item);
|
||||
return QVariant(labelItem->colorid());
|
||||
}
|
||||
|
||||
if (role == ReadingListModel::IDRole)
|
||||
{
|
||||
QLOG_DEBUG() << "getting role";
|
||||
return item->getId();
|
||||
}
|
||||
|
||||
if (role == ReadingListModel::SpecialListTypeRole && typeid(*item) == typeid(SpecialListItem))
|
||||
{
|
||||
SpecialListItem * specialListItem = static_cast<SpecialListItem*>(item);
|
||||
return QVariant(specialListItem->getType());
|
||||
}
|
||||
|
||||
if(typeid(*item) == typeid(ReadingListSeparatorItem))
|
||||
return QVariant();
|
||||
|
||||
if (role == Qt::DecorationRole)
|
||||
{
|
||||
return QVariant(item->getIcon());
|
||||
}
|
||||
|
||||
if (role != Qt::DisplayRole)
|
||||
return QVariant();
|
||||
|
||||
return item->data(index.column());
|
||||
}
|
||||
|
||||
Qt::ItemFlags ReadingListModel::flags(const QModelIndex &index) const
|
||||
{
|
||||
if (!index.isValid())
|
||||
return 0;
|
||||
|
||||
ListItem * item = static_cast<ListItem*>(index.internalPointer());
|
||||
if(typeid(*item) == typeid(ReadingListSeparatorItem))
|
||||
return 0;
|
||||
|
||||
if(typeid(*item) == typeid(ReadingListItem) && static_cast<ReadingListItem *>(item)->parent->getId()!=0)
|
||||
return Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsDropEnabled | Qt::ItemIsDragEnabled; //only sublists are dragable
|
||||
|
||||
return Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsDropEnabled;
|
||||
}
|
||||
|
||||
QVariant ReadingListModel::headerData(int section, Qt::Orientation orientation, int role) const
|
||||
{
|
||||
if (orientation == Qt::Horizontal && role == Qt::DisplayRole)
|
||||
return rootItem->data(section);
|
||||
|
||||
return QVariant();
|
||||
}
|
||||
|
||||
QModelIndex ReadingListModel::index(int row, int column, const QModelIndex &parent) const
|
||||
{
|
||||
if (!hasIndex(row, column, parent))
|
||||
return QModelIndex();
|
||||
|
||||
if(!parent.isValid())
|
||||
{
|
||||
int separatorsCount = 2;//labels.isEmpty()?1:2;
|
||||
|
||||
if(rowIsSpecialList(row,parent))
|
||||
return createIndex(row, column, specialLists.at(row));
|
||||
|
||||
if(row == specialLists.count())
|
||||
return createIndex(row,column,separator1);
|
||||
|
||||
if(rowIsLabel(row,parent))
|
||||
return createIndex(row,column,labels.at(row-specialLists.count()-1));
|
||||
|
||||
if(separatorsCount == 2)
|
||||
if(row == specialLists.count() + labels.count() + 1)
|
||||
return createIndex(row,column,separator2);
|
||||
|
||||
if(rowIsReadingList(row,parent))
|
||||
return createIndex(row,column,rootItem->child(row - (specialLists.count() + labels.count() + separatorsCount)));
|
||||
|
||||
} else //sublist
|
||||
{
|
||||
ReadingListItem *parentItem;
|
||||
|
||||
if (!parent.isValid())
|
||||
parentItem = rootItem; //this should be impossible
|
||||
else
|
||||
parentItem = static_cast<ReadingListItem*>(parent.internalPointer());
|
||||
|
||||
ReadingListItem *childItem = parentItem->child(row);
|
||||
return createIndex(row,column,childItem);
|
||||
}
|
||||
/*FolderItem *childItem = parentItem->child(row);
|
||||
if (childItem)
|
||||
return createIndex(row, column, childItem);
|
||||
else*/
|
||||
return QModelIndex();
|
||||
|
||||
}
|
||||
|
||||
QModelIndex ReadingListModel::parent(const QModelIndex &index) const
|
||||
{
|
||||
|
||||
if(!index.isValid())
|
||||
return QModelIndex();
|
||||
|
||||
ListItem * item = static_cast<ListItem*>(index.internalPointer());
|
||||
|
||||
if(typeid(*item) == typeid(ReadingListItem))
|
||||
{
|
||||
ReadingListItem * childItem = static_cast<ReadingListItem*>(index.internalPointer());
|
||||
ReadingListItem * parent = childItem->parent;
|
||||
if(parent->getId() != 0)
|
||||
return createIndex(parent->row()+specialLists.count()+labels.count()+2, 0, parent);
|
||||
}
|
||||
|
||||
return QModelIndex();
|
||||
}
|
||||
|
||||
bool ReadingListModel::canDropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent) const
|
||||
{
|
||||
Q_UNUSED(action);
|
||||
|
||||
QLOG_DEBUG() << "trying to drop into row = " << row << "column column = " << column << "parent" << parent;
|
||||
|
||||
if(row == -1)
|
||||
return false;
|
||||
|
||||
if(!parent.isValid()) //top level items
|
||||
{
|
||||
if(row == -1) //no list
|
||||
return false;
|
||||
|
||||
if(row == 1) //reading is just an smart list
|
||||
return false;
|
||||
|
||||
if(rowIsSeparator(row,parent))
|
||||
return false;
|
||||
}
|
||||
|
||||
if(data->formats().contains(YACReader::YACReaderLibrarComiscSelectionMimeDataFormat))
|
||||
return true;
|
||||
|
||||
if(rowIsReadingList(row,parent))// TODO avoid droping in a different parent
|
||||
if(!parent.isValid())
|
||||
return false;
|
||||
else
|
||||
{
|
||||
QList<QPair<int,int> > sublistsRows;
|
||||
QByteArray rawData = data->data(YACReader::YACReaderLibrarSubReadingListMimeDataFormat);
|
||||
QDataStream in(&rawData,QIODevice::ReadOnly);
|
||||
in >> sublistsRows; //deserialize the list of indentifiers
|
||||
if(parent.row()!= sublistsRows.at(0).second)
|
||||
return false;
|
||||
return data->formats().contains(YACReader::YACReaderLibrarSubReadingListMimeDataFormat);
|
||||
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
bool ReadingListModel::dropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent)
|
||||
{
|
||||
QLOG_DEBUG() << "drop mimedata into row = " << row << " column = " << column << "parent" << parent;
|
||||
if(data->formats().contains(YACReader::YACReaderLibrarComiscSelectionMimeDataFormat))
|
||||
return dropComics(data, action, row, column, parent);
|
||||
|
||||
if(data->formats().contains(YACReader::YACReaderLibrarSubReadingListMimeDataFormat))
|
||||
return dropSublist(data, action, row, column, parent);
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
bool ReadingListModel::dropComics(const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent)
|
||||
{
|
||||
Q_UNUSED(action);
|
||||
|
||||
QList<qulonglong> comicIds = YACReader::mimeDataToComicsIds(data);
|
||||
|
||||
QLOG_DEBUG() << "dropped : " << comicIds;
|
||||
|
||||
QModelIndex dest;
|
||||
QModelIndex parentDest;
|
||||
|
||||
if(row == -1)
|
||||
{
|
||||
dest = parent;
|
||||
}
|
||||
else
|
||||
dest = index(row,column,parent);
|
||||
|
||||
parentDest = dest.parent();
|
||||
|
||||
if(rowIsSpecialList(dest.row(),parentDest)) {
|
||||
if(dest.row() == 0) //add to favorites
|
||||
{
|
||||
QLOG_DEBUG() << "-------addComicsToFavorites : " << comicIds << " to " << dest.data(IDRole).toULongLong();
|
||||
emit addComicsToFavorites(comicIds);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
if(rowIsLabel(dest.row(),parentDest)) {
|
||||
QLOG_DEBUG() << "+++++++++++addComicsToLabel : " << comicIds << " to " << dest.data(IDRole).toULongLong();
|
||||
emit addComicsToLabel(comicIds, dest.data(IDRole).toULongLong());
|
||||
return true;
|
||||
}
|
||||
|
||||
if(rowIsReadingList(dest.row(),parentDest)) {
|
||||
QLOG_DEBUG() << "///////////addComicsToReadingList : " << comicIds << " to " << dest.data(IDRole).toULongLong();
|
||||
emit addComicsToReadingList(comicIds, dest.data(IDRole).toULongLong());
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
bool ReadingListModel::dropSublist(const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent)
|
||||
{
|
||||
Q_UNUSED(action);
|
||||
Q_UNUSED(column);
|
||||
|
||||
QList<QPair<int,int> > sublistsRows;
|
||||
QByteArray rawData = data->data(YACReader::YACReaderLibrarSubReadingListMimeDataFormat);
|
||||
QDataStream in(&rawData,QIODevice::ReadOnly);
|
||||
in >> sublistsRows; //deserialize the list of indentifiers
|
||||
|
||||
QLOG_DEBUG() << "dropped : " << sublistsRows;
|
||||
|
||||
int sourceRow = sublistsRows.at(0).first;
|
||||
int destRow = row;
|
||||
QModelIndex destParent = parent;
|
||||
if(row == -1)
|
||||
{
|
||||
QLOG_DEBUG() << "droping inside parent";
|
||||
destRow = parent.row();
|
||||
destParent = parent.parent();
|
||||
}
|
||||
QLOG_DEBUG() << "move " << sourceRow << "-" << destRow;
|
||||
|
||||
if(sourceRow == destRow)
|
||||
return false;
|
||||
|
||||
//beginMoveRows(destParent,sourceRow,sourceRow,destParent,destRow);
|
||||
|
||||
ReadingListItem * parentItem = static_cast<ReadingListItem *>(destParent.internalPointer());
|
||||
ReadingListItem * child = parentItem->child(sourceRow);
|
||||
parentItem->removeChild(child);
|
||||
parentItem->appendChild(child,destRow);
|
||||
|
||||
reorderingChildren(parentItem->children());
|
||||
//endMoveRows();
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
QMimeData *ReadingListModel::mimeData(const QModelIndexList &indexes) const
|
||||
{
|
||||
QLOG_DEBUG() << "mimeData requested" << indexes;
|
||||
|
||||
if(indexes.length() == 0)
|
||||
{
|
||||
QLOG_ERROR() << "mimeData requested: indexes is empty";
|
||||
return new QMimeData();//TODO what happens if 0 is returned?
|
||||
}
|
||||
|
||||
if(indexes.length() > 1)
|
||||
QLOG_DEBUG() << "mimeData requested for more than one index, this shouldn't be possible";
|
||||
|
||||
QModelIndex modelIndex = indexes.at(0);
|
||||
|
||||
QList<QPair<int,int> > rows;
|
||||
rows << QPair<int,int>(modelIndex.row(),modelIndex.parent().row());
|
||||
QLOG_DEBUG() << "mimeData requested for row : " << modelIndex.row();
|
||||
|
||||
QByteArray data;
|
||||
QDataStream out(&data,QIODevice::WriteOnly);
|
||||
out << rows; //serialize the list of identifiers
|
||||
|
||||
QMimeData * mimeData = new QMimeData();
|
||||
mimeData->setData(YACReader::YACReaderLibrarSubReadingListMimeDataFormat, data);
|
||||
|
||||
return mimeData;
|
||||
}
|
||||
|
||||
void ReadingListModel::setupReadingListsData(QString path)
|
||||
{
|
||||
beginResetModel();
|
||||
|
||||
cleanAll();
|
||||
|
||||
_databasePath = path;
|
||||
QSqlDatabase db = DataBaseManagement::loadDatabase(path);
|
||||
|
||||
//setup special lists
|
||||
specialLists = setupSpecialLists(db);
|
||||
|
||||
//separator--------------------------------------------
|
||||
|
||||
//setup labels
|
||||
setupLabels(db);
|
||||
|
||||
//separator--------------------------------------------
|
||||
|
||||
//setup reading list
|
||||
setupReadingLists(db);
|
||||
|
||||
endResetModel();
|
||||
}
|
||||
|
||||
void ReadingListModel::addNewLabel(const QString &name, YACReader::LabelColors color)
|
||||
{
|
||||
QSqlDatabase db = DataBaseManagement::loadDatabase(_databasePath);
|
||||
qulonglong id = DBHelper::insertLabel(name, color, db);
|
||||
|
||||
Q_UNUSED(id);
|
||||
|
||||
beginInsertRows(QModelIndex(),0, 0);
|
||||
|
||||
// using the specfic row pos for inserting doesnt work
|
||||
// int newPos = addLabelIntoList(new LabelItem(QList<QVariant>() << name << YACReader::colorToName(color) << id << color));
|
||||
// beginInsertRows(QModelIndex(),specialLists.count()+1+newPos+1, specialLists.count()+1+newPos+1);
|
||||
|
||||
// endInsertRows();
|
||||
|
||||
endInsertRows();
|
||||
|
||||
QSqlDatabase::removeDatabase(_databasePath);
|
||||
}
|
||||
|
||||
void ReadingListModel::addReadingList(const QString &name)
|
||||
{
|
||||
QSqlDatabase db = DataBaseManagement::loadDatabase(_databasePath);
|
||||
|
||||
beginInsertRows(QModelIndex(), 0, 0); //TODO calculate the right coordinates before inserting
|
||||
|
||||
qulonglong id = DBHelper::insertReadingList(name,db);
|
||||
ReadingListItem * newItem;
|
||||
rootItem->appendChild(newItem = new ReadingListItem(QList<QVariant>()
|
||||
<< name
|
||||
<< id
|
||||
<< false
|
||||
<< true
|
||||
<< 0));
|
||||
|
||||
items.insert(id, newItem);
|
||||
|
||||
/*int pos = rootItem->children().indexOf(newItem);
|
||||
|
||||
pos += specialLists.count()+1+labels.count()+labels.count()>0?1:0;*/
|
||||
|
||||
|
||||
endInsertRows();
|
||||
|
||||
QSqlDatabase::removeDatabase(_databasePath);
|
||||
}
|
||||
|
||||
void ReadingListModel::addReadingListAt(const QString &name, const QModelIndex &mi)
|
||||
{
|
||||
QSqlDatabase db = DataBaseManagement::loadDatabase(_databasePath);
|
||||
|
||||
beginInsertRows(mi, 0, 0); //TODO calculate the right coordinates before inserting
|
||||
|
||||
ReadingListItem * readingListParent = static_cast<ReadingListItem*>(mi.internalPointer());
|
||||
qulonglong id = DBHelper::insertReadingSubList(name,mi.data(IDRole).toULongLong(),readingListParent->childCount(),db);
|
||||
ReadingListItem * newItem;
|
||||
|
||||
readingListParent->appendChild(newItem = new ReadingListItem(QList<QVariant>()
|
||||
<< name
|
||||
<< id
|
||||
<< false
|
||||
<< true
|
||||
<< readingListParent->childCount()));
|
||||
|
||||
items.insert(id, newItem);
|
||||
|
||||
/*int pos = readingListParent->children().indexOf(newItem);
|
||||
|
||||
pos += specialLists.count()+1+labels.count()+labels.count()>0?1:0;*/
|
||||
|
||||
|
||||
endInsertRows();
|
||||
|
||||
QSqlDatabase::removeDatabase(_databasePath);
|
||||
}
|
||||
|
||||
bool ReadingListModel::isEditable(const QModelIndex &mi)
|
||||
{
|
||||
if(!mi.isValid())
|
||||
return false;
|
||||
ListItem * item = static_cast<ListItem*>(mi.internalPointer());
|
||||
return typeid(*item) != typeid(SpecialListItem);
|
||||
}
|
||||
|
||||
bool ReadingListModel::isReadingList(const QModelIndex &mi)
|
||||
{
|
||||
if(!mi.isValid())
|
||||
return false;
|
||||
ListItem * item = static_cast<ListItem*>(mi.internalPointer());
|
||||
return typeid(*item) == typeid(ReadingListItem);
|
||||
}
|
||||
|
||||
bool ReadingListModel::isReadingSubList(const QModelIndex &mi)
|
||||
{
|
||||
if(!mi.isValid())
|
||||
return false;
|
||||
ListItem * item = static_cast<ListItem*>(mi.internalPointer());
|
||||
if(typeid(*item) == typeid(ReadingListItem))
|
||||
{
|
||||
ReadingListItem * readingListItem = static_cast<ReadingListItem *>(item);
|
||||
if(readingListItem->parent == rootItem)
|
||||
return false;
|
||||
else
|
||||
return true;
|
||||
}
|
||||
else
|
||||
return false;
|
||||
}
|
||||
|
||||
QString ReadingListModel::name(const QModelIndex &mi)
|
||||
{
|
||||
return data(mi,Qt::DisplayRole).toString();
|
||||
}
|
||||
|
||||
void ReadingListModel::rename(const QModelIndex &mi, const QString &name)
|
||||
{
|
||||
if(!isEditable(mi))
|
||||
return;
|
||||
|
||||
QSqlDatabase db = DataBaseManagement::loadDatabase(_databasePath);
|
||||
|
||||
ListItem * item = static_cast<ListItem*>(mi.internalPointer());
|
||||
|
||||
if(typeid(*item) == typeid(ReadingListItem))
|
||||
{
|
||||
ReadingListItem * rli = static_cast<ReadingListItem*>(item);
|
||||
rli->setName(name);
|
||||
DBHelper::renameList(item->getId(), name, db);
|
||||
|
||||
if(rli->parent->getId()!=0)
|
||||
{
|
||||
//TODO
|
||||
//move row depending on the name
|
||||
}else
|
||||
emit dataChanged(index(mi.row(), 0), index(mi.row(), 0));
|
||||
}
|
||||
else if(typeid(*item) == typeid(LabelItem))
|
||||
{
|
||||
LabelItem * li = static_cast<LabelItem*>(item);
|
||||
li->setName(name);
|
||||
DBHelper::renameLabel(item->getId(), name, db);
|
||||
emit dataChanged(index(mi.row(), 0), index(mi.row(), 0));
|
||||
}
|
||||
|
||||
QSqlDatabase::removeDatabase(_databasePath);
|
||||
}
|
||||
|
||||
void ReadingListModel::deleteItem(const QModelIndex &mi)
|
||||
{
|
||||
if(isEditable(mi))
|
||||
{
|
||||
QLOG_DEBUG() << "parent row :" << mi.parent().data() << "-" << mi.row();
|
||||
beginRemoveRows(mi.parent(),mi.row(),mi.row());
|
||||
|
||||
QSqlDatabase db = DataBaseManagement::loadDatabase(_databasePath);
|
||||
|
||||
ListItem * item = static_cast<ListItem*>(mi.internalPointer());
|
||||
|
||||
if(typeid(*item) == typeid(ReadingListItem))
|
||||
{
|
||||
ReadingListItem * rli = static_cast<ReadingListItem*>(item);
|
||||
QLOG_DEBUG() << "num children : " << rli->parent->childCount();
|
||||
rli->parent->removeChild(rli);
|
||||
QLOG_DEBUG() << "num children : " << rli->parent->childCount();
|
||||
DBHelper::removeListFromDB(item->getId(), db);
|
||||
if(rli->parent->getId()!=0)
|
||||
{
|
||||
reorderingChildren(rli->parent->children());
|
||||
}
|
||||
QLOG_DEBUG() << "num children : " << rli->parent->childCount();
|
||||
}
|
||||
else if(typeid(*item) == typeid(LabelItem))
|
||||
{
|
||||
LabelItem * li = static_cast<LabelItem*>(item);
|
||||
labels.removeOne(li);
|
||||
DBHelper::removeLabelFromDB(item->getId(), db);
|
||||
}
|
||||
|
||||
QSqlDatabase::removeDatabase(_databasePath);
|
||||
|
||||
endRemoveRows();
|
||||
}
|
||||
}
|
||||
|
||||
const QList<LabelItem *> ReadingListModel::getLabels()
|
||||
{
|
||||
return labels;
|
||||
}
|
||||
|
||||
void ReadingListModel::cleanAll()
|
||||
{
|
||||
if(rootItem != 0)
|
||||
{
|
||||
delete rootItem;
|
||||
|
||||
qDeleteAll(specialLists);
|
||||
qDeleteAll(labels);
|
||||
|
||||
specialLists.clear();
|
||||
labels.clear();
|
||||
|
||||
items.clear();
|
||||
}
|
||||
|
||||
rootItem = 0;
|
||||
}
|
||||
|
||||
void ReadingListModel::setupReadingListsData(QSqlQuery &sqlquery, ReadingListItem *parent)
|
||||
{
|
||||
items.insert(parent->getId(),parent);
|
||||
|
||||
while (sqlquery.next())
|
||||
{
|
||||
QSqlRecord record = sqlquery.record();
|
||||
ReadingListItem * rli = new ReadingListItem(QList<QVariant>()
|
||||
<< record.value("name")
|
||||
<< record.value("id")
|
||||
<< record.value("finished")
|
||||
<< record.value("completed")
|
||||
<< record.value("ordering"));
|
||||
|
||||
ReadingListItem * currentParent;
|
||||
if(record.value("parentId").isNull())
|
||||
currentParent = rootItem;
|
||||
else
|
||||
currentParent = items.value(record.value("parentId").toULongLong());
|
||||
|
||||
currentParent->appendChild(rli);
|
||||
|
||||
items.insert(rli->getId(),rli);
|
||||
}
|
||||
}
|
||||
|
||||
QList<SpecialListItem *> ReadingListModel::setupSpecialLists(QSqlDatabase & db)
|
||||
{
|
||||
QList<SpecialListItem *> list;
|
||||
|
||||
QSqlQuery selectQuery("SELECT * FROM default_reading_list ORDER BY id,name",db);
|
||||
while(selectQuery.next()) {
|
||||
QSqlRecord record = selectQuery.record();
|
||||
list << new SpecialListItem(QList<QVariant>()
|
||||
<< record.value("name")
|
||||
<< record.value("id"));
|
||||
}
|
||||
|
||||
//Reading after Favorites, Why? Because I want to :P
|
||||
list.insert(1,new SpecialListItem(QList<QVariant>() << "Reading" << 0));
|
||||
|
||||
return list;
|
||||
}
|
||||
|
||||
void ReadingListModel::setupLabels(QSqlDatabase & db)
|
||||
{
|
||||
QSqlQuery selectQuery("SELECT * FROM label ORDER BY ordering,name",db); //TODO add some kind of
|
||||
while(selectQuery.next()) {
|
||||
QSqlRecord record = selectQuery.record();
|
||||
addLabelIntoList(new LabelItem(QList<QVariant>()
|
||||
<< record.value("name")
|
||||
<< record.value("color")
|
||||
<< record.value("id")
|
||||
<< record.value("ordering")));
|
||||
}
|
||||
|
||||
//TEST
|
||||
|
||||
// INSERT INTO label (name, color, ordering) VALUES ("Oh Oh", "red", 1);
|
||||
// INSERT INTO label (name, color, ordering) VALUES ("lalala", "orange", 2);
|
||||
// INSERT INTO label (name, color, ordering) VALUES ("we are not sorry", "yellow", 3);
|
||||
// INSERT INTO label (name, color, ordering) VALUES ("there we go", "green", 4);
|
||||
// INSERT INTO label (name, color, ordering) VALUES ("oklabunga", "cyan", 5);
|
||||
// INSERT INTO label (name, color, ordering) VALUES ("hailer mailer", "blue", 6);
|
||||
// INSERT INTO label (name, color, ordering) VALUES ("lol", "violet", 7);
|
||||
// INSERT INTO label (name, color, ordering) VALUES ("problems", "purple", 8);
|
||||
// INSERT INTO label (name, color, ordering) VALUES ("me gussssta", "pink", 9);
|
||||
// INSERT INTO label (name, color, ordering) VALUES (":D", "white", 10);
|
||||
// INSERT INTO label (name, color, ordering) VALUES ("ainsss", "light", 11);
|
||||
// INSERT INTO label (name, color, ordering) VALUES ("put a smile on my face", "dark", 12);
|
||||
|
||||
}
|
||||
|
||||
void ReadingListModel::setupReadingLists(QSqlDatabase & db)
|
||||
{
|
||||
//setup root item
|
||||
rootItem = new ReadingListItem(QList<QVariant>() << "ROOT" << 0 << true << false);
|
||||
|
||||
QSqlQuery selectQuery("select * from reading_list order by parentId IS NULL DESC",db);
|
||||
|
||||
//setup reading lists
|
||||
setupReadingListsData(selectQuery,rootItem);
|
||||
|
||||
//TEST
|
||||
// ReadingListItem * node1;
|
||||
// rootItem->appendChild(node1 = new ReadingListItem(QList<QVariant>() /*<< 0*/ << "My reading list" << "atr"));
|
||||
// rootItem->appendChild(new ReadingListItem(QList<QVariant>() /*<< 0*/ << "X timeline" << "atr"));
|
||||
|
||||
// node1->appendChild(new ReadingListItem(QList<QVariant>() /*<< 0*/ << "sublist" << "atr",node1));
|
||||
}
|
||||
|
||||
int ReadingListModel::addLabelIntoList(LabelItem *item)
|
||||
{
|
||||
if(labels.isEmpty())
|
||||
labels << item;
|
||||
else
|
||||
{
|
||||
int i = 0;
|
||||
|
||||
while (i < labels.count() && (labels.at(i)->colorid() < item->colorid()) )
|
||||
i++;
|
||||
|
||||
if(i < labels.count())
|
||||
{
|
||||
if(labels.at(i)->colorid() == item->colorid()) //sort by name
|
||||
{
|
||||
while( i < labels.count() && labels.at(i)->colorid() == item->colorid() && naturalSortLessThanCI(labels.at(i)->name(),item->name()))
|
||||
i++;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
if(i >= labels.count())
|
||||
{
|
||||
QLOG_DEBUG() << "insertando label al final " << item->name();
|
||||
labels << item;
|
||||
}
|
||||
else
|
||||
{
|
||||
QLOG_DEBUG() << "insertando label en " << i << "-" << item->name();
|
||||
labels.insert(i,item);
|
||||
}
|
||||
|
||||
return i;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
void ReadingListModel::reorderingChildren(QList<ReadingListItem *> children)
|
||||
{
|
||||
QList<qulonglong> childrenIds;
|
||||
int i = 0;
|
||||
foreach (ReadingListItem * item, children) {
|
||||
item->setOrdering(i++);
|
||||
childrenIds << item->getId();
|
||||
}
|
||||
|
||||
QSqlDatabase db = DataBaseManagement::loadDatabase(_databasePath);
|
||||
DBHelper::reasignOrderToSublists(childrenIds, db);
|
||||
QSqlDatabase::removeDatabase(_databasePath);
|
||||
}
|
||||
|
||||
bool ReadingListModel::rowIsSpecialList(int row, const QModelIndex &parent) const
|
||||
{
|
||||
if(parent.isValid())
|
||||
return false; //by now no sublists in special list
|
||||
|
||||
if(row >=0 && row < specialLists.count())
|
||||
return true;
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
bool ReadingListModel::rowIsLabel(int row, const QModelIndex &parent) const
|
||||
{
|
||||
if(parent.isValid())
|
||||
return false; //by now no sublists in labels
|
||||
|
||||
if(row > specialLists.count() && row <= specialLists.count() + labels.count())
|
||||
return true;
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
bool ReadingListModel::rowIsReadingList(int row, const QModelIndex &parent) const
|
||||
{
|
||||
if(parent.isValid())
|
||||
return true; //only lists with sublists
|
||||
|
||||
int separatorsCount = labels.isEmpty()?1:2;
|
||||
|
||||
if(row >= specialLists.count() + labels.count() + separatorsCount)
|
||||
return true;
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
bool ReadingListModel::rowIsSeparator(int row, const QModelIndex &parent) const
|
||||
{
|
||||
if(parent.isValid())
|
||||
return false; //only separators at top level
|
||||
|
||||
if(row == specialLists.count())
|
||||
return true;
|
||||
|
||||
int separatorsCount = labels.isEmpty()?1:2;
|
||||
if(separatorsCount == 2 && row == specialLists.count() + labels.count() + 1)
|
||||
return true;
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
ReadingListModelProxy::ReadingListModelProxy(QObject *parent)
|
||||
:QSortFilterProxyModel(parent)
|
||||
{
|
||||
|
||||
}
|
117
YACReaderLibrary/db/reading_list_model.h
Normal file
117
YACReaderLibrary/db/reading_list_model.h
Normal file
@ -0,0 +1,117 @@
|
||||
#ifndef READING_LIST_MODEL_H
|
||||
#define READING_LIST_MODEL_H
|
||||
|
||||
#include <QAbstractItemModel>
|
||||
#include <QSortFilterProxyModel>
|
||||
#include <QModelIndex>
|
||||
#include <QVariant>
|
||||
#include <QSqlQuery>
|
||||
#include <QSqlDatabase>
|
||||
|
||||
#include "yacreader_global.h"
|
||||
|
||||
class LabelItem;
|
||||
class SpecialListItem;
|
||||
class ReadingListItem;
|
||||
class ReadingListSeparatorItem;
|
||||
|
||||
class ReadingListModelProxy : public QSortFilterProxyModel
|
||||
{
|
||||
Q_OBJECT
|
||||
public:
|
||||
explicit ReadingListModelProxy(QObject *parent = 0);
|
||||
};
|
||||
|
||||
class ReadingListModel : public QAbstractItemModel
|
||||
{
|
||||
Q_OBJECT
|
||||
public:
|
||||
explicit ReadingListModel(QObject *parent = 0);
|
||||
|
||||
//QAbstractItemModel methods
|
||||
int rowCount(const QModelIndex &parent = QModelIndex()) const;
|
||||
int columnCount(const QModelIndex &parent = QModelIndex()) const;
|
||||
QVariant data(const QModelIndex &index, int role) const;
|
||||
Qt::ItemFlags flags(const QModelIndex &index) const;
|
||||
QVariant headerData(int section, Qt::Orientation orientation,
|
||||
int role = Qt::DisplayRole) const;
|
||||
QModelIndex index(int row, int column,
|
||||
const QModelIndex &parent = QModelIndex()) const;
|
||||
QModelIndex parent(const QModelIndex &index) const;
|
||||
bool canDropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent) const;
|
||||
bool dropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent);
|
||||
QMimeData *mimeData(const QModelIndexList &indexes) const;
|
||||
|
||||
//Convenience methods
|
||||
void setupReadingListsData(QString path);
|
||||
void addNewLabel(const QString & name, YACReader::LabelColors color);
|
||||
void addReadingList(const QString & name);//top level reading list
|
||||
void addReadingListAt(const QString & name, const QModelIndex & mi);
|
||||
bool isEditable(const QModelIndex & mi);
|
||||
bool isReadingList(const QModelIndex & mi);
|
||||
bool isReadingSubList(const QModelIndex & mi);
|
||||
QString name(const QModelIndex & mi);
|
||||
void rename(const QModelIndex & mi, const QString & name);
|
||||
void deleteItem(const QModelIndex & mi);
|
||||
const QList<LabelItem *> getLabels();
|
||||
|
||||
enum Roles {
|
||||
TypeListsRole = Qt::UserRole + 1,
|
||||
IDRole,
|
||||
LabelColorRole,
|
||||
SpecialListTypeRole
|
||||
};
|
||||
|
||||
enum TypeList {
|
||||
SpecialList,
|
||||
Label,
|
||||
ReadingList,
|
||||
Separator
|
||||
};
|
||||
|
||||
enum TypeSpecialList {
|
||||
Reading,
|
||||
Favorites
|
||||
};
|
||||
|
||||
signals:
|
||||
|
||||
void addComicsToFavorites(const QList<qulonglong> & comicIds);
|
||||
void addComicsToLabel(const QList<qulonglong> & comicIds, qulonglong labelId);
|
||||
void addComicsToReadingList(const QList<qulonglong> & comicIds, qulonglong readingListId);
|
||||
|
||||
private:
|
||||
void cleanAll();
|
||||
void setupReadingListsData(QSqlQuery &sqlquery, ReadingListItem *parent);
|
||||
QList<SpecialListItem *> setupSpecialLists(QSqlDatabase &db);
|
||||
void setupLabels(QSqlDatabase &db);
|
||||
void setupReadingLists(QSqlDatabase &db);
|
||||
int addLabelIntoList(LabelItem *item);
|
||||
void reorderingChildren(QList<ReadingListItem *> children);
|
||||
|
||||
bool rowIsSpecialList(int row, const QModelIndex & parent = QModelIndex()) const;
|
||||
bool rowIsLabel(int row, const QModelIndex & parent = QModelIndex()) const;
|
||||
bool rowIsReadingList(int row, const QModelIndex & parent = QModelIndex()) const;
|
||||
bool rowIsSeparator(int row, const QModelIndex & parent = QModelIndex()) const;
|
||||
|
||||
bool dropComics(const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent);
|
||||
bool dropSublist(const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent);
|
||||
//Special lists
|
||||
QList<SpecialListItem *> specialLists;
|
||||
|
||||
//Label
|
||||
QList<LabelItem *> labels;
|
||||
|
||||
//Reading lists
|
||||
ReadingListItem * rootItem; //
|
||||
QMap<unsigned long long int, ReadingListItem *> items; //lists relationship
|
||||
|
||||
//separators
|
||||
ReadingListSeparatorItem * separator1;
|
||||
ReadingListSeparatorItem * separator2;
|
||||
|
||||
QString _databasePath;
|
||||
|
||||
};
|
||||
|
||||
#endif // READING_LIST_MODEL_H
|
Reference in New Issue
Block a user