ctkDICOMQuery.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505
  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 <QVariant>
  18. #include <QDate>
  19. #include <QStringList>
  20. #include <QSet>
  21. #include <QFile>
  22. #include <QDirIterator>
  23. #include <QFileInfo>
  24. #include <QDebug>
  25. // ctkDICOMCore includes
  26. #include "ctkDICOMQuery.h"
  27. #include "ctkLogger.h"
  28. // DCMTK includes
  29. #include "dcmtk/dcmnet/dimse.h"
  30. #include "dcmtk/dcmnet/diutil.h"
  31. #include <dcmtk/dcmdata/dcfilefo.h>
  32. #include <dcmtk/dcmdata/dcfilefo.h>
  33. #include <dcmtk/dcmdata/dcdeftag.h>
  34. #include <dcmtk/dcmdata/dcdatset.h>
  35. #include <dcmtk/ofstd/ofcond.h>
  36. #include <dcmtk/ofstd/ofstring.h>
  37. #include <dcmtk/ofstd/ofstd.h> /* for class OFStandard */
  38. #include <dcmtk/dcmdata/dcddirif.h> /* for class DicomDirInterface */
  39. // NOTE: using ctk stand-in class for now - switch back
  40. // to dcmtk's scu.h when cget support is in a release version
  41. //#include <dcmtk/dcmnet/scu.h>
  42. #include <ctkDcmSCU.h>
  43. static ctkLogger logger ( "org.commontk.dicom.DICOMQuery" );
  44. //------------------------------------------------------------------------------
  45. // A customized implemenation so that Qt signals can be emitted
  46. // when query results are obtained
  47. class ctkDICOMQuerySCUPrivate : public ctkDcmSCU
  48. {
  49. public:
  50. ctkDICOMQuery *query;
  51. ctkDICOMQuerySCUPrivate()
  52. {
  53. this->query = 0;
  54. };
  55. ~ctkDICOMQuerySCUPrivate() {};
  56. virtual OFCondition handleFINDResponse(const T_ASC_PresentationContextID presID,
  57. QRResponse *response,
  58. OFBool &waitForNextResponse)
  59. {
  60. if (this->query)
  61. {
  62. logger.debug ( "FIND RESPONSE" );
  63. emit this->query->debug("Got a find response!");
  64. return this->ctkDcmSCU::handleFINDResponse(presID, response, waitForNextResponse);
  65. }
  66. return DIMSE_NULLKEY;
  67. };
  68. };
  69. //------------------------------------------------------------------------------
  70. class ctkDICOMQueryPrivate
  71. {
  72. public:
  73. ctkDICOMQueryPrivate();
  74. ~ctkDICOMQueryPrivate();
  75. /// Add a StudyInstanceUID to be queried
  76. void addStudyInstanceUIDAndDataset(const QString& StudyInstanceUID, DcmDataset* dataset );
  77. QString CallingAETitle;
  78. QString CalledAETitle;
  79. QString Host;
  80. int Port;
  81. bool PreferCGET;
  82. QMap<QString,QVariant> Filters;
  83. ctkDICOMQuerySCUPrivate SCU;
  84. DcmDataset* Query;
  85. QStringList StudyInstanceUIDList;
  86. QList<DcmDataset*> StudyDatasetList;
  87. bool Canceled;
  88. };
  89. //------------------------------------------------------------------------------
  90. // ctkDICOMQueryPrivate methods
  91. //------------------------------------------------------------------------------
  92. ctkDICOMQueryPrivate::ctkDICOMQueryPrivate()
  93. {
  94. this->Query = new DcmDataset();
  95. this->Port = 0;
  96. this->Canceled = false;
  97. this->PreferCGET = true;
  98. }
  99. //------------------------------------------------------------------------------
  100. ctkDICOMQueryPrivate::~ctkDICOMQueryPrivate()
  101. {
  102. delete this->Query;
  103. }
  104. //------------------------------------------------------------------------------
  105. void ctkDICOMQueryPrivate::addStudyInstanceUIDAndDataset( const QString& s, DcmDataset* dataset )
  106. {
  107. this->StudyInstanceUIDList.append ( s );
  108. this->StudyDatasetList.append ( dataset );
  109. }
  110. //------------------------------------------------------------------------------
  111. // ctkDICOMQuery methods
  112. //------------------------------------------------------------------------------
  113. ctkDICOMQuery::ctkDICOMQuery(QObject* parentObject)
  114. : QObject(parentObject)
  115. , d_ptr(new ctkDICOMQueryPrivate)
  116. {
  117. Q_D(ctkDICOMQuery);
  118. d->SCU.query = this; // give the dcmtk level access to this for emitting signals
  119. }
  120. //------------------------------------------------------------------------------
  121. ctkDICOMQuery::~ctkDICOMQuery()
  122. {
  123. }
  124. /// Set methods for connectivity
  125. //------------------------------------------------------------------------------
  126. void ctkDICOMQuery::setCallingAETitle( const QString& callingAETitle )
  127. {
  128. Q_D(ctkDICOMQuery);
  129. d->CallingAETitle = callingAETitle;
  130. }
  131. //------------------------------------------------------------------------------
  132. QString ctkDICOMQuery::callingAETitle() const
  133. {
  134. Q_D(const ctkDICOMQuery);
  135. return d->CallingAETitle;
  136. }
  137. //------------------------------------------------------------------------------
  138. void ctkDICOMQuery::setCalledAETitle( const QString& calledAETitle )
  139. {
  140. Q_D(ctkDICOMQuery);
  141. d->CalledAETitle = calledAETitle;
  142. }
  143. //------------------------------------------------------------------------------
  144. QString ctkDICOMQuery::calledAETitle()const
  145. {
  146. Q_D(const ctkDICOMQuery);
  147. return d->CalledAETitle;
  148. }
  149. //------------------------------------------------------------------------------
  150. void ctkDICOMQuery::setHost( const QString& host )
  151. {
  152. Q_D(ctkDICOMQuery);
  153. d->Host = host;
  154. }
  155. //------------------------------------------------------------------------------
  156. QString ctkDICOMQuery::host() const
  157. {
  158. Q_D(const ctkDICOMQuery);
  159. return d->Host;
  160. }
  161. //------------------------------------------------------------------------------
  162. void ctkDICOMQuery::setPort ( int port )
  163. {
  164. Q_D(ctkDICOMQuery);
  165. d->Port = port;
  166. }
  167. //------------------------------------------------------------------------------
  168. int ctkDICOMQuery::port()const
  169. {
  170. Q_D(const ctkDICOMQuery);
  171. return d->Port;
  172. }
  173. //------------------------------------------------------------------------------
  174. void ctkDICOMQuery::setPreferCGET ( bool preferCGET )
  175. {
  176. Q_D(ctkDICOMQuery);
  177. d->PreferCGET = preferCGET;
  178. }
  179. //------------------------------------------------------------------------------
  180. bool ctkDICOMQuery::preferCGET()const
  181. {
  182. Q_D(const ctkDICOMQuery);
  183. return d->PreferCGET;
  184. }
  185. //------------------------------------------------------------------------------
  186. void ctkDICOMQuery::setFilters( const QMap<QString,QVariant>& filters )
  187. {
  188. Q_D(ctkDICOMQuery);
  189. d->Filters = filters;
  190. }
  191. //------------------------------------------------------------------------------
  192. QMap<QString,QVariant> ctkDICOMQuery::filters()const
  193. {
  194. Q_D(const ctkDICOMQuery);
  195. return d->Filters;
  196. }
  197. //------------------------------------------------------------------------------
  198. QStringList ctkDICOMQuery::studyInstanceUIDQueried()const
  199. {
  200. Q_D(const ctkDICOMQuery);
  201. return d->StudyInstanceUIDList;
  202. }
  203. //------------------------------------------------------------------------------
  204. bool ctkDICOMQuery::query(ctkDICOMDatabase& database )
  205. {
  206. //// turn on logging if needed for debug:
  207. //dcmtk::log4cplus::Logger log = dcmtk::log4cplus::Logger::getRoot();
  208. //log.setLogLevel(OFLogger::DEBUG_LOG_LEVEL);
  209. // ctkDICOMDatabase::setDatabase ( database );
  210. Q_D(ctkDICOMQuery);
  211. // In the following, we emit progress(int) after progress(QString), this
  212. // is in case the connected object doesn't refresh its ui when the progress
  213. // message is updated but only if the progress value is (e.g. QProgressDialog)
  214. if ( database.database().isOpen() )
  215. {
  216. logger.debug ( "DB open in Query" );
  217. emit progress("DB open in Query");
  218. }
  219. else
  220. {
  221. logger.debug ( "DB not open in Query" );
  222. emit progress("DB not open in Query");
  223. }
  224. emit progress(0);
  225. if (d->Canceled) {return false;}
  226. d->StudyInstanceUIDList.clear();
  227. d->SCU.setAETitle ( OFString(this->callingAETitle().toStdString().c_str()) );
  228. d->SCU.setPeerAETitle ( OFString(this->calledAETitle().toStdString().c_str()) );
  229. d->SCU.setPeerHostName ( OFString(this->host().toStdString().c_str()) );
  230. d->SCU.setPeerPort ( this->port() );
  231. logger.error ( "Setting Transfer Syntaxes" );
  232. emit progress("Setting Transfer Syntaxes");
  233. emit progress(10);
  234. if (d->Canceled) {return false;}
  235. OFList<OFString> transferSyntaxes;
  236. transferSyntaxes.push_back ( UID_LittleEndianExplicitTransferSyntax );
  237. transferSyntaxes.push_back ( UID_BigEndianExplicitTransferSyntax );
  238. transferSyntaxes.push_back ( UID_LittleEndianImplicitTransferSyntax );
  239. d->SCU.addPresentationContext ( UID_FINDStudyRootQueryRetrieveInformationModel, transferSyntaxes );
  240. // d->SCU.addPresentationContext ( UID_VerificationSOPClass, transferSyntaxes );
  241. if ( !d->SCU.initNetwork().good() )
  242. {
  243. logger.error( "Error initializing the network" );
  244. emit progress("Error initializing the network");
  245. emit progress(100);
  246. return false;
  247. }
  248. logger.debug ( "Negotiating Association" );
  249. emit progress("Negotiating Association");
  250. emit progress(20);
  251. if (d->Canceled) {return false;}
  252. OFCondition result = d->SCU.negotiateAssociation();
  253. if (result.bad())
  254. {
  255. logger.error( "Error negotiating the association: " + QString(result.text()) );
  256. emit progress("Error negotiating the association");
  257. emit progress(100);
  258. return false;
  259. }
  260. // Clear the query
  261. d->Query->clear();
  262. // Insert all keys that we like to receive values for
  263. d->Query->insertEmptyElement ( DCM_PatientID );
  264. d->Query->insertEmptyElement ( DCM_PatientName );
  265. d->Query->insertEmptyElement ( DCM_PatientBirthDate );
  266. d->Query->insertEmptyElement ( DCM_StudyID );
  267. d->Query->insertEmptyElement ( DCM_StudyInstanceUID );
  268. d->Query->insertEmptyElement ( DCM_StudyDescription );
  269. d->Query->insertEmptyElement ( DCM_StudyDate );
  270. d->Query->insertEmptyElement ( DCM_StudyTime );
  271. d->Query->insertEmptyElement ( DCM_ModalitiesInStudy );
  272. d->Query->insertEmptyElement ( DCM_AccessionNumber );
  273. d->Query->insertEmptyElement ( DCM_NumberOfStudyRelatedInstances ); // Number of images in the series
  274. d->Query->insertEmptyElement ( DCM_NumberOfStudyRelatedSeries ); // Number of series in the study
  275. // Make clear we define our search values in ISO Latin 1 (default would be ASCII)
  276. d->Query->putAndInsertOFStringArray(DCM_SpecificCharacterSet, "ISO_IR 100");
  277. d->Query->putAndInsertString ( DCM_QueryRetrieveLevel, "STUDY" );
  278. /* Now, for all keys that the user provided for filtering on STUDY level,
  279. * overwrite empty keys with value. For now, only Patient's Name, Patient ID,
  280. * Study Description, Modalities in Study, and Study Date are used.
  281. */
  282. QString seriesDescription;
  283. foreach( QString key, d->Filters.keys() )
  284. {
  285. if ( key == QString("Name") && !d->Filters[key].toString().isEmpty())
  286. {
  287. // make the filter a wildcard in dicom style
  288. d->Query->putAndInsertString( DCM_PatientName,
  289. (QString("*") + d->Filters[key].toString() + QString("*")).toAscii().data());
  290. }
  291. else if ( key == QString("Study") && !d->Filters[key].toString().isEmpty())
  292. {
  293. // make the filter a wildcard in dicom style
  294. d->Query->putAndInsertString( DCM_StudyDescription,
  295. (QString("*") + d->Filters[key].toString() + QString("*")).toAscii().data());
  296. }
  297. else if ( key == QString("ID") && !d->Filters[key].toString().isEmpty())
  298. {
  299. // make the filter a wildcard in dicom style
  300. d->Query->putAndInsertString( DCM_PatientID,
  301. (QString("*") + d->Filters[key].toString() + QString("*")).toAscii().data());
  302. }
  303. else if ( key == QString("Modalities") && !d->Filters[key].toString().isEmpty())
  304. {
  305. // make the filter be an "OR" of modalities using backslash (dicom-style)
  306. QString modalitySearch("");
  307. foreach (const QString& modality, d->Filters[key].toStringList())
  308. {
  309. modalitySearch += modality + QString("\\");
  310. }
  311. modalitySearch.chop(1); // remove final backslash
  312. logger.debug("modalityInStudySearch " + modalitySearch);
  313. d->Query->putAndInsertString( DCM_ModalitiesInStudy, modalitySearch.toAscii().data() );
  314. }
  315. // Rememer Series Description for later series query if we go through the keys now
  316. else if ( key == QString("Series") && !d->Filters[key].toString().isEmpty())
  317. {
  318. // make the filter a wildcard in dicom style
  319. seriesDescription = "*" + d->Filters[key].toString() + "*";
  320. }
  321. else
  322. {
  323. logger.debug("Ignoring unknown search key: " + key);
  324. }
  325. }
  326. if ( d->Filters.keys().contains("StartDate") && d->Filters.keys().contains("EndDate") )
  327. {
  328. QString dateRange = d->Filters["StartDate"].toString() +
  329. QString("-") +
  330. d->Filters["EndDate"].toString();
  331. d->Query->putAndInsertString ( DCM_StudyDate, dateRange.toAscii().data() );
  332. logger.debug("Query on study date " + dateRange);
  333. }
  334. emit progress(30);
  335. if (d->Canceled) {return false;}
  336. OFList<QRResponse *> responses;
  337. Uint16 presentationContext = 0;
  338. // Check for any accepted presentation context for FIND in study root (dont care about transfer syntax)
  339. presentationContext = d->SCU.findPresentationContextID ( UID_FINDStudyRootQueryRetrieveInformationModel, "");
  340. if ( presentationContext == 0 )
  341. {
  342. logger.error ( "Failed to find acceptable presentation context" );
  343. emit progress("Failed to find acceptable presentation context");
  344. }
  345. else
  346. {
  347. logger.info ( "Found useful presentation context" );
  348. emit progress("Found useful presentation context");
  349. }
  350. emit progress(40);
  351. if (d->Canceled) {return false;}
  352. OFCondition status = d->SCU.sendFINDRequest ( presentationContext, d->Query, &responses );
  353. if ( !status.good() )
  354. {
  355. logger.error ( "Find failed" );
  356. emit progress("Find failed");
  357. d->SCU.closeAssociation ( DCMSCU_RELEASE_ASSOCIATION );
  358. emit progress(100);
  359. return false;
  360. }
  361. logger.debug ( "Find succeded");
  362. emit progress("Find succeded");
  363. emit progress(50);
  364. if (d->Canceled) {return false;}
  365. for ( OFIterator<QRResponse*> it = responses.begin(); it != responses.end(); it++ )
  366. {
  367. DcmDataset *dataset = (*it)->m_dataset;
  368. if ( dataset != NULL ) // the last response is always empty
  369. {
  370. database.insert ( dataset, false /* do not store to disk*/, false /* no thumbnail*/);
  371. OFString StudyInstanceUID;
  372. dataset->findAndGetOFString ( DCM_StudyInstanceUID, StudyInstanceUID );
  373. d->addStudyInstanceUIDAndDataset ( StudyInstanceUID.c_str(), dataset );
  374. emit progress(QString("Processing: ") + QString(StudyInstanceUID.c_str()));
  375. emit progress(50);
  376. if (d->Canceled) {return false;}
  377. }
  378. }
  379. /* Only ask for series attributes now. This requires kicking out the rest of former query. */
  380. d->Query->clear();
  381. d->Query->insertEmptyElement ( DCM_SeriesNumber );
  382. d->Query->insertEmptyElement ( DCM_SeriesDescription );
  383. d->Query->insertEmptyElement ( DCM_SeriesInstanceUID );
  384. d->Query->insertEmptyElement ( DCM_SeriesDate );
  385. d->Query->insertEmptyElement ( DCM_SeriesTime );
  386. d->Query->insertEmptyElement ( DCM_Modality );
  387. d->Query->insertEmptyElement ( DCM_NumberOfSeriesRelatedInstances ); // Number of images in the series
  388. /* Add user-defined filters */
  389. d->Query->putAndInsertOFStringArray(DCM_SeriesDescription, seriesDescription.toLatin1().data());
  390. // Now search each within each Study that was identified
  391. d->Query->putAndInsertString ( DCM_QueryRetrieveLevel, "SERIES" );
  392. float progressRatio = 25. / d->StudyInstanceUIDList.count();
  393. int i = 0;
  394. QListIterator<DcmDataset*> datasetIterator(d->StudyDatasetList);
  395. foreach ( QString StudyInstanceUID, d->StudyInstanceUIDList )
  396. {
  397. DcmDataset *studyDataset = datasetIterator.next();
  398. DcmElement *patientName, *patientID;
  399. studyDataset->findAndGetElement(DCM_PatientName, patientName);
  400. studyDataset->findAndGetElement(DCM_PatientID, patientID);
  401. logger.debug ( "Starting Series C-FIND for Study: " + StudyInstanceUID );
  402. emit progress(QString("Starting Series C-FIND for Study: ") + StudyInstanceUID);
  403. emit progress(50 + (progressRatio * i++));
  404. if (d->Canceled) {return false;}
  405. d->Query->putAndInsertString ( DCM_StudyInstanceUID, StudyInstanceUID.toStdString().c_str() );
  406. OFList<QRResponse *> responses;
  407. status = d->SCU.sendFINDRequest ( presentationContext, d->Query, &responses );
  408. if ( status.good() )
  409. {
  410. for ( OFIterator<QRResponse*> it = responses.begin(); it != responses.end(); it++ )
  411. {
  412. DcmDataset *dataset = (*it)->m_dataset;
  413. if ( dataset != NULL )
  414. {
  415. // add the patient elements not provided for the series level query
  416. dataset->insert( patientName, true );
  417. dataset->insert( patientID, true );
  418. // insert series dataset
  419. database.insert ( dataset, false /* do not store */, false /* no thumbnail */ );
  420. }
  421. }
  422. logger.debug ( "Find succeded on Series level for Study: " + StudyInstanceUID );
  423. emit progress(QString("Find succeded on Series level for Study: ") + StudyInstanceUID);
  424. emit progress(50 + (progressRatio * i++));
  425. if (d->Canceled) {return false;}
  426. }
  427. else
  428. {
  429. logger.error ( "Find on Series level failed for Study: " + StudyInstanceUID );
  430. emit progress(QString("Find on Series level failed for Study: ") + StudyInstanceUID);
  431. }
  432. emit progress(50 + (progressRatio * i++));
  433. if (d->Canceled) {return false;}
  434. }
  435. d->SCU.closeAssociation ( DCMSCU_RELEASE_ASSOCIATION );
  436. emit progress(100);
  437. return true;
  438. }
  439. //----------------------------------------------------------------------------
  440. void ctkDICOMQuery::cancel()
  441. {
  442. Q_D(ctkDICOMQuery);
  443. d->Canceled = true;
  444. }