Connection::Connection(QString uri, QObject *parent) :
    Connection(parent)
{
    uri.remove(0, 5);//remove the prefix "ss://" from uri
    QStringList resultList = QString(QByteArray::fromBase64(QByteArray(uri.toStdString().c_str()))).split(':');
    profile.method = resultList.takeFirst().toUpper();
    profile.serverPort = resultList.takeLast().toUShort();
    QStringList ser = resultList.join(':').split('@');//there are lots of ':' in IPv6 address
    profile.serverAddress = ser.takeLast();
    profile.password = ser.join('@');//incase there is a '@' in password
}
 QObject* Utils::findObject(const QString& path)
 {
     const QString separator("::");
     QStringList parts = path.split(separator);
     if (parts.isEmpty())
     {
         return NULL;
     }
     const QString name = parts.takeLast();
     const QObject * parent = NULL;
     if (parts.isEmpty())
     {
         {
             const QString childObjectName = Utils::objectName(Application::instance());
             if (childObjectName == name)
             {
                 return Application::instance();
             }
         }
         // Top level widget
         Q_FOREACH(QObject * const object, Application::instance()->children())
         {
             const QString childObjectName = Utils::objectName(object);
             if (childObjectName == name)
             {
                 return object;
             }
         }
         return NULL;
     }
void OcaOctaveController::readStdout()
{
  char buf[ 1024 ];
  //fprintf( stderr, "OcaOctaveController::readStdout $$$ %d (%d)\n", result, m_pipeFd );
  int result = -1;
  do {
    result = read( m_pipeFd, buf, 1023 );
    if( 0 < result ) {
      //fprintf( stderr, "OcaOctaveController::readStdout\n" );
      //fwrite( buf, 1, result, stderr );
      //fprintf( stderr, "OcaOctaveController::readStdout - END\n" );
      buf[ result ] = 0;

      m_stdoutBuf += QString::fromLocal8Bit( buf );
      QStringList lines = m_stdoutBuf.split( '\n' );
      m_stdoutBuf = lines.takeLast();
      //Q_ASSERT( ! lines.isEmpty() );
      /*
      if( '\n' != m_stdoutBuf[ m_stdoutBuf.length() - 1 ] ) {
        m_stdoutBuf = lines.takeLast();
      }
      else {
        m_stdoutBuf.clear();
        QString s = lines.takeLast();
        Q_ASSERT( s.isEmpty() );
      }
      */
      while( ! lines.isEmpty() ) {
        QString s = lines.takeFirst();
        //fprintf( stderr, "readStdout: %s\n", s.toLocal8Bit().data() );
        emit outputReceived( s, 0 );
      }
    }
  } while( ( 1023 == result ) && ( e_StateReady == m_state ) );
}
Example #4
0
 void testString(const QString &message)
 {
     qDebug() << Utils::normalizeMarkup(message, Utils::NoMarkup);
     SnoreCore &snore = SnoreCore::instance();
     QStringList backends = snore.pluginNames(SnorePlugin::Backend);
     auto notify = [&backends, &snore, &message, this](Notification n) {
         qDebug() << n << "closed";
         qDebug() << backends.size();
         if (backends.empty()) {
             return;
         }
         QString old = snore.primaryNotificationBackend();
         while (snore.primaryNotificationBackend() == old) {
             QString p = backends.takeLast();
             snore.setSettingsValue(QStringLiteral("PrimaryBackend"), p, LocalSetting);
             SnoreCorePrivate::instance()->syncSettings();
             if (snore.primaryNotificationBackend() == p) {
                 qDebug() << p;
                 snore.broadcastNotification(Notification(app, app.defaultAlert(), QStringLiteral("Title"), message, app.icon()));
             }
         }
     };
     auto con = connect(&snore, &SnoreCore::notificationClosed, notify);
     notify(Notification());
     while (!backends.empty()) {
         QTest::qWait(100);
     }
     QTest::qWait(100);
     disconnect(con);
 }
void AmbienteExternoROSBridge::configuraAmbienteROS()
{
    bool ok;
    QString endereco = QInputDialog::getText(0x0, QString("Configuracao ROSBridge"), QString("Endereco:"), QLineEdit::Normal, "ws://localhost:9090", &ok);
    endereco = endereco.trimmed();
    if (ok && !endereco.isEmpty())
    {
        string ip;
        int porta;
        if (endereco.contains(QRegExp(QLatin1String(":([0-9]|[1-9][0-9]{1,3}|[1-5][0-9]{1,4}|6[0-4][0-9]{3}|65[0-4][0-9]{2}|655[0-2][0-9]|6553[0-5])$"))))
        {
            QStringList splitted = endereco.split(':');
            porta = splitted.takeLast().toUInt();
            ip = splitted.join(":").toStdString();
        }
        else
        {
            ip = endereco.toStdString();
            porta = 80;
        }
        cout << "IP: " << ip << " porta " << porta << endl;

        m_ros.conecta(ip, porta);
    }
}
Example #6
0
void
RestStateWidget::updatePlayerNames()
{
#ifdef WIN32
    QStringList plugins = The::settings().allPlugins( false );
    plugins.removeAll( "" );

    if ( plugins.count() )
    {
        QString last_plugin = plugins.takeLast();

        if ( plugins.count() )
        {
            QString text = tr( "or listen to your music in %1 or %2.",
                    "%1 is a list of plugins, eg. 'Foobar, Winamp, Windows Media Player'" );

            ui.label2->setText( text.arg( plugins.join( ", " ) ).arg( last_plugin ) );
        }
        else
            ui.label2->setText( tr( "or listen to your music in %1.", "%1 is a media player" ).arg( last_plugin ) );
    }
    else
        ui.label2->setText( tr( "or install a player plugin to scrobble music from your media player." ) );
#endif
}
Example #7
0
void Server::newMessage()
{
    if(QTcpSocket *c = dynamic_cast<QTcpSocket*> (sender())) {
        data[c].append(c->readAll());
        if(!data[c].contains(QChar(23)))
            return;
        QStringList l = data[c].split(QChar(23));
        data[c] = l.takeLast();
        foreach(QString s, l) {
            string sss = s.toStdString();
            stringstream ss(sss);
            int a;
            ss >> a;
            if(a == 2 || a == 5 || a == 12) {
                s.append(QChar(23));
                c1->write(s.toLocal8Bit());
                c2->write(s.toLocal8Bit());
            }
            else if(a == 7) { //team selection
                if(num == 1 && t1 == "n") {
                    string str;
                    ss >> str;
                    t1 = QString::fromStdString(str);
                    QString s = "11";
                    s.append(QChar(23));
                    c1->write(s.toLocal8Bit());
                }
                else if(num == 2) {
Example #8
0
QStringList CSite::traffic(quint16 &busy) const {
    QStringList zeeiList = m_zeei.split("\n");
    QStringList btsList = zeeiList.filter("BTS-");

    busy = 0;
    QStringList btss;

    for (int i = 0; i < btsList.count(); i++) {
        QStringList btsLine = btsList[i].split(" ");
        btsLine.removeAll("");

        QString state = btsLine[btsLine.indexOf(btsLine.filter("BTS-").first()) + 2];
        if (state.contains("BL-")) {
            btss << state;
            continue;
        }

        QString fr = btsLine.takeLast();
        QString hr = btsLine.takeLast();

        quint8 btsBusy = fr.toUShort() + hr.toUShort();

        if (!btsBusy)
            btss << "EMPTY";
        else if (i < m_caps.count() && btsBusy > m_caps[i] - BUSY_LIMIT)
            btss << "FULL";
        else
            btss << QString::number(btsBusy);

        busy += btsBusy;
    }

    return btss;
}
Example #9
0
/*!
* parse a text file and return a links list in html format:
* left the names and right the contact address
* the html table can be "split" in sections
* @param QString fileName the file to be parsed
* @return QString the html table
*/
QString About::parseLinksFile(QString fileName)
{
	QString result;
	QString file;
	QFile linksFile(fileName);
	if (linksFile.open(QIODevice::ReadOnly | QIODevice::Text))
	{
		QTextStream inTS(&linksFile);
		inTS.setCodec("UTF-8");
		inTS.setAutoDetectUnicode(true);
		QString lineTS;
		bool isTitle = true;
		result = "<table>";
		while (!inTS.atEnd())
		{
			lineTS = inTS.readLine();
			// convert (r) "�" to &#174, "�" to &#8482
			// lineTS = QString::fromUtf8(lineTS);
			lineTS.replace("<", "&lt;");
			lineTS.replace(">", "&gt;");
			lineTS.replace("�", "&#174;");
			lineTS.replace("�", "&#8482;");
			if (!lineTS.isEmpty())
			{
				if (isTitle)
				{
					isTitle = false;
					result += "<tr><td><b>"+About::trLinksTitle(lineTS)+"</b></td></tr>";

				} // if is title
				else
				{
					result += "<tr><td><a href=\""+lineTS+"\">"+lineTS+"</a></td></tr>";
				} // else is title
			} // if is empty line
			else
			{
				// empty lines switch to title (one line)
			  result += "<tr><td></td></tr>";
			  isTitle = true;
			} // else is empty line
		} // while ! atEnd
		result += "<table>";
	} // if file found
	else
	{
		if (!fileName.isEmpty())
		{
			QStringList field = fileName.split("/");
			if (!field.isEmpty())
			{
				file = field.takeLast();
			}
		}
		result = tr("Unable to open %1 file. Please check your install directory or the Scribus website for %1 information.").arg(file);
		result = "";
	} // else file found
	return result;
} // parseLinksFile()
 // FIXME: this should actually be a member function of ContentIndex
 int contentIndexUp( KMime::ContentIndex &index )
 {
   Q_ASSERT( index.isValid() );
   QStringList ids = index.toString().split( QLatin1Char('.') );
   QString lastId = ids.takeLast();
   index = KMime::ContentIndex( ids.join( QLatin1String(".") ) );
   return lastId.toInt();
 }
	void UpdatesNotificationManager::notify ()
	{
		NotifyScheduled_ = false;

		auto em = Proxy_->GetEntityManager ();

		const auto upgradableCount = UpgradablePackages_.size ();
		QString bodyText;
		if (!upgradableCount)
		{
			auto cancel = Util::MakeANCancel ("org.LeechCraft.LackMan", "org.LeechCraft.LackMan");
			em->HandleEntity (cancel);

			return;
		}
		else if (upgradableCount <= 3)
		{
			QStringList names;
			for (auto id : UpgradablePackages_)
				names << Core::Instance ().GetListPackageInfo (id).Name_;
			names.sort ();

			if (upgradableCount == 1)
				bodyText = tr ("A new version of %1 is available.")
						.arg ("<em>" + names.value (0) + "</em>");
			else
			{
				const auto& lastName = names.takeLast ();
				bodyText = tr ("New versions of %1 and %2 are available.")
						.arg ("<em>" + names.join ("</em>, <em>") + "</em>")
						.arg ("<em>" + lastName + "</em>");
			}
		}
		else
			bodyText = tr ("New versions are available for %n package(s).",
					0, upgradableCount);

		auto entity = Util::MakeAN ("Lackman",
				bodyText,
				PInfo_,
				"org.LeechCraft.LackMan",
				AN::CatPackageManager,
				AN::TypePackageUpdated,
				"org.LeechCraft.LackMan",
				{ "Lackman" },
				0,
				upgradableCount);

		auto nah = new Util::NotificationActionHandler (entity, this);
		nah->AddFunction (tr ("Open LackMan"),
				[this, entity, em] () -> void
				{
					emit openLackmanRequested ();
					em->HandleEntity (Util::MakeANCancel (entity));
				});

		em->HandleEntity (entity);
	}
Example #12
0
void
TrackDashboard::onArtistGotTopTags( WsReply* reply )
{
    ui.tags->clear();
    QStringList tags = Tag::list( reply ).values();
    int x = qMin( 8, tags.count() );
    while (x--)
        ui.tags->addItem( tags.takeLast() );
}
Example #13
0
static Profile createGccProfile(const QString &compilerFilePath, Settings *settings,
                                const QStringList &toolchainTypes,
                                const QString &profileName = QString())
{
    const QString machineName = gccMachineName(compilerFilePath);
    const QStringList compilerTriplet = machineName.split(QLatin1Char('-'));
    const bool isMingw = toolchainTypes.contains(QLatin1String("mingw"));
    const bool isClang = toolchainTypes.contains(QLatin1String("clang"));

    if (isMingw) {
        if (!validMinGWMachines().contains(machineName)) {
            throw ErrorInfo(Tr::tr("Detected gcc platform '%1' is not supported.")
                    .arg(machineName));
        }
    } else if (compilerTriplet.count() < 2) {
        throw qbs::ErrorInfo(Tr::tr("Architecture of compiler for platform '%1' at '%2' not understood.")
                             .arg(machineName, compilerFilePath));
    }

    Profile profile(!profileName.isEmpty() ? profileName : machineName, settings);
    profile.removeProfile();
    if (isMingw) {
        profile.setValue(QLatin1String("qbs.targetOS"), QStringList(QLatin1String("windows")));
    }

    const QString compilerName = QFileInfo(compilerFilePath).fileName();
    QString toolchainPrefix;
    if (compilerName.contains(QLatin1Char('-'))) {
        QStringList nameParts = compilerName.split(QLatin1Char('-'));
        profile.setValue(QLatin1String("cpp.compilerName"), nameParts.takeLast());
        toolchainPrefix = nameParts.join(QLatin1Char('-')) + QLatin1Char('-');
        profile.setValue(QLatin1String("cpp.toolchainPrefix"), toolchainPrefix);
    }
    profile.setValue(QLatin1String("cpp.linkerName"),
                     isClang ? QLatin1String("clang++") : QLatin1String("g++"));
    setCommonProperties(profile, compilerFilePath, toolchainPrefix, toolchainTypes,
                        compilerTriplet.first());

    // Check whether auxiliary tools reside within the toolchain's install path.
    // This might not be the case when using icecc or another compiler wrapper.
    const QString compilerDirPath = QFileInfo(compilerFilePath).absolutePath();
    const ToolPathSetup toolPathSetup(&profile, compilerDirPath, toolchainPrefix);
    toolPathSetup.apply(QLatin1String("ar"), QLatin1String("cpp.archiverPath"));
    toolPathSetup.apply(QLatin1String("nm"), QLatin1String("cpp.nmPath"));
    if (HostOsInfo::isOsxHost())
        toolPathSetup.apply(QLatin1String("dsymutil"), QLatin1String("cpp.dsymutilPath"));
    else
        toolPathSetup.apply(QLatin1String("objcopy"), QLatin1String("cpp.objcopyPath"));
    toolPathSetup.apply(QLatin1String("strip"), QLatin1String("cpp.stripPath"));

    qStdout << Tr::tr("Profile '%1' created for '%2'.").arg(profile.name(), compilerFilePath)
            << endl;
    return profile;
}
Example #14
0
AbstractCommand::ReturnCodes Move::run()
{
    if (! checkInRepository())
        return NotInRepo;
    moveToRoot();
    // Move in git is really remove and add. Git will auto detect that being a move.

    typedef QPair<QString, QString> RenamePair;

    QList<RenamePair> renamePairs;
    QStringList files = rebasedArguments();
    if (files.count() < 2) { // not sure what that would mean...
        Logger::error() << "Vng failed: you must specify at least two arguments for mv\n";
        return InvalidOptions;
    }
    QString target = files.takeLast();
    QFileInfo path(target);
    if (files.count() > 1) { // multiple files into a dir.
        if (! path.isDir()) {
            Logger::error() << "Vng failed:  The target directory '" << target <<
                "` does not seem to be an existing directory\n";
            return InvalidOptions;
        }
    }
    else { // target is a file
        if(File::fileKnownToGit(path)) {
            Logger::error() << "Vng failed: The file named '"<<  target <<
                "` already exists in working directory.\n";
            return InvalidOptions;
        }
    }
    foreach (QString arg, files) {
        if (canMoveFile(arg)) {
            if (files.count() > 1)
                renamePairs.append(qMakePair(arg, target + QDir::separator() + arg));
            else
                renamePairs.append(qMakePair(arg, target));
        }
    }

    if (dryRun())
        return Ok;

    QProcess git;
    QStringList arguments;
    arguments << "update-index" << "--add" << "--remove";
    foreach(RenamePair p, renamePairs) {
        Logger::debug() << "rename " << p.first << " => " << p.second << endl;
        if (QFile::rename(p.first, p.second))
            arguments << p.first << p.second;
        else
            Logger::error() << "Vng failed: Could not rename '" << p.first << "` to '" <<
                    p.second << "`, check permissions\n";
    }
Example #15
0
void Controller::addFileToRecentlyOpen(QString fileName){
    QStringList recentlyOpen = Settings::getInstance().lastImportedFiles();
    if(recentlyOpen.contains(fileName)){
        recentlyOpen.removeAll(fileName);
    }
    recentlyOpen.prepend(fileName);
    while(recentlyOpen.size() > RECENTLY_OPEN_MAX){
        recentlyOpen.takeLast();
    }
    emit recentlyImportedFilesChanged(recentlyOpen);
    Settings::getInstance().setLastImportedFiles(recentlyOpen);
}
Example #16
0
/*
 * Process the output of the refresh commands
 *
 * @param output The output of the dryrun process
 */
void PackageGroupModel::processDryrunResult(QString output) {
  QStringList lines = output.split(QRegularExpression("\\n"), QString::SkipEmptyParts);

  if(lines.length() == 1 || output.contains("*.pkg.tar?(.+([^.]))"))
  {
    //"==> no candidate packages found for pruning"
    m_cleanButton->setText(tr("Clean"));
  }
  else
  {
    //process package list
    for(int i = 0; i < lines.length(); i++)
    {
      QString line = lines.at(i);

      if(i == 0)
        //skip the first line ("==> Candidate packages:")
        continue;

      else if(i == lines.length() - 1)
      {
        //extract size from "==> finished dry run: 8 candidates (disk space saved: 19.11 MiB)")
        QStringList components = line.split(" ");

        QString unit = components.takeLast();
        unit.remove(unit.length() - 1, 1);

        QString size = components.takeLast();

        m_cleanButton->setText(tr("Clean %1").arg(" " + size + " " + unit));
      }
      else
        m_listView->addItem(line);
    }

    //there is packages to clean so reenable the clean button
    m_cleanButton->setEnabled(true);
  }
}
Example #17
0
void DropLabel::dropEvent( QDropEvent* event )
{
	QFileInfo fileInfo(event->mimeData()->text());

	//A little sting manuipulation to remove the "file:///"-prefix on the file path if dragged from asset browser
	QString filePath;
	if (fileInfo.filePath().startsWith(QLatin1String("file:///")))
	{
		filePath =  fileInfo.filePath().mid(8);
	}
	else
	{
		filePath =  fileInfo.filePath();	
	}

	QDir dirInfo(filePath);
	//Check if there is a name to begin with
	if(fileInfo.baseName() != 0)
	{
		QStringList dirPaths;
		//Collect all dirs up to Assets
		while(dirInfo.dirName() != "Assets")
		{
			dirPaths << dirInfo.dirName();

			if(!dirInfo.cdUp())
				break;
		}

		//Remove and store the file name without suffix
		dirPaths.pop_front();
		//Remove category folder from path list
		dirPaths.pop_back();

		QString relativePath;

		//Construct the relative path
		while (!dirPaths.isEmpty())
		{
			relativePath += dirPaths.takeLast() + "/";
		}

		//Finally add file name to path
		relativePath += fileInfo.completeBaseName();

		emit dropped(relativePath);
	}

	setStyleSheet("");

}
Example #18
0
void Slog2InfoRunner::processLog(bool force)
{
    QString input = QString::fromLatin1(m_logProcess->readAllStandardOutput());
    QStringList lines = input.split(QLatin1Char('\n'));
    if (lines.isEmpty())
        return;
    lines.first().prepend(m_remainingData);
    if (force)
        m_remainingData.clear();
    else
        m_remainingData = lines.takeLast();
    foreach (const QString &line, lines)
        processLogLine(line);
}
Example #19
0
    virtual void output(Entity* entity, QIODevice& iodevice) const{

        QStringList tokens= getCommentInternalText(BOOK_TAG).split(",",QString::SkipEmptyParts);


        QString title = tokens.takeFirst();
        QString location=tokens.takeFirst();

        QStringList pages = tokens;

        QString declPagesArray="var pages = [";

        QString lastPage = pages.takeLast();

        for(const QString& pageNumber: pages){
            declPagesArray.append('"').append(pageNumber).append("\",\n");
        }

        declPagesArray.append('"').append(lastPage).append("\"];\n");

        qDebug() << declPagesArray << location;

        QFileInfo bookDir(outputSite,location);
        if (!bookDir.exists()){
            return;
        }

        QFile outputJsFile(QFileInfo(QDir(bookDir.absolutePath()),"numero.js").absoluteFilePath());

        if (!outputJsFile.open(QIODevice::WriteOnly | QIODevice::Text | QIODevice::Truncate)){
            return ;
        }

        outputJsFile.write(declPagesArray.toUtf8());
        outputJsFile.write(readTemplate("://templates/numero.js").toUtf8());


        QFile outputHtmlFile(QFileInfo(QDir(bookDir.absolutePath()),"numero.html").absoluteFilePath());

        if (!outputHtmlFile.open(QIODevice::WriteOnly | QIODevice::Text | QIODevice::Truncate)){
            return ;
        }

        outputHtmlFile.write(readTemplate("://templates/numero.html").toUtf8());

        QString anchor=QString("<a href=\"").append(location).append("numero.html#page/1/mode/2up\">").append(title).append("</a>");
        iodevice.write(anchor.toUtf8());


    }
Example #20
0
//?х??
void Photos::scanFile(QString path)
{
    QDirIterator dirIterator(path,QDir::Files|QDir::NoSymLinks);
    while (dirIterator.hasNext())
    {
        QString tmpFile = dirIterator.next();
        QStringList list = tmpFile.split(".");
        QString expandedName = list.takeLast();
        if("jpg" == expandedName || "JPG" == expandedName)
        imageList << tmpFile;

    }
    getPosition();

}
Example #21
0
QString CameraNameHelper::extractCameraNameToken(const QString& cameraName, int tokenID)
{
    QStringList capturedTexts;
    QString     tmp;

    capturedTexts = cameraName.split(" (");

    // TODO: Right now we just assume that a camera name has no parentheses in it
    //       There is a testcase (CameraNameHelperTest::testCameraNameFromGPCamera) that
    //       checks all camera names delivered by gphoto2. At the moment all seems to be fine.
    if (!capturedTexts.isEmpty())
    {
        QString mode;
        QString vendorAndProduct;

        if (capturedTexts.count() == 1)     // camera name only
        {
            vendorAndProduct = capturedTexts.takeFirst();
        }
        else
        {
            mode             = capturedTexts.takeLast().simplified();
            vendorAndProduct = capturedTexts.join((" ")).simplified();
        }

        if (tokenID == VendorAndProduct)
        {
            tmp = vendorAndProduct;
        }
        else if (tokenID == Mode)
        {
            tmp = mode;
        }

    }

    // clean up the string
    QStringList words = tmp.split((' '));
    tmp.clear();

    foreach (const QString& word, words)
    {
        tmp.append(word.simplified());
        tmp.append(' ');
    }
Example #22
0
void client::read_message()
{
    if(mysocket->state() != QAbstractSocket::ConnectedState)
    {
        qDebug()<<"no connection exist any more";
        return;
    }
    qDebug()<<" connected to: "<<mysocket->localAddress()<<"  port: "<<5044;
    myreceivedData.append(mysocket->readAll());
    if(!myreceivedData.contains(QChar(23)))
        return;
    QStringList message = myreceivedData.split(QChar(23));
    myreceivedData = message.takeLast();
//    foreach(const QString &msg, message)
//    {

//    }
}
Example #23
0
void MainWindow::browse()
{
    QString directory = QFileDialog::getExistingDirectory(this,
                               tr("Dossier cible"), QDir::currentPath());

    if (!directory.isEmpty()) {
        if (fromComboBox->findText(directory) == -1)
            fromComboBox->addItem(directory);
        fromComboBox->setCurrentIndex(fromComboBox->findText(directory));
        QStringList sDir = directory.split('/');
        QString filename = sDir.takeLast();
        QString path = sDir.join('/');
        QString toFileName = path+"/"+filename+".ecf";
        if(toComboBox->findText(toFileName) == -1)
            toComboBox->addItem(toFileName);
        toComboBox->setCurrentIndex(toComboBox->findText(toFileName));
    }
}
Example #24
0
bool ArgoAObjModel::load(QString filename)
{
    ifstream file(qPrintable(filename), ios::in|ios::binary|ios::ate);
    if (file.is_open())
    {
        float version=0;
        file.seekg (0, ios::beg);
        file.read((char*)&version,sizeof(version));
        file.read((char*)&numTriangles,sizeof(numTriangles));
        float *vertex = new float[numTriangles*9];
        float *texture = new float[numTriangles*6];
        float *normal = new float[numTriangles*9];
        float *tangentbuf = new float[numTriangles*9];
        float *bitangentbuf = new float[numTriangles*9];
        file.read((char*)vertex,sizeof(float)*9*numTriangles);
        file.read((char*)texture,sizeof(float)*6*numTriangles);
        file.read((char*)normal,sizeof(float)*9*numTriangles);
        file.read((char*)tangentbuf,sizeof(float)*9*numTriangles);
        file.read((char*)bitangentbuf,sizeof(float)*9*numTriangles);
        file.read((char*)&radius,sizeof(radius));
        center[0]=center[1]=center[2]=0.0;
        physTriangles=vertex;

        glGenBuffers(1,&bufferID);
        glBindBuffer(GL_ARRAY_BUFFER,bufferID);
        glBufferData(GL_ARRAY_BUFFER,numTriangles*42*sizeof(GLfloat), NULL,GL_STATIC_DRAW);
        glBufferSubData(GL_ARRAY_BUFFER,0,numTriangles*9*sizeof(GLfloat),vertex);
        glBufferSubData(GL_ARRAY_BUFFER,numTriangles*9*sizeof(GLfloat),numTriangles*6*sizeof(GLfloat),texture);
        glBufferSubData(GL_ARRAY_BUFFER,numTriangles*15*sizeof(GLfloat),numTriangles*9*sizeof(GLfloat),normal);
        glBufferSubData(GL_ARRAY_BUFFER,numTriangles*24*sizeof(GLfloat),numTriangles*9*sizeof(GLfloat),tangentbuf);
        glBufferSubData(GL_ARRAY_BUFFER,numTriangles*33*sizeof(GLfloat),numTriangles*9*sizeof(GLfloat),bitangentbuf);

        location=QString(filename);
        QStringList fields = location.split('/');
        QString right = fields.takeLast();
        fields = right.split('.');
        name=new QString();
        *name=fields.takeFirst();

        return true;
    }
    return false;
}
Example #25
0
void Action::actionOutput()
{
    if (!m_outputFormat.isEmpty()) {
        m_outputData.append( readAll() );
        return;
    }

    m_lastOutput.append( QString::fromLocal8Bit(readAll()) );
    if ( m_lastOutput.isEmpty() || m_sep.isEmpty() )
        return;

    // Split to items.
    QStringList items;
    items = m_lastOutput.split(m_sep);
    m_lastOutput = items.takeLast();
    if (m_index.isValid())
        emit newItems(items, m_index);
    else
        emit newItems(items, m_tab);
}
Example #26
0
void DispatcherPrivate::prepareAction(Context *c, const QString &requestPath) const
{
    QStringList pathParts = requestPath.split(QLatin1Char('/'), QString::SkipEmptyParts);
    const QString path = pathParts.join(QLatin1Char('/'));
    QStringList args;

    int pos = path.size();

    //  "foo/bar"
    //  "foo/" skip
    //  "foo"
    //  ""
    Q_FOREVER {
        // Check out the dispatch types to see if any
        // will handle the path at this level
        const QString actionPath = path.mid(0, pos);
        for (DispatchType *type : dispatchers) {
            if (type->match(c, actionPath, args) == DispatchType::ExactMatch) {
                return;
            }
        }

        // leave the loop if we are at the root "/"
        if (pos <= 0) {
            break;
        }

        pos = path.lastIndexOf(QLatin1Char('/'), --pos);
        if (pos == -1) {
            pos = 0;
        }

        // If not, move the last part path to args
        if (pathParts.isEmpty()) {
            args.prepend(QString());
        } else {
            args.prepend(QUrl::fromPercentEncoding(pathParts.takeLast().toLatin1()));
        }
    }
}
Example #27
0
QValidator::State ProjectItemValidator::validate(QString& input, int& pos) const
{
    Q_UNUSED( pos );
    KDevelop::ProjectModel* model = KDevelop::ICore::self()->projectController()->projectModel();
    QStringList path = joinProjectBasePath( KDevelop::splitWithEscaping( input, sep, escape ), mBase );
    QModelIndex idx = model->pathToIndex( path );
    QValidator::State state = input.isEmpty() ? QValidator::Intermediate : QValidator::Invalid;
    if( idx.isValid() )
    {
        state = QValidator::Acceptable;
    } else if( path.count() > 1 )
    {
        // Check beginning of path and if that is ok, then try to find a child
        QString end = path.takeLast();
        idx = model->pathToIndex( path );
        if( idx.isValid() )
        {
            for( int i = 0; i < model->rowCount( idx ); i++ )
            {
                if( model->data( model->index( i, 0, idx ) ).toString().startsWith( end, Qt::CaseInsensitive ) )
                {
                    state = QValidator::Intermediate;
                    break;
                }
            }
        }
    } else if( path.count() == 1 )
    {
        // Check for a project whose name beings with the input
        QString first = path.first();
        foreach( KDevelop::IProject* project, KDevelop::ICore::self()->projectController()->projects() )
        {
            if( project->name().startsWith( first, Qt::CaseInsensitive ) )
            {
                state = QValidator::Intermediate;
                break;
            }
        }
    }
Example #28
0
bool GstEnginePipeline::InitFromUrl(const QUrl& url, qint64 end_nanosec) {
  pipeline_ = gst_pipeline_new("pipeline");

  if (url.scheme() == "cdda" && !url.path().isEmpty()) {
    // Currently, Gstreamer can't handle input CD devices inside cdda URL. So
    // we handle them ourselve: we extract the track number and re-create an
    // URL with only cdda:// + the track number (which can be handled by
    // Gstreamer). We keep the device in mind, and we will set it later using
    // SourceSetupCallback
    QStringList path = url.path().split('/');
    url_ = QUrl(QString("cdda://%1").arg(path.takeLast()));
    source_device_ = path.join("/");
  } else {
    url_ = url;
  }
  end_offset_nanosec_ = end_nanosec;

  // Decode bin
  if (!ReplaceDecodeBin(url_)) return false;

  return Init();
}
Example #29
0
void RssManager::loadStreamList()
{
  RssSettings settings;
  const QStringList streamsUrl = settings.getRssFeedsUrls();
  const QStringList aliases =  settings.getRssFeedsAliases();
  if (streamsUrl.size() != aliases.size()) {
    std::cerr << "Corrupted Rss list, not loading it\n";
    return;
  }
  uint i = 0;
  qDebug() << Q_FUNC_INFO << streamsUrl;
  foreach (QString s, streamsUrl) {
    QStringList path = s.split("\\", QString::SkipEmptyParts);
    if (path.empty()) continue;
    const QString feed_url = path.takeLast();
    qDebug() << "Feed URL:" << feed_url;
    // Create feed path (if it does not exists)
    RssFolder* feed_parent = this;
    foreach (const QString &folder_name, path) {
      qDebug() << "Adding parent folder:" << folder_name;
      feed_parent = feed_parent->addFolder(folder_name).data();
    }
Example #30
0
void Client::connectSocket()
{
	bool ok;
	QString ipAddress = QInputDialog::getText(this, tr("Client"), tr("Server IP:"), QLineEdit::Normal, "ws://localhost:80", &ok);
	ipAddress = ipAddress.trimmed();
	if (ok && !ipAddress.isEmpty())
	{
		QString ip;
		quint16 port;
		if (ipAddress.contains(QRegExp(QLatin1String(":([0-9]|[1-9][0-9]{1,3}|[1-5][0-9]{1,4}|6[0-4][0-9]{3}|65[0-4][0-9]{2}|655[0-2][0-9]|6553[0-5])$"))))
		{
			QStringList splitted = ipAddress.split(':');
			port = splitted.takeLast().toUInt();
            ip = splitted.join(":");
		}
		else
		{
			ip = ipAddress;
			port = 80;
		}
		wsSocket->connectToHost(ip.toUtf8(), port);
	}
}