void printError()
 {
     QByteArray errorOut = streamProcess.readAllStandardError();
     qDebug() << "Called the C++ slot and got following error:" << errorOut.simplified();
     errorMsg = errorOut.simplified();
     error(errorMsg);
 }
Example #2
0
// ------------------------------------------------------------------
bool 
JcnModel::rmvEntry(const QByteArray & s, int itemRow)
{
	if (jcndbg)
		std::cout << "JcnModel::rmvEntry: " << s.simplified().toUpper() << std::endl;

	_entryMap.erase(s.simplified().toUpper());
	takeRow(itemRow);
	return true;
}
Example #3
0
bool Mama::buildCommands()
{
    QFile cmdFile("cmd.txt");
    //Use :/ prefix if cmd.txt is embedded into resource
    //QFile cmdFile(":/cmd.txt");

    if (!cmdFile.open(QIODevice::ReadOnly|QIODevice::Text)) {
        cerr << "File" << "cmd.txt" << "does not exit" << endl;
        return false;
    }

    while (!cmdFile.atEnd()) {
        QByteArray line = cmdFile.readLine();
        if (line.simplified() == QByteArray("browser")) {
            line = cmdFile.readLine();
            QList<QByteArray> qList = line.split(',');
            browserCmd = qList[0];
            browserArg = QStringList(qList[1]);
        }
        if (line.simplified() == QByteArray("news")) {
            line = cmdFile.readLine();
            QList<QByteArray> qList = line.split(',');
            newsCmd = qList[0];
            newsArg = QStringList(qList[1]);
        }
        if (line.simplified() == QByteArray("email")) {
            line = cmdFile.readLine();
            QList<QByteArray> qList = line.split(',');
            emailCmd = qList[0];
            emailArg = QStringList(qList[1]);
        }
        if (line.simplified() == QByteArray("movie")) {
            line = cmdFile.readLine();
            QList<QByteArray> qList = line.split(',');
            movieCmd = qList[0];
            movieArg = QStringList(qList[1]);
        }
    }
    QString fileName = QDir::currentPath();
    QIcon icon4;
    fileName += "\\img\\chopper.jpg";
    icon4.addPixmap(QPixmap(fileName), QIcon::Normal, QIcon::Off);

    ui->toolButton->setIcon(icon4);
    ui->toolButton->setIconSize(QSize(90, 90));

    return true;
}
Example #4
0
void RoomPropertySetter::parseProperty(const QByteArray &command, const Coordinate &roomPos)
{
    QList<QByteArray> words = command.simplified().split(' ');
    AbstractAction *action = 0;
    QByteArray property = words[1];
    uint pos = propPositions[property];
    if (words.size() == 4) {
        //change exit property
        ExitDirection dir = Mmapper2Exit::dirForChar(words[2][0]);
        switch (pos) {
        case E_FLAGS:
        case E_DOORFLAGS:
            action = new ModifyExitFlags(fieldValues[property], dir, pos, FMM_TOGGLE);
            break;
        case E_DOORNAME:
            action = new UpdateExitField(property, dir, pos);
            break;
        default:
            emit sendToUser("unknown property: " + property + "\r\n");
            return;
        }
    } else if (words.size() == 3) {
        //change room property
        switch (pos) {
        case R_TERRAINTYPE:
            action = new UpdatePartial(fieldValues[property], pos);
            break;
        case R_NAME:
        case R_DESC:
            action = new UpdatePartial(property, pos);
            break;
        case R_MOBFLAGS:
        case R_LOADFLAGS:
            action = new ModifyRoomFlags(fieldValues[property], pos, FMM_TOGGLE);
            break;
        case R_DYNAMICDESC:
        case R_NOTE:
            action = new UpdateRoomField(property, pos);
            break;
        case R_PORTABLETYPE:
        case R_LIGHTTYPE:
        case R_ALIGNTYPE:
        case R_RIDABLETYPE:
            action = new UpdateRoomField(fieldValues[property], pos);
            break;
        default:
            emit sendToUser("unknown property: " + property + "\r\n");
            return;
        }

        RoomPropertySetterSlave slave(action);
        emit lookingForRooms(&slave, roomPos);

        if (slave.getResult()) {
            emit sendToUser("OK\r\n");
        } else {
            emit sendToUser("setting " + property + " failed!\r\n");
        }
    }
}
Example #5
0
void Tercon::convertData(QByteArray strData){
    TerconData data;
    bool convertIsOK=false;

    strData = strData.simplified();
    QString tempStr = strData;
    int indexSeparator = tempStr.indexOf(QRegExp("[tRU]"));
    QString unitAndNumberData = tempStr.left(indexSeparator+1);
    tempStr.remove(0,indexSeparator+1);
    if(indexSeparator==-1){
        emit message(tr("Ошибка чтения данных Теркона\n"
                        "(разделитель не обнаружен): ")+strData+".",Shared::warning);
        return;
    }

    data.value = tempStr.toDouble(&convertIsOK);
    if (!convertIsOK){
        emit message(tr("Ошибка чтения данных Теркона\n"
                        "(невозможно преобразовать строку в число): ")+strData+".",Shared::warning);
        return;
    }

    data.unit  = unitAndNumberData.at(unitAndNumberData.size()-1);
    unitAndNumberData.chop(1);

    data.channel = unitAndNumberData.toShort(&convertIsOK);
    if (!convertIsOK){
        emit message(tr("Ошибка чтения данных Теркона\n"
                        "(неверный номер канала): ")+strData+".",Shared::warning);
        return;
    }
    data.deviceNumber = deviceNumber;

    emit dataSend(data);
}
Example #6
0
void TelemetrySimulator::LogPlaybackController::loadLogFile()
{
  // reset the playback ui
  ui->play->setEnabled(false);
  ui->rewind->setEnabled(false);
  ui->stepBack->setEnabled(false);
  ui->stepForward->setEnabled(false);
  ui->stop->setEnabled(false);
  ui->positionIndicator->setEnabled(false);
  ui->replayRate->setEnabled(false);
  ui->positionLabel->setText("Row #\nTimestamp");

  // clear existing data
  csvRecords.clear();

  QString logFileNameAndPath = QFileDialog::getOpenFileName(NULL, tr("Log File"), ".", tr("LOG Files (*.csv)"));
  QFileInfo fileInfo(logFileNameAndPath);
  QFile file(logFileNameAndPath);
  if (!file.open(QIODevice::ReadOnly)) {
    ui->logFileLabel->setText(tr("ERROR - invalid file"));
    return;
  }
  while (!file.atEnd()) {
    QByteArray line = file.readLine();
    csvRecords.append(line.simplified());
  }
  if (csvRecords.count() > 1) {
    columnNames.clear();
    QStringList keys = csvRecords[0].split(',');
    // override the first two column names
    keys[0] = "LogDate";
    keys[1] = "LogTime";
    Q_FOREACH(QString key, keys) {
      columnNames.append(key.simplified());
    }
Example #7
0
void NoSpacesProcessor::processText()
{
    QFile file(m_filename);
    if(!file.open(QIODevice::ReadOnly)) {
        emit error(tr("Could not open file %1").arg(m_filename));
        return;
    }

    const int totalLineCount = detectLineCount();
    int lineNumber(1);

    while(!file.atEnd()) {
        emit progress(lineNumber,totalLineCount,tr("Parsing text with no spaces"));
        QByteArray line = file.readLine();

        emit lineFound(line, lineNumber);

        line = line.simplified();
        if(line.isEmpty()) {
            ++lineNumber;
            continue;
        }

        for(int pos=0;pos<line.count();++pos) {
            emit progress(pos,line.count(),tr("Line %1 of %2").arg(lineNumber).arg(totalLineCount));
            for(int len=1;len<14;++len) {
                emit combinationFound(processorName(),line.mid(pos,len),lineNumber);
            }
        }
        //emit combinationFound(processorName(), word,lineNumber);
        ++lineNumber;
    }
    file.close();

}
Example #8
0
/*!
    \internal
    Reads the configuration out from a io device.
*/
void dtkLoggingPrivate::readSettings(QIODevice &device)
{
    QMutexLocker locker(&_mutexRegisteredCategory);
    {
        _logConfigItemList.clear();

        if (device.open(QIODevice::ReadOnly)) {
            QByteArray truearray("true");
            QByteArray line;
            while (!device.atEnd()) {
                line = device.readLine().replace(" ", "");
                line = line.simplified();
                const QList<QByteArray> pair = line.split('=');
                if (pair.count() == 2)
                    _logConfigItemList.append(dtkLogConfigFilterItem(QString::fromLatin1(pair.at(0))
                                                     , (pair.at(1).toLower() == truearray)));
            }
        }

        foreach (dtkLoggingCategory *category, _registeredCategories) {
            updateCategory(category);
        }

        _registerCategories = true;
    }
Example #9
0
QByteArray Variant::toUtf8() const
{
  QDomDocument doc;
  xmlWrite(doc, doc);
  QByteArray result = doc.toByteArray(0);
  return result.simplified();
}
Example #10
0
//--------------------------------------------------------------------------------------------------
/// 
//--------------------------------------------------------------------------------------------------
bool RiaImageFileCompare::runComparison(QString imgFileName, QString refFileName, QString diffFileName)
{
    reset();

    if (m_compareExecutable.isEmpty())
    {
        m_lastError = SEVERE_ERROR;
        m_errorMsg = "Cannot compare images, no compare executable set";
        return false;
    }


    //QString args = QString("-fuzz 2% -lowlight-color white -metric ae \"%1\" \"%2\" \"%3\"").arg(imgFileName).arg(refFileName).arg((diffFileName));
    // The ImageMagick compare tool on RedHat 5 does not support the lowlight-color options
    // Use GCC version as a crude mechanism for disabling use of this option on RedHat5
#if (__GNUC__ == 4 && __GNUC_MINOR__ <= 1)
    QString args = QString("-fuzz 0.4% -metric ae \"%1\" \"%2\" \"%3\"").arg(imgFileName).arg(refFileName).arg((diffFileName));
#else
    QString args = QString("-fuzz 0.4% -lowlight-color white -metric ae \"%1\" \"%2\" \"%3\"").arg(imgFileName).arg(refFileName).arg((diffFileName));
#endif
    QString completeCommand = QString("\"%1\" %2").arg(m_compareExecutable).arg(args);

    // Launch process and wait
    QProcess proc;
    proc.start(completeCommand);
    proc.waitForFinished(30000);

    QProcess::ProcessError procError = proc.error();
    if (procError != QProcess::UnknownError)
    {
        m_lastError = SEVERE_ERROR;
        m_errorMsg = "Error running compare tool process";
        m_errorDetails = completeCommand;
        return false;
    }

    QByteArray stdErr = proc.readAllStandardError();
    int procExitCode = proc.exitCode();
    if (procExitCode == 0)
    {
        // Strip out whitespace and look for 0 (as in zero pixel differences)
        stdErr = stdErr.simplified();
        if (!stdErr.isEmpty() && stdErr[0] == '0')
        {
            m_imagesEqual = true;
        }

        return true;
    }
    else
    {
        // Report non-severe error
        m_lastError = IC_ERROR;
        m_errorMsg = "Error running compare tool process";
        m_errorDetails = stdErr;

        return false;
    }
}
Example #11
0
void
M3uLoader::parseM3u( const QString& fileLink )
{
    QFileInfo fileInfo( fileLink );
    QFile file( QUrl::fromUserInput( fileLink ).toLocalFile() );

    if ( !file.open( QIODevice::ReadOnly | QIODevice::Text ) )
    {
        tDebug() << "Error opening m3u:" << file.errorString();
        return;
    }

    m_title = fileInfo.baseName();
    while ( !file.atEnd() )
    {
         QByteArray line = file.readLine();
         /// If anyone wants to take on the regex for parsing EXT, go ahead
         /// But the notion that users does not tag by a common rule. that seems hard
         /// So ignore that for now
         if ( line.contains( "EXT" ) )
             continue;

         QFileInfo tmpFile( QUrl::fromUserInput( QString( line.simplified() ) ).toLocalFile() );

         if( tmpFile.exists() )
             getTags( tmpFile );
         else
         {
             QUrl fileUrl = QUrl::fromUserInput( QString( QFileInfo(file).canonicalPath() + "/" + line.simplified() ) );
             QFileInfo tmpFile( fileUrl.toLocalFile() );
             if ( tmpFile.exists() )
                getTags( tmpFile );
         }
    }

    if ( m_tracks.isEmpty() )
    {
        tDebug() << Q_FUNC_INFO << "Could not parse M3U!";
        return;
    }

    if ( m_createNewPlaylist )
    {
        m_playlist = Playlist::create( SourceList::instance()->getLocal(),
                                       uuid(),
                                       m_title,
                                       m_info,
                                       m_creator,
                                       false,
                                       m_tracks );

        connect( m_playlist.data(), SIGNAL( revisionLoaded( Tomahawk::PlaylistRevision ) ), this, SLOT( playlistCreated() ) );
    }
    else
        emit tracks( m_tracks );

    m_tracks.clear();
}
Example #12
0
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
bool RiaTextFileCompare::runComparison(const QString& baseFolder, const QString& generatedFolder)
{
    reset();

    QString fullFilePath = "diff";
    if (!m_pathToDiffTool.isEmpty())
    {
        fullFilePath = m_pathToDiffTool + "/" + fullFilePath;
    }

    // Command line arguments used when invoking 'diff'
    // See https://docs.freebsd.org/info/diff/diff.info.diff_Options.html
    QString args = "-r -u --strip-trailing-cr";

    QString completeCommand = QString("\"%1\" %2 %3 %4").arg(fullFilePath).arg(baseFolder).arg(generatedFolder).arg(args);

    // Launch process and wait
    QProcess proc;
    proc.start(completeCommand);
    proc.waitForFinished(30000);

    QProcess::ProcessError procError = proc.error();
    if (procError != QProcess::UnknownError)
    {
        m_lastError    = SEVERE_ERROR;
        m_errorMsg     = "Error running 'diff' tool process";
        m_errorDetails = completeCommand;
        return false;
    }

    QByteArray stdErr       = proc.readAllStandardError();
    int        procExitCode = proc.exitCode();

    if (procExitCode == 0)
    {
        return true;
    }
    else if (procExitCode == 1)
    {
        QByteArray stdOut = proc.readAllStandardOutput();
        m_diffOutput      = stdOut;

        return false;
    }
    else
    {
        stdErr = stdErr.simplified();

        // Report non-severe error
        m_lastError    = IC_ERROR;
        m_errorMsg     = "Error running 'diff' tool process";
        m_errorDetails = stdErr;

        return false;
    }
}
Example #13
0
/*Checksum of the received packet*/
ANWR_PROTOCOL::RETURN_ANSWER ftdiChip::CheckingReceivedPacket(const QByteArray &bS)
{
if(bS.isEmpty())return ANWR_PROTOCOL::retNoAnsError;
QByteArray cmd = bS.simplified();
if(cmd.contains("#")){
    if(cmd[1]=='>')return ANWR_PROTOCOL::retOK;
    if(cmd[1]=='?')return ANWR_PROTOCOL::retIncorData;
    }
return ANWR_PROTOCOL::retError;
}
Example #14
0
// ------------------------------------------------------------------
bool 
JcnModel::hasEntry(const QByteArray & s)
{
	if (jcndbg)
		std::cout << "JcnModel::hasEntry" << std::endl;

	EntryMap_itr_t itr = _entryMap.find(s.simplified().toUpper());
	if ( itr == _entryMap.end())
		return false;
	else
		return true;
}
Example #15
0
int populateAfterRegInfo(QTextStream& t) 
{
	t << endl << endl;
	t << "RESOURCE SERVICE_CONFIGURATION_ARRAY r_service_configuration_reg" << endl;
	t << "\t{" << endl;
	t << "\t\tservice_configuration_array=" << endl;
	t << "\t\t\t{" << endl;

    QFile cf(configurationFile);	

	int err = 0;
	
	QByteArray escapedQuotationMark = QByteArray("\\\"");
	
	if (cf.open(QIODevice::ReadOnly | QIODevice::Text)) {
		QByteArray xmlConf;

		xmlConf = cf.readAll();
		xmlConf = xmlConf.replace("\"","\\\"");
		if (xmlConf.count()) {
			QByteArray xml = xmlConf.simplified();
			for (int n=0;;n++) {
				int splitCount = 255;
				if (xml.size() > 255 && (xml.mid(254, 2) == escapedQuotationMark)) {
					splitCount = 254;
				}
				QByteArray split = xml.left(splitCount);
				if (!split.count()) {
					break;
				}
				if (n) {
					t << "\t\t\t\t,"  << endl;
				}
				t << "\t\t\t\tSERVICE_CONFIGURATION"  << endl;
				t << "\t\t\t\t{" <<  endl;
				t << "\t\t\t\txmldata = \"" << split <<"\";" <<  endl;
				t << "\t\t\t\t}" <<  endl;

				xml = xml.mid(splitCount);
			}
		}	
	} else {
		fprintf(stderr, "Error: Cannot open %s file for reading.", qPrintable(configurationFile));
		err = 1;
	}
	
	t << endl;
	t << "\t\t\t};" << endl;
	t << "\t}" << endl;
	
	return err;
}
void AndroidRunnerWorkerBase::forceStop()
{
    runAdb({"shell", "am", "force-stop", m_androidRunnable.packageName}, 30);

    // try killing it via kill -9
    const QByteArray out = Utils::SynchronousProcess()
            .runBlocking(m_adb, selector() << QStringLiteral("shell") << pidScriptPreNougat)
            .allRawOutput();

    qint64 pid = extractPID(out.simplified(), m_androidRunnable.packageName);
    if (pid != -1) {
        adbKill(pid);
    }
}
Example #17
0
MainWindow::MainWindow(QWidget *parent) :
	QMainWindow(parent),
	ui(new Ui::MainWindow)
{
	ui->setupUi(this);

	QByteArray test;

	test.append(49);
	test.append(46);
	test.append(49);
	test.append(56);
	test.append(48);
	test.append(48);
	test.append('\n');
	test.append((char)0);
	test.append(char(0));
	test.append(char(0));
	test.append(char(0));
	test.append(char(0));


	qDebug("org [%s], size %d", test.constData(), test.size());

	QByteArray test3 = test.simplified();

	qDebug("simplified [%s] size %d", test3.constData(), test3.size());


	QByteArray test4 = test.trimmed();

	qDebug("trimmed [%s] size %d", test4.constData(), test4.size());

	float val = test3.toFloat();

	qDebug("value = %f", val);

	if ( test.contains('\n'))

	{
		QByteArray test2 = test.left( test.indexOf('\n'));



		qDebug("%d test2 [%s]", test.indexOf(char(0)), test2.constData());
	}

}
Example #18
0
 QString StreamMail::HeaderMail() {
     QByteArray out; ////  ////onlyMETAHEADER = QByteArray();
     int cursor = 0;
     start();
     while (d->canReadLine()) {
         QByteArray chunk = d->readLine();
         ///// const QString t_line = QString(chunk.constData()); //// decodeWordSequence(chunk);
         const QByteArray cline = chunk.simplified();
         cursor++;
         if (!cline.isEmpty()) {
             out.append(cline);
             out.append("\n\r");
             continue;
         }
         if (cline.isEmpty()) {
             start();
             break;
         }
     }
     start();
     QString useline;
     bool readc = false;
     QString clean_header = decodeWordSequence(out); //// utf subject clean
     //// here handle Subject on 2 or more line!!!
     QStringList h_lines = clean_header.split(QRegExp("(\\r\\n)|(\\n\\r)|\\r|\\n"), QString::SkipEmptyParts);
     for (int i = 0; i < h_lines.size(); ++i) {
         const QString line = QString(h_lines.at(i).simplified());
         if (!line.isEmpty()) {
             QChar fchar(line.at(0));
             int ucharkc = fchar.unicode();
             if ( line.indexOf(QChar(':'), 0) !=-1 ) {
                 readc = false;
             }
             if (Filter::headerfilter(line) && !readc) {
                 readc = true;
                 useline.append("\n");
             }
             if (readc) {
                 useline.append(line);
                 useline.append(" ");
                 continue;
             }
         }
     }
     return useline;
 }
Example #19
0
QByteArray Crypt::decrypt(const QByteArray &data) const
{
	/// odstran vsechny bile znaky, v zakodovanem textu nemohou byt, muzou to byt ale zalomeni radku
	QByteArray ba = data.simplified();
	ba.replace(' ', "");
	ba = decodeArray(ba);
	///odstran \0 na konci, byly tam asi umele pridany
	int pos = ba.size();
	while(pos > 0) {
		pos--;
		if(ba[pos] == '\0') {
		}
		else {
			pos++;
			break;
		}
	}
	ba = ba.mid(0, pos);
	return ba;
}
Example #20
0
void YouTube::parseLiveVideoPage(QNetworkReply *reply) {
    QNetworkAccessManager *manager = qobject_cast<QNetworkAccessManager*>(sender());

    QByteArray response = reply->readAll();
    response = QByteArray::fromPercentEncoding(response.simplified().replace(QByteArray(" "), QByteArray("")));
//    qDebug() << response;
    int pos = response.indexOf("fmt_stream_map=") + 18;
    int pos2 = response.indexOf('|', pos);
    response = response.mid(pos, pos2 - pos);
    QByteArray videoUrl = response.replace(QByteArray("\\/"), QByteArray("/")).replace(QByteArray("\\u0026"), QByteArray("&")).replace(QByteArray("%2C"), QByteArray(","));
    if (!(videoUrl.startsWith("http"))) {
        emit alert(tr("Error: Unable to retrieve video"));
        emit videoUrlError();
    }
    else {
        emit gotVideoUrl(QString(videoUrl));
    }
//        qDebug() << videoUrl;
    reply->deleteLater();
    manager->deleteLater();
}
QByteArray qMyMessageFormatString(QtMsgType type, const QMessageLogContext &context,
                                              const QString &str)
{
    QByteArray message;
    if (!usedefaultformat) {
        message.append(context.category);
        switch (type) {
        case QtDebugMsg:   message.append(".debug"); break;
        case QtInfoMsg:    message.append(".info"); break;
        case QtWarningMsg: message.append(".warning"); break;
        case QtCriticalMsg:message.append(".critical"); break;
        case QtFatalMsg:   message.append(".fatal"); break;
        }
        message.append(": ");
        message.append(qPrintable(str));
    } else {
        message.append(qPrintable(str));
    }

    return message.simplified();
}
Example #22
0
void EventAttribute::deserialize(const QByteArray& data)
{
    kDebug() << data;

    // Set default values
    d->mCommandError = KAEvent::CMD_NO_ERROR;

    bool ok;
    int c[1];
    const QList<QByteArray> items = data.simplified().split(' ');
    switch (items.count())
    {
        case 1:
            c[0] = items[0].toInt(&ok);
            if (!ok  ||  (c[0] & ~(KAEvent::CMD_ERROR | KAEvent::CMD_ERROR_PRE | KAEvent::CMD_ERROR_POST)))
                return;
            d->mCommandError = static_cast<KAEvent::CmdErrType>(c[0]);
            break;

        default:
            break;
    }
}
Example #23
0
// ------------------------------------------------------------------
bool 
JcnModel::findEntry(const QByteArray & s, JcnCalc & c)
{
	if (jcndbg)
		std::cout << "JcnModel::findEntry" << std::endl;

/*
   	EntryMap_itr_t itra;
    for (itra = _entryMap.begin();  itra != _entryMap.end(); ++itra)
    {
		JcnCalc & trg = itra->second;
		std::cout << "(" << trg.text() << ")" << std::endl;
	}
*/

	EntryMap_itr_t itr = _entryMap.find(s.simplified().toUpper());
	if ( itr == _entryMap.end())
		return false;
	else
	{
		c = itr->second;
		return true;
	}
}
Example #24
0
QString
ITunesDevice::LibraryPath()
{
    if ( !m_iTunesLibraryPath.isEmpty() )
        return m_iTunesLibraryPath;

    QString path;
    QString confPath;

#ifdef Q_WS_MAC
    QSettings ist( "apple.com", "iTunes" );
    path = ist.value( "AppleNavServices:ChooseObject:0:Path" ).toString();
    path = path.remove( "file://localhost" );
    qDebug() << "Found iTunes Library in:" << path;

    QFileInfo fi( path + "iTunes Music Library.xml" );
    if ( fi.exists() )
        m_iTunesLibraryPath = fi.absoluteFilePath();
    else
        m_iTunesLibraryPath = QFileInfo( QDir::homePath() + "/Music/iTunes/iTunes Music Library.xml" ).absoluteFilePath();

    return m_iTunesLibraryPath;
#endif

#ifdef WIN32
    {
        // Get path to My Music
        char acPath[MAX_PATH];
        HRESULT h = SHGetFolderPathA( NULL, CSIDL_MYMUSIC,
                                      NULL, 0, acPath );

        if ( h == S_OK )
            path = QString::fromLocal8Bit( acPath );
        else
            LOG( 1, "Couldn't get My Music path\n" );

        qDebug() << "CSIDL_MYMUSIC path: " << path;
    }

    {
        // Get path to Local App Data
        char acPath[MAX_PATH];
        HRESULT h = SHGetFolderPathA( NULL, CSIDL_LOCAL_APPDATA,
                                      NULL, 0, acPath );

        if ( h == S_OK )
            confPath = QString::fromLocal8Bit( acPath );
        else
            LOG( 1, "Couldn't get Local Application Data path\n" );

        qDebug() << "CSIDL_LOCAL_APPDATA path: " << confPath;
    }

    // Try reading iTunesPrefs.xml for custom library path
    QFile f( confPath + "/Apple Computer/iTunes/iTunesPrefs.xml" );
    if ( f.open( QIODevice::ReadOnly | QIODevice::Text ) )
    {
        qDebug() << "Found iTunesPrefs.xml";

        QByteArray content = f.readAll();

        int tagStart = content.indexOf( "iTunes Library XML Location:1" );

        if ( tagStart != -1 )
        {
            // TODO: this could fail if the XML is broken
            int dataTagStart = content.indexOf( "<data>", tagStart );
            int dataTagEnd = dataTagStart + 6;
            int dataEndTagStart = content.indexOf( "</data>", dataTagStart );
            QByteArray lp = content.mid( dataTagEnd, dataEndTagStart - dataTagEnd );

            qDebug() << "lp before trim: " << lp;

            // The file contains whitespace and linebreaks in the middle of
            // the data so need to squeeze all that out
            lp = lp.simplified();
            lp = lp.replace( ' ', "" );

            qDebug() << "lp after simplified: " << lp;

            lp = QByteArray::fromBase64( lp );

            qDebug() << "lp after base64: " << lp;

            QString sp = QString::fromUtf16( (ushort*)lp.data() );

            qDebug() << "Found iTunes Library path (after conversion to QString):" << sp;

            QFileInfo fi( sp );
            if ( fi.exists() )
            {
                qDebug() << "file exists, returning: " << fi.absoluteFilePath();
                m_iTunesLibraryPath = fi.absoluteFilePath();
                return m_iTunesLibraryPath;
            }
        }
        else
        {
            qDebug() << "No custom library location found in iTunesPrefs.xml";
        }
    }

    // Fall back to default path otherwise
    m_iTunesLibraryPath = path + "/iTunes/iTunes Music Library.xml";

    qDebug() << "Will use default iTunes Library path: " << m_iTunesLibraryPath;

    return m_iTunesLibraryPath;

#endif

    // Fallback for testing
//    m_iTunesLibraryPath = "/tmp/iTunes Music Library.xml";
//    return m_iTunesLibraryPath;
}
void QmitkDiffusionImagingAppIntroPart::DelegateMeTo(const QUrl& showMeNext)
{
  QString scheme          = showMeNext.scheme();
#if QT_VERSION < QT_VERSION_CHECK(5, 0, 0)
  QByteArray urlHostname  = showMeNext.encodedHost();
  QByteArray urlPath      = showMeNext.encodedPath();
  QByteArray dataset      = showMeNext.encodedQueryItemValue("dataset");
  QByteArray clear        = showMeNext.encodedQueryItemValue("clear");
#else
  QByteArray urlHostname  = QUrl::toAce(showMeNext.host());
  QByteArray urlPath      = showMeNext.path().toLatin1();
  QUrlQuery query(showMeNext);
  QByteArray dataset      = query.queryItemValue("dataset").toLatin1();
  QByteArray clear        = query.queryItemValue("clear").toLatin1();//showMeNext.encodedQueryItemValue("clear");
#endif

  if (scheme.isEmpty()) MITK_INFO << " empty scheme of the to be delegated link" ;

  // if the scheme is set to mitk, it is to be tested which action should be applied
  if (scheme.contains(QString("mitk")) )
  {
    if(urlPath.isEmpty() ) MITK_INFO << " mitk path is empty " ;

    // searching for the perspective keyword within the host name
    if(urlHostname.contains(QByteArray("perspectives")) )
    {
      // the simplified method removes every whitespace
      // ( whitespace means any character for which the standard C++ isspace() method returns true)
      urlPath = urlPath.simplified();
      QString perspectiveId(urlPath.data());
      perspectiveId.replace(QString("/"), QString("") );

      // is working fine as long as the perspective id is valid, if not the application crashes
      GetIntroSite()->GetWorkbenchWindow()->GetWorkbench()->ShowPerspective(perspectiveId, GetIntroSite()->GetWorkbenchWindow() );

      // search the Workbench for opened StdMultiWidgets to ensure the focus does not stay on the welcome screen and is switched to
      // an StdMultiWidget if one available
      ctkPluginContext* context = QmitkDiffusionApplicationPlugin::GetDefault()->GetPluginContext();
      ctkServiceReference ref = context->getServiceReference<mitk::IDataStorageService>();
      if (ref)
      {
        mitk::IDataStorageService* service = context->getService<mitk::IDataStorageService>(ref);
        berry::IEditorInput::Pointer editorInput(
              new mitk::DataStorageEditorInput( service->GetActiveDataStorage() ));

        // the solution is not clean, but the dependency to the StdMultiWidget was removed in order to fix a crash problem
        // as described in Bug #11715
        // This is the correct way : use the static string ID variable
        // berry::IEditorPart::Pointer editor = GetIntroSite()->GetPage()->FindEditors( editorInput, QmitkStdMultiWidgetEditor::EDITOR_ID );
        // QuickFix: we use the same string for an local variable
        const QString stdEditorID = "org.mitk.editors.stdmultiwidget";

        // search for opened StdMultiWidgetEditors
        QList<berry::IEditorReference::Pointer> editorList = GetIntroSite()->GetPage()->FindEditors( editorInput, stdEditorID, 1 );

        // if an StdMultiWidgetEditor open was found, give focus to it
        if(!editorList.isEmpty())
        {
          GetIntroSite()->GetPage()->Activate( editorList[0]->GetPart(true) );
        }
      }
    }
  }
  // if the scheme is set to http, by default no action is performed, if an external webpage needs to be
  // shown it should be implemented below
  else if (scheme.contains(QString("http")) )
  {
    QDesktopServices::openUrl(showMeNext);
//    m_view->load( ) ;
  }
  else if(scheme.contains("qrc"))
  {
    m_view->load(showMeNext);
  }

}
void wrapInFunction()
{

//! [0]
QByteArray ba("Hello");
//! [0]


//! [1]
QByteArray ba;
ba.resize(5);
ba[0] = 0x3c;
ba[1] = 0xb8;
ba[2] = 0x64;
ba[3] = 0x18;
ba[4] = 0xca;
//! [1]


//! [2]
for (int i = 0; i < ba.size(); ++i) {
    if (ba.at(i) >= 'a' && ba.at(i) <= 'f')
        cout << "Found character in range [a-f]" << endl;
}
//! [2]


//! [3]
QByteArray x("and");
x.prepend("rock ");         // x == "rock and"
x.append(" roll");          // x == "rock and roll"
x.replace(5, 3, "&");       // x == "rock & roll"
//! [3]


//! [4]
QByteArray ba("We must be <b>bold</b>, very <b>bold</b>");
int j = 0;
while ((j = ba.indexOf("<b>", j)) != -1) {
    cout << "Found <b> tag at index position " << j << endl;
    ++j;
}
//! [4]


//! [5]
QByteArray().isNull();          // returns true
QByteArray().isEmpty();         // returns true

QByteArray("").isNull();        // returns false
QByteArray("").isEmpty();       // returns true

QByteArray("abc").isNull();     // returns false
QByteArray("abc").isEmpty();    // returns false
//! [5]


//! [6]
QByteArray ba("Hello");
int n = ba.size();          // n == 5
ba.data()[0];               // returns 'H'
ba.data()[4];               // returns 'o'
ba.data()[5];               // returns '\0'
//! [6]


//! [7]
QByteArray().isEmpty();         // returns true
QByteArray("").isEmpty();       // returns true
QByteArray("abc").isEmpty();    // returns false
//! [7]


//! [8]
QByteArray ba("Hello world");
char *data = ba.data();
while (*data) {
    cout << "[" << *data << "]" << endl;
    ++data;
}
//! [8]


//! [9]
QByteArray ba;
for (int i = 0; i < 10; ++i)
    ba[i] = 'A' + i;
// ba == "ABCDEFGHIJ"
//! [9]


//! [10]
QByteArray ba("Stockholm");
ba.truncate(5);             // ba == "Stock"
//! [10]


//! [11]
QByteArray ba("STARTTLS\r\n");
ba.chop(2);                 // ba == "STARTTLS"
//! [11]


//! [12]
QByteArray x("free");
QByteArray y("dom");
x += y;
// x == "freedom"
//! [12]


//! [13]
QByteArray().isNull();          // returns true
QByteArray("").isNull();        // returns false
QByteArray("abc").isNull();     // returns false
//! [13]


//! [14]
QByteArray ba("Istambul");
ba.fill('o');
// ba == "oooooooo"

ba.fill('X', 2);
// ba == "XX"
//! [14]


//! [15]
QByteArray x("ship");
QByteArray y("air");
x.prepend(y);
// x == "airship"
//! [15]


//! [16]
QByteArray x("free");
QByteArray y("dom");
x.append(y);
// x == "freedom"
//! [16]


//! [17]
QByteArray ba("Meal");
ba.insert(1, QByteArray("ontr"));
// ba == "Montreal"
//! [17]


//! [18]
QByteArray ba("Montreal");
ba.remove(1, 4);
// ba == "Meal"
//! [18]


//! [19]
QByteArray x("Say yes!");
QByteArray y("no");
x.replace(4, 3, y);
// x == "Say no!"
//! [19]


//! [20]
QByteArray ba("colour behaviour flavour neighbour");
ba.replace(QByteArray("ou"), QByteArray("o"));
// ba == "color behavior flavor neighbor"
//! [20]


//! [21]
QByteArray x("sticky question");
QByteArray y("sti");
x.indexOf(y);               // returns 0
x.indexOf(y, 1);            // returns 10
x.indexOf(y, 10);           // returns 10
x.indexOf(y, 11);           // returns -1
//! [21]


//! [22]
QByteArray ba("ABCBA");
ba.indexOf("B");            // returns 1
ba.indexOf("B", 1);         // returns 1
ba.indexOf("B", 2);         // returns 3
ba.indexOf("X");            // returns -1
//! [22]


//! [23]
QByteArray x("crazy azimuths");
QByteArray y("az");
x.lastIndexOf(y);           // returns 6
x.lastIndexOf(y, 6);        // returns 6
x.lastIndexOf(y, 5);        // returns 2
x.lastIndexOf(y, 1);        // returns -1
//! [23]


//! [24]
QByteArray ba("ABCBA");
ba.lastIndexOf("B");        // returns 3
ba.lastIndexOf("B", 3);     // returns 3
ba.lastIndexOf("B", 2);     // returns 1
ba.lastIndexOf("X");        // returns -1
//! [24]


//! [25]
QByteArray url("ftp://ftp.qt-project.org/");
if (url.startsWith("ftp:"))
    ...
//! [25]


//! [26]
QByteArray url("http://qt-project.org/doc/qt-5.0/qtdoc/index.html");
if (url.endsWith(".html"))
    ...
//! [26]


//! [27]
QByteArray x("Pineapple");
QByteArray y = x.left(4);
// y == "Pine"
//! [27]


//! [28]
QByteArray x("Pineapple");
QByteArray y = x.right(5);
// y == "apple"
//! [28]


//! [29]
QByteArray x("Five pineapples");
QByteArray y = x.mid(5, 4);     // y == "pine"
QByteArray z = x.mid(5);        // z == "pineapples"
//! [29]


//! [30]
QByteArray x("Qt by DIGIA");
QByteArray y = x.toLower();
// y == "qt by digia"
//! [30]


//! [31]
QByteArray x("Qt by DIGIA");
QByteArray y = x.toUpper();
// y == "QT BY DIGIA"
//! [31]


//! [32]
QByteArray ba("  lots\t of\nwhitespace\r\n ");
ba = ba.simplified();
// ba == "lots of whitespace";
//! [32]


//! [33]
QByteArray ba("  lots\t of\nwhitespace\r\n ");
ba = ba.trimmed();
// ba == "lots\t of\nwhitespace";
//! [33]


//! [34]
QByteArray x("apple");
QByteArray y = x.leftJustified(8, '.');   // y == "apple..."
//! [34]


//! [35]
QByteArray x("apple");
QByteArray y = x.rightJustified(8, '.');    // y == "...apple"
//! [35]


//! [36]
QByteArray str("FF");
bool ok;
int hex = str.toInt(&ok, 16);     // hex == 255, ok == true
int dec = str.toInt(&ok, 10);     // dec == 0, ok == false
//! [36]


//! [37]
QByteArray str("FF");
bool ok;
long hex = str.toLong(&ok, 16);   // hex == 255, ok == true
long dec = str.toLong(&ok, 10);   // dec == 0, ok == false
//! [37]


//! [38]
QByteArray string("1234.56");
double a = string.toDouble();   // a == 1234.56
//! [38]


//! [39]
QByteArray text("Qt is great!");
text.toBase64();        // returns "UXQgaXMgZ3JlYXQh"
//! [39]

//! [39bis]
QByteArray text("<p>Hello?</p>");
text.toBase64(QByteArray::Base64 | QByteArray::OmitTrailingEquals);      // returns "PHA+SGVsbG8/PC9wPg"
text.toBase64(QByteArray::Base64);                                       // returns "PHA+SGVsbG8/PC9wPg=="
text.toBase64(QByteArray::Base64Url);                                    // returns "PHA-SGVsbG8_PC9wPg=="
text.toBase64(QByteArray::Base64Url | QByteArray::OmitTrailingEquals);   // returns "PHA-SGVsbG8_PC9wPg"
//! [39bis]


//! [40]
QByteArray ba;
int n = 63;
ba.setNum(n);           // ba == "63"
ba.setNum(n, 16);       // ba == "3f"
//! [40]


//! [41]
int n = 63;
QByteArray::number(n);              // returns "63"
QByteArray::number(n, 16);          // returns "3f"
QByteArray::number(n, 16).toUpper();  // returns "3F"
//! [41]


//! [42]
QByteArray ba = QByteArray::number(12.3456, 'E', 3);
// ba == 1.235E+01
//! [42]


//! [43]
 static const char mydata[] = {
    0x00, 0x00, 0x03, 0x84, 0x78, 0x9c, 0x3b, 0x76,
    0xec, 0x18, 0xc3, 0x31, 0x0a, 0xf1, 0xcc, 0x99,
    ...
    0x6d, 0x5b
};

QByteArray data = QByteArray::fromRawData(mydata, sizeof(mydata));
QDataStream in(&data, QIODevice::ReadOnly);
...
//! [43]


//! [44]
QByteArray text = QByteArray::fromBase64("UXQgaXMgZ3JlYXQh");
text.data();            // returns "Qt is great!"
//! [44]

//! [44bis]
QByteArray::fromBase64("PHA+SGVsbG8/PC9wPg==", QByteArray::Base64Encoding); // returns "<p>Hello?</p>"
QByteArray::fromBase64("PHA-SGVsbG8_PC9wPg==", QByteArray::Base64UrlEncoding); // returns "<p>Hello?</p>"
//! [44bis]


//! [45]
QByteArray text = QByteArray::fromHex("517420697320677265617421");
text.data();            // returns "Qt is great!"
//! [45]

//! [46]
QString tmp = "test";
QByteArray text = tmp.toLocal8Bit();
char *data = new char[text.size()];
strcpy(data, text.data());
delete [] data;
//! [46]

//! [47]
QString tmp = "test";
QByteArray text = tmp.toLocal8Bit();
char *data = new char[text.size() + 1];
strcpy(data, text.data());
delete [] data;
//! [47]

//! [48]
QByteArray ba1("ca\0r\0t");
ba1.size();                     // Returns 2.
ba1.constData();                // Returns "ca" with terminating \0.

QByteArray ba2("ca\0r\0t", 3);
ba2.size();                     // Returns 3.
ba2.constData();                // Returns "ca\0" with terminating \0.

QByteArray ba3("ca\0r\0t", 4);
ba3.size();                     // Returns 4.
ba3.constData();                // Returns "ca\0r" with terminating \0.

const char cart[] = {'c', 'a', '\0', 'r', '\0', 't'};
QByteArray ba4(QByteArray::fromRawData(cart, 6));
ba4.size();                     // Returns 6.
ba4.constData();                // Returns "ca\0r\0t" without terminating \0.
//! [48]

}
Example #27
0
bool ZInstrument::loadSfz(const QString& s)
      {
      _program = 0;
      QFile f(s);
      if (!f.open(QIODevice::ReadOnly)) {
            qDebug("ZInstrument: cannot load %s", qPrintable(s));
            return false;
            }
      QFileInfo fi(f);
      QString path = fi.absolutePath();
      qint64 total = fi.size();

      QString sample;

      SfzRegion r;
      SfzRegion g;      // group
      r.init(path);
      g.init(path);

      bool groupMode = false;
      zerberus->setLoadProgress(0);

      while (!f.atEnd()) {
            QByteArray ba = f.readLine();
            zerberus->setLoadProgress(((qreal)f.pos() * 100) / total);
            ba = ba.simplified();

            if (ba.isEmpty() || ba.startsWith("//"))
                  continue;
            if (zerberus->loadWasCanceled())
                  return false;
            if (ba.startsWith("<group>")) {
                  if (!groupMode && !r.isEmpty())
                        addRegion(r);
                  g.init(path);
                  r.init(path);
                  groupMode = true;
                  ba = ba.mid(7);
                  }
            else if (ba.startsWith("<region>")) {
                  if (groupMode) {
                        g = r;
                        groupMode = false;
                        }
                  else {
                        if (!r.isEmpty())
                              addRegion(r);
                        r = g;  // initialize next region with group values
                        }
                  ba = ba.mid(8);
                  }
            QRegularExpression re("\\s?(\\w+)=");
            QRegularExpressionMatchIterator i = re.globalMatch(ba);

            while (i.hasNext()) {
                  QRegularExpressionMatch match = i.next();
                  int si = match.capturedEnd();
                  int ei;
                  if (i.hasNext()) {
                        QRegularExpressionMatch nextMatch = i.peekNext();
                        ei = nextMatch.capturedStart();
                        }
                  else
                        ei = ba.size();
                  QString s = ba.mid(si, ei-si);
                  r.readOp(match.captured(1), s);
                  }
            }
      zerberus->setLoadProgress(100);
      if (!groupMode && !r.isEmpty())
            addRegion(r);
      return true;
      }
Example #28
0
static void parse( MetaTranslator *tor, const char *initialContext,
           const char *defaultContext )
{
    QMap<QByteArray, QByteArray> qualifiedContexts;
    QByteArray context;
    QByteArray text;
    QByteArray com;
    QByteArray functionContext = initialContext;
    QByteArray prefix;
    bool utf8 = false;

    yyTok = getToken();
    while ( yyTok != Tok_Eof ) {
        switch ( yyTok ) {
        case Tok_class:
                yyTok = getToken();
                functionContext = yyIdent;
                yyTok = getToken();
                break;
            case Tok_tr:
            case Tok_trUtf8:
                utf8 = (yyTok == Tok_trUtf8 || (yyCodecForTr && strcmp(yyCodecForTr->name(), "UTF-8") == 0));
                yyTok = getToken();
                if (match(Tok_LeftParen) && matchString(&text))
                {
                    com = "";
                    bool plural = false;

                    if (match(Tok_RightParen))
                    {
                        // There is no comment or plural arguments.
                    }
                    else if (match(Tok_Comma) && matchStringOrNone(&com))
                    {
                        // There is a comment argument.
                        if (match(Tok_RightParen))
                        {
                            // There is no plural argument.
                        }
                        else if (match(Tok_Comma))
                        {
                            // There is a plural argument.
                            plural = true;
                        }
                    }

                    if (prefix.isNull())
                        context = defaultContext;
                    else if (qstrcmp(prefix, "self") == 0)
                        context = functionContext;
                    else
                        context = prefix;

                    prefix = (const char *) 0;

                    if (qualifiedContexts.contains(context))
                        context = qualifiedContexts[context];

                    if (!text.isEmpty())
                    {
                        tor->insert(MetaTranslatorMessage(context, text, com, 
                                yyFileName, yyParenLineNo,
                                QStringList(), utf8,
                                MetaTranslatorMessage::Unfinished, plural));
                    }
                }
                break;
            case Tok_translate:
                utf8 = false;
                yyTok = getToken();
                if ( match(Tok_LeftParen) &&
                 matchString(&context) &&
                 match(Tok_Comma) &&
                 matchString(&text) ) {
                    com = "";
                    bool plural = false;
                    if (!match(Tok_RightParen)) {
                        // look for comment
                        if ( match(Tok_Comma) && matchStringOrNone(&com)) {
                            if (!match(Tok_RightParen)) {
                                // look for encoding
                                if (match(Tok_Comma)) {
                                    if (matchEncoding(&utf8)) {
                                        if (!match(Tok_RightParen)) {
                                            // look for the plural quantifier,
                                            // this can be a number, an identifier or a function call,
                                            // so for simplicity we mark it as plural if we know we have a comma instead of an
                                            // right parentheses.
                                            plural = match(Tok_Comma);
                                        }
                                    } else {
                                        // This can be a QTranslator::translate("context", "source", "comment", n) plural translation
                                        if (matchExpression() && match(Tok_RightParen)) {
                                            plural = true;
                                        } else {
                                            break;
                                        }
                                    }
                                } else {
                                    break;
                                }
                            }
                        } else {
                            break;
                        }
                    }
                    if (!text.isEmpty())
                    {
                        tor->insert( MetaTranslatorMessage(context, text, com, 
                                                        yyFileName, yyParenLineNo,
                                                        QStringList(), utf8,
                                                        MetaTranslatorMessage::Unfinished,
                                                        plural) );
                    }
                }
                break;
            case Tok_Ident:
                if ( !prefix.isNull() )
                    prefix += ".";
                prefix += yyIdent;
                yyTok = getToken();
                if ( yyTok != Tok_Dot )
                    prefix = (const char *) 0;
                break;
            case Tok_Comment:
                com = yyComment;
                com = com.simplified();
                if ( com.left(sizeof(MagicComment) - 1) == MagicComment ) {
                    com.remove( 0, sizeof(MagicComment) - 1 );
                    int k = com.indexOf( ' ' );
                    if ( k == -1 ) {
                        context = com;
                    } else {
                        context = com.left( k );
                        com.remove( 0, k + 1 );
                        tor->insert( MetaTranslatorMessage(context, "", com,
                                                        yyFileName, yyParenLineNo,
                                                        QStringList(), false) );
    
                    }
                }
                yyTok = getToken();
                break;
            default:
                yyTok = getToken();
        }
    }

    if ( yyParenDepth != 0 )
        qWarning( "%s: Unbalanced parentheses in Python code",
            (const char *) yyFileName );
}
Example #29
0
void CamView::readDevices()
      {
      devices.clear();

      QDir d("/sys/class/video4linux/");
      for (auto i : d.entryList(QDir::NoDotAndDotDot | QDir::AllEntries)) {
            if (!i.startsWith("video"))
                  continue;
            QString name = i;
            QDir dd(d.filePath(i));
            QFile f(dd.filePath("name"));
            if (f.open(QIODevice::ReadOnly)) {
                  QByteArray ba = f.readAll();
                  f.close();
                  name = ba.simplified();
                  }
            // QDir ddd(dd.filePath("device"));

            CamDevice cd;
            cd.shortName = i;
            cd.name      = name;
            cd.device    = "/dev/" + i;

            char* videodevice = cd.device.toLocal8Bit().data();
            int fd = open(videodevice, O_RDWR);
            if (fd == -1) {
                  fprintf(stderr, "CamView: cannot open <%s>: %s\n", videodevice, strerror(errno));
                  return;
                  }
            struct v4l2_frmsizeenum s;
            memset(&s, 0, sizeof(s));
            s.pixel_format = V4L2_PIX_FMT_MJPEG;

            for (int idx = 0;;++idx) {
                  s.index = idx;
                  int ret = ioctl(fd, VIDIOC_ENUM_FRAMESIZES, &s);
                  if (ret == -1) {
                        if (errno != EINVAL) {
                              fprintf(stderr, "CamView: <%s>: %d ioctl failed %s\n",
                                 qPrintable(cd.device),
                                 errno, strerror(errno));
                              }
                        break;
                        }
                  if (s.type == V4L2_FRMSIZE_TYPE_DISCRETE) {
                        CamDeviceFormat fmt;
                        fmt.size = QSize(s.discrete.width, s.discrete.height);

                        struct v4l2_frmivalenum f;
                        memset(&f, 0, sizeof(f));
                        f.pixel_format = V4L2_PIX_FMT_MJPEG;
                        f.width        = s.discrete.width;
                        f.height       = s.discrete.height;

                        for (int k = 0;; ++k) {
                              f.index = k;
                              int ret = ioctl(fd, VIDIOC_ENUM_FRAMEINTERVALS, &f);
                              if (ret == -1) {
                                    if (errno != EINVAL) {
                                          fprintf(stderr, "CamView: <%s>: %d ioctl failed %s\n",
                                             qPrintable(cd.device),
                                             errno, strerror(errno));
                                          }
                                    break;
                                    }
                              if (f.type == V4L2_FRMIVAL_TYPE_DISCRETE) {
                                    fmt.frameRates.push_back(f.discrete.denominator);
                                    }
                              else if (f.type == V4L2_FRMIVAL_TYPE_STEPWISE) {
                                    ;
                                    }
                              else if (f.type == V4L2_FRMIVAL_TYPE_CONTINUOUS) {
                                    ;
                                    }
                              }
                        cd.formats.push_back(fmt);
                        }
                  else if (s.type == V4L2_FRMSIZE_TYPE_CONTINUOUS) {
                        break;
                        }
                  else if (s.type == V4L2_FRMSIZE_TYPE_STEPWISE) {
                        break;
                        }
                  }
            ::close(fd);
            // search for button device
            QDir ddd(dd.filePath("device/input"));
            for (auto i : ddd.entryList(QDir::NoDotAndDotDot | QDir::AllEntries)) {
                  if (i.startsWith("input")) {
                        QDir dddd(ddd.filePath(i));
                        for (auto i : dddd.entryList(QDir::NoDotAndDotDot | QDir::AllEntries)) {
                              if (i.startsWith("event")) {
                                    cd.buttonDevice = "/dev/input/" + i;
                                    break;
                                    }
                              }
                        }
                  break;
                  }

            devices.push_back(cd);
            }
      }
Example #30
0
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
FloatArrayType::Pointer AngleFileLoader::loadData()
{
  FloatArrayType::Pointer angles = FloatArrayType::NullPointer();

  // Make sure the input file variable is not empty
  if (m_InputFile.size() == 0)
  {
    setErrorMessage("Input File Path is empty");
    setErrorCode(-1);
    return angles;
  }

  QFileInfo fi(getInputFile());

  // Make sure the file exists on disk
  if (fi.exists() == false)
  {
    setErrorMessage("Input File does not exist at path");
    setErrorCode(-2);
    return angles;
  }

  // Make sure we have a valid angle representation
  if(m_AngleRepresentation != EulerAngles
      && m_AngleRepresentation != QuaternionAngles
      && m_AngleRepresentation != RodriguezAngles)
  {
    setErrorMessage("The Angle representation was not set to anything known to this code");
    setErrorCode(-3);
    return angles;
  }


  // The format of the file is quite simple. Comment lines start with a "#" symbol
  // The only Key-Value pair we are looking for is 'Angle Count' which will have
  // the total number of angles that will be read

  int numOrients = 0;
  QByteArray buf;

  // Open the file and read the first line
  QFile reader(getInputFile());
  if (!reader.open(QIODevice::ReadOnly | QIODevice::Text))
  {
    QString msg = QObject::tr("Angle file could not be opened: %1").arg(getInputFile());
    setErrorCode(-100);
    setErrorMessage(msg);
    return angles;
  }

  bool ok = false;
  buf = reader.readLine();
  while(buf[0] == '#')
  {
    buf = reader.readLine();
  }
  buf = buf.trimmed();

  //Split the next line into a pair of tokens delimited by the ":" character
  QList<QByteArray> tokens = buf.split(':');
  if(tokens.count() != 2)
  {
    QString msg = QObject::tr("Proper Header was not detected. The file should have a single header line of 'Angle Count:XXXX'");
    setErrorCode(-101);
    setErrorMessage(msg);
    return angles;
  }

  if(tokens[0].toStdString().compare("Angle Count") != 0)
  {
    QString msg = QObject::tr("Proper Header was not detected. The file should have a single header line of 'Angle Count:XXXX'");
    setErrorCode(-102);
    setErrorMessage(msg);
    return angles;
  }
  numOrients = tokens[1].toInt(&ok, 10);

  // Allocate enough for the angles
  QVector<size_t> dims(1, 5);
  angles = FloatArrayType::CreateArray(numOrients, dims, "EulerAngles_From_File");

  for(int i = 0; i < numOrients; i++)
  {
    float weight = 0.0f;
    float sigma = 1.0f;
    buf = reader.readLine();
    // Skip any lines that start with a '#' character
    if(buf[0] == '#') { continue; }
    buf = buf.trimmed();

    // Remove multiple Delimiters if wanted by the user.
    if (m_IgnoreMultipleDelimiters == true)
    {
      buf = buf.simplified();
    }
    tokens = buf.split( *(getDelimiter().toLatin1().data()));

    FOrientArrayType euler(3);
    if (m_AngleRepresentation == EulerAngles)
    {
      euler[0] = tokens[0].toFloat(&ok);
      euler[1] = tokens[1].toFloat(&ok);
      euler[2] = tokens[2].toFloat(&ok);
      weight = tokens[3].toFloat(&ok);
      sigma = tokens[4].toFloat(&ok);
    }
    else if (m_AngleRepresentation == QuaternionAngles)
    {
      FOrientArrayType quat(4);
      quat[0] = tokens[0].toFloat(&ok);
      quat[1] = tokens[1].toFloat(&ok);
      quat[2] = tokens[2].toFloat(&ok);
      quat[3] = tokens[3].toFloat(&ok);
      FOrientTransformsType::qu2eu(quat, euler);
      weight = tokens[4].toFloat(&ok);
      sigma = tokens[5].toFloat(&ok);
    }
    else if (m_AngleRepresentation == RodriguezAngles)
    {
      FOrientArrayType rod(4, 0.0);
      rod[0] = tokens[0].toFloat(&ok);
      rod[1] = tokens[1].toFloat(&ok);
      rod[2] = tokens[2].toFloat(&ok);
      FOrientTransformsType::ro2eu(rod, euler);
      weight = tokens[3].toFloat(&ok);
      sigma = tokens[4].toFloat(&ok);
    }

    // Values in File are in Radians and the user wants them in Degrees
    if (m_FileAnglesInDegrees == false && m_OutputAnglesInDegrees == true)
    {
      euler[0] = euler[0] * SIMPLib::Constants::k_RadToDeg;
      euler[1] = euler[1] * SIMPLib::Constants::k_RadToDeg;
      euler[2] = euler[2] * SIMPLib::Constants::k_RadToDeg;
    }
    // Values are in Degrees but user wants them in Radians
    else if (m_FileAnglesInDegrees == true && m_OutputAnglesInDegrees == false)
    {
      euler[0] = euler[0] * SIMPLib::Constants::k_DegToRad;
      euler[1] = euler[1] * SIMPLib::Constants::k_DegToRad;
      euler[2] = euler[2] * SIMPLib::Constants::k_DegToRad;
    }

    // Store the values into our array
    angles->setComponent(i, 0, euler[0]);
    angles->setComponent(i, 1, euler[1]);
    angles->setComponent(i, 2, euler[2]);
    angles->setComponent(i, 3, weight);
    angles->setComponent(i, 4, sigma);
    //   qDebug() << "reading line: " << i ;
  }



  return angles;
}