ctkDICOMModel.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622
  1. /*=========================================================================
  2. Library: CTK
  3. Copyright (c) 2010 Kitware Inc.
  4. Licensed under the Apache License, Version 2.0 (the "License");
  5. you may not use this file except in compliance with the License.
  6. You may obtain a copy of the License at
  7. http://www.commontk.org/LICENSE
  8. Unless required by applicable law or agreed to in writing, software
  9. distributed under the License is distributed on an "AS IS" BASIS,
  10. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11. See the License for the specific language governing permissions and
  12. limitations under the License.
  13. =========================================================================*/
  14. // Qt includes
  15. #include <QStringList>
  16. #include <QSqlDriver>
  17. #include <QSqlError>
  18. #include <QSqlQuery>
  19. #include <QSqlQueryModel>
  20. #include <QSqlRecord>
  21. #include <QTime>
  22. #include <QDebug>
  23. // ctkDICOM includes
  24. #include "ctkDICOMModel.h"
  25. struct Node;
  26. //------------------------------------------------------------------------------
  27. class ctkDICOMModelPrivate:public ctkPrivate<ctkDICOMModel>
  28. {
  29. public:
  30. ctkDICOMModelPrivate();
  31. virtual ~ctkDICOMModelPrivate();
  32. void init();
  33. enum IndexType{
  34. RootType,
  35. PatientType,
  36. StudyType,
  37. SeriesType,
  38. ImageType
  39. };
  40. void fetch(const QModelIndex& indexValue, int limit);
  41. Node* createNode(int row, const QModelIndex& parentValue)const;
  42. Node* nodeFromIndex(const QModelIndex& indexValue)const;
  43. //QModelIndexList indexListFromNode(const Node* node)const;
  44. //QModelIndexList modelIndexList(Node* node = 0)const;
  45. //int childrenCount(Node* node = 0)const;
  46. // move it in the Node struct
  47. QVariant value(Node* parentValue, int row, int field)const;
  48. QVariant value(const QModelIndex& indexValue, int row, int field)const;
  49. QString generateQuery(const QString& fields, const QString& table, const QString& conditions = QString())const;
  50. void updateQueries(Node* node)const;
  51. Node* RootNode;
  52. QSqlDatabase DataBase;
  53. QStringList Headers;
  54. QString Sort;
  55. };
  56. //------------------------------------------------------------------------------
  57. // 1 node per row
  58. struct Node
  59. {
  60. ~Node()
  61. {
  62. foreach(Node* node, this->Children)
  63. {
  64. delete node;
  65. }
  66. this->Children.clear();
  67. }
  68. ctkDICOMModelPrivate::IndexType Type;
  69. Node* Parent;
  70. QVector<Node*> Children;
  71. int Row;
  72. QSqlQuery Query;
  73. QString UID;
  74. int RowCount;
  75. bool AtEnd;
  76. bool Fetching;
  77. };
  78. //------------------------------------------------------------------------------
  79. ctkDICOMModelPrivate::ctkDICOMModelPrivate()
  80. {
  81. this->RootNode = 0;
  82. }
  83. //------------------------------------------------------------------------------
  84. ctkDICOMModelPrivate::~ctkDICOMModelPrivate()
  85. {
  86. delete this->RootNode;
  87. this->RootNode = 0;
  88. }
  89. //------------------------------------------------------------------------------
  90. void ctkDICOMModelPrivate::init()
  91. {
  92. this->Headers = QStringList() << "Name" << "Age" << "Scan" << "Date" << "Subject ID"
  93. << "Number" << "Institution" << "Referrer" << "Performer";
  94. }
  95. //------------------------------------------------------------------------------
  96. Node* ctkDICOMModelPrivate::nodeFromIndex(const QModelIndex& indexValue)const
  97. {
  98. return indexValue.isValid() ? reinterpret_cast<Node*>(indexValue.internalPointer()) : this->RootNode;
  99. }
  100. /*
  101. //------------------------------------------------------------------------------
  102. QModelIndexList ctkDICOMModelPrivate::indexListFromNode(const Node* node)const
  103. {
  104. CTK_P(const ctkDICOMModel);
  105. Q_ASSERT(node);
  106. QModelIndexList indexList;
  107. Node* parentNode = node->Parent;
  108. if (parentNode == 0)
  109. {
  110. return indexList;
  111. }
  112. int field = parentNode->Query.record().indexOf("UID");
  113. int row = -1;
  114. for (row = 0; row < parentNode->RowCount; ++row)
  115. {
  116. QString uid = this->value(parentNode, row, field).toString();
  117. if (uid == node->UID)
  118. {
  119. break;
  120. }
  121. }
  122. if (row >= parentNode->RowCount)
  123. {
  124. return indexList;
  125. }
  126. for (int column = 0 ; column < this->Headers.size(); ++column)
  127. {
  128. indexList.append(p->createIndex(row, column, parentNode));
  129. }
  130. return indexList;
  131. }
  132. //------------------------------------------------------------------------------
  133. QModelIndexList ctkDICOMModelPrivate::modelIndexList(Node* node)const
  134. {
  135. QModelIndexList list;
  136. if (node == 0)
  137. {
  138. node = this->RootNode;
  139. }
  140. foreach(Node* child, node->Children)
  141. {
  142. list.append(this->indexListFromNode(child));
  143. }
  144. foreach(Node* child, node->Children)
  145. {
  146. list.append(this->modelIndexList(child));
  147. }
  148. return list;
  149. }
  150. //------------------------------------------------------------------------------
  151. int ctkDICOMModelPrivate::childrenCount(Node* node)const
  152. {
  153. int count = 0;
  154. if (node == 0)
  155. {
  156. node = this->RootNode;
  157. }
  158. count += node->Children.size();
  159. foreach(Node* child, node->Children)
  160. {
  161. count += this->childrenCount(child);
  162. }
  163. return count;
  164. }
  165. */
  166. //------------------------------------------------------------------------------
  167. Node* ctkDICOMModelPrivate::createNode(int row, const QModelIndex& parentValue)const
  168. {
  169. Node* node = new Node;
  170. Node* nodeParent = 0;
  171. if (row == -1)
  172. {// root node
  173. node->Type = ctkDICOMModelPrivate::RootType;
  174. node->Parent = 0;
  175. }
  176. else
  177. {
  178. nodeParent = this->nodeFromIndex(parentValue);
  179. nodeParent->Children.push_back(node);
  180. node->Parent = nodeParent;
  181. node->Type = ctkDICOMModelPrivate::IndexType(nodeParent->Type + 1);
  182. }
  183. node->Row = row;
  184. if (node->Type != ctkDICOMModelPrivate::RootType)
  185. {
  186. int field = nodeParent->Query.record().indexOf("UID");
  187. node->UID = this->value(parentValue, row, field).toString();
  188. }
  189. node->RowCount = 0;
  190. node->AtEnd = false;
  191. node->Fetching = false;
  192. this->updateQueries(node);
  193. return node;
  194. }
  195. //------------------------------------------------------------------------------
  196. QVariant ctkDICOMModelPrivate::value(const QModelIndex& parentValue, int row, int column) const
  197. {
  198. Node* node = this->nodeFromIndex(parentValue);
  199. if (row >= node->RowCount)
  200. {
  201. const_cast<ctkDICOMModelPrivate *>(this)->fetch(parentValue, row + 256);
  202. }
  203. return this->value(node, row, column);
  204. }
  205. //------------------------------------------------------------------------------
  206. QVariant ctkDICOMModelPrivate::value(Node* parentValue, int row, int column) const
  207. {
  208. Q_ASSERT(row < parentValue->RowCount);
  209. if (!parentValue->Query.seek(row))
  210. {
  211. qDebug() << parentValue->Query.lastError();
  212. Q_ASSERT(parentValue->Query.seek(row));
  213. return QVariant();
  214. }
  215. QVariant res = parentValue->Query.value(column);
  216. Q_ASSERT(res.isValid());
  217. return res;
  218. }
  219. //------------------------------------------------------------------------------
  220. QString ctkDICOMModelPrivate::generateQuery(const QString& fields, const QString& table, const QString& conditions)const
  221. {
  222. QString res = QString("SELECT ") + fields + QString(" FROM ") + table;
  223. if (!conditions.isEmpty())
  224. {
  225. res += QString(" WHERE ") + conditions;
  226. }
  227. if (!this->Sort.isEmpty())
  228. {
  229. res += QString(" ORDER BY ") + this->Sort;
  230. }
  231. return res;
  232. }
  233. //------------------------------------------------------------------------------
  234. void ctkDICOMModelPrivate::updateQueries(Node* node)const
  235. {
  236. // are you kidding me, it should be virtualized here :-)
  237. QString query;
  238. switch(node->Type)
  239. {
  240. default:
  241. Q_ASSERT(node->Type == ctkDICOMModelPrivate::RootType);
  242. break;
  243. case ctkDICOMModelPrivate::RootType:
  244. //query = QString("SELECT FROM ");
  245. query = this->generateQuery("UID as UID, PatientsName as Name, PatientsAge as Age, PatientsBirthDate as Date, PatientID as \"Subject ID\"","Patients");
  246. break;
  247. case ctkDICOMModelPrivate::PatientType:
  248. //query = QString("SELECT FROM Studies WHERE PatientsUID='%1'").arg(node->UID);
  249. query = this->generateQuery("StudyInstanceUID as UID, StudyDescription as Name, ModalitiesInStudy as Scan, StudyDate as Date, AccessionNumber as Number, ReferringPhysician as Institution, ReferringPhysician as Referrer, PerformingPysiciansName as Performer", "Studies",QString("PatientsUID='%1'").arg(node->UID));
  250. break;
  251. case ctkDICOMModelPrivate::StudyType:
  252. //query = QString("SELECT SeriesInstanceUID as UID, SeriesDescription as Name, BodyPartExamined as Scan, SeriesDate as Date, AcquisitionNumber as Number FROM Series WHERE StudyInstanceUID='%1'").arg(node->UID);
  253. query = this->generateQuery("SeriesInstanceUID as UID, SeriesDescription as Name, BodyPartExamined as Scan, SeriesDate as Date, AcquisitionNumber as Number","Series",QString("StudyInstanceUID='%1'").arg(node->UID));
  254. break;
  255. case ctkDICOMModelPrivate::SeriesType:
  256. //query = QString("SELECT Filename as UID, Filename as Name, SeriesInstanceUID as Date FROM Images WHERE SeriesInstanceUID='%1'").arg(node->UID);
  257. query = this->generateQuery("Filename as UID, Filename as Name, SeriesInstanceUID as Date", "Images", QString("SeriesInstanceUID='%1'").arg(node->UID));
  258. break;
  259. case ctkDICOMModelPrivate::ImageType:
  260. break;
  261. }
  262. node->Query = QSqlQuery(query, this->DataBase);
  263. foreach(Node* child, node->Children)
  264. {
  265. this->updateQueries(child);
  266. }
  267. }
  268. //------------------------------------------------------------------------------
  269. void ctkDICOMModelPrivate::fetch(const QModelIndex& indexValue, int limit)
  270. {
  271. CTK_P(ctkDICOMModel);
  272. Node* node = this->nodeFromIndex(indexValue);
  273. if (node->AtEnd || limit <= node->RowCount || node->Fetching/*|| bottom.column() == -1*/)
  274. {
  275. return;
  276. }
  277. node->Fetching = true;
  278. int newRowCount;
  279. const int oldRowCount = node->RowCount;
  280. // try to seek directly
  281. if (node->Query.seek(limit - 1))
  282. {
  283. newRowCount = limit;
  284. }
  285. else
  286. {
  287. newRowCount = qMax(oldRowCount, 1);
  288. if (node->Query.seek(newRowCount - 1))
  289. {
  290. while (node->Query.next())
  291. {
  292. ++newRowCount;
  293. }
  294. }
  295. else
  296. {
  297. // empty or invalid query
  298. newRowCount = 0;
  299. }
  300. node->AtEnd = true; // this is the end.
  301. }
  302. if (newRowCount > 0 && newRowCount > node->RowCount)
  303. {
  304. p->beginInsertRows(indexValue, node->RowCount, newRowCount - 1);
  305. node->RowCount = newRowCount;
  306. node->Fetching = false;
  307. p->endInsertRows();
  308. }
  309. else
  310. {
  311. node->RowCount = newRowCount;
  312. node->Fetching = false;
  313. }
  314. }
  315. //------------------------------------------------------------------------------
  316. ctkDICOMModel::ctkDICOMModel(QObject* parentValue)
  317. {
  318. CTK_INIT_PRIVATE(ctkDICOMModel);
  319. ctk_d()->init();
  320. }
  321. //------------------------------------------------------------------------------
  322. ctkDICOMModel::~ctkDICOMModel()
  323. {
  324. }
  325. //------------------------------------------------------------------------------
  326. bool ctkDICOMModel::canFetchMore ( const QModelIndex & parentValue ) const
  327. {
  328. CTK_D(const ctkDICOMModel);
  329. Node* node = d->nodeFromIndex(parentValue);
  330. return !node->AtEnd;
  331. }
  332. //------------------------------------------------------------------------------
  333. int ctkDICOMModel::columnCount ( const QModelIndex & _parent ) const
  334. {
  335. CTK_D(const ctkDICOMModel);
  336. Q_UNUSED(_parent);
  337. return d->RootNode != 0 ? d->Headers.size() : 0;
  338. }
  339. //------------------------------------------------------------------------------
  340. QVariant ctkDICOMModel::data ( const QModelIndex & indexValue, int role ) const
  341. {
  342. CTK_D(const ctkDICOMModel);
  343. if (role & ~(Qt::DisplayRole | Qt::EditRole))
  344. {
  345. return QVariant();
  346. }
  347. QModelIndex indexParent = this->parent(indexValue);
  348. Node* parentNode = d->nodeFromIndex(indexParent);
  349. if (indexValue.row() >= parentNode->RowCount)
  350. {
  351. const_cast<ctkDICOMModelPrivate *>(d)->fetch(indexValue, indexValue.row());
  352. }
  353. /*
  354. if (!node->Query.seek(indexValue.row()))
  355. {
  356. qDebug() << node->Query.lastError();
  357. return QVariant();
  358. }
  359. */
  360. int field = parentNode->Query.record().indexOf(d->Headers[indexValue.column()]);
  361. if (field < 0)
  362. {
  363. return QString();
  364. }
  365. return d->value(indexParent, indexValue.row(), field);
  366. //return node->Query.value(field);
  367. }
  368. //------------------------------------------------------------------------------
  369. void ctkDICOMModel::fetchMore ( const QModelIndex & parentValue )
  370. {
  371. CTK_D(ctkDICOMModel);
  372. Node* node = d->nodeFromIndex(parentValue);
  373. d->fetch(parentValue, qMax(node->RowCount, 0) + 256);
  374. }
  375. //------------------------------------------------------------------------------
  376. Qt::ItemFlags ctkDICOMModel::flags ( const QModelIndex & indexValue ) const
  377. {
  378. return Qt::ItemIsSelectable | Qt::ItemIsEnabled;
  379. }
  380. //------------------------------------------------------------------------------
  381. bool ctkDICOMModel::hasChildren ( const QModelIndex & parentValue ) const
  382. {
  383. CTK_D(const ctkDICOMModel);
  384. if (parentValue.column() > 0)
  385. {
  386. return false;
  387. }
  388. Node* node = d->nodeFromIndex(parentValue);
  389. if (!node)
  390. {
  391. return false;
  392. }
  393. if (node->RowCount == 0 && !node->AtEnd)
  394. {
  395. //const_cast<qCTKDCMTKModelPrivate*>(d)->fetch(parentValue, 1);
  396. return node->Query.seek(0);
  397. }
  398. return node->RowCount > 0;
  399. }
  400. //------------------------------------------------------------------------------
  401. QVariant ctkDICOMModel::headerData(int section, Qt::Orientation orientation, int role)const
  402. {
  403. CTK_D(const ctkDICOMModel);
  404. if (role & ~(Qt::DisplayRole | Qt::EditRole))
  405. {
  406. return QVariant();
  407. }
  408. if (orientation == Qt::Vertical)
  409. {
  410. return section;
  411. }
  412. Q_ASSERT(orientation == Qt::Horizontal);
  413. Q_ASSERT(section < d->Headers.size());
  414. return d->Headers[section];
  415. }
  416. //------------------------------------------------------------------------------
  417. QModelIndex ctkDICOMModel::index ( int row, int column, const QModelIndex & parentValue ) const
  418. {
  419. CTK_D(const ctkDICOMModel);
  420. if (d->RootNode == 0 || parentValue.column() > 0)
  421. {
  422. return QModelIndex();
  423. }
  424. Node* parentNode = d->nodeFromIndex(parentValue);
  425. int field = parentNode->Query.record().indexOf("UID");
  426. QString uid = d->value(parentValue, row, field).toString();
  427. Node* node = 0;
  428. foreach(Node* tmpNode, parentNode->Children)
  429. {
  430. if (tmpNode->UID == uid)
  431. {
  432. node = tmpNode;
  433. break;
  434. }
  435. }
  436. if (node == 0)
  437. {
  438. node = d->createNode(row, parentValue);
  439. }
  440. return this->createIndex(row, column, node);
  441. }
  442. //------------------------------------------------------------------------------
  443. QModelIndex ctkDICOMModel::parent ( const QModelIndex & indexValue ) const
  444. {
  445. CTK_D(const ctkDICOMModel);
  446. Node* node = d->nodeFromIndex(indexValue);
  447. Q_ASSERT(node);
  448. Node* parentNode = node->Parent;
  449. if (parentNode == 0)
  450. {// node is root
  451. return QModelIndex();
  452. }
  453. return parentNode == d->RootNode ? QModelIndex() : this->createIndex(parentNode->Row, 0, parentNode);
  454. /* need to recalculate the parent row
  455. Node* greatParentNode = parentNode->Parent;
  456. if (greatParentNode == 0)
  457. {
  458. return QModelIndex();
  459. }
  460. int field = greatParentNode->Query.record().indexOf("UID");
  461. int row = -1;
  462. for (row = 0; row < greatParentNode->RowCount; ++row)
  463. {
  464. QString uid = d->value(greatParentNode, row, field).toString();
  465. if (uid == parentNode->UID)
  466. {
  467. break;
  468. }
  469. }
  470. Q_ASSERT(row < greatParentNode->RowCount);
  471. return this->createIndex(row, 0, parentNode);
  472. */
  473. }
  474. //------------------------------------------------------------------------------
  475. int ctkDICOMModel::rowCount ( const QModelIndex & parentValue ) const
  476. {
  477. CTK_D(const ctkDICOMModel);
  478. if (d->RootNode == 0 || parentValue.column() > 0)
  479. {
  480. return 0;
  481. }
  482. Node* node = d->nodeFromIndex(parentValue);
  483. Q_ASSERT(node);
  484. if (node->RowCount == 0 && !node->AtEnd)
  485. {
  486. //const_cast<ctkDICOMModelPrivate*>(d)->fetch(parentValue, 256);
  487. }
  488. return node->RowCount;
  489. }
  490. //------------------------------------------------------------------------------
  491. void ctkDICOMModel::setDatabase(const QSqlDatabase &db)
  492. {
  493. CTK_D(ctkDICOMModel);
  494. this->beginResetModel();
  495. d->DataBase = db;
  496. delete d->RootNode;
  497. d->RootNode = 0;
  498. if (d->DataBase.tables().empty())
  499. {
  500. //Q_ASSERT(d->DataBase.isOpen());
  501. this->endResetModel();
  502. return;
  503. }
  504. d->RootNode = d->createNode(-1, QModelIndex());
  505. this->endResetModel();
  506. // TODO, use hasQuerySize everywhere, not only in setDataBase()
  507. bool hasQuerySize = d->RootNode->Query.driver()->hasFeature(QSqlDriver::QuerySize);
  508. if (hasQuerySize && d->RootNode->Query.size() > 0)
  509. {
  510. int newRowCount= d->RootNode->Query.size();
  511. beginInsertRows(QModelIndex(), 0, qMax(0, newRowCount - 1));
  512. d->RootNode->RowCount = newRowCount;
  513. d->RootNode->AtEnd = true;
  514. endInsertRows();
  515. }
  516. d->fetch(QModelIndex(), 256);
  517. }
  518. //------------------------------------------------------------------------------
  519. void ctkDICOMModel::sort(int column, Qt::SortOrder order)
  520. {
  521. CTK_D(ctkDICOMModel);
  522. /* The following would work if there is no fetch involved.
  523. ORDER BY doesn't just apply on the fetched item. By sorting
  524. new items can show up in the model, and we need to be more
  525. careful
  526. emit layoutAboutToBeChanged();
  527. QModelIndexList oldIndexList = d->modelIndexList();
  528. d->Sort = QString("\"%1\" %2")
  529. .arg(d->Headers[column])
  530. .arg(order == Qt::AscendingOrder ? "ASC" : "DESC");
  531. d->updateQueries(d->RootNode);
  532. QModelIndexList newIndexList = d->modelIndexList();
  533. Q_ASSERT(oldIndexList.count() == newIndexList.count());
  534. this->changePersistentIndexList(oldIndexList, newIndexList);
  535. emit layoutChanged();
  536. */
  537. this->beginResetModel();
  538. delete d->RootNode;
  539. d->RootNode = 0;
  540. d->Sort = QString("\"%1\" %2")
  541. .arg(d->Headers[column])
  542. .arg(order == Qt::AscendingOrder ? "ASC" : "DESC");
  543. d->RootNode = d->createNode(-1, QModelIndex());
  544. this->endResetModel();
  545. }
  546. //------------------------------------------------------------------------------
  547. bool ctkDICOMModel::setHeaderData ( int section, Qt::Orientation orientation, const QVariant & value, int role)
  548. {
  549. CTK_D(ctkDICOMModel);
  550. if (role & ~(Qt::DisplayRole | Qt::EditRole))
  551. {
  552. return false;
  553. }
  554. if (orientation == Qt::Vertical)
  555. {
  556. return false;
  557. }
  558. if (value.toString() == d->Headers[section])
  559. {
  560. return false;
  561. }
  562. d->Headers[section] = value.toString();
  563. emit this->headerDataChanged(orientation, section, section);
  564. return true;
  565. }