예제 #1
0
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;
}
예제 #2
0
파일: fractal.cpp 프로젝트: avinash/phrax
void Fractal::load( QString fileName)
{
    int t,h,w;
    double miniX,maxiX,miniY,maxiY;
          
    QFile xmlFile( fileName );
    QXmlInputSource source( &xmlFile );
    QXmlSimpleReader reader;
    reader.setContentHandler( &handler );
    reader.parse( source );
    
//    set the minimum x & y and maximum x & y according to the values in the
//    xml file
    handler.setValues();
    
//    once the values are set we get the values from the class
    t = handler.getType();
    
    // if the type isn't between 0 and 9 inclusive (suppose the user tried changing the parameter)
    // the application will load the default fractaal
    if( ( t != 0 ) && ( t != 1 ) && ( t != 2 ) && ( t != 3 ) && ( t != 4 ) && ( t != 5 ) && ( t != 6 ) && ( t != 7 ) && ( t != 8 ) && ( t != 9 ) )
    {
	static QMessageBox* error = new QMessageBox( "Error", "File has been modified with wrong parameters. \n" "The default fractal will be loaded instead." , QMessageBox::Information, 1, 0, 0, this, 0, FALSE );
	
	error->setButtonText( 1, "Ok" );
	error->show();
	
	data.setDefaultData( MANDEL_TYPE1 );
	
	mandel1Action->setOn( TRUE );
	
	update();
	
	render( data.getType() , data.getHeight() , data.getWidth() , data.getDefaultMinX() , data.getDefaultMaxX() , data.getDefaultMinY() , data.getDefaultMaxY() );
    } // if
    
    else
    {
	h = data.getHeight();
	w = data.getWidth();    
	miniX = handler.getMinX();
	maxiX = handler.getMaxX();
	miniY = handler.getMinY();
	maxiY = handler.getMaxY();
	
	
	//    according to the image we load (i.e. whether the image is mandelbrot or julia)
	//    we check the appropriate action in Fractal -> Select Fractal
	
	if( t == MANDEL_TYPE1 )
	    mandel1Action->setOn( TRUE );
	
	if( t == MANDEL_TYPE2)
	    mandel2Action->setOn( TRUE );
	
	if( t == MANDEL_TYPE3)
	    mandel3Action->setOn( TRUE );
	
	if( t == MANDEL_TYPE4)
	    mandel4Action->setOn( TRUE );
	
	if( t == MANDEL_TYPE5)
	    mandel5Action->setOn( TRUE );
	
	if( t == JULIA_TYPE1)
	    julia1Action->setOn( TRUE );
	
	if( t == JULIA_TYPE2 )
	    julia2Action->setOn( TRUE );
	
	if( t == JULIA_TYPE3 )
	    julia3Action->setOn( TRUE );
	
	if( t == JULIA_TYPE4 )
	    julia4Action->setOn( TRUE );
	
	if( t == JULIA_TYPE5 )
	    julia5Action->setOn( TRUE );
	
	//    now we set the data in the metadata class (the class which stores the minimum 
	//    and maximum values of x & y)   				       
	data.setMetaData( t , h , w , miniX , maxiX , miniY , maxiY);
	
	update();	
	
	render( t , h , w , miniX , maxiX , miniY , maxiY );       
    } // else
    
    check = 0;
	
} // load()
bool
TrainingsTageBuch::open(QStringList &errors)
{
    // get a session token, then get the settings for the account
    printd("TrainingStageBuch::open\n");

    // GET ACCOUNT SETTINGS
    QString username = getSetting(GC_TTBUSER).toString();
    QString password = getSetting(GC_TTBPASS).toString();

#if QT_VERSION > 0x050000
    QUrlQuery urlquery;
#else
    QUrl urlquery( TTB_URL + "/settings/list" );
#endif
    urlquery.addQueryItem( "view", "xml" );
    urlquery.addQueryItem( "user", username );
    urlquery.addQueryItem( "pass", password );

#if QT_VERSION > 0x050000
    QUrl url (TTB_URL + "/settings/list");
    url.setQuery(urlquery.query());
    QNetworkRequest request = QNetworkRequest(url);
#else
    QNetworkRequest request = QNetworkRequest(urlquery);
#endif

    request.setRawHeader( "Accept-Encoding", "identity" );
    request.setRawHeader( "Accept", "application/xml" );
    request.setRawHeader( "Accept-Charset", "utf-8" );

    // block waiting for response...
    QEventLoop loop;
    reply = nam->get(request);
    connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
    loop.exec();

    TTBSettingsParser handler;
    QXmlInputSource source(reply);

    QXmlSimpleReader reader;
    reader.setContentHandler(&handler);

    if(! reader.parse(source) ){
        errors << (tr("failed to parse Settings response: ")+handler.errorString());
        return false;
    }

    if( handler.error.length() > 0 ){
        errors << (tr("failed to get settings: ") +handler.error);
        return false;
    }

    sessionId = handler.session;
    proMember = handler.pro;

    // if we got a session id, no need to go further.
    if(sessionId.length() > 0) return true;

    // GET SESSION TOKEN

#if QT_VERSION > 0x050000
    urlquery = QUrlQuery();
#else
    urlquery = QUrl(TTB_URL + "/login/sso");
#endif
    urlquery.addQueryItem( "view", "xml" );
    urlquery.addQueryItem( "user", username );
    urlquery.addQueryItem( "pass", password );

#if QT_VERSION > 0x050000
    url = QUrl(TTB_URL + "/login/sso");
    url.setQuery(urlquery.query());
    request = QNetworkRequest(url);
#else
    request = QNetworkRequest(urlquery);
#endif

    request.setRawHeader( "Accept-Encoding", "identity" );
    request.setRawHeader( "Accept", "application/xml" );
    request.setRawHeader( "Accept-Charset", "utf-8" );

    // block waiting for response
    reply = nam->get(request);
    connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
    loop.exec();

    TTBSessionParser shandler;
    QXmlInputSource ssource(reply);

    reader.setContentHandler(&shandler);

    if(! reader.parse(ssource)) {
        errors << (tr("failed to parse Session response: ")+shandler.errorString());
        return false;
    }

    if(handler.error.length() > 0){
        errors << (tr("failed to get new session: ") +shandler.error );
        return false;
    }

    sessionId = shandler.session;

    if(sessionId.length() == 0){
        errors << (tr("got empty session"));
        return false;
    }

    // SUCCESS
    return true;
}
예제 #4
0
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();
}
예제 #5
0
VideoWindow::VideoWindow(Context *context)  :
    GcWindow(context), context(context), m_MediaChanged(false)
{
    setControls(NULL);
    setProperty("color", QColor(Qt::black));

    QHBoxLayout *layout = new QHBoxLayout();
    setLayout(layout);

    curPosition = 1;

    init = true; // assume initialisation was ok ...

#ifdef GC_VIDEO_VLC
    //
    // USE VLC VIDEOPLAYER
    //
#if QT_VERSION >= 0x050000
#warning "WARNING: Please ensure the VLC QT4 plugin (gui/libqt4_plugin) is NOT available as it will cause GC to crash."
#endif

    // config parameters to libvlc
    const char * const vlc_args[] = {
                    "-I", "dummy", /* Don't use any interface */
                    "--ignore-config", /* Don't use VLC's config */
                    "--disable-screensaver", /* disable screensaver during playback */
#ifdef Q_OS_LINUX
                    "--no-xlib", // avoid xlib thread error messages
#endif
                    //"--verbose=-1", // -1 = no output at all
                    //"--quiet"
                };

    /* create an exception handler */
    //libvlc_exception_init(&exceptions);
    //vlc_exceptions(&exceptions);

    /* Load the VLC engine */
    inst = libvlc_new(sizeof(vlc_args) / sizeof(vlc_args[0]), vlc_args);
    //vlc_exceptions(&exceptions);

    /* Create a new item */

    if (inst) { // if vlc doesn't initialise don't even try!

        m = NULL;
        //vlc_exceptions(&exceptions);

        /* Create a media player playing environement */
        mp = libvlc_media_player_new (inst);
        //vlc_exceptions(&exceptions);

        //vlc_exceptions(&exceptions);


    /* This is a non working code that show how to hooks into a window,
     * if we have a window around */
#ifdef Q_OS_LINUX
#if QT_VERSION > 0x50000
        x11Container = new QWidget(this); //XXX PORT TO 5.1 BROKEN CODE XXX
#else
        x11Container = new QX11EmbedContainer(this);
#endif
        layout->addWidget(x11Container);
        libvlc_media_player_set_xwindow (mp, x11Container->winId());
#endif

#ifdef WIN32
        container = new QWidget(this);
        layout->addWidget(container);
        libvlc_media_player_set_hwnd (mp, (HWND)(container->winId()));

        QString filename = context->athlete->home->config().canonicalPath() + "/" + "video-layout.xml";
        QFileInfo finfo(filename);

        if (finfo.exists())
        {
            QFile file(filename);

            // clean previous layout
            foreach(MeterWidget* p_meterWidget, m_metersWidget)
            {
                m_metersWidget.removeAll(p_meterWidget);
                delete p_meterWidget;
            }

            VideoLayoutParser handler(&m_metersWidget, container);

            QXmlInputSource source (&file);
            QXmlSimpleReader reader;
            reader.setContentHandler (&handler);

            reader.parse (source);
        }
예제 #6
0
파일: main.cpp 프로젝트: Interima/Menaan
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();
}
예제 #7
0
//
// 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 3 months"));
    season.setType(Season::temporary);
    season.setEnd(today);
    season.setStart(today.addMonths(-3));
    season.setId(QUuid("{00000000-0000-0000-0000-000000000008}"));
    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!
}
예제 #8
0
void MainWindow::statusXmlIsReady(QNetworkReply* reply) {
    qDebug() << "updating server status";

    if (reply->error() != QNetworkReply::NoError) {
        QString errorStr = reply->errorString();

        if (!errorStr.isEmpty()) {
            ui->textBrowser->setText("Error while fetching server status:" + errorStr);
            return;
        }
    }

    QXmlSimpleReader xmlReader;
    QXmlInputSource inputSource;
    inputSource.setData(reply->readAll());

    //StatusXmlContentHandler* handler = new StatusXmlContentHandler(this);
    StatusXmlContentHandler handler(this);
    xmlReader.setContentHandler(&handler);
    xmlReader.parse(&inputSource);

    QMap<QString, QString>* values = handler.getValues();

    QString labelText;
    QTextStream stream(&labelText);

    bool up = values->value("status") == "up";

    stream << "<div align=\"center\"><b>" << values->value("name") << "</b></div>";

    if (up) {
        stream << "<div align=\"center\" style=\"color:green\">Status: " << values->value("status") << "</div>";

        stream << "<div align=\"center\">Current online connections: " << values->value("connected") << "</div>";
        stream << "<div align=\"center\">Max allowed connections: " << values->value("cap") << "</div>";
        /*QDateTime upTime;
        upTime.addSecs(values->value("uptime").toULong());*/
        //upTime.
        //stream << "<div align=\"center\">Uptime: " << values->value("uptime") << " seconds</div>";
        QString uptimeString;
        QTextStream uptimeStream(&uptimeString);
        qint64 uptimeSeconds = values->value("uptime").toULongLong();
        //if (uptimeSeconds % )
        qint64 minutes = uptimeSeconds / 60 % 60;
        qint64 hours = uptimeSeconds / 3600 % 24;
        qint64 days = uptimeSeconds / 86400;

        if (days != 0) {
            uptimeStream << days << (days == 1 ? " day " : " days ") << hours << (hours == 1 ? " hour " : " hours ") << minutes << (minutes == 1 ? " minute " : " minutes" );
        } else if (hours != 0) {
            uptimeStream << hours << (hours == 1 ? " hour " : " hours ") << minutes << (minutes == 1 ? " minute " : " minutes ");
        } else {
            uptimeStream << minutes << (minutes == 1 ? " minute " : " minutes ") << uptimeSeconds % 60 << " seconds";
        }

        stream << "<div align=\"center\">Uptime: " << uptimeString << " </div>";
    } else
        stream << "<div align=\"center\" style=\"color:red\">Status: " << values->value("status") << "</div>";

    QDateTime timestamp;
    timestamp.setTime_t(values->value("timestamp").toULong());
    stream << "<div align=\"center\">Last updated: " << timestamp.toString(Qt::SystemLocaleShortDate) << "</div><br>";
    stream << "<div align=\"center\"><i>Notice:</i> " << values->value("notice") << "</div><br>";
    stream << "<div align=\"center\">" << values->value("banner") << "</div><br><br>";

    ui->textBrowser->insertHtml(labelText);
}
예제 #9
0
파일: tvr.cpp 프로젝트: Geekking/lima
int main(int argc,char* argv[])
{
  QCoreApplication a(argc, argv);
  QsLogging::initQsLog();
  string resourcesPath=string(getenv("LIMA_RESOURCES"));
  string configDir=string(getenv("LIMA_CONF"));
  string lpConfigFile=string("lima-lp-tvr.xml");
  string commonConfigFile=string("lima-common.xml");
  string clientId=string("lp-structuredXmlreaderclient");
  string workingDir=string(".");

  if (resourcesPath.empty())
  {
    resourcesPath = "/usr/share/apps/lima/resources/";
  }
  if (configDir.empty())
  {
    configDir = "/usr/share/config/lima/";
  }

  deque<string> files;
  deque<string> langs;
  deque<string> pipelines;

  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);
      }
    }
  }

  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,
    MediaticData::single().getMedias());

  client=dynamic_cast<AbstractLinguisticProcessingClient*>(LinguisticProcessingClientFactory::single().createClient(clientId));
  
  
  ReaderTestCaseProcessor
    readerTestCaseProcessor(workingDir, client);
    
  QXmlSimpleReader parser;
  TestCasesHandler tch(readerTestCaseProcessor);

  parser.setContentHandler(&tch);
  parser.setErrorHandler(&tch);

  for (deque<string>::const_iterator it=files.begin();
       it!=files.end();
       it++)
  {
    cout << "process tests in " << *it << 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)
    {
      cerr << "caught LimaException : " << endl << e.what() << endl;
    }
    catch (logic_error& e)
    {
      cerr << "caught logic_error : " << endl << e.what() << endl;
    }

    TestCasesHandler::TestReport resTotal;
    cout << endl;
    cout << "=========================================================" << endl;
    cout << endl;
    cout << "  TestReport :   " << *it << " " << endl;
    cout << endl;
    cout << "\ttype           \tsuccess\tcond.\tfailed\ttotal" << endl;
    cout << "---------------------------------------------------------" << endl;
    for (map<string,TestCasesHandler::TestReport>::const_iterator resItr=tch.m_reportByType.begin();
         resItr!=tch.m_reportByType.end();
         resItr++)
    {
      string label(resItr->first);
      label.resize(15,' ');
      cout << "\t" << label << "\t" << resItr->second.success << "\t" << resItr->second.conditional << "\t" << resItr->second.failed << "\t" << resItr->second.nbtests << endl;
      resTotal.success+=resItr->second.success;
      resTotal.conditional+=resItr->second.conditional;
      resTotal.failed+=resItr->second.failed;
      resTotal.nbtests+=resItr->second.nbtests;
    }
    cout << "---------------------------------------------------------" << endl;
    cout << "\ttotal          \t" << resTotal.success << "\t" << resTotal.conditional << "\t" << resTotal.failed << "\t" << resTotal.nbtests << endl;
    cout << "=========================================================" << endl;
    cout << endl;
    tch.m_reportByType.clear();
  }
}
예제 #10
0
int run(int argc, char** argv)
{
  readCommandLineArguments(argc, argv);

  if (param->help)
  {
    usage(argc, argv);
    exit(0);
  }

  std::string resourcesPath = (getenv("LIMA_RESOURCES")!=0) ? string(getenv("LIMA_RESOURCES")) : string("/usr/share/apps/lima/resources");
  std::string configPath = (param->configDir.size()>0) ? param->configDir : string("");
  if (configPath.size() == 0)
    configPath = string(getenv("LIMA_CONF"));
  if (configPath.size() == 0)
    configPath = string("/usr/share/config/lima");

  if (QsLogging::initQsLog(QString::fromUtf8(configPath.c_str())) != 0)
  {
    LOGINIT("Common::Misc");
    LERROR << "Call to QsLogging::initQsLog(\"" << configPath << "\") failed.";
    return EXIT_FAILURE;
  }

  // Necessary to initialize factories
  Lima::AmosePluginsManager::single();

  setlocale(LC_ALL,"fr_FR.UTF-8");

  // check that input file exists
  {
    ifstream fin(param->input.c_str(), std::ifstream::binary);
    if (!fin.good())
    {
      cerr << "can't open input file " << param->input << endl;
      exit(-1);
    }
    fin.close();
  }

  // parse charchart
  if (param->charChart == "") {
    cerr << "please specify CharChart file with --charChart=<file> option" << endl;
    exit(0);
  }
  CharChart charChart;
  charChart.loadFromFile(param->charChart);

  try
  {
    cerr << "parse charChart file : " << param->charChart << endl;
//     cerr << "TODO: to implement at "<<__FILE__<<", line "<<__LINE__<<"!" <<std::endl;
//     exit(2);
//     charChart = 0;
/*    ParseCharClass parseCharClass;
    parseCharClass.parse(param->charChart);
    charChart = ParseChar::parse(param->charChart, parseCharClass);*/
  }
  catch (exception& e)
  {
    cerr << "Caught exception while parsing file " << param->charChart << endl;
    cerr << e.what() << endl;
    exit(-1);
  }

  if (param->extractKeys != "")
  {
    // just extract keys
    ofstream fout(param->extractKeys.c_str(), std::ofstream::binary);
    if (!fout.good())
    {
      cerr << "can't open file " << param->extractKeys << endl;
      exit(-1);
    }
    KeysLogger keysLogger(fout,&charChart,param->reverseKeys);

    cerr << "parse input file : " << param->input << endl;
    try
    {
      QXmlSimpleReader parser;
      //     parser->setValidationScheme(SAXParser::Val_Auto);
      //     parser->setDoNamespaces(false);
      //     parser->setDoSchema(false);
      //     parser->setValidationSchemaFullChecking(false);
      parser.setContentHandler(&keysLogger);
      parser.setErrorHandler(&keysLogger);
      QFile file(param->input.c_str());
      if (!file.open(QIODevice::ReadOnly))
      {
        std::cerr << "Error opening " << param->input << std::endl;
        return 1;
      }
      if (!parser.parse( QXmlInputSource(&file)))
      {
        std::cerr << "Error parsing " << param->input << " : " << parser.errorHandler()->errorString().toUtf8().constData() << std::endl;
        return 1;
      }
      else
      {
        std::cerr << std::endl;
      }
    }
    catch (const XMLException& toCatch)
    {
      std::cerr << "An error occurred  Error: " << toCatch.what() << endl;
      throw;
    }
    fout.close();
  } else {
    // compile dictionaries

    cerr << "parse property code file : " << param->propertyFile << endl;
    PropertyCodeManager propcodemanager;
    propcodemanager.readFromXmlFile(param->propertyFile);

    cerr << "parse symbolicCode file : " << param->symbolicCodes << endl;
    map<string,LinguisticCode> conversionMap;
    propcodemanager.convertSymbolicCodes(param->symbolicCodes,conversionMap);
    cerr << conversionMap.size() << " code read from symbolicCode file" << endl;
/*    for (map<string,LinguisticCode>::const_iterator it=conversionMap.begin();
         it!=conversionMap.end();
         it++)
    {
      cerr << it->first << " -> " << it->second << endl;
    }*/

    AbstractAccessByString* access(0);
    if (param->fsaKey!="") {
      cerr << "load fsa access method : " << param->fsaKey << endl;
      FsaAccessSpare16* fsaAccess=new FsaAccessSpare16();
      fsaAccess->read(param->fsaKey);
      access=fsaAccess;
    } else {
      cerr << "ERROR : no access Keys defined !" << endl;
      exit(-1);
    }
    cerr << access->getSize() << " keys loaded" << endl;

    cerr << "parse input file : " << param->input << endl;
    DictionaryCompiler handler(&charChart,access,conversionMap,param->reverseKeys);

    QXmlSimpleReader parser;
//     parser->setValidationScheme(SAXParser::Val_Auto);
//     parser->setDoNamespaces(false);
//     parser->setDoSchema(false);
//     parser->setValidationSchemaFullChecking(false);
    try
    {
      parser.setContentHandler(&handler);
      parser.setErrorHandler(&handler);
      QFile file(param->input.c_str());
      if (!file.open(QIODevice::ReadOnly))
      {
        std::cerr << "Error opening " << param->input << std::endl;
        return 1;
      }
      if (!parser.parse( QXmlInputSource(&file)))
      {
        std::cerr << "Error parsing " << param->input << " : " << parser.errorHandler()->errorString().toUtf8().constData() << std::endl;
        return 1;
      }
    }
    catch (const XMLException& toCatch)
    {
      cerr << "An error occurred  Error: " << toCatch.what() << endl;
      throw;
    }

    cerr << "write data to output file : " << param->output << endl;
    ofstream fout(param->output.c_str(),ios::out | ios::binary);
    if (!fout.good())
    {
      cerr << "can't open file " << param->output << endl;
      exit(-1);
    }
    handler.writeBinaryDictionary(fout);
    fout.close();
    delete access;
  }
  return EXIT_SUCCESS;
}
예제 #11
0
void MainWindow::queueStepBegin()
{
    if(queue.isEmpty()) return;

    currentAct = queue.dequeue();

    switch(currentAct.type)
    {
    case ACT_LOCK_CONFIG_PAGE:
        qDebug() << "ACT: lock config page";
        ui->refresh->setEnabled(false);
        statusBar()->clearMessage();
        cancelStatusBarButton->hide();
        ui->progressBar->show();
        queueStepBegin();
        break;

    case ACT_DOWNLOAD_FILE:
        qDebug() << "ACT: Download file" << currentAct.param1 << currentAct.param2 << currentAct.param3;
        curstep++;
        downloader.downloadFile(currentAct.param1, currentAct.param2);
        statusBar()->showMessage(tr("Step %1/%2 Downloading file %3...").arg(curstep).arg(totalSteps).arg(currentAct.param1));
        cancelStatusBarButton->show();
        break;

    case ACT_PARSE_CPACK_LIST_XML:
    {
        qDebug() << "ACT: parse XML file";
        XMLCpackList handler;
        QXmlSimpleReader reader;
        reader.setContentHandler(&handler);
        reader.setErrorHandler(&handler);
        QFile file(tempDir + "/configs.index");

        if(!file.open(QFile::ReadOnly | QFile::Text))
        {
            queueStepBegin();
            break;
        }

        QXmlInputSource xmlInputSource(&file);

        if(reader.parse(xmlInputSource))
        {}

        queueStepBegin();
    }
    break;

    case ACT_REBUILD_CPACK_LIST:
        buildConfigPackList();
        queueStepBegin();
        break;

    case ACT_UNLOCK_CONFIG_PAGE:
        qDebug() << "ACT: unlock config page";
        ui->refresh->setEnabled(true);
        ui->progressBar->hide();
        cancelStatusBarButton->hide();
        queueStepBegin();
        break;

    case ACT_SHOWMSG:
        qDebug() << "ACT: show msg" << currentAct.param1 << currentAct.param2;
        statusBar()->showMessage(currentAct.param1, currentAct.param2.toInt());
        queueStepBegin();
        break;

    default:
        queueStepBegin();
        break;
    }
}
void FRXMLCharDataReader::parseFiles(Document *pDocument, std::vector<ImageChar> &imageCharVec, std::vector<std::string> &charVec) const
{
	imageCharVec.clear(); charVec.clear();

	// load document images if not done yet:
	if (!pDocument->isDocumentImagesLoaded()) {
		std::cout << "opening document images" << std::endl;
		pDocument->openDocumentImages();
	}
	// create XML filenames:
//	pDocument->createSegmentationResultFileNames();
	pDocument->createSegmentationResultFileNames("xml", pDocument->parsingParameters().filenamePrefix,  pDocument->parsingParameters().filenameSuffix);

	// create the finereader xml output handler object need for parsing the files
	FineReaderXMLOutputHandler *pXMLHandler = new FineReaderXMLOutputHandler();
	// create simple reader and set the content/error handler
    QXmlSimpleReader reader;
    reader.setContentHandler(pXMLHandler);
    reader.setErrorHandler(pXMLHandler);

    int parsedCharsCount = 0;
    for (int i=0; i < pDocument->nFiles(); ++i) {
    	const std::string& xmlFileName = pDocument->segmentationResultFileName(i);
    	// create QFile object
        QFile file( QString::fromStdString(xmlFileName) );
        if (!file.open(QFile::ReadOnly | QFile::Text)) {
        	throw Exception("Error openening xml-file in FRXMLCharDataReader::parseXMLFiles!");
        }
        // create xml input source from file object
        QXmlInputSource xmlInputSource(&file);
        // parse the file using the simple reader
        reader.parse(xmlInputSource);
        std::cout << "Successfully parsed xml data of file " << xmlFileName << std::endl;
    	// store results
        SimpleFineReaderXMLData* pData = pXMLHandler->getFineReaderData();
        GrayImage<>* pImage = pDocument->imagePointer(i);
//        const int pType = pDocument->parsingParameters().parsingType;
        const ParseSubsetType pType = pDocument->parsingParameters().parsingType;
        std::cout << "Parsing type is: " << pType << std::endl;
        for (int j=0; j<pData->parsedBBoxes.size(); ++j) {
        	ImageChar imChar(pData->parsedBBoxes[j], pImage, i, parsedCharsCount);
        	imChar.text = pData->parsedChars[j];
        	imChar.suspicious = pData->isSuspicious[j];
        	//        	std::cout << "isSusp = " << imChar.suspicious << std::endl;
			// add imagechar to list, depending on parsing type:
        	// 0-->parse all chars, 1-->parse all non-susp. chars, 2-->parse all susp. chars

        	if (pType == UNKNOWN_PARSESUBSET_TYPE) {
        		throw Exception("An invalid parsing type was given!");
        	}
        	else if ((pType == 0) || (pType == PARSE_ONLY_NON_SUSP && !imChar.suspicious) || (pType == PARSE_ONLY_SUSP && imChar.suspicious)) {
				++parsedCharsCount;
				imageCharVec.push_back(imChar);
				charVec.push_back(pData->parsedChars[j]);
			}
        	else if (pType == PARSE_SUBSET) {

        	}
        } // end for j
        pXMLHandler->clearData();
    } // end for all xml files
    std::cout << "Successfully parsed " << pDocument->nFiles() << " xml files!" << std::endl;
    delete pXMLHandler;

	return;
} // end parseXMLFiles
예제 #13
0
/*
 * This program accepts the following command line options
 * -lab string: name of file with lab description (default, stdin);
 * -grid string: name of file with start position grid (default, stdin);
 * -log string: name of log file (default, server.log);
 * -nc real: compass noise coeficient (default, 0.0);
 * -nb real: beacon noise coeficient (default, 0.0);
 * -ni real: infrared noise coeficient (default, 0.0);
 * -nm real: motors noise coeficient (default, 0.0);
 * -st integer: simulation time, in number of cycle time units (default, 3000);
 * -ct integer: cycle time, in miliseconds (default, 75).
 */
