picturemodel.cpp 2.4 KB

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