ctkDICOMIndexer.cpp 10 KB

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