ctkDICOMIndexer.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  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. {
  85. QStringList listOfFiles;
  86. QDir directory(directoryName);
  87. if(directory.exists("DICOMDIR"))
  88. {
  89. addDicomdir(ctkDICOMDatabase,directoryName,destinationDirectoryName);
  90. }
  91. else
  92. {
  93. QDirIterator it(directoryName,QDir::Files,QDirIterator::Subdirectories);
  94. while(it.hasNext())
  95. {
  96. listOfFiles << it.next();
  97. }
  98. emit foundFilesToIndex(listOfFiles.count());
  99. addListOfFiles(ctkDICOMDatabase,listOfFiles,destinationDirectoryName);
  100. }
  101. }
  102. //------------------------------------------------------------------------------
  103. void ctkDICOMIndexer::addListOfFiles(ctkDICOMDatabase& ctkDICOMDatabase,
  104. const QStringList& listOfFiles,
  105. const QString& destinationDirectoryName)
  106. {
  107. Q_D(ctkDICOMIndexer);
  108. d->Canceled = false;
  109. int CurrentFileIndex = 0;
  110. foreach(QString filePath, listOfFiles)
  111. {
  112. int percent = ( 100 * CurrentFileIndex ) / listOfFiles.size();
  113. emit this->progress(percent);
  114. this->addFile(ctkDICOMDatabase, filePath, destinationDirectoryName);
  115. CurrentFileIndex++;
  116. if( d->Canceled )
  117. {
  118. break;
  119. }
  120. }
  121. emit this->indexingComplete();
  122. }
  123. //------------------------------------------------------------------------------
  124. bool ctkDICOMIndexer::addDicomdir(ctkDICOMDatabase& ctkDICOMDatabase,
  125. const QString& directoryName,
  126. const QString& destinationDirectoryName
  127. )
  128. {
  129. //Initialize dicomdir with directory path
  130. QString dcmFilePath = directoryName;
  131. dcmFilePath.append("/DICOMDIR");
  132. DcmDicomDir* dicomDir = new DcmDicomDir(dcmFilePath.toStdString().c_str());
  133. //Values to store records data at the moment only uid needed
  134. OFString patientsName, studyInstanceUID, seriesInstanceUID, sopInstanceUID, referencedFileName ;
  135. //Variables for progress operations
  136. QString instanceFilePath;
  137. QStringList listOfInstances;
  138. DcmDirectoryRecord* rootRecord = &(dicomDir->getRootRecord());
  139. DcmDirectoryRecord* patientRecord = NULL;
  140. DcmDirectoryRecord* studyRecord = NULL;
  141. DcmDirectoryRecord* seriesRecord = NULL;
  142. DcmDirectoryRecord* fileRecord = NULL;
  143. /*Iterate over all records in dicomdir and setup path to the dataset of the filerecord
  144. then insert. the filerecord into the database.
  145. If any UID is missing the record and all of it's subelements won't be added to the database*/
  146. bool success = true;
  147. if(rootRecord != NULL)
  148. {
  149. while ((patientRecord = rootRecord->nextSub(patientRecord)) != NULL)
  150. {
  151. logger.debug( "Reading new Patient:" );
  152. if (patientRecord->findAndGetOFString(DCM_PatientName, patientsName).bad())
  153. {
  154. logger.warn( "DICOMDIR file at "+directoryName+" is invalid: patient name not found. All records belonging to this patient will be ignored.");
  155. success = false;
  156. continue;
  157. }
  158. logger.debug( "Patient's Name: " + QString(patientsName.c_str()) );
  159. while ((studyRecord = patientRecord->nextSub(studyRecord)) != NULL)
  160. {
  161. logger.debug( "Reading new Study:" );
  162. if (studyRecord->findAndGetOFString(DCM_StudyInstanceUID, studyInstanceUID).bad())
  163. {
  164. 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.");
  165. success = false;
  166. continue;
  167. }
  168. logger.debug( "Study instance UID: " + QString(studyInstanceUID.c_str()) );
  169. while ((seriesRecord = studyRecord->nextSub(seriesRecord)) != NULL)
  170. {
  171. logger.debug( "Reading new Series:" );
  172. if (seriesRecord->findAndGetOFString(DCM_SeriesInstanceUID, seriesInstanceUID).bad())
  173. {
  174. 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.");
  175. success = false;
  176. continue;
  177. }
  178. logger.debug( "Series instance UID: " + QString(seriesInstanceUID.c_str()) );
  179. while ((fileRecord = seriesRecord->nextSub(fileRecord)) != NULL)
  180. {
  181. if (fileRecord->findAndGetOFStringArray(DCM_ReferencedSOPInstanceUIDInFile, sopInstanceUID).bad()
  182. || fileRecord->findAndGetOFStringArray(DCM_ReferencedFileID,referencedFileName).bad())
  183. {
  184. logger.warn( "DICOMDIR file at "+directoryName+" is invalid: referenced SOP instance UID or file name is invalid for patient "
  185. + QString(patientsName.c_str())+", study "+ QString(studyInstanceUID.c_str())+", series "+ QString(seriesInstanceUID.c_str())+
  186. ". This file will be ignored.");
  187. success = false;
  188. continue;
  189. }
  190. //Get the filepath of the instance and insert it into a list
  191. instanceFilePath = directoryName;
  192. instanceFilePath.append("/");
  193. instanceFilePath.append(QString( referencedFileName.c_str() ));
  194. instanceFilePath.replace("\\","/");
  195. listOfInstances << instanceFilePath;
  196. }
  197. }
  198. }
  199. }
  200. emit foundFilesToIndex(listOfInstances.count());
  201. addListOfFiles(ctkDICOMDatabase,listOfInstances,destinationDirectoryName);
  202. }
  203. return success;
  204. }
  205. //------------------------------------------------------------------------------
  206. void ctkDICOMIndexer::refreshDatabase(ctkDICOMDatabase& dicomDatabase, const QString& directoryName)
  207. {
  208. Q_UNUSED(dicomDatabase);
  209. Q_UNUSED(directoryName);
  210. /*
  211. * Probably this should go to the database class as well
  212. * Or we have to extend the interface to make possible what we do here
  213. * without using SQL directly
  214. /// get all filenames from the database
  215. QSqlQuery allFilesQuery(dicomDatabase.database());
  216. QStringList databaseFileNames;
  217. QStringList filesToRemove;
  218. this->loggedExec(allFilesQuery, "SELECT Filename from Images;");
  219. while (allFilesQuery.next())
  220. {
  221. QString fileName = allFilesQuery.value(0).toString();
  222. databaseFileNames.append(fileName);
  223. if (! QFile::exists(fileName) )
  224. {
  225. filesToRemove.append(fileName);
  226. }
  227. }
  228. QSet<QString> filesytemFiles;
  229. QDirIterator dirIt(directoryName);
  230. while (dirIt.hasNext())
  231. {
  232. filesytemFiles.insert(dirIt.next());
  233. }
  234. // TODO: it looks like this function was never finished...
  235. //
  236. // I guess the next step is to remove all filesToRemove from the database
  237. // and also to add filesystemFiles into the database tables
  238. */
  239. }
  240. //------------------------------------------------------------------------------
  241. void ctkDICOMIndexer::waitForImportFinished()
  242. {
  243. // No-op - this had been used when the indexing was multi-threaded,
  244. // and has only been retained for API compatibility.
  245. }
  246. //----------------------------------------------------------------------------
  247. void ctkDICOMIndexer::cancel()
  248. {
  249. Q_D(ctkDICOMIndexer);
  250. d->Canceled = true;
  251. }