int main(int argc, char *argv[])
{
	/* Copyright and wellcome message */
	printf(" CiberRato 2013 Logplayer\n Copyright (C) 2003-2013 Universidade de Aveiro\n");

	/* extract option values */
	char *logFilename = 0;
	int port = 6000;

    QApplication app(argc,argv);


    //cout << "Parsing command line..."

    int p=1;
	while (p < argc) 
	{
        if (strcmp(argv[p], "-log") == 0) {
            if (p+1 < argc) {
                logFilename = argv[p+1];
                p+=2;
            }
            else CommandLineError();
		}
        else if (strcmp(argv[p], "-port") == 0)	{
            if (p+1 < argc) {
                sscanf(argv[p+1], "%d", &port);
                p+=2;
            }
            else CommandLineError();
		}
        else {
            CommandLineError();
		}
	}
	
	//cout << " done.\n";

	/* create lab object and parse lab file */
	//cout << "Creating lab object...";
	QXmlInputSource *source;

    if(logFilename) {
        QFile srcFile(logFilename);

        if(!srcFile.exists())
        {
            cerr << "Could not open log file " << logFilename << "\n";
            QMessageBox::critical(0,"Error", QString("Could not open log file ") + logFilename,
                                  QMessageBox::Ok,Qt::NoButton,Qt::NoButton);
            return 1;
        }
        if ((source = new QXmlInputSource(&srcFile)) == 0)
        {
            cerr << "Fail sourcing log file\n";
                        QMessageBox::critical(0,"Error", QString("Failed sourcing log file "),
                               QMessageBox::Ok,Qt::NoButton,Qt::NoButton);
            return 1;
        }

        cbLogHandler *logHandler = new cbLogHandler(&xmlParser);
        xmlParser.setContentHandler(logHandler);

        if( ! xmlParser.parse(*source) )
        {
            cerr << "Error parsing log file\n";
                        QMessageBox::critical(0,"Error", QString("Error parsing log file"),
                                              QMessageBox::Ok,Qt::NoButton,Qt::NoButton);
            return 1;
        }
        vector< vector <cbRobot> > *log = logHandler->parsedLog();
        logplayer.setLog(log);
        if(logHandler->getLab()!=0)
            logplayer.setLab(logHandler->getLab());
        else
        {
            cerr << "Error parsing log file\n";
            QMessageBox::critical(0,"Error", QString("Error parsing log file"),
                                  QMessageBox::Ok,Qt::NoButton,Qt::NoButton);
            return 1;
        }
        if(logHandler->getGrid()!=0)
            logplayer.setGrid(logHandler->getGrid());
        else
        {
            cerr << "Error parsing log file\n";
            QMessageBox::critical(0,"Error", QString("Error parsing log file"),
                                  QMessageBox::Ok,Qt::NoButton,Qt::NoButton);
            return 1;
        }
        if(logHandler->getParameters()!=0)
            logplayer.setParameters(logHandler->getParameters());
        else
        {
            cerr << "Error parsing log file\n";
            QMessageBox::critical(0,"Error", QString("Error parsing log file"),
                                  QMessageBox::Ok,Qt::NoButton,Qt::NoButton);
            return 1;
        }
        delete logHandler;
        delete source;
    }
    else {
        CommandLineError();
        return 1;
    }

	/* preparing the receptionist */
	//cout << "Launching the receptionist...";
	cbReceptionist *receptionist = new cbReceptionist(port);
	if (receptionist == 0 || receptionist->bad())
    {
        QMessageBox::critical(0,"Error", QString("Error creating socket"),
                              QMessageBox::Ok,Qt::NoButton,Qt::NoButton);
		//cerr << "fail\n";
		return 1;
	}
	receptionist->setXmlParser(&xmlParser);
	logplayer.setReceptionist(receptionist);
	//cout << " done.\n";
	
	/* preparing the random generator */
#ifndef MicWindows
	srand(getpid());
#else
	srand(_getpid());
#endif

    /* preparing ALARM timer */
	QTimer timer;
	timer.start(logplayer.cycleTime());
	QObject::connect(&timer,SIGNAL(timeout()),&logplayer,SLOT(step()));

    QWidget *gui = new QWidget;
    Ui::logplayerGUI ui;
    ui.setupUi(gui);

    QObject::connect(ui.QuitButton,SIGNAL(clicked()),&app,SLOT(quit()));
    logplayer.setGUI(&ui);
    gui->setMaximumSize(gui->size());
    gui->setMinimumSize(gui->size());
    gui->show();

	app.exec();

	return 0;
}
예제 #14
0
/*******************************************
 * DeviceInfo::DeviceInfo
 ******************************************/
