// for multicurrency implementation see comments marked ##### in salesOrder.ui.h void arWorkBench::processYourPay() { QDomDocument odoc; // Build the order QDomElement root = odoc.createElement("order"); odoc.appendChild(root); QDomElement elem, sub; // add the 'credit card' elem = odoc.createElement("creditcard"); QString work_month; work_month.setNum(_ccard_month_expired); if (work_month.length() == 1) work_month = "0" + work_month; sub = odoc.createElement("cardexpmonth"); sub.appendChild(odoc.createTextNode(work_month)); elem.appendChild(sub); QString work_year; work_year.setNum(_ccard_year_expired); work_year = work_year.right(2); sub = odoc.createElement("cardexpyear"); sub.appendChild(odoc.createTextNode(work_year)); elem.appendChild(sub); sub = odoc.createElement("cardnumber"); sub.appendChild(odoc.createTextNode(_ccard_number)); elem.appendChild(sub); root.appendChild(elem); // Build 'merchantinfo' elem = odoc.createElement("merchantinfo"); sub = odoc.createElement("configfile"); sub.appendChild(odoc.createTextNode(configfile)); elem.appendChild(sub); root.appendChild(elem); // Build 'orderoptions' elem = odoc.createElement("orderoptions"); sub = odoc.createElement("ordertype"); sub.appendChild(odoc.createTextNode("POSTAUTH")); elem.appendChild(sub); sub = odoc.createElement("result"); sub.appendChild(odoc.createTextNode("LIVE")); elem.appendChild(sub); root.appendChild(elem); // Build 'payment' elem = odoc.createElement("payment"); QString tmp; sub = odoc.createElement("chargetotal"); sub.appendChild(odoc.createTextNode(tmp.setNum(_CCAmount->baseValue(), 'f', 2))); // ##### localValue()? elem.appendChild(sub); root.appendChild(elem); // Build 'transaction details' elem = odoc.createElement("transactiondetails"); sub = odoc.createElement("oid"); sub.appendChild(odoc.createTextNode(_backrefnum)); elem.appendChild(sub); root.appendChild(elem); // Process the order saved_order = odoc.toString(); if (_metrics->boolean("CCTest")) { _metrics->set("CCOrder", saved_order); } proc = new QProcess( this ); QString curl_path; #ifdef Q_WS_WIN curl_path = qApp->applicationDirPath() + "\\curl"; #elif defined Q_WS_MACX curl_path = "/usr/bin/curl"; #elif defined Q_WS_X11 curl_path = "/usr/bin/curl"; #endif QStringList curl_args; curl_args.append( "-k" ); curl_args.append( "-d" ); curl_args.append( saved_order ); curl_args.append( "-E" ); curl_args.append( pemfile ); _port.setNum(port); doServer = "https://" + _metrics->value("CCServer") + ":" + _port; curl_args.append( doServer ); QString proxy_login; QString proxy_server; if(_metrics->boolean("CCUseProxyServer")) { proxy_login = _metricsenc->value("CCProxyLogin") + ":" + _metricsenc->value("CCPassword") ; proxy_server = _metrics->value("CCProxyServer") + ":" + _metrics->value("CCProxyPort"); curl_args.append( "-x" ); curl_args.append( proxy_server ); curl_args.append( "-U" ); curl_args.append( proxy_login ); } _response = ""; connect( proc, SIGNAL(readyReadStandardOutput()), this, SLOT(readFromStdout()) ); QApplication::setOverrideCursor( QCursor(Qt::WaitCursor) ); _editPreauth->setEnabled(FALSE); proc->start(curl_path, curl_args); if ( !proc->waitForStarted() ) { QMessageBox::critical( 0, tr("Fatal error"), tr("Could not start the %1 command.").arg(curl_path), tr("Quit") ); return; } while (proc->state() == QProcess::Running) qApp->processEvents(); _editPreauth->setEnabled(TRUE); QApplication::restoreOverrideCursor(); _response = "<myroot>" + _response + "</myroot>"; QString whyMe; if (_metrics->boolean("CCTest")) { whyMe = _ccard_number + " " + _response; _metrics->set("CCTestMe", whyMe); _metrics->set("CCOrder", saved_order); } /*if (_metrics->boolean("CCTest")) { QMessageBox::information(this, tr("YourPay"), tr("The return code was ") + _response, QMessageBox::Ok); }*/ QDomDocument doc; doc.setContent(_response); QDomNode node; root = doc.documentElement(); QString _r_avs; QString _r_ordernum; QString _r_error; QString _r_approved; QString _r_code; QString _r_score; QString _r_shipping; QString _r_tax; QString _r_tdate; QString _r_ref; QString _r_message; QString _r_time; node = root.firstChild(); while ( !node.isNull() ) { if ( node.isElement() && node.nodeName() == "r_avs" ) { QDomElement r_avs = node.toElement(); _r_avs = r_avs.text(); } if ( node.isElement() && node.nodeName() == "r_ordernum" ) { QDomElement r_ordernum = node.toElement(); _r_ordernum = r_ordernum.text(); } if ( node.isElement() && node.nodeName() == "r_error" ) { QDomElement r_error = node.toElement(); _r_error = r_error.text(); } if ( node.isElement() && node.nodeName() == "r_approved" ) { QDomElement r_approved = node.toElement(); _r_approved = r_approved.text(); } if ( node.isElement() && node.nodeName() == "r_code" ) { QDomElement r_code = node.toElement(); _r_code = r_code.text(); } if ( node.isElement() && node.nodeName() == "r_message" ) { QDomElement r_message = node.toElement(); _r_message = r_message.text(); } if ( node.isElement() && node.nodeName() == "r_time" ) { QDomElement r_time = node.toElement(); _r_time = r_time.text(); } if ( node.isElement() && node.nodeName() == "r_ref" ) { QDomElement r_ref = node.toElement(); _r_ref = r_ref.text(); } if ( node.isElement() && node.nodeName() == "r_tdate" ) { QDomElement r_tdate = node.toElement(); _r_tdate = r_tdate.text(); } if ( node.isElement() && node.nodeName() == "r_tax" ) { QDomElement r_tax = node.toElement(); _r_tax = r_tax.text(); } if ( node.isElement() && node.nodeName() == "r_shipping" ) { QDomElement r_shipping = node.toElement(); _r_shipping = r_shipping.text(); } if ( node.isElement() && node.nodeName() == "r_score") { QDomElement r_score = node.toElement(); _r_score = r_score.text(); } node = node.nextSibling(); } q.prepare( "UPDATE ccpay" " SET ccpay_amount = :ccpay_amount, " " ccpay_auth = FALSE, " " ccpay_status = :ccpay_status, " " ccpay_curr_id = :ccpay_curr_id " " WHERE ccpay_id = :ccpay_id;" ); q.bindValue(":ccpay_id", _preauth->id()); q.bindValue(":ccpay_amount",_CCAmount->baseValue()); // ##### localValue()? q.bindValue(":ccpay_curr_id",_CCAmount->baseId()); // ##### id()? doDollars = 0; if (_r_approved == "APPROVED") { QMessageBox::information(this, tr("YourPay"), tr("This transaction was approved\n") + _r_ref, QMessageBox::Ok); q.bindValue(":ccpay_status","C"); doDollars = _CCAmount->baseValue(); // ##### localValue()? } if (_r_approved == "DENIED") { QMessageBox::information(this, tr("YourPay"), tr("This transaction was denied\n") + _r_message, QMessageBox::Ok); q.bindValue(":ccpay_status","D"); } if (_r_approved == "DUPLICATE") { QMessageBox::information(this, tr("YourPay"), tr("This transaction is a duplicate\n") + _r_message, QMessageBox::Ok); q.bindValue(":ccpay_status","D"); } if (_r_approved == "DECLINED") { QMessageBox::information(this, tr("YourPay"), tr("This transaction is a declined\n") + _r_error, QMessageBox::Ok); q.bindValue(":ccpay_status","D"); } if (_r_approved == "FRAUD") { QMessageBox::information(this, tr("YourPay"), tr("This transaction is denied because of possible fraud\n") + _r_error, QMessageBox::Ok); q.bindValue(":ccpay_status","D"); } if (_r_approved.length() == 0 || _r_approved.isNull() || _r_approved.isEmpty()) { QMessageBox::information(this, tr("YourPay"), tr("<p>No Approval Code<br>%1<br>%2<br>%3") .arg(_r_error).arg(_r_message).arg(_response), QMessageBox::Ok); q.bindValue(":ccpay_status","X"); } q.exec(); //We need to a charge here to do a cash receipt // We need some logic for a successful charge and for a non-successful charge if (doDollars > 0) { // This is a sucessful charge q.prepare("INSERT INTO cashrcpt (cashrcpt_id," " cashrcpt_cust_id," " cashrcpt_amount," " cashrcpt_curr_id," " cashrcpt_fundstype, " " cashrcpt_docnumber," " cashrcpt_bankaccnt_id," " cashrcpt_notes," " cashrcpt_distdate) " "VALUES (nextval('cashrcpt_cashrcpt_id_seq'), :cashrcpt_cust_id," " :cashrcpt_amount, :cashrcpt_curr_id, :cashrcpt_fundstype," " :cashrcpt_docnumber, :cashrcpt_bankaccnt_id," " :cashrcpt_notes, current_date);"); q.bindValue(":cashrcpt_cust_id",_cust->id()); q.bindValue(":cashrcpt_amount",doDollars); q.bindValue(":cashrcpt_curr_id", _CCAmount->baseId()); // ##### id()? q.bindValue(":cashrcpt_fundstype",_ccard_type); q.bindValue(":cashrcpt_docnumber",_backrefnum); q.bindValue(":cashrcpt_bankaccnt_id",_metrics->value("CCDefaultBank").toInt()); q.bindValue(":cashrcpt_notes","Converted Pre-auth"); q.exec(); } //Clean up sFillCashrcptList(); sFillAropenCMList(); sFillAropenList(); sFillPreauthList(); _CCAmount->clear(); }
void AutomatableModel::loadSettings( const QDomElement& element, const QString& name ) { // compat code QDomNode node = element.namedItem( AutomationPattern::classNodeName() ); if( node.isElement() ) { node = node.namedItem( name ); if( node.isElement() ) { AutomationPattern * p = AutomationPattern::globalAutomationPattern( this ); p->loadSettings( node.toElement() ); setValue( p->valueAt( 0 ) ); // in older projects we sometimes have odd automations // with just one value in - eliminate if necessary if( !p->hasAutomation() ) { delete p; } return; } // logscales were not existing at this point of time // so they can be ignored } QDomNode connectionNode = element.namedItem( "connection" ); // reads controller connection if( connectionNode.isElement() ) { QDomNode thisConnection = connectionNode.toElement().namedItem( name ); if( thisConnection.isElement() ) { setControllerConnection( new ControllerConnection( (Controller*)NULL ) ); m_controllerConnection->loadSettings( thisConnection.toElement() ); //m_controllerConnection->setTargetName( displayName() ); } } // models can be stored as elements (port00) or attributes (port10): // <ladspacontrols port10="4.41"> // <port00 value="4.41" id="4249278"/> // </ladspacontrols> // element => there is automation data, or scaletype information node = element.namedItem( name ); if( node.isElement() ) { changeID( node.toElement().attribute( "id" ).toInt() ); setValue( node.toElement().attribute( "value" ).toFloat() ); if( node.toElement().hasAttribute( "scale_type" ) ) { if( node.toElement().attribute( "scale_type" ) == "linear" ) { setScaleType( Linear ); } else if( node.toElement().attribute( "scale_type" ) == "log" ) { setScaleType( Logarithmic ); } } } else if( element.hasAttribute( name ) ) // attribute => read the element's value from the attribute list { setInitValue( element.attribute( name ).toFloat() ); } else { reset(); } }
void ThymioVisualProgramming::loadFromDom(const QDomDocument& document, bool fromFile) { scene->clear(); QDomNode domNode = document.documentElement().firstChild(); while (!domNode.isNull()) { if (domNode.isElement()) { QDomElement element = domNode.toElement(); if (element.tagName() == "settings") { if( element.attribute("advanced-mode") == "true" ) advancedMode(); else { advancedButton->setEnabled(true); actionButtons.last()->hide(); // state button scene->setAdvanced(false); } colorComboButton->setCurrentIndex(element.attribute("color-scheme").toInt()); } else if(element.tagName() == "buttonset") { QString buttonName; ThymioButton *eventButton = 0; ThymioButton *actionButton = 0; if( !(buttonName = element.attribute("event-name")).isEmpty() ) { if ( buttonName == "button" ) eventButton = new ThymioButtonsEvent(0,scene->getAdvanced()); else if ( buttonName == "prox" ) eventButton = new ThymioProxEvent(0,scene->getAdvanced()); else if ( buttonName == "proxground" ) eventButton = new ThymioProxGroundEvent(0,scene->getAdvanced()); else if ( buttonName == "tap" ) { eventButton = new ThymioTapEvent(0,scene->getAdvanced()); eventButton->setSharedRenderer(tapSvg); } else if ( buttonName == "clap" ) { eventButton = new ThymioClapEvent(0,scene->getAdvanced()); eventButton->setSharedRenderer(clapSvg); } else { QMessageBox::warning(this,tr("Loading"), tr("Error in XML source file: %0 unknown event type").arg(buttonName)); return; } for(int i=0; i<eventButton->getNumButtons(); ++i) eventButton->setClicked(i,element.attribute(QString("eb%0").arg(i)).toInt()); eventButton->setState(element.attribute("state").toInt()); } if( !(buttonName = element.attribute("action-name")).isEmpty() ) { if ( buttonName == "move" ) actionButton = new ThymioMoveAction(); else if ( buttonName == "color" ) actionButton = new ThymioColorAction(); else if ( buttonName == "circle" ) actionButton = new ThymioCircleAction(); else if ( buttonName == "sound" ) actionButton = new ThymioSoundAction(); else if ( buttonName == "memory" ) actionButton = new ThymioMemoryAction(); else { QMessageBox::warning(this,tr("Loading"), tr("Error in XML source file: %0 unknown event type").arg(buttonName)); return; } for(int i=0; i<actionButton->getNumButtons(); ++i) actionButton->setClicked(i,element.attribute(QString("ab%0").arg(i)).toInt()); } scene->addButtonSet(eventButton, actionButton); } } domNode = domNode.nextSibling(); } scene->setModified(!fromFile); if (!scene->isEmpty()) QTimer::singleShot(0, this, SLOT(exec())); }
void FlickrTalker::parseResponseCheckToken(const QByteArray& data) { bool success = false; QString errorString; QString username; QString transReturn; QDomDocument doc("checktoken"); if (!doc.setContent(data)) { return; } QDomElement docElem = doc.documentElement(); QDomNode node = docElem.firstChild(); QDomElement e; while (!node.isNull()) { if (node.isElement() && node.nodeName() == "auth") { e = node.toElement(); // try to convert the node to an element. QDomNode details = e.firstChild(); while (!details.isNull()) { if (details.isElement()) { e = details.toElement(); if (details.nodeName() == "token") { kDebug() << "Token=" << e.text(); m_token = e.text();//this is what is obtained from data. } if (details.nodeName() == "perms") { kDebug() << "Perms=" << e.text(); QString perms = e.text();//this is what is obtained from data. if (perms == "write") { transReturn = i18nc("As in the permission to", "write"); } else if (perms == "read") { transReturn = i18nc("As in the permission to", "read"); } else if (perms == "delete") { transReturn = i18nc("As in the permission to", "delete"); } } if (details.nodeName() == "user") { kDebug() << "nsid=" << e.attribute("nsid"); m_userId = e.attribute("nsid"); username = e.attribute("username"); m_username = username; kDebug() << "username="******"username"); kDebug() << "fullname=" << e.attribute("fullname"); } } details = details.nextSibling(); } m_authProgressDlg->hide(); emit signalTokenObtained(m_token); success = true; } if (node.isElement() && node.nodeName() == "err") { kDebug() << "Checking Error in response"; errorString = node.toElement().attribute("code"); kDebug() << "Error code=" << errorString; kDebug() << "Msg=" << node.toElement().attribute("msg"); int valueOk = KMessageBox::questionYesNo(kapp->activeWindow(), i18n("Your token is invalid. Would you like to " "get a new token to proceed?\n")); if (valueOk == KMessageBox::Yes) { getFrob(); return; } else { m_authProgressDlg->hide(); //will popup the result for the checktoken failure below } } node = node.nextSibling(); } if (!success) { emit signalError(errorString); } kDebug() << "CheckToken finished"; }
void FlickrTalker::parseResponseListPhotoSets(const QByteArray& data) { kDebug() << "parseResponseListPhotosets" << data; bool success = false; QDomDocument doc("getListPhotoSets"); if (!doc.setContent(data)) { return; } QDomElement docElem = doc.documentElement(); QDomNode node = docElem.firstChild(); QDomElement e; QString photoSet_id, photoSet_title, photoSet_description; m_photoSetsList = new QLinkedList <FPhotoSet> (); while (!node.isNull()) { if (node.isElement() && node.nodeName() == "photosets") { e = node.toElement(); QDomNode details = e.firstChild(); FPhotoSet fps; QDomNode detailsNode = details; while (!detailsNode.isNull()) { if (detailsNode.isElement()) { e = detailsNode.toElement(); if (detailsNode.nodeName() == "photoset") { kDebug() << "id=" << e.attribute("id"); photoSet_id = e.attribute("id"); // this is what is obtained from data. fps.id = photoSet_id; QDomNode photoSetDetails = detailsNode.firstChild(); QDomElement e_detail; while (!photoSetDetails.isNull()) { e_detail = photoSetDetails.toElement(); if (photoSetDetails.nodeName() == "title") { kDebug() << "Title=" << e_detail.text(); photoSet_title = e_detail.text(); fps.title = photoSet_title; } else if (photoSetDetails.nodeName() == "description") { kDebug() << "Description =" << e_detail.text(); photoSet_description = e_detail.text(); fps.description = photoSet_description; } photoSetDetails = photoSetDetails.nextSibling(); } m_photoSetsList->append(fps); } } detailsNode = detailsNode.nextSibling(); } details = details.nextSibling(); success = true; } if (node.isElement() && node.nodeName() == "err") { kDebug() << "Checking Error in response"; QString code = node.toElement().attribute("code"); kDebug() << "Error code=" << code; kDebug() << "Msg=" << node.toElement().attribute("msg"); emit signalError(code); } node = node.nextSibling(); } kDebug() << "GetPhotoList finished"; if (!success) { emit signalListPhotoSetsFailed(i18n("Failed to fetch list of photo sets.")); } else { emit signalListPhotoSetsSucceeded(); maxAllowedFileSize(); } }
bool GraphMLImporter::processGraph_Nodes( QDomElement& graphElement ) { bool ok = true; iColor_ = 0; // nodes for ( QDomElement nodeElement = graphElement.firstChildElement( "node" ); ok && !nodeElement.isNull(); nodeElement = nodeElement.nextSiblingElement( "node" ) ) { QString nameId = nodeElement.attribute( "id" ); QString name = NULL; // pozerame sa na data ktore nesie Data::Type* newNodeType; newNodeType = NULL; QDomNodeList nodeDataList = nodeElement.elementsByTagName( "data" ); for ( unsigned int j = 0; j < nodeDataList.length(); j++ ) { QDomNode nodeData = nodeDataList.item( static_cast<int>( j ) ); if ( !nodeData.isNull() && nodeData.isElement() ) { QDomElement nodeDataElement = nodeData.toElement(); QString dataName = nodeDataElement.attribute( "key" ); QString dataValue = nodeDataElement.text(); // rozpoznavame typy if ( dataName == nodeTypeAttribute_ ) { // overime ci uz dany typ existuje v grafe QList<Data::Type*> types = context_->getGraph().getTypesByName( dataValue ); if ( types.isEmpty() ) { QMap<QString, QString>* settings = new QMap<QString, QString>; settings->insert( "color.R", QString::number( colors_[iColor_][0] ) ); settings->insert( "color.G", QString::number( colors_[iColor_][1] ) ); settings->insert( "color.B", QString::number( colors_[iColor_][2] ) ); settings->insert( "color.A", QString::number( colors_[iColor_][3] ) ); settings->insert( "scale", Util::ApplicationConfig::get()->getValue( "Viewer.Textures.DefaultNodeScale" ) ); settings->insert( "textureFile", Util::ApplicationConfig::get()->getValue( "Viewer.Textures.Node" ) ); newNodeType = context_->getGraph().addType( dataValue, settings ); iColor_++; if ( iColor_ == colors_.size() ) { iColor_ = 0; } } else { newNodeType = types.first(); } } else { // kazde dalsie data nacitame do nosica dat - Node.name // FIXME potom prerobit cez Adamove Node.settings if ( name == NULL ) { name = dataName+":"+dataValue; } else { name += " | "+dataName+":"+dataValue; } } } } // ak sme nenasli name, tak ako name pouzijeme aspon ID if ( name == NULL ) { name = nameId; } // ak nebol najdeny ziaden typ, tak pouzijeme defaultny typ osg::ref_ptr<Data::Node> node; if ( newNodeType == NULL ) { node = context_->getGraph().addNode( name, nodeType_ ); } else { node = context_->getGraph().addNode( name, newNodeType ); } readNodes_->addNode( nameId, node ); // subgraphs for ( QDomElement subgraphElement = nodeElement.firstChildElement( "graph" ); ok && !subgraphElement.isNull(); subgraphElement = subgraphElement.nextSiblingElement( "graph" ) ) { if ( ok ) { context_->getGraph().createNestedGraph( node ); } if ( ok ) { ok = processGraph( subgraphElement ); } if ( ok ) { context_->getGraph().closeNestedGraph(); } } entitiesProcessed_++; context_->getInfoHandler().setProgress( static_cast<unsigned int>( entitiesProcessed_ * 100 / entitiesCount_ ) ); } return ok; }
// load given song void Song::loadProject( const QString & fileName ) { QDomNode node; m_loadingProject = true; Engine::projectJournal()->setJournalling( false ); m_fileName = fileName; m_oldFileName = fileName; DataFile dataFile( m_fileName ); // if file could not be opened, head-node is null and we create // new project if( dataFile.validate( fileName.right( fileName.lastIndexOf(".") ) ) ) { return; } clearProject(); clearErrors(); DataFile::LocaleHelper localeHelper( DataFile::LocaleHelper::ModeLoad ); Engine::mixer()->lock(); // get the header information from the DOM m_tempoModel.loadSettings( dataFile.head(), "bpm" ); m_timeSigModel.loadSettings( dataFile.head(), "timesig" ); m_masterVolumeModel.loadSettings( dataFile.head(), "mastervol" ); m_masterPitchModel.loadSettings( dataFile.head(), "masterpitch" ); if( m_playPos[Mode_PlaySong].m_timeLine ) { // reset loop-point-state m_playPos[Mode_PlaySong].m_timeLine->toggleLoopPoints( 0 ); } if( !dataFile.content().firstChildElement( "track" ).isNull() ) { m_globalAutomationTrack->restoreState( dataFile.content(). firstChildElement( "track" ) ); } //Backward compatibility for LMMS <= 0.4.15 PeakController::initGetControllerBySetting(); // Load mixer first to be able to set the correct range for FX channels node = dataFile.content().firstChildElement( Engine::fxMixer()->nodeName() ); if( !node.isNull() ) { Engine::fxMixer()->restoreState( node.toElement() ); if( gui ) { // refresh FxMixerView gui->fxMixerView()->refreshDisplay(); } } node = dataFile.content().firstChild(); while( !node.isNull() ) { if( node.isElement() ) { if( node.nodeName() == "trackcontainer" ) { ( (JournallingObject *)( this ) )->restoreState( node.toElement() ); } else if( node.nodeName() == "controllers" ) { restoreControllerStates( node.toElement() ); } else if( gui ) { if( node.nodeName() == gui->getControllerRackView()->nodeName() ) { gui->getControllerRackView()->restoreState( node.toElement() ); } else if( node.nodeName() == gui->pianoRoll()->nodeName() ) { gui->pianoRoll()->restoreState( node.toElement() ); } else if( node.nodeName() == gui->automationEditor()->m_editor->nodeName() ) { gui->automationEditor()->m_editor->restoreState( node.toElement() ); } else if( node.nodeName() == gui->getProjectNotes()->nodeName() ) { gui->getProjectNotes()->SerializingObject::restoreState( node.toElement() ); } else if( node.nodeName() == m_playPos[Mode_PlaySong].m_timeLine->nodeName() ) { m_playPos[Mode_PlaySong].m_timeLine->restoreState( node.toElement() ); } } } node = node.nextSibling(); } // quirk for fixing projects with broken positions of TCOs inside // BB-tracks Engine::getBBTrackContainer()->fixIncorrectPositions(); // Connect controller links to their controllers // now that everything is loaded ControllerConnection::finalizeConnections(); // resolve all IDs so that autoModels are automated AutomationPattern::resolveAllIDs(); Engine::mixer()->unlock(); ConfigManager::inst()->addRecentlyOpenedProject( fileName ); Engine::projectJournal()->setJournalling( true ); emit projectLoaded(); if ( hasErrors()) { if ( gui ) { QMessageBox::warning( NULL, tr("LMMS Error report"), *errorSummary(), QMessageBox::Ok ); } else { QTextStream(stderr) << *Engine::getSong()->errorSummary() << endl; } } m_loadingProject = false; m_modified = false; if( gui && gui->mainWindow() ) { gui->mainWindow()->resetWindowTitle(); } }
// load given song void Song::loadProject( const QString & fileName ) { QDomNode node; m_loadingProject = true; Engine::projectJournal()->setJournalling( false ); m_oldFileName = m_fileName; setProjectFileName(fileName); DataFile dataFile( m_fileName ); // if file could not be opened, head-node is null and we create // new project if( dataFile.head().isNull() ) { if( m_loadOnLaunch ) { createNewProject(); } setProjectFileName(m_oldFileName); return; } m_oldFileName = m_fileName; clearProject(); clearErrors(); Engine::mixer()->requestChangeInModel(); // get the header information from the DOM m_tempoModel.loadSettings( dataFile.head(), "bpm" ); m_timeSigModel.loadSettings( dataFile.head(), "timesig" ); m_masterVolumeModel.loadSettings( dataFile.head(), "mastervol" ); m_masterPitchModel.loadSettings( dataFile.head(), "masterpitch" ); if( m_playPos[Mode_PlaySong].m_timeLine ) { // reset loop-point-state m_playPos[Mode_PlaySong].m_timeLine->toggleLoopPoints( 0 ); } if( !dataFile.content().firstChildElement( "track" ).isNull() ) { m_globalAutomationTrack->restoreState( dataFile.content(). firstChildElement( "track" ) ); } //Backward compatibility for LMMS <= 0.4.15 PeakController::initGetControllerBySetting(); // Load mixer first to be able to set the correct range for FX channels node = dataFile.content().firstChildElement( Engine::fxMixer()->nodeName() ); if( !node.isNull() ) { Engine::fxMixer()->restoreState( node.toElement() ); if( gui ) { // refresh FxMixerView gui->fxMixerView()->refreshDisplay(); } } node = dataFile.content().firstChild(); QDomNodeList tclist=dataFile.content().elementsByTagName("trackcontainer"); m_nLoadingTrack=0; for( int i=0,n=tclist.count(); i<n; ++i ) { QDomNode nd=tclist.at(i).firstChild(); while(!nd.isNull()) { if( nd.isElement() && nd.nodeName() == "track" ) { ++m_nLoadingTrack; if( nd.toElement().attribute("type").toInt() == Track::BBTrack ) { n += nd.toElement().elementsByTagName("bbtrack").at(0) .toElement().firstChildElement().childNodes().count(); } nd=nd.nextSibling(); } } } while( !node.isNull() && !isCancelled() ) { if( node.isElement() ) { if( node.nodeName() == "trackcontainer" ) { ( (JournallingObject *)( this ) )->restoreState( node.toElement() ); } else if( node.nodeName() == "controllers" ) { restoreControllerStates( node.toElement() ); } else if( gui ) { if( node.nodeName() == gui->getControllerRackView()->nodeName() ) { gui->getControllerRackView()->restoreState( node.toElement() ); } else if( node.nodeName() == gui->pianoRoll()->nodeName() ) { gui->pianoRoll()->restoreState( node.toElement() ); } else if( node.nodeName() == gui->automationEditor()->m_editor->nodeName() ) { gui->automationEditor()->m_editor->restoreState( node.toElement() ); } else if( node.nodeName() == gui->getProjectNotes()->nodeName() ) { gui->getProjectNotes()->SerializingObject::restoreState( node.toElement() ); } else if( node.nodeName() == m_playPos[Mode_PlaySong].m_timeLine->nodeName() ) { m_playPos[Mode_PlaySong].m_timeLine->restoreState( node.toElement() ); } } } node = node.nextSibling(); } // quirk for fixing projects with broken positions of TCOs inside // BB-tracks Engine::getBBTrackContainer()->fixIncorrectPositions(); // Connect controller links to their controllers // now that everything is loaded ControllerConnection::finalizeConnections(); // Remove dummy controllers that was added for correct connections m_controllers.erase(std::remove_if(m_controllers.begin(), m_controllers.end(), [](Controller* c){return c->type() == Controller::DummyController;}), m_controllers.end()); // resolve all IDs so that autoModels are automated AutomationPattern::resolveAllIDs(); Engine::mixer()->doneChangeInModel(); ConfigManager::inst()->addRecentlyOpenedProject( fileName ); Engine::projectJournal()->setJournalling( true ); emit projectLoaded(); if( isCancelled() ) { m_isCancelled = false; createNewProject(); return; } if ( hasErrors()) { if ( gui ) { QMessageBox::warning( NULL, tr("LMMS Error report"), errorSummary(), QMessageBox::Ok ); } else { QTextStream(stderr) << Engine::getSong()->errorSummary() << endl; } } m_loadingProject = false; setModified(false); m_loadOnLaunch = false; }
WbWidget::WbWidget(SxeSession* session, QWidget *parent) : QGraphicsView(parent) { newWbItem_ = 0; adding_ = 0; addVertex_ = false; strokeColor_ = Qt::black; fillColor_ = Qt::transparent; strokeWidth_ = 1; session_ = session; // setCacheMode(CacheBackground); setRenderHint(QPainter::Antialiasing); setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); // Make the scroll bars always stay on because otherwise the resize event can cause // an infinite loop as the effective size of the widget changes when scroll bars are // added/removed setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOn); setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn); // create the scene scene_ = new WbScene(session_, this); scene_->setItemIndexMethod(QGraphicsScene::NoIndex); setRenderHint(QPainter::Antialiasing); setTransformationAnchor(AnchorUnderMouse); setResizeAnchor(AnchorViewCenter); setScene(scene_); // render the initial document rerender(); // rerender on update connect(session_, SIGNAL(documentUpdated(bool)), SLOT(handleDocumentUpdated(bool))); // add the initial items const QDomNodeList children = session_->document().documentElement().childNodes(); for(int i = 0; i < (int)children.length(); i++) { const QDomNode node = children.at(i); if(node.isElement()) { queueNodeInspection(node.toElement()); } } inspectNodes(); // add new items as nodes are added // remove/add items if corresponding nodes are moved connect(session_, SIGNAL(nodeAdded(QDomNode, bool)), SLOT(queueNodeInspection(QDomNode))); connect(session_, SIGNAL(nodeMoved(QDomNode, bool)), SLOT(queueNodeInspection(QDomNode))); // remove items if corresponding nodes are deleted connect(session_, SIGNAL(nodeToBeRemoved(QDomNode, bool)), SLOT(removeWbItem(QDomNode))); connect(session_, SIGNAL(nodeToBeRemoved(QDomNode, bool)), SLOT(checkForRemovalOfId(QDomNode))); // adjust the viewBox as necessary connect(session_, SIGNAL(nodeAdded(QDomNode, bool)), SLOT(checkForViewBoxChange(QDomNode))); connect(session_, SIGNAL(nodeMoved(QDomNode, bool)), SLOT(checkForViewBoxChange(QDomNode))); connect(session_, SIGNAL(chdataChanged(QDomNode, bool)), SLOT(checkForViewBoxChange(QDomNode))); // set the default mode to select setMode(Select); // set the initial size if(session_->document().documentElement().hasAttribute("viewBox")) checkForViewBoxChange(session_->document().documentElement().attributeNode("viewBox")); else { QSize size; QRectF rect = scene_->sceneRect(); size.setWidth(rect.x() + rect.width()); size.setHeight(rect.y() + rect.height()); if(size.width() > 0 && size.height() > 0) setSize(size); else setSize(QSize(400, 600)); } }
void XMLHandler::read_xml_file() { QDomDocument document; // load the file QFile file(filename); if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) { qDebug() << "Unable to open file!"; return; } else { if (!document.setContent(&file)) { qDebug() << "Invalid XML file!"; return; } file.close(); } // get root element QDomElement docElem = document.documentElement(); // check root tag QString rootTag = docElem.tagName(); if (!rootTag.compare("\"StreXRD_Project\"")) { qDebug() << "Not a StreXRD project file!"; } QDomElement root = document.firstChildElement(); // get the project name QDomNodeList items = root.elementsByTagName("Name"); QDomNode itemnode = items.at(0); QDomElement itemEl = itemnode.toElement(); project_name = itemEl.text(); // get file names and locations QDomNodeList files = docElem.elementsByTagName("File"); for (int i = 0; i < files.count(); i++) { QDomNode filenode = files.at(i); if (filenode.isElement()) { QString file_ID = filenode.toElement().attribute("ID"); int file_ID_number = file_ID.toInt(); file_ID_list.append(file_ID_number); QDomNodeList file_names = filenode.toElement().elementsByTagName("Name"); QDomNodeList file_locations = filenode.toElement().elementsByTagName("Location"); QString file_name = file_names.at(0).toElement().text(); QString file_location = file_locations.at(0).toElement().text(); this->file_names_locations.insert(file_name, file_location); file_name_list.append(file_name); file_location_list.append(file_location); } } }
// load given song void song::loadProject( const QString & _file_name ) { QDomNode node; m_loadingProject = true; clearProject(); engine::projectJournal()->setJournalling( false ); m_fileName = _file_name; m_oldFileName = _file_name; DataFile dataFile( m_fileName ); // if file could not be opened, head-node is null and we create // new project if( dataFile.head().isNull() ) { createNewProject(); return; } engine::mixer()->lock(); // get the header information from the DOM m_tempoModel.loadSettings( dataFile.head(), "bpm" ); m_timeSigModel.loadSettings( dataFile.head(), "timesig" ); m_masterVolumeModel.loadSettings( dataFile.head(), "mastervol" ); m_masterPitchModel.loadSettings( dataFile.head(), "masterpitch" ); if( m_playPos[Mode_PlaySong].m_timeLine ) { // reset loop-point-state m_playPos[Mode_PlaySong].m_timeLine->toggleLoopPoints( 0 ); } if( !dataFile.content().firstChildElement( "track" ).isNull() ) { m_globalAutomationTrack->restoreState( dataFile.content(). firstChildElement( "track" ) ); } //Backward compatibility for LMMS <= 0.4.15 PeakController::initGetControllerBySetting(); // Load mixer first to be able to set the correct range for FX channels node = dataFile.content().firstChildElement( engine::fxMixer()->nodeName() ); if( !node.isNull() ) { engine::fxMixer()->restoreState( node.toElement() ); if( engine::hasGUI() ) { // refresh FxMixerView engine::fxMixerView()->refreshDisplay(); } } node = dataFile.content().firstChild(); while( !node.isNull() ) { if( node.isElement() ) { if( node.nodeName() == "trackcontainer" ) { ( (JournallingObject *)( this ) )->restoreState( node.toElement() ); } else if( node.nodeName() == "controllers" ) { restoreControllerStates( node.toElement() ); } else if( engine::hasGUI() ) { if( node.nodeName() == engine::getControllerRackView()->nodeName() ) { engine::getControllerRackView()->restoreState( node.toElement() ); } else if( node.nodeName() == engine::pianoRoll()->nodeName() ) { engine::pianoRoll()->restoreState( node.toElement() ); } else if( node.nodeName() == engine::automationEditor()->nodeName() ) { engine::automationEditor()->restoreState( node.toElement() ); } else if( node.nodeName() == engine::getProjectNotes()->nodeName() ) { engine::getProjectNotes()->SerializingObject::restoreState( node.toElement() ); } else if( node.nodeName() == m_playPos[Mode_PlaySong].m_timeLine->nodeName() ) { m_playPos[Mode_PlaySong].m_timeLine->restoreState( node.toElement() ); } } } node = node.nextSibling(); } // quirk for fixing projects with broken positions of TCOs inside // BB-tracks engine::getBBTrackContainer()->fixIncorrectPositions(); // Connect controller links to their controllers // now that everything is loaded ControllerConnection::finalizeConnections(); // resolve all IDs so that autoModels are automated AutomationPattern::resolveAllIDs(); engine::mixer()->unlock(); configManager::inst()->addRecentlyOpenedProject( _file_name ); engine::projectJournal()->setJournalling( true ); emit projectLoaded(); m_loadingProject = false; m_modified = false; if( engine::mainWindow() ) { engine::mainWindow()->resetWindowTitle(); } }
void WPushButton::setup(QDomNode node, const SkinContext& context) { // Number of states int iNumStates = context.selectInt(node, "NumberStates"); setStates(iNumStates); // Set background pixmap if available if (context.hasNode(node, "BackPath")) { QString mode_str = context.selectAttributeString( context.selectElement(node, "BackPath"), "scalemode", "TILE"); setPixmapBackground(context.getSkinPath(context.selectString(node, "BackPath")), Paintable::DrawModeFromString(mode_str)); } // Load pixmaps for associated states QDomNode state = context.selectNode(node, "State"); while (!state.isNull()) { if (state.isElement() && state.nodeName() == "State") { int iState = context.selectInt(state, "Number"); if (iState < m_iNoStates) { if (context.hasNode(state, "Pressed")) { setPixmap(iState, true, context.getSkinPath(context.selectString(state, "Pressed"))); } if (context.hasNode(state, "Unpressed")) { setPixmap(iState, false, context.getSkinPath(context.selectString(state, "Unpressed"))); } m_text.replace(iState, context.selectString(state, "Text")); } } state = state.nextSibling(); } ControlParameterWidgetConnection* leftConnection = NULL; if (m_leftConnections.isEmpty()) { if (!m_connections.isEmpty()) { // If no left connection is set, the this is the left connection leftConnection = m_connections.at(0); } } else { leftConnection = m_leftConnections.at(0); } if (leftConnection) { bool leftClickForcePush = context.selectBool(node, "LeftClickIsPushButton", false); m_leftButtonMode = ControlPushButton::PUSH; if (!leftClickForcePush) { const ConfigKey& configKey = leftConnection->getKey(); ControlPushButton* p = dynamic_cast<ControlPushButton*>( ControlObject::getControl(configKey)); if (p) { m_leftButtonMode = p->getButtonMode(); } } if (leftConnection->getEmitOption() & ControlParameterWidgetConnection::EMIT_DEFAULT) { switch (m_leftButtonMode) { case ControlPushButton::PUSH: case ControlPushButton::LONGPRESSLATCHING: case ControlPushButton::POWERWINDOW: leftConnection->setEmitOption( ControlParameterWidgetConnection::EMIT_ON_PRESS_AND_RELEASE); break; default: leftConnection->setEmitOption( ControlParameterWidgetConnection::EMIT_ON_PRESS); break; } } if (leftConnection->getDirectionOption() & ControlParameterWidgetConnection::DIR_DEFAULT) { if (m_pDisplayConnection == leftConnection) { leftConnection->setDirectionOption(ControlParameterWidgetConnection::DIR_FROM_AND_TO_WIDGET); } else { leftConnection->setDirectionOption(ControlParameterWidgetConnection::DIR_FROM_WIDGET); if (m_pDisplayConnection->getDirectionOption() & ControlParameterWidgetConnection::DIR_DEFAULT) { m_pDisplayConnection->setDirectionOption(ControlParameterWidgetConnection::DIR_TO_WIDGET); } } } } if (!m_rightConnections.isEmpty()) { ControlParameterWidgetConnection* rightConnection = m_rightConnections.at(0); bool rightClickForcePush = context.selectBool(node, "RightClickIsPushButton", false); m_rightButtonMode = ControlPushButton::PUSH; if (!rightClickForcePush) { const ConfigKey configKey = rightConnection->getKey(); ControlPushButton* p = dynamic_cast<ControlPushButton*>( ControlObject::getControl(configKey)); if (p) { m_rightButtonMode = p->getButtonMode(); if (m_rightButtonMode != ControlPushButton::PUSH) { qWarning() << "WPushButton::setup: Connecting a Pushbutton not in PUSH mode is not implemented\n" << "Please set <RightClickIsPushButton>true</RightClickIsPushButton>"; } } } if (rightConnection->getEmitOption() & ControlParameterWidgetConnection::EMIT_DEFAULT) { switch (m_rightButtonMode) { case ControlPushButton::PUSH: case ControlPushButton::LONGPRESSLATCHING: case ControlPushButton::POWERWINDOW: leftConnection->setEmitOption( ControlParameterWidgetConnection::EMIT_ON_PRESS_AND_RELEASE); break; default: leftConnection->setEmitOption( ControlParameterWidgetConnection::EMIT_ON_PRESS); break; } } if (rightConnection->getDirectionOption() & ControlParameterWidgetConnection::DIR_DEFAULT) { rightConnection->setDirectionOption(ControlParameterWidgetConnection::DIR_FROM_WIDGET); } } }
void InstrumentTrack::loadTrackSpecificSettings( const QDomElement & thisElement ) { silenceAllNotes( true ); lock(); m_volumeModel.loadSettings( thisElement, "vol" ); m_panningModel.loadSettings( thisElement, "pan" ); m_pitchRangeModel.loadSettings( thisElement, "pitchrange" ); m_pitchModel.loadSettings( thisElement, "pitch" ); m_effectChannelModel.setRange( 0, Engine::fxMixer()->numChannels()-1 ); m_effectChannelModel.loadSettings( thisElement, "fxch" ); m_baseNoteModel.loadSettings( thisElement, "basenote" ); m_useMasterPitchModel.loadSettings( thisElement, "usemasterpitch"); // clear effect-chain just in case we load an old preset without FX-data m_audioPort.effects()->clear(); QDomNode node = thisElement.firstChild(); while( !node.isNull() ) { if( node.isElement() ) { if( m_soundShaping.nodeName() == node.nodeName() ) { m_soundShaping.restoreState( node.toElement() ); } else if( m_noteStacking.nodeName() == node.nodeName() ) { m_noteStacking.restoreState( node.toElement() ); } else if( m_arpeggio.nodeName() == node.nodeName() ) { m_arpeggio.restoreState( node.toElement() ); } else if( m_midiPort.nodeName() == node.nodeName() ) { m_midiPort.restoreState( node.toElement() ); } else if( m_audioPort.effects()->nodeName() == node.nodeName() ) { m_audioPort.effects()->restoreState( node.toElement() ); } else if( node.nodeName() == "instrument" ) { delete m_instrument; m_instrument = NULL; m_instrument = Instrument::instantiate( node.toElement().attribute( "name" ), this ); m_instrument->restoreState( node.firstChildElement() ); emit instrumentChanged(); } // compat code - if node-name doesn't match any known // one, we assume that it is an instrument-plugin // which we'll try to load else if( AutomationPattern::classNodeName() != node.nodeName() && ControllerConnection::classNodeName() != node.nodeName() && !node.toElement().hasAttribute( "id" ) ) { delete m_instrument; m_instrument = NULL; m_instrument = Instrument::instantiate( node.nodeName(), this ); if( m_instrument->nodeName() == node.nodeName() ) { m_instrument->restoreState( node.toElement() ); } emit instrumentChanged(); } } node = node.nextSibling(); } updatePitchRange(); unlock(); }
bool MyMoneyStatement::read(const QDomElement& _e) { bool result = false; if (_e.tagName() == "STATEMENT") { result = true; m_strAccountName = _e.attribute("accountname"); m_strAccountNumber = _e.attribute("accountnumber"); m_strRoutingNumber = _e.attribute("routingnumber"); m_strCurrency = _e.attribute("currency"); m_dateBegin = QDate::fromString(_e.attribute("begindate"), Qt::ISODate); m_dateEnd = QDate::fromString(_e.attribute("enddate"), Qt::ISODate); m_closingBalance = MyMoneyMoney(_e.attribute("closingbalance")); m_accountId = _e.attribute("accountid"); m_skipCategoryMatching = _e.attribute("skipCategoryMatching").isEmpty(); int i = kAccountTypeTxt.indexOf(_e.attribute("type", kAccountTypeTxt[1])); if (i != -1) m_eType = static_cast<EType>(i); QDomNode child = _e.firstChild(); while (!child.isNull() && child.isElement()) { QDomElement c = child.toElement(); if (c.tagName() == "TRANSACTION") { MyMoneyStatement::Transaction t; t.m_datePosted = QDate::fromString(c.attribute("dateposted"), Qt::ISODate); t.m_amount = MyMoneyMoney(c.attribute("amount")); t.m_strMemo = c.attribute("memo"); t.m_strNumber = c.attribute("number"); t.m_strPayee = c.attribute("payee"); t.m_strBankID = c.attribute("bankid"); t.m_reconcile = static_cast<MyMoneySplit::reconcileFlagE>(c.attribute("reconcile").toInt()); int i = kActionText.indexOf(c.attribute("action", kActionText[1])); if (i != -1) t.m_eAction = static_cast<Transaction::EAction>(i); if (m_eType == etInvestment) { t.m_shares = MyMoneyMoney(c.attribute("shares")); t.m_strSecurity = c.attribute("security"); t.m_strBrokerageAccount = c.attribute("brokerageaccount"); } // process splits (if any) QDomNode child = c.firstChild(); while (!child.isNull() && child.isElement()) { QDomElement c = child.toElement(); if (c.tagName() == "SPLIT") { MyMoneyStatement::Split s; s.m_accountId = c.attribute("accountid"); s.m_amount = MyMoneyMoney(c.attribute("amount")); s.m_reconcile = static_cast<MyMoneySplit::reconcileFlagE>(c.attribute("reconcile").toInt()); s.m_strCategoryName = c.attribute("category"); s.m_strMemo = c.attribute("memo"); t.m_listSplits += s; } child = child.nextSibling(); } m_listTransactions += t; } else if (c.tagName() == "PRICE") { MyMoneyStatement::Price p; p.m_date = QDate::fromString(c.attribute("dateposted"), Qt::ISODate); p.m_strSecurity = c.attribute("security"); p.m_amount = MyMoneyMoney(c.attribute("amount")); m_listPrices += p; } else if (c.tagName() == "SECURITY") { MyMoneyStatement::Security s; s.m_strName = c.attribute("name"); s.m_strSymbol = c.attribute("symbol"); s.m_strId = c.attribute("id"); m_listSecurities += s; } child = child.nextSibling(); } } return result; }
bool GraphMLImporter::processGraph_Edges( QDomElement& graphElement ) { bool ok = true; iColor_ = 0; // default direction bool defaultDirection; if ( graphElement.attribute( "edgedefault" ) == "directed" ) { defaultDirection = true; } else { defaultDirection = false; } // edges for ( QDomElement edgeElement = graphElement.firstChildElement( "edge" ); ok && !edgeElement.isNull(); edgeElement = edgeElement.nextSiblingElement( "edge" ) ) { QString sourceId = edgeElement.attribute( "source" ); QString targetId = edgeElement.attribute( "target" ); QString direction = NULL; bool directed = false; direction = edgeElement.attribute( "directed" ); if ( direction == NULL ) { directed = defaultDirection; if ( directed ) { direction = "_directed"; } else { direction = ""; } } else { if ( direction == "true" ) { direction = "_directed"; directed = true; } else { direction = ""; directed = false; } } // pozerame sa na data ktore hrana nesie Data::Type* newEdgeType; newEdgeType = NULL; QDomNodeList edgeDataList = edgeElement.elementsByTagName( "data" ); for ( unsigned int j = 0; j < edgeDataList.length(); j++ ) { QDomNode edgeData = edgeDataList.item( static_cast<int>( j ) ); if ( !edgeData.isNull() && edgeData.isElement() ) { QDomElement edgeDataElement = edgeData.toElement(); QString dataName = edgeDataElement.attribute( "key" ); QString dataValue = edgeDataElement.text(); // rozpoznavame typy deklarovane atributom relation if ( dataName == edgeTypeAttribute_ ) { // overime ci uz dany typ existuje v grafe QList<Data::Type*> types = context_->getGraph().getTypesByName( dataValue+direction ); if ( types.isEmpty() ) { QMap<QString, QString>* settings = new QMap<QString, QString>; // FIXME spravit tak, aby to rotovalo po tom poli - palo az to budes prerabat tak pre hrany pouzi ine pole, take co ma alfu na 0.5.. a to sa tyka aj uzlov s defaultnym typom settings->insert( "color.R", QString::number( colors_[iColor_][0] ) ); settings->insert( "color.G", QString::number( colors_[iColor_][1] ) ); settings->insert( "color.B", QString::number( colors_[iColor_][2] ) ); settings->insert( "color.A", QString::number( colors_[iColor_][3] ) ); settings->insert( "scale", Util::ApplicationConfig::get()->getValue( "Viewer.Textures.DefaultNodeScale" ) ); if ( !directed ) { settings->insert( "textureFile", Util::ApplicationConfig::get()->getValue( "Viewer.Textures.Edge" ) ); } else { settings->insert( "textureFile", Util::ApplicationConfig::get()->getValue( "Viewer.Textures.OrientedEdgePrefix" ) ); settings->insert( "textureFile", Util::ApplicationConfig::get()->getValue( "Viewer.Textures.OrientedEdgeSuffix" ) ); } newEdgeType = context_->getGraph().addType( dataValue+direction, settings ); iColor_++; if ( iColor_ == colors_.size() ) { iColor_ = 0; } } else { newEdgeType = types.first(); } } else { // kazde dalsie data nacitame do nosica dat - Edge.name // FIXME potom prerobit cez Adamove Node.settings } } } // ak nebol najdeny typ, tak pouzijeme defaulty if ( newEdgeType == NULL ) { newEdgeType = edgeType_; } context_->getGraph().addEdge( sourceId+targetId, readNodes_->get( sourceId ), readNodes_->get( targetId ), newEdgeType, directed ); // vnorene grafy for ( QDomElement subgraphElement = edgeElement.firstChildElement( "graph" ); ok && !subgraphElement.isNull(); subgraphElement = subgraphElement.nextSiblingElement( "graph" ) ) { if ( ok ) { // TODO: begin subgraph in edge } if ( ok ) { ok = processGraph( subgraphElement ); } if ( ok ) { // TODO: end subgraph in edge } } entitiesProcessed_++; context_->getInfoHandler().setProgress( static_cast<unsigned int>( entitiesProcessed_ * 100 / entitiesCount_ ) ); } return ok; }
void ExerciseWindow::XMLtoCode(QTextStream &text, QDomNode &node, int num_of_spaces) { QString space = ""; for (int i = 0; i < num_of_spaces; i++) { space += " "; } QDomNode domNode = node.firstChild(); while(!domNode.isNull()) { if (domNode.isElement()) { QDomElement domElement = domNode.toElement(); if (!domElement.isNull()) { //if (domElement.tagName() == "Body") loadFlowChart(widget, domElement); if (domElement.tagName() == "Left" || domElement.tagName() == "Right" || domElement.tagName() == "Body") XMLtoCode(text, domElement, num_of_spaces); if (domElement.tagName() != "FCLine" && domElement.tagName() != "Left" && domElement.tagName() != "Right" && domElement.tagName() != "Body") { QString line = domElement.attribute("text"); if (domElement.tagName() == "FCBeginWidget") { if (openFromNewLine) text << endl << "{" << endl; else text << " {" << endl; for (int i = 0; i < vars.size(); i++) { QString variable = vars[i]; text << space + "int " + variable + " = 0;" << endl; } } else if (domElement.tagName() == "FCActionWidget") text << space + line + ";" << endl; else if (domElement.tagName() == "FCInputWidget") text << space + "cin >> " + line + ";" << endl; else if (domElement.tagName() == "FCOutputWidget") text << space + "cout << " + line + ";" << endl; else if (domElement.tagName() == "FCDivarWidget") { text << space + "if (" + line + ")"; if (openFromNewLine) text << endl << space + "{" << endl; else text << " {" << endl; XMLtoCode(text, domElement, num_of_spaces + 5); text << space + "}" << endl; } else if (domElement.tagName() == "FCPrefixCycleWidget") { text << space + "while (" + line + ")"; if (openFromNewLine) text << endl << space + "{" << endl; else text << " {" << endl; XMLtoCode(text, domElement, num_of_spaces + 5); text << space + "}" << endl; } else if (domElement.tagName() == "FCPostfixCycleWidget") { text << space + "do"; if (openFromNewLine) text << endl << space + "{" << endl; else text << " {" << endl; XMLtoCode(text, domElement, num_of_spaces + 5); text << space + "} while (" + line + ");" << endl; } else if (domElement.tagName() == "FCParameterCycleWidget") { text << space + "for (" + line + ")"; if (openFromNewLine) text << endl << space + "{" << endl; else text << " {" << endl; XMLtoCode(text, domElement, num_of_spaces + 5); text << space + "}" << endl; } else if (domElement.tagName() == "FCEndWidget") text << "}" << endl; } } if (domElement.tagName() == "Left") { space = ""; for (int i = 0; i < num_of_spaces - 5; i++) { space += " "; } text << space + "} else"; if (openFromNewLine) text << endl << space + "{" << endl; else text << " {" << endl; } } domNode = domNode.nextSibling(); } }
bool GraphMLImporter::import( ImporterContext& context ) { // context context_ = &context; // helpers graphOp_.reset( new GraphOperations( context_->getGraph() ) ); readNodes_.reset( new ReadNodesStore() ); // default types edgeType_ = NULL; nodeType_ = NULL; ( void )graphOp_->addDefaultTypes( edgeType_, nodeType_ ); // ziskame pristup ku nastaveniam Util::ApplicationConfig* appConf = Util::ApplicationConfig::get(); edgeTypeAttribute_ = appConf->getValue( "GraphMLParser.edgeTypeAttribute" ); nodeTypeAttribute_ = appConf->getValue( "GraphMLParser.nodeTypeAttribute" ); // pole farieb FIXME oddelit farby hran od farieb uzlov colors_.push_back( ColorType( 0, 1, 0, 1 ) ); colors_.push_back( ColorType( 0, 1, 1, 1 ) ); colors_.push_back( ColorType( 1, 0, 0, 1 ) ); colors_.push_back( ColorType( 1, 0, 1, 1 ) ); colors_.push_back( ColorType( 1, 1, 0, 1 ) ); colors_.push_back( ColorType( 1, 1, 1, 1 ) ); iColor_ = 0; bool ok = true; // ziskame graph element QDomElement graphElement; if ( ok ) { QDomNode graphNode; QDomDocument doc( "graphMLDocument" ); if ( doc.setContent( &( context_->getStream() ) ) ) { QDomElement docElem = doc.documentElement(); if ( !docElem.isNull() && docElem.nodeName() == "graphml" ) { QDomNodeList graphNodes = docElem.elementsByTagName( "graph" ); if ( graphNodes.length() > 0 ) { graphNode = graphNodes.item( 0 ); if ( !graphNode.isNull() && graphNode.parentNode() == docElem && graphNode.isElement() ) { graphElement = graphNode.toElement(); } } } } ok = !graphElement.isNull(); context_->getInfoHandler().reportError( ok, "Zvoleny subor nie je validny GraphML subor." ); } if ( ok ) { // for progress reporting entitiesProcessed_ = 0; entitiesCount_ = graphElement.elementsByTagName( "node" ).size() + graphElement.elementsByTagName( "edge" ).count(); } if ( ok ) { ok = processGraph( graphElement ); } return ok; }
bool SVT_Soap::_doFunc(const QString &host, const QString &module, const QString &method, quint32 port, const QMap<QString, QString> *paras, QMap<QString, QString> *retmap){ if((mFlags&IS_CGDG) ||isSetApi(module,method)) { sendStart(host,port); } if(retmap) { retmap->clear(); } const char *cHeadMode="POST /soap/server_sa/ HTTP/1.0\r\n" "SOAPAction: urn:NETGEAR-ROUTER:service:%1:1#%2\r\n" "content-type: text/xml;charset=utf-8\r\n" "HOST: www.routerlogin.com\r\n" "User-Agent: SOAP Toolkit 3.0\r\n" "connection: keep-Alive\r\n" "Cache-Control: no-cache\r\n" "Pragma: no-cache\r\n" "content-length: %3\r\n\r\n"; const char *cBodyMode= "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>" "<SOAP-ENV:Envelope xmlns:SOAPSDK1=\"http://www.w3.org/2001/XMLSchema\" " "xmlns:SOAPSDK2=\"http://www.w3.org/2001/XMLSchema-instance\" " "xmlns:SOAPSDK3=\"http://schemas.xmlsoap.org/soap/encoding/\" " "xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\">" "<SOAP-ENV:Header>" "<SessionID>58DEE6006A88A967E89A</SessionID>" "</SOAP-ENV:Header>" "<SOAP-ENV:Body>" "<M1:%2 xmlns:M1=\"urn:NETGEAR-ROUTER:service:%1:1\">" "%3" "</M1:%2>" "</SOAP-ENV:Body>" "</SOAP-ENV:Envelope>"; QString s_para=""; if(paras) { QMap<QString, QString>::const_iterator i = paras->begin(); while (i != paras->end()) { s_para+=QString("<%1>%2</%1>").arg(i.key(),i.value()); ++i; } } QString body=QString(cBodyMode).arg(module,method,s_para); QString head=QString(cHeadMode).arg(module,method).arg(body.length()); if(0==module.compare("ParentalControl",Qt::CaseInsensitive)) { cHeadMode="POST /soap/server_sa/ HTTP/1.0\r\n" "SOAPAction: urn:NETGEAR-ROUTER:service:%1:1#%2\r\n" "content-type: text/xml;charset=utf-8\r\n" "HOST: www.routerlogin.com\r\n" "User-Agent: SOAP Toolkit 3.0\r\n" "connection: keep-Alive\r\n" "Cache-Control: no-cache\r\n" "Pragma: no-cache\r\n" "content-length: %3\r\n\r\n"; cBodyMode="<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\">\n" "<SOAP-ENV:Header>\n" "<SessionID xsi:type=\"xsd:string\" xmlns:xsi=\"http://www.w3.org/1999/XMLSchema-instance\">E6A88AE69687E58D9A00</SessionID>\n" "</SOAP-ENV:Header>\n" "<SOAP-ENV:Body>\n" "<%1>\n" "%2" "</%1>\n" "</SOAP-ENV:Body>\n" "</SOAP-ENV:Envelope>\n"; const char *cParaString=" xsi:type=\"xsd:string\" xmlns:xsi=\"http://www.w3.org/1999/XMLSchema-instance\""; s_para=""; if(paras) { QMap<QString, QString>::const_iterator i = paras->begin(); while (i != paras->end()) { s_para+=QString("<%1%3>%2</%1>\n").arg(i.key(),i.value(),cParaString); ++i; } } body=QString(cBodyMode).arg(method,s_para); head=QString(cHeadMode).arg(module,method).arg(body.length()); } SVT_Http http(mExitFlag); QByteArray &retarray=http.rawRequest(host,head+body,port); qDebug()<<retarray; int retv=getRetValue(retarray); bool retOk=(200==retv); if(retOk && retmap) { qDebug()<<"start parse"; QDomDocument doc; QByteArray body=SVT_Http::getBody(retarray); doc.setContent(body,true); // QDomNode root=doc.namedItem() // doc. //QString tagname=method+"Response"; QDomNode rnode = doc.firstChild(); if (!rnode.isElement()) rnode = rnode.nextSibling(); parseNode(rnode,retmap); } if((retOk)&&((mFlags&IS_CGDG) ||isSetApi(module,method))) { sendFinish(host,port); } if(!retOk && retmap) { retmap->insert("error",QString::number(retv)); } return retOk; }
bool MyMoneyReport::read(const QDomElement& e) { // The goal of this reading method is 100% backward AND 100% forward // compatibility. Any report ever created with any version of KMyMoney // should be able to be loaded by this method (as long as it's one of the // report types supported in this version, of course) bool result = false; if ( "REPORT" == e.tagName() && ( (e.attribute("type").indexOf("pivottable 1.") == 0) || (e.attribute("type").indexOf("querytable 1.") == 0) || (e.attribute("type").indexOf("infotable 1.") == 0) ) ) { result = true; clear(); int i; m_name = e.attribute("name"); m_comment = e.attribute("comment", "Extremely old report"); //set report type if (!e.attribute("type").indexOf("pivottable")) { m_reportType = MyMoneyReport::ePivotTable; } else if (!e.attribute("type").indexOf("querytable")) { m_reportType = MyMoneyReport::eQueryTable; } else if (!e.attribute("type").indexOf("infotable")) { m_reportType = MyMoneyReport::eInfoTable; } else { m_reportType = MyMoneyReport::eNoReport; } // Removed the line that screened out loading reports that are called // "Default Report". It's possible for the user to change the comment // to this, and we'd hate for it to break as a result. m_group = e.attribute("group"); m_id = e.attribute("id"); //check for reports with older settings which didn't have the detail attribute if (e.hasAttribute("detail")) { i = kDetailLevelText.indexOf(e.attribute("detail", "all")); if (i != -1) m_detailLevel = static_cast<EDetailLevel>(i); } else if (e.attribute("showsubaccounts", "0").toUInt()) { //set to show all accounts m_detailLevel = eDetailAll; } else { //set to show the top level account instead m_detailLevel = eDetailTop; } m_convertCurrency = e.attribute("convertcurrency", "1").toUInt(); m_favorite = e.attribute("favorite", "0").toUInt(); m_tax = e.attribute("tax", "0").toUInt(); m_investments = e.attribute("investments", "0").toUInt(); m_loans = e.attribute("loans", "0").toUInt(); m_includeSchedules = e.attribute("includeschedules", "0").toUInt(); m_columnsAreDays = e.attribute("columnsaredays", "0").toUInt(); m_includeTransfers = e.attribute("includestransfers", "0").toUInt(); if (e.hasAttribute("budget")) m_budgetId = e.attribute("budget"); m_includeBudgetActuals = e.attribute("includesactuals", "0").toUInt(); m_includeUnusedAccounts = e.attribute("includeunused", "0").toUInt(); m_includeForecast = e.attribute("includesforecast", "0").toUInt(); m_includePrice = e.attribute("includesprice", "0").toUInt(); m_includeAveragePrice = e.attribute("includesaverageprice", "0").toUInt(); m_mixedTime = e.attribute("mixedtime", "0").toUInt(); m_includeMovingAverage = e.attribute("includesmovingaverage", "0").toUInt(); m_skipZero = e.attribute("skipZero", "0").toUInt(); if (m_includeMovingAverage) m_movingAverageDays = e.attribute("movingaveragedays", "1").toUInt(); //only load chart data if it is a pivot table m_chartType = static_cast<EChartType>(0); if (m_reportType == ePivotTable) { i = kChartTypeText.indexOf(e.attribute("charttype")); if (i >= 0) m_chartType = static_cast<EChartType>(i); // if it is invalid, set to first type if (m_chartType >= eChartEnd) m_chartType = eChartLine; m_chartDataLabels = e.attribute("chartdatalabels", "1").toUInt(); m_chartGridLines = e.attribute("chartgridlines", "1").toUInt(); m_chartByDefault = e.attribute("chartbydefault", "0").toUInt(); m_chartLineWidth = e.attribute("chartlinewidth", QString(m_lineWidth)).toUInt(); } else { m_chartDataLabels = true; m_chartGridLines = true; m_chartByDefault = false; m_chartLineWidth = 1; } QString datelockstr = e.attribute("datelock", "userdefined"); // Handle the pivot 1.2/query 1.1 case where the values were saved as // numbers bool ok = false; i = datelockstr.toUInt(&ok); if (!ok) { i = kDateLockText.indexOf(datelockstr); if (i == -1) i = userDefined; } setDateFilter(static_cast<dateOptionE>(i)); i = kRowTypeText.indexOf(e.attribute("rowtype", "expenseincome")); if (i != -1) { setRowType(static_cast<ERowType>(i)); // recent versions of KMyMoney always showed a total column for // income/expense reports. We turn it on for backward compatibility // here. If the total column is turned off, the flag will be reset // in the next step if (i == eExpenseIncome) m_showRowTotals = true; } if (e.hasAttribute("showrowtotals")) m_showRowTotals = e.attribute("showrowtotals").toUInt(); i = kColumnTypeText.indexOf(e.attribute("columntype", "months")); if (i != -1) setColumnType(static_cast<EColumnType>(i)); unsigned qc = 0; QStringList columns = e.attribute("querycolumns", "none").split(','); QStringList::const_iterator it_column = columns.constBegin(); while (it_column != columns.constEnd()) { i = kQueryColumnsText.indexOf(*it_column); if (i > 0) qc |= (1 << (i - 1)); ++it_column; } setQueryColumns(static_cast<EQueryColumns>(qc)); QDomNode child = e.firstChild(); while (!child.isNull() && child.isElement()) { QDomElement c = child.toElement(); if ("TEXT" == c.tagName() && c.hasAttribute("pattern")) { setTextFilter(QRegExp(c.attribute("pattern"), c.attribute("casesensitive", "1").toUInt() ? Qt::CaseSensitive : Qt::CaseInsensitive, c.attribute("regex", "1").toUInt() ? QRegExp::Wildcard : QRegExp::RegExp), c.attribute("inverttext", "0").toUInt()); } if ("TYPE" == c.tagName() && c.hasAttribute("type")) { i = kTypeText.indexOf(c.attribute("type")); if (i != -1) addType(i); } if ("STATE" == c.tagName() && c.hasAttribute("state")) { i = kStateText.indexOf(c.attribute("state")); if (i != -1) addState(i); } if ("NUMBER" == c.tagName()) { setNumberFilter(c.attribute("from"), c.attribute("to")); } if ("AMOUNT" == c.tagName()) { setAmountFilter(MyMoneyMoney(c.attribute("from", "0/100")), MyMoneyMoney(c.attribute("to", "0/100"))); } if ("DATES" == c.tagName()) { QDate from, to; if (c.hasAttribute("from")) from = QDate::fromString(c.attribute("from"), Qt::ISODate); if (c.hasAttribute("to")) to = QDate::fromString(c.attribute("to"), Qt::ISODate); MyMoneyTransactionFilter::setDateFilter(from, to); } if ("PAYEE" == c.tagName()) { addPayee(c.attribute("id")); } if ("TAG" == c.tagName()) { addTag(c.attribute("id")); } if ("CATEGORY" == c.tagName() && c.hasAttribute("id")) { addCategory(c.attribute("id")); } if ("ACCOUNT" == c.tagName() && c.hasAttribute("id")) { addAccount(c.attribute("id")); } if ("ACCOUNTGROUP" == c.tagName() && c.hasAttribute("group")) { i = kAccountTypeText.indexOf(c.attribute("group")); if (i != -1) addAccountGroup(static_cast<MyMoneyAccount::accountTypeE>(i)); } child = child.nextSibling(); } } return result; }
void ConfigManager::loadConfigFile() { // read the XML file and create DOM tree QFile cfg_file( m_lmmsRcFile ); QDomDocument dom_tree; if( cfg_file.open( QIODevice::ReadOnly ) ) { QString errorString; int errorLine, errorCol; if( dom_tree.setContent( &cfg_file, false, &errorString, &errorLine, &errorCol ) ) { // get the head information from the DOM QDomElement root = dom_tree.documentElement(); QDomNode node = root.firstChild(); // Cache the config version for upgrade() if ( !root.attribute( "version" ).isNull() ) { m_version = root.attribute( "version" ); } // create the settings-map out of the DOM while( !node.isNull() ) { if( node.isElement() && node.toElement().hasAttributes () ) { stringPairVector attr; QDomNamedNodeMap node_attr = node.toElement().attributes(); for( int i = 0; i < node_attr.count(); ++i ) { QDomNode n = node_attr.item( i ); if( n.isAttr() ) { attr.push_back( qMakePair( n.toAttr().name(), n.toAttr().value() ) ); } } m_settings[node.nodeName()] = attr; } else if( node.nodeName() == "recentfiles" ) { m_recentlyOpenedProjects.clear(); QDomNode n = node.firstChild(); while( !n.isNull() ) { if( n.isElement() && n.toElement().hasAttributes() ) { m_recentlyOpenedProjects << n.toElement().attribute( "path" ); } n = n.nextSibling(); } } node = node.nextSibling(); } if( value( "paths", "artwork" ) != "" ) { m_artworkDir = value( "paths", "artwork" ); if( !QDir( m_artworkDir ).exists() ) { m_artworkDir = defaultArtworkDir(); } if( m_artworkDir.right( 1 ) != QDir::separator() ) { m_artworkDir += QDir::separator(); } } setWorkingDir( value( "paths", "workingdir" ) ); setGIGDir( value( "paths", "gigdir" ) == "" ? gigDir() : value( "paths", "gigdir" ) ); setSF2Dir( value( "paths", "sf2dir" ) == "" ? sf2Dir() : value( "paths", "sf2dir" ) ); setVSTDir( value( "paths", "vstdir" ) ); setFLDir( value( "paths", "fldir" ) ); setLADSPADir( value( "paths", "laddir" ) ); #ifdef LMMS_HAVE_STK setSTKDir( value( "paths", "stkdir" ) ); #endif #ifdef LMMS_HAVE_FLUIDSYNTH setDefaultSoundfont( value( "paths", "defaultsf2" ) ); #endif setBackgroundArtwork( value( "paths", "backgroundartwork" ) ); } else if( gui ) { QMessageBox::warning( NULL, MainWindow::tr( "Configuration file" ), MainWindow::tr( "Error while parsing configuration file at line %1:%2: %3" ). arg( errorLine ). arg( errorCol ). arg( errorString ) ); } cfg_file.close(); } if( m_vstDir.isEmpty() || m_vstDir == QDir::separator() || !QDir( m_vstDir ).exists() ) { #ifdef LMMS_BUILD_WIN32 QString programFiles = QString::fromLocal8Bit( getenv( "ProgramFiles" ) ); m_vstDir = programFiles + QDir::separator() + "VstPlugins" + QDir::separator(); #else m_vstDir = m_workingDir + "plugins/vst/"; #endif } if( m_flDir.isEmpty() || m_flDir == QDir::separator() ) { m_flDir = ensureTrailingSlash( QDir::home().absolutePath() ); } if( m_ladDir.isEmpty() || m_ladDir == QDir::separator() || ( !m_ladDir.contains( ':' ) && !QDir( m_ladDir ).exists() ) ) { #if defined(LMMS_BUILD_WIN32) m_ladDir = qApp->applicationDirPath() + "/plugins/ladspa" + QDir::separator(); #elif defined(LMMS_BUILD_APPLE) m_ladDir = qApp->applicationDirPath() + "/../lib/lmms/ladspa/"; #else m_ladDir = qApp->applicationDirPath() + '/' + LIB_DIR + "/ladspa/"; #endif m_ladDir += ","+userLadspaDir(); } #ifdef LMMS_HAVE_STK if( m_stkDir.isEmpty() || m_stkDir == QDir::separator() || !QDir( m_stkDir ).exists() ) { #if defined(LMMS_BUILD_WIN32) m_stkDir = m_dataDir + "stk/rawwaves/"; #elif defined(LMMS_BUILD_APPLE) m_stkDir = qApp->applicationDirPath() + "/../share/stk/rawwaves/"; #else m_stkDir = "/usr/share/stk/rawwaves/"; #endif } #endif QStringList searchPaths; if(! qgetenv("LMMS_THEME_PATH").isNull()) searchPaths << qgetenv("LMMS_THEME_PATH"); searchPaths << artworkDir() << defaultArtworkDir(); QDir::setSearchPaths( "resources", searchPaths); if( !QDir( m_workingDir ).exists() && gui && QMessageBox::question( 0, MainWindow::tr( "Working directory" ), MainWindow::tr( "The LMMS working directory %1 does not " "exist. Create it now? You can change the directory " "later via Edit -> Settings." ).arg( m_workingDir ), QMessageBox::Yes, QMessageBox::No ) == QMessageBox::Yes ) { QDir().mkpath( m_workingDir ); } if( QDir( m_workingDir ).exists() ) { QDir().mkpath( userProjectsDir() ); QDir().mkpath( userTemplateDir() ); QDir().mkpath( userSamplesDir() ); QDir().mkpath( userPresetsDir() ); QDir().mkpath( userGigDir() ); QDir().mkpath( userSf2Dir() ); QDir().mkpath( userVstDir() ); QDir().mkpath( userLadspaDir() ); } upgrade(); }
//得到音乐(xml格式) void DownloadThread::slot_GetMusicXML(QNetworkReply *replay) { QTextCodec *codec = QTextCodec::codecForName("utf8");//转换成utf8编码格式 QString musicStr = codec ->toUnicode(replay ->readAll()); //没有连接到网络 if (musicStr == "") { QMessageBox::information(NULL, tr("信息"), tr("下载超时,请检查您的网络或者本机防火墙设置!"), QMessageBox::Yes); QString musicTitle = m_musicArtist + "-" + m_musicName; emit sig_DelCurrentMusicMapItem(musicTitle); return; } QString errorStr; int errorLine; int errorColumn; QDomDocument doc; if (!doc.setContent(musicStr, false, &errorStr, &errorLine, &errorColumn)) { qDebug() << "在第" << errorLine << "行,第" << errorColumn << "列,读取字符串到doc中错误:" << errorStr; QMessageBox::information(NULL, tr("信息"), tr("没有找到该歌曲!"), QMessageBox::Yes); return; } QDomElement root = doc.documentElement();//获取根元素 if (root.tagName() != "result") { QMessageBox::information(NULL, tr("信息"), tr("没有找到该歌曲!"), QMessageBox::Yes); return; } //获取音乐url QString sFirstPartUrl; //前半部分 QString sLastPartUrl; //后半部分 QDomNodeList nodeList = root.childNodes();//获得root所有子节点的列表 for (int i = 0; i < nodeList.count(); ++i) { QDomNode node = nodeList.at(i); if (!node.isNull())//如果节点不为空 { if (node.isElement())//如果节点是元素 { QDomElement element = node.toElement();//转换成元素 if (element.tagName() == "count") { qDebug() << "element.text() = " << element.text(); if (element.text() == "0")//返回元素文本 { QMessageBox::information(NULL, tr("信息"), tr("没有找到该歌曲!"), QMessageBox::Yes); return; } } else if (element.tagName() == "url") { QDomNodeList nodeList2 = element.childNodes();//获得url所有子节点的列表 for (int i = 0; i < nodeList2.count(); ++i) { QDomNode node2 = nodeList2.at(i); if (!node2.isNull())//如果节点不为空 { if (node2.isElement())//如果节点是元素 { QDomElement element2 = node2.toElement();//转换成元素 if (element2.tagName() == "encode") { //qDebug() << element2.text(); sFirstPartUrl = element2.text(); } else if (element2.tagName() == "decode") { //qDebug() << element2.text(); sLastPartUrl = element2.text(); break; } } else { QMessageBox::information(NULL, tr("信息"), tr("没有找到该歌曲!"), QMessageBox::Yes); return; } } else { QMessageBox::information(NULL, tr("信息"), tr("没有找到该歌曲!"), QMessageBox::Yes); return; } } break; } } else { QMessageBox::information(NULL, tr("信息"), tr("没有找到该歌曲!"), QMessageBox::Yes); return; } } else { QMessageBox::information(NULL, tr("信息"), tr("没有找到该歌曲!"), QMessageBox::Yes); return; } } //判断是否包含xcode,防止歌曲下载错误! if (!sLastPartUrl.contains("xcode")) { QMessageBox::information(NULL, tr("信息"), tr("没有找到该歌曲!"), QMessageBox::Yes); return; } //音乐url QString musicUrl = sFirstPartUrl + sLastPartUrl; //qDebug() << musicUrl; #ifdef _WIN32_WINNT QString WINPATH = CZPlayerConfig::getValue("MUSICDIR_WIN").toString(); QString musicFilePath = WINPATH + "/" + m_musicArtist + " - " + m_musicName + ".mp3"; #else QString X11PATH = QDir::homePath() + CZPlayerConfig::getValue("MUSICDIR_X11").toString(); QString musicFilePath = X11PATH + "/" + m_musicArtist + " - " + m_musicName + ".mp3"; #endif //插入下载列表 int currentRows = m_downloadList ->rowCount();//返回列表中的行数 m_downloadList ->insertRow(currentRows);//从下载列表中的当前行插入 //进度条 progressBar = new QProgressBar; progressBar ->setObjectName(tr("progressBar")); timer ->start(1000); time ->start(); //歌曲名称 musicTitleItem = new QTableWidgetItem; musicTitleItem ->setText(m_musicArtist + "-" + m_musicName); musicTitleItem ->setTextAlignment(Qt::AlignCenter); musicTitleItem ->setToolTip(m_musicArtist + "-" + m_musicName); //歌曲状态 musicStatusItem = new QTableWidgetItem; musicStatusItem ->setTextAlignment(Qt::AlignCenter); musicStatusItem ->setText(tr("正在下载")); //大小 musicSizeItem = new QTableWidgetItem; musicSizeItem ->setTextAlignment(Qt::AlignCenter); //网速 speedItem = new QTableWidgetItem; speedItem ->setTextAlignment(Qt::AlignCenter); m_downloadList ->setItem(currentRows, 0, musicTitleItem); m_downloadList ->setItem(currentRows, 1, musicStatusItem); m_downloadList ->setItem(currentRows, 2, musicSizeItem); m_downloadList ->setItem(currentRows, 3, speedItem); m_downloadList ->setCellWidget(currentRows, 4, progressBar); static int index = 0; threadMap.insert(make_pair(index, this)); listMap.insert(make_pair(index, currentRows)); //emit musicListMap(listMap); m_downloadList ->setMusicListMap(listMap); ++index; this ->getMusicFromURL(musicUrl, musicFilePath); replay ->deleteLater();//最后要释放reply对象 }
void Uploader::requestFinished(QNetworkReply * reply) { // Did we have a network error? if (reply->error() != QNetworkReply::NoError) { emit uploadError(tr("Network error: %1").arg(reply->error())); reply->deleteLater(); return; } // Parse the reply QHash<int, QString> linksMap; QDomDocument doc; QString error; if (!doc.setContent(reply->readAll(), false, &error)) { emit uploadError(tr("Parse error: %1").arg(error)); reply->deleteLater(); return; } // See if we have an upload reply, or an error QDomElement rootElem = doc.documentElement(); error = ""; if (rootElem.tagName() == "upload") { // Skip all elements until we reach the <links> tag QDomNode n = rootElem.firstChild(); while (!n.isNull()) { if (n.isElement() && n.toElement().tagName() == "links") { QDomNode innerNode = n.firstChild(); while (!innerNode.isNull()) { if (innerNode.isElement()) { QDomElement e = innerNode.toElement(); if (e.tagName() == "original") { linksMap.insert(OriginalImage, e.text()); } else if (e.tagName() == "small_square") { linksMap.insert(SmallSquare, e.text()); } else if (e.tagName() == "large_thumbnail") { linksMap.insert(LargeThumbnail, e.text()); } else if (e.tagName() == "imgur_page") { linksMap.insert(ImgurPage, e.text()); } else if (e.tagName() == "delete_page") { linksMap.insert(DeletePage, e.text()); } } innerNode = innerNode.nextSibling(); } } n = n.nextSibling(); } } else if (rootElem.tagName() == "error") { // Skip all elements until we reach the <message> tag QDomNode n = rootElem.firstChild(); while (!n.isNull()) { if (n.isElement() && n.toElement().tagName() == "message") { error = n.toElement().text(); } n = n.nextSibling(); } } else { error = tr("Reccived unexpected reply from web service"); } if (!error.isEmpty()) { emit uploadError(error); } else { emit uploadDone(linksMap); } reply->deleteLater(); }
void FlickrTalker::parseResponseGetToken(const QByteArray& data) { bool success = false; QString errorString; QDomDocument doc("gettoken"); if (!doc.setContent(data)) { return; } QDomElement docElem = doc.documentElement(); QDomNode node = docElem.firstChild(); QDomElement e; while (!node.isNull()) { if (node.isElement() && node.nodeName() == "auth") { e = node.toElement(); // try to convert the node to an element. QDomNode details = e.firstChild(); while (!details.isNull()) { if (details.isElement()) { e = details.toElement(); if (details.nodeName() == "token") { kDebug() << "Token=" << e.text(); m_token = e.text(); //this is what is obtained from data. } if (details.nodeName() == "perms") { kDebug() << "Perms=" << e.text(); } if (details.nodeName() == "user") { kDebug() << "nsid=" << e.attribute("nsid"); kDebug() << "username="******"username"); kDebug() << "fullname=" << e.attribute("fullname"); m_username = e.attribute("username"); m_userId = e.attribute("nsid"); } } details = details.nextSibling(); } success = true; } else if (node.isElement() && node.nodeName() == "err") { kDebug() << "Checking Error in response"; errorString = node.toElement().attribute("code"); kDebug() << "Error code=" << errorString; kDebug() << "Msg=" << node.toElement().attribute("msg"); //emit signalError(code); } node = node.nextSibling(); } kDebug() << "GetToken finished"; //emit signalBusy( false ); m_authProgressDlg->hide(); if (success) { emit signalTokenObtained(m_token); } else { emit signalError(errorString); } }
static void ParseFile(QMap<QString, QString>& result, const QString& fileName, const QString& bankName) { QFile f(fileName); if (f.open(QIODevice::ReadOnly)) { QTextStream stream(&f); #if OFXHOME stream.setCodec("UTF-8"); QString msg; int errl, errc; QDomDocument doc; if (doc.setContent(stream.readAll(), &msg, &errl, &errc)) { QDomNodeList olist = doc.elementsByTagName("institutionid"); for (int i = 0; i < olist.count(); ++i) { QDomNode onode = olist.item(i); if (onode.isElement()) { QDomElement elo = onode.toElement(); QString name = elo.attribute("name"); if (bankName.isEmpty()) result[name].clear(); else if (name == bankName) { result[elo.attribute("id")].clear(); } } } } #endif #if MSN stream.setCodec("UTF-16"); QString msg; int errl, errc; QDomDocument doc; if (doc.setContent(stream.readAll(), &msg, &errl, &errc)) { QDomNodeList olist = doc.elementsByTagName("prov"); for (int i = 0; i < olist.count(); ++i) { QDomNode onode = olist.item(i); if (onode.isElement()) { bool collectGuid = false; QDomElement elo = onode.toElement(); QDomNodeList ilist = onode.childNodes(); for (int j = 0; j < ilist.count(); ++j) { QDomNode inode = ilist.item(j); QDomElement el = inode.toElement(); if (el.tagName() == "name") { if (bankName.isEmpty()) result[el.text()].clear(); else if (el.text() == bankName) { collectGuid = true; } } if (el.tagName() == "guid" && collectGuid) { result[el.text()].clear(); } } } } } #endif f.close(); } }
void FlickrTalker::parseResponseAddPhoto(const QByteArray& data) { bool success = false; QString line; QDomDocument doc("AddPhoto Response"); if (!doc.setContent(data)) { return; } QDomElement docElem = doc.documentElement(); QDomNode node = docElem.firstChild(); QDomElement e; QString photoId; while (!node.isNull()) { if (node.isElement() && node.nodeName() == "photoid") { e = node.toElement(); // try to convert the node to an element. QDomNode details = e.firstChild(); photoId = e.text(); kDebug() << "Photoid= " << photoId; success = true; } if (node.isElement() && node.nodeName() == "err") { kDebug() << "Checking Error in response"; QString code = node.toElement().attribute("code"); kDebug() << "Error code=" << code; kDebug() << "Msg=" << node.toElement().attribute("msg"); emit signalError(code); } node = node.nextSibling(); } if (!success) { emit signalAddPhotoFailed(i18n("Failed to upload photo")); } else { QString photoSetId = m_selectedPhotoSet.id; if (photoSetId == "-1") { kDebug() << "PhotoSet Id not set, not adding the photo to any photoset"; emit signalAddPhotoSucceeded(); } else { if (m_serviceName == "Zooomr") { // addPhotoToPhotoSet not supported by Zooomr (Zooomr only has // smart folder-type photosets); silently fail emit signalAddPhotoSucceeded(); } else { addPhotoToPhotoSet(photoId, photoSetId); } } } }
QString MessageValidator::validateMessage(QString message, bool* illformed, HTMLTextFormatter* formatter) { // qDebug() << "IMG val0" << message; QDomDocument doc("document"); *illformed = false; QString errorMessage; int line, column; QDomDocument tmpDoc; //used by textformatter xmlSource.setData(message); if (!doc.setContent(&xmlSource, &xmlReader, &errorMessage, &line, &column)) { qDebug() << errorMessage << " " << line << " " << column << message; *illformed = true; qDebug() << "WARNING: MessageValidator::validateMessage() - illformed message"; return "illformed message!!!"; } //now DOM tree will be traversed in preorder. QStack<QDomElement> stack; //current element, QStack is used to avoid possible stack overflow in ordinary recursion stack.push(doc.documentElement()); while (!stack.empty()) { QDomElement cur = stack.top(); stack.pop(); // Traverse through DOM Tree(cur), cut off bad elements/attributes // and format text nodes using textFormatter // qDebug() << QString(4, ' ') << cur.tagName(); QString parentName = cur.tagName(); NodeInfo curNI = allowed[parentName]; //delete disallowed attributes for (int i = 0; i < cur.attributes().count(); i++) { QString attrName = cur.attributes().item(i).toAttr().name(); if (!curNI.allowedAttributes.contains(attrName)) { // qDebug() << "VALIDATIN ERR" << "TA" << attrName << " in " << parentName; // qDebug() << "note allowed attributes are:" << curNI.allowedAttributes; cur.attributes().removeNamedItem(attrName); i--; } } QDomNodeList children = cur.childNodes(); for (int i = children.size() - 1; i >= 0; i--) { QDomNode node = children.at(i); if (node.isElement()) { QString childName = node.toElement().tagName(); if (childName == "a") { // always show hyperlink destination QString href = node.toElement().attribute("href"); node.appendChild(doc.createTextNode(" [ " + href + " ]")); } if (childName == "style") { //NOTE: this action is not XHTML-IM compliant! (css rules should be displayed, but it's stupid) cur.removeChild(node); } else if (childName == "img") { //disabling images until they are whitelisted QString href = node.toElement().attribute("src"); QDomElement newElement = doc.createElement("a"); newElement.setAttribute("class", "psi_disabled_image"); newElement.setAttribute("href", "javascript:psi_addToWhiteList('" + href + "')"); newElement.appendChild(doc.createTextNode("[ click here to display: " + href + " ]")); cur.replaceChild(newElement, node); } else if (!curNI.allowedTags.contains(childName)) {//is subElement valid here? qDebug() << "VALIDATIN ERR" << "TS" << childName << " in " << parentName; qDebug() << "note allowed subElements are:" << curNI.allowedTags; //append bad node's children (they will be validated in next loop iteration) int j = 0; while (node.hasChildNodes()) { cur.insertBefore(node.firstChild(), node); j++; } i = i + j; //j nodes were inserted //delete bad node cur.removeChild(node); } else { stack.push(node.toElement()); } } else if (node.isText() && !node.isCDATASection()) { if (!curNI.canHaveText) { cur.removeChild(node); } else { //format text QString formattedText = "<tmp>" + formatter->format(Qt::escape(node.toText().data()), cur) + "</tmp>"; //NOTE: we don't need to escape quotes, and we want this code be more reusable/decoupled, //NOTE: so we use Qt::escape() instead of TextUtil::escape() xmlSource.setData(formattedText); tmpDoc.setContent(&xmlSource, &xmlReader); QDomNode tmpElement = tmpDoc.firstChild(); while (tmpElement.hasChildNodes()) { //append <tmp>'s children. They won't be validated cur.insertBefore(tmpElement.firstChild(), node); } cur.removeChild(node); } } }//foreach child } //stack/dfs // qDebug() << "IMG MV:" << doc.toString(0); return doc.toString(0); }
void ScreenWidget::loadPressed() { QString fileName = QFileDialog::getOpenFileName(this, tr("Load Scene"), "",tr("DSS XML Scene File (*.xml);;All Files (*)")); if (fileName.isEmpty()) { return; } else { QDomDocument doc("loadedscene"); QFile file(fileName); if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) { return; } if (!doc.setContent(&file)) { file.close(); return; } file.close(); QDomElement scene = doc.documentElement(); qDebug()<<scene.text(); QDomNode field=scene.firstChildElement("field"); if (field.isElement()) { this->scene->addField(field.firstChildElement("width").text().toUInt(),field.firstChildElement("height").text().toUInt()); } QDomNode targetEntity = scene.firstChildElement("targetEntity"); if (targetEntity.isElement()) { TargetEntity* newTargetEntity = new TargetEntity(); Point2i targetPos(targetEntity.firstChildElement("x").text().toInt(),targetEntity.firstChildElement("y").text().toInt()); this->scene->setTargetEntity(newTargetEntity,targetPos); } QDomNode entities = scene.firstChildElement("entities"); if (entities.isElement()) { QDomNodeList entityList =entities.toElement().elementsByTagName("entity"); for(int i=0;i<entityList.count();i++) { QDomElement entity = entityList.at(i).toElement(); int type = entity.firstChildElement("type").text().toInt(); Point2i entityPos(entity.firstChildElement("x").text().toInt(),entity.firstChildElement("y").text().toInt()); this->scene->addEntityAtPosition(type,entityPos); } } /* for(int i=0;i<fieldList.count();i++) { QDomElement field = fieldList.at(i).toElement(); qDebug()<<field.attribute("width"); qDebug()<<field.attribute("height"); QDomNodeList lll=e1.elementsByTagName("a"); qDebug(QString::number(lll.count()).toAscii()); for(int j=0;j<lll.count();j++) { QDomElement e2 = lll.at(j).toElement(); qDebug(e2.tagName().toAscii()+" "+e2.attribute("ITEM").toAscii()); QDomNodeList llll=e2.elementsByTagName("b"); for(int k=0;k<llll.count();k++) { QDomElement e3 = llll.at(k).toElement(); qDebug(e3.tagName().toAscii()+" "+e3.text().toAscii()); } } } */ } }
int YourPayProcessor::handleResponse(const QString &presponse, const int pccardid, const QString &ptype, const double pamount, const int pcurrid, QString &pneworder, QString &preforder, int &pccpayid, ParameterList &pparams) { if (DEBUG) qDebug("YP::handleResponse(%s, %d, %s, %f, %d, %s, %d, pparams)", presponse.toAscii().data(), pccardid, ptype.toAscii().data(), pamount, pcurrid, preforder.toAscii().data(), pccpayid); QDomDocument response; // YP doesn't even send back a valid XML doc! response.setContent("<yp_wrapper>" + presponse + "</yp_wrapper>"); QDomNode node; QDomElement root = response.documentElement(); QString r_approved; QString r_avs; QString r_code; QString r_error; QString r_message; QString r_ordernum; QString r_ref; QString r_score; QString r_shipping; QString r_tax; QString r_tdate; QString r_time; QString status; node = root.firstChild(); while ( !node.isNull() ) { if (node.isElement()) { if (node.nodeName() == "r_approved" ) r_approved = node.toElement().text(); else if (node.nodeName() == "r_avs" ) r_avs = node.toElement().text(); else if (node.nodeName() == "r_code" ) r_code = node.toElement().text(); else if (node.nodeName() == "r_error" ) r_error = node.toElement().text(); else if (node.nodeName() == "r_message" ) r_message = node.toElement().text(); else if (node.nodeName() == "r_ordernum" ) r_ordernum = node.toElement().text(); else if (node.nodeName() == "r_ref" ) r_ref = node.toElement().text(); else if (node.nodeName() == "r_score" ) r_score = node.toElement().text(); else if (node.nodeName() == "r_shipping" ) r_shipping = node.toElement().text(); else if (node.nodeName() == "r_tax" ) r_tax = node.toElement().text(); else if (node.nodeName() == "r_tdate" ) r_tdate = node.toElement().text(); else if (node.nodeName() == "r_time" ) r_time = node.toElement().text(); } node = node.nextSibling(); } if (isTest()) { // in test mode YP doesn't send an approval code if (r_approved == "APPROVED" && r_code.isEmpty()) r_code = "12345"; // inject failures to test AVS and CVV checking but ONLY IN TEST MODE if (r_avs.isEmpty() && _metrics->value("CCTestResult") == "S") { switch (qrand() % 50) { case 0: r_avs = "NN"; break; case 1: r_avs = "XN"; break; case 2: r_avs = "YN"; break; case 3: r_avs = "NX"; break; case 4: r_avs = "XX"; break; case 5: r_avs = "YX"; break; default: r_avs = "YY"; break; } switch (qrand() % 50) { case 0: r_avs += "N"; break; case 1: r_avs += "P"; break; case 2: r_avs += "S"; break; case 3: r_avs += "U"; break; default: r_avs += "M"; break; } } } int returnValue = 0; if (r_approved == "APPROVED") { _errorMsg = errorMsg(0).arg(r_ref); if (ptype == "A") status = "A"; // Authorized else if (ptype == "V") status = "V"; // Voided else status = "C"; // Completed/Charged } else if (r_approved == "DENIED") { _errorMsg = errorMsg(10).arg(r_message); returnValue = 10; status = "D"; } else if (r_approved == "DUPLICATE") { _errorMsg = errorMsg(11).arg(r_message); returnValue = 11; status = "D"; } else if (r_approved == "DECLINED") { _errorMsg = errorMsg(12).arg(r_error); returnValue = 12; status = "D"; } else if (r_approved == "FRAUD") { _errorMsg = errorMsg(13).arg(r_error); returnValue = 13; status = "D"; } else if (r_approved.isEmpty()) { _errorMsg = errorMsg(-100) .arg(r_error).arg(r_message).arg(presponse); returnValue = -100; status = "X"; } // YP encodes AVS and CVV checking in the r_avs response field QRegExp avsRegExp("^[" + _metrics->value("CCAvsAddr") + "][" + _metrics->value("CCAvsZIP") + "]"); _passedAvs = _metrics->value("CCAvsCheck") == "X" || ! r_avs.contains(avsRegExp); // avsregexp matches failures _passedCvv = _metrics->value("CCCVVCheck") == "X" || ! r_avs.contains(QRegExp("[" + _metrics->value("CCCVVErrors") + "]$")); _passedLinkShield = (! _metrics->boolean("CCYPLinkShield")) || (! r_score.isEmpty() && r_score.toInt() <= _metrics->value("CCYPLinkShieldMax").toInt()); if (DEBUG) qDebug("YP:%s\t_passedAvs %d\t_passedCvv %d\t_passedLinkShield %d", r_avs.toAscii().data(), _passedAvs, _passedCvv, _passedLinkShield); pparams.append("ccard_id", pccardid); pparams.append("auth_charge", ptype); pparams.append("type", ptype); pparams.append("reforder", preforder.isEmpty() ? pneworder : preforder); pparams.append("status", status); pparams.append("avs", r_avs); pparams.append("ordernum", pneworder); pparams.append("xactionid", r_ordernum.isEmpty() ? pneworder : r_ordernum); pparams.append("error", r_error); pparams.append("approved", r_approved); pparams.append("code", r_code); pparams.append("score", r_score.toInt()); pparams.append("shipping", r_shipping); pparams.append("tax", r_tax); pparams.append("tdate", r_tdate); pparams.append("ref", r_ref); pparams.append("message", r_message); if (pcurrid != _ypcurrid) { pparams.append("fromcurr", pcurrid); pparams.append("tocurr", _ypcurrid); } else pparams.append("currid", pcurrid); if (ptype == "A") pparams.append("auth", QVariant(true, 0)); else pparams.append("auth", QVariant(false, 1)); if (! r_time.isEmpty()) pparams.append("time", r_time); if (DEBUG) qDebug("YP:r_error.isEmpty() = %d", r_error.isEmpty()); if (! r_error.isEmpty()) { _errorMsg = errorMsg(-12).arg(r_error); returnValue = -12; } if (returnValue == 0) pparams.append("amount", pamount); else pparams.append("amount", 0); // no money changed hands this attempt return returnValue; }
void XMLPreferences::loadPreferences(const QString& filename, PrefSectionDict& dict) { QDomDocument doc(seqPrefName); QFile f(filename); if (!f.open(IO_ReadOnly)) { qWarning("Unable to open file: %s!", (const char*)filename); return; } QString errorMsg; int errorLine = 0; int errorColumn = 0; if (!doc.setContent(&f, false, &errorMsg, &errorLine, &errorColumn)) { qWarning("Error processing file: %s!\n\t %s on line %d in column %d!", (const char*)filename, (const char*)errorMsg, errorLine, errorColumn); f.close(); return; } // do more processing here QDomElement docElem = doc.documentElement(); DomConvenience conv(doc); QDomNodeList sectionList, propertyList; PreferenceDict* sectionDict; CommentDict* commentSectionDict; QString comment; QString* commentVal; QDomElement section; QDomElement property; QString sectionName; QString propertyName; QDomNode n; QDomElement valueElement; bool foundValue; sectionList = doc.elementsByTagName("section"); for (uint i = 0; i < sectionList.length(); i++) { section = sectionList.item(i).toElement(); if (!section.hasAttribute("name")) { qWarning("section without name!"); continue; } sectionName = section.attribute("name"); // see if the section exists in the dictionary sectionDict = dict.find(sectionName); // if not, then create it if (sectionDict == NULL) { // create the new preference dictionary sectionDict = new PreferenceDict(preferenceHashSize); // make sure the dictionary deletes removed properties sectionDict->setAutoDelete(true); // insert the preference dictionary into the section dict.insert(sectionName, sectionDict); } // see if comment section exists in the dictionary commentSectionDict = m_commentSections.find(sectionName); // if not, then create it if (commentSectionDict == NULL) { // create the new preference dictionary commentSectionDict = new CommentDict(preferenceHashSize); // make sure the dictionary deletes removed properties commentSectionDict->setAutoDelete(true); // insert the preference dictionary into the section m_commentSections.insert(sectionName, commentSectionDict); } propertyList = section.elementsByTagName("property"); for (uint j = 0; j < propertyList.length(); j++) { property = propertyList.item(j).toElement(); if (!property.hasAttribute("name")) { qWarning("property in section '%s' without name! Ignoring!", (const char*)sectionName); continue; } propertyName = property.attribute("name"); foundValue = false; QVariant value; // iterate over the nodes under the property for (n = property.firstChild(); !n.isNull(); n = n.nextSibling()) { if (!n.isElement()) continue; valueElement = n.toElement(); if (valueElement.tagName() == "comment") { // get comment if any comment = valueElement.text(); // if there is a comment, cache it if (!comment.isEmpty()) { commentVal = commentSectionDict->find(propertyName); if (commentVal != NULL) *commentVal = comment; else commentSectionDict->insert(propertyName, new QString(comment)); } continue; } if (!conv.elementToVariant(valueElement, value)) { qWarning("property '%s' in section '%s' with bogus value in tag '%s'!" " Ignoring!", (const char*)propertyName, (const char*)sectionName, (const char*)valueElement.tagName()); continue; } // found the value foundValue = true; // insert value into the section dictionary sectionDict->insert(propertyName, new QVariant(value)); break; } #if 0 // ZBTEMP : Support properties without values to get comments? if (!foundValue) { qWarning("property '%s' in section '%s' without value! Ignoring!", (const char*)propertyName, (const char*)sectionName); continue; } #endif } } // close the file f.close(); #if 1 // ZBTEMP printf("Loaded preferences file: %s!\n", (const char*)filename); #endif }
bool RCCResourceLibrary::interpretResourceFile(QIODevice *inputDevice, const QString &fname, QString currentPath, bool ignoreErrors) { Q_ASSERT(m_errorDevice); const QChar slash = QLatin1Char('/'); if (!currentPath.isEmpty() && !currentPath.endsWith(slash)) currentPath += slash; QDomDocument document; { QString errorMsg; int errorLine = 0; int errorColumn = 0; if (!document.setContent(inputDevice, &errorMsg, &errorLine, &errorColumn)) { if (ignoreErrors) return true; const QString msg = QString::fromUtf8("RCC Parse Error: '%1' Line: %2 Column: %3 [%4]\n").arg(fname).arg(errorLine).arg(errorColumn).arg(errorMsg); m_errorDevice->write(msg.toUtf8()); return false; } } QDomElement domRoot = document.firstChildElement(m_strings.TAG_RCC).toElement(); if (!domRoot.isNull() && domRoot.tagName() == m_strings.TAG_RCC) { for (QDomNode node = domRoot.firstChild(); !node.isNull(); node = node.nextSibling()) { if (!node.isElement()) continue; QDomElement child = node.toElement(); if (!child.isNull() && child.tagName() == m_strings.TAG_RESOURCE) { QLocale::Language language = QLocale::c().language(); QLocale::Country country = QLocale::c().country(); if (child.hasAttribute(m_strings.ATTRIBUTE_LANG)) { QString attribute = child.attribute(m_strings.ATTRIBUTE_LANG); QLocale lang = QLocale(attribute); language = lang.language(); if (2 == attribute.length()) { // Language only country = QLocale::AnyCountry; } else { country = lang.country(); } } QString prefix; if (child.hasAttribute(m_strings.ATTRIBUTE_PREFIX)) prefix = child.attribute(m_strings.ATTRIBUTE_PREFIX); if (!prefix.startsWith(slash)) prefix.prepend(slash); if (!prefix.endsWith(slash)) prefix += slash; for (QDomNode res = child.firstChild(); !res.isNull(); res = res.nextSibling()) { if (res.isElement() && res.toElement().tagName() == m_strings.TAG_FILE) { QString fileName(res.firstChild().toText().data()); if (fileName.isEmpty()) { const QString msg = QString::fromUtf8("RCC: Warning: Null node in XML of '%1'\n").arg(fname); m_errorDevice->write(msg.toUtf8()); } QString alias; if (res.toElement().hasAttribute(m_strings.ATTRIBUTE_ALIAS)) alias = res.toElement().attribute(m_strings.ATTRIBUTE_ALIAS); else alias = fileName; int compressLevel = m_compressLevel; if (res.toElement().hasAttribute(m_strings.ATTRIBUTE_COMPRESS)) compressLevel = res.toElement().attribute(m_strings.ATTRIBUTE_COMPRESS).toInt(); int compressThreshold = m_compressThreshold; if (res.toElement().hasAttribute(m_strings.ATTRIBUTE_THRESHOLD)) compressThreshold = res.toElement().attribute(m_strings.ATTRIBUTE_THRESHOLD).toInt(); // Special case for -no-compress. Overrides all other settings. if (m_compressLevel == -2) compressLevel = 0; alias = QDir::cleanPath(alias); while (alias.startsWith(QLatin1String("../"))) alias.remove(0, 3); alias = QDir::cleanPath(m_resourceRoot) + prefix + alias; QString absFileName = fileName; if (QDir::isRelativePath(absFileName)) absFileName.prepend(currentPath); QFileInfo file(absFileName); if (!file.exists()) { m_failedResources.push_back(absFileName); const QString msg = QString::fromUtf8("RCC: Error in '%1': Cannot find file '%2'\n").arg(fname).arg(fileName); m_errorDevice->write(msg.toUtf8()); if (ignoreErrors) continue; else return false; } else if (file.isFile()) { const bool arc = addFile(alias, RCCFileInfo(alias.section(slash, -1), file, language, country, RCCFileInfo::NoFlags, compressLevel, compressThreshold) ); if (!arc) m_failedResources.push_back(absFileName); } else { QDir dir; if (file.isDir()) { dir.setPath(file.filePath()); } else { dir.setPath(file.path()); dir.setNameFilters(QStringList(file.fileName())); if (alias.endsWith(file.fileName())) alias = alias.left(alias.length()-file.fileName().length()); } if (!alias.endsWith(slash)) alias += slash; QDirIterator it(dir, QDirIterator::FollowSymlinks|QDirIterator::Subdirectories); while (it.hasNext()) { it.next(); QFileInfo child(it.fileInfo()); if (child.fileName() != QLatin1String(".") && child.fileName() != QLatin1String("..")) { const bool arc = addFile(alias + child.fileName(), RCCFileInfo(child.fileName(), child, language, country, RCCFileInfo::NoFlags, compressLevel, compressThreshold) ); if (!arc) m_failedResources.push_back(child.fileName()); } } } } } } } } if (m_root == 0) { const QString msg = QString::fromUtf8("RCC: Warning: No resources in '%1'.\n").arg(fname); m_errorDevice->write(msg.toUtf8()); if (!ignoreErrors && m_format == Binary) { // create dummy entry, otherwise loading qith QResource will crash m_root = new RCCFileInfo(QString(), QFileInfo(), QLocale::C, QLocale::AnyCountry, RCCFileInfo::Directory); } } return true; }