picturemodel.cpp 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. #include "picturemodel.h"
  2. #include <QDir>
  3. #include <QDebug>
  4. #include <QCoreApplication>
  5. struct FSNode {
  6. FSNode(const QString& rname, const FSNode *pparent = nullptr)
  7. : name(rname),
  8. parent(pparent) { /**/ }
  9. const QString name;
  10. const FSNode *parent;
  11. };
  12. PictureModel::PictureModel(QObject *parent)
  13. : QAbstractListModel(parent)
  14. { /**/ }
  15. PictureModel::~PictureModel()
  16. {
  17. // TODO: Destroy model
  18. }
  19. void PictureModel::addModelNode(const FSNode* parentNode)
  20. {
  21. QCoreApplication::processEvents();
  22. // TODO: Check for symlink recursion
  23. QDir parentDir(qualifyNode(parentNode));
  24. foreach(const QString &currentDir, parentDir.entryList(QDir::Dirs | QDir::NoDotAndDotDot)) {
  25. const FSNode *dir = new FSNode(currentDir, parentNode);
  26. addModelNode(dir);
  27. }
  28. foreach(const QString &currentFile, parentDir.entryList(QDir::Files)) {
  29. if (!extensions.isEmpty()) {
  30. QString extension = currentFile.mid(currentFile.length() - 3);
  31. if (!extensions.contains(extension))
  32. continue;
  33. }
  34. const FSNode *file = new FSNode(currentFile, parentNode);
  35. files << file;
  36. }
  37. }
  38. void PictureModel::setModelRoot(const QString &root)
  39. {
  40. QDir currentDir(root);
  41. if (!currentDir.exists()) {
  42. qDebug() << "Being told to watch a non existent directory";
  43. }
  44. addModelNode(new FSNode(root));
  45. // foreach(FSNode *node, files) {
  46. // qDebug() << "Contains:" << qualifyNode(node);
  47. // }
  48. }
  49. int PictureModel::rowCount(const QModelIndex &parent) const
  50. {
  51. Q_UNUSED(parent)
  52. return files.length();
  53. }
  54. QString PictureModel::randomPicture() const
  55. {
  56. return qualifyNode(files.at(qrand()%files.size()));
  57. }
  58. QVariant PictureModel::data(const QModelIndex &index, int role) const
  59. {
  60. Q_UNUSED(role)
  61. if (index.row() < 0 || index.row() >= files.length())
  62. return QVariant();
  63. const FSNode *node = files.at(index.row());
  64. return qualifyNode(node);
  65. }
  66. QString PictureModel::qualifyNode(const FSNode *node) const {
  67. QString qualifiedPath;
  68. while(node->parent != nullptr) {
  69. qualifiedPath = "/" + node->name + qualifiedPath;
  70. node = node->parent;
  71. }
  72. qualifiedPath = node->name + qualifiedPath;
  73. return qualifiedPath;
  74. }
  75. void PictureModel::addSupportedExtension(const QString &extension)
  76. {
  77. extensions << extension;
  78. }
  79. QHash<int, QByteArray> PictureModel::roleNames() const
  80. {
  81. QHash<int, QByteArray> roles;
  82. roles[PathRole] = "path";
  83. return roles;
  84. }