ctkDICOMModel.cpp 19 KB

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