ctkDICOMIndexer.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  1. /*=========================================================================
  2. Library: CTK
  3. Copyright (c) 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.apache.org/licenses/LICENSE-2.0.txt
  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 <QSqlQuery>
  16. #include <QSqlRecord>
  17. #include <QSqlError>
  18. #include <QVariant>
  19. #include <QDate>
  20. #include <QStringList>
  21. #include <QSet>
  22. #include <QFile>
  23. #include <QDirIterator>
  24. #include <QFileInfo>
  25. #include <QDebug>
  26. // ctkDICOM includes
  27. #include "ctkLogger.h"
  28. #include "ctkDICOMIndexer.h"
  29. #include "ctkDICOMIndexer_p.h"
  30. #include "ctkDICOMDatabase.h"
  31. // DCMTK includes
  32. #include <dcmtk/dcmdata/dcfilefo.h>
  33. #include <dcmtk/dcmdata/dcfilefo.h>
  34. #include <dcmtk/dcmdata/dcdeftag.h>
  35. #include <dcmtk/dcmdata/dcdatset.h>
  36. #include <dcmtk/ofstd/ofcond.h>
  37. #include <dcmtk/ofstd/ofstring.h>
  38. #include <dcmtk/ofstd/ofstd.h> /* for class OFStandard */
  39. #include <dcmtk/dcmdata/dcddirif.h> /* for class DicomDirInterface */
  40. #include <dcmtk/dcmimgle/dcmimage.h> /* for class DicomImage */
  41. #include <dcmtk/dcmimage/diregist.h> /* include support for color images */
  42. //------------------------------------------------------------------------------
  43. static ctkLogger logger("org.commontk.dicom.DICOMIndexer" );
  44. //------------------------------------------------------------------------------
  45. //------------------------------------------------------------------------------
  46. // ctkDICOMIndexerPrivate methods
  47. //------------------------------------------------------------------------------
  48. ctkDICOMIndexerPrivate::ctkDICOMIndexerPrivate(ctkDICOMIndexer& o) : q_ptr(&o), Canceled(false)
  49. {
  50. }
  51. //------------------------------------------------------------------------------
  52. ctkDICOMIndexerPrivate::~ctkDICOMIndexerPrivate()
  53. {
  54. }
  55. //------------------------------------------------------------------------------
  56. //------------------------------------------------------------------------------
  57. // ctkDICOMIndexer methods
  58. //------------------------------------------------------------------------------
  59. ctkDICOMIndexer::ctkDICOMIndexer(QObject *parent):d_ptr(new ctkDICOMIndexerPrivate(*this))
  60. {
  61. Q_UNUSED(parent);
  62. }
  63. //------------------------------------------------------------------------------
  64. ctkDICOMIndexer::~ctkDICOMIndexer()
  65. {
  66. }
  67. //------------------------------------------------------------------------------
  68. void ctkDICOMIndexer::addFile(ctkDICOMDatabase& database,
  69. const QString filePath,
  70. const QString& destinationDirectoryName)
  71. {
  72. std::cout << filePath.toStdString();
  73. if (!destinationDirectoryName.isEmpty())
  74. {
  75. logger.warn("Ignoring destinationDirectoryName parameter, just taking it as indication we should copy!");
  76. }
  77. emit indexingFilePath(filePath);
  78. database.insert(filePath, !destinationDirectoryName.isEmpty(), true);
  79. }
  80. //------------------------------------------------------------------------------
  81. void ctkDICOMIndexer::addDirectory(ctkDICOMDatabase& ctkDICOMDatabase,
  82. const QString& directoryName,
  83. const QString& destinationDirectoryName,
  84. bool includeHidden/*=true*/)
  85. {
  86. QStringList listOfFiles;
  87. QDir directory(directoryName);
  88. if(directory.exists("DICOMDIR"))
  89. {
  90. addDicomdir(ctkDICOMDatabase,directoryName,destinationDirectoryName);
  91. }
  92. else
  93. {
  94. QDir::Filters filters = QDir::Files;
  95. if (includeHidden)
  96. {
  97. filters |= QDir::Hidden;
  98. }
  99. QDirIterator it(directoryName, filters, QDirIterator::Subdirectories);
  100. while(it.hasNext())
  101. {
  102. listOfFiles << it.next();
  103. }
  104. emit foundFilesToIndex(listOfFiles.count());
  105. addListOfFiles(ctkDICOMDatabase,listOfFiles,destinationDirectoryName);
  106. }
  107. }
  108. //------------------------------------------------------------------------------
  109. void ctkDICOMIndexer::addListOfFiles(ctkDICOMDatabase& ctkDICOMDatabase,
  110. const QStringList& listOfFiles,
  111. const QString& destinationDirectoryName)
  112. {
  113. Q_D(ctkDICOMIndexer);
  114. QTime timeProbe;
  115. timeProbe.start();
  116. d->Canceled = false;
  117. int CurrentFileIndex = 0;
  118. int lastReportedPercent = 0;
  119. foreach(QString filePath, listOfFiles)
  120. {
  121. int percent = ( 100 * CurrentFileIndex ) / listOfFiles.size();
  122. if (lastReportedPercent / 10 < percent / 10)
  123. {
  124. // Reporting progress has a huge overhead (pending events are processed,
  125. // database is updated), therefore only report progress at every 10% increase
  126. emit this->progress(percent);
  127. lastReportedPercent = percent;
  128. }
  129. this->addFile(ctkDICOMDatabase, filePath, destinationDirectoryName);
  130. CurrentFileIndex++;
  131. if( d->Canceled )
  132. {
  133. break;
  134. }
  135. }
  136. float elapsedTimeInSeconds = timeProbe.elapsed() / 1000.0;
  137. qDebug()
  138. << QString("DICOM indexer has successfully processed %1 files [%2s]")
  139. .arg(CurrentFileIndex)
  140. .arg(QString::number(elapsedTimeInSeconds,'f', 2));
  141. emit this->indexingComplete();
  142. }
  143. //------------------------------------------------------------------------------
  144. bool ctkDICOMIndexer::addDicomdir(ctkDICOMDatabase& ctkDICOMDatabase,
  145. const QString& directoryName,
  146. const QString& destinationDirectoryName
  147. )
  148. {
  149. //Initialize dicomdir with directory path
  150. QString dcmFilePath = directoryName;
  151. dcmFilePath.append("/DICOMDIR");
  152. DcmDicomDir* dicomDir = new DcmDicomDir(dcmFilePath.toStdString().c_str());
  153. //Values to store records data at the moment only uid needed
  154. OFString patientsName, studyInstanceUID, seriesInstanceUID, sopInstanceUID, referencedFileName ;
  155. //Variables for progress operations
  156. QString instanceFilePath;
  157. QStringList listOfInstances;
  158. DcmDirectoryRecord* rootRecord = &(dicomDir->getRootRecord());
  159. DcmDirectoryRecord* patientRecord = NULL;
  160. DcmDirectoryRecord* studyRecord = NULL;
  161. DcmDirectoryRecord* seriesRecord = NULL;
  162. DcmDirectoryRecord* fileRecord = NULL;
  163. QTime timeProbe;
  164. timeProbe.start();
  165. /*Iterate over all records in dicomdir and setup path to the dataset of the filerecord
  166. then insert. the filerecord into the database.
  167. If any UID is missing the record and all of it's subelements won't be added to the database*/
  168. bool success = true;
  169. if(rootRecord != NULL)
  170. {
  171. while ((patientRecord = rootRecord->nextSub(patientRecord)) != NULL)
  172. {
  173. logger.debug( "Reading new Patient:" );
  174. if (patientRecord->findAndGetOFString(DCM_PatientName, patientsName).bad())
  175. {
  176. logger.warn( "DICOMDIR file at "+directoryName+" is invalid: patient name not found. All records belonging to this patient will be ignored.");
  177. success = false;
  178. continue;
  179. }
  180. logger.debug( "Patient's Name: " + QString(patientsName.c_str()) );
  181. while ((studyRecord = patientRecord->nextSub(studyRecord)) != NULL)
  182. {
  183. logger.debug( "Reading new Study:" );
  184. if (studyRecord->findAndGetOFString(DCM_StudyInstanceUID, studyInstanceUID).bad())
  185. {
  186. logger.warn( "DICOMDIR file at "+directoryName+" is invalid: study instance UID not found for patient "+ QString(patientsName.c_str())+". All records belonging to this study will be ignored.");
  187. success = false;
  188. continue;
  189. }
  190. logger.debug( "Study instance UID: " + QString(studyInstanceUID.c_str()) );
  191. while ((seriesRecord = studyRecord->nextSub(seriesRecord)) != NULL)
  192. {
  193. logger.debug( "Reading new Series:" );
  194. if (seriesRecord->findAndGetOFString(DCM_SeriesInstanceUID, seriesInstanceUID).bad())
  195. {
  196. logger.warn( "DICOMDIR file at "+directoryName+" is invalid: series instance UID not found for patient "+ QString(patientsName.c_str())+", study "+ QString(studyInstanceUID.c_str())+". All records belonging to this series will be ignored.");
  197. success = false;
  198. continue;
  199. }
  200. logger.debug( "Series instance UID: " + QString(seriesInstanceUID.c_str()) );
  201. while ((fileRecord = seriesRecord->nextSub(fileRecord)) != NULL)
  202. {
  203. if (fileRecord->findAndGetOFStringArray(DCM_ReferencedSOPInstanceUIDInFile, sopInstanceUID).bad()
  204. || fileRecord->findAndGetOFStringArray(DCM_ReferencedFileID,referencedFileName).bad())
  205. {
  206. logger.warn( "DICOMDIR file at "+directoryName+" is invalid: referenced SOP instance UID or file name is invalid for patient "
  207. + QString(patientsName.c_str())+", study "+ QString(studyInstanceUID.c_str())+", series "+ QString(seriesInstanceUID.c_str())+
  208. ". This file will be ignored.");
  209. success = false;
  210. continue;
  211. }
  212. //Get the filepath of the instance and insert it into a list
  213. instanceFilePath = directoryName;
  214. instanceFilePath.append("/");
  215. instanceFilePath.append(QString( referencedFileName.c_str() ));
  216. instanceFilePath.replace("\\","/");
  217. listOfInstances << instanceFilePath;
  218. }
  219. }
  220. }
  221. }
  222. float elapsedTimeInSeconds = timeProbe.elapsed() / 1000.0;
  223. qDebug()
  224. << QString("DICOM indexer has successfully processed DICOMDIR in %1 [%2s]")
  225. .arg(directoryName)
  226. .arg(QString::number(elapsedTimeInSeconds,'f', 2));
  227. emit foundFilesToIndex(listOfInstances.count());
  228. addListOfFiles(ctkDICOMDatabase,listOfInstances,destinationDirectoryName);
  229. }
  230. return success;
  231. }
  232. //------------------------------------------------------------------------------
  233. void ctkDICOMIndexer::refreshDatabase(ctkDICOMDatabase& dicomDatabase, const QString& directoryName)
  234. {
  235. Q_UNUSED(dicomDatabase);
  236. Q_UNUSED(directoryName);
  237. /*
  238. * Probably this should go to the database class as well
  239. * Or we have to extend the interface to make possible what we do here
  240. * without using SQL directly
  241. /// get all filenames from the database
  242. QSqlQuery allFilesQuery(dicomDatabase.database());
  243. QStringList databaseFileNames;
  244. QStringList filesToRemove;
  245. this->loggedExec(allFilesQuery, "SELECT Filename from Images;");
  246. while (allFilesQuery.next())
  247. {
  248. QString fileName = allFilesQuery.value(0).toString();
  249. databaseFileNames.append(fileName);
  250. if (! QFile::exists(fileName) )
  251. {
  252. filesToRemove.append(fileName);
  253. }
  254. }
  255. QSet<QString> filesytemFiles;
  256. QDirIterator dirIt(directoryName);
  257. while (dirIt.hasNext())
  258. {
  259. filesytemFiles.insert(dirIt.next());
  260. }
  261. // TODO: it looks like this function was never finished...
  262. //
  263. // I guess the next step is to remove all filesToRemove from the database
  264. // and also to add filesystemFiles into the database tables
  265. */
  266. }
  267. //------------------------------------------------------------------------------
  268. void ctkDICOMIndexer::waitForImportFinished()
  269. {
  270. // No-op - this had been used when the indexing was multi-threaded,
  271. // and has only been retained for API compatibility.
  272. }
  273. //----------------------------------------------------------------------------
  274. void ctkDICOMIndexer::cancel()
  275. {
  276. Q_D(ctkDICOMIndexer);
  277. d->Canceled = true;
  278. }