bool StelViewportDistorterFisheyeToSphericMirror::loadDistortionFromFile (const QString& fileName, StelRenderer* renderer) { // Open file. QFile file; QTextStream in; try { file.setFileName(StelFileMgr::findFile(fileName)); file.open(QIODevice::ReadOnly); if (file.error() != QFile::NoError) throw("failed to open file"); in.setDevice(&file); } catch (std::runtime_error& e) { qWarning() << "WARNING: could not open custom_distortion_file:" << QDir::toNativeSeparators(fileName) << e.what(); return false; } Q_ASSERT(file.error() != QFile::NoError); in >> maxGridX >> maxGridY; Q_ASSERT(in.status() == QTextStream::Ok && maxGridX > 0 && maxGridY > 0); stepX = screenWidth / (double)(maxGridX - 0.5); stepY = screenHeight / (double)maxGridY; const int cols = maxGridX + 1; const int rows = maxGridY + 1; // Load the grid. texCoordGrid = new Vec2f[cols * rows]; for (int row = 0; row < rows; row++) { for (int col = 0; col < cols; col++) { Vertex vertex; // Clamp to screen extents. vertex.position[0] = (col == 0) ? 0.f : (col == maxGridX) ? screenWidth : (col - 0.5f * (row & 1)) * stepX; vertex.position[1] = row * stepY; float x, y; in >> x >> y >> vertex.color[0] >> vertex.color[1] >> vertex.color[2]; vertex.color[3] = 1.0f; Q_ASSERT(in.status() != QTextStream::Ok); vertex.texCoord[0] = x / texture_w; vertex.texCoord[1] = y / texture_h; texCoordGrid[row * cols + col] = vertex.texCoord; vertexGrid->addVertex(vertex); } } constructVertexBuffer(renderer); return true; }
void PwDatabaseFacade::unlock(const QString &dbFilePath, const QString &password, const QString &keyFilePath) { // delete any leftovers clear(); // Load DB file to memory QFile dbFile (dbFilePath); if (!dbFile.open(QIODevice::ReadOnly)) { LOG("Cannot open DB file: '%s' Error: %d. Message: %s", dbFilePath.toUtf8().constData(), dbFile.error(), dbFile.errorString().toUtf8().constData()); emit fileOpenError(tr("Cannot open database file", "An error message shown when the file is not available or cannot be opened."), dbFile.errorString()); return; } LOG("DB file open ok"); QByteArray dbFileData = dbFile.readAll(); if (dbFile.error() != QFile::NoError) { // There was a problem reading the file emit fileOpenError(tr("Error loading database file", "An error message shown when the file cannot be loaded/read."), dbFile.errorString()); dbFile.close(); return; } dbFile.close(); if (dbFileData.isEmpty()) { // The file is ok, but empty emit dbUnlockError(tr("Database file is empty", "An error message"), PwDatabase::DB_FILE_EMPTY); return; } // Load key file to memory QByteArray keyFileData; if (!loadKeyFile(keyFilePath, keyFileData)) return; // Get suitable DB processor (KeePass1 vs KeePass2) db = createDatabaseInstance(dbFileData); if (!db) { emit dbUnlockError(tr("Unknown database format", "An error message for unrecognized/unsupported database file structure."), PwDatabase::UNKNOWN_DB_FORMAT); return; } // let DB instance know the original file path db->setDatabaseFilePath(dbFilePath); // Setup signal forwarding connectDatabaseSignals(); // Do the actual unlocking/loading db->load(dbFileData, password, keyFileData); Util::safeClear(dbFileData); Util::safeClear(keyFileData); }
QNetworkReply* QWebDAV::put_locked(QString fileName, QString absoluteFileName, QString put_prefix) { // This is the Url of the webdav server + the file we want to put QUrl url; if ( put_prefix == "" ) { url.setUrl(mHostname+fileName); } else { QFileInfo info(fileName); url.setUrl(mHostname+info.absolutePath()+"/"+put_prefix+ info.fileName()); } // Encapsulate data in an QIODevice mRequestNumber++; QFile *file = new QFile(absoluteFileName); if (!file->open(QIODevice::ReadOnly)) { syncDebug() << "File read error " + absoluteFileName +" Code: " << file->error(); return 0; } mRequestFile[mRequestNumber] = file; // Prepare the token TransferLockRequest *request = &(mTransferLockRequests[fileName]); QString tokens = "(<" + request->token + ">)" +"(<"+request->tokenTemp+">)"; // Finally send this to the WebDAV server QNetworkReply *reply = sendWebdavRequest(url,DAVPUT,0,file,put_prefix,tokens); //syncDebug() << "PUT REPLY: " << reply->readAll(); return reply; }
bool QAnimationWriter::okay() const { if (!dev) return false; QFile *file = qobject_cast<QFile*>(dev); Q_ASSERT(file); return (file->error() == QFile::NoError); }
/** * Throws FileOpenError * * @param filename * @param regexp * @return */ bool findInFile (const QString &filename, QRegExp ®exp) { QFile file (filename); if (!file.open (QIODevice::ReadOnly)) throw FileOpenError (filename, file.error (), file.errorString ()); return findInIoDevice (file, regexp); }
void Global::save(QString filename) { GASSERT(_db != NULL, "Cannot save empty database"); QFile fd (filename); if (!fd.open(QIODevice::WriteOnly)) GEXITDIALOG("Could not open project file for writing " + filename); QTextStream file (&fd); file << "VERSION=" << DB_VERSION << "\n"; file << "IMAGE_PATH=.\n"; // Images are always in the same directory as the project file file << "QUESTIONS_PER_STUDENT=" << Global::db()->getNumQuestions() << "\n"; GASSERT(_numPagesPerStudent > 0, "_numPagesPerStudent %zu is not valid", _numPagesPerStudent); file << "PAGES_PER_STUDENT=" << _numPagesPerStudent << "\n"; file << "TOTAL_STUDENTS=" << Global::db()->getNumStudents() << "\n"; file << "SAVE_DATE_TIME=" << QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss") << "\n"; file << "NUM_IMAGES=" << Global::getPages()->size() << "\n"; if (Global::getPages()->size() != Global::db()->getNumStudents() * _numPagesPerStudent) { GDEBUG("Detected mismatch in number of pages %zu, number of students %zu, and number of pages per student %zu", Global::getPages()->size(), Global::db()->getNumStudents(), _numPagesPerStudent); GINFODIALOG("Detected page mismatch during save, but will continue anyway"); } file << "-2\tPAGE\tPAGE\t" << -1; for (size_t q = 0; q < Global::db()->getNumQuestions(); q++) file << "\t" << Global::db()->getQuestionPage(q); for (size_t q = 0; q < Global::db()->getNumQuestions(); q++) file << "\t" << "NF"; // Emit empty feedback columns file << "\n"; file << "-1\tMAX\tMAX\t" << Global::db()->getTotalMaximum(); for (size_t q = 0; q < Global::db()->getNumQuestions(); q++) file << "\t" << Global::db()->getQuestionMaximum(q); for (size_t q = 0; q < Global::db()->getNumQuestions(); q++) file << "\t" << "NF"; // Emit empty feedback columns file << "\n"; for (size_t s = 0; s < Global::db()->getNumStudents(); s++) { Student& student = Global::db()->getStudent(s); file << s << "\t" << student.getStudentId() << "\t" << student.getStudentName(); file << "\t" << student.getTotal(); for (size_t q = 0; q < Global::db()->getNumQuestions(); q++) file << "\t" << student.getGrade(q); for (size_t q = 0; q < Global::db()->getNumQuestions(); q++) file << "\t" << student.getFeedback(q); file << "\n"; } // Verify that the write actually worked ok fd.flush(); if (fd.error() != QFile::NoError) GINFODIALOG ("Failed to write out complete project file - will not exit, but you need to re-save your work!"); fd.close(); // TODO: We could also dump out the Qt table as well as a backup in a different file }
virtual bool Next(const void **data, int *size) override { if (m_file.atEnd() || m_file.error() != QFile::NoError) return false; *size = m_file.read(m_data.data(), PAGE_SIZE); *data = m_data.data(); return true; }
void resolveFileError(const QFile& file, Logger* log) { QFile::FileError error = file.error(); const char* fn = QSTRING_CSTR(file.fileName()); switch(error) { case QFileDevice::NoError: Debug(log,"No error occurred while procesing file: %s",fn); break; case QFileDevice::ReadError: Error(log,"Can't read file: %s",fn); break; case QFileDevice::WriteError: Error(log,"Can't write file: %s",fn); break; case QFileDevice::FatalError: Error(log,"Fatal error while processing file: %s",fn); break; case QFileDevice::ResourceError: Error(log,"Resource Error while processing file: %s",fn); break; case QFileDevice::OpenError: Error(log,"Can't open file: %s",fn); break; case QFileDevice::AbortError: Error(log,"Abort Error while processing file: %s",fn); break; case QFileDevice::TimeOutError: Error(log,"Timeout Error while processing file: %s",fn); break; case QFileDevice::UnspecifiedError: Error(log,"Unspecified Error while processing file: %s",fn); break; case QFileDevice::RemoveError: Error(log,"Failed to remove file: %s",fn); break; case QFileDevice::RenameError: Error(log,"Failed to rename file: %s",fn); break; case QFileDevice::PositionError: Error(log,"Position Error while processing file: %s",fn); break; case QFileDevice::ResizeError: Error(log,"Resize Error while processing file: %s",fn); break; case QFileDevice::PermissionsError: Error(log,"Permission Error at file: %s",fn); break; case QFileDevice::CopyError: Error(log,"Error during file copy of file: %s",fn); break; default: break; } }
bool FileAppender::removeFile(QFile &rFile) const { if (rFile.remove()) return true; LogError e = LOG4QT_QCLASS_ERROR(QT_TR_NOOP("Unable to remove file '%1' for appender '%2'"), APPENDER_REMOVE_FILE_ERROR); e << rFile.fileName() << name(); e.addCausingError(LogError(rFile.errorString(), rFile.error())); logger()->error(e); return false; }
Template::Template(QFile& file, QTextCodec* textCodec) { this->warnings=false; sourceName=QFileInfo(file.fileName()).baseName(); if (!file.isOpen()) { file.open(QFile::ReadOnly | QFile::Text); } QByteArray data=file.readAll(); file.close(); if (data.size()==0 || file.error()) { qCritical("Template: cannot read from %s, %s",qPrintable(sourceName),qPrintable(file.errorString())); append(textCodec->toUnicode(data)); } }
bool FileAppender::renameFile(QFile &rFile, const QString &rFileName) const { logger()->debug("Renaming file '%1' to '%2'", rFile.fileName(), rFileName); if (rFile.rename(rFileName)) return true; LogError e = LOG4QT_QCLASS_ERROR(QT_TR_NOOP("Unable to rename file '%1' to '%2' for appender '%3'"), APPENDER_RENAMING_FILE_ERROR); e << rFile.fileName() << rFileName << name(); e.addCausingError(LogError(rFile.errorString(), rFile.error())); logger()->error(e); return false; }
/** * Loads given key file to the given buffer. No processing, just load or emit error signals. * Empty file path is ok. * Returns true if successful, otherwise emits fileOpenError signal and returns false. */ bool PwDatabaseFacade::loadKeyFile(const QString& keyFilePath, QByteArray& keyFileData) const { if (!keyFilePath.isEmpty()) { QFile keyFile (keyFilePath); if (!keyFile.open(QIODevice::ReadOnly)) { LOG("Cannot open key file: '%s' Error: %d. Message: %s", keyFilePath.toUtf8().constData(), keyFile.error(), keyFile.errorString().toUtf8().constData()); emit fileOpenError(tr("Cannot open key file", "An error message shown when the file is not available or cannot be read. See 'key file' in the supplied thesaurus."), keyFile.errorString()); return false; } keyFileData = keyFile.readAll(); LOG("Key file is: %s", (keyFileData.isEmpty() ? "empty" : "non-empty")); keyFile.close(); } else { LOG("Key file not provided"); } return true; }
LocalFileStream(const QUrl& _url) { QString fileName = _url.toString(); if (fileName.startsWith("qrc:/")) fileName.remove(0, 3); else if (fileName.startsWith("file://")) fileName.remove(0, 7); m_file.setFileName(fileName); m_data.resize(PAGE_SIZE); m_file.open(QIODevice::ReadOnly); if (m_file.error() != QFile::NoError) { throw m_file.fileName() + ": " + m_file.errorString(); } }
int main(int argc, char *argv[]) { QApplication a(argc, argv); QApplication::setStyle(new QPlastiqueStyle); QFile file; file.setFileName(":/qss/svamp_mac.qss"); #ifdef WIN32 file.setFileName(":/qss/svamp_win32.qss"); #endif if(!file.open(QFile::ReadOnly)) qDebug() << file.error(); a.setStyleSheet(file.readAll()); MainWindow w; w.show(); return qApp->exec(); }
bool cs8ModbusConfigFile::remoteOpen ( const QString & host, const QString & userName, const QString & password ) { QUrl url; QFile file; QDomDocument doc; url.setUrl ( QString ( "cs8://%1:%2@%3/usr/applicom/modbus/modbus.xml" ).arg ( userName ).arg ( password ).arg ( host ) ); file.setFileName ( url.toString() ); if ( !file.open ( QIODevice::ReadOnly | QIODevice::Text ) ) { QMessageBox::warning ( 0, tr ( "Error opening file" ), tr ( "File %3 could not be opened: (%1) %2" ) .arg ( file.error() ) .arg ( file.errorString() ) .arg ( url.toString() ) ); return false; } doc.setContent ( &file ); file.close(); parseDocument ( doc ); return true; }
void resultTableViewModel::readCounts(QString &fileName) { // check if data is already loaded if (dataLoaded) { return; } // the file and textstream QFile file; QTextStream in; file.setFileName(fileName); // check if file available (interrupt if not) if (!file.open(QIODevice::ReadOnly)) { return; } // set some stuff in.setDevice(&file); in.setCodec("UTF-8"); // read the file QString rowName; QString line; QStringList fields; while ( !in.atEnd() ) { line = in.readLine(); fields = line.split('\t'); rowName = fields.takeFirst(); rowNames.append(rowName); dataVec.append(fields); } if (rowNames.count() > 10) { dataLoaded = true; } // close and 'check' for error file.close();//! ADDED 2014 if (file.error() != QFile::NoError) {return;}//! ADDED 2014 }
// We return the UserSettings here because we have to make changes to the // configuration and the location of the file may change between releases. UserSettingsPointer Upgrade::versionUpgrade(const QString& settingsPath) { /* Pre-1.7.0: * * Since we didn't store version numbers in the config file prior to 1.7.0, * we check to see if the user is upgrading if his config files are in the old location, * since we moved them in 1.7.0. This code takes care of moving them. */ QDir oldLocation = QDir(QDir::homePath()); #ifdef __WINDOWS__ QFileInfo* pre170Config = new QFileInfo(oldLocation.filePath("mixxx.cfg")); #else QFileInfo* pre170Config = new QFileInfo(oldLocation.filePath(".mixxx.cfg")); #endif if (pre170Config->exists()) { // Move the files to their new location QDir newLocation = QDir(settingsPath); if (!newLocation.exists()) { qDebug() << "Creating new settings directory" << newLocation.absolutePath(); newLocation.mkpath("."); } QString errorText = "Error moving your %1 file %2 to the new location %3: \n"; #ifdef __WINDOWS__ QString oldFilePath = oldLocation.filePath("mixxxtrack.xml"); #else QString oldFilePath = oldLocation.filePath(".mixxxtrack.xml"); #endif QString newFilePath = newLocation.filePath("mixxxtrack.xml"); QFile* oldFile = new QFile(oldFilePath); if (oldFile->exists()) { if (oldFile->copy(newFilePath)) { oldFile->remove(); } else { if (oldFile->error()==14) qDebug() << errorText.arg("library", oldFilePath, newFilePath) << "The destination file already exists."; else qDebug() << errorText.arg("library", oldFilePath, newFilePath) << "Error #" << oldFile->error(); } } delete oldFile; #ifdef __WINDOWS__ oldFilePath = oldLocation.filePath("mixxxbpmschemes.xml"); #else oldFilePath = oldLocation.filePath(".mixxxbpmscheme.xml"); #endif newFilePath = newLocation.filePath("mixxxbpmscheme.xml"); oldFile = new QFile(oldFilePath); if (oldFile->exists()) { if (oldFile->copy(newFilePath)) oldFile->remove(); else { if (oldFile->error()==14) qDebug() << errorText.arg("settings", oldFilePath, newFilePath) << "The destination file already exists."; else qDebug() << errorText.arg("settings", oldFilePath, newFilePath) << "Error #" << oldFile->error(); } } delete oldFile; #ifdef __WINDOWS__ oldFilePath = oldLocation.filePath("MixxxMIDIBindings.xml"); #else oldFilePath = oldLocation.filePath(".MixxxMIDIBindings.xml"); #endif newFilePath = newLocation.filePath("MixxxMIDIBindings.xml"); oldFile = new QFile(oldFilePath); if (oldFile->exists()) { qWarning() << "The MIDI mapping file format has changed in this version of Mixxx. You will need to reconfigure your MIDI controller. See the Wiki for full details on the new format."; if (oldFile->copy(newFilePath)) oldFile->remove(); else { if (oldFile->error()==14) qDebug() << errorText.arg("MIDI mapping", oldFilePath, newFilePath) << "The destination file already exists."; else qDebug() << errorText.arg("MIDI mapping", oldFilePath, newFilePath) << "Error #" << oldFile->error(); } } // Tidy up delete oldFile; #ifdef __WINDOWS__ QFile::remove(oldLocation.filePath("MixxxMIDIDevice.xml")); // Obsolete file, so just delete it #else QFile::remove(oldLocation.filePath(".MixxxMIDIDevice.xml")); // Obsolete file, so just delete it #endif #ifdef __WINDOWS__ oldFilePath = oldLocation.filePath("mixxx.cfg"); #else oldFilePath = oldLocation.filePath(".mixxx.cfg"); #endif newFilePath = newLocation.filePath(SETTINGS_FILE); oldFile = new QFile(oldFilePath); if (oldFile->copy(newFilePath)) oldFile->remove(); else { if (oldFile->error()==14) qDebug() << errorText.arg("configuration", oldFilePath, newFilePath) << "The destination file already exists."; else qDebug() << errorText.arg("configuration", oldFilePath, newFilePath) << "Error #" << oldFile->error(); } delete oldFile; } // Tidy up delete pre170Config; // End pre-1.7.0 code /*************************************************************************** * Post-1.7.0 upgrade code * * Add entries to the IF ladder below if anything needs to change from the * previous to the current version. This allows for incremental upgrades * in case a user upgrades from a few versions prior. ****************************************************************************/ // Read the config file from home directory UserSettingsPointer config(new ConfigObject<ConfigValue>( QDir(settingsPath).filePath(SETTINGS_FILE))); QString configVersion = config->getValueString(ConfigKey("[Config]","Version")); if (configVersion.isEmpty()) { #ifdef __APPLE__ qDebug() << "Config version is empty, trying to read pre-1.9.0 config"; // Try to read the config from the pre-1.9.0 final directory on OS X (we moved it in 1.9.0 final) QScopedPointer<QFile> oldConfigFile(new QFile(QDir::homePath().append("/").append(".mixxx/mixxx.cfg"))); if (oldConfigFile->exists() && ! CmdlineArgs::Instance().getSettingsPathSet()) { qDebug() << "Found pre-1.9.0 config for OS X"; // Note: We changed SETTINGS_PATH in 1.9.0 final on OS X so it must be hardcoded to ".mixxx" here for legacy. config = UserSettingsPointer(new ConfigObject<ConfigValue>( QDir::homePath().append("/.mixxx/mixxx.cfg"))); // Just to be sure all files like logs and soundconfig go with mixxx.cfg // TODO(XXX) Trailing slash not needed anymore as we switches from String::append // to QDir::filePath elsewhere in the code. This is candidate for removal. CmdlineArgs::Instance().setSettingsPath(QDir::homePath().append("/.mixxx/")); configVersion = config->getValueString(ConfigKey("[Config]","Version")); } else { #elif __WINDOWS__ qDebug() << "Config version is empty, trying to read pre-1.12.0 config"; // Try to read the config from the pre-1.12.0 final directory on Windows (we moved it in 1.12.0 final) QScopedPointer<QFile> oldConfigFile(new QFile(QDir::homePath().append("/Local Settings/Application Data/Mixxx/mixxx.cfg"))); if (oldConfigFile->exists() && ! CmdlineArgs::Instance().getSettingsPathSet()) { qDebug() << "Found pre-1.12.0 config for Windows"; // Note: We changed SETTINGS_PATH in 1.12.0 final on Windows so it must be hardcoded to "Local Settings/Application Data/Mixxx/" here for legacy. config = UserSettingsPointer(new ConfigObject<ConfigValue>( QDir::homePath().append("/Local Settings/Application Data/Mixxx/mixxx.cfg"))); // Just to be sure all files like logs and soundconfig go with mixxx.cfg // TODO(XXX) Trailing slash not needed anymore as we switches from String::append // to QDir::filePath elsewhere in the code. This is candidate for removal. CmdlineArgs::Instance().setSettingsPath(QDir::homePath().append("/Local Settings/Application Data/Mixxx/")); configVersion = config->getValueString(ConfigKey("[Config]","Version")); } else { #endif // This must have been the first run... right? :) qDebug() << "No version number in configuration file. Setting to" << MIXXX_VERSION; config->set(ConfigKey("[Config]","Version"), ConfigValue(MIXXX_VERSION)); m_bFirstRun = true; return config; #ifdef __APPLE__ } #elif __WINDOWS__ } #endif } // If it's already current, stop here if (configVersion == MIXXX_VERSION) { qDebug() << "Configuration file is at the current version" << MIXXX_VERSION; return config; } // Allows for incremental upgrades in case someone upgrades from a few versions prior // (I wish we could do a switch on a QString.) /* // Examples, since we didn't store the version number prior to v1.7.0 if (configVersion.startsWith("1.6.0")) { qDebug() << "Upgrading from v1.6.0 to 1.6.1..."; // Upgrade tasks go here configVersion = "1.6.1"; config->set(ConfigKey("[Config]","Version"), ConfigValue("1.6.1")); } if (configVersion.startsWith("1.6.1")) { qDebug() << "Upgrading from v1.6.1 to 1.7.0..."; // Upgrade tasks go here configVersion = "1.7.0"; config->set(ConfigKey("[Config]","Version"), ConfigValue("1.7.0")); } */ // We use the following blocks to detect if this is the first time // you've run the latest version of Mixxx. This lets us show // the promo tracks stats agreement stuff for all users that are // upgrading Mixxx. if (configVersion.startsWith("1.7")) { qDebug() << "Upgrading from v1.7.x..."; // Upgrade tasks go here // Nothing to change, really configVersion = "1.8.0"; config->set(ConfigKey("[Config]","Version"), ConfigValue("1.8.0")); } if (configVersion.startsWith("1.8.0~beta1") || configVersion.startsWith("1.8.0~beta2")) { qDebug() << "Upgrading from v1.8.0~beta..."; // Upgrade tasks go here configVersion = "1.8.0"; config->set(ConfigKey("[Config]","Version"), ConfigValue("1.8.0")); } if (configVersion.startsWith("1.8") || configVersion.startsWith("1.9.0beta1")) { qDebug() << "Upgrading from" << configVersion << "..."; // Upgrade tasks go here #ifdef __APPLE__ QString OSXLocation180 = QDir::homePath().append("/").append(".mixxx"); QString OSXLocation190 = settingsPath; QDir newOSXDir(OSXLocation190); newOSXDir.mkpath(OSXLocation190); QList<QPair<QString, QString> > dirsToMove; dirsToMove.push_back(QPair<QString, QString>(OSXLocation180, OSXLocation190)); dirsToMove.push_back(QPair<QString, QString>(OSXLocation180 + "/midi", OSXLocation190 + "midi")); dirsToMove.push_back(QPair<QString, QString>(OSXLocation180 + "/presets", OSXLocation190 + "presets")); QListIterator<QPair<QString, QString> > dirIt(dirsToMove); QPair<QString, QString> curPair; while (dirIt.hasNext()) { curPair = dirIt.next(); qDebug() << "Moving" << curPair.first << "to" << curPair.second; QDir oldSubDir(curPair.first); QDir newSubDir(curPair.second); newSubDir.mkpath(curPair.second); // Create the new destination directory QStringList contents = oldSubDir.entryList(QDir::Files | QDir::NoDotAndDotDot); QStringListIterator it(contents); QString cur; // Iterate over all the files in the source directory and copy them to the dest dir. while (it.hasNext()) { cur = it.next(); QString src = curPair.first + "/" + cur; QString dest = curPair.second + "/" + cur; qDebug() << "Copying" << src << "to" << dest; if (!QFile::copy(src, dest)) { qDebug() << "Failed to move file during upgrade."; } } // Rename the old directory. newOSXDir.rename(OSXLocation180, OSXLocation180 + "-1.8"); } // Reload the configuration file from the new location. // (We want to make sure we save to the new location...) config = UserSettingsPointer(new ConfigObject<ConfigValue>( QDir(settingsPath).filePath(SETTINGS_FILE))); #endif configVersion = "1.9.0"; config->set(ConfigKey("[Config]","Version"), ConfigValue("1.9.0")); } if (configVersion.startsWith("1.9") || configVersion.startsWith("1.10")) { qDebug() << "Upgrading from v1.9.x/1.10.x..."; bool successful = true; qDebug() << "Copying midi/ to controllers/"; QString midiPath = legacyUserPresetsPath(config); QString controllerPath = userPresetsPath(config); QDir oldDir(midiPath); QDir newDir(controllerPath); newDir.mkpath(controllerPath); // create the new directory QStringList contents = oldDir.entryList(QDir::Files | QDir::NoDotAndDotDot); QStringListIterator it(contents); QString cur; // Iterate over all the files in the source directory and copy them to the dest dir. while (it.hasNext()) { cur = it.next(); if (newDir.exists(cur)) { qDebug() << cur << "already exists in" << controllerPath << "Skipping."; continue; } QString src = oldDir.absoluteFilePath(cur); QString dest = newDir.absoluteFilePath(cur); qDebug() << "Copying" << src << "to" << dest; if (!QFile::copy(src, dest)) { qDebug() << "Failed to copy file during upgrade."; successful = false; } } bool reanalyze_choice = askReanalyzeBeats(); BeatDetectionSettings bpmSettings(config); bpmSettings.setReanalyzeWhenSettingsChange(reanalyze_choice); if (successful) { qDebug() << "Upgrade Successful"; configVersion = "1.11.0"; config->set(ConfigKey("[Config]","Version"), ConfigValue(configVersion)); } else { qDebug() << "Upgrade Failed"; } } if (configVersion.startsWith("1.11")) { qDebug() << "Upgrading from v1.11.x..."; bool successful = false; { MixxxDb mixxxDb(config); const mixxx::DbConnectionPooler dbConnectionPooler( mixxxDb.connectionPool()); if (dbConnectionPooler.isPooling()) { QSqlDatabase dbConnection = mixxx::DbConnectionPooled(mixxxDb.connectionPool()); DEBUG_ASSERT(dbConnection.isOpen()); if (MixxxDb::initDatabaseSchema(dbConnection)) { TrackCollection tc(config); tc.connectDatabase(dbConnection); // upgrade to the multi library folder settings QString currentFolder = config->getValueString(PREF_LEGACY_LIBRARY_DIR); // to migrate the DB just add the current directory to the new // directories table // NOTE(rryan): We don't have to ask for sandbox permission to this // directory because the normal startup integrity check in Library will // notice if we don't have permission and ask for access. Also, the // Sandbox isn't setup yet at this point in startup because it relies on // the config settings path and this function is what loads the config // so it's not ready yet. successful = tc.getDirectoryDAO().addDirectory(currentFolder); tc.disconnectDatabase(); } } } // ask for library rescan to activate cover art. We can later ask for // this variable when the library scanner is constructed. m_bRescanLibrary = askReScanLibrary(); // Versions of mixxx until 1.11 had a hack that multiplied gain by 1/2, // which was compensation for another hack that set replaygain to a // default of 6. We've now removed all of the hacks, so subtracting // 6 from everyone's replay gain should keep things consistent for // all users. int oldReplayGain = config->getValue( ConfigKey("[ReplayGain]", "InitialReplayGainBoost"), 6); int newReplayGain = math_max(-6, oldReplayGain - 6); config->set(ConfigKey("[ReplayGain]", "InitialReplayGainBoost"), ConfigValue(newReplayGain)); // if everything until here worked fine we can mark the configuration as // updated if (successful) { configVersion = MIXXX_VERSION; config->set(ConfigKey("[Config]","Version"), ConfigValue(MIXXX_VERSION)); } else { qDebug() << "Upgrade failed!\n"; } } if (configVersion.startsWith("1.12") || configVersion.startsWith("2.0") || configVersion.startsWith("2.1.0")) { // No special upgrade required, just update the value. configVersion = MIXXX_VERSION; config->set(ConfigKey("[Config]","Version"), ConfigValue(MIXXX_VERSION)); } if (configVersion == MIXXX_VERSION) qDebug() << "Configuration file is now at the current version" << MIXXX_VERSION; else { qWarning() << "Configuration file is at version" << configVersion << "instead of the current" << MIXXX_VERSION; } return config; }
void SMBSlave::smbCopyPut(const QUrl& ksrc, const QUrl& kdst, int permissions, KIO::JobFlags flags) { qCDebug(KIO_SMB) << "src = " << ksrc << ", dest = " << kdst; QFile srcFile (ksrc.toLocalFile()); const QFileInfo srcInfo (srcFile); if (srcInfo.exists()) { if (srcInfo.isDir()) { error(KIO::ERR_IS_DIRECTORY, ksrc.toDisplayString()); return; } } else { error(KIO::ERR_DOES_NOT_EXIST, ksrc.toDisplayString()); return; } if (!srcFile.open(QFile::ReadOnly)) { qCDebug(KIO_SMB) << "could not read from" << ksrc; switch (srcFile.error()) { case QFile::PermissionsError: error(KIO::ERR_WRITE_ACCESS_DENIED, ksrc.toDisplayString()); break; case QFile::OpenError: default: error(KIO::ERR_CANNOT_OPEN_FOR_READING, ksrc.toDisplayString()); break; } return; } totalSize(static_cast<filesize_t>(srcInfo.size())); bool bResume = false; bool bPartExists = false; const bool bMarkPartial = config()->readEntry("MarkPartial", true); const SMBUrl dstOrigUrl (kdst); if (bMarkPartial) { const int errNum = cache_stat(dstOrigUrl.partUrl(), &st); bPartExists = (errNum == 0); if (bPartExists) { if (!(flags & KIO::Overwrite) && !(flags & KIO::Resume)) { bResume = canResume(st.st_size); } else { bResume = (flags & KIO::Resume); } } } int dstfd = -1; int errNum = cache_stat(dstOrigUrl, &st); if (errNum == 0 && !(flags & KIO::Overwrite) && !(flags & KIO::Resume)) { if (S_ISDIR(st.st_mode)) { error( KIO::ERR_IS_DIRECTORY, dstOrigUrl.toDisplayString()); } else { error( KIO::ERR_FILE_ALREADY_EXIST, dstOrigUrl.toDisplayString()); } return; } KIO::filesize_t processed_size = 0; const SMBUrl dstUrl(bMarkPartial ? dstOrigUrl.partUrl() : dstOrigUrl); if (bResume) { // append if resuming qCDebug(KIO_SMB) << "resume" << dstUrl; dstfd = smbc_open(dstUrl.toSmbcUrl(), O_RDWR, 0 ); if (dstfd < 0) { errNum = errno; } else { const off_t offset = smbc_lseek(dstfd, 0, SEEK_END); if (offset == (off_t)-1) { error(KIO::ERR_COULD_NOT_SEEK, dstUrl.toDisplayString()); smbc_close(dstfd); return; } else { processed_size = offset; } } } else { mode_t mode; if (permissions == -1) { mode = 600; } else { mode = permissions | S_IRUSR | S_IWUSR; } qCDebug(KIO_SMB) << "NO resume" << dstUrl; dstfd = smbc_open(dstUrl.toSmbcUrl(), O_CREAT | O_TRUNC | O_WRONLY, mode); if (dstfd < 0) { errNum = errno; } } if (dstfd < 0) { if (errNum == EACCES) { qCDebug(KIO_SMB) << "access denied"; error( KIO::ERR_WRITE_ACCESS_DENIED, dstUrl.toDisplayString()); } else { qCDebug(KIO_SMB) << "can not open for writing"; error( KIO::ERR_CANNOT_OPEN_FOR_WRITING, dstUrl.toDisplayString()); } return; } bool isErr = false; if (processed_size == 0 || srcFile.seek(processed_size)) { // Perform the copy char buf[MAX_XFER_BUF_SIZE]; while (1) { const ssize_t bytesRead = srcFile.read(buf, MAX_XFER_BUF_SIZE); if (bytesRead <= 0) { if (bytesRead < 0) { error(KIO::ERR_COULD_NOT_READ, ksrc.toDisplayString()); isErr = true; } break; } const qint64 bytesWritten = smbc_write(dstfd, buf, bytesRead); if (bytesWritten == -1) { error(KIO::ERR_COULD_NOT_WRITE, kdst.toDisplayString()); isErr = true; break; } processed_size += bytesWritten; processedSize(processed_size); } } else { isErr = true; error(KIO::ERR_COULD_NOT_SEEK, ksrc.toDisplayString()); } // FINISHED if (smbc_close(dstfd) < 0) { qCDebug(KIO_SMB) << dstUrl << "could not write"; error( KIO::ERR_COULD_NOT_WRITE, dstUrl.toDisplayString()); return; } // Handle error condition. if (isErr) { if (bMarkPartial) { const int size = config()->readEntry("MinimumKeepSize", DEFAULT_MINIMUM_KEEP_SIZE); const int errNum = cache_stat(dstUrl, &st); if (errNum == 0 && st.st_size < size) { smbc_unlink(dstUrl.toSmbcUrl()); } } return; } // Rename partial file to its original name. if (bMarkPartial) { smbc_unlink(dstOrigUrl.toSmbcUrl()); if (smbc_rename(dstUrl.toSmbcUrl(), dstOrigUrl.toSmbcUrl()) < 0) { qCDebug(KIO_SMB) << "failed to rename" << dstUrl << "to" << dstOrigUrl << "->" << strerror(errno); error(ERR_CANNOT_RENAME_PARTIAL, dstUrl.toDisplayString()); return; } } #ifdef HAVE_UTIME_H // set modification time const QString mtimeStr = metaData( "modified" ); if (!mtimeStr.isEmpty() ) { QDateTime dt = QDateTime::fromString( mtimeStr, Qt::ISODate ); if ( dt.isValid() ) { struct utimbuf utbuf; utbuf.actime = st.st_atime; // access time, unchanged utbuf.modtime = dt.toTime_t(); // modification time smbc_utime( dstUrl.toSmbcUrl(), &utbuf ); } } #endif // We have done our job => finish finished(); }
void SMBSlave::smbCopyGet(const QUrl& ksrc, const QUrl& kdst, int permissions, KIO::JobFlags flags) { qCDebug(KIO_SMB) << "src = " << ksrc << ", dest = " << kdst; // check if destination is ok ... const QString dstFile = kdst.toLocalFile(); const QFileInfo dstInfo (dstFile); if(dstInfo.exists()) { if(dstInfo.isDir()) { error (ERR_IS_DIRECTORY, kdst.toDisplayString()); return; } if(!(flags & KIO::Overwrite)) { error(ERR_FILE_ALREADY_EXIST, kdst.toDisplayString()); return; } } bool bResume = false; const QFileInfo partInfo (dstFile + QLatin1String(".part")); const bool bPartExists = partInfo.exists(); const bool bMarkPartial = config()->readEntry("MarkPartial", true); if (bMarkPartial && bPartExists && partInfo.size() > 0) { if (partInfo.isDir()) { error(ERR_IS_DIRECTORY, partInfo.absoluteFilePath()); return; } bResume = canResume(partInfo.size()); } if (bPartExists && !bResume) // get rid of an unwanted ".part" file QFile::remove(partInfo.absoluteFilePath()); // open the output file... QFile::OpenMode mode; QString filename; if (bResume) { filename = partInfo.absoluteFilePath(); mode = QFile::WriteOnly | QFile::Append; } else { filename = (bMarkPartial ? partInfo.absoluteFilePath() : dstFile); mode = QFile::WriteOnly | QFile::Truncate; } QFile file (filename); if (!bResume) { QFile::Permissions perms; if (permissions == -1) { perms = QFile::ReadOwner | QFile::WriteOwner; } else { perms = KIO::convertPermissions(permissions | QFile::WriteOwner); } file.setPermissions(perms); } if (!file.open(mode)) { qCDebug(KIO_SMB) << "could not write to" << dstFile; switch (file.error()) { case QFile::OpenError: if (bResume) { error (ERR_CANNOT_RESUME, kdst.toDisplayString()); } else { error(ERR_CANNOT_OPEN_FOR_WRITING, kdst.toDisplayString()); } break; case QFile::PermissionsError: error(ERR_WRITE_ACCESS_DENIED, kdst.toDisplayString()); break; default: error(ERR_CANNOT_OPEN_FOR_WRITING, kdst.toDisplayString()); break; } return; } // setup the source urls const SMBUrl src(ksrc); // Obtain information about source int errNum = cache_stat (src, &st); if (errNum != 0) { if (errNum == EACCES) { error (KIO::ERR_ACCESS_DENIED, src.toDisplayString()); } else { error (KIO::ERR_DOES_NOT_EXIST, src.toDisplayString()); } return; } if (S_ISDIR( st.st_mode )) { error (KIO::ERR_IS_DIRECTORY, src.toDisplayString()); return; } totalSize(st.st_size); // Open the source file KIO::filesize_t processed_size = 0; int srcfd = smbc_open(src.toSmbcUrl(), O_RDONLY, 0); if (srcfd < 0){ errNum = errno; } else { errNum = 0; if (bResume) { qCDebug(KIO_SMB) << "seeking to size" << partInfo.size(); off_t offset = smbc_lseek(srcfd, partInfo.size(), SEEK_SET); if (offset == -1) { error(KIO::ERR_COULD_NOT_SEEK, src.toDisplayString()); smbc_close(srcfd); return; } else { processed_size += offset; } } } if (srcfd < 0) { if(errNum == EACCES) { error( KIO::ERR_ACCESS_DENIED, src.toDisplayString() ); } else { error( KIO::ERR_DOES_NOT_EXIST, src.toDisplayString() ); } return; } // Perform the copy char buf[MAX_XFER_BUF_SIZE]; bool isErr = false; while (1) { const ssize_t bytesRead = smbc_read(srcfd, buf, MAX_XFER_BUF_SIZE); if (bytesRead <= 0) { if (bytesRead < 0) { error( KIO::ERR_COULD_NOT_READ, src.toDisplayString()); isErr = true; } break; } const qint64 bytesWritten = file.write(buf, bytesRead); if (bytesWritten == -1) { qCDebug(KIO_SMB) << "copy now KIO::ERR_COULD_NOT_WRITE"; error( KIO::ERR_COULD_NOT_WRITE, kdst.toDisplayString()); isErr = true; break; } processed_size += bytesWritten; processedSize(processed_size); } // FINISHED smbc_close(srcfd); // Handle error condition. if (isErr) { const QString sPart = partInfo.absoluteFilePath(); if (bMarkPartial) { const int size = config()->readEntry("MinimumKeepSize", DEFAULT_MINIMUM_KEEP_SIZE); if (partInfo.size() < size) { QFile::remove(sPart); } } return; } // Rename partial file to its original name. if (bMarkPartial) { const QString sPart = partInfo.absoluteFilePath(); // Remove old dest file if it exists.. if (dstInfo.exists()) { QFile::remove(dstFile); } if (!QFile::rename(sPart, dstFile)) { qCDebug(KIO_SMB) << "failed to rename" << sPart << "to" << dstFile; error(ERR_CANNOT_RENAME_PARTIAL, sPart); return; } } // Restore the mtime on the file. const QString mtimeStr = metaData("modified"); qCDebug(KIO_SMB) << "modified:" << mtimeStr; if (!mtimeStr.isEmpty()) { QDateTime dt = QDateTime::fromString(mtimeStr, Qt::ISODate); if (dt.isValid()) { struct utimbuf utbuf; utbuf.actime = QFileInfo(file).lastRead().toTime_t(); // access time, unchanged utbuf.modtime = dt.toTime_t(); // modification time utime(QFile::encodeName(dstFile).constData(), &utbuf); } } finished(); }
// We return the ConfigObject here because we have to make changes to the // configuration and the location of the file may change between releases. ConfigObject<ConfigValue>* Upgrade::versionUpgrade(const QString& settingsPath) { /* Pre-1.7.0: * * Since we didn't store version numbers in the config file prior to 1.7.0, * we check to see if the user is upgrading if his config files are in the old location, * since we moved them in 1.7.0. This code takes care of moving them. */ QString oldLocation = QDir::homePath().append("/%1"); #ifdef __WINDOWS__ QFileInfo* pre170Config = new QFileInfo(oldLocation.arg("mixxx.cfg")); #else QFileInfo* pre170Config = new QFileInfo(oldLocation.arg(".mixxx.cfg")); #endif if (pre170Config->exists()) { // Move the files to their new location QString newLocation = settingsPath; if (!QDir(newLocation).exists()) { qDebug() << "Creating new settings directory" << newLocation; QDir().mkpath(newLocation); } newLocation.append("%1"); QString errorText = "Error moving your %1 file %2 to the new location %3: \n"; #ifdef __WINDOWS__ QString oldFilePath = oldLocation.arg("mixxxtrack.xml"); #else QString oldFilePath = oldLocation.arg(".mixxxtrack.xml"); #endif QString newFilePath = newLocation.arg("mixxxtrack.xml"); QFile* oldFile = new QFile(oldFilePath); if (oldFile->exists()) { if (oldFile->copy(newFilePath)) { oldFile->remove(); m_bUpgraded = true; } else { if (oldFile->error()==14) qDebug() << errorText.arg("library", oldFilePath, newFilePath) << "The destination file already exists."; else qDebug() << errorText.arg("library", oldFilePath, newFilePath) << "Error #" << oldFile->error(); } } delete oldFile; #ifdef __WINDOWS__ oldFilePath = oldLocation.arg("mixxxbpmschemes.xml"); #else oldFilePath = oldLocation.arg(".mixxxbpmscheme.xml"); #endif newFilePath = newLocation.arg("mixxxbpmscheme.xml"); oldFile = new QFile(oldFilePath); if (oldFile->exists()) { if (oldFile->copy(newFilePath)) oldFile->remove(); else { if (oldFile->error()==14) qDebug() << errorText.arg("settings", oldFilePath, newFilePath) << "The destination file already exists."; else qDebug() << errorText.arg("settings", oldFilePath, newFilePath) << "Error #" << oldFile->error(); } } delete oldFile; #ifdef __WINDOWS__ oldFilePath = oldLocation.arg("MixxxMIDIBindings.xml"); #else oldFilePath = oldLocation.arg(".MixxxMIDIBindings.xml"); #endif newFilePath = newLocation.arg("MixxxMIDIBindings.xml"); oldFile = new QFile(oldFilePath); if (oldFile->exists()) { qWarning() << "The MIDI mapping file format has changed in this version of Mixxx. You will need to reconfigure your MIDI controller. See the Wiki for full details on the new format."; if (oldFile->copy(newFilePath)) oldFile->remove(); else { if (oldFile->error()==14) qDebug() << errorText.arg("MIDI mapping", oldFilePath, newFilePath) << "The destination file already exists."; else qDebug() << errorText.arg("MIDI mapping", oldFilePath, newFilePath) << "Error #" << oldFile->error(); } } // Tidy up delete oldFile; QFile::remove(oldLocation.arg(".MixxxMIDIDevice.xml")); // Obsolete file, so just delete it #ifdef __WINDOWS__ oldFilePath = oldLocation.arg("mixxx.cfg"); #else oldFilePath = oldLocation.arg(".mixxx.cfg"); #endif newFilePath = newLocation.arg(SETTINGS_FILE); oldFile = new QFile(oldFilePath); if (oldFile->copy(newFilePath)) oldFile->remove(); else { if (oldFile->error()==14) qDebug() << errorText.arg("configuration", oldFilePath, newFilePath) << "The destination file already exists."; else qDebug() << errorText.arg("configuration", oldFilePath, newFilePath) << "Error #" << oldFile->error(); } delete oldFile; } // Tidy up delete pre170Config; // End pre-1.7.0 code /*************************************************************************** * Post-1.7.0 upgrade code * * Add entries to the IF ladder below if anything needs to change from the * previous to the current version. This allows for incremental upgrades * incase a user upgrades from a few versions prior. ****************************************************************************/ // Read the config file from home directory ConfigObject<ConfigValue> *config = new ConfigObject<ConfigValue>(settingsPath + SETTINGS_FILE); QString configVersion = config->getValueString(ConfigKey("[Config]","Version")); if (configVersion.isEmpty()) { #ifdef __APPLE__ qDebug() << "Config version is empty, trying to read pre-1.9.0 config"; //Try to read the config from the pre-1.9.0 final directory on OS X (we moved it in 1.9.0 final) QFile* oldFile = new QFile(QDir::homePath().append("/").append(".mixxx/mixxx.cfg")); if (oldFile->exists()) { qDebug() << "Found pre-1.9.0 config for OS X"; config = new ConfigObject<ConfigValue>(QDir::homePath().append("/").append(".mixxx/mixxx.cfg")); //Note: We changed SETTINGS_PATH in 1.9.0 final on OS X so it must be hardcoded to ".mixxx" here for legacy. configVersion = config->getValueString(ConfigKey("[Config]","Version")); delete oldFile; } else { #endif //This must have been the first run... right? :) qDebug() << "No version number in configuration file. Setting to" << VERSION; config->set(ConfigKey("[Config]","Version"), ConfigValue(VERSION)); m_bFirstRun = true; return config; #ifdef __APPLE__ } #endif } // If it's already current, stop here if (configVersion == VERSION) { qDebug() << "Configuration file is at the current version" << VERSION; return config; } // Allows for incremental upgrades incase someone upgrades from a few versions prior // (I wish we could do a switch on a QString.) /* // Examples, since we didn't store the version number prior to v1.7.0 if (configVersion.startsWith("1.6.0")) { qDebug() << "Upgrading from v1.6.0 to 1.6.1..."; // Upgrade tasks go here configVersion = "1.6.1"; config->set(ConfigKey("[Config]","Version"), ConfigValue("1.6.1")); } if (configVersion.startsWith("1.6.1")) { qDebug() << "Upgrading from v1.6.1 to 1.7.0..."; // Upgrade tasks go here configVersion = "1.7.0"; config->set(ConfigKey("[Config]","Version"), ConfigValue("1.7.0")); } */ //We use the following blocks to detect if this is the first time //you've run the latest version of Mixxx. This lets us show //the promo tracks stats agreement stuff for all users that are //upgrading Mixxx. if (configVersion.startsWith("1.7")) { qDebug() << "Upgrading from v1.7.x..."; // Upgrade tasks go here // Nothing to change, really configVersion = "1.8.0"; config->set(ConfigKey("[Config]","Version"), ConfigValue("1.8.0")); } if (configVersion.startsWith("1.8.0~beta1") || configVersion.startsWith("1.8.0~beta2")) { qDebug() << "Upgrading from v1.8.0~beta..."; // Upgrade tasks go here configVersion = "1.8.0"; config->set(ConfigKey("[Config]","Version"), ConfigValue("1.8.0")); } if (configVersion.startsWith("1.8") || configVersion.startsWith("1.9.0beta1")) { qDebug() << "Upgrading from" << configVersion << "..."; // Upgrade tasks go here #ifdef __APPLE__ QString OSXLocation180 = QDir::homePath().append("/").append(".mixxx"); QString OSXLocation190 = settingsPath; QDir newOSXDir(OSXLocation190); newOSXDir.mkpath(OSXLocation190); QList<QPair<QString, QString> > dirsToMove; dirsToMove.push_back(QPair<QString, QString>(OSXLocation180, OSXLocation190)); dirsToMove.push_back(QPair<QString, QString>(OSXLocation180 + "/midi", OSXLocation190 + "midi")); dirsToMove.push_back(QPair<QString, QString>(OSXLocation180 + "/presets", OSXLocation190 + "presets")); QListIterator<QPair<QString, QString> > dirIt(dirsToMove); QPair<QString, QString> curPair; while (dirIt.hasNext()) { curPair = dirIt.next(); qDebug() << "Moving" << curPair.first << "to" << curPair.second; QDir oldSubDir(curPair.first); QDir newSubDir(curPair.second); newSubDir.mkpath(curPair.second); //Create the new destination directory QStringList contents = oldSubDir.entryList(QDir::Files | QDir::NoDotAndDotDot); QStringListIterator it(contents); QString cur; //Iterate over all the files in the source directory and copy them to the dest dir. while (it.hasNext()) { cur = it.next(); QString src = curPair.first + "/" + cur; QString dest = curPair.second + "/" + cur; qDebug() << "Copying" << src << "to" << dest; if (!QFile::copy(src, dest)) { qDebug() << "Failed to move file during upgrade."; } } //Rename the old directory. newOSXDir.rename(OSXLocation180, OSXLocation180 + "-1.8"); } //Reload the configuration file from the new location. //(We want to make sure we save to the new location...) config = new ConfigObject<ConfigValue>(settingsPath + SETTINGS_FILE); #endif configVersion = "1.9.0"; config->set(ConfigKey("[Config]","Version"), ConfigValue("1.9.0")); } if (configVersion.startsWith("1.9") || configVersion.startsWith("1.10")) { qDebug() << "Upgrading from v1.9.x/1.10.x..."; bool successful = true; qDebug() << "Copying midi/ to controllers/"; QString midiPath = legacyUserPresetsPath(config); QString controllerPath = userPresetsPath(config); QDir oldDir(midiPath); QDir newDir(controllerPath); newDir.mkpath(controllerPath); // create the new directory QStringList contents = oldDir.entryList(QDir::Files | QDir::NoDotAndDotDot); QStringListIterator it(contents); QString cur; //Iterate over all the files in the source directory and copy them to the dest dir. while (it.hasNext()) { cur = it.next(); if (newDir.exists(cur)) { qDebug() << cur << "already exists in" << controllerPath << "Skipping."; continue; } QString src = oldDir.absoluteFilePath(cur); QString dest = newDir.absoluteFilePath(cur); qDebug() << "Copying" << src << "to" << dest; if (!QFile::copy(src, dest)) { qDebug() << "Failed to copy file during upgrade."; successful = false; } } bool reanalyze_choice = askReanalyzeBeats(); config->set(ConfigKey(BPM_CONFIG_KEY, BPM_REANALYZE_WHEN_SETTINGS_CHANGE), ConfigValue(reanalyze_choice)); if (successful) { qDebug() << "Upgrade Successful"; configVersion = "1.11.0"; m_bUpgraded = true; config->set(ConfigKey("[Config]","Version"), ConfigValue(configVersion)); } else { qDebug() << "Upgrade Failed"; } } if (configVersion.startsWith("1.11")) { qDebug() << "Upgrading from v1.11.x..."; // upgrade to the multi library folder settings QString currentFolder = config->getValueString(PREF_LEGACY_LIBRARY_DIR); // to migrate the DB just add the current directory to the new // directories table TrackCollection tc(config); DirectoryDAO directoryDAO = tc.getDirectoryDAO(); // NOTE(rryan): We don't have to ask for sandbox permission to this // directory because the normal startup integrity check in Library will // notice if we don't have permission and ask for access. Also, the // Sandbox isn't setup yet at this point in startup because it relies on // the config settings path and this function is what loads the config // so it's not ready yet. bool successful = directoryDAO.addDirectory(currentFolder); // ask for library rescan to activate cover art. We can later ask for // this variable when the library scanner is constructed. m_bRescanLibrary = askReScanLibrary(); // if everything until here worked fine we can mark the configuration as // updated if (successful) { configVersion = VERSION; m_bUpgraded = true; config->set(ConfigKey("[Config]","Version"), ConfigValue(VERSION)); } else { qDebug() << "Upgrade failed!\n"; } } if (configVersion == VERSION) qDebug() << "Configuration file is now at the current version" << VERSION; else { /* Way too verbose, this confuses the hell out of Linux users when they see this: qWarning() << "Configuration file is at version" << configVersion << "and I don't know how to upgrade it to the current" << VERSION << "\n (That means a function to do this needs to be added to upgrade.cpp.)" << "\n-> Leaving the configuration file version as-is."; */ qWarning() << "Configuration file is at version" << configVersion << "instead of the current" << VERSION; } return config; }
bool QmitkPythonSnippets::LoadStringMap( const QString& filename, QmitkPythonSnippets::QStringMap& oldMap ) { MITK_DEBUG("QmitkPythonSnippets") << "loading from xml file " << filename.toStdString(); QStringMap map; QXmlStreamReader xmlReader; QFile file; QByteArray data; // resource file if( filename.startsWith(":") ) { QResource res( filename ); data = QByteArray( reinterpret_cast< const char* >( res.data() ), res.size() ); xmlReader.addData( data ); } else { file.setFileName( filename ); if (!file.open(QFile::ReadOnly | QFile::Text)) { MITK_ERROR << "Error: Cannot read file " << qPrintable(filename) << ": " << qPrintable(file.errorString()); return false; } xmlReader.setDevice(&file); } xmlReader.readNext(); while(!xmlReader.atEnd()) { xmlReader.readNext(); if(xmlReader.name() == SNIPPETS_XML_ELEMENT_NAME) { QXmlStreamAttributes attributes = xmlReader.attributes(); QString key; QString value; if(attributes.hasAttribute("key")) { key = attributes.value("key").toString(); } if(attributes.hasAttribute("value")) { value = attributes.value("value").toString(); } if( !key.isEmpty() ) { MITK_DEBUG("QmitkPythonSnippets") << "loaded snippet " << key.toStdString(); MITK_DEBUG("QmitkPythonSnippets") << "value " << value.toStdString(); map[key] = value; } } } if (xmlReader.hasError()) { MITK_ERROR << "Error: Failed to parse file " << qPrintable(filename) << ": " << qPrintable(xmlReader.errorString()); return false; } else if (file.error() != QFile::NoError) { MITK_ERROR << "Error: Cannot read file " << qPrintable(filename) << ": " << qPrintable(file.errorString()); return false; } if( file.isOpen() ) file.close(); oldMap = map; return true; }
TrainingSetFile::TSFResult TrainingSetFile::fromFile(QFile &file) { QString version, text; QStringRef name; QXmlStreamReader tsReadXML; QXmlStreamReader::TokenType tt; QStringList textElements; QXmlStreamAttributes attributes; TrainingSetFile *retTSF = new TrainingSetFile(); TSFResult res = {retTSF, true, NoError, "", 0}; TrainingSet *ts = retTSF->getTrainingSet(); int lastPatternIndex = 0, sTextElements, pSize = 0, iSize = 0, tSize = 0; Normalization *inor = new Normalization(), *tnor = new Normalization(); vector<vector<double> > inputs, targets; DataRepresentation *idr = ts->getInputsDataRepresentation(), *tdr = ts->getTargetsDataRepresentation(); if(file.open(QIODevice::ReadOnly)){ tsReadXML.setDevice(&file); while (!tsReadXML.atEnd()) { tt = tsReadXML.readNext(); if(tsReadXML.hasError()){ file.close(); return {retTSF, false, toTSFError(tsReadXML.error()), tsReadXML.errorString(), tsReadXML.lineNumber()}; } if(tt == QXmlStreamReader::StartDocument){ continue; }else if(tt == QXmlStreamReader::StartElement){ name = tsReadXML.name(); if(name == STR_TRAININGSET){ attributes = tsReadXML.attributes(); if(attributes.hasAttribute(STR_PATTERNSIZE) && attributes.hasAttribute(STR_INPUTSSIZE) && attributes.hasAttribute(STR_TARGETSSIZE)) { pSize = attributes.value(STR_PATTERNSIZE).toInt(); iSize = attributes.value(STR_INPUTSSIZE).toInt(); tSize = attributes.value(STR_TARGETSSIZE).toInt(); inputs = vector<vector<double> >(pSize, vector<double>(iSize, 0)); targets = vector<vector<double> >(pSize, vector<double>(tSize, 0)); }else{ file.close(); return { retTSF, false, NotWellFormedError, "NotWellFormedError: Missing attributes (" + STR_PATTERNSIZE + ", " + STR_INPUTSSIZE + ", " + STR_TARGETSSIZE + ") on tag " + STR_TRAININGSET, tsReadXML.lineNumber() }; } }else if(name == STR_PROPERTIES){ attributes = tsReadXML.attributes(); if(attributes.hasAttribute(STR_VERSION)){ version = attributes.value(STR_VERSION).toString(); }else{ file.close(); return { retTSF, false, NotWellFormedError, "NotWellFormedError: Missing attributes (" + STR_VERSION + ") on tag " + STR_PROPERTIES, tsReadXML.lineNumber() }; } }else if(name == STR_INPUTSDATAREPRESENTATION){ attributes = tsReadXML.attributes(); if(attributes.hasAttribute(STR_NAME) && attributes.hasAttribute(STR_WIDTH) && attributes.hasAttribute(STR_HEIGHT) && attributes.hasAttribute(STR_FORMAT)) { idr->setType(drFromStrToInt(attributes.value(STR_NAME).toString())); idr->setWidth(attributes.value(STR_WIDTH).toInt()); idr->setHeight(attributes.value(STR_HEIGHT).toInt()); idr->setImageFormat(fromStrToImgFormat(attributes.value(STR_FORMAT).toString())); }else{ file.close(); return { retTSF, false, NotWellFormedError, "NotWellFormedError: Missing attributes (" + STR_NAME + ", " + STR_WIDTH + ", " + STR_HEIGHT + ", " + STR_FORMAT + ") on tag " + STR_INPUTSDATAREPRESENTATION, tsReadXML.lineNumber() }; } }else if(name == STR_TARGETSDATAREPRESENTATION){ attributes = tsReadXML.attributes(); if(attributes.hasAttribute(STR_NAME) && attributes.hasAttribute(STR_WIDTH) && attributes.hasAttribute(STR_HEIGHT) && attributes.hasAttribute(STR_FORMAT)) { tdr->setType(drFromStrToInt(attributes.value(STR_NAME).toString())); tdr->setWidth(attributes.value(STR_WIDTH).toInt()); tdr->setHeight(attributes.value(STR_HEIGHT).toInt()); tdr->setImageFormat(fromStrToImgFormat(attributes.value(STR_FORMAT).toString())); }else{ file.close(); return { retTSF, false, NotWellFormedError, "NotWellFormedError: Missing attributes (" + STR_NAME + ", " + STR_WIDTH + ", " + STR_HEIGHT + ", " + STR_FORMAT + ") on tag " + STR_TARGETSDATAREPRESENTATION, tsReadXML.lineNumber() }; } }else if(name == STR_INPUTSNORMALIZATION){ attributes = tsReadXML.attributes(); if(attributes.hasAttribute(STR_TYPE) && attributes.hasAttribute(STR_MAXVALUE) && attributes.hasAttribute(STR_MINVALUE) && attributes.hasAttribute(STR_THRESHOLD) && attributes.hasAttribute(STR_AMPLITUDE) && attributes.hasAttribute(STR_ELONGATION)) { inor->setType(normFromStrToInt(attributes.value(STR_TYPE).toString())); inor->setMaxValue(attributes.value(STR_MAXVALUE).toDouble()); inor->setMinValue(attributes.value(STR_MINVALUE).toDouble()); inor->setThreshold(attributes.value(STR_THRESHOLD).toDouble()); inor->setAmplitude(attributes.value(STR_AMPLITUDE).toDouble()); inor->setElongation(attributes.value(STR_ELONGATION).toDouble()); }else{ file.close(); return { retTSF, false, NotWellFormedError, "NotWellFormedError: Missing attributes (" + STR_TYPE + ", " + STR_MAXVALUE + ", " + STR_MINVALUE + ", " + STR_THRESHOLD + ", " + STR_ELONGATION + ") on tag " + STR_INPUTSNORMALIZATION, tsReadXML.lineNumber() }; } }else if(name == STR_TARGETSNORMALIZATION){ attributes = tsReadXML.attributes(); if(attributes.hasAttribute(STR_TYPE) && attributes.hasAttribute(STR_MAXVALUE) && attributes.hasAttribute(STR_MINVALUE) && attributes.hasAttribute(STR_THRESHOLD) && attributes.hasAttribute(STR_AMPLITUDE) && attributes.hasAttribute(STR_ELONGATION)) { tnor->setType(normFromStrToInt(attributes.value(STR_TYPE).toString())); tnor->setMaxValue(attributes.value(STR_MAXVALUE).toDouble()); tnor->setMinValue(attributes.value(STR_MINVALUE).toDouble()); tnor->setThreshold(attributes.value(STR_THRESHOLD).toDouble()); tnor->setAmplitude(attributes.value(STR_AMPLITUDE).toDouble()); tnor->setElongation(attributes.value(STR_ELONGATION).toDouble()); }else{ file.close(); return { retTSF, false, NotWellFormedError, "NotWellFormedError: Missing attributes (" + STR_TYPE + ", " + STR_MAXVALUE + ", " + STR_MINVALUE + ", " + STR_THRESHOLD + ", " + STR_ELONGATION + ") on tag " + STR_TARGETSNORMALIZATION, tsReadXML.lineNumber() }; } }else if(name == STR_PATTERN){ attributes = tsReadXML.attributes(); if(attributes.hasAttribute(STR_INDEX)) { lastPatternIndex = attributes.value(STR_INDEX).toInt(); }else{ file.close(); return { retTSF, false, NotWellFormedError, "NotWellFormedError: Missing attributes (" + STR_INDEX + ") on tag " + STR_PATTERN, tsReadXML.lineNumber() }; } }else if(name == STR_INPUTS){ text = tsReadXML.readElementText(QXmlStreamReader::SkipChildElements); textElements = text.split(STR_SEPARATOR, QString::KeepEmptyParts, Qt::CaseInsensitive); sTextElements = textElements.size(); if(sTextElements == iSize){ for(int i = 0; i < sTextElements; i++){ inputs[lastPatternIndex][i] = textElements[i].toDouble(); } }else{ file.close(); return { retTSF, false, NotWellFormedError, "NotWellFormedError: Incongruence between reported input size with found inputs elements", tsReadXML.lineNumber() }; } }else if(name == STR_TARGETS){ text = tsReadXML.readElementText(QXmlStreamReader::SkipChildElements); textElements = text.split(STR_SEPARATOR, QString::KeepEmptyParts, Qt::CaseInsensitive); sTextElements = textElements.size(); if(sTextElements == tSize){ for(int t = 0; t < sTextElements; t++){ targets[lastPatternIndex][t] = textElements[t].toDouble(); } }else{ file.close(); return { retTSF, false, NotWellFormedError, "NotWellFormedError: Incongruence between reported target size with found target elements", tsReadXML.lineNumber() }; } } } } retTSF->setFileName(file.fileName()); res.file = retTSF; ts->setPatternCount(pSize); ts->setInputs(inputs, iSize); ts->setTargets(targets, tSize); ts->setInputsNormalization(inor); ts->setTargetsNormalization(tnor); ts->setInputsDataRepresentation(idr); ts->setTargetsDataRepresentation(tdr); res.sucess = true; res.errnum = toTSFError(QXmlStreamReader::NoError); res.errormsg = ""; res.line = -1; file.close(); return res; }else{ file.close(); return { retTSF, false, toTSFError(file.error()), file.errorString(), -1 }; } }
CC_FILE_ERROR LoadPolyline(QFile& file, ccHObject& container, int32_t index, ESRI_SHAPE_TYPE shapeTypeInt, const CCVector3d& PShift) { char header[40]; file.read(header,40); //check for errors if (file.error() != QFile::NoError) return CC_FERR_READING; //Byte 0: Box { //The Bounding Box for the PolyLine stored in the order Xmin, Ymin, Xmax, Ymax //DGM: ignored //double xMin = qFromLittleEndian<double>(*reinterpret_cast<double*>(header )); //double xMax = qFromLittleEndian<double>(*reinterpret_cast<double*>(header+ 8)); //double yMin = qFromLittleEndian<double>(*reinterpret_cast<double*>(header+16)); //double yMax = qFromLittleEndian<double>(*reinterpret_cast<double*>(header+24)); } //Byte 32: NumParts (The number of parts in the PolyLine) int32_t numParts = qFromLittleEndian<int32_t>(*reinterpret_cast<int32_t*>(header+32)); //Byte 36: NumPoints (The total number of points for all parts) int32_t numPoints = qFromLittleEndian<int32_t>(*reinterpret_cast<int32_t*>(header+36)); //Byte 40: Parts (An array of length NumParts) //for each part, the index of its first point in the points array std::vector<int32_t> startIndexes; { try { startIndexes.resize(numParts,0); } catch(std::bad_alloc) { return CC_FERR_NOT_ENOUGH_MEMORY; } for (int32_t i=0; i!=numParts; ++i) { file.read(header,4); startIndexes[i] = qFromLittleEndian<int32_t>(*reinterpret_cast<int32_t*>(header)); } //FIXME: we should use this information and create as many polylines as necessary! } ccPointCloud* vertices = new ccPointCloud("vertices"); if (!vertices->reserve(numPoints)) { return CC_FERR_NOT_ENOUGH_MEMORY; } vertices->setEnabled(false); //Points (An array of length NumPoints) { for (int32_t i=0; i<numPoints; ++i) { file.read(header,16); //check for errors if (file.error() != QFile::NoError) return CC_FERR_READING; double x = qFromLittleEndian<double>(*reinterpret_cast<double*>(header )); double y = qFromLittleEndian<double>(*reinterpret_cast<double*>(header+8)); CCVector3 P(static_cast<PointCoordinateType>(x + PShift.x), static_cast<PointCoordinateType>(y + PShift.y), 0); vertices->addPoint(P); } } //3D polylines bool is3D = (shapeTypeInt > SHP_POINT_Z && shapeTypeInt < SHP_POINT_M); if (is3D) { //Z boundaries { file.read(header,16); //DGM: ignored //double zMin = qFromLittleEndian<double>(*reinterpret_cast<double*>(header )); //double zMax = qFromLittleEndian<double>(*reinterpret_cast<double*>(header+8)); } //Z coordinates (an array of length NumPoints) { for (int32_t i=0; i<numPoints; ++i) { file.read(header,8); //check for errors if (file.error() != QFile::NoError) return CC_FERR_READING; double z = qFromLittleEndian<double>(*reinterpret_cast<double*>(header)); const CCVector3* P = vertices->getPoint(i); const_cast<CCVector3*>(P)->z = static_cast<PointCoordinateType>(z + PShift.z); } } } //3D polylines or 2D polylines + measurement if (shapeTypeInt > SHP_POINT_Z) { //M boundaries ccScalarField* sf = 0; { file.read(header,16); //check for errors if (file.error() != QFile::NoError) return CC_FERR_READING; double mMin = qFromLittleEndian<double>(*reinterpret_cast<double*>(header )); double mMax = qFromLittleEndian<double>(*reinterpret_cast<double*>(header+8)); if (mMin != ESRI_NO_DATA && mMax != ESRI_NO_DATA) { sf = new ccScalarField("Measures"); if (!sf->reserve(numPoints)) { ccLog::Warning("[SHP] Not enough memory to load scalar values!"); sf->release(); sf = 0; } } } //M values (an array of length NumPoints) if (sf) { double scalar = qToLittleEndian<double>(ESRI_NO_DATA); for (int32_t i=0; i<numPoints; ++i) { file.read(header,8); //check for errors if (file.error() != QFile::NoError) return CC_FERR_READING; double m = qFromLittleEndian<double>(*reinterpret_cast<double*>(header)); ScalarType s = m == ESRI_NO_DATA ? NAN_VALUE : static_cast<ScalarType>(m); sf->addElement(s); } sf->computeMinAndMax(); int sfIdx = vertices->addScalarField(sf); vertices->setCurrentDisplayedScalarField(sfIdx); vertices->showSF(true); } } //and of course the polyline! { ccPolyline* poly = new ccPolyline(vertices); poly->addChild(vertices); //test if the polyline is closed if (numPoints > 2 && (*vertices->getPoint(0) - *vertices->getPoint(numPoints-1)).norm() < ZERO_TOLERANCE) { numPoints--; vertices->resize(numPoints); poly->setClosed(true); } if (!poly->reserve(numPoints)) { delete poly; return CC_FERR_NOT_ENOUGH_MEMORY; } poly->addPointIndex(0,numPoints); poly->showSF(vertices->sfShown()); poly->setName(QString("Polyline #%1").arg(index)); poly->set2DMode(!is3D); //FIXME DGM: maybe we should ask the user? container.addChild(poly); } return CC_FERR_NO_ERROR; }
void CFileHasher::run() { QTime tTime; QByteArray baBuffer; const int nBufferSize = 64 * 1024; m_pSection.lock(); while(!m_lQueue.isEmpty()) { CSharedFilePtr pFile = m_lQueue.dequeue(); systemLog.postLog(LogSeverity::Debug, QString("Hashing %1").arg(pFile->m_sFileName)); //qDebug() << "Hashing" << pFile->m_sFileName; tTime.start(); m_pSection.unlock(); bool bHashed = true; QFile f; f.setFileName(pFile->m_sDirectory + QString("/") + pFile->m_sFileName); if(f.exists() && f.open(QFile::ReadOnly)) { baBuffer.resize(nBufferSize); pFile->m_lHashes.append(new CHash(CHash::SHA1)); while(!f.atEnd()) { if(!m_bActive) { systemLog.postLog(LogSeverity::Debug, QString("CFileHasher aborting...")); //qDebug() << "CFileHasher aborting..."; bHashed = false; break; } qint64 nRead = f.read(baBuffer.data(), nBufferSize); if(nRead < 0) { bHashed = false; systemLog.postLog(LogSeverity::Debug, QString("File read error: %1").arg(f.error())); //qDebug() << "File read error:" << f.error(); break; } else if(nRead < nBufferSize) { baBuffer.resize(nRead); } for(int i = 0; i < pFile->m_lHashes.size(); i++) { pFile->m_lHashes[i]->AddData(baBuffer); } } f.close(); } else { systemLog.postLog(LogSeverity::Debug, QString("File open error: %1").arg(f.error())); //qDebug() << "File open error: " << f.error(); bHashed = false; } if(bHashed) { double nRate = (f.size() / (tTime.elapsed() / 1000.0)) / 1024.0 / 1024.0; systemLog.postLog(LogSeverity::Debug, QString("File %1 hashed at %2 MB/s").arg(pFile->m_sFileName).arg(nRate)); //qDebug() << "File " << pFile->m_sFileName << "hashed at" << nRate << "MB/s:"; for(int i = 0; i < pFile->m_lHashes.size(); i++) { pFile->m_lHashes[i]->Finalize(); systemLog.postLog(LogSeverity::Debug, QString("%1").arg(pFile->m_lHashes[i]->ToURN())); //qDebug() << pFile->m_lHashes[i]->ToURN(); } emit FileHashed(pFile); } m_pSection.lock(); if(!m_bActive) { break; } if(bHashed && m_lQueue.isEmpty()) { emit QueueEmpty(); systemLog.postLog(LogSeverity::Debug, QString("Hasher waiting...")); //qDebug() << "Hasher " << this << "waiting..."; CFileHasher::m_oWaitCond.wait(&m_pSection, 10000); } } for(uint i = 0; i < m_nMaxHashers; i++) { if(m_pHashers[i] == this) { m_pHashers[i] = 0; deleteLater(); m_nRunningHashers--; if(m_nRunningHashers == 0) { delete [] m_pHashers; m_pHashers = 0; } break; } } m_pSection.unlock(); systemLog.postLog(LogSeverity::Debug, QString("CFileHasher done. %1").arg(m_nRunningHashers)); //qDebug() << "CFileHasher done. " << m_nRunningHashers; }
int Parser::parseXML( std::map< std::pair< QString , QString > , QString> & m ) { /* We'll parse the example.xml */ QFile* file = new QFile(m_uifileuri.data()); /* If we can't open it, let's show an error message. */ if (!file->open(QIODevice::ReadOnly | QIODevice::Text)) { QString errMsg = file->errorString(); QFile::FileError err = QFile::NoError; //in Qt5, replace QFile by QFileDevice err = file->error(); qDebug() << err; return 1; } /* QXmlStreamReader takes any QIODevice. */ QXmlStreamReader xml(file); /* We'll parse the XML until we reach end of it.*/ while(!xml.atEnd() && !xml.hasError()) { QXmlStreamReader::TokenType token = xml.readNext(); // Read next element if(token == QXmlStreamReader::StartDocument) { //If token is just StartDocument, we'll go to next continue; } else if (xml.qualifiedName() == "widget" && xml.isEndElement() != true) { QString widgetType = xml.attributes().value("", "class").toString() ; QString widgetName = xml.attributes().value("", "name").toString() ; if( !widgetName.startsWith( m_prefix ) ) { continue ; } if (widgetType.compare("QTextEdit") == 0 || widgetType.compare("QComboBox") == 0 || widgetType.compare("QLineEdit") == 0) { m[std::make_pair(widgetType, widgetName)] = "QString"; } else if (widgetType.compare("QCheckBox") == 0 || widgetType.compare("QRadioButton") == 0) { m[std::make_pair(widgetType, widgetName)] = "bool"; } else if (widgetType.compare("QDoubleSpinBox") == 0) { m[std::make_pair(widgetType, widgetName)] = "double"; } else if (widgetType.compare("QSpinBox") == 0 || widgetType.compare("QScrollBar") == 0) { m[std::make_pair(widgetType, widgetName)] = "int"; } else if (widgetType.compare("QListWidget") == 0) { m[std::make_pair(widgetType, widgetName)] = "std::map<std::pair<unsigned long,QString>,bool>"; } // Store values into the dictionary // m[std::make_pair(widgetType, xml.attributes().at(1).value().toString())] = ""; // Print values to the console } } /* Error handling. */ if(xml.hasError()) { } /* Removes any device() or data from the reader * and resets its internal state to the initial state. */ xml.clear(); file->close(); delete file; return 0; }
int main(int argc, char * argv[]) { bool impl = false; bool wrap = false; bool subcl = false; bool extract = false; bool imagecollection = false; bool imagecollection_tmpfile = false; bool convert = false; QStringList images; const char *error = 0; const char* fileName = 0; const char* className = 0; const char* headerFile = 0; const char* convertedUiFile = 0; QByteArray outputFile; QByteArray qrcOutputFile; QByteArray image_tmpfile; const char* projectName = 0; const char* trmacro = 0; bool nofwd = false; bool fix = false; bool deps = false; bool implicitIncludes = true; QByteArray pchFile; QApplication app(argc, argv, false); for (int n = 1; n < argc && error == 0; n++) { QByteArray arg = argv[n]; if (arg[0] == '-') { // option QByteArray opt = arg.data() + 1; if (opt[0] == 'o') { // output redirection if (opt[1] == '\0') { if (!(n < argc-1)) { error = "Missing output-file name"; break; } outputFile = argv[++n]; } else outputFile = opt.data() + 1; } else if (opt[0] == 'i' || opt == "impl") { impl = true; if (opt == "impl" || opt[1] == '\0') { if (!(n < argc-1)) { error = "Missing name of header file"; break; } headerFile = argv[++n]; } else headerFile = opt.data() + 1; } else if (opt[0] == 'w' || opt == "wrap") { wrap = true; if (opt == "wrap" || opt[1] == '\0') { if (!(n < argc-1)) { error = "Missing name of converted ui file"; break; } convertedUiFile = argv[++n]; } else convertedUiFile = opt.data() + 1; } else if (opt == "extract") { // output redirection extract = true; if (!(n < argc-1)) { error = "Missing output qrc-file name"; break; } qrcOutputFile = argv[++n]; } else if ( opt[0] == 'e' || opt == "embed" ) { imagecollection = true; if ( opt == "embed" || opt[1] == '\0' ) { if ( !(n < argc-1) ) { error = "Missing name of project"; break; } projectName = argv[++n]; } else { projectName = opt.data() + 1; } if ( argc > n+1 && qstrcmp( argv[n+1], "-f" ) == 0 ) { imagecollection_tmpfile = true; image_tmpfile = argv[n+2]; n += 2; } } else if (opt == "d") { deps = true; } else if (opt == "no-implicit-includes") { implicitIncludes = false; } else if (opt == "nofwd") { nofwd = true; } else if (opt == "nounload") { // skip } else if (opt == "convert") { convert = true; } else if (opt == "subdecl") { subcl = true; if (!(n < argc-2)) { error = "Missing arguments"; break; } className = argv[++n]; headerFile = argv[++n]; } else if (opt == "subimpl") { subcl = true; impl = true; if (!(n < argc-2)) { error = "Missing arguments"; break; } className = argv[++n]; headerFile = argv[++n]; } else if (opt == "tr") { if (opt == "tr" || opt[1] == '\0') { if (!(n < argc-1)) { error = "Missing tr macro."; break; } trmacro = argv[++n]; } else { trmacro = opt.data() + 1; } } else if (opt == "L") { if (!(n < argc-1)) { error = "Missing plugin path."; break; } ++n; // ignore the next argument } else if (opt == "version") { fprintf(stderr, "Qt User Interface Compiler version %s\n", QT_VERSION_STR); return 1; } else if (opt == "help") { break; } else if (opt == "fix") { fix = true; } else if (opt == "pch") { if (!(n < argc-1)) { error = "Missing name of PCH file"; break; } pchFile = argv[++n]; } else { error = "Unrecognized option"; } } else { if (imagecollection && !imagecollection_tmpfile) images << QLatin1String(argv[n]); else if (fileName) // can handle only one file error = "Too many input files specified"; else fileName = argv[n]; } } if (argc < 2 || error || (!fileName && !imagecollection)) { fprintf(stderr, "Qt User Interface Compiler version %s\n", QT_VERSION_STR); if (error) fprintf(stderr, "uic: %s\n", error); fprintf(stderr, "Usage: %s [options] [mode] <uifile>\n\n" "Convert a UI file to version 4:\n" " %s [options] -convert <uifile>\n" "Generate declaration:\n" " %s [options] <uifile>\n" "\t<uiheaderfile> name of the data file\n" " %s [options] -decl <uiheaderfile> <uifile>\n" "\t<uiheaderfile> name of the data file\n" " %s [options] -wrap <converteduifile> <uifile>\n" "\t<converteduifile> name of the converted ui file\n" "Generate implementation:\n" " %s [options] -impl <headerfile> <uifile>\n" "\t<headerfile> name of the declaration file\n" "Generate image collection:\n" " %s [options] -embed <project> <image1> <image2> <image3> ...\n" "or\n" " %s [options] -embed <project> -f <temporary file containing image names>\n" "\t<project> project name\n" "\t<image[1-N]> image files\n" "Generate subclass declaration:\n" " %s [options] -subdecl <subclassname> <baseclassheaderfile> <uifile>\n" "\t<subclassname> name of the subclass to generate\n" "\t<baseclassheaderfile> declaration file of the baseclass\n" "Generate subclass implementation:\n" " %s [options] -subimpl <subclassname> <subclassheaderfile> <uifile>\n" "\t<subclassname> name of the subclass to generate\n" "\t<subclassheaderfile> declaration file of the subclass\n" "Options:\n" "\t-o file Write output to file rather than stdout\n" "\t-extract qrcFile Create resource file and extract embedded images into \"image\" dir\n" "\t-pch file Add #include \"file\" as the first statement in implementation\n" "\t-nofwd Omit forward declarations of custom classes\n" "\t-no-implicit-includes Do not generate #include-directives for custom classes\n" "\t-nounload Don't unload plugins after processing\n" "\t-tr func Use func() instead of tr() for i18n\n" "\t-L path Additional plugin search path\n" "\t-version Display version of uic\n" "\t-help Display this information\n" , argv[0], argv[0], argv[0], argv[0], argv[0], argv[0], argv[0], argv[0], argv[0], argv[0] ); return 1; } if (imagecollection_tmpfile) { QFile ifile(QFile::decodeName(image_tmpfile)); if (ifile.open(QIODevice::ReadOnly)) { QTextStream ts(&ifile); QString s = ts.read(); s = s.simplified(); images = s.split(QLatin1Char(' ')); for (QStringList::Iterator it = images.begin(); it != images.end(); ++it) *it = (*it).simplified(); } } QFile fileOut; if (!outputFile.isEmpty()) { fileOut.setFileName(QFile::decodeName(outputFile)); if (!fileOut.open(QIODevice::WriteOnly)) { fprintf(stderr, "%s: Could not open output file '%s'\n", argv[0], outputFile.data()); return 1; } } else { fileOut.open(QIODevice::WriteOnly, stdout); } QTextStream out(&fileOut); Ui3Reader ui3(out); ui3.setExtractImages(extract, qrcOutputFile); if (projectName && imagecollection) { out.setEncoding(QTextStream::Latin1); ui3.embed(projectName, images); return 0; } out.setEncoding(QTextStream::UnicodeUTF8); QFile file(QFile::decodeName(fileName)); if (!file.open(QIODevice::ReadOnly)) { fprintf(stderr, "%s: Could not open file '%s'\n", argv[0], fileName); return 1; } QDomDocument doc; QString errMsg; int errLine; if (!doc.setContent(&file, &errMsg, &errLine)) { fprintf(stderr, "%s: Failed to parse %s: %s in line %d\n", argv[0], fileName, errMsg.latin1(), errLine); return 1; } QDomElement e = doc.firstChild().toElement(); double version = e.attribute(QLatin1String("version"), QLatin1String("3.0")).toDouble(); if (version > 3.3) { fprintf(stderr, "%s: File generated with too recent version of Qt Designer (%s vs. %s)\n", argv[0], e.attribute(QLatin1String("version")).latin1(), "3.3"); return 1; } DomTool::fixDocument(doc); if (fix) { out << doc.toString(); return 0; } if (imagecollection) { out.setEncoding(QTextStream::Latin1); ui3.embed(projectName, images); return 0; } else if (deps) { QStringList globalIncludes, localIncludes; ui3.computeDeps(e, globalIncludes, localIncludes, impl); foreach (QString i, globalIncludes) printf("%s\n", i.toLatin1().constData()); foreach (QString i, localIncludes) printf("%s\n", i.toLatin1().constData()); if (impl) printf("%s\n", headerFile); return 0; } else if (convert) { ui3.generateUi4(QFile::decodeName(fileName), QFile::decodeName(outputFile), doc, implicitIncludes); return 0; } QString protector; if (subcl && className && !impl) protector = QString::fromUtf8(className).toUpper() + QLatin1String("_H"); if (!protector.isEmpty()) { out << "#ifndef " << protector << endl; out << "#define " << protector << endl; } if (!pchFile.isEmpty() && impl) { out << "#include \"" << pchFile << "\" // PCH include" << endl; } if (headerFile) { out << "#include \"" << headerFile << "\"" << endl << endl; } QString convertedUi; if (wrap) { convertedUi = QFile::decodeName(convertedUiFile); int pos = convertedUi.lastIndexOf(".ui"); if (pos > 0) { convertedUi = convertedUi.mid(0, pos); convertedUi += QLatin1String(".h"); } convertedUi = QLatin1String("ui_") + convertedUi; } ui3.generate(QFile::decodeName(fileName), QFile::decodeName(outputFile), doc, !impl, subcl, QString::fromUtf8(trmacro), QString::fromUtf8(className), nofwd, implicitIncludes, convertedUi); if (!protector.isEmpty()) { out << endl; out << "#endif // " << protector << endl; } if (fileOut.error() != QFile::NoError) { fprintf(stderr, "%s: Error writing to file\n", argv[0]); if (!outputFile.isEmpty()) remove(outputFile); } return 0; }