DeviceInfo::DeviceInfo( QObject *parent ) :
    QObject(parent),
    m_batteryLevel(BATTERYLEVEL_DEFAULT),
    m_copyrightInfo(COPYRIGHTINFO_DEFAULT),
    m_syncPartner(SYNCPARTNER_DEFAULT),
    m_deviceFriendlyName(DEVFRNDNAME_DEFAULT),
    m_deviceIconPath(DEVICON_DEFAULT),
    m_standardVersion(STDVER_DEFAULT),
    m_vendorExtension(VENDOREXTN_DEFAULT),
    m_mtpVersion(MTPVER_DEFAULT),
    m_mtpExtension(MTPEXTN_DEFAULT),
    m_functionalMode(FNMODE_DEFAULT),
    m_manufacturer(MFR_DEFAULT),
    m_model(MODEL_DEFAULT),
    m_serialNo(SERNO_DEFAULT),
    m_deviceVersion(DEVVER_DEFAULT),
    m_deviceType(DEVTYPE_DEFAULT),
    m_imageMinWidth(IMAGE_MIN_WIDTH), m_imageMaxWidth(IMAGE_MAX_WIDTH),
    m_imageMinHeight(IMAGE_MIN_HEIGHT), m_imageMaxHeight(IMAGE_MAX_HEIGHT),
    m_videoMinWidth(VIDEO_MIN_WIDTH), m_videoMaxWidth(VIDEO_MAX_WIDTH),
    m_videoMinHeight(VIDEO_MIN_HEIGHT), m_videoMaxHeight(VIDEO_MAX_HEIGHT),
    m_videoMinFPS(0), m_videoMaxFPS(100000), m_videoScanType(0x0001), m_videoSampleRate(0),
    m_videoMinBitRate(0), m_videoMaxBitRate(0xFFFFFFFF),
    m_audioMinBitRate(0), m_audioMaxBitRate(0xFFFFFFFF),
    m_videoAudioMinBitRate(0), m_videoAudioMaxBitRate(0xFFFFFFFF),
    m_videoMinKFD(0), m_videoMaxKFD(0xFFFFFFFF),
    m_audioSampleRate(0)
{
    //Parse deviceinfo.xml to populate default device values.

    // Kludge : till we know how and where to securely install a file
    // that can be modifed by an apllication.
    QFile fileDst(getDeviceInfoXmlPath());
#ifndef UT_ON
    QFile fileSrc("/usr/share/mtp/deviceinfo.xml");
    if( !fileDst.exists() )
    {
        fileSrc.copy(m_deviceInfoXmlPath);
    }
#endif // UT_ON
    fileDst.open(QIODevice::ReadOnly | QIODevice::Text);
    QXmlSimpleReader xmlReader;
    QXmlInputSource source(&fileDst);
    XMLHandler handler(this);
    xmlReader.setContentHandler(&handler);
    xmlReader.setErrorHandler(&handler);
    m_xmlOk = false;

    if(0 == xmlReader.parse(&source))
    {
        MTP_LOG_CRITICAL("Failure reading deviceinfo.xml, using default hard-coded values\n");
        //FIXME Hard code the QVectors themselves by default? Then we can avoid the memcpy.
        for( quint32 i = 0 ; i < sizeof(m_operationsSupportedTable)/sizeof(m_operationsSupportedTable[0]); i++ )
        {
            m_mtpOperationsSupported.append( m_operationsSupportedTable[i] );
        }
        for( quint32 i = 0 ; i < sizeof(m_eventsSupportedTable)/sizeof(m_eventsSupportedTable[0]); i++ )
        {
            m_mtpEventsSupported.append( m_eventsSupportedTable[i] );
        }
        for( quint32 i = 0 ; i < sizeof(m_devPropsSupportedTable)/sizeof(m_devPropsSupportedTable[0]); i++ )
        {
            m_mtpDevicePropertiesSupported.append( m_devPropsSupportedTable[i] );
        }
        for( quint32 i = 0 ; i < sizeof(m_commonFormatsTable)/sizeof(m_commonFormatsTable[0]); i++ )
        {
            m_commonFormats.append( m_commonFormatsTable[i] );
        }
        for( quint32 i = 0 ; i < sizeof(m_audioFormatsTable)/sizeof(m_audioFormatsTable[0]); i++ )
        {
            m_audioFormats.append( m_audioFormatsTable[i] );
        }
        for( quint32 i = 0 ; i < sizeof(m_imageFormatsTable)/sizeof(m_imageFormatsTable[0]); i++ )
        {
            m_imageFormats.append( m_imageFormatsTable[i] );
        }
        for( quint32 i = 0 ; i < sizeof(m_videoFormatsTable)/sizeof(m_videoFormatsTable[0]); i++ )
        {
            m_videoFormats.append( m_videoFormatsTable[i] );
        }
        for( quint32 i = 0 ; i < sizeof(m_audChannelTable)/sizeof(m_audChannelTable[0]); i++ )
        {
            m_audioChannels.append( m_audChannelTable[i] );
        }
        for( quint32 i = 0 ; i < sizeof(m_vidChannelTable)/sizeof(m_vidChannelTable[0]); i++ )
        {
            m_videoChannels.append( m_vidChannelTable[i] );
        }
        for( quint32 i = 0 ; i < sizeof(m_supportedCodecsTable)/sizeof(m_supportedCodecsTable[0]); i++ )
        {
            m_supportedCodecs.append( m_supportedCodecsTable[i] );
        }
    }
    else
    {
        m_xmlOk = true;
    }
    m_supportedFormats = m_imageFormats + m_audioFormats + m_videoFormats + m_commonFormats;
}
예제 #15
0
파일: main.cpp 프로젝트: cpina/qdacco
void Main::UpdateList() {
	StructureList handler;

	handler.setIgnoreCase(m_IgnoreCase);
	handler.setIgnoreAccents(m_IgnoreAccents);

	AuxiliarGUI::m=this;
	int (*ptrFunction)(QString)=NULL;
	ptrFunction = lib2class;

	handler.setAddFunction(ptrFunction);
       
       	QString search = ui.paraula->text();

	handler.setWord(search);

        char letter;

        QString idioma;
	ui.llistat->show();

        //prepare the path
	if (m_idioma_actiu == Auxiliar::eng2cat() ) {
                idioma="cateng";
        }
        else {
                idioma="engcat";
        }

        if (!isValidWord(search)) {
		ui.definicio->setPlainText(""); //not valid input*
		return;
        }

	letter=lletra_buscar(search);
	QFile xmlFile(m_directori_usuari+"/"+idioma+"/"+letter+".dic");

	if (!xmlFile.exists()) {
		showError(tr("Cannot open dictionary file. Check configuration directory and permissions"));
	}
	else {
		Auxiliar::debug("File2: "+m_directori_usuari+"/"+idioma+"/"+letter+".dic");

		QXmlInputSource source( &xmlFile );
		QXmlSimpleReader reader;
		reader.setFeature("http://trolltech.com/xml/features/report-whitespace-only-CharData",false);   //if we don't use it, we get more entries because spaces...
		reader.setContentHandler(&handler);

		handler.setParaula(search);

		reader.parse(source);

		WordData d = handler.getWordData();

		ui.definicio->setPlainText("");

		ui.definicio->setPlainText("");
		m_searched=search;
		selectItem();
	}
}
예제 #16
0
bool App::openTree(const QString &file)
{
    NotesFileParser handler;

    connect(&handler, SIGNAL(backupLoaded(bool, const QString &)),
            this,       SLOT(setBackupLocation(bool, const QString &)));
    connect(&handler, SIGNAL(notesShowReminderAtStartUpLoaded(bool)),
            this,       SLOT(setNotesShowReminderAtStartUp(bool)));
//  connect(&handler, SIGNAL(notesWordWrapLoaded(bool)),
//          this,       SLOT(setNotesWordWrap(bool)));
//  connect(&handler, SIGNAL(notesRootNodeDecorationLoaded(bool)),
//          this,       SLOT(setNotesRootNodeDecoration(bool)));
//  connect(&handler, SIGNAL(notesShowScrollBarsLoaded(bool)),
//          this,       SLOT(setNotesShowScrollBars(bool)));
    connect(&handler, SIGNAL(entryLoaded(Entry *)),
            this,       SLOT(addEntry(Entry *)));
    connect(&handler, SIGNAL(noteLoaded(const QString &, QList<QString> *,
                                        const QString &, const QString &,
                                        int, QDateTime, const QString &, QDateTime)),
            notes,      SLOT(addNote(const QString &, QList<QString> *,
                                        const QString &, const QString &,
                                        int, QDateTime, const QString &, QDateTime)));
    connect(&handler, SIGNAL(securityPasswdLoaded(const QString &)),
            this,       SLOT(setSecurityPasswd(const QString &)));
    connect(&handler, SIGNAL(noteLoaded(const QString &, Strokes *,
                                        const QString &, const QString &,
                                        int, QDateTime, const QString &, QDateTime)),
            notes,      SLOT(addNote(const QString &, Strokes *,
                                        const QString &, const QString &,
                                        int, QDateTime, const QString &, QDateTime)));
    connect(&handler, SIGNAL(noNoteChild()),
            notes,      SLOT(noNoteChild()));

    QFile xmlFile(Global::applicationFileName("iqnotes", file + ".xml")),
    xmlRijndaelFile(Global::applicationFileName("iqnotes", file + ".rijn"));
    QXmlInputSource *source;

    // Init xml file
    if (!xmlFile.exists() && !xmlRijndaelFile.exists())
    {
        xmlFile.open(IO_WriteOnly);
        QTextStream ts(&xmlFile);

        ts << "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<iqnotes>\n<entries>\n"

        << "<entry name=\"Company\">\n"
        << "<property name=\"Name\" type=\"oneLine\"/>\n"
        << "<property name=\"Address\" type=\"multiLine\"/>\n"
        << "<property name=\"Tels\" type=\"oneLine\"/>\n"
        << "<property name=\"Emails\" type=\"oneLine\"/>\n"
        << "<property name=\"Note\" type=\"multiLine\"/>\n"
        << "</entry>\n"

        << "<entry name=\"Person\">\n"
        << "<property name=\"Name\" type=\"oneLine\"/>\n"
        << "<property name=\"Nick\" type=\"oneLine\"/>\n"
        << "<property name=\"Work Address\" type=\"multiLine\"/>\n"
        << "<property name=\"Work Tel\" type=\"oneLine\"/>\n"
        << "<property name=\"Work Emails\" type=\"oneLine\"/>\n"
        << "<property name=\"Home Address\" type=\"multiLine\"/>\n"
        << "<property name=\"Home Tel\" type=\"oneLine\"/>\n"
        << "<property name=\"Emails\" type=\"oneLine\"/>\n"
        << "<property name=\"Note\" type=\"multiLine\"/>\n"
        << "</entry>\n"

        << "<entry name=\"User account\">\n"
        << "<property name=\"Host\" type=\"oneLine\"/>\n"
        << "<property name=\"Username\" type=\"oneLine\"/>\n"
        << "<property name=\"Password\" type=\"oneLine\"/>\n"
        << "<property name=\"Type\" type=\"oneLine\"/>\n"
        << "<property name=\"Note\" type=\"mutliLine\"/>\n"
        << "</entry>\n"

        << "<entry name=\"Credit card\">\n"
        << "<property name=\"Card type\" type=\"oneLine\"/>\n"
        << "<property name=\"Account #\" type=\"oneLine\"/>\n"
        << "<property name=\"Expire\" type=\"oneLine\"/>\n"
        << "<property name=\"PIN\" type=\"oneLine\"/>\n"
        << "<property name=\"Note\" type=\"mutliLine\"/>\n"
        << "</entry>\n"

        << "<entry name=\"WWW Link\">\n"
        << "<property name=\"Title\" type=\"oneLine\"/>\n"
        << "<property name=\"URL\" type=\"oneLine\"/>\n"
        << "<property name=\"Description\" type=\"multiLine\"/>\n"
        << "</entry>\n"

        << "</entries>\n"
        << "<notes>\n</notes>\n</iqnotes>\n";

        xmlFile.close();
        source = new QXmlInputSource(xmlFile);
    }
    else if (xmlRijndaelFile.exists())
    {
        StartUpPasswdBase passwdD(this, 0, true);
        passwdD.adjustSize();
        if (!passwdD.exec())
        {
            return false;
        }
        
        preferences.setPasswd(passwdD.Passwd->text());

        xmlRijndaelFile.open(IO_ReadOnly);
        uint fileSize = xmlRijndaelFile.size();
        unsigned char *rijnData = (unsigned char *) malloc(fileSize),
            *rijnDataDecrypted = (unsigned char *) malloc(fileSize);
        Rijndael rijndael;

        xmlRijndaelFile.readBlock((char *)rijnData, fileSize);
        rijndael.init(Rijndael::CBC, Rijndael::Decrypt, preferences.passwd16Bin, Rijndael::Key16Bytes);
        rijndael.padDecrypt(rijnData, fileSize, rijnDataDecrypted);

		// yeah, stupid
        if (memcmp((void *)"<iqnotes>", (void *)rijnDataDecrypted, 9) != 0 && memcmp((void *)"<?xml version", (void *)rijnDataDecrypted, 13) != 0)
        {
            free(rijnData);
            free(rijnDataDecrypted);

            QMessageBox::critical(this, "Bad password", "Please,\ntype correct password.");

            return false;
        }

        source = new QXmlInputSource();
        //        source->setData(QString((char *)rijnDataDecrypted));
        source->setData(QString::fromUtf8((char *)rijnDataDecrypted));

        free(rijnData);
        free(rijnDataDecrypted);
    }
    else
    {
        source = new QXmlInputSource(xmlFile);
    }

    QXmlSimpleReader reader;
    reader.setContentHandler(&handler);
    reader.setErrorHandler(new NotesFileParserError);
    if(!reader.parse(*source))
        qWarning(tr("parse error"));

    delete source;

    setCaption("IQNotes :: " + file);
     
    return true;
}
예제 #17
0
파일: main.cpp 프로젝트: cpina/qdacco
void Main::treballaBuscar() {
        StructureParser handler;

       	QString buscar = ui.paraula->text();
        QString buscar_orig = ui.paraula->text();
        char lletra;

        QString idioma;

        //per preparar el path
        if (m_idioma_actiu== Auxiliar::eng2cat() ) {
                idioma="cateng";
        }
        else {
                idioma="engcat";
        }

        if (!isValidWord(buscar)) {
		showError(tr("You have to write a word. The word has to start with a letter."));
                ui.definicio->setPlainText(""); //not valid input
        }
        else {  //TODO: clean this crazy if-else!

		lletra=lletra_buscar(buscar);
		QFile xmlFile(m_directori_usuari+"/"+idioma+"/"+lletra+".dic");


		if (!xmlFile.exists()) {
			showError(tr("Cannot open dictionary file. Check configuration directory and permissions"));
		}
		else {
			Auxiliar::debug("File: "+m_directori_usuari+"/"+idioma+"/"+lletra+".dic");

			QXmlInputSource source( &xmlFile );
			QXmlSimpleReader reader;
			reader.setFeature("http://trolltech.com/xml/features/report-whitespace-only-CharData",false);   //if we don't use it, we get more entries because spaces...
			reader.setContentHandler( &handler );

			handler.setParaula(buscar_orig);

			reader.parse(source);

			WordData d = handler.getWordData();

			ui.definicio->setPlainText("");

		        if (d.getNum()!=0) {
				ui.definicio->show();
				ui.llistat->hide();

				QString definicio;
				
				for (int i=0;i<d.getNum();i++) {
					if (i==0) {
						definicio=d.getEntry(i);
					}
					else {
						definicio+="<BR><BR>"+d.getEntry(i);
					}
				}
				ui.definicio->setHtml(definicio);
			}
			
			else if (d.getNum()==0) {
				//No word found or buscar == 1: we show the list
				
				ui.definicio->setPlainText("");
				ui.definicio->hide();
				ui.llistat->show();
				//loadList(&handler);
				
				m_searched=buscar_orig;
				selectItem();
				if (d.getNum()==0) {
					showError(tr("Exact match not found"));
				}
			}
			m_numberFound=d.getNum();
		}
        }
}
예제 #18
0
int main(int argc,char* argv[])
{
    QCoreApplication a(argc, argv);
    QsLogging::initQsLog();

    Param param = {
        std::string(getenv("LIMA_RESOURCES")==0?"/usr/share/apps/lima/resources":getenv("LIMA_RESOURCES")),
        std::string(getenv("LIMA_CONF")==0?"/usr/share/config/lima":getenv("LIMA_CONF")),
        std::string("lima-common.xml"),
        std::string("XXX-coreclient"),
        std::string("."),
        std::vector<std::string>()
    };

    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("--common-config-file=")) != std::string::npos )
                    param.commonConfigFile = arg.substr(pos+20);
                else if ( (pos = arg.find("--config-dir=")) != std::string::npos )
                    param.configDir = arg.substr(pos+13);
                else if ( (pos = arg.find("--resources-dir=")) != std::string::npos )
                    param.resourcesPath = arg.substr(pos+16);
                else if ( (pos = arg.find("--client=")) != std::string::npos )
                    param.clientId=arg.substr(pos+9);
                else if ( (pos = arg.find("--working-dir=")) != std::string::npos )
                    param.workingDir=arg.substr(pos+14);
                else usage(argc, argv);
            }
            else
            {
                param.files.push_back(std::string(arg));
            }
        }
    }

    setlocale(LC_ALL,"fr_FR.UTF-8");


    QXmlSimpleReader parser;

    // create TvgTestCaseProcessor
    // TvgTestCaseProcessor tvgTestCaseProcessor(param.workingDir, cerr);
    TvgTestCaseProcessor* tvgTestCaseProcessor(0);
    tvgTestCaseProcessor = new TvgTestCaseProcessor(param.workingDir, cerr);

    TestCasesHandler tch(*tvgTestCaseProcessor);

    parser.setContentHandler(&tch);
    parser.setErrorHandler(&tch);

    try
    {
        for( std::vector<std::string>::const_iterator fit = param.files.begin() ;
                fit != param.files.end() ; fit++ ) {
            string sfile(param.workingDir);
            sfile.append("/").append(*fit);
            cout << "parse " << sfile << endl;

            // cerr << "<?xml version='1.0' encoding='UTF-8'?>\n";
// cerr << "<testcases>\n";
            QFile file(sfile.c_str());
            if (!file.open(QIODevice::ReadOnly))
            {
                std::cerr << "Error opening " << sfile << std::endl;
                return 1;
            }
            if (!parser.parse( QXmlInputSource(&file)))
            {
                std::cerr << "Error parsing " << sfile << " : " << parser.errorHandler()->errorString().toUtf8().constData() << std::endl;
                return 1;
            }
            // cerr << "</testcases>\n";

            TestCasesHandler::TestReport resTotal;
            cout << endl;
            cout << "=========================================================" << endl;
            cout << endl;
            cout << "  TestReport :   " << sfile.c_str() << " " << endl;
            cout << endl;
            cout << "\ttype           \tsuccess\tcond.\tfailed\ttotal" << endl;
            cout << "---------------------------------------------------------" << endl;
            for (map<string,TestCasesHandler::TestReport>::const_iterator resItr=tch.m_reportByType.begin();
                    resItr!=tch.m_reportByType.end();
                    resItr++)
            {
                string label(resItr->first);
                label.resize(15,' ');
                cout << "\t" << label << "\t" << resItr->second.success
                     << "\t" << resItr->second.conditional << "\t"
                     << resItr->second.failed << "\t" << resItr->second.nbtests << endl;
                resTotal.success+=resItr->second.success;
                resTotal.conditional+=resItr->second.conditional;
                resTotal.failed+=resItr->second.failed;
                resTotal.nbtests+=resItr->second.nbtests;
            }
            cout << "---------------------------------------------------------" << endl;
            cout << "\ttotal          \t" << resTotal.success
                 << "\t" << resTotal.conditional << "\t" << resTotal.failed
                 << "\t" << resTotal.nbtests << endl;
            cout << "=========================================================" << endl;
            cout << endl;
            tch.m_reportByType.clear();
        }
    }
    catch (Lima::LimaException& e)
    {
        cerr << "caught LimaException : " << endl << e.what() << endl;
    }
    catch (logic_error& e)
    {
        cerr << "caught logic_error : " << endl << e.what() << endl;
    }

    if( tvgTestCaseProcessor != 0 )
        delete tvgTestCaseProcessor;
    // cerr << "main: after MLPlatformUtils::Terminate. before end..." << endl;
}
예제 #19
0
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);
    }
}
예제 #20
0
void SessionManager::handleRead()
{
    int count = tcpSocket->bytesAvailable();
    if(count <= 0)
        return;

    char dataIn[count+1];
    memset(dataIn, 0, count+1);

    //从socket中读取数据
    tcpSocket->read(dataIn, count);
    QString data = QString(dataIn);

    /*打印接收到的服务器数据*/
    std::cerr << "<!-- IN -->\n" << dataIn << "\n\n";

    //对数据进行预处理
    /*如果数据包交换已经结束,即已经收到</stream:stream>数据包*/
    if(data.contains(QString("</stream:stream>"), Qt::CaseInsensitive))
    {
        /*****************************************************
         *我们仍然需要处理</stream:stream>之前的部分数据
         *此处我们暂时不考虑,但是要注意时候必须补上,此处一定会出错!
         **************************************************/
        tcpSocket->close();
        return;
    }

    /*如果是第一个数据包,必须在后面加一个</stream:stream>, 否则解析的过程中会报错*/
    if(data.contains(QString("<?xml version='1.0'?>"), Qt::CaseInsensitive))
    {
        data += QString("</stream:stream>");
    }

    /**
     *为了能正确的解析数据,对数据进行预处理
     *所有的非初始数据都将被<stream:stream />对包裹
     */
    else
        data = QString("<stream:stream>")+data+QString("</stream:stream>");

    /*解析xml流,生成xml树*/
    xmlTree->clear();
    QXmlInputSource inputSource;
    inputSource.setData(data);
    QXmlSimpleReader reader;
    reader.setContentHandler(xmlHandler);
    reader.setErrorHandler(xmlHandler);
    reader.parse(inputSource);

    /*解析xmlTree,生成状态信息*/
    if(!parseTree())
    {
        QMessageBox::warning(0, tr("Error"),
                             tr("Error: %1\n").arg(getError()));
        return;
    }

    /*根据解析生成的状态信息,生成回复*/
    outData = generateResponse();

    if(status >= PRESENCEUPDATED)
        return;

    if(outData.isEmpty())
    {
        QMessageBox::warning(0, tr("Error"),
                             tr("Error: %1\n").arg(getError()));
    }else{
        emit send(outData);
    }
}
예제 #21
0
파일: FileIO.cpp 프로젝트: Kampbell/qfsm
/**
 * Opens a 'fsm'-file.
 * Opens the '.fsm' file @a mrufile. 
 * If @a mrufile is null a file dialog is opened first.
 */ 
