bool KThemeManager::applyTheme(const KThemeDocument &kd) { // kDebug() << "Applying theme" << endl; bool ok = false; QXmlSimpleReader reader; reader.setContentHandler(this); reader.setErrorHandler(this); QXmlInputSource xmlsource; xmlsource.setData(kd.toString()); if (reader.parse(&xmlsource)) { ok = true; } else { kDebug() << QObject::tr("I can't analize the theme document") << endl; ok = false; } return ok; }
bool MainHandler::readXMLDir(const char * xmlDirName) { m_xmlDirName = xmlDirName; QString xmlFileName=m_xmlDirName+"/index.xml"; QFile xmlFile(xmlFileName); //printf("Trying %s xmlFile.exists()=%d isReadable()=%d\n", // xmlFileName.data(),xmlFile.exists(),xmlFile.isReadable()); if (xmlFile.exists()) { ErrorHandler errorHandler; QXmlInputSource source( xmlFile ); QXmlSimpleReader reader; reader.setContentHandler( this ); reader.setErrorHandler( &errorHandler ); reader.parse( source ); dump(); return TRUE; } return FALSE; }
/** * \brief Opens the file at the given path * \author Peter Grasch * \param QString path * If no path is given, we use the path given in the path-member * \param QXmlDefaultHandler* handler * This handler is used to parse the content. It is adviced to subclass QXmlDefaultHandler to provide the functionality */ void XMLSAXReader::load(QXmlDefaultHandler* handler, QString path) { if (!handler) return; if (path.isEmpty()) path = this->path; QIODevice *sourcefile = KFilterDev::deviceForFile(path, KMimeType::findByFileContent(path)->name()); if ((!sourcefile) || (!sourcefile->open(QIODevice::ReadOnly))) return; QXmlInputSource source(sourcefile); QXmlSimpleReader *reader = new QXmlSimpleReader(); reader->setContentHandler(handler); reader->setErrorHandler(handler); emit (loaded()); reader->parse(source); }
bool PercussionMap::loadPercussionMap(const QString &filename) { QFile mapFile(filename); bool ok = mapFile.open(QIODevice::ReadOnly); // if (!ok) // QMessageBox::critical(0, tr("Rosegarden"), tr("couldn't open file '%1'").arg(handler.errorString())); QXmlInputSource source(&mapFile); QXmlSimpleReader reader; reader.setContentHandler(this); reader.setErrorHandler(this); ok = reader.parse(source); // if (!ok) // QMessageBox::critical(0, tr("Rosegarden"), tr("couldn't parse chord dictionary : %1").arg(handler.errorString())); return ok; }
int main(int argc, char **argv) { if (argc != 2) { std::cout << "Usage: " << argv[0] << " <filename>" << std::endl; return 1; } QFile *file = new QFile(argv[1]); //! [0] QXmlSimpleReader xmlReader; QXmlInputSource *source = new QXmlInputSource(file); //! [0] //! [1] Handler *handler = new Handler; xmlReader.setContentHandler(handler); xmlReader.setErrorHandler(handler); //! [1] //! [2] bool ok = xmlReader.parse(source); if (!ok) std::cout << "Parsing failed." << std::endl; //! [2] else { QStringList names = handler->names(); QList<int> indentations = handler->indentations(); int items = names.count(); for (int i = 0; i < items; ++i) { for (int j = 0; j < indentations[i]; ++j) std::cout << " "; std::cout << names[i].toLocal8Bit().constData() << std::endl; } } return 0; }
bool FbReadThread::parse() { QXmlStreamWriter writer(&m_html); FbReadHandler handler(*this, writer); QXmlSimpleReader reader; reader.setContentHandler(&handler); reader.setLexicalHandler(&handler); reader.setErrorHandler(&handler); QXmlInputSource source; if (m_xml.isEmpty()) { QFile file(m_filename); if (!file.open(QFile::ReadOnly | QFile::Text)) { qCritical() << QObject::tr("Cannot read file %1: %2.").arg(m_filename).arg(file.errorString()); return false; } source.setData(file.readAll()); } else { source.setData(m_xml); } return reader.parse(source); }
const QString PatternParser::parseCommandPattern(const QString& pattern, const QString& input, const QString& output, int trackno, int cdno, int trackoffset, int nooftracks, const QString& artist, const QString& title, const QString& tartist, const QString& ttitle, const QString& date, const QString& genre, const QString& suffix, CachedImage *cover, bool fatcompatible, const QString& tmppath, const QString& encoder, const bool demomode) { SaxHandler handler; handler.setInputFile(input); handler.setOutputFile(output); handler.setTrackNo(trackno); handler.setCDNo(cdno); handler.setTrackOffset(trackoffset); handler.setNoOfTracks(nooftracks); handler.setArtist(artist); handler.setTitle(title); handler.setTrackArtist(tartist); handler.setTrackTitle(ttitle); handler.setDate(date); handler.setGenre(genre); handler.setSuffix(suffix); handler.setCover(cover); handler.setFAT32Compatible(fatcompatible); handler.setTMPPath(tmppath); handler.setDemoMode(demomode); handler.set2DigitsTrackNum(false); handler.setEncoder(encoder); QXmlInputSource inputSource; inputSource.setData("<commandpattern>"+p_xmlize_pattern(pattern)+"</commandpattern>"); QXmlSimpleReader reader; reader.setContentHandler(&handler); reader.setErrorHandler(&handler); reader.parse(inputSource); return handler.text(); }
void AnnoqtConfEditor::loadAnnotationConfigurationFile(const QString& fileName) { if (fileName.isEmpty()) return; QFile file(fileName); if (!file.open(QFile::ReadOnly | QFile::Text)) { QMessageBox::warning(this, tr("Annotation Tool"), tr("Cannot read file %1:\n%2.") .arg(fileName) .arg(file.errorString())); return; } m_currentAnnotationConfigurationFile = fileName; m_listWidget->clear(); m_colors.clear(); setWindowModified( false ); QList<QString> recursiveEntityTypes; AnnotationConfigurationHandler handler(m_listWidget, &m_colors, &m_colorNames2EntityTypes, &recursiveEntityTypes, true); QXmlSimpleReader reader; reader.setContentHandler(&handler); reader.setErrorHandler(&handler); QXmlInputSource xmlInputSource(&file); if (reader.parse(xmlInputSource)) statusBar()->showMessage(tr("Annotation Configuration File loaded"), 2000); for (QMap<QString, QString>::const_iterator it=m_colorNames2EntityTypes.begin(); it != m_colorNames2EntityTypes.end(); it++) { m_entityNames2Types.insert(it.value(),m_entityNames2Types.size()); m_entityTypes2Names.insert(m_entityNames2Types.size()-1,it.value()); m_entityTypes2ColorNames.insert(m_entityNames2Types[it.value()],it.key()); } statusBar()->showMessage( tr( "Loaded configuration file " ) + fileName ); }
void Robot::open(const QString& fileName, bool verbose) throw(KinematicModelException) { //printf("Robot.Open()\n"); ZPHandler handler( model, this ); QXmlSimpleReader reader; reader.setContentHandler(&handler); reader.setErrorHandler(&handler); QFile file(fileName); //printf("set up xml parser\n"); if ( !file.open(QFile::ReadOnly | QFile::Text) ) { QString errStr = "failed to open file '"; errStr.append(fileName); errStr.append("'"); throw KinematicModelException(errStr); } //else printf("text file found\n"); QXmlInputSource xmlInputSource( &file ); if ( !reader.parse( xmlInputSource ) ) { QString errStr = "failed to create robot '"; errStr.append(getName()); errStr.append("' from file '"); errStr.append(fileName); errStr.append("'"); throw KinematicModelException(errStr); } //else printf("text file parsed\n"); //printf("Parsed the robot file\n"); ignoreAdjacentPairs(); home(); printf("Created Robot: %s (%d kinematic tree nodes, %d primitives)\n",getName().toStdString().c_str(), numCompositObjects, getNumPrimitives()); isConfigured = true; }
void load( const QString& filename ) { QFile file( filename ); if ( !file.open( IO_ReadOnly ) ) { Console::instance()->send( tr( "Unable to open %1!\n" ).arg( filename ) ); return; } filenames.push_back( filename ); QXmlInputSource input( &file ); QXmlSimpleReader reader; reader.setFeature( "http://trolltech.com/xml/features/report-whitespace-only-CharData", false ); reader.setContentHandler( this ); reader.setErrorHandler( this ); reader.parse( &input, false ); filenames.pop_back(); }
void MainWindow::open() { #if defined(Q_OS_SYMBIAN) // Look for bookmarks on the same drive where the application is installed to, // if drive is not read only. QDesktopServices::DataLocation does this check, // and returns writable drive. QString bookmarksFolder = QDesktopServices::storageLocation(QDesktopServices::DataLocation).left(1); bookmarksFolder.append(":/Data/qt/saxbookmarks"); QDir::setCurrent(bookmarksFolder); #endif QString fileName = QFileDialog::getOpenFileName(this, tr("Open Bookmark File"), QDir::currentPath(), tr("XBEL Files (*.xbel *.xml)")); if (fileName.isEmpty()) return; treeWidget->clear(); XbelHandler handler(treeWidget); QXmlSimpleReader reader; reader.setContentHandler(&handler); reader.setErrorHandler(&handler); QFile file(fileName); if (!file.open(QFile::ReadOnly | QFile::Text)) { QMessageBox::warning(this, tr("SAX Bookmarks"), tr("Cannot read file %1:\n%2.") .arg(fileName) .arg(file.errorString())); return; } QXmlInputSource xmlInputSource(&file); if (reader.parse(xmlInputSource)) statusBar()->showMessage(tr("File loaded"), 2000); }
void CriticalPowerWindow::addSeasons() { QFile seasonFile(home.absolutePath() + "/seasons.xml"); QXmlInputSource source( &seasonFile ); QXmlSimpleReader xmlReader; SeasonParser( handler ); xmlReader.setContentHandler(&handler); xmlReader.setErrorHandler(&handler); bool ok = xmlReader.parse( source ); if(!ok) qWarning("Failed to parse seasons.xml"); seasons = handler.getSeasons(); Season season; season.setName("All Seasons"); seasons.insert(0,season); for (int i = 0; i < seasons.size(); ++i) { season = seasons.at(i); cComboSeason->addItem(season.getName()); } }
void QQTMRequester::requestFinishedSlot(QNetworkReply * reply) { if(reply->error() == QNetworkReply::NoError) { QByteArray data = reply->readAll(); QXmlSimpleReader xmlReader; QXmlInputSource xmlSource; xmlSource.setData(data); xmlReader.setContentHandler(m_xmlParser); xmlReader.setErrorHandler(m_xmlParser); xmlReader.parse(xmlSource); } else { qDebug() << Q_FUNC_INFO << "reply->error() =" << reply->error() << ", " << reply->errorString(); emit requestFinished(); } m_netReply = NULL; reply->deleteLater(); }
//bool Parser::parse(ParserTypes which, QFile &file, MusicCollection *collection) { bool MusicCollectionIO::parse(QFile &file, MusicCollection *collection) { /* switch ( which ) { case ITUNES: { */ iTunesXmlHandler parser(collection); QXmlSimpleReader reader; reader.setContentHandler(&parser); reader.setErrorHandler(&parser); QXmlInputSource xmlInputSource(&file); return reader.parse(xmlInputSource); /* } case MARCSV: case MARXML: default: return false; } */ }
bool MainFrm::readXMLFile(const QString strFileName) { //TODO: add some XML semantic validation? //SessionFileParser *handler=new SessionFileParser(sSample); if (handler!=0) {delete handler; handler=0;} handler=new SessionFileParser(sSample); QFile file( strFileName ); QXmlInputSource source( &file ); QXmlSimpleReader reader; reader.setContentHandler( handler ); reader.setErrorHandler(handler); if (!reader.parse( source )){ //delete handler; handler=0; return false; } //delete handler; handler=0; return true; }
void TimersModel::readTimers(const QString &file) { TimersHandler *handler = new TimersHandler(); QXmlSimpleReader reader; reader.setContentHandler(handler); reader.setErrorHandler(handler); QFile f(file); if (!f.open(QFile::ReadOnly | QFile::Text)) return; QXmlInputSource xmlInputSource(&f); if (!reader.parse(xmlInputSource)) return; QList<Timer *> timers = handler->timersList(); for(int i = 0; i < timers.size(); i++) { appendRow(timers[i]); } delete handler; }
bool QAutoGUI::ParseXML(const QString& fileName) { // Try to open the file QFile file(fileName); if (!file.exists()) { qDebug() << "QAutoGUI::ParseXML() : Error, vrpn_Qt_AutoGUI configuration file" << fileName << "does not exist."; return false; } // Set up XML parsing QXmlAutoGUIHandler handler(this); QXmlSimpleReader xmlReader; xmlReader.setContentHandler(&handler); xmlReader.setErrorHandler(&handler); // Parse the GUI description QXmlInputSource source(file); xmlReader.parse(source); return true; }
int QueryWqlBaseList::parseResults( QString &results ) { int success = -1; QXmlSimpleReader parser; resetResults(); QueryWqlBaseListHandler *handler = new QueryWqlBaseListHandler( &m_results ); QXmlInputSource source; source.setData(results); qDebug() << "QueryWqlBaseList::parseResults: " << results; parser.setContentHandler(handler); parser.setErrorHandler(handler); success = parser.parse(source); if(!success) { qDebug() << "Parse error: " << parser.errorHandler()->errorString(); } delete handler; return (success ? 0 : -1); }
bool VOCatalogHeaderParser::parse(const QByteArray &data, QList <VOCatalogHeader> &catalogs, QList <VOCooSys> &cooSys) { QXmlInputSource xmlInputStream; QXmlSimpleReader xml; if (data.isEmpty()) { return false; } xmlInputStream.setData(data); xml.setContentHandler(this); xml.setErrorHandler(this); if (xml.parse(&xmlInputStream)) { catalogs = m_list; cooSys = m_cooSys; return true; } return false; }
/*! * \brief CTConfToyStick::setParameters * * Sets values of all configurable block parameters based on the content of the * supplied XML string. * * \param xml containing data of all configurable parameters. */ bool CTConfToyStick::setParameters(QString xml) { // qDebug() << xml; int num_stimuli = NUM_LIGHTS + NUM_SPEAKERS; int num_actions = NUM_LIGHTS + NUM_SPEAKERS; QXmlSimpleReader xmlReader; QXmlInputSource *source = new QXmlInputSource(); source->setData(xml); CTXmlHandler *handler = new CTXmlHandler; /* *Passing pointer of the class to the xml parser handler, *in order to set the parsed values into it's input fields */ handler->setWidget(1, this, num_stimuli, num_actions); QList<CTLight*> empty1; QList<CTScreen*> empty2; QList<CTBigLight*> empty3; QList<CTButton*> empty4; handler->setStimuli(light_stimuli, speaker_stimuli, empty1,empty2,empty3,empty4); handler->setActions(light_actions, speaker_actions, empty2,empty3,empty4,empty1); xmlReader.setContentHandler(handler); xmlReader.setErrorHandler(handler); bool ok = xmlReader.parse(source); qDebug() << "The parsing went ok? " << ok; block_duration = handler->getBlockDuration(); if(ok) { updateBlockRuntime(1.0); } return true; }
// Recursive Function for Importing Script Sections bool cDefinitions::ImportSections( const QString& FileName ) { QFile File( FileName ); if ( !File.open( IO_ReadOnly ) ) { Console::instance()->send( "Unable to open " ); Console::instance()->send( FileName ); Console::instance()->send( "!\n" ); return false; } QXmlInputSource input( &File ); QXmlSimpleReader reader; reader.setFeature( "http://trolltech.com/xml/features/report-whitespace-only-CharData", false ); cXmlHandler handler( impl, FileName ); reader.setContentHandler( &handler ); reader.setErrorHandler( &handler ); reader.parse( &input, false ); File.close(); return true; }
void XMLTokenizer::finish() { // parse xml file XMLHandler handler(m_doc,m_view); QXmlInputSource source; source.setData(m_xmlCode); QXmlSimpleReader reader; reader.setContentHandler( &handler ); reader.setLexicalHandler( &handler ); reader.setErrorHandler( &handler ); reader.setDeclHandler( &handler ); reader.setDTDHandler( &handler ); bool ok = reader.parse( source ); // ### handle exceptions inserting nodes if (!ok) { kdDebug(6036) << "Error during XML parsing: " << handler.errorProtocol() << endl; int exceptioncode; while (m_doc->hasChildNodes()) static_cast<NodeImpl*>(m_doc)->removeChild(m_doc->firstChild(),exceptioncode); // construct a HTML page giving the error message // ### for multiple error messages, display the code for each QTextIStream stream(&m_xmlCode); unsigned long lineno; for (lineno = 0; lineno < handler.errorLine-1; lineno++) stream.readLine(); QString line = stream.readLine(); m_doc->appendChild(m_doc->createElementNS("http://www.w3.org/1999/xhtml","html"),exceptioncode); NodeImpl *body = m_doc->createElementNS("http://www.w3.org/1999/xhtml","body"); m_doc->firstChild()->appendChild(body,exceptioncode); NodeImpl *h1 = m_doc->createElementNS("http://www.w3.org/1999/xhtml","h1"); body->appendChild(h1,exceptioncode); h1->appendChild(m_doc->createTextNode(i18n("XML parsing error")),exceptioncode); h1->renderer()->close(); body->appendChild(m_doc->createTextNode(handler.errorProtocol()),exceptioncode); body->appendChild(m_doc->createElementNS("http://www.w3.org/1999/xhtml","hr"),exceptioncode); NodeImpl *pre = m_doc->createElementNS("http://www.w3.org/1999/xhtml","pre"); body->appendChild(pre,exceptioncode); pre->appendChild(m_doc->createTextNode(line+"\n"),exceptioncode); unsigned long colno; QString indent = ""; for (colno = 0; colno < handler.errorCol-1; colno++) indent += " "; pre->appendChild(m_doc->createTextNode(indent+"^"),exceptioncode); pre->renderer()->close(); body->renderer()->close(); m_doc->applyChanges(); m_doc->updateRendering(); end(); } else { addScripts(m_doc); m_scriptsIt = new QListIterator<HTMLScriptElementImpl>(m_scripts); executeScripts(); } }
// // Manage the seasons array // void Seasons::readSeasons() { QFile seasonFile(home.absolutePath() + "/seasons.xml"); QXmlInputSource source( &seasonFile ); QXmlSimpleReader xmlReader; SeasonParser handler; xmlReader.setContentHandler(&handler); xmlReader.setErrorHandler(&handler); xmlReader.parse( source ); seasons = handler.getSeasons(); Season season; QDate today = QDate::currentDate(); QDate eom = QDate(today.year(), today.month(), today.daysInMonth()); // add Default Date Ranges season.setName(tr("All Dates")); season.setType(Season::temporary); season.setStart(QDate::currentDate().addYears(-50)); season.setEnd(QDate::currentDate().addYears(50)); season.setId(QUuid("{00000000-0000-0000-0000-000000000001}")); seasons.append(season); season.setName(tr("This Year")); season.setType(Season::temporary); season.setStart(QDate(today.year(), 1,1)); season.setEnd(QDate(today.year(), 12, 31)); season.setId(QUuid("{00000000-0000-0000-0000-000000000002}")); seasons.append(season); season.setName(tr("This Month")); season.setType(Season::temporary); season.setStart(QDate(today.year(), today.month(),1)); season.setEnd(eom); season.setId(QUuid("{00000000-0000-0000-0000-000000000003}")); seasons.append(season); season.setName(tr("This Week")); season.setType(Season::temporary); // from Mon-Sun QDate wstart = QDate::currentDate(); wstart = wstart.addDays(Qt::Monday - wstart.dayOfWeek()); QDate wend = wstart.addDays(6); // first day + 6 more season.setStart(wstart); season.setEnd(wend); season.setId(QUuid("{00000000-0000-0000-0000-000000000004}")); seasons.append(season); season.setName(tr("Last 7 days")); season.setType(Season::temporary); season.setStart(today.addDays(-6)); // today plus previous 6 season.setEnd(today); season.setId(QUuid("{00000000-0000-0000-0000-000000000005}")); seasons.append(season); season.setName(tr("Last 14 days")); season.setType(Season::temporary); season.setStart(today.addDays(-13)); season.setEnd(today); season.setId(QUuid("{00000000-0000-0000-0000-000000000006}")); seasons.append(season); season.setName(tr("Last 21 days")); season.setType(Season::temporary); season.setStart(today.addDays(-20)); season.setEnd(today); season.setId(QUuid("{00000000-0000-0000-0000-000000000011}")); seasons.append(season); season.setName(tr("Last 28 days")); season.setType(Season::temporary); season.setStart(today.addDays(-27)); season.setEnd(today); season.setId(QUuid("{00000000-0000-0000-0000-000000000007}")); seasons.append(season); season.setName(tr("Last 2 months")); season.setType(Season::temporary); season.setEnd(today); season.setStart(today.addMonths(-2)); season.setId(QUuid("{00000000-0000-0000-0000-000000000008}")); seasons.append(season); season.setName(tr("Last 3 months")); season.setType(Season::temporary); season.setEnd(today); season.setStart(today.addMonths(-3)); season.setId(QUuid("{00000000-0000-0000-0000-000000000011}")); seasons.append(season); season.setName(tr("Last 6 months")); season.setType(Season::temporary); season.setEnd(today); season.setStart(today.addMonths(-6)); season.setId(QUuid("{00000000-0000-0000-0000-000000000009}")); seasons.append(season); season.setName(tr("Last 12 months")); season.setType(Season::temporary); season.setEnd(today); season.setStart(today.addMonths(-12)); season.setId(QUuid("{00000000-0000-0000-0000-000000000010}")); seasons.append(season); seasonsChanged(); // signal! }
void SkyBackgroundPluginForm::setupSkyBackground( const QDir dir, const bool zUp ) { try { skyBackground = NullFC; bool imageLoaded[6] = {false, false, false, false, false, false}; const QFileInfoList* fileList = dir.entryInfoList(); QFileInfoListIterator it(*fileList); QFileInfo* fileInfo; while ((fileInfo = it.current()) != 0) { QString qstr = fileInfo->absFilePath(); const char *filename = qstr.latin1(); if (((qstr.find("north") >= 0) || (qstr.find("front") >= 0)) && !imageLoaded[0]) { beginEditCP(images[5]); if (images[5]->read(filename)) { beginEditCP(textures[5]); textures[5]->setImage(images[5]); endEditCP(textures[5]); vrLog::info("Sky Background: Front/North image loaded."); imageLoaded[0] = true; } endEditCP(images[5]); } if (((qstr.find("south") >= 0) || (qstr.find("back") >= 0)) && !imageLoaded[1]) { beginEditCP(images[4]); if (images[4]->read(filename)) { if (zUp) vrImage::rotateImage180Degrees(images[4]); beginEditCP(textures[4]); textures[4]->setImage(images[4]); endEditCP(textures[4]); vrLog::info("Sky Background: Back/South image loaded."); imageLoaded[1] = true; } endEditCP(images[4]); } if (((qstr.find("down") >= 0) || (qstr.find("bottom") >= 0)) && !imageLoaded[2]) { beginEditCP(images[3]); if (images[3]->read(filename)) { beginEditCP(textures[3]); textures[3]->setImage(images[3]); endEditCP(textures[3]); vrLog::info("Sky Background: Bottom/Down image loaded."); imageLoaded[2] = true; } endEditCP(images[3]); } if (((qstr.find("up") >= 0) || (qstr.find("top") >= 0)) && !imageLoaded[3]) { beginEditCP(images[2]); if (images[2]->read(filename)) { if (zUp) vrImage::rotateImage180Degrees(images[2]); beginEditCP(textures[2]); textures[2]->setImage(images[2]); endEditCP(textures[2]); vrLog::info("Sky Background: Top/Up image loaded."); imageLoaded[3] = true; } endEditCP(images[2]); } if (((qstr.find("east") >= 0) || (qstr.find("right") >= 0)) && !imageLoaded[4]) { beginEditCP(images[1]); if (images[1]->read(filename)) { if (zUp) vrImage::rotate90Left(images[1]); beginEditCP(textures[1]); textures[1]->setImage(images[1]); endEditCP(textures[1]); vrLog::info("Sky Background: Right/East image loaded."); imageLoaded[4] = true; } endEditCP(images[1]); } if (((qstr.find("west") >= 0) || (qstr.find("left") >= 0)) && !imageLoaded[5]) { beginEditCP(images[0]); if (images[0]->read(filename)) { if (zUp) vrImage::rotate90Right(images[0]); beginEditCP(textures[0]); textures[0]->setImage(images[0]); endEditCP(textures[0]); vrLog::info("Sky Background: Left/West image loaded."); imageLoaded[5] = true; } endEditCP(images[0]); } ++it; } skyBackground = SkyBackground::create(); beginEditCP(skyBackground); if (!zUp) { skyBackground->setFrontTexture(textures[5]); skyBackground->setBackTexture(textures[4]); skyBackground->setBottomTexture(textures[3]); skyBackground->setTopTexture(textures[2]); skyBackground->setRightTexture(textures[1]); skyBackground->setLeftTexture(textures[0]); } else { skyBackground->setFrontTexture(textures[3]); skyBackground->setBackTexture(textures[2]); skyBackground->setBottomTexture(textures[4]); skyBackground->setTopTexture(textures[5]); skyBackground->setRightTexture(textures[1]); skyBackground->setLeftTexture(textures[0]); } endEditCP(skyBackground); vrOSGWidget *gl = vrOSGWidget::getMGLW(-1); ViewportPtr vredViewport = gl->getViewport(); //oldBackground = vredViewport->getBackground(); beginEditCP(vredViewport); vredViewport->setBackground(skyBackground); endEditCP(vredViewport); directoryLineEdit->setText(dir.absPath()); // read light settings if (SetLightingCheckBox->isChecked()) { string lightName = LightNameLineEdit->text().ascii(); if (!QFile::exists(dir.absPath() + "/LightSettings.xml")) vrLog::warning("Light Settings not found."); else { QFile* file = new QFile(dir.absPath() + "/LightSettings.xml"); if (file->open(IO_ReadOnly)) { LightSettingsHandler handler; QXmlSimpleReader reader; reader.setContentHandler(&handler); reader.setErrorHandler(&handler); QXmlInputSource source(file); reader.parse(source); file->close(); handler.direction.normalize(); vector<NodePtr> lights; vrLights::getLights(lights); bool lightSet = false; for (vector<NodePtr>::const_iterator it = lights.begin(); it != lights.end(); ++it) { LightPtr light = LightPtr::dcast((*it)->getCore()); if (light != NullFC) { NodePtr node = *it; string name = getName(node); if (name.find(lightName) != string::npos) { setLightSettings(light, handler); lightSet = true; } } } if (!lightSet) { NodePtr rootNode = vrScenegraph::getRoot(); TransformPtr beaconTransform = Transform::create(); NodePtr beaconNode = Node::create(); beginEditCP(beaconNode); beaconNode->setCore(beaconTransform); endEditCP(beaconNode); PointLightPtr light = PointLight::create(); beginEditCP(light); light->setAttenuation(1,0,0); light->setBeacon(beaconNode); endEditCP(light); NodePtr lightNode = Node::create(); beginEditCP(lightNode); lightNode->setCore(light); endEditCP(lightNode); OSG::setName(lightNode, lightName); beginEditCP(rootNode); rootNode->addChild(lightNode); rootNode->addChild(beaconNode); endEditCP(rootNode); setLightSettings(light, handler); vrScenegraph::update(true); } } } } } catch (std::exception const& e) { cout << "type: " << typeid(e).name() << endl; cout << "message: " << e.what() << endl << endl; } }
Engine::Engine(QFileInfo& fileAlbum) throw(EngineException*) : m_dirty(false), m_fileAlbum(new QFileInfo(fileAlbum)), m_uid(0), m_fileSystemScanner(new FileSystemScanner(this)), m_nextSourceDirId(1), m_sourceDirDict(new QIntDict<Folder>()), m_sourceDirs(new QPtrList<Folder>()), m_nextTagNodeId(1), m_tagNodeDict(new QIntDict<TagNode>()), m_tagForest(new QPtrList<TagNode>()), m_exifTitleTag(0), m_fileDict(new QDict<File>()), m_fileList(new QPtrList<File>()), m_fileList2display(new QPtrList<File>()) { tracer->sinvoked(__func__) << "with file '" << m_fileAlbum->absFilePath() << "'" << endl; // if file does not exist, we have nothing to do //if (!m_fileAlbum->exists()) { QString msg = QString("File '%1' does not exist.").arg(m_fileAlbum->absFilePath()); tracer->serror(__func__) << msg << endl; throw new EngineException(msg, "no detailmessage"); //} QFile file(m_fileAlbum->absFilePath()); // close the file if it is open already if (file.isOpen()) { file.close(); } // open the file for reading if (!file.open( IO_ReadOnly )) { QString msg = QString("Could not open file '%1'.").arg(file.name()); tracer->serror(__func__) << msg << ": " << file.errorString() << endl; throw new EngineException(msg, file.errorString()); } // prepare input source QXmlInputSource xmlInputSource(file); // instantiate the parser XmlParser parser = XmlParser(this); // prepare the xml reader QXmlSimpleReader reader; // set the handler on the reader reader.setContentHandler(&parser); reader.setErrorHandler(&parser); // parse the document bool success = reader.parse(&xmlInputSource, false); // close the file file.close(); if (!success) { tracer->serror(__func__) << "Error occured during parsing the file '" << file.name() << "'" << endl; cleanUp(); if (parser.exception()) { tracer->serror(__func__) << "exception occured: " << parser.exception()->message() << endl; throw parser.exception(); } else { throw new EngineException(i18n("Unknown error while parsing the xml file occured!")); } } // generate a uid if the file does not contain one (for compatibility reason with version 0.0.5) if (!m_uid) { m_uid = generateUid(); } // create the EXIF tagnode if it was not contained in the database (for compatibility reason with version 0.0.6) if (m_exifTitleTag == 0) { createExifTagNode(); } // read the files in all sourcedirectories if (Settings::generalRescanWhileStartup()) { m_fileSystemScanner->rescan(); } // trace a little tracer->sdebug(__func__) << m_fileList->count() << " images added" << endl; }
KVSO_CLASS_FUNCTION(xmlReader, parse) { KviKvsVariant * pVariantData; KVSO_PARAMETERS_BEGIN(c) KVSO_PARAMETER("string_or_memorybuffer_object", KVS_PT_VARIANT, 0, pVariantData) KVSO_PARAMETERS_END(c) #ifdef QT_NO_XML fatalError(__tr2qs_ctx("XML support not available in the Qt library")); c->returnValue()->setBoolean(false); #else m_szLastError = ""; KviXmlHandler handler(this); QXmlInputSource source; if(pVariantData->isHObject()) { KviKvsObject * pObject; kvs_hobject_t hObject; pVariantData->asHObject(hObject); pObject = KviKvsKernel::instance()->objectController()->lookupObject(hObject); if(!pObject) { c->warning(__tr2qs_ctx("Data parameter is not an object", "objects")); return true; } if(pObject->inheritsClass("memorybuffer")) { source.setData(*((KvsObject_memoryBuffer *)pObject)->pBuffer()); } else { c->warning(__tr2qs_ctx("Data parameter is not a memorybuffer object", "objects")); return true; } } else if(pVariantData->isString()) { QString szString; pVariantData->asString(szString); // We have a problem here.. most kvirc functions already interpret the data // read from files. We should have binary data handling features to get this to work correctly. // The following snippet of code tries to provide a best-effort workaround. QByteArray utf8data = szString.toUtf8(); QByteArray data = utf8data; data.truncate(utf8data.length()); // don't include the null terminator in data source.setData(data); //qDebug("PARSING(%s) LEN(%d)",szString.toUtf8().data(),szString.toUtf8().length()); } else { c->warning(__tr2qs_ctx("Data is not a memorybuffer object or string", "objects")); return true; } QXmlSimpleReader reader; reader.setContentHandler(&handler); reader.setErrorHandler(&handler); c->returnValue()->setBoolean(reader.parse(source)); #endif return true; }
int main(int argc,char* argv[]) { QCoreApplication a(argc, argv); QsLogging::initQsLog(); std::string resourcesPath=std::string(getenv("LIMA_RESOURCES")); std::string configDir=std::string(getenv("LIMA_CONF")); std::string lpConfigFile=std::string("lima-lp-tva.xml"); std::string commonConfigFile=std::string("lima-common.xml"); std::string clientId=std::string("lima-coreclient"); std::string workingDir=std::string("."); std::deque<std::string> files; std::deque<std::string> pipelines; std::deque<std::string> langs; if (argc>1) { for (int i = 1 ; i < argc; i++) { std::string arg(argv[i]); std::string::size_type pos = std::string::npos; if ( arg[0] == '-' ) { if (arg == "--help") usage(argc, argv); else if ( (pos = arg.find("--lp-config-file=")) != std::string::npos ) lpConfigFile = arg.substr(pos+17); else if ( (pos = arg.find("--common-config-file=")) != std::string::npos ) commonConfigFile = arg.substr(pos+21); else if ( (pos = arg.find("--config-dir=")) != std::string::npos ) configDir = arg.substr(pos+13); else if ( (pos = arg.find("--resources-dir=")) != std::string::npos ) resourcesPath = arg.substr(pos+16); else if ( (pos = arg.find("--client=")) != std::string::npos ) clientId=arg.substr(pos+9); else if ( (pos = arg.find("--working-dir=")) != std::string::npos ) workingDir=arg.substr(pos+14); else if ( (pos = arg.find("--language=")) != std::string::npos ) langs.push_back(arg.substr(pos+11)); else usage(argc, argv); } else { files.push_back(arg); } } } if(langs.empty()) { std::cerr << "No language specified. Aborting." << std::endl; return 1; } setlocale(LC_ALL,"fr_FR.UTF-8"); AbstractLinguisticProcessingClient* client(0); // initialize common MediaticData::changeable().init( resourcesPath, configDir, commonConfigFile, langs); // initialize linguistic processing Lima::Common::XMLConfigurationFiles::XMLConfigurationFileParser lpconfig(configDir + "/" + lpConfigFile); LinguisticProcessingClientFactory::changeable().configureClientFactory( clientId, lpconfig, langs, pipelines); client=static_cast<AbstractLinguisticProcessingClient*>(LinguisticProcessingClientFactory::single().createClient(clientId)); // Set the handlers std::map<std::string, AbstractAnalysisHandler*> handlers; BowTextWriter* bowTextWriter = new BowTextWriter(); handlers.insert(std::make_pair("bowTextWriter", bowTextWriter)); SimpleStreamHandler* simpleStreamHandler = new SimpleStreamHandler(); handlers.insert(std::make_pair("simpleStreamHandler", simpleStreamHandler)); BowTextHandler* bowTextHandler = new BowTextHandler(); handlers.insert(std::make_pair("bowTextHandler", bowTextHandler)); AnalysisTestCaseProcessor analysisTestCaseProcessor(workingDir, client, handlers); QXmlSimpleReader parser; TestCasesHandler tch(analysisTestCaseProcessor); parser.setContentHandler(&tch); parser.setErrorHandler(&tch); for (std::deque<std::string>::const_iterator it=files.begin(); it!=files.end(); it++) { std::cout << "process tests in " << *it << std::endl; try { QFile file(it->c_str()); if (!file.open(QIODevice::ReadOnly)) { std::cerr << "Error opening " << *it << std::endl; return 1; } if (!parser.parse( QXmlInputSource(&file))) { std::cerr << "Error parsing " << *it << " : " << parser.errorHandler()->errorString().toUtf8().constData() << std::endl; return 1; } } catch (Lima::LimaException& e) { std::cerr << __FILE__ << ", line " << __LINE__ << ": caught LimaException : " << std::endl << e.what() << std::endl; } catch (std::logic_error& e) { std::cerr << __FILE__ << ", line " << __LINE__ << ": caught logic_error : " << std::endl << e.what() << std::endl; } catch (std::runtime_error& e) { std::cerr << __FILE__ << ", line " << __LINE__ << ": caught runtime_error : " << std::endl << e.what() << std::endl; } TestCasesHandler::TestReport resTotal; std::cout << std::endl; std::cout << "=========================================================" << std::endl; std::cout << std::endl; std::cout << " TestReport : " << *it << " " << std::endl; std::cout << std::endl; std::cout << "\ttype \tsuccess\tcond.\tfailed\ttotal" << std::endl; std::cout << "---------------------------------------------------------" << std::endl; for (std::map<std::string,TestCasesHandler::TestReport>::const_iterator resItr=tch.m_reportByType.begin(); resItr!=tch.m_reportByType.end(); resItr++) { std::string label(resItr->first); label.resize(15,' '); std::cout << "\t" << label << "\t" << resItr->second.success << "\t" << resItr->second.conditional << "\t" << resItr->second.failed << "\t" << resItr->second.nbtests << std::endl; resTotal.success+=resItr->second.success; resTotal.conditional+=resItr->second.conditional; resTotal.failed+=resItr->second.failed; resTotal.nbtests+=resItr->second.nbtests; } std::cout << "---------------------------------------------------------" << std::endl; std::cout << "\ttotal \t" << resTotal.success << "\t" << resTotal.conditional << "\t" << resTotal.failed << "\t" << resTotal.nbtests << std::endl; std::cout << "=========================================================" << std::endl; std::cout << std::endl; tch.m_reportByType.clear(); } delete client; delete bowTextWriter; delete simpleStreamHandler; delete bowTextHandler; }
Q_DECL_EXPORT int main(int argc, char *argv[]) { QApplication app(argc, argv); // we can't read config in menaan contructor // because translator must be create and installed before widgets creating // so we read conf file there... qDebug()<<"[Application say:] Reading configuration"; ConfigData *configData; // read config data for application { QFile file(QApplication::applicationDirPath()+"/config.xml"); qDebug()<<"[Application say:] Check file"<<QApplication::applicationDirPath()+"/config.xml"; QXmlInputSource inputSource(&file); QXmlSimpleReader configReader; configData = new ConfigData(); ConfigHandler *configHandler = new ConfigHandler(configData); configReader.setContentHandler(configHandler); configReader.setErrorHandler(configHandler); configReader.parse(inputSource); delete configHandler; } // set translation qDebug()<<"[Application say:] Translation install"; QTranslator trans; int lg = configData->getLanguage(); switch (lg) { case ConfigData::English: trans.load(QApplication::applicationDirPath()+"/translations/en.qm"); break; case ConfigData::Russian: trans.load(QApplication::applicationDirPath()+"/translations/ru.qm"); break; case ConfigData::Germany: trans.load(QApplication::applicationDirPath()+"/translations/de.qm"); break; case ConfigData::French: trans.load(QApplication::applicationDirPath()+"/translations/fr.qm"); break; default: trans.load(QApplication::applicationDirPath()+"/translations/en.qm"); } app.installTranslator(&trans); Menaan * mainWidget = new Menaan(configData); Q_UNUSED(mainWidget) return app.exec(); }
void OsmReader::read(shared_ptr<OsmMap> map) { _osmFound = false; _missingNodeCount = 0; _missingWayCount = 0; _badAccuracyCount = 0; _map = map; // Ticket 5871: uncompress .osm.bz2 or .osm.gz files before processing QString originalFile; if ( _path.endsWith(".osm.bz2") == true ) { originalFile = _path; _path.chop(std::strlen(".bz2")); // "man bunzip2" confirms success return code is zero // -k option is "keep," meaning don't delete input .osm.bz2 const std::string cmd(std::string("bunzip2 -k ") + originalFile.toStdString()); LOG_DEBUG("Running uncompress command: " << cmd); int retVal; if ( (retVal = std::system(cmd.c_str())) != 0 ) { QString error = QString("Error %1 returned from uncompress command: %2").arg(retVal). arg(QString::fromStdString(cmd)); throw HootException(error); } LOG_DEBUG("Uncompress succeeded!"); } else if ( _path.endsWith(".osm.gz") == true ) { originalFile = _path; _path.chop(std::strlen(".gz")); // "man gzip" confirms success return code is zero // -d option is "decompress" // -k option is "keep," meaning don't delete input .osm.gz const std::string cmd(std::string("gzip -d -k ") + originalFile.toStdString()); LOG_DEBUG("Running uncompress command: " << cmd); int retVal; if ( (retVal = std::system(cmd.c_str())) != 0 ) { QString error = QString("Error %1 returned from uncompress command: %2").arg(retVal). arg(QString::fromStdString(cmd)); throw HootException(error); } LOG_DEBUG("Uncompress succeeded!"); } // do xml parsing QXmlSimpleReader reader; reader.setContentHandler(this); reader.setErrorHandler(this); QFile file(_path); if (!file.open(QFile::ReadOnly | QFile::Text)) { throw Exception(QObject::tr("Error opening OSM file for parsing: %1").arg(_path)); } LOG_DEBUG("File " << _path << " opened for read"); QXmlInputSource xmlInputSource(&file); if (reader.parse(xmlInputSource) == false) { throw HootException(_errorString); } file.close(); // Ticket 5871: if we did have to decompress, delete the decompressed file when we're done if ( originalFile.length() > 0 ) { // Delete the temp file std::remove(_path.toStdString().c_str()); LOG_DEBUG("Removed decompressed file " << _path); } ReportMissingElementsVisitor visitor; _map->visitRw(visitor); _map.reset(); }
void XMLDocument::open(const QString &file) { EnumType::enums.clear(); filename = file; FieldFactory *fieldFactory = new FieldFactory; XMLParser parser(fieldFactory, file); ifstream test(file.toStdString().c_str(),ios::in); if (!test) { docType = "Plugin"; plugin = new Plugin("","","","","","", "", false, false, false, false); attribute = new Attribute("","",QString(),"","",""); plugin->atts = attribute; return; } else { test.close(); } try { QFile xmlFile(file); QXmlInputSource source(&xmlFile); QXmlSimpleReader reader; ErrorHandler errorhandler; reader.setFeature("http://trolltech.com/xml/features/report-whitespace-only-CharData", false); reader.setContentHandler(&parser); reader.setErrorHandler(&errorhandler); bool success = reader.parse(source); if (!success) { cerr << "Error parsing input file " << file.toStdString() << endl; exit(-1); } docType = parser.docType; plugin = parser.plugin; if (docType == "Attribute") attribute = parser.attribute; else { if (!plugin->atts) { plugin->atts = new Attribute(QString(),QString(),QString(),QString(),QString(),QString()); } attribute = plugin->atts; } #if !defined(_WIN32) struct stat s; stat(file.toStdString().c_str(), &s); if (!(s.st_mode & S_IWUSR)) { QMessageBox::warning(0,"Warning","File is not writable."); } if (attribute && attribute->codeFile) { stat(attribute->codeFile->FileName().toStdString().c_str(), &s); if (!(s.st_mode & S_IWUSR)) { QMessageBox::warning(0,"Warning","Code file is not writable."); } } #endif } catch (const char *s) { cerr << "ERROR: " << s << endl; exit(-1); } catch (const QString &s) { cerr << "ERROR: " << s.toStdString() << endl; exit(-1); } }