ViewProperties::ViewProperties(const KUrl& url) : m_changedProps(false), m_autoSave(true), m_node(0) { GeneralSettings* settings = DolphinSettings::instance().generalSettings(); const bool useGlobalViewProps = settings->globalViewProps(); bool useDetailsViewWithPath = false; // We try and save it to the file .directory in the directory being viewed. // If the directory is not writable by the user or the directory is not local, // we store the properties information in a local file. if (useGlobalViewProps) { m_filePath = destinationDir("global"); } else if (url.protocol().contains("search")) { m_filePath = destinationDir("search"); useDetailsViewWithPath = true; } else if (url.protocol() == QLatin1String("trash")) { m_filePath = destinationDir("trash"); useDetailsViewWithPath = true; } else if (url.isLocalFile()) { m_filePath = url.toLocalFile(); const QFileInfo info(m_filePath); if (!info.isWritable() || !isPartOfHome(m_filePath)) { m_filePath = destinationDir("local") + m_filePath; } } else { m_filePath = destinationDir("remote") + m_filePath; } const QString file = m_filePath + QDir::separator() + QLatin1String(".directory"); m_node = new ViewPropertySettings(KSharedConfig::openConfig(file)); // If the .directory file does not exist or the timestamp is too old, // use default values instead. const bool useDefaultProps = (!useGlobalViewProps || useDetailsViewWithPath) && (!QFileInfo(file).exists() || (m_node->timestamp() < settings->viewPropsTimestamp())); if (useDefaultProps) { if (useDetailsViewWithPath) { setViewMode(DolphinView::DetailsView); setAdditionalInfo(KFileItemDelegate::InformationList() << KFileItemDelegate::LocalPathOrUrl); } else { // The global view-properties act as default for directories without // any view-property configuration settings->setGlobalViewProps(true); ViewProperties defaultProps(url); setDirProperties(defaultProps); settings->setGlobalViewProps(false); m_changedProps = false; } } }
void Configurator::exportThemes() const { // copy default themes from resources to user hard disk QDir resourceDir(THEMES_FOLDER_IN_RESOURCES); QDir themesDir = getThemesDir(); qDebug() << "Exporting themes from " << resourceDir.absolutePath() << " to " << themesDir.absolutePath(); QStringList themesInResources = resourceDir.entryList(QDir::Dirs | QDir::NoDotAndDotDot); for (const QString &themeDir : themesInResources) { QDir themeFolderInResources(resourceDir.absoluteFilePath(themeDir)); themesDir.mkdir(themeDir); QDir destinationDir(themesDir.absoluteFilePath(themeDir)); qDebug() << "Exporting theme " << themeDir << " from " << themeFolderInResources.absolutePath() << " to " << destinationDir.absolutePath(); QString fullPath = themeFolderInResources.absolutePath() + "/css/themes/" + themeDir; QDir pathInResources(fullPath); QStringList themeFiles = pathInResources.entryList(QDir::Files); // css files for (const QString &themeCSSFile : themeFiles) { QString sourcePath = pathInResources.absoluteFilePath(themeCSSFile); QString destinationPath = destinationDir.absoluteFilePath(themeCSSFile); if (QFile::copy(sourcePath, destinationPath)) QFile(destinationPath).setPermissions(QFile::ReadOwner | QFile::WriteOwner); else qDebug(jtConfigurator) << "Can't copy " << sourcePath << " to " << destinationPath; } } }
QScriptValue File::renamePrivate(const QString &source, const QString &destination, bool noErrorDialog, bool noConfirmDialog, bool noProgressDialog, bool allowUndo, bool createDestinationDirectory, QScriptContext *context, QScriptEngine *engine) { Q_UNUSED(engine) #ifdef Q_OS_LINUX movePrivate(source, destination, noErrorDialog, noConfirmDialog, noProgressDialog, allowUndo, createDestinationDirectory, context, engine); #endif #ifdef Q_OS_WIN Q_UNUSED(createDestinationDirectory) QDir sourceDir(source); QDir destinationDir(destination); std::wstring wideSource = QDir::toNativeSeparators(sourceDir.absolutePath()).toStdWString(); wideSource += L'\0'; std::wstring wideDestination = QDir::toNativeSeparators(destinationDir.absolutePath()).toStdWString(); wideDestination += L'\0'; SHFILEOPSTRUCT shFileOpStruct; shFileOpStruct.hwnd = 0; shFileOpStruct.wFunc = FO_RENAME; shFileOpStruct.pFrom = wideSource.c_str(); shFileOpStruct.pTo = wideDestination.c_str(); shFileOpStruct.fFlags = 0; shFileOpStruct.fAnyOperationsAborted = false; shFileOpStruct.lpszProgressTitle = 0; shFileOpStruct.hNameMappings = 0; if(noErrorDialog) shFileOpStruct.fFlags |= FOF_NOERRORUI; if(noConfirmDialog) shFileOpStruct.fFlags |= (FOF_NOCONFIRMATION | FOF_NOCONFIRMMKDIR); if(noProgressDialog) shFileOpStruct.fFlags |= FOF_SILENT; if(allowUndo) shFileOpStruct.fFlags |= FOF_ALLOWUNDO; int result = SHFileOperation(&shFileOpStruct); if(result != 0) { throwError(context, engine, "RenameError", tr("Rename failed: %1").arg(getErrorString(result))); return context->thisObject(); } if(shFileOpStruct.fAnyOperationsAborted) { throwError(context, engine, "RenameAbortedError", tr("Rename failed: aborted")); return context->thisObject(); } #endif return context->thisObject(); }
void ResourceManager::download() { QPushButton *button = dynamic_cast<QPushButton*>( sender() ); QString data = buttonMap[button]; QString hash = buttonHashMap[button]; button->setText(tr("Updating")); button->setDisabled(1); QString baseAddress = baseAddr + data; DownloadUtils *dl = new DownloadUtils(this); dl->setTarget(baseAddress); qDebug() << baseAddress; QString localPath = dataPath + "/locale/" + data.split('/')[1]; dl->setLocalFile(localPath); dl->download(); if( !dl->saveFile() || !verifyFile(localPath, hash)) { button->setText(tr("Failed, try again")); button->setEnabled(1); } else { // unzip and delete MQZipReader zipFile(localPath); QFileInfo zfi(localPath); QString destinationDir(zfi.absolutePath()); QList<MQZipReader::FileInfo> allFiles = zipFile.fileInfoList(); bool result = true; foreach (MQZipReader::FileInfo fi, allFiles) { const QString absPath = destinationDir + QDir::separator() + fi.filePath; if (fi.isFile) { QFile f(absPath); if (!f.open(QIODevice::WriteOnly)) { result = false; break; } f.write(zipFile.fileData(fi.filePath)); f.setPermissions(fi.permissions); f.close(); } } zipFile.close(); if (result) { QFile::remove(localPath); button->setText(tr("Updated")); // retranslate the UI if current language is updated if (data == buttonMap.first()) setMscoreLocale(localeName); } else { button->setText(tr("Failed, try again")); button->setEnabled(1); } } }
bool SharePlugin::receivePackage(const NetworkPackage& np) { /* //TODO: Write a test like this if (np.type() == PACKAGE_TYPE_PING) { qCDebug(KDECONNECT_PLUGIN_SHARE) << "sending file" << (QDesktopServices::storageLocation(QDesktopServices::HomeLocation) + "/.bashrc"); NetworkPackage out(PACKAGE_TYPE_SHARE); out.set("filename", mDestinationDir + "itworks.txt"); AutoClosingQFile* file = new AutoClosingQFile(QDesktopServices::storageLocation(QDesktopServices::HomeLocation) + "/.bashrc"); //Test file to transfer out.setPayload(file, file->size()); device()->sendPackage(out); return true; } */ qCDebug(KDECONNECT_PLUGIN_SHARE) << "File transfer"; if (np.hasPayload()) { //qCDebug(KDECONNECT_PLUGIN_SHARE) << "receiving file"; const QString filename = np.get<QString>("filename", QString::number(QDateTime::currentMSecsSinceEpoch())); const QUrl dir = destinationDir().adjusted(QUrl::StripTrailingSlash); QUrl destination(dir.toString() + '/' + filename); if (destination.isLocalFile() && QFile::exists(destination.toLocalFile())) { destination = QUrl(dir.toString() + '/' + KIO::suggestName(dir, filename)); } FileTransferJob* job = np.createPayloadTransferJob(destination); job->setDeviceName(device()->name()); connect(job, SIGNAL(result(KJob*)), this, SLOT(finished(KJob*))); KIO::getJobTracker()->registerJob(job); job->start(); } else if (np.has("text")) {
/** * Trashes the file of the current item * * @return */ bool TrashItem::doTrashing() { if (!this->store()) { return false; } QString destinationPath = NoteFolder::currentTrashPath(); QDir destinationDir(destinationPath); // created the trash folder if it doesn't exist if (!destinationDir.exists() && !destinationDir.mkpath(destinationDir.path())) { return false; } QFile file(_fullNoteFilePath); QString destinationFileName = destinationPath + QDir::separator() + QString::number( this->getId() ); qDebug() << __func__ << " - 'destinationFileName': " << destinationFileName; // copy file to trash folder return file.copy(destinationFileName); }
//------------------------------------------------------------------------------ void ctkDICOMDatabase::insert ( DcmDataset *dataset, bool storeFile, bool generateThumbnail) { Q_D(ctkDICOMDatabase); if (!dataset) { return; } // Check to see if the file has already been loaded OFString sopInstanceUID ; dataset->findAndGetOFString(DCM_SOPInstanceUID, sopInstanceUID); QSqlQuery fileExists ( d->Database ); fileExists.prepare("SELECT InsertTimestamp,Filename FROM Images WHERE SOPInstanceUID == ?"); fileExists.bindValue(0,QString(sopInstanceUID.c_str())); fileExists.exec(); if ( fileExists.next() && QFileInfo(fileExists.value(1).toString()).lastModified() < QDateTime::fromString(fileExists.value(0).toString(),Qt::ISODate) ) { logger.debug ( "File " + fileExists.value(1).toString() + " already added" ); return; } OFString patientsName, patientID, patientsBirthDate, patientsBirthTime, patientsSex, patientComments, patientsAge; OFString studyInstanceUID, studyID, studyDate, studyTime, accessionNumber, modalitiesInStudy, institutionName, performingPhysiciansName, referringPhysician, studyDescription; OFString seriesInstanceUID, seriesDate, seriesTime, seriesDescription, bodyPartExamined, frameOfReferenceUID, contrastAgent, scanningSequence; OFString instanceNumber; Sint32 seriesNumber = 0, acquisitionNumber = 0, echoNumber = 0, temporalPosition = 0; //If the following fields can not be evaluated, cancel evaluation of the DICOM file dataset->findAndGetOFString(DCM_PatientName, patientsName); dataset->findAndGetOFString(DCM_StudyInstanceUID, studyInstanceUID); dataset->findAndGetOFString(DCM_SeriesInstanceUID, seriesInstanceUID); dataset->findAndGetOFString(DCM_PatientID, patientID); dataset->findAndGetOFString(DCM_PatientBirthDate, patientsBirthDate); dataset->findAndGetOFString(DCM_PatientBirthTime, patientsBirthTime); dataset->findAndGetOFString(DCM_PatientSex, patientsSex); dataset->findAndGetOFString(DCM_PatientAge, patientsAge); dataset->findAndGetOFString(DCM_PatientComments, patientComments); dataset->findAndGetOFString(DCM_StudyID, studyID); dataset->findAndGetOFString(DCM_StudyDate, studyDate); dataset->findAndGetOFString(DCM_StudyTime, studyTime); dataset->findAndGetOFString(DCM_AccessionNumber, accessionNumber); dataset->findAndGetOFString(DCM_ModalitiesInStudy, modalitiesInStudy); dataset->findAndGetOFString(DCM_InstitutionName, institutionName); dataset->findAndGetOFString(DCM_PerformingPhysicianName, performingPhysiciansName); dataset->findAndGetOFString(DCM_ReferringPhysicianName, referringPhysician); dataset->findAndGetOFString(DCM_StudyDescription, studyDescription); dataset->findAndGetOFString(DCM_SeriesDate, seriesDate); dataset->findAndGetOFString(DCM_SeriesTime, seriesTime); dataset->findAndGetOFString(DCM_SeriesDescription, seriesDescription); dataset->findAndGetOFString(DCM_BodyPartExamined, bodyPartExamined); dataset->findAndGetOFString(DCM_FrameOfReferenceUID, frameOfReferenceUID); dataset->findAndGetOFString(DCM_ContrastBolusAgent, contrastAgent); dataset->findAndGetOFString(DCM_ScanningSequence, scanningSequence); dataset->findAndGetSint32(DCM_SeriesNumber, seriesNumber); dataset->findAndGetSint32(DCM_AcquisitionNumber, acquisitionNumber); dataset->findAndGetSint32(DCM_EchoNumbers, echoNumber); dataset->findAndGetSint32(DCM_TemporalPositionIdentifier, temporalPosition); // store the file if the database is not in memomry QString filename; if ( storeFile && !this->isInMemory() ) { DcmFileFormat* fileformat = new DcmFileFormat ( dataset ); QString destinationDirectoryName = databaseDirectory() + "/dicom/"; QDir destinationDir(destinationDirectoryName); QString studySeriesDirectory = QString(studyInstanceUID.c_str()) + "/" + seriesInstanceUID.c_str(); destinationDir.mkpath(studySeriesDirectory); filename = databaseDirectory() + "/dicom/" + pathForDataset(dataset); logger.debug ( "Saving file: " + filename ); OFCondition status = fileformat->saveFile ( filename.toAscii() ); if ( !status.good() ) { logger.error ( "Error saving file: " + filename + "\nError is " + status.text() ); delete fileformat; return; } delete fileformat; } QSqlQuery check_exists_query(d->Database); //The patient UID is a unique number within the database, generated by the sqlite autoincrement int patientUID = -1; if ( patientID != "" && patientsName != "" ) { //Check if patient is already present in the db check_exists_query.prepare ( "SELECT * FROM Patients WHERE PatientID = ? AND PatientsName = ?" ); check_exists_query.bindValue ( 0, QString ( patientID.c_str() ) ); check_exists_query.bindValue ( 1, QString ( patientsName.c_str() ) ); check_exists_query.exec(); if (check_exists_query.next()) { patientUID = check_exists_query.value(check_exists_query.record().indexOf("UID")).toInt(); } else { // Insert it QSqlQuery statement ( d->Database ); statement.prepare ( "INSERT INTO Patients ('UID', 'PatientsName', 'PatientID', 'PatientsBirthDate', 'PatientsBirthTime', 'PatientsSex', 'PatientsAge', 'PatientsComments' ) values ( NULL, ?, ?, ?, ?, ?, ?, ? )" ); statement.bindValue ( 0, QString ( patientsName.c_str() ) ); statement.bindValue ( 1, QString ( patientID.c_str() ) ); statement.bindValue ( 2, QString ( patientsBirthDate.c_str() ) ); statement.bindValue ( 3, QString ( patientsBirthTime.c_str() ) ); statement.bindValue ( 4, QString ( patientsSex.c_str() ) ); // TODO: shift patient's age to study, since this is not a patient level attribute in images // statement.bindValue ( 5, QString ( patientsAge.c_str() ) ); statement.bindValue ( 6, QString ( patientComments.c_str() ) ); statement.exec (); patientUID = statement.lastInsertId().toInt(); logger.debug ( "New patient inserted: " + QString().setNum ( patientUID ) ); } } if ( studyInstanceUID != "" ) { check_exists_query.prepare ( "SELECT * FROM Studies WHERE StudyInstanceUID = ?" ); check_exists_query.bindValue ( 0, QString ( studyInstanceUID.c_str() ) ); check_exists_query.exec(); if(!check_exists_query.next()) { QSqlQuery statement ( d->Database ); statement.prepare ( "INSERT INTO Studies ( 'StudyInstanceUID', 'PatientsUID', 'StudyID', 'StudyDate', 'StudyTime', 'AccessionNumber', 'ModalitiesInStudy', 'InstitutionName', 'ReferringPhysician', 'PerformingPhysiciansName', 'StudyDescription' ) VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )" ); statement.bindValue ( 0, QString ( studyInstanceUID.c_str() ) ); statement.bindValue ( 1, patientUID ); statement.bindValue ( 2, QString ( studyID.c_str() ) ); statement.bindValue ( 3, QDate::fromString ( studyDate.c_str(), "yyyyMMdd" ) ); statement.bindValue ( 4, QString ( studyTime.c_str() ) ); statement.bindValue ( 5, QString ( accessionNumber.c_str() ) ); statement.bindValue ( 6, QString ( modalitiesInStudy.c_str() ) ); statement.bindValue ( 7, QString ( institutionName.c_str() ) ); statement.bindValue ( 8, QString ( referringPhysician.c_str() ) ); statement.bindValue ( 9, QString ( performingPhysiciansName.c_str() ) ); statement.bindValue ( 10, QString ( studyDescription.c_str() ) ); if ( !statement.exec() ) { logger.error ( "Error executing statament: " + statement.lastQuery() + " Error: " + statement.lastError().text() ); } } } if ( seriesInstanceUID != "" ) { check_exists_query.prepare ( "SELECT * FROM Series WHERE SeriesInstanceUID = ?" ); check_exists_query.bindValue ( 0, QString ( seriesInstanceUID.c_str() ) ); logger.warn ( "Statement: " + check_exists_query.lastQuery() ); check_exists_query.exec(); if(!check_exists_query.next()) { QSqlQuery statement ( d->Database ); statement.prepare ( "INSERT INTO Series ( 'SeriesInstanceUID', 'StudyInstanceUID', 'SeriesNumber', 'SeriesDate', 'SeriesTime', 'SeriesDescription', 'BodyPartExamined', 'FrameOfReferenceUID', 'AcquisitionNumber', 'ContrastAgent', 'ScanningSequence', 'EchoNumber', 'TemporalPosition' ) VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )" ); statement.bindValue ( 0, QString ( seriesInstanceUID.c_str() ) ); statement.bindValue ( 1, QString ( studyInstanceUID.c_str() ) ); statement.bindValue ( 2, static_cast<int>(seriesNumber) ); statement.bindValue ( 3, QString ( seriesDate.c_str() ) ); statement.bindValue ( 4, QDate::fromString ( seriesTime.c_str(), "yyyyMMdd" ) ); statement.bindValue ( 5, QString ( seriesDescription.c_str() ) ); statement.bindValue ( 6, QString ( bodyPartExamined.c_str() ) ); statement.bindValue ( 7, QString ( frameOfReferenceUID.c_str() ) ); statement.bindValue ( 8, static_cast<int>(acquisitionNumber) ); statement.bindValue ( 9, QString ( contrastAgent.c_str() ) ); statement.bindValue ( 10, QString ( scanningSequence.c_str() ) ); statement.bindValue ( 11, static_cast<int>(echoNumber) ); statement.bindValue ( 12, static_cast<int>(temporalPosition) ); if ( !statement.exec() ) { logger.error ( "Error executing statament: " + statement.lastQuery() + " Error: " + statement.lastError().text() ); } } } if ( !filename.isEmpty() ) { check_exists_query.prepare ( "SELECT * FROM Images WHERE Filename = ?" ); check_exists_query.bindValue ( 0, filename ); check_exists_query.exec(); if(!check_exists_query.next()) { QSqlQuery statement ( d->Database ); statement.prepare ( "INSERT INTO Images ( 'SOPInstanceUID', 'Filename', 'SeriesInstanceUID', 'InsertTimestamp' ) VALUES ( ?, ?, ?, ? )" ); statement.bindValue ( 0, QString ( sopInstanceUID.c_str() ) ); statement.bindValue ( 1, filename ); statement.bindValue ( 2, QString ( seriesInstanceUID.c_str() ) ); statement.bindValue ( 3, QDateTime::currentDateTime() ); statement.exec(); } } if(generateThumbnail){ if(d->thumbnailGenerator){ QString studySeriesDirectory = QString(studyInstanceUID.c_str()) + "/" + QString(seriesInstanceUID.c_str()); //Create thumbnail here QString thumbnailPath = databaseDirectory() + "/thumbs/" + this->pathForDataset(dataset) + ".png"; //QString(studyInstanceUID.c_str()) + "/" + //QString(seriesInstanceUID.c_str()) + "/" + //QString(sopInstanceUID.c_str()) + ".png"; QFileInfo thumbnailInfo(thumbnailPath); if(!(thumbnailInfo.exists() && (thumbnailInfo.lastModified() > QFileInfo(filename).lastModified()))){ QDir(databaseDirectory() + "/thumbs/").mkpath(studySeriesDirectory); DicomImage dcmImage(QDir::toNativeSeparators(filename).toAscii()); d->thumbnailGenerator->generateThumbnail(&dcmImage, thumbnailPath); } } } if (isInMemory()) { emit databaseChanged(); } }
QScriptValue File::movePrivate(const QString &source, const QString &destination, bool noErrorDialog, bool noConfirmDialog, bool noProgressDialog, bool allowUndo, bool createDestinationDirectory, QScriptContext *context, QScriptEngine *engine) { Q_UNUSED(engine) #ifdef Q_OS_LINUX Q_UNUSED(noErrorDialog) Q_UNUSED(noConfirmDialog) Q_UNUSED(noProgressDialog) Q_UNUSED(allowUndo) QDir destinationDir(destination); QString sourceCopy(source); QString destinationCopy(destination); sourceCopy.replace(" ", "\\ "); destinationCopy.replace(" ", "\\ "); if(!destinationDir.exists()) { if(createDestinationDirectory) { if(QProcess::execute("sh -c \"mkdir -p " + QFile::encodeName(destinationCopy) + "\"")) { throwError(context, engine, "DirectoryCreationError", tr("Unable to create destination directory")); return context->thisObject(); } } else { throwError(context, engine, "DirectoryDoesntExistError", tr("Destination directory doesn't exist")); return context->thisObject(); } } QString command = "sh -c \"mv -f"; command += " "; command += QFile::encodeName(sourceCopy); command += " "; command += QFile::encodeName(destinationCopy); command += "\""; if(QProcess::execute(command)) { throwError(context, engine, "MoveRenameError", tr("Move/rename failed")); return context->thisObject(); } #endif #ifdef Q_OS_WIN Q_UNUSED(createDestinationDirectory) QDir sourceDir(source); QDir destinationDir(destination); std::wstring wideSource = QDir::toNativeSeparators(sourceDir.absolutePath()).toStdWString(); wideSource += L'\0'; std::wstring wideDestination = QDir::toNativeSeparators(destinationDir.absolutePath()).toStdWString(); wideDestination += L'\0'; SHFILEOPSTRUCT shFileOpStruct; shFileOpStruct.hwnd = 0; shFileOpStruct.wFunc = FO_MOVE; shFileOpStruct.pFrom = wideSource.c_str(); shFileOpStruct.pTo = wideDestination.c_str(); shFileOpStruct.fFlags = 0; shFileOpStruct.fAnyOperationsAborted = false; shFileOpStruct.lpszProgressTitle = 0; shFileOpStruct.hNameMappings = 0; if(noErrorDialog) shFileOpStruct.fFlags |= FOF_NOERRORUI; if(noConfirmDialog) shFileOpStruct.fFlags |= (FOF_NOCONFIRMATION | FOF_NOCONFIRMMKDIR); if(noProgressDialog) shFileOpStruct.fFlags |= FOF_SILENT; if(allowUndo) shFileOpStruct.fFlags |= FOF_ALLOWUNDO; int result = SHFileOperation(&shFileOpStruct); if(result != 0) { throwError(context, engine, "MoveError", tr("Move failed: %1").arg(getErrorString(result))); return context->thisObject(); } if(shFileOpStruct.fAnyOperationsAborted) { throwError(context, engine, "MoveAbortedError", tr("Move failed: aborted")); return context->thisObject(); } #endif return context->thisObject(); }
//------------------------------------------------------------------------------ void ctkDICOMDatabasePrivate::insert( const ctkDICOMDataset& ctkDataset, const QString& filePath, bool storeFile, bool generateThumbnail) { Q_Q(ctkDICOMDatabase); // Check to see if the file has already been loaded // TODO: // It could make sense to actually remove the dataset and re-add it. This needs the remove // method we still have to write. // QString sopInstanceUID ( ctkDataset.GetElementAsString(DCM_SOPInstanceUID) ); QSqlQuery fileExists ( Database ); fileExists.prepare("SELECT InsertTimestamp,Filename FROM Images WHERE SOPInstanceUID == :sopInstanceUID"); fileExists.bindValue(":sopInstanceUID",sopInstanceUID); bool success = fileExists.exec(); if (!success) { logger.error("SQLITE ERROR: " + fileExists.lastError().driverText()); return; } qDebug() << "filename is: " << fileExists.value(1).toString(); qDebug() << "modified date is: " << QFileInfo(fileExists.value(1).toString()).lastModified(); qDebug() << "db mod date is: " << QDateTime::fromString(fileExists.value(0).toString(),Qt::ISODate); if ( fileExists.next() && QFileInfo(fileExists.value(1).toString()).lastModified() < QDateTime::fromString(fileExists.value(0).toString(),Qt::ISODate) ) { logger.debug ( "File " + fileExists.value(1).toString() + " already added" ); return; } //If the following fields can not be evaluated, cancel evaluation of the DICOM file QString patientsName(ctkDataset.GetElementAsString(DCM_PatientName) ); QString studyInstanceUID(ctkDataset.GetElementAsString(DCM_StudyInstanceUID) ); QString seriesInstanceUID(ctkDataset.GetElementAsString(DCM_SeriesInstanceUID) ); QString patientID(ctkDataset.GetElementAsString(DCM_PatientID) ); if ( patientsName.isEmpty() && !patientID.isEmpty() ) { // Use patient id as name if name is empty - can happen on anonymized datasets // see: http://www.na-mic.org/Bug/view.php?id=1643 patientsName = patientID; } if ( patientsName.isEmpty() || studyInstanceUID.isEmpty() || patientID.isEmpty() ) { logger.error("Dataset is missing necessary information!"); return; } QString patientsBirthDate(ctkDataset.GetElementAsString(DCM_PatientBirthDate) ); QString patientsBirthTime(ctkDataset.GetElementAsString(DCM_PatientBirthTime) ); QString patientsSex(ctkDataset.GetElementAsString(DCM_PatientSex) ); QString patientsAge(ctkDataset.GetElementAsString(DCM_PatientAge) ); QString patientComments(ctkDataset.GetElementAsString(DCM_PatientComments) ); QString studyID(ctkDataset.GetElementAsString(DCM_StudyID) ); QString studyDate(ctkDataset.GetElementAsString(DCM_StudyDate) ); QString studyTime(ctkDataset.GetElementAsString(DCM_StudyTime) ); QString accessionNumber(ctkDataset.GetElementAsString(DCM_AccessionNumber) ); QString modalitiesInStudy(ctkDataset.GetElementAsString(DCM_ModalitiesInStudy) ); QString institutionName(ctkDataset.GetElementAsString(DCM_InstitutionName) ); QString performingPhysiciansName(ctkDataset.GetElementAsString(DCM_PerformingPhysicianName) ); QString referringPhysician(ctkDataset.GetElementAsString(DCM_ReferringPhysicianName) ); QString studyDescription(ctkDataset.GetElementAsString(DCM_StudyDescription) ); QString seriesDate(ctkDataset.GetElementAsString(DCM_SeriesDate) ); QString seriesTime(ctkDataset.GetElementAsString(DCM_SeriesTime) ); QString seriesDescription(ctkDataset.GetElementAsString(DCM_SeriesDescription) ); QString bodyPartExamined(ctkDataset.GetElementAsString(DCM_BodyPartExamined) ); QString frameOfReferenceUID(ctkDataset.GetElementAsString(DCM_FrameOfReferenceUID) ); QString contrastAgent(ctkDataset.GetElementAsString(DCM_ContrastBolusAgent) ); QString scanningSequence(ctkDataset.GetElementAsString(DCM_ScanningSequence) ); long seriesNumber(ctkDataset.GetElementAsInteger(DCM_SeriesNumber) ); long acquisitionNumber(ctkDataset.GetElementAsInteger(DCM_AcquisitionNumber) ); long echoNumber(ctkDataset.GetElementAsInteger(DCM_EchoNumbers) ); long temporalPosition(ctkDataset.GetElementAsInteger(DCM_TemporalPositionIdentifier) ); // store the file if the database is not in memomry // TODO: if we are called from insert(file) we // have to do something else // QString filename = filePath; if ( storeFile && !q->isInMemory() && !seriesInstanceUID.isEmpty() ) { // QString studySeriesDirectory = studyInstanceUID + "/" + seriesInstanceUID; QString destinationDirectoryName = q->databaseDirectory() + "/dicom/"; QDir destinationDir(destinationDirectoryName); filename = destinationDirectoryName + studyInstanceUID + "/" + seriesInstanceUID + "/" + sopInstanceUID; destinationDir.mkpath(studyInstanceUID + "/" + seriesInstanceUID); if(filePath.isEmpty()) { logger.debug ( "Saving file: " + filename ); if ( !ctkDataset.SaveToFile( filename) ) { logger.error ( "Error saving file: " + filename ); return; } } else { // we're inserting an existing file QFile currentFile( filePath ); currentFile.copy(filename); logger.debug( "Copy file from: " + filePath ); logger.debug( "Copy file to : " + filename ); } } QSqlQuery checkPatientExistsQuery(Database); //The dbPatientID is a unique number within the database, //generated by the sqlite autoincrement //The patientID is the (non-unique) DICOM patient id int dbPatientID = -1; if ( patientID != "" && patientsName != "" ) { //Speed up: Check if patient is the same as in last file; // very probable, as all images belonging to a study have the same patient if ( lastPatientID != patientID || lastPatientsBirthDate != patientsBirthDate || lastPatientsName != patientsName ) { // Ok, something is different from last insert, let's insert him if he's not // already in the db. // // Check if patient is already present in the db // TODO: maybe add birthdate check for extra safety checkPatientExistsQuery.prepare ( "SELECT * FROM Patients WHERE PatientID = ? AND PatientsName = ?" ); checkPatientExistsQuery.bindValue ( 0, patientID ); checkPatientExistsQuery.bindValue ( 1, patientsName ); loggedExec(checkPatientExistsQuery); if (checkPatientExistsQuery.next()) { // we found him dbPatientID = checkPatientExistsQuery.value(checkPatientExistsQuery.record().indexOf("UID")).toInt(); } else { // Insert it QSqlQuery insertPatientStatement ( Database ); insertPatientStatement.prepare ( "INSERT INTO Patients ('UID', 'PatientsName', 'PatientID', 'PatientsBirthDate', 'PatientsBirthTime', 'PatientsSex', 'PatientsAge', 'PatientsComments' ) values ( NULL, ?, ?, ?, ?, ?, ?, ? )" ); insertPatientStatement.bindValue ( 0, patientsName ); insertPatientStatement.bindValue ( 1, patientID ); insertPatientStatement.bindValue ( 2, patientsBirthDate ); insertPatientStatement.bindValue ( 3, patientsBirthTime ); insertPatientStatement.bindValue ( 4, patientsSex ); // TODO: shift patient's age to study, // since this is not a patient level attribute in images // insertPatientStatement.bindValue ( 5, patientsAge ); insertPatientStatement.bindValue ( 6, patientComments ); loggedExec(insertPatientStatement); dbPatientID = insertPatientStatement.lastInsertId().toInt(); logger.debug ( "New patient inserted: " + QString().setNum ( dbPatientID ) ); } /// keep this for the next image lastPatientUID = dbPatientID; lastPatientID = patientID; lastPatientsBirthDate = patientsBirthDate; lastPatientsName = patientsName; } // Patient is in now. Let's continue with the study if ( studyInstanceUID != "" && lastStudyInstanceUID != studyInstanceUID ) { QSqlQuery checkStudyExistsQuery (Database); checkStudyExistsQuery.prepare ( "SELECT * FROM Studies WHERE StudyInstanceUID = ?" ); checkStudyExistsQuery.bindValue ( 0, studyInstanceUID ); checkStudyExistsQuery.exec(); if(!checkStudyExistsQuery.next()) { QSqlQuery insertStudyStatement ( Database ); insertStudyStatement.prepare ( "INSERT INTO Studies ( 'StudyInstanceUID', 'PatientsUID', 'StudyID', 'StudyDate', 'StudyTime', 'AccessionNumber', 'ModalitiesInStudy', 'InstitutionName', 'ReferringPhysician', 'PerformingPhysiciansName', 'StudyDescription' ) VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )" ); insertStudyStatement.bindValue ( 0, studyInstanceUID ); insertStudyStatement.bindValue ( 1, dbPatientID ); insertStudyStatement.bindValue ( 2, studyID ); insertStudyStatement.bindValue ( 3, QDate::fromString ( studyDate, "yyyyMMdd" ) ); insertStudyStatement.bindValue ( 4, studyTime ); insertStudyStatement.bindValue ( 5, accessionNumber ); insertStudyStatement.bindValue ( 6, modalitiesInStudy ); insertStudyStatement.bindValue ( 7, institutionName ); insertStudyStatement.bindValue ( 8, referringPhysician ); insertStudyStatement.bindValue ( 9, performingPhysiciansName ); insertStudyStatement.bindValue ( 10, studyDescription ); if ( !insertStudyStatement.exec() ) { logger.error ( "Error executing statament: " + insertStudyStatement.lastQuery() + " Error: " + insertStudyStatement.lastError().text() ); } else { lastStudyInstanceUID = studyInstanceUID; } } } if ( seriesInstanceUID != "" && seriesInstanceUID != lastSeriesInstanceUID ) { QSqlQuery checkSeriesExistsQuery (Database); checkSeriesExistsQuery.prepare ( "SELECT * FROM Series WHERE SeriesInstanceUID = ?" ); checkSeriesExistsQuery.bindValue ( 0, seriesInstanceUID ); logger.warn ( "Statement: " + checkSeriesExistsQuery.lastQuery() ); loggedExec(checkSeriesExistsQuery); if(!checkSeriesExistsQuery.next()) { QSqlQuery insertSeriesStatement ( Database ); insertSeriesStatement.prepare ( "INSERT INTO Series ( 'SeriesInstanceUID', 'StudyInstanceUID', 'SeriesNumber', 'SeriesDate', 'SeriesTime', 'SeriesDescription', 'BodyPartExamined', 'FrameOfReferenceUID', 'AcquisitionNumber', 'ContrastAgent', 'ScanningSequence', 'EchoNumber', 'TemporalPosition' ) VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )" ); insertSeriesStatement.bindValue ( 0, seriesInstanceUID ); insertSeriesStatement.bindValue ( 1, studyInstanceUID ); insertSeriesStatement.bindValue ( 2, static_cast<int>(seriesNumber) ); insertSeriesStatement.bindValue ( 3, seriesDate ); insertSeriesStatement.bindValue ( 4, QDate::fromString ( seriesTime, "yyyyMMdd" ) ); insertSeriesStatement.bindValue ( 5, seriesDescription ); insertSeriesStatement.bindValue ( 6, bodyPartExamined ); insertSeriesStatement.bindValue ( 7, frameOfReferenceUID ); insertSeriesStatement.bindValue ( 8, static_cast<int>(acquisitionNumber) ); insertSeriesStatement.bindValue ( 9, contrastAgent ); insertSeriesStatement.bindValue ( 10, scanningSequence ); insertSeriesStatement.bindValue ( 11, static_cast<int>(echoNumber) ); insertSeriesStatement.bindValue ( 12, static_cast<int>(temporalPosition) ); if ( !insertSeriesStatement.exec() ) { logger.error ( "Error executing statament: " + insertSeriesStatement.lastQuery() + " Error: " + insertSeriesStatement.lastError().text() ); lastSeriesInstanceUID = ""; } else { lastSeriesInstanceUID = seriesInstanceUID; } } } // TODO: what to do with imported files // if ( !filename.isEmpty() && !seriesInstanceUID.isEmpty() ) { QSqlQuery checkImageExistsQuery (Database); checkImageExistsQuery.prepare ( "SELECT * FROM Images WHERE Filename = ?" ); checkImageExistsQuery.bindValue ( 0, filename ); checkImageExistsQuery.exec(); if(!checkImageExistsQuery.next()) { QSqlQuery insertImageStatement ( Database ); insertImageStatement.prepare ( "INSERT INTO Images ( 'SOPInstanceUID', 'Filename', 'SeriesInstanceUID', 'InsertTimestamp' ) VALUES ( ?, ?, ?, ? )" ); insertImageStatement.bindValue ( 0, sopInstanceUID ); insertImageStatement.bindValue ( 1, filename ); insertImageStatement.bindValue ( 2, seriesInstanceUID ); insertImageStatement.bindValue ( 3, QDateTime::currentDateTime() ); insertImageStatement.exec(); } } if( generateThumbnail && thumbnailGenerator && !seriesInstanceUID.isEmpty() ) { QString studySeriesDirectory = studyInstanceUID + "/" + seriesInstanceUID; //Create thumbnail here QString thumbnailPath = q->databaseDirectory() + "/thumbs/" + studyInstanceUID + "/" + seriesInstanceUID + "/" + sopInstanceUID + ".png"; QFileInfo thumbnailInfo(thumbnailPath); if( !(thumbnailInfo.exists() && (thumbnailInfo.lastModified() > QFileInfo(filename).lastModified()))) { QDir(q->databaseDirectory() + "/thumbs/").mkpath(studySeriesDirectory); DicomImage dcmImage(QDir::toNativeSeparators(filename).toAscii()); thumbnailGenerator->generateThumbnail(&dcmImage, thumbnailPath); } } if (q->isInMemory()) { emit q->databaseChanged(); } } }
void AMScanDatabaseImportController::copyScans() { if(state_ != Importing) return; emit progressDescription("Copying Scans..."); emit stepProgress(-1); QString scanTableName = AMDbObjectSupport::s()->tableNameForClass<AMScan>(); QList<int> scanIds = sourceDb_->objectsWhere(scanTableName, QString()); AMScan::setAutoLoadData(false); // disable loading data for performance. It will also fail to load because it's in the wrong spot. for(int i=0, cc=scanIds.count(); i<cc; i++) { if(state_ != Importing) return; emit stepProgress(int(100.0*(i+1)/cc)); AMDbObject* object = AMDbObjectSupport::s()->createAndLoadObjectAt(sourceDb_, scanTableName, scanIds.at(i)); if(!object) { AMErrorMon::report(AMErrorReport(this, AMErrorReport::Alert, -3, QString("Error copying the scan with ID '%1' out of the import database. Your database might be corrupted. Please report this problem to the Acquaman developers.").arg(scanIds.at(i)))); continue; } AMScan* scan = qobject_cast<AMScan*>(object); if(!scan) { AMErrorMon::report(AMErrorReport(this, AMErrorReport::Alert, -4, QString("Error copying the scan with ID '%1' out of the import database: it wasn't a scan object. Your database might be corrupted. Please report this problem to the Acquaman developers.").arg(scanIds.at(i)))); delete object; continue; } scan->retain(this); // update scan fields: scan->setRunId(s2dRunIds_.value(scan->runId(), -1)); scan->setSampleId(s2dSampleIds_.value(scan->sampleId(), -1)); // copy the raw data: filePath and additionalFilePaths QDir destinationDir(destinationPath_); // Assuming paths always in relative file format. QString filePath = scan->filePath(); // Does the file exist already in the destination? if(destinationDir.exists(filePath)) { // I know we're not supposed to be a GUI module... but is it okay to prompt here for what to do? if(userSaysShouldSkipDuplicateScan(scan)) { scan->release(this); continue; } filePath = makeUniqueFileName(destinationPath_, filePath); } copyFileAndMakeFoldersAsRequired(sourcePath_ % "/" % scan->filePath(), destinationPath_ % "/" % filePath); scan->setFilePath(filePath); // Copy additional file paths: QStringList extraPaths = scan->additionalFilePaths(); for(int j=0, cc=extraPaths.count(); j<cc; j++) { QString destinationFilePath = extraPaths.at(j); if(destinationDir.exists(destinationFilePath)) { destinationFilePath = makeUniqueFileName(destinationPath_, destinationFilePath); } copyFileAndMakeFoldersAsRequired(sourcePath_ % "/" % extraPaths.at(j), destinationPath_ % "/" % destinationFilePath); extraPaths[j] = destinationFilePath; } scan->setAdditionalFilePaths(extraPaths); // OK. raw data copied and file paths adjusted. Just store this scan in the new db: if(!scan->storeToDb(destinationDb_, false)) { // HOLD UP! Don't generate those thumbnails... We'll do a direct copy. AMErrorMon::report(AMErrorReport(this, AMErrorReport::Alert, -4, QString("Error copying the scan with ID '%1' into the new database. Your database might be corrupted. Please report this problem to the Acquaman developers.").arg(scanIds.at(i)))); scan->release(this); continue; } // Copy the thumbnails from the old DB to the new DB: // find the old thumbnails: QStringList thumbnailCols; thumbnailCols << "objectId" << "objectTableName" << "number" << "type" << "title" << "subtitle" << "thumbnail"; int thumbnailFirstId = -1; int thumbnailCount = 0; QSqlQuery q = sourceDb_->select(AMDbObjectSupport::thumbnailTableName(), thumbnailCols.join(","), "objectId = ? AND objectTableName = ?"); q.bindValue(0, scanIds.at(i)); q.bindValue(1, scanTableName); if(!q.exec()) { AMErrorMon::report(AMErrorReport(this, AMErrorReport::Alert, -4, QString("Error copying the the thumbnails for scan with ID '%1' out of the old database. Please report this problem to the Acquaman developers.").arg(scanIds.at(i)))); } else { if(q.first()) { QVariantList thumbnailVals; thumbnailVals << q.value(0) << q.value(1) << q.value(2) << q.value(3) << q.value(4) << q.value(5) << q.value(6); thumbnailVals[0] = scan->id(); // update the scan id from old DB to new DB's value thumbnailFirstId = destinationDb_->insertOrUpdate(0, AMDbObjectSupport::thumbnailTableName(), thumbnailCols, thumbnailVals); if(thumbnailFirstId > 0) thumbnailCount++; else AMErrorMon::report(AMErrorReport(this, AMErrorReport::Alert, -4, QString("Error copying the the thumbnails for scan with ID '%1' into the new database. Please report this problem to the Acquaman developers.").arg(scanIds.at(i)))); } while(q.next()) { QVariantList thumbnailVals; thumbnailVals << q.value(0) << q.value(1) << q.value(2) << q.value(3) << q.value(4) << q.value(5) << q.value(6); thumbnailVals[0] = scan->id(); // update the scan id from old DB to new DB's value if(destinationDb_->insertOrUpdate(0, AMDbObjectSupport::thumbnailTableName(), thumbnailCols, thumbnailVals) > 0) thumbnailCount++; } } // Finally, update the thumbnail references in the scan object: // now that we know where the thumbnails are, update this in the object table if(!destinationDb_->update(scan->id(), scanTableName, QStringList() << "thumbnailCount" << "thumbnailFirstId", QVariantList() << thumbnailCount << thumbnailFirstId)) { AMErrorMon::report(AMErrorReport(this, AMErrorReport::Alert, AMSCANDATABASEIMPORTCONTROLLER_ERROR_STORING_UPDATED_THUMBNAIL_COUNT_AND_FIRST_ID, QString("While importing, error trying to store the updated thumbnail count and firstThumbnailId for database object %1. Please report this problem to the Acquaman developers.").arg(scanIds.at(i)))); } // What experiments was this scan in? Need to map and add in new database. QList<int> experiments = AMExperiment::experimentsContainingScan(scanIds.at(i), sourceDb_); foreach(int oldExperimentId, experiments) { int newExperimentId = s2dExperimentIds_.value(oldExperimentId); if(newExperimentId > 0) AMExperiment::addScanToExperiment(scan->id(), newExperimentId, destinationDb_); } // All done! scan->release(); qApp->sendPostedEvents(); qApp->processEvents(); }
bool SharePlugin::receivePackage(const NetworkPackage& np) { /* //TODO: Write a test like this if (np.type() == PACKAGE_TYPE_PING) { qCDebug(KDECONNECT_PLUGIN_SHARE) << "sending file" << (QDesktopServices::storageLocation(QDesktopServices::HomeLocation) + "/.bashrc"); NetworkPackage out(PACKAGE_TYPE_SHARE_REQUEST); out.set("filename", mDestinationDir + "itworks.txt"); AutoClosingQFile* file = new AutoClosingQFile(QDesktopServices::storageLocation(QDesktopServices::HomeLocation) + "/.bashrc"); //Test file to transfer out.setPayload(file, file->size()); device()->sendPackage(out); return true; } */ qCDebug(KDECONNECT_PLUGIN_SHARE) << "File transfer"; if (np.hasPayload()) { //qCDebug(KDECONNECT_PLUGIN_SHARE) << "receiving file"; const QString filename = np.get<QString>(QStringLiteral("filename"), QString::number(QDateTime::currentMSecsSinceEpoch())); const QUrl dir = destinationDir().adjusted(QUrl::StripTrailingSlash); QUrl destination(dir.toString() + '/' + filename); if (destination.isLocalFile() && QFile::exists(destination.toLocalFile())) { destination = QUrl(dir.toString() + '/' + KIO::suggestName(dir, filename)); } FileTransferJob* job = np.createPayloadTransferJob(destination); job->setOriginName(device()->name() + ": " + filename); connect(job, &KJob::result, this, &SharePlugin::finished); KIO::getJobTracker()->registerJob(job); job->start(); } else if (np.has(QStringLiteral("text"))) { QString text = np.get<QString>(QStringLiteral("text")); if (!QStandardPaths::findExecutable(QStringLiteral("kate")).isEmpty()) { QProcess* proc = new QProcess(); connect(proc, SIGNAL(finished(int)), proc, SLOT(deleteLater())); proc->start(QStringLiteral("kate"), QStringList(QStringLiteral("--stdin"))); proc->write(text.toUtf8()); proc->closeWriteChannel(); } else { QTemporaryFile tmpFile; tmpFile.setAutoRemove(false); tmpFile.open(); tmpFile.write(text.toUtf8()); tmpFile.close(); const QUrl url = QUrl::fromLocalFile(tmpFile.fileName()); Q_EMIT shareReceived(url); QDesktopServices::openUrl(url); } } else if (np.has(QStringLiteral("url"))) { QUrl url = QUrl::fromEncoded(np.get<QByteArray>(QStringLiteral("url"))); QDesktopServices::openUrl(url); Q_EMIT shareReceived(url); } else { qCDebug(KDECONNECT_PLUGIN_SHARE) << "Error: Nothing attached!"; } return true; }
void SharePlugin::openDestinationFolder() { QDesktopServices::openUrl(destinationDir()); }