Project* FileIO::openFileXML(QString mrufile /*=QString::null*/)
{
  Project* p=NULL;
//  filedlg->setMode(Q3FileDialog::ExistingFile);
  filedlg->setAcceptMode(QFileDialog::AcceptOpen);
  filedlg->setFileMode(QFileDialog::ExistingFile);

  if (mrufile.isNull())
  {
    if (!filedlg->exec())
    {
      act_file = QString::null;
      return p;
    }
    act_file = filedlg->selectedFile();
  }
  else
  {
    if (!QFile::exists(mrufile))
      return NULL;

    act_file = mrufile;
  }

  emit sbMessage(tr("File loading..."));
  QFile file(act_file);
//  if (!file.open(IO_ReadOnly))
//    return NULL;
  
  p = new Project(main);
  XMLHandler handler(p);
  QXmlInputSource source(file);
  QXmlSimpleReader reader;

  reader.setContentHandler(&handler);
  emit setWaitCursor();
  if (reader.parse(source))
  {
    file.close();
    emit setPreviousCursor();
    return p;
  }
  file.close();

  p->machine->updateDefaultTransitions();

  emit setPreviousCursor();
  return NULL;

/*  QTextStream s(&file);

  QDomDocument domdoc("domdoc");

  if ( !domdoc.setContent( &file ) ) 
  {
    file.close();
    return NULL;
  }
  qDebug(domdoc.toString());

  QDomDocumentType domdoctype=domdoc.docType();
  if (domdoctype.name!="fsmproject")
    return NULL;

  QDomElement domroot=domdoc.documentElement();
*/ 

  /*
  int version_major, version_minor;
  QString mname;
  int mtype, numbits, numin, numout, initial;
  int num_states;
  int scode;
  QString sname;
  double xpos, ypos;
  double c1x, c1y, c2x, c2y;
  double endx, endy;
  int radius, linewidth;
  unsigned int pencolor, brushcolor;
  QString sfamily, tfamily;
  int spointsize, tpointsize;
  int dest_code, anz, type;
  QString in, out;
  int straight;
  GState *state, *dest_state;
  Convert conv;
  TransitionInfo* info=NULL;
  Machine* m;
  int arrowtype;
  QString inames, onames, onamesm;
  int endstate;

  s >> version_major;
  s >> version_minor;
  s.readLine();
  mname = s.readLine();
  s >> mtype >> numbits >> numin >> numout;
  if (mtype==Ascii)
  {
    numbits=32;
    numin=8;
    numout=8;
  }
  s.readLine();
  onamesm = s.readLine();
  inames = s.readLine();
  onames = s.readLine();
  s >> num_states;
  s >> initial;
  s.readLine();
  sfamily = s.readLine(); 
  spointsize = s.readLine().toInt();
  tfamily = s.readLine(); 
  tpointsize = s.readLine().toInt();
  s >> arrowtype;
  QFont sfont(sfamily, spointsize);
  QFont tfont(tfamily, tpointsize);

  p = new Project(main);
  p->addMachine(mname, mtype, numbits, onamesm, numin, inames, numout, onames, sfont, tfont, arrowtype);
  m = p->machine;

  for (int i=0; i<num_states; i++)
  {
    s >> scode;
    s.readLine();
    sname=s.readLine();
    s >> xpos >> ypos >> radius;
    s >> pencolor >> linewidth;
    s >> brushcolor;
    s >> endstate;

    QColor pcol((QRgb)pencolor);
    QColor bcol((QRgb)brushcolor);
    QPen pen(pcol, linewidth );
    QBrush brush(bcol);

    m->addState(sname, scode, xpos, ypos, radius, 1.0, pen, bool(endstate));
  }
  
  state = m->getState(initial);
  if (state)
    m->setInitialState(state);
  else
    m->setInitialState(m->getSList().first());

  for(int i=0; i<num_states; i++)
  {
    s >> scode;
    state = m->getState(scode);
    s >> anz;
    for (int j=0; j<anz; j++)
    {
      s >> dest_code;
      if (dest_code==-1)
	dest_state=NULL;
      else
	dest_state = m->getState(dest_code);
      s >> type;
      s >> in >> out;
      s >> xpos >> ypos >> c1x >> c1y >> c2x >> c2y >> endx >> endy;
      s >> straight;

      if (type == Binary)
      {
        IOInfoBin bin, bout;

	bin = conv.binStrToX10(numin, in);
       
	if (out!="<noout>")
	{
	  bout = conv.binStrToX10(numout, out);
	}

	info = new TransitionInfoBin(bin,bout);
      }
      else
      {
	if (out=="<noout>")
	  out="";

        IOInfoASCII ain(in), aout(out);

	info = new TransitionInfoASCII(ain, aout);
      }
      
      if (state)
      {
	state->addTransition(p, dest_state, info, xpos, ypos, endx, endy,
	  c1x, c1y, c2x, c2y, (bool)straight);
      } 
    }
  }

  // phantom state
  state = m->getPhantomState();
  s >> anz;
  for (int j=0; j<anz; j++)
  {
    s >> dest_code;
    if (dest_code==-1)
      dest_state=NULL;
    else
      dest_state = m->getState(dest_code);
    s >> type;
    s >> in >> out;
    s >> xpos >> ypos >> c1x >> c1y >> c2x >> c2y >> endx >> endy;
    s >> straight;

    if (type == Binary)
    {
      IOInfoBin bin, bout;

      bin = conv.binStrToX10(numin, in);
      bout = conv.binStrToX10(numout, out);
      
      info = new TransitionInfoBin(bin/,bout);
    }
    else
    {
      IOInfoASCII ain(in), aout(out);

      info = new TransitionInfoASCII(ain, aout);
    }
    
    if (state)
    {
      state->addTransition(p, dest_state, info, xpos, ypos, endx, endy,
	c1x, c1y, c2x, c2y, (bool)straight);
    } 
  }       
  m->calcCanvasSize();   
*/
}
예제 #22
0
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;
}
예제 #23
0
int main( int argc, char **argv )
{
	QPCApplication app(argc, argv);

	QApplication::setStyle("plastik");
	
	qapital::QPLOGGER.salvarLog(SBLogger::QP_INFO, SBLogger::CLIENTE, QObject::tr("Iniciando QPCliente"));
	
	QString splash = qapital::GUIDATADIR + QString("qapital-splash-2004-08-31.png");
	
	QPixmap pixmap( splash );
    	QSplashScreen *pantalla = new QSplashScreen( pixmap );
      	pantalla->show();
	pantalla->message(QObject::tr("Iniciando aplicacion..."));

	QFile configFile( qapital::CONFIGRC +  QString("QPCConfig.xml"));

	QXmlInputSource sourceXML(configFile);
	configFile.close();
	
	QPCConfigHandler *handler = new QPCConfigHandler;
	QXmlSimpleReader reader;
    	reader.setContentHandler( handler );
		
	if ( ! reader.parse( sourceXML ) )
	{
		std::cout << QObject::tr("Error en la configuracion del cliente") << std::endl;
	}		
	
	ClnRed cliente ( handler->obtenerQPSHost(), handler->obtenerQPSPuerto() );

	pantalla->message(QObject::tr("creando interfaz..."));

	//GCLMdiMainWindow *qpCliente;
	QMainWindow *qpCliente = 0;

	switch ( int opt = handler->obtenerTipoDeInterfaz() )
	{
		case SBGui::MenuBased:
		{
			std::cout << "Iniciando MenuBased" << std::endl;
			qpCliente = new GCLPrincipal(&cliente);
		}
		break;
		case SBGui::MDIBased:
		{
			std::cout << "Iniciando MDIBased" << std::endl;
			qpCliente = new GCLMdiMainWindow();
		}
		break;
		default:
		{
			std::cout << "Tipo de interfaz desconocido " << opt << std::endl;
			qpCliente = new GCLMdiMainWindow();
		}
		break;
	}
	
	app.setMainWidget( qpCliente );
	
	
	QObject::connect( qApp, SIGNAL( lastWindowClosed() ), &cliente, SLOT( clnCerrarConexion() ) );
	
	pantalla->finish( qpCliente );

    	delete pantalla;
	
	return app.exec();
}
예제 #24
0
파일: tva.cpp 프로젝트: pquentin/lima
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;
}
예제 #25
0
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;
	}
}
예제 #26
0
void
ProcessFile(QString file)
{
    QString    docType;
    Plugin    *plugin    = NULL;
    Attribute *attribute = NULL;

    EnumType::enums.clear();

    currentInputDir = "";
    int lastslash = file.lastIndexOf("/");
    if (lastslash < 0)
        lastslash = file.lastIndexOf("\\");
    if (lastslash >= 0)
        currentInputDir = file.left(lastslash+1);

    FieldFactory  *fieldFactory = new FieldFactory;
    XMLParser     parser(fieldFactory, file);
    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);
        reader.parse(source);

        docType   = parser.docType;
        plugin    = parser.plugin;

        if (docType == "Attribute")
            attribute = parser.attribute;
        else if(plugin != NULL)
            attribute = plugin->atts;
    }
    catch (const char *s)
    {
        cErr << "ERROR: " << s << Endl;
        Die();
    }
    catch (const QString &s)
    {
        cErr << "ERROR: " << s.toStdString().c_str() << Endl;
        Die();
    }

    if (docType.isNull())
    {
        cErr << "Error in parsing " << file.toStdString().c_str() << Endl;
        Die();
    }

    if (print)
    {
        cOut << "--------------------------------------------------------------"
             << "---" << Endl;
        cOut << "               Parsed document of type " << docType << Endl;
        cOut << "--------------------------------------------------------------"
             << "---" << Endl;
        cOut << Endl;
    }

    // test mode
    try
    {
        if (print)
        {
            for (size_t i=0; i<EnumType::enums.size(); i++)
            {
                EnumType::enums[i]->Print(cOut);
                cOut << Endl;
            }
            if (docType == "Plugin")
            {
                if(plugin != NULL)
                    plugin->Print(cOut);
            }
            else if (docType == "Attribute")
            {
                if(attribute != NULL)
                    attribute->Print(cOut);
            }
            else
            {
                cErr << "Document type "
                     << docType
                     << "not supported" << Endl;
                Die();
            }
            cOut << Endl;
        }

        CallGenerator(docType, attribute, plugin, file);

        cOut.flush();
        cErr.flush();

        delete attribute;
        delete plugin;
    }
    catch (const char *s)
    {
        cErr << "ERROR: " << s << Endl;
        Die();
    }
    catch (const QString &s)
    {
        cErr << "ERROR: " << s << Endl;
        Die();
    }
}