QList<QSharedPointer<TransportDefinition> > TransportReader::parse(const QDomDocument &document) { QList<QSharedPointer<TransportDefinition> > result; QDomNode node = document.documentElement().firstChild(); while (! node.isNull()) { if (node.toElement().tagName() == "transportDefinitions") { QDomNode transportNode = node.toElement().firstChild(); while(!transportNode.isNull()) { if (transportNode.toElement().tagName() == "transportDefinition") { QSharedPointer<TransportDefinition> transport = _parseTransport(transportNode.toElement()); if (! transport.isNull()) result << transport; } transportNode = transportNode.nextSiblingElement(); } } node = node.nextSiblingElement(); } return result; }
QList<QSharedPointer<FormatDefinition> > FormatReader::parse(const QDomDocument &document) { QList<QSharedPointer<FormatDefinition> > result; QDomNode node = document.documentElement().firstChild(); while (! node.isNull()) { if (node.toElement().tagName() == "formatDefinitions") { QDomNode formatNode = node.toElement().firstChild(); while(!formatNode.isNull()) { if (formatNode.toElement().tagName() == "formatDefinition") { QSharedPointer<FormatDefinition> format = _parseFormat(formatNode.toElement()); if (! format.isNull()) result << format; } formatNode = formatNode.nextSiblingElement(); } } node = node.nextSiblingElement(); } return result; }
QDomElement QDomNodeProto:: nextSiblingElement(const QString &taName) const { QDomNode *item = qscriptvalue_cast<QDomNode*>(thisObject()); if (item) return item->nextSiblingElement(taName); return QDomElement(); }
bool XmlRelationCheckerCoreImpl::SearchGivenNodeFrom(QDomNode nodeToCheck, const QString& key, XmlRelation* xmlRelation) const { if(!nodeToCheck.isNull()) { if(nodeToCheck.isElement() && !nodeToCheck.isComment()) { //For debug //const QString& nodeName = nodeToCheck.nodeName(); //Controll if the node is a node to key QList<QString>* keyList = CheckIsNodeFrom(nodeToCheck, xmlRelation); bool found = false; for(int i=0; i < keyList->size() && !found; ++i) { if(key.compare(keyList->at(i), Qt::CaseInsensitive) == 0) { found = true; } } delete keyList; //Check this is the wanted node to if(found || SearchGivenNodeFrom(nodeToCheck.firstChildElement(), key, xmlRelation)) { return true; } } //Recursive call return SearchGivenNodeFrom(nodeToCheck.nextSiblingElement(), key, xmlRelation); } return false; }
void StationsPluginFactorySimple::loadCities(const QString & xml) { QFile file(xml); QDomDocument doc; QDomNode city; if (!file.exists()) { qDebug() << "Skipping non-existent " << xml << "file"; return ; } if (!file.open(QIODevice::ReadOnly)) { qWarning() << "Can't open" << file.fileName() << ": " << file.error(); return ; } doc.setContent(&file); city = doc.firstChildElement("cities").firstChildElement("city"); while (!city.isNull()) { loadCity(city); city = city.nextSiblingElement("city"); } }
void QXmppRpcResponseIq::parseElementFromChild(const QDomElement &element) { QDomElement queryElement = element.firstChildElement("query"); QDomElement methodElement = queryElement.firstChildElement("methodResponse"); const QDomElement contents = methodElement.firstChildElement(); if( contents.tagName().toLower() == "params") { QDomNode param = contents.firstChildElement("param"); while (!param.isNull()) { QStringList errors; const QVariant value = QXmppRpcMarshaller::demarshall(param.firstChildElement("value"), errors); if (!errors.isEmpty()) break; m_values << value; param = param.nextSiblingElement("param"); } } else if( contents.tagName().toLower() == "fault") { QStringList errors; const QDomElement errElement = contents.firstChildElement("value"); const QVariant error = QXmppRpcMarshaller::demarshall(errElement, errors); if (!errors.isEmpty()) return; m_faultCode = error.toMap()["faultCode"].toInt(); m_faultString = error.toMap()["faultString"].toString(); } }
static QString parseInstrName(const QString& name) { QString sName; QDomDocument dom; int line, column; QString err; if (!dom.setContent(name, false, &err, &line, &column)) { QString col, ln; col.setNum(column); ln.setNum(line); QString error = err + "\n at line " + ln + " column " + col; qDebug("error: %s\n", qPrintable(error)); qDebug(" data:<%s>\n", qPrintable(name)); return QString(); } for (QDomNode e = dom.documentElement(); !e.isNull(); e = e.nextSiblingElement()) { for (QDomNode ee = e.firstChild(); !ee.isNull(); ee = ee.nextSibling()) { QDomElement el = ee.toElement(); const QString& tag(el.tagName()); if (tag == "symbol") { QString name = el.attribute(QString("name")); if (name == "flat") sName += "b"; else if (name == "sharp") sName += "#"; } QDomText t = ee.toText(); if (!t.isNull()) sName += t.data(); } } return sName; }
bool UpdatesInfo::Private::parseCompatUpdateElement(const QDomElement & updateE) { if( updateE.isNull() ) return false; UpdateInfo info; info.type = CompatUpdate; for( QDomNode childNode = updateE.firstChild(); !childNode.isNull(); childNode = childNode.nextSiblingElement() ) { const QDomElement childE = childNode.toElement(); if( childE.isNull() ) continue; if( childE.tagName() == QLatin1String( "ReleaseNotes" ) ) { info.data[childE.tagName()] = QUrl(childE.text()); } else if( childE.tagName() == QLatin1String( "UpdateFile" ) ) { UpdateFileInfo ufInfo; ufInfo.platformRegEx = childE.attribute(QLatin1String( "platform-regex" ), QLatin1String( ".*" )); ufInfo.compressedSize = childE.attribute( QLatin1String( "compressed-size" ) ).toLongLong(); ufInfo.uncompressedSize = childE.attribute( QLatin1String( "uncompressed-size" ) ).toLongLong(); ufInfo.arch = childE.attribute(QLatin1String( "Arch" ), QLatin1String( "i386" )); ufInfo.fileName = childE.text(); info.updateFiles.append(ufInfo); } else { info.data[childE.tagName()] = childE.text(); } } if (!info.data.contains( QLatin1String( "CompatLevel" ) )) { setInvalidContentError(tr("CompatUpdate element without CompatLevel")); return false; } if (!info.data.contains( QLatin1String( "ReleaseDate" ) )) { setInvalidContentError(tr("CompatUpdate element without ReleaseDate")); return false; } if (info.updateFiles.isEmpty()) { setInvalidContentError(tr("CompatUpdate element without UpdateFile")); return false; } updateInfoList.append(info); return true; }
bool OSParser::parseXml(QByteArray text) { qDebug("OSParser::parseXml: source: '%s'", text.constData()); s_list.clear(); bool ok = dom_document.setContent(text); qDebug("OSParser::parseXml: success: %d", ok); if (!ok) return false; QDomNode root = dom_document.documentElement(); //qDebug("tagname: '%s'", root.toElement().tagName().toLatin1().constData()); QString base_url = root.firstChildElement("base").text(); //qDebug("base_url: '%s'", base_url.toLatin1().constData()); QDomNode child = root.firstChildElement("results"); if (!child.isNull()) { //qDebug("items: %s", child.toElement().attribute("items").toLatin1().constData()); QDomNode subtitle = child.firstChildElement("subtitle"); while (!subtitle.isNull()) { //qDebug("tagname: '%s'", subtitle.tagName().toLatin1().constData()); qDebug("OSParser::parseXml: text: '%s'", subtitle.toElement().text().toLatin1().constData()); OSSubtitle sub; sub.releasename = subtitle.firstChildElement("releasename").text(); QString path = subtitle.firstChildElement("download").text(); if (path.contains("http://")) { sub.link = subtitle.firstChildElement("download").text(); } else { sub.link = base_url + subtitle.firstChildElement("download").text(); } sub.detail = subtitle.firstChildElement("detail").text(); sub.date = subtitle.firstChildElement("subadddate").text(); sub.rating = subtitle.firstChildElement("subrating").text(); sub.comments = subtitle.firstChildElement("subcomments").text(); sub.movie = subtitle.firstChildElement("movie").text(); sub.files = subtitle.firstChildElement("files").text(); sub.format = subtitle.firstChildElement("format").text(); sub.language = subtitle.firstChildElement("language").text(); sub.iso639 = subtitle.firstChildElement("iso639").text(); sub.user = subtitle.firstChildElement("user").text(); s_list.append(sub); subtitle = subtitle.nextSiblingElement("subtitle"); } } return true; }
void StationsPluginWien::handleInfos(const QByteArray & data) { QDomDocument doc; QDomNode node; doc.setContent(data); node = doc.firstChildElement("stations").firstChildElement("station"); while (!node.isNull()) { Station *station; QDomNamedNodeMap attrs = node.attributes(); int id; bool ok; qreal lat, lng; id = node.firstChildElement("id").text().toInt(&ok); if (!ok) continue ; station = getOrCreateStation(id); station->setData(node.firstChildElement("internal_id").text().toInt()); if (station->name().isEmpty()) station->setName(node.firstChildElement("name").text()); if (station->description().isEmpty()) station->setDescription(node.firstChildElement("description").text()); lng = node.firstChildElement("longitude").text().toDouble(); lat = node.firstChildElement("latitude").text().toDouble(); if (station->pos().isNull()) station->setPos(QPointF(lat, lng)); station->setBikes(node.firstChildElement("free_bikes").text().toInt()); station->setFreeSlots(node.firstChildElement("free_boxes").text().toInt()); station->setTotalSlots(node.firstChildElement("boxes").text().toInt()); storeOrDropStation(station); node = node.nextSiblingElement("station"); } emit stationsCreated(stations.values()); emit stationsUpdated(stations.values()); }
QString XmlRelationCheckerCoreImpl::SearchGivenNodeTo(QDomNode nodeToCheck, const QString& key, XmlRelation* xmlRelation, const QString& parentNumberBase, int number) const { if(!nodeToCheck.isNull()) { if(nodeToCheck.isElement() && !nodeToCheck.isComment()) { //Initialize the identifiersNumber string with the base number QString identifierNumber = parentNumberBase; //If it's not empty is because it's the first node and it needn't the dot seprator if(!parentNumberBase.isEmpty()) { identifierNumber.append('.'); } //Attach the number identifierNumber.append(QString::number(number)); //Controll if the node is a node to key const QString& nodeToKey = CheckIsNodeTo(nodeToCheck, xmlRelation); //Check this is the wanted node to if(key.compare(nodeToKey, Qt::CaseInsensitive) == 0) { return identifierNumber; } //Check the son else { const QString& sonIdentifier = SearchGivenNodeTo(nodeToCheck.firstChildElement(), key, xmlRelation, identifierNumber, 1); //If the son is the node searched if( ! sonIdentifier.isEmpty()) { //return the child identifier number return sonIdentifier; } } } //Recursive call on the sibling return SearchGivenNodeTo(nodeToCheck.nextSiblingElement(), key, xmlRelation, parentNumberBase, number+1); } return ""; }
void SongSearch::getSearchSites() { searchSites.clear(); QFile file("searchsites.xml"); if(file.open(QIODevice::ReadOnly)) { QDomDocument doc("SearchSites"); doc.setContent(&file); file.close(); QDomElement docElement = doc.documentElement(); QDomNode node = docElement.firstChildElement("Site"); while(!node.isNull()) { SearchSite site; site.songType = node.attributes().namedItem("Type").nodeValue(); if(ui->anyTypeButton->isChecked() || (site.songType == "MIDI" && ui->midiButton->isChecked()) || (site.songType == "UltraStar" && ui->ultraStarButton->isChecked()) ) { site.requestType = node.attributes().namedItem("Request").nodeValue() == "POST" ? HttpHandler::REQUEST_POST : HttpHandler::REQUEST_GET; site.baseUrl = node.attributes().namedItem("BaseUrl").nodeValue(); site.searchUrl = node.attributes().namedItem("SearchUrl").nodeValue(); site.searchForParamNames = node.attributes().namedItem("SearchForParamNames").nodeValue().split(';'); site.searchForParamValues = node.attributes().namedItem("SearchForParamValues").nodeValue().split(';'); site.queryParamName = node.attributes().namedItem("QueryParamName").nodeValue(); site.regExp = node.attributes().namedItem("Regex").nodeValue(); site.resultGroups = node.attributes().namedItem("Groups").nodeValue().split(';'); site.additionalParams = node.attributes().namedItem("AdditionalParams").nodeValue().split(';'); searchSites.append(site); } node = node.nextSiblingElement(); } } }
void XmlRelationCheckerCoreImpl::CheckAllRelation(QDomNode nodeToCheck, QList<XmlRelationError*>* errorCollection, const QString& absoluteFileName, const QString& parentNumberBase, int number) const { if(!nodeToCheck.isNull()) { if(nodeToCheck.isElement() && !nodeToCheck.isComment()) { //Calcolate the hierarchical number QString completeIdentifiersNumber = parentNumberBase; //If it's not empty is because it's the first node and it needn't the dot seprator if(!parentNumberBase.isEmpty()) { completeIdentifiersNumber.append('.'); } //Attach the number completeIdentifiersNumber.append(QString::number(number)); //For debug //const QString& nodeName = nodeToCheck.nodeName(); //For every xml relations for(int i=0; i < m_pXmlRelationCollection->Size(); ++i) { //Current analized xml relation XmlRelation* xmlRelation = new XmlRelation(*m_pXmlRelationCollection->GetRelationAt(i)); //If the relation is a SUB_TAG relation if(xmlRelation->GetRelationType() == SUB_TAG) { //It would be better if it's mantained a list of the finded tag to in order to avoid the research of //the tag from of this tag //It's not inplemented because even without thid optimization it's fast enough //If the current tag is a node from for the current relation then check for the existence of the node to //The current tag is a nofe from is the list of the key contained is at least 1 QList<QString>* keyFound = CheckIsNodeFrom(nodeToCheck, xmlRelation); if(keyFound->size() > 0) { //For each key for(int k=0; k < keyFound->size(); ++k) { bool referenceFound = false; //Search in all the files the referenced node to for(int j=0; j < m_xmlDocumentsList->size() && !referenceFound; ++j) { const QDomNode& rootNode = m_xmlDocumentsList->at(j)->GetQDomDocument()->firstChildElement(); //Search if this reference is valid referenceFound = referenceFound || ! SearchGivenNodeTo(rootNode, keyFound->at(k), xmlRelation, "", 1).isEmpty(); } //If the reference not exist add an error if(!referenceFound) { XmlRelationError* xmlRelationError = new XmlRelationError(absoluteFileName, xmlRelation, completeIdentifiersNumber, keyFound->at(k), XML_RELATION_ERROR_TYPE_REFERENCED_NOT_FOUND); //Add the error in the list errorCollection->append(xmlRelationError); } } } delete keyFound; //If the current tag is a node to for the current relation then check for the existence of the node to const QString& tagToKey = CheckIsNodeTo(nodeToCheck, xmlRelation); if(tagToKey != "") //then is a node to { bool referenceFound = false; //Search in all the files the referencer node from for(int j=0; j < m_xmlDocumentsList->size() && !referenceFound; ++j) { const QDomNode& rootNode = m_xmlDocumentsList->at(j)->GetQDomDocument()->firstChildElement(); //Search if this reference is valid referenceFound = referenceFound || SearchGivenNodeFrom(rootNode, tagToKey, xmlRelation); } //If the reference not exist add an error if(!referenceFound) { XmlRelationError* xmlRelationError = new XmlRelationError(absoluteFileName, xmlRelation, completeIdentifiersNumber, tagToKey, XML_RELATION_ERROR_TYPE_REFERENCED_NEVER_REFERENCED); //Add the error in the list errorCollection->append(xmlRelationError); } } } } //Recursive call that ensure to explore all the document element CheckAllRelation(nodeToCheck.firstChildElement(), errorCollection, absoluteFileName, completeIdentifiersNumber, 1); } //Recursive call that ensure to explore all the document element CheckAllRelation(nodeToCheck.nextSiblingElement(), errorCollection, absoluteFileName, parentNumberBase, number+1); } }
bool FilterOutputOpticalFlowPlugin::loadRasterList( QString &mlpFilename, QList<OOCRaster> &rasters ) { QFile qf(mlpFilename); QFileInfo qfInfo(mlpFilename); QDir tmpDir = QDir::current(); QDir::setCurrent(qfInfo.absoluteDir().absolutePath()); if( !qf.open(QIODevice::ReadOnly ) ) return false; QString project_path = qfInfo.absoluteFilePath(); QDomDocument doc("MeshLabDocument"); //It represents the XML document if(!doc.setContent( &qf )) return false; QDomElement root = doc.documentElement(); QDomNode node; node = root.firstChild(); //Devices while( !node.isNull() ) { if(QString::compare(node.nodeName(),"RasterGroup")==0) { QDomNode raster; QString filen, label; raster = node.firstChild(); while(!raster.isNull()) { QString imgFile; QDomElement el = raster.firstChildElement("Plane"); while(!el.isNull()) { QString sem = el.attribute("semantic"); if( sem == "RGB" ) { QString filen = el.attribute("fileName"); QFileInfo fi(filen); imgFile = fi.absoluteFilePath(); } el = node.nextSiblingElement("Plane"); } if( !imgFile.isNull() ) { QDomNode sh=raster.firstChild(); vcg::Shotf shot; ReadShotFromQDomNode( shot, sh ); rasters.push_back( OOCRaster(imgFile,shot,rasters.size()) ); } raster=raster.nextSibling(); } } node = node.nextSibling(); } QDir::setCurrent(tmpDir.absolutePath()); qf.close(); return true; }
Pattern* LocalFileMng::loadPattern( const QString& directory ) { InstrumentList* instrList = Hydrogen::get_instance()->getSong()->get_instrument_list(); Pattern *pPattern = NULL; QString patternInfoFile = directory; QFile check( patternInfoFile ); if (check.exists() == false) { ERRORLOG( QString("Load Pattern: Data file %1 not found." ).arg( patternInfoFile ) ); return NULL; } QDomDocument doc = LocalFileMng::openXmlDocument( patternInfoFile ); QFile file( patternInfoFile ); // root element QDomNode rootNode = doc.firstChildElement( "drumkit_pattern" ); // root element if ( rootNode.isNull() ) { ERRORLOG( "Error reading Pattern: Pattern_drumkit_infonode not found" ); return NULL; } QDomNode patternNode = rootNode.firstChildElement( "pattern" ); QString sName( LocalFileMng::readXmlString( patternNode,"pattern_name", "" ) ); QString sInfo( LocalFileMng::readXmlString( patternNode,"info", "" ) ); QString sCategory( LocalFileMng::readXmlString( patternNode,"category", "" ) ); int nSize = -1; nSize = LocalFileMng::readXmlInt( patternNode, "size",nSize ,false,false ); pPattern = new Pattern( sName, sInfo, sCategory, nSize ); QDomNode pNoteListNode = patternNode.firstChildElement( "noteList" ); if ( ! pNoteListNode.isNull() ) { // new code :) QDomNode noteNode = pNoteListNode.firstChildElement( "note" ); while ( ! noteNode.isNull() ) { Note* pNote = NULL; unsigned nPosition = LocalFileMng::readXmlInt( noteNode, "position", 0 ); float fLeadLag = LocalFileMng::readXmlFloat( noteNode, "leadlag", 0.0 , false , false); float fVelocity = LocalFileMng::readXmlFloat( noteNode, "velocity", 0.8f ); float fPan_L = LocalFileMng::readXmlFloat( noteNode, "pan_L", 0.5 ); float fPan_R = LocalFileMng::readXmlFloat( noteNode, "pan_R", 0.5 ); int nLength = LocalFileMng::readXmlInt( noteNode, "length", -1, true ); float nPitch = LocalFileMng::readXmlFloat( noteNode, "pitch", 0.0, false, false ); QString sKey = LocalFileMng::readXmlString( noteNode, "key", "C0", false, false ); QString nNoteOff = LocalFileMng::readXmlString( noteNode, "note_off", "false", false, false ); int instrId = LocalFileMng::readXmlInt( noteNode, "instrument", 0, true ); Instrument *instrRef = instrList->find( instrId ); if ( !instrRef ) { ERRORLOG( QString( "Instrument with ID: '%1' not found. Note skipped." ).arg( instrId ) ); noteNode = noteNode.nextSiblingElement( "note" ); continue; } //assert( instrRef ); bool noteoff = false; if ( nNoteOff == "true" ) noteoff = true; pNote = new Note( instrRef, nPosition, fVelocity, fPan_L, fPan_R, nLength, nPitch); pNote->set_key_octave( sKey ); pNote->set_lead_lag(fLeadLag); pNote->set_note_off( noteoff ); pPattern->insert_note( pNote ); noteNode = noteNode.nextSiblingElement( "note" ); } } return pPattern; }
/// /// Load the preferences file /// void Preferences::loadPreferences( bool bGlobal ) { bool recreate = false; // configuration file must be recreated? QString sPreferencesDirectory; QString sPreferencesFilename; QString sDataDirectory; if ( bGlobal ) { sPreferencesDirectory = DataPath::get_data_path(); sPreferencesFilename = sPreferencesDirectory + "/composite.default.conf"; DEBUGLOG( "Loading preferences file (GLOBAL) [" + sPreferencesFilename + "]" ); } else { sPreferencesFilename = m_sPreferencesFilename; sPreferencesDirectory = m_sPreferencesDirectory; sDataDirectory = QDir::homePath().append( "/.composite/data" ); DEBUGLOG( "Loading preferences file (USER) [" + sPreferencesFilename + "]" ); } // preferences directory exists? QDir prefDir( sPreferencesDirectory ); if ( !prefDir.exists() ) { if ( bGlobal ) { WARNINGLOG( "System configuration directory '" + sPreferencesDirectory + "' not found." ); } else { ERRORLOG( "Configuration directory '" + sPreferencesDirectory + "' not found." ); createPreferencesDirectory(); } } // data directory exists? QDir dataDir( sDataDirectory ); if ( !dataDir.exists() ) { WARNINGLOG( "Data directory not found." ); createDataDirectory(); } // soundLibrary directory exists? QString sDir = sDataDirectory; QString sDrumkitDir; QString sSongDir; QString sPatternDir; DEBUGLOG( "Creating soundLibrary directories in " + sDir ); sDrumkitDir = sDir + "/drumkits"; sSongDir = sDir + "/songs"; sPatternDir = sDir + "/patterns"; QDir drumkitDir( sDrumkitDir ); QDir songDir( sSongDir ); QDir patternDir( sPatternDir ); if ( ! drumkitDir.exists() || ! songDir.exists() || ! patternDir.exists() ) { createSoundLibraryDirectories(); } // pref file exists? std::ifstream input( sPreferencesFilename.toLocal8Bit() , std::ios::in | std::ios::binary ); if ( input ) { // read preferences file QDomDocument doc = LocalFileMng::openXmlDocument( sPreferencesFilename ); QDomNode rootNode = doc.firstChildElement( "hydrogen_preferences" ); if ( !rootNode.isNull() ) { // version QString version = LocalFileMng::readXmlString( rootNode, "version", "" ); if ( version.isEmpty() ) { recreate = true; } //////// GENERAL /////////// //m_sLadspaPath = LocalFileMng::readXmlString( this, rootNode, "ladspaPath", m_sLadspaPath ); m_bShowDevelWarning = LocalFileMng::readXmlBool( rootNode, "showDevelWarning", m_bShowDevelWarning ); restoreLastSong = LocalFileMng::readXmlBool( rootNode, "restoreLastSong", restoreLastSong ); m_bPatternModePlaysSelected = LocalFileMng::readXmlBool( rootNode, "patternModePlaysSelected", TRUE ); hearNewNotes = LocalFileMng::readXmlBool( rootNode, "hearNewNotes", hearNewNotes ); recordEvents = LocalFileMng::readXmlBool( rootNode, "recordEvents", recordEvents ); quantizeEvents = LocalFileMng::readXmlBool( rootNode, "quantizeEvents", quantizeEvents ); QDomNode pRecentUsedSongsNode = rootNode.firstChildElement( "recentUsedSongs" ); if ( !pRecentUsedSongsNode.isNull() ) { QDomElement pSongElement = pRecentUsedSongsNode.firstChildElement( "song" ); while( !pSongElement.isNull() && !pSongElement.text().isEmpty() ){ m_recentFiles.push_back( pSongElement.text() ); pSongElement = pSongElement.nextSiblingElement( "song" ); } } else { DEBUGLOG( "recentUsedSongs node not found" ); } QDomNode pRecentFXNode = rootNode.firstChildElement( "recentlyUsedEffects" ); if ( ! pRecentFXNode.isNull() ) { QDomElement pFXElement = pRecentFXNode.firstChildElement( "FX" ); while ( !pFXElement.isNull() && ! pFXElement.text().isEmpty()) { m_recentFX.push_back( pFXElement.text() ); pFXElement = pFXElement.nextSiblingElement( "FX" ); } } else { DEBUGLOG( "recentlyUsedEffects node not found" ); } sServerList.clear(); QDomNode pServerListNode = rootNode.firstChildElement( "serverList" ); if ( !pServerListNode.isNull() ) { QDomElement pServerElement = pServerListNode.firstChildElement( "server" ); while ( !pServerElement.isNull() && !pServerElement.text().isEmpty() ) { sServerList.push_back( pServerElement.text() ); pServerElement = pServerElement.nextSiblingElement( "server" ); } } else { DEBUGLOG( "serverList node not found" ); } m_patternCategories.clear(); QDomNode pPatternCategoriesNode = rootNode.firstChildElement( "patternCategories" ); if ( !pPatternCategoriesNode.isNull() ) { QDomElement pPatternCategoriesElement = pPatternCategoriesNode.firstChildElement( "categories" ); while ( !pPatternCategoriesElement.isNull() && !pPatternCategoriesElement.text().isEmpty() ) { m_patternCategories.push_back( pPatternCategoriesElement.text() ); pPatternCategoriesElement = pPatternCategoriesElement.nextSiblingElement( "categories" ); } } else { DEBUGLOG( "patternCategories node not found" ); } m_sLastNews = LocalFileMng::readXmlString( rootNode, "lastNews", "-", true ); /////////////// AUDIO ENGINE ////////////// QDomNode audioEngineNode = rootNode.firstChildElement( "audio_engine" ); if ( audioEngineNode.isNull() ) { DEBUGLOG( "audio_engine node not found" ); recreate = true; } else { m_sAudioDriver = LocalFileMng::readXmlString( audioEngineNode, "audio_driver", m_sAudioDriver ); m_bUseMetronome = LocalFileMng::readXmlBool( audioEngineNode, "use_metronome", m_bUseMetronome ); m_fMetronomeVolume = LocalFileMng::readXmlFloat( audioEngineNode, "metronome_volume", 0.5f ); m_nMaxNotes = LocalFileMng::readXmlInt( audioEngineNode, "maxNotes", m_nMaxNotes ); m_nBufferSize = LocalFileMng::readXmlInt( audioEngineNode, "buffer_size", m_nBufferSize ); m_nSampleRate = LocalFileMng::readXmlInt( audioEngineNode, "samplerate", m_nSampleRate ); //// JACK DRIVER //// QDomNode jackDriverNode = audioEngineNode.firstChildElement( "jack_driver" ); if ( jackDriverNode.isNull() ) { DEBUGLOG( "jack_driver node not found" ); recreate = true; } else { m_sJackPortName1 = LocalFileMng::readXmlString( jackDriverNode, "jack_port_name_1", m_sJackPortName1 ); m_sJackPortName2 = LocalFileMng::readXmlString( jackDriverNode, "jack_port_name_2", m_sJackPortName2 ); QString sMode = LocalFileMng::readXmlString( jackDriverNode, "jack_transport_mode", "NO_JACK_TRANSPORT" ); if ( sMode == "NO_JACK_TRANSPORT" ) { m_bJackTransportMode = NO_JACK_TRANSPORT; } else if ( sMode == "USE_JACK_TRANSPORT" ) { m_bJackTransportMode = USE_JACK_TRANSPORT; } //jack time master QString tmMode = LocalFileMng::readXmlString( jackDriverNode, "jack_transport_mode_master", "NO_JACK_TIME_MASTER" ); if ( tmMode == "NO_JACK_TIME_MASTER" ) { m_bJackMasterMode = NO_JACK_TIME_MASTER; } else if ( tmMode == "USE_JACK_TIME_MASTER" ) { m_bJackMasterMode = USE_JACK_TIME_MASTER; } //~ jack time master m_bJackTrackOuts = LocalFileMng::readXmlBool( jackDriverNode, "jack_track_outs", m_bJackTrackOuts ); m_bJackConnectDefaults = LocalFileMng::readXmlBool( jackDriverNode, "jack_connect_defaults", m_bJackConnectDefaults ); m_nJackTrackOutputMode = LocalFileMng::readXmlInt( jackDriverNode, "jack_track_output_mode", m_nJackTrackOutputMode ); } /// MIDI DRIVER /// QDomNode midiDriverNode = audioEngineNode.firstChildElement( "midi_driver" ); if ( midiDriverNode.isNull() ) { DEBUGLOG( "midi_driver node not found" ); recreate = true; } else { m_sMidiDriver = LocalFileMng::readXmlString( midiDriverNode, "driverName", "JackMidi" ); m_sMidiPortName = LocalFileMng::readXmlString( midiDriverNode, "port_name", "None" ); m_nMidiChannelFilter = LocalFileMng::readXmlInt( midiDriverNode, "channel_filter", -1 ); m_bMidiNoteOffIgnore = LocalFileMng::readXmlBool( midiDriverNode, "ignore_note_off", true ); } } /////////////// GUI ////////////// QDomNode guiNode = rootNode.firstChildElement( "gui" ); if ( guiNode.isNull() ) { DEBUGLOG( "gui node not found" ); recreate = true; } else { // QT Style m_sQTStyle = LocalFileMng::readXmlString( guiNode, "QTStyle", m_sQTStyle, true ); // Application font family applicationFontFamily = LocalFileMng::readXmlString( guiNode, "application_font_family", applicationFontFamily ); // Application font pointSize applicationFontPointSize = LocalFileMng::readXmlInt( guiNode, "application_font_pointsize", applicationFontPointSize ); // mixer font family mixerFontFamily = LocalFileMng::readXmlString( guiNode, "mixer_font_family", mixerFontFamily ); // mixer font pointSize mixerFontPointSize = LocalFileMng::readXmlInt( guiNode, "mixer_font_pointsize", mixerFontPointSize ); // Mixer falloff speed mixerFalloffSpeed = LocalFileMng::readXmlFloat( guiNode, "mixer_falloff_speed", 1.1f ); // pattern editor grid resolution m_nPatternEditorGridResolution = LocalFileMng::readXmlInt( guiNode, "patternEditorGridResolution", m_nPatternEditorGridResolution ); m_bPatternEditorUsingTriplets = LocalFileMng::readXmlBool( guiNode, "patternEditorUsingTriplets", m_bPatternEditorUsingTriplets ); m_bShowInstrumentPeaks = LocalFileMng::readXmlBool( guiNode, "showInstrumentPeaks", m_bShowInstrumentPeaks ); m_bIsFXTabVisible = LocalFileMng::readXmlBool( guiNode, "isFXTabVisible", m_bIsFXTabVisible ); // pattern editor grid height m_nPatternEditorGridHeight = LocalFileMng::readXmlInt( guiNode, "patternEditorGridHeight", m_nPatternEditorGridHeight ); // pattern editor grid width m_nPatternEditorGridWidth = LocalFileMng::readXmlInt( guiNode, "patternEditorGridWidth", m_nPatternEditorGridWidth ); // mainForm window properties setMainFormProperties( readWindowProperties( guiNode, "mainForm_properties", mainFormProperties ) ); setMixerProperties( readWindowProperties( guiNode, "mixer_properties", mixerProperties ) ); setPatternEditorProperties( readWindowProperties( guiNode, "patternEditor_properties", patternEditorProperties ) ); setSongEditorProperties( readWindowProperties( guiNode, "songEditor_properties", songEditorProperties ) ); setAudioEngineInfoProperties( readWindowProperties( guiNode, "audioEngineInfo_properties", audioEngineInfoProperties ) ); m_bFollowPlayhead = LocalFileMng::readXmlBool( guiNode, "followPlayhead", true ); //beatcounter QString bcMode = LocalFileMng::readXmlString( guiNode, "bc", "BC_OFF" ); if ( bcMode == "BC_OFF" ) { m_bbc = BC_OFF; } else if ( bcMode == "BC_ON" ) { m_bbc = BC_ON; } QString setPlay = LocalFileMng::readXmlString( guiNode, "setplay", "SET_PLAY_OFF" ); if ( setPlay == "SET_PLAY_OFF" ) { m_mmcsetplay = SET_PLAY_OFF; } else if ( setPlay == "SET_PLAY_ON" ) { m_mmcsetplay = SET_PLAY_ON; } m_countOffset = LocalFileMng::readXmlInt( guiNode, "countoffset", 0 ); m_startOffset = LocalFileMng::readXmlInt( guiNode, "playoffset", 0 ); //~ beatcounter //SoundLibraryPanel expand items __expandSongItem = LocalFileMng::readXmlBool( guiNode, "expandSongItem", __expandSongItem ); __expandPatternItem = LocalFileMng::readXmlBool( guiNode, "expandPatternItem", __expandPatternItem ); for ( unsigned nFX = 0; nFX < MAX_FX; nFX++ ) { QString sNodeName = QString("ladspaFX_properties%1").arg( nFX ); setLadspaProperties( nFX, readWindowProperties( guiNode, sNodeName, m_ladspaProperties[nFX] ) ); } QDomNode pUIStyle = guiNode.firstChildElement( "UI_Style" ); if ( !pUIStyle.isNull() ) { readUIStyle( pUIStyle ); } else { DEBUGLOG( "UI_Style node not found" ); recreate = true; } } /////////////// FILES ////////////// QDomNode filesNode = rootNode.firstChildElement( "files" ); if ( filesNode.isNull() ) { DEBUGLOG( "files node not found" ); recreate = true; } else { // last used song lastSongFilename = LocalFileMng::readXmlString( filesNode, "lastSongFilename", lastSongFilename, true ); m_sDefaultEditor = LocalFileMng::readXmlString( filesNode, "defaulteditor", m_sDefaultEditor, true ); } MidiMap* mM = get_midi_map(); mM->reset(); QDomNode pMidiEventMapNode = rootNode.firstChildElement( "midiEventMap" ); if ( !pMidiEventMapNode.isNull() ) { QDomNode pMidiEventNode = pMidiEventMapNode.firstChildElement( "midiEvent" ); while ( !pMidiEventNode.isNull() ) { if( pMidiEventNode.firstChildElement().nodeValue() == QString("mmcEvent")){ QString event = pMidiEventNode.firstChildElement("mmcEvent").firstChildElement().nodeValue(); QString s_action = pMidiEventNode.firstChildElement("action").firstChildElement().nodeValue(); QString s_param = pMidiEventNode.firstChildElement("parameter").firstChildElement().nodeValue(); Action* pAction = new Action( s_action ); pAction->setParameter1( s_param ); mM->registerMMCEvent(event, pAction); } if( pMidiEventNode.firstChildElement().nodeValue() == QString("noteEvent")){ QString event = pMidiEventNode.firstChildElement("noteEvent").firstChildElement().nodeValue(); QString s_action = pMidiEventNode.firstChildElement("action").firstChildElement().nodeValue(); QString s_param = pMidiEventNode.firstChildElement("parameter").firstChildElement().nodeValue(); QString s_eventParameter = pMidiEventNode.firstChildElement("eventParameter").firstChildElement().nodeValue(); Action* pAction = new Action( s_action ); pAction->setParameter1( s_param ); mM->registerNoteEvent(s_eventParameter.toInt(), pAction); } if( pMidiEventNode.firstChildElement().nodeValue() == QString("ccEvent") ){ QString event = pMidiEventNode.firstChildElement("ccEvent").firstChildElement().nodeValue(); QString s_action = pMidiEventNode.firstChildElement("action").firstChildElement().nodeValue(); QString s_param = pMidiEventNode.firstChildElement("parameter").firstChildElement().nodeValue(); QString s_eventParameter = pMidiEventNode.firstChildElement("eventParameter").firstChildElement().nodeValue(); Action * pAction = new Action( s_action ); pAction->setParameter1( s_param ); mM->registerCCEvent( s_eventParameter.toInt(), pAction ); } pMidiEventNode = pMidiEventNode.nextSiblingElement( "midiEvent" ); } } else { DEBUGLOG( "midiMap node not found" ); } } // rootNode else { DEBUGLOG( "hydrogen_preferences node not found" ); recreate = true; } } else { if ( bGlobal ) { WARNINGLOG( "System configuration file not found." ); } else { WARNINGLOG( "Configuration file not found." ); recreate = true; } } // The preferences file should be recreated? if ( recreate == true ) { WARNINGLOG( "Recreating configuration file." ); savePreferences(); } }
/*! This function re-reads the Packages.xml file and updates itself. Changes to \ref targetName and \ref targetVersion are lost after this function returns. The function emits a reset() signal after completion. */ void PackagesInfo::refresh() { // First clear internal variables d->targetName.clear(); d->targetVersion.clear(); d->packageInfoList.clear(); d->modified = false; QFile file( d->fileName ); // if the file does not exist then we just skip the reading if( !file.exists() ) { d->error = NoError; d->errorMessage.clear(); emit reset(); return; } // Open Packages.xml if( !file.open(QFile::ReadOnly) ) { d->error = CouldNotReadPackageFileError; d->errorMessage = tr("Could not read \"%1\"").arg(d->fileName); emit reset(); return; } // Parse the XML document QDomDocument doc; QString parseErrorMessage; int parseErrorLine; int parseErrorColumn; if( !doc.setContent( &file, &parseErrorMessage, &parseErrorLine, &parseErrorColumn ) ) { d->error = InvalidXmlError; d->errorMessage = tr("Parse error in %1 at %2, %3: %4") .arg(d->fileName, QString::number(parseErrorLine), QString::number(parseErrorColumn), parseErrorMessage); emit reset(); return; } file.close(); // Now populate information from the XML file. const QDomElement rootE = doc.documentElement(); if( rootE.tagName() != QLatin1String( "Packages" ) ) { d->setInvalidContentError(tr("root element %1 unexpected, should be \"Packages\"").arg(rootE.tagName())); emit reset(); return; } for( QDomNode childNode = rootE.firstChild(); !childNode.isNull(); childNode = childNode.nextSiblingElement() ) { const QDomElement childNodeE = childNode.toElement(); if( childNodeE.isNull() ) continue; if ( childNodeE.tagName() == QLatin1String( "TargetName" ) || childNodeE.tagName() == QLatin1String( "ApplicationName" ) ) // backwards compat d->targetName = childNodeE.text(); else if ( childNodeE.tagName() == QLatin1String( "TargetVersion" ) || childNodeE.tagName() == QLatin1String( "ApplicationVersion" ) ) d->targetVersion = childNodeE.text(); else if( childNodeE.tagName() == QLatin1String( "Package" ) ) d->addPackageFrom( childNodeE ); else if( childNodeE.tagName() == QLatin1String( "CompatLevel" ) ) d->compatLevel = childNodeE.text().toInt(); } d->error = NoError; d->errorMessage.clear(); emit reset(); }
SBGNGlyph::SBGNGlyph(QDomNode node) : m_shape(NULL), m_orient(HORIZ) { QDomNamedNodeMap attrs = node.attributes(); m_id = attrs.namedItem("id").toAttr().value(); m_class = attrs.namedItem("class").toAttr().value(); // Get orientation, if defined. QDomNode orient = attrs.namedItem("orientation"); if (!orient.isNull()) { QString ostr = orient.toAttr().value(); if (ostr == "vertical") { m_orient = VERT; } else if (ostr == "horizontal") { m_orient = HORIZ; } } // Get any ports that may be defined. QDomNode port = node.namedItem("port"); while (!port.isNull()) { addPort(port); port = port.nextSiblingElement("port"); } // Label QDomNode label = node.namedItem("label"); if (!label.isNull()) { QDomNamedNodeMap labelAttrs = label.attributes(); m_labelText = labelAttrs.namedItem("text").toAttr().value(); // Get bbox of label, if it is specified. if (label.hasChildNodes()) { QDomNode labelBboxNode = label.namedItem("bbox"); if (!labelBboxNode.isNull()) { QDomNamedNodeMap lbboxAttrs = labelBboxNode.attributes(); float x = lbboxAttrs.namedItem("x").toAttr().value().toFloat(); float y = lbboxAttrs.namedItem("y").toAttr().value().toFloat(); float w = lbboxAttrs.namedItem("w").toAttr().value().toFloat(); float h = lbboxAttrs.namedItem("h").toAttr().value().toFloat(); m_labelBbox = QRectF(x,y,w,h); } } } // Is it marked as a clone? QDomNode cloneMarker = node.namedItem("clone"); m_isCloned = !cloneMarker.isNull(); // Bbox of node QDomNode bbox = node.namedItem("bbox"); QDomNamedNodeMap bboxAttrs = bbox.attributes(); float x = bboxAttrs.namedItem("x").toAttr().value().toFloat(); float y = bboxAttrs.namedItem("y").toAttr().value().toFloat(); float w = bboxAttrs.namedItem("w").toAttr().value().toFloat(); float h = bboxAttrs.namedItem("h").toAttr().value().toFloat(); m_Bbox = QRectF(x,y,w,h); // Make the shape. makeShape(); }
Project::Project(QString projectPath) : projectPath_(projectPath) { if(projectPath.isNull()) return; auto &schema = getSchema(); auto &validator = getValidator(); if(!schema.isValid()) { QFile schemaFile(SCHEMA_PATH); if(schemaFile.open(QFile::ReadOnly) && schema.load(&schemaFile)) validator.setSchema(schema); } // First make sure the XML is valid w.r.t. our schema if(!validator.validate(QUrl::fromLocalFile(projectPath))) throw std::runtime_error("Failed to validate"); // Load the file into a DOM model QDomDocument doc; QFile xmlFile(projectPath); if(!xmlFile.open(QFile::ReadOnly)) throw std::runtime_error("Failed to open file"); if(!doc.setContent(&xmlFile)) { xmlFile.close(); throw std::runtime_error("Failed to set XML content"); } xmlFile.close(); cameras_.clear(); imageSets_.clear(); // // Cameras // qDebug() << "Loading cameras..."; QDomNode camerasNode = doc.documentElement().firstChildElement("cameras"); QDomNode cameraNode = camerasNode.firstChildElement("camera"); while(!cameraNode.isNull()) { CameraPtr cam(new Camera(getAttribute(cameraNode, "id"))); cam->setName(getAttribute(cameraNode, "name", cam->id())); // The projection matrix node is required, so no need to check for null QDomNode projectionMatrixNode = cameraNode.firstChildElement("projectionMatrix"); if(!projectionMatrixNode.isNull()) { ProjMat P; P << getAttribute(projectionMatrixNode, "m11").toDouble(), getAttribute(projectionMatrixNode, "m12").toDouble(), getAttribute(projectionMatrixNode, "m13").toDouble(), getAttribute(projectionMatrixNode, "m14").toDouble(), getAttribute(projectionMatrixNode, "m21").toDouble(), getAttribute(projectionMatrixNode, "m22").toDouble(), getAttribute(projectionMatrixNode, "m23").toDouble(), getAttribute(projectionMatrixNode, "m24").toDouble(), getAttribute(projectionMatrixNode, "m31").toDouble(), getAttribute(projectionMatrixNode, "m32").toDouble(), getAttribute(projectionMatrixNode, "m33").toDouble(), getAttribute(projectionMatrixNode, "m34").toDouble(); cam->setP(P); } // QDomNode lensDistortionNode = cameraNode.firstChildElement("lensDistortion"); if(!lensDistortionNode.isNull()) { LensDistortions dist; dist[0] = getAttribute(lensDistortionNode, "k1", "0").toDouble(); dist[1] = getAttribute(lensDistortionNode, "k2", "0").toDouble(); dist[2] = getAttribute(lensDistortionNode, "p1", "0").toDouble(); dist[3] = getAttribute(lensDistortionNode, "p2", "0").toDouble(); dist[4] = getAttribute(lensDistortionNode, "k3", "0").toDouble(); cam->setLensDistortion(dist); } // QDomNode responseNode = cameraNode.firstChildElement("response"); Responses responses(256, Response::Zero()); while(!responseNode.isNull()) { QString channelName = getAttribute(responseNode, "channel", QString()); if(!channelName.isNull()) { int channel = -1; if(channelName == "red") channel = 0; else if(channelName == "green") channel = 1; else if(channelName == "blue") channel = 2; if(channel >= 0) { QDomNode valueNode = responseNode.firstChild(); for(int index = 0; index < 256; ++index, valueNode = valueNode.nextSibling()) responses[index][channel] = valueNode.firstChild().toText().data().toDouble(); } } responseNode = responseNode.nextSiblingElement("response"); } cam->setResponse(responses); // QDomNode refractiveNode = cameraNode.firstChildElement("refractiveInterface"); if(!refractiveNode.isNull()) { double px = getAttribute(refractiveNode, "px", "0.0").toDouble(); double py = getAttribute(refractiveNode, "py", "0.0").toDouble(); double dist = getAttribute(refractiveNode, "dist", "0.0").toDouble(); cam->setRefractiveIndex(getAttribute(refractiveNode, "refractiveRatio", "1.0").toDouble()); cam->setPlane(Plane3d(cam->K().inverse() * Vector3d(px, py, 1), dist)); } // cameras_[cam->id()] = cam; cameraNode = cameraNode.nextSiblingElement("camera"); } // // Image sets // qDebug() << "Loading image sets..."; QDomNode imageSetsNode = doc.documentElement().firstChildElement("imageSets"); QDomNode imageSetNode = imageSetsNode.firstChildElement("imageSet"); while(!imageSetNode.isNull()) { ImageSetPtr imageSet(new ImageSet(getAttribute(imageSetNode, "id"))); imageSet->setName(getAttribute(imageSetNode, "name", imageSet->id())); QDir root(projectPath); root.cdUp(); if(hasAttribute(imageSetNode, "root")) { QString rootStr = getAttribute(imageSetNode, "root"); if(QDir::isRelativePath(rootStr)) root.cd(rootStr); else root.setPath(rootStr); } imageSet->setRoot(root); // Images QDomNode imageNode = imageSetNode.firstChild(); while(!imageNode.isNull()) { ProjectImagePtr image(new ProjectImage(imageSet->root().absoluteFilePath(getAttribute(imageNode, "file")))); image->setExposure(getAttribute(imageNode, "exposure", "-1.0").toDouble()); if(cameras_.contains(getAttribute(imageNode, "for"))) imageSet->addImageForCamera(cameras_[getAttribute(imageNode, "for")], image); imageNode = imageNode.nextSibling(); } // if(imageSet->images().size() > 0) imageSets_[imageSet->id()] = imageSet; imageSetNode = imageSetNode.nextSiblingElement("imageSet"); } // // Features // qDebug() << "Loading features..."; std::map<ProjectImagePtr, std::map<int, FeaturePtr> > featureMap; QDomNode featureSetsNode = doc.documentElement().firstChildElement("featureSets"); QDomNode featureSetNode = featureSetsNode.firstChildElement("featureSet"); while(!featureSetNode.isNull()) { // CameraPtr cam = cameras_[getAttribute(featureSetNode, "camera")]; ImageSetPtr imageSet = imageSets_[getAttribute(featureSetNode, "imageSet")]; ProjectImagePtr image; if(cam && imageSet) image = imageSet->defaultImageForCamera(cam); // if(image) { Features features; QDomElement featureNode = featureSetNode.firstChildElement("feature"); while(!featureNode.isNull()) { QString type = getAttribute(featureNode, "type"); FeaturePtr feature; if(type.compare("surf", Qt::CaseInsensitive) == 0) { feature = SurfDetector::load(featureNode); } else if(type.compare("checkerboard", Qt::CaseInsensitive) == 0) { feature = CheckerboardDetector::load(featureNode); } // Index mapping is necessary for establishing correspondence // relationships later int index = getAttribute(featureNode, "index").toInt(); featureMap[image][index] = feature; // features.push_back(feature); featureNode = featureNode.nextSiblingElement("feature"); } CameraPtr cam = cameras_[getAttribute(featureSetNode, "camera")]; ImageSetPtr imageSet = imageSets_[getAttribute(featureSetNode, "imageSet")]; ProjectImagePtr image = imageSet->defaultImageForCamera(cam); // if(features.size() > 0) featuresDB_.features(image).swap(features); } // featureSetNode = featureSetNode.nextSiblingElement("featureSet"); } // // Correspondences // qDebug() << "Loading correspondences..."; QDomNode correspondenceSetsNode = doc.documentElement().firstChildElement("correspondenceSets"); QDomNode correspondenceSetNode = correspondenceSetsNode.firstChildElement("correspondenceSet"); Correspondences correspondences; while(!correspondenceSetNode.isNull()) { // CameraPtr cam1 = cameras_[getAttribute(correspondenceSetNode, "camera1")]; CameraPtr cam2 = cameras_[getAttribute(correspondenceSetNode, "camera2")]; ImageSetPtr imageSet1 = imageSets_[getAttribute(correspondenceSetNode, "imageSet1")]; ImageSetPtr imageSet2 = imageSets_[getAttribute(correspondenceSetNode, "imageSet2")]; ProjectImagePtr image1, image2; if(cam1 && imageSet1) image1 = imageSet1->defaultImageForCamera(cam1); if(cam2 && imageSet2) image2 = imageSet2->defaultImageForCamera(cam2); // if(image1 && image2) { correspondences.clear(); correspondences.reserve(correspondenceSetNode.childNodes().size()); QDomElement correspondenceNode = correspondenceSetNode.firstChildElement("correspondence"); while(!correspondenceNode.isNull()) { int index1 = getAttribute(correspondenceNode, "index1", "-1").toInt(); int index2 = getAttribute(correspondenceNode, "index2", "-1").toInt(); if(index1 >= 0 && index2 >= 0) { FeaturePtr feature1 = featureMap[image1][index1]; FeaturePtr feature2 = featureMap[image2][index2]; if(feature1 && feature2) correspondences.push_back( Correspondence(feature1, feature2) ); } correspondenceNode = correspondenceNode.nextSiblingElement("correspondence"); } if(correspondences.size() > 0) featuresDB_.correspondences(image1, image2).swap(correspondences); } correspondenceSetNode = correspondenceSetNode.nextSiblingElement("correspondenceSet"); } }
bool EpochIO::open(const QString &formatName, const QString &fileName, MeshModel &m, int& mask,const RichParameterSet & /*par*/, CallBackPos *cb, QWidget *parent) { EpochReconstruction er; mask = vcg::tri::io::Mask::IOM_VERTCOLOR | vcg::tri::io::Mask::IOM_VERTQUALITY; // just to be sure... if (fileName.isEmpty()) return false; // initializing progress bar status if (cb != NULL) (*cb)(0, "Loading..."); // this change of dir is needed for subsequent texture/material loading QString FileNameDir = fileName.left(fileName.lastIndexOf("/")); QDir::setCurrent(FileNameDir); QString errorMsgFormat = "Error encountered while loading file %1:\n%2"; string stdfilename = QFile::encodeName(fileName).constData (); //string filename = fileName.toUtf8().data(); QDomDocument doc; if(formatName.toUpper() == tr("V3D") && fileName.endsWith(".v3d")) { QFile file(fileName); if (file.open(QIODevice::ReadOnly) && doc.setContent(&file)) { file.close(); QDomElement root = doc.documentElement(); if (root.nodeName() == tr("reconstruction")) { QDomNode nhead = root.firstChildElement("head"); for(QDomNode n = nhead.firstChildElement("meta"); !n.isNull(); n = n.nextSiblingElement("meta")) { if(!n.hasAttributes()) return false; QDomNamedNodeMap attr= n.attributes(); if(attr.contains("name")) er.name = (attr.namedItem("name")).nodeValue() ; if(attr.contains("author")) er.author = (attr.namedItem("author")).nodeValue() ; if(attr.contains("created")) er.created = (attr.namedItem("created")).nodeValue() ; } for(QDomNode n = root.firstChildElement("model"); !n.isNull(); n = n.nextSiblingElement("model")) { EpochModel em; em.Init(n); er.modelList.push_back(em); } } } } epochDialog->setEpochReconstruction( &er, cb); do { epochDialog->exportToPLY=false; //Here we invoke the modal dialog and wait for its termination int continueValue = epochDialog->exec(); // The user has pressed the ok button: now start the real processing: if(epochDialog->exportToPLY == true) qDebug("Starting the ply exporting process"); int t0=clock(); logFP=fopen("epoch.log","w"); int subSampleVal = epochDialog->subsampleSpinBox->value(); int minCountVal= epochDialog->minCountSpinBox->value(); float maxCCDiagVal= epochDialog->maxCCDiagSpinBox->value(); int mergeResolution=epochDialog->mergeResolutionSpinBox->value(); int smoothSteps=epochDialog->smoothSpinBox->value(); bool closeHole = epochDialog->holeCheckBox->isChecked(); int maxHoleSize = epochDialog->holeSpinBox->value(); if (continueValue == QDialog::Rejected) { QMessageBox::warning(parent, "Open V3d format","Aborted"); return false; } CMeshO mm; QTableWidget *qtw=epochDialog->imageTableWidget; float MinAngleCos=cos(vcg::math::ToRad(epochDialog->qualitySpinBox->value())); bool clustering=epochDialog->fastMergeCheckBox->isChecked(); bool removeSmallCC=epochDialog->removeSmallCCCheckBox->isChecked(); vcg::tri::Clustering<CMeshO, vcg::tri::AverageColorCell<CMeshO> > Grid; int selectedNum=0,selectedCount=0; int i; for(i=0;i<qtw->rowCount();++i) if(qtw->isItemSelected(qtw->item(i,0))) ++selectedNum; if(selectedNum==0) { QMessageBox::warning(parent, "Open V3d format","No range map selected. Nothing loaded"); return false; } bool dilationFlag = epochDialog->dilationCheckBox->isChecked(); int dilationN = epochDialog->dilationNumPassSpinBox->value(); int dilationSz = epochDialog->dilationSizeSlider->value() * 2 + 1; bool erosionFlag = epochDialog->erosionCheckBox->isChecked(); int erosionN = epochDialog->erosionNumPassSpinBox->value(); int erosionSz = epochDialog->erosionSizeSlider->value() * 2 + 1; float scalingFactor = epochDialog->scaleLineEdit->text().toFloat(); std::vector<string> savedMeshVector; bool firstTime=true; QList<EpochModel>::iterator li; for(li=er.modelList.begin(), i=0;li!=er.modelList.end();++li,++i) { if(qtw->isItemSelected(qtw->item(i,0))) { ++selectedCount; mm.Clear(); int tt0=clock(); (*li).BuildMesh(mm,subSampleVal,minCountVal,MinAngleCos,smoothSteps, dilationFlag, dilationN, dilationSz, erosionFlag, erosionN, erosionSz,scalingFactor); int tt1=clock(); if(logFP) fprintf(logFP,"** Mesh %i : Build in %i\n",selectedCount,tt1-tt0); if(epochDialog->exportToPLY) { QString plyFilename =(*li).textureName.left((*li).textureName.length()-4); plyFilename.append(".x.ply"); savedMeshVector.push_back(qPrintable(plyFilename)); int mask= tri::io::Mask::IOM_VERTCOORD + tri::io::Mask::IOM_VERTCOLOR + tri::io::Mask::IOM_VERTQUALITY; tri::io::ExporterPLY<CMeshO>::Save(mm,qPrintable(plyFilename),mask); } else { if(clustering) { if (firstTime) { //Grid.Init(mm.bbox,100000); vcg::tri::UpdateBounding<CMeshO>::Box(mm); //Grid.Init(mm.bbox,1000.0*pow(10.0,mergeResolution),mm.bbox.Diag()/1000.0f); Grid.Init(mm.bbox,100000.0*pow(10.0,mergeResolution)); firstTime=false; } Grid.AddMesh(mm); } else tri::Append<CMeshO,CMeshO>::Mesh(m.cm,mm); // append mesh mr to ml } int tt2=clock(); if(logFP) fprintf(logFP,"** Mesh %i : Append in %i\n",selectedCount,tt2-tt1); } if (cb)(*cb)(selectedCount*90/selectedNum, "Building meshes"); } if (cb != NULL) (*cb)(90, "Final Processing: clustering"); if(clustering) { Grid.ExtractPointSet(m.cm); } if(epochDialog->exportToPLY) { QString ALNfilename = fileName.left(fileName.length()-4).append(".aln"); ALNParser::SaveALN(qPrintable(ALNfilename), savedMeshVector); } int t1=clock(); if(logFP) fprintf(logFP,"Extracted %i meshes in %i\n",selectedCount,t1-t0); if (cb != NULL) (*cb)(95, "Final Processing: Removing Small Connected Components"); if(removeSmallCC) { vcg::tri::UpdateBounding<CMeshO>::Box(m.cm); // updates bounding box m.updateDataMask(MeshModel::MM_FACEFACETOPO | MeshModel::MM_FACEFLAGBORDER | MeshModel::MM_FACEMARK); tri::Clean<CMeshO>::RemoveSmallConnectedComponentsDiameter(m.cm,m.cm.bbox.Diag()*maxCCDiagVal/100.0); } int t2=clock(); if(logFP) fprintf(logFP,"Topology and removed CC in %i\n",t2-t1); vcg::tri::UpdateBounding<CMeshO>::Box(m.cm); // updates bounding box if (cb != NULL) (*cb)(97, "Final Processing: Closing Holes"); if(closeHole) { m.updateDataMask(MeshModel::MM_FACEFACETOPO | MeshModel::MM_FACEFLAGBORDER | MeshModel::MM_FACEMARK); tri::UpdateNormals<CMeshO>::PerVertexNormalizedPerFace(m.cm); vcg::tri::Hole<CMeshO>::EarCuttingFill<vcg::tri::MinimumWeightEar< CMeshO> >(m.cm,maxHoleSize,false); } if (cb != NULL) (*cb)(100, "Done"); // vcg::tri::UpdateNormals<CMeshO>::PerVertex(m.cm); // updates normals m.updateDataMask(MeshModel::MM_VERTCOLOR); int t3=clock(); if(logFP) fprintf(logFP,"---------- Total Processing Time%i\n\n\n",t3-t0); if(logFP) fclose(logFP); logFP=0; } while(epochDialog->exportToPLY); return true; }
bool HydrogenImport::readSong() { QHash<QString, InstrumentTrack *> drum_track; QHash<QString, int> pattern_length; QHash<QString, int> pattern_id; Song *s = Engine::getSong(); int song_num_tracks = s->tracks().size(); if ( QFile( filename ).exists() == false ) { printf( "Song file not found \n" ); return false; } QDomDocument doc = LocalFileMng::openXmlDocument( filename ); QDomNodeList nodeList = doc.elementsByTagName( "song" ); if( nodeList.isEmpty() ) { printf( "Error reading song: song node not found\n" ); return false; } QDomNode songNode = nodeList.at( 0 ); QString m_sSongVersion = LocalFileMng::readXmlString( songNode , "version", "Unknown version" ); QString sName( LocalFileMng::readXmlString( songNode, "name", "Untitled Song" ) ); QString sAuthor( LocalFileMng::readXmlString( songNode, "author", "Unknown Author" ) ); QString sNotes( LocalFileMng::readXmlString( songNode, "notes", "..." ) ); QString sLicense( LocalFileMng::readXmlString( songNode, "license", "Unknown license" ) ); QString sMode = LocalFileMng::readXmlString( songNode, "mode", "pattern" ); QDomNode instrumentListNode = songNode.firstChildElement( "instrumentList" ); if ( ( ! instrumentListNode.isNull() ) ) { int instrumentList_count = 0; QDomNode instrumentNode; instrumentNode = instrumentListNode.firstChildElement( "instrument" ); while ( ! instrumentNode.isNull() ) { instrumentList_count++; QString sId = LocalFileMng::readXmlString( instrumentNode, "id", "" ); // instrument id QString sDrumkit = LocalFileMng::readXmlString( instrumentNode, "drumkit", "" ); // drumkit QString sName = LocalFileMng::readXmlString( instrumentNode, "name", "" ); // name float fVolume = LocalFileMng::readXmlFloat( instrumentNode, "volume", 1.0 ); // volume float fPan_L = LocalFileMng::readXmlFloat( instrumentNode, "pan_L", 0.5 ); // pan L float fPan_R = LocalFileMng::readXmlFloat( instrumentNode, "pan_R", 0.5 ); // pan R if ( sId.isEmpty() ) { printf( "Empty ID for instrument. skipping \n" ); instrumentNode = (QDomNode) instrumentNode.nextSiblingElement( "instrument" ); continue; } QDomNode filenameNode = instrumentNode.firstChildElement( "filename" ); if ( ! filenameNode.isNull() ) { return false; } else { unsigned nLayer = 0; QDomNode layerNode = instrumentNode.firstChildElement( "layer" ); while ( ! layerNode.isNull() ) { if ( nLayer >= MAX_LAYERS ) { printf( "nLayer >= MAX_LAYERS" ); continue; } QString sFilename = LocalFileMng::readXmlString( layerNode, "filename", "" ); QString sMode = LocalFileMng::readXmlString( layerNode, "smode", "forward" ); if ( nLayer == 0 ) { drum_track[sId] = ( InstrumentTrack * ) Track::create( Track::InstrumentTrack,Engine::getBBTrackContainer() ); drum_track[sId]->volumeModel()->setValue( fVolume * 100 ); drum_track[sId]->panningModel()->setValue( ( fPan_R - fPan_L ) * 100 ); ins = drum_track[sId]->loadInstrument( "audiofileprocessor" ); ins->loadFile( sFilename ); } nLayer++; layerNode = ( QDomNode ) layerNode.nextSiblingElement( "layer" ); } } instrumentNode = (QDomNode) instrumentNode.nextSiblingElement( "instrument" ); } if ( instrumentList_count == 0 ) { return false; } } else { return false; } QDomNode patterns = songNode.firstChildElement( "patternList" ); int pattern_count = 0; int nbb = Engine::getBBTrackContainer()->numOfBBs(); QDomNode patternNode = patterns.firstChildElement( "pattern" ); int pn = 1; while ( !patternNode.isNull() ) { if ( pn > 0 ) { pattern_count++; s->addBBTrack(); pn = 0; } QString sName; // name sName = LocalFileMng::readXmlString( patternNode, "name", sName ); QString sCategory = ""; // category sCategory = LocalFileMng::readXmlString( patternNode, "category", sCategory ,false ,false ); int nSize = -1; nSize = LocalFileMng::readXmlInt( patternNode, "size", nSize, false, false ); pattern_length[sName] = nSize; QDomNode pNoteListNode = patternNode.firstChildElement( "noteList" ); if ( ! pNoteListNode.isNull() ) { QDomNode noteNode = pNoteListNode.firstChildElement( "note" ); while ( ! noteNode.isNull() ) { int nPosition = LocalFileMng::readXmlInt( noteNode, "position", 0 ); float fVelocity = LocalFileMng::readXmlFloat( noteNode, "velocity", 0.8f ); float fPan_L = LocalFileMng::readXmlFloat( noteNode, "pan_L", 0.5 ); float fPan_R = LocalFileMng::readXmlFloat( noteNode, "pan_R", 0.5 ); QString sKey = LocalFileMng::readXmlString( noteNode, "key", "C0", false, false ); QString nNoteOff = LocalFileMng::readXmlString( noteNode, "note_off", "false", false, false ); QString instrId = LocalFileMng::readXmlString( noteNode, "instrument", 0,false, false ); int i = pattern_count - 1 + nbb; pattern_id[sName] = pattern_count - 1; Pattern*p = dynamic_cast<Pattern*>( drum_track[instrId]->getTCO( i ) ); Note n; n.setPos( nPosition ); if ( (nPosition + 48) <= nSize ) { n.setLength( 48 ); } else { n.setLength( nSize - nPosition ); } n.setVolume( fVelocity * 100 ); n.setPanning( ( fPan_R - fPan_L ) * 100 ); n.setKey( NoteKey::stringToNoteKey( sKey ) ); p->addNote( n,false ); pn = pn + 1; noteNode = ( QDomNode ) noteNode.nextSiblingElement( "note" ); } } patternNode = ( QDomNode ) patternNode.nextSiblingElement( "pattern" ); } // Pattern sequence QDomNode patternSequenceNode = songNode.firstChildElement( "patternSequence" ); QDomNode groupNode = patternSequenceNode.firstChildElement( "group" ); int pos = 0; while ( !groupNode.isNull() ) { int best_length = 0; QDomNode patternId = groupNode.firstChildElement( "patternID" ); while ( !patternId.isNull() ) { QString patId = patternId.firstChild().nodeValue(); patternId = ( QDomNode ) patternId.nextSiblingElement( "patternID" ); int i = pattern_id[patId]+song_num_tracks; Track *t = ( BBTrack * ) s->tracks().at( i ); TrackContentObject *tco = t->createTCO( pos ); tco->movePosition( pos ); if ( pattern_length[patId] > best_length ) { best_length = pattern_length[patId]; } } pos = pos + best_length; groupNode = groupNode.nextSiblingElement( "group" ); } if ( pattern_count == 0 ) { return false; } return true; }
bool EditArc3DPlugin::StartEdit(MeshDocument &_md, GLArea *_gla ) { er.modelList.clear(); this->md=&_md; gla=_gla; /////// delete arc3DDialog; arc3DDialog=new v3dImportDialog(gla->window(),this); QString fileName=arc3DDialog->fileName; if (fileName.isEmpty()) return false; // this change of dir is needed for subsequent texture/material loading QString FileNameDir = fileName.left(fileName.lastIndexOf("/")); QDir::setCurrent(FileNameDir); QString errorMsgFormat = "Error encountered while loading file %1:\n%2"; string stdfilename = QFile::encodeName(fileName).constData (); QDomDocument doc; QFile file(fileName); if (file.open(QIODevice::ReadOnly) && doc.setContent(&file)) { file.close(); QDomElement root = doc.documentElement(); if (root.nodeName() == tr("reconstruction")) { QDomNode nhead = root.firstChildElement("head"); for(QDomNode n = nhead.firstChildElement("meta"); !n.isNull(); n = n.nextSiblingElement("meta")) { if(!n.hasAttributes()) return false; QDomNamedNodeMap attr= n.attributes(); if(attr.contains("name")) er.name = (attr.namedItem("name")).nodeValue() ; if(attr.contains("author")) er.author = (attr.namedItem("author")).nodeValue() ; if(attr.contains("created")) er.created = (attr.namedItem("created")).nodeValue() ; } for(QDomNode n = root.firstChildElement("model"); !n.isNull(); n = n.nextSiblingElement("model")) { Arc3DModel em; em.Init(n); //em.cam.TR er.modelList.push_back(em); } } } arc3DDialog->setArc3DReconstruction( &er); arc3DDialog->exportToPLY=false; connect(arc3DDialog, SIGNAL(closing()),gla,SLOT(endEdit()) ); connect(arc3DDialog->ui.plyButton, SIGNAL(clicked()),this,SLOT(ExportPly()) ); connect(arc3DDialog->ui.exportbut,SIGNAL(clicked()),this,SLOT(exportShotsToRasters())); connect(this,SIGNAL(resetTrackBall()),gla,SLOT(resetTrackBall())); return